The best way to control Claude Code, Codex and more from any computer or phone
fix(server): self-update moves the t3 command to the new runtime (#14875)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Jonas B. committed
Nov 11, 2026 at 18:37 UTC
f6b260df159143f4d9856230bcbe6dd78e9e3719
9 files changed
+387
-36
apps/server/src/cloud/bootService.test.ts
+69
@@ -137,6 +137,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
137
installerPath = macInstallerPath,
138
xdgConfigHome?: string,
139
managerXdgConfigHome = xdgConfigHome,
140
+ installBinDir?: string,
141
) {
142
const fs = yield* FileSystem.FileSystem;
143
const path = yield* Path.Path;
@@ -282,6 +283,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
283
insideService = false,
284
hostExecPath = "/usr/bin/t3",
285
underSudo = false,
286
+ serviceInstallBinDir: string | null | undefined = installBinDir,
287
) =>
288
Effect.gen(function* () {
289
const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
@@ -309,6 +311,9 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
311
ConfigProvider.fromEnv({
312
env: {
313
HOME: home,
314
+ ...(serviceInstallBinDir === undefined || serviceInstallBinDir === null
315
+ ? {}
316
+ : { T3CODE_INSTALL_BIN_DIR: serviceInstallBinDir }),
317
...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }),
318
USERPROFILE: home,
319
LOCALAPPDATA: path.join(home, "AppData", "Local"),
@@ -572,6 +577,69 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
577
}),
578
);
579
580
+ it.effect.each(["linux", "darwin"] as const)(
581
+ "preserves the custom install bin directory in the installed service on %s",
582
+ (platform) =>
583
+ Effect.gen(function* () {
584
+ const installBinDir = '/custom/T3 & <100%>/"quoted"\\bin';
585
+ const { service, makeService, fs } = yield* makeHarness(
586
+ platform,
587
+ "",
588
+ undefined,
589
+ undefined,
590
+ installBinDir,
591
+ );
592
+ const plan = yield* service.install();
593
+ const unit = yield* fs.readFileString(plan.unitPath);
594
+ expect(unit).toContain(
595
+ platform === "linux"
596
+ ? 'Environment=T3CODE_INSTALL_BIN_DIR="/custom/T3 & <100%%>/\\"quoted\\"\\\\bin"'
597
+ : '<key>T3CODE_INSTALL_BIN_DIR</key>\n <string>/custom/T3 & <100%>/"quoted"\\bin</string>',
598
+ );
599
+ expect((yield* service.status).current).toBe(true);
600
+
601
+ const ordinaryCli = yield* makeService(
602
+ "",
603
+ "1.2.3",
604
+ undefined,
605
+ false,
606
+ undefined,
607
+ false,
608
+ null,
609
+ );
610
+ expect((yield* ordinaryCli.status).current).toBe(true);
611
+ expect((yield* ordinaryCli.install()).installBinDir).toBe(installBinDir);
612
+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
613
+
614
+ const updatedCli = yield* makeService(
615
+ "",
616
+ "1.2.4",
617
+ undefined,
618
+ false,
619
+ undefined,
620
+ false,
621
+ null,
622
+ );
623
+ expect((yield* updatedCli.install({ start: false })).installBinDir).toBe(installBinDir);
624
+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit.replaceAll("1.2.3", "1.2.4"));
625
+
626
+ const replacementCli = yield* makeService(
627
+ "",
628
+ "1.2.4",
629
+ undefined,
630
+ false,
631
+ undefined,
632
+ false,
633
+ "/replacement/bin",
634
+ );
635
+ expect((yield* replacementCli.status).current).toBe(false);
636
+ expect((yield* replacementCli.install()).installBinDir).toBe("/replacement/bin");
637
+ const laterCli = yield* makeService("", "1.2.4", undefined, false, undefined, false, "");
638
+ expect((yield* laterCli.status).current).toBe(true);
639
+ expect((yield* laterCli.install()).installBinDir).toBe("/replacement/bin");
640
+ }),
641
+ );
642
+
643
it.effect.each([
644
"unset",
645
"empty",
@@ -624,6 +692,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
692
activeVersion: "1.2.3",
693
});
694
expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
695
+ expect(yield* fs.readFileString(plan.unitPath)).not.toContain("T3CODE_INSTALL_BIN_DIR");
696
expect(yield* fs.readFileString(plan.unitPath)).toContain(
697
`ExecStart=${runtime.entryPath} __service-launcher`,
698
);
apps/server/src/cloud/bootService.ts
+29
-5
@@ -41,6 +41,7 @@ import {
41
disabledServiceTask,
42
serviceTaskIsDisabled,
43
serviceUnitBaseDirOf as bootServiceBaseDirOf,
44
+ serviceUnitEnvironmentValueOf,
45
parseServiceState,
46
serviceStateActiveVersion,
47
serviceStateHasPendingUpdate,
@@ -84,6 +85,7 @@ export interface BootServicePlan {
85
readonly baseDir: string;
86
readonly logPath: string;
87
readonly unitPath: string;
88
+ readonly installBinDir?: string;
89
/** The manager accepted a detached install; its outcome is written to `logPath`. */
90
readonly handedOff?: boolean;
91
}
@@ -101,6 +103,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
103
"Type=simple",
104
"WorkingDirectory=%h",
105
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
106
+ ...(plan.installBinDir === undefined
107
+ ? []
108
+ : [`Environment=T3CODE_INSTALL_BIN_DIR=${quoteSystemdValue(plan.installBinDir)}`]),
109
`Environment=${SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
110
`ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
111
// Let the launcher mark an explicit stop before it signals the server.
@@ -159,6 +164,12 @@ export function renderBootServicePlist(
164
` <string>${escapeXmlText(options.environmentPath)}</string>`,
165
` <key>T3CODE_HOME</key>`,
166
` <string>${escapeXmlText(plan.baseDir)}</string>`,
167
+ ...(plan.installBinDir === undefined
168
+ ? []
169
+ : [
170
+ ` <key>T3CODE_INSTALL_BIN_DIR</key>`,
171
+ ` <string>${escapeXmlText(plan.installBinDir)}</string>`,
172
+ ]),
173
` <key>${SERVICE_UNIT_ENV}</key>`,
174
` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
175
` </dict>`,
@@ -772,6 +783,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
783
);
784
const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
785
const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
786
+ const installBinDir = Option.getOrUndefined(
787
+ yield* Config.String("T3CODE_INSTALL_BIN_DIR").pipe(Config.option),
788
+ );
789
const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault(""));
790
// Root under sudo must not reach or start a separate root service.
791
const rootUnderSudo =
@@ -989,6 +1003,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1003
);
1004
}),
1005
).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1006
+ const planForUnit = (unit: string): BootServicePlan => {
1007
+ const effectiveInstallBinDir =
1008
+ installBinDir || serviceUnitEnvironmentValueOf(unit, "T3CODE_INSTALL_BIN_DIR");
1009
+ return effectiveInstallBinDir ? { ...plan, installBinDir: effectiveInstallBinDir } : plan;
1010
+ };
1011
const requireManager = Effect.suspend(() =>
1012
detectedManager === undefined
1013
? new BootServiceUnsupportedError({ platform })
@@ -1270,7 +1289,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1289
input.baseDir.replaceAll("$", () => "$$"),
1290
...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
1291
]);
1273
- return { ...plan, handedOff: true };
1292
+ const unit = yield* fs
1293
+ .readFileString(unitPath)
1294
+ .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1295
+ return { ...planForUnit(unit), handedOff: true };
1296
}
1297
// Task Scheduler restarts the task itself, so the files are written as for a deferred
1298
// restart while this launcher keeps running, then the restart is handed to the manager.
@@ -1281,7 +1303,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1303
1304
// State first, then unit. The launcher acquires only one at a time, and a
1305
// failure to lock the unit must never prevent its durable update commit.
1284
- yield* withSelectionLock(
1306
+ const installedPlan = yield* withSelectionLock(
1307
statePath,
1308
withSelectionLock(
1309
unitPath,
@@ -1323,6 +1345,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1345
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1346
// Files can match the new version even when activation fails; keep that install retryable.
1347
yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
1348
+ const plan = planForUnit(currentlyInstalled ? yield* fs.readFileString(unitPath) : "");
1349
yield* writeDurably(
1350
statePath,
1351
// @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
@@ -1344,10 +1367,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1367
const unit = manager.render(plan);
1368
yield* writeDurably(unitPath, unit);
1369
if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit);
1370
+ return plan;
1371
}),
1372
),
1373
).pipe(
1350
- Effect.andThen(
1374
+ Effect.tap(
1375
Effect.gen(function* () {
1376
if (handOff) {
1377
yield* runSteps(manager.handoff ?? []);
@@ -1375,7 +1399,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1399
: Effect.void,
1400
),
1401
);
1378
- return handOff ? { ...plan, handedOff: true } : plan;
1402
+ return handOff ? { ...installedPlan, handedOff: true } : installedPlan;
1403
});
1404
1405
const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
@@ -1520,7 +1544,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1544
problems,
1545
current:
1546
problems.length === 0 &&
1523
- normalizeUnit(unit) === normalizeUnit(manager.render(plan)) &&
1547
+ normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) &&
1548
runtimeEntryExists &&
1549
Option.isSome(runtimeSentinel) &&
1550
runtimeSentinel.value.trim() === input.cliVersion &&
apps/server/src/cloud/selfUpdate.test.ts
+1
-1
@@ -145,7 +145,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
145
order.push("accept");
146
return "launcher-id";
147
})),
148
- prepareTrial: Effect.undefined,
148
+ prepareTrial: () => Effect.undefined,
149
});
150
const config = yield* ServerConfig.ServerConfig.pipe(
151
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
apps/server/src/cloud/serviceLauncherClient.test.ts
+159
-4
@@ -1,4 +1,9 @@
1
-import { expect, it } from "@effect/vitest";
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import * as FileSystem from "effect/FileSystem";
3
+import * as Path from "effect/Path";
4
+import * as Logger from "effect/Logger";
5
+import * as PlatformError from "effect/PlatformError";
6
+import { assert, expect, it } from "@effect/vitest";
7
import * as HostProcess from "@t3tools/shared/HostProcess";
8
import * as Effect from "effect/Effect";
9
import * as Fiber from "effect/Fiber";
@@ -47,13 +52,27 @@ const makeClient = (host: FakeLauncherProcess, currentVersion: string) =>
52
ServiceLauncherClient.make({ currentVersion }).pipe(
53
Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host),
54
Effect.provideService(HostProcess.Environment, host.env),
55
+ Effect.provide(NodeServices.layer),
56
);
57
58
// regression: #34502 a remote update never replaces the launcher, so an installed one stays protocol 3
59
it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])(
54
- "waits for a protocol-%i launcher to durably commit the trial update ID",
60
+ "waits for a protocol-%i launcher to durably commit the trial update ID, then moves owned launchers",
61
(protocol) =>
62
Effect.gen(function* () {
63
+ const fs = yield* FileSystem.FileSystem;
64
+ const path = yield* Path.Path;
65
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-trial-" });
66
+ const baseDir = path.join(root, ".t3");
67
+ const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
68
+ const installed = path.join(root, ".local/bin/t3");
69
+ for (const file of [exe("1.0.0"), exe("1.1.0")]) {
70
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
71
+ yield* fs.writeFileString(file, "");
72
+ }
73
+ yield* fs.makeDirectory(path.dirname(installed), { recursive: true });
74
+ yield* fs.symlink(exe("1.0.0"), installed);
75
+
76
const pending = {
77
id: "update-1",
78
fromVersion: "1.0.0",
@@ -62,10 +81,14 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])(
81
status: "pending" as const,
82
};
83
const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending });
84
+ host.env["HOME"] = root;
85
const client = yield* makeClient(host, "1.1.0");
66
- const prepared = yield* Effect.forkChild(client.prepareTrial, { startImmediately: true });
86
+ const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), {
87
+ startImmediately: true,
88
+ });
89
yield* Effect.yieldNow;
90
expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]);
91
+ assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
92
93
const committed = {
94
id: pending.id,
@@ -75,7 +98,21 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])(
98
};
99
host.emit({ type: "committed", updateId: committed.id });
100
expect(yield* Fiber.join(prepared)).toEqual(committed);
78
- }),
101
+ assert.equal(yield* fs.readLink(installed), exe("1.1.0"));
102
+
103
+ // A later start replays the stored outcome; user pins made since then stay put.
104
+ yield* fs.remove(installed);
105
+ yield* fs.symlink(exe("1.0.0"), installed);
106
+ const restarted = new FakeLauncherProcess({
107
+ protocol,
108
+ childVersion: "1.1.0",
109
+ update: committed,
110
+ });
111
+ restarted.env["HOME"] = root;
112
+ const restartedClient = yield* makeClient(restarted, "1.1.0");
113
+ expect(yield* restartedClient.prepareTrial({ baseDir })).toEqual(committed);
114
+ assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
115
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
116
);
117
118
it.effect("returns the launcher-generated ID only after update acceptance", () =>
@@ -169,3 +206,121 @@ it.effect("ignores launcher context inherited without an IPC channel", () =>
206
expect(host.sent).toEqual([]);
207
}),
208
);
209
+
210
+it.layer(NodeServices.layer)("self-update launchers", (it) => {
211
+ it.effect(
212
+ "updates custom install and PATH launchers, including versions older than fromVersion",
213
+ () =>
214
+ Effect.gen(function* () {
215
+ const fs = yield* FileSystem.FileSystem;
216
+ const path = yield* Path.Path;
217
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
218
+ const baseDir = path.join(root, ".t3");
219
+ const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
220
+ const installed = path.join(root, "custom/bin/t3");
221
+ const onPath = path.join(root, "bin/t3");
222
+ for (const file of [exe("1.0.0"), exe("1.5.0"), exe("2.0.0")]) {
223
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
224
+ yield* fs.writeFileString(file, "");
225
+ }
226
+ yield* fs.makeDirectory(path.dirname(installed), { recursive: true });
227
+ yield* fs.symlink(exe("1.5.0"), installed);
228
+ yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
229
+ yield* fs.symlink(exe("1.0.0"), onPath);
230
+
231
+ yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
232
+ Effect.provideService(HostProcess.Environment, {
233
+ HOME: root,
234
+ T3CODE_INSTALL_BIN_DIR: path.dirname(installed),
235
+ PATH: path.dirname(onPath),
236
+ }),
237
+ );
238
+
239
+ assert.equal(yield* fs.readLink(installed), exe("2.0.0"));
240
+ assert.equal(yield* fs.readLink(onPath), exe("2.0.0"));
241
+ }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
242
+ );
243
+
244
+ it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () =>
245
+ Effect.gen(function* () {
246
+ const fs = yield* FileSystem.FileSystem;
247
+ const path = yield* Path.Path;
248
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
249
+ const baseDir = path.join(root, ".t3");
250
+ const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
251
+ const installed = path.join(root, ".local/bin/t3");
252
+ const onPath = path.join(root, "bin/t3");
253
+ for (const file of [exe("1.0.0"), exe("2.0.0")]) {
254
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
255
+ yield* fs.writeFileString(file, "");
256
+ }
257
+ for (const link of [installed, onPath]) {
258
+ yield* fs.makeDirectory(path.dirname(link), { recursive: true });
259
+ yield* fs.symlink(exe("1.0.0"), link);
260
+ }
261
+ const warnings: unknown[] = [];
262
+ const logger = Logger.make(({ logLevel, message }) => {
263
+ if (logLevel === "Warn") warnings.push(message);
264
+ });
265
+ const failingFs = FileSystem.FileSystem.of({
266
+ ...fs,
267
+ rename: (source, destination) =>
268
+ destination === installed
269
+ ? Effect.fail(
270
+ new PlatformError.PlatformError(
271
+ new PlatformError.SystemError({
272
+ _tag: "PermissionDenied",
273
+ module: "FileSystem",
274
+ method: "rename",
275
+ pathOrDescriptor: destination,
276
+ }),
277
+ ),
278
+ )
279
+ : fs.rename(source, destination),
280
+ });
281
+
282
+ yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
283
+ Effect.provideService(HostProcess.Environment, {
284
+ HOME: root,
285
+ PATH: path.dirname(onPath),
286
+ }),
287
+ Effect.provideService(FileSystem.FileSystem, failingFs),
288
+ Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
289
+ );
290
+
291
+ assert.lengthOf(warnings, 1);
292
+ assert.include(JSON.stringify(warnings), installed);
293
+ assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
294
+ assert.equal(yield* fs.readLink(onPath), exe("2.0.0"));
295
+ }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
296
+ );
297
+
298
+ it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () =>
299
+ Effect.gen(function* () {
300
+ const fs = yield* FileSystem.FileSystem;
301
+ const path = yield* Path.Path;
302
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
303
+ const baseDir = path.join(root, ".t3");
304
+ const installed = path.join(root, ".local/bin/t3");
305
+ const onPath = path.join(root, "bin/t3");
306
+ const foreign = path.join(root, "other-home/runtime/versions/1.0.0/t3");
307
+ const target = path.join(baseDir, "runtime/versions/2.0.0/t3");
308
+ for (const file of [installed, foreign, target]) {
309
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
310
+ yield* fs.writeFileString(file, "user-owned file");
311
+ }
312
+ yield* fs.makeDirectory(path.dirname(onPath), { recursive: true });
313
+ yield* fs.symlink(foreign, onPath);
314
+
315
+ yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe(
316
+ Effect.provideService(HostProcess.Environment, {
317
+ HOME: root,
318
+ PATH: path.dirname(onPath),
319
+ }),
320
+ );
321
+
322
+ assert.equal(yield* fs.readFileString(installed), "user-owned file");
323
+ assert.equal(yield* fs.readLink(onPath), foreign);
324
+ }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
325
+ );
326
+});
apps/server/src/cloud/serviceLauncherClient.ts
+110
-16
@@ -1,12 +1,16 @@
1
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2
import * as HostProcess from "@t3tools/shared/HostProcess";
3
import * as Context from "effect/Context";
4
+import * as Cause from "effect/Cause";
5
import * as Effect from "effect/Effect";
6
+import * as FileSystem from "effect/FileSystem";
7
import * as Layer from "effect/Layer";
8
import * as Option from "effect/Option";
9
+import * as Path from "effect/Path";
10
import * as Schema from "effect/Schema";
11
12
import packageJson from "../../package.json" with { type: "json" };
13
+import { pinnedRuntimePaths, pinnedRuntimeVersionsDir } from "./pinnedRuntime.ts";
14
import {
15
decodeServiceLauncherContext,
16
decodeServiceLauncherParentMessage,
@@ -106,10 +110,10 @@ export class ServiceLauncherClient extends Context.Service<
110
readonly targetVersion: string;
111
readonly dbPath: string;
112
}) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
109
- readonly prepareTrial: Effect.Effect<
110
- ServerSelfUpdateOutcome | undefined,
111
- ServiceLauncherClientError
112
- >;
113
+ /** Owned `t3` symlinks move to the new runtime only when this start commits the trial. */
114
+ readonly prepareTrial: (input: {
115
+ readonly baseDir: string;
116
+ }) => Effect.Effect<ServerSelfUpdateOutcome | undefined, ServiceLauncherClientError>;
117
}
118
>()("t3/cloud/serviceLauncherClient") {}
119
@@ -142,6 +146,83 @@ export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_clie
146
},
147
);
148
149
+export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint_launchers")(
150
+ function* (input: { readonly baseDir: string; readonly targetVersion: string }) {
151
+ const fs = yield* FileSystem.FileSystem;
152
+ const path = yield* Path.Path;
153
+ const environment = yield* HostProcess.Environment;
154
+ const platform = yield* HostProcess.Platform;
155
+ if (platform !== "linux" && platform !== "darwin") return;
156
+ const installBinDir =
157
+ environment["T3CODE_INSTALL_BIN_DIR"] ||
158
+ (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined);
159
+ const candidates = new Set<string>();
160
+ if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3"));
161
+ for (const directory of (environment["PATH"] ?? "").split(":")) {
162
+ if (directory.length === 0) continue;
163
+ const candidate = path.join(directory, "t3");
164
+ if (
165
+ yield* fs.exists(candidate).pipe(
166
+ Effect.catch((cause) =>
167
+ Effect.logWarning("Could not check the t3 command on PATH", {
168
+ launchedAs: candidate,
169
+ cause,
170
+ }).pipe(Effect.as(false)),
171
+ ),
172
+ )
173
+ ) {
174
+ candidates.add(candidate);
175
+ break;
176
+ }
177
+ }
178
+ const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
179
+ const target = pinnedRuntimePaths(path, input.baseDir, input.targetVersion, platform);
180
+ for (const launchedAs of candidates) {
181
+ yield* Effect.scoped(
182
+ Effect.gen(function* () {
183
+ const linkTarget = yield* fs.readLink(launchedAs).pipe(
184
+ Effect.asSome,
185
+ Effect.catchIf(
186
+ (error) =>
187
+ error.reason._tag === "NotFound" ||
188
+ (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EINVAL",
189
+ () => Effect.succeedNone,
190
+ ),
191
+ );
192
+ if (Option.isNone(linkTarget)) return;
193
+ const relative = path.relative(
194
+ versionsDir,
195
+ path.resolve(path.dirname(launchedAs), linkTarget.value),
196
+ );
197
+ if (
198
+ relative.length === 0 ||
199
+ relative === ".." ||
200
+ relative.startsWith(`..${path.sep}`) ||
201
+ path.isAbsolute(relative)
202
+ )
203
+ return;
204
+ const temporary = yield* fs.makeTempDirectoryScoped({
205
+ directory: path.dirname(launchedAs),
206
+ prefix: ".t3-launcher-",
207
+ });
208
+ const link = path.join(temporary, "t3");
209
+ yield* fs.symlink(target.entryPath, link);
210
+ yield* fs.rename(link, launchedAs);
211
+ }),
212
+ ).pipe(
213
+ Effect.catchCause((cause) =>
214
+ Cause.hasInterrupts(cause)
215
+ ? Effect.interrupt
216
+ : Effect.logWarning("Could not move the t3 command to the updated version", {
217
+ launchedAs,
218
+ cause,
219
+ }),
220
+ ),
221
+ );
222
+ }
223
+ },
224
+);
225
+
226
/** Completes when the launcher asks this server to stop, which Windows cannot signal. */
227
export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")(
228
function* (options?: { readonly currentVersion?: string }) {
@@ -162,6 +243,11 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
243
readonly currentVersion?: string;
244
}) {
245
const { host, context, managed } = yield* resolveStartup(options);
246
+ // prepareTrial runs later, outside whatever context built the client.
247
+ const fs = yield* FileSystem.FileSystem;
248
+ const path = yield* Path.Path;
249
+ const environment = yield* HostProcess.Environment;
250
+ const platform = yield* HostProcess.Platform;
251
252
const exchange = (
253
message: ServiceLauncherChildMessage,
@@ -239,23 +325,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
325
context?.update === undefined || context.update.status === "pending"
326
? undefined
327
: context.update;
242
- const prepareTrial =
328
+ const prepareTrial = (input: { readonly baseDir: string }) =>
329
pending !== undefined
330
? exchange(
331
{ type: "prepared", updateId: pending.id },
332
(reply) => reply.type === "committed" && reply.updateId === pending.id,
333
).pipe(
248
- Effect.flatMap((reply) => {
249
- if (reply.type !== "committed") {
250
- return Effect.die("service launcher returned an impossible prepared response");
251
- }
252
- return Effect.succeed({
253
- id: pending.id,
254
- fromVersion: pending.fromVersion,
255
- targetVersion: pending.targetVersion,
256
- status: "committed" as const,
257
- });
258
- }),
334
+ Effect.flatMap((reply) =>
335
+ reply.type !== "committed"
336
+ ? Effect.die("service launcher returned an impossible prepared response")
337
+ : repointLaunchers({
338
+ baseDir: input.baseDir,
339
+ targetVersion: pending.targetVersion,
340
+ }).pipe(
341
+ Effect.provideService(FileSystem.FileSystem, fs),
342
+ Effect.provideService(Path.Path, path),
343
+ Effect.provideService(HostProcess.Environment, environment),
344
+ Effect.provideService(HostProcess.Platform, platform),
345
+ Effect.as({
346
+ id: pending.id,
347
+ fromVersion: pending.fromVersion,
348
+ targetVersion: pending.targetVersion,
349
+ status: "committed" as const,
350
+ }),
351
+ ),
352
+ ),
353
)
354
: Effect.succeed(outcome);
355
apps/server/src/cloud/serviceProtocol.ts
+12
-4
@@ -46,11 +46,19 @@ export const disabledServiceTask = (taskXml: string): string =>
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];
49
+export function serviceUnitEnvironmentValueOf(
50
+ contents: string,
51
+ name: "T3CODE_HOME" | "T3CODE_INSTALL_BIN_DIR",
52
+): string | undefined {
53
+ const systemd = new RegExp(`^Environment=${name}=(.*)$`, "m").exec(contents)?.[1];
54
if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
52
- const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
53
- if (plist !== undefined) return unescapeXmlText(plist);
55
+ const plist = new RegExp(`<key>${name}</key>\\s*<string>([^<]*)</string>`).exec(contents)?.[1];
56
+ return plist === undefined ? undefined : unescapeXmlText(plist);
57
+}
58
+
59
+export function serviceUnitBaseDirOf(contents: string): string | undefined {
60
+ const unix = serviceUnitEnvironmentValueOf(contents, "T3CODE_HOME");
61
+ if (unix !== undefined) return unix;
62
const task = /<Arguments>[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1];
63
return task === undefined ? undefined : unquoteWindowsArgument(task);
64
}
apps/server/src/serverRuntimeStartup.autoPull.test.ts
+5
-4
@@ -148,10 +148,11 @@ it.effect("parks automatic pull until activation without delaying command readin
148
Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
149
managed: true,
150
protocol: SERVICE_LAUNCHER_PROTOCOL,
151
- prepareTrial: Deferred.succeed(prepared, undefined).pipe(
152
- Effect.andThen(Deferred.await(commitTrial)),
153
- Effect.as(undefined),
154
- ),
151
+ prepareTrial: () =>
152
+ Deferred.succeed(prepared, undefined).pipe(
153
+ Effect.andThen(Deferred.await(commitTrial)),
154
+ Effect.as(undefined),
155
+ ),
156
}),
157
Layer.mock(GitVcsDriver.GitVcsDriver)({
158
statusDetails: (root) =>
apps/server/src/serverRuntimeStartup.test.ts
+1
-1
@@ -202,7 +202,7 @@ it.effect.each([
202
Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
203
managed: false,
204
protocol: undefined,
205
- prepareTrial: Effect.undefined,
205
+ prepareTrial: () => Effect.undefined,
206
}),
207
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
208
Layer.mock(AnalyticsService.AnalyticsService)({}),
apps/server/src/serverRuntimeStartup.ts
+1
-1
@@ -633,7 +633,7 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup
633
yield* runStartupPhase("http.wait", Deferred.await(httpListening));
634
yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
635
636
- const updateOutcome = yield* launcher.prepareTrial;
636
+ const updateOutcome = yield* launcher.prepareTrial({ baseDir: serverConfig.baseDir });
637
638
yield* Effect.logDebug("startup phase: publishing welcome event", {
639
environmentId: environment.environmentId,