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 22, 23:15 UTC
fix(server): preserve service environment across updates (#19486)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
James C committed
Oct 20, 2026 at 06:06 UTC
29a7d80469e7ad120434627de1e3005dd7dd7a71
6 files changed
+199
-34
apps/server/src/cloud/bootService.test.ts
+52
-26
@@ -15,6 +15,7 @@ import * as BootService from "./bootService.ts";
15
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
16
import {
17
parseServiceState,
18
+ SERVICE_ENV_FILE,
19
SERVICE_LAUNCHER_PROTOCOL,
20
SERVICE_RESTART_PENDING_FILE,
21
serviceStateHasPendingUpdate,
@@ -246,7 +247,18 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
247
),
248
);
249
const service = yield* makeService();
249
- return { service, makeService, fs, statePath, commands, invocations, timeouts, control, runtime };
250
+ return {
251
+ service,
252
+ makeService,
253
+ fs,
254
+ baseDir,
255
+ statePath,
256
+ commands,
257
+ invocations,
258
+ timeouts,
259
+ control,
260
+ runtime,
261
+ };
262
});
263
264
it.layer(NodeServices.layer)("boot service install", (it) => {
@@ -487,34 +499,48 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
499
}),
500
);
501
490
- it.effect("install with start=false rewrites the files and marks a restart pending", () =>
491
- Effect.gen(function* () {
492
- const { service, fs, statePath, commands, makeService } = yield* makeHarness();
493
- yield* service.install();
494
- commands.length = 0;
502
+ it.effect.each(["linux", "darwin"] as const)(
503
+ "install with start=false rewrites files, preserves service.env, and marks a restart pending on %s",
504
+ (platform) =>
505
+ Effect.gen(function* () {
506
+ const { service, fs, baseDir, statePath, commands, makeService } =
507
+ yield* makeHarness(platform);
508
+ const path = yield* Path.Path;
509
+ const envPath = path.join(baseDir, SERVICE_ENV_FILE);
510
+ const envBytes = new TextEncoder().encode(
511
+ '# user configuration\r\nT3CODE_TOKEN="literal $HOME # token"',
512
+ );
513
+ yield* fs.writeFile(envPath, envBytes);
514
+ yield* service.install();
515
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
516
+ yield* service.install();
517
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
518
+ commands.length = 0;
519
496
- const newer = yield* makeService(undefined, "1.2.4");
497
- const plan = yield* newer.install({ start: false });
520
+ const newer = yield* makeService(undefined, "1.2.4");
521
+ const plan = yield* newer.install({ start: false });
522
+ expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
523
499
- expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
500
- protocol: SERVICE_LAUNCHER_PROTOCOL,
501
- activeVersion: "1.2.4",
502
- });
503
- expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
504
- expect(
505
- commands.filter(
506
- (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
507
- ),
508
- ).toEqual([]);
509
- const status = yield* newer.status;
510
- expect(status.current).toBe(false);
511
- expect(status.problems).toContain("restart-pending");
524
+ expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
525
+ protocol: SERVICE_LAUNCHER_PROTOCOL,
526
+ activeVersion: "1.2.4",
527
+ });
528
+ expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
529
+ expect(
530
+ commands.filter(
531
+ (command) =>
532
+ /^(systemctl|launchctl) /.test(command) && !command.includes("show-environment"),
533
+ ),
534
+ ).toEqual([]);
535
+ const status = yield* newer.status;
536
+ expect(status.current).toBe(false);
537
+ expect(status.problems).toContain("restart-pending");
538
513
- commands.length = 0;
514
- expect(yield* newer.restart).toBe("restarted");
515
- expect((yield* newer.status).problems).not.toContain("restart-pending");
516
- expect((yield* newer.status).current).toBe(true);
517
- }),
539
+ commands.length = 0;
540
+ expect(yield* newer.restart).toBe("restarted");
541
+ expect((yield* newer.status).problems).not.toContain("restart-pending");
542
+ expect((yield* newer.status).current).toBe(true);
543
+ }),
544
);
545
546
it.effect("install with start=false keeps the marker when a later write fails", () =>
apps/server/src/cloud/serviceProtocol.ts
+1
@@ -4,6 +4,7 @@ import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
4
// or the installed runtime tree changes incompatibly; launchers survive self-updates.
5
export const SERVICE_LAUNCHER_PROTOCOL = 3 as const;
6
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
7
+export const SERVICE_ENV_FILE = "service.env";
8
export const SERVICE_STATE_FILE = "service-state.json";
9
/** Written by the launcher just before an explicit stop kills its child, so
10
the child can tell "the service is going away" from "the launcher is about
apps/server/src/serviceLauncher.test.ts
+74
-3
@@ -12,6 +12,8 @@ import { vi } from "vite-plus/test";
12
import {
13
databaseBackupBlocker,
14
Launcher,
15
+ main,
16
+ readServiceEnvironment,
17
PREPARED_TIMEOUT_MS,
18
type BackupSpaceProbe,
19
readServiceState,
@@ -21,6 +23,7 @@ import {
23
compareExactServiceVersions,
24
decodeServiceState,
25
isExactServiceVersion,
26
+ SERVICE_ENV_FILE,
27
SERVICE_LAUNCHER_PROTOCOL,
28
SERVICE_RESTART_PENDING_FILE,
29
SERVICE_STOP_MARKER_FILE,
@@ -126,6 +129,52 @@ const writeFakeRuntime = (
129
});
130
131
it.layer(NodeServices.layer)("service state persistence", (it) => {
132
+ it.effect(
133
+ "loads optional service.env literally without changing inherited or managed variables",
134
+ () =>
135
+ Effect.gen(function* () {
136
+ const fs = yield* FileSystem.FileSystem;
137
+ const path = yield* Path.Path;
138
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
139
+ const inherited = Object.freeze({
140
+ PATH: "inherited-path",
141
+ T3CODE_HOME: root,
142
+ T3_BOOT_SERVICE_UNIT: "managed-unit",
143
+ T3_SERVICE_LAUNCHER_CONTEXT: "managed-context",
144
+ T3CODE_PORT: "ambient",
145
+ });
146
+ assert.deepEqual(
147
+ yield* Effect.promise(() => readServiceEnvironment(root, inherited)),
148
+ inherited,
149
+ );
150
+ yield* fs.writeFileString(
151
+ path.join(root, SERVICE_ENV_FILE),
152
+ [
153
+ "# service configuration",
154
+ "export T3CODE_PORT=1234 # inline comment",
155
+ 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"',
156
+ 'MULTILINE="first\nsecond"',
157
+ "EMPTY=",
158
+ "PATH=/bad",
159
+ "Path=/bad",
160
+ "T3CODE_HOME=/bad",
161
+ "t3code_home=/bad",
162
+ "T3_BOOT_SERVICE_UNIT=bad",
163
+ "t3_boot_service_unit=bad",
164
+ "T3_SERVICE_LAUNCHER_CONTEXT=bad",
165
+ "t3_service_launcher_context=bad",
166
+ ].join("\n"),
167
+ );
168
+ assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), {
169
+ ...inherited,
170
+ T3CODE_PORT: "1234",
171
+ T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token",
172
+ MULTILINE: "first\nsecond",
173
+ EMPTY: "",
174
+ });
175
+ }),
176
+ );
177
+
178
it.effect("durably replaces and strictly reads one state document", () =>
179
Effect.gen(function* () {
180
const fs = yield* FileSystem.FileSystem;
@@ -303,21 +352,33 @@ if (context.update?.status === "pending") {
352
}),
353
);
354
306
- it.effect("rolls back a trial that reports the wrong update ID", () =>
355
+ it.effect("rolls back invalid trials with the startup environment", () =>
356
Effect.gen(function* () {
357
const fs = yield* FileSystem.FileSystem;
358
const path = yield* Path.Path;
359
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
360
const statePath = path.join(root, "runtime", "service-state.json");
361
const databasePath = path.join(root, "userdata", "state.sqlite");
362
+ const observationsPath = path.join(root, "environment-observations.jsonl");
363
+ const envPath = path.join(root, SERVICE_ENV_FILE);
364
+ yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n");
365
+ vi.stubEnv("T3CODE_HOME", root);
366
+ vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited");
367
+ yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs()));
368
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
369
yield* fs.writeFileString(databasePath, "before trial");
370
const encodedDatabasePath = JSON.stringify(databasePath);
371
const childSource = `
372
+import { appendFileSync, writeFileSync } from "node:fs";
373
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
374
+appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({
375
+ token: process.env.T3CODE_TEST_SERVICE_TOKEN,
376
+ update: context.update?.status ?? "active",
377
+}) + "\\n");
378
if (context.update?.status === "pending") {
379
process.send({ type: "prepared", updateId: "wrong-update" });
380
} else if (context.update === undefined) {
381
+ writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n");
382
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
383
setInterval(() => {}, 1_000);
384
} else {
@@ -339,9 +400,8 @@ if (context.update?.status === "pending") {
400
}),
401
);
402
342
- const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
403
yield* Effect.promise(() =>
344
- launcher.run().then(
404
+ main().then(
405
() => Promise.reject(new Error("launcher unexpectedly completed")),
406
() => Promise.resolve(),
407
),
@@ -354,6 +414,17 @@ if (context.update?.status === "pending") {
414
state.update?.status === "rolled-back" ? state.update.reason : undefined,
415
"invalid-prepared",
416
);
417
+ const observations = (yield* fs.readFileString(observationsPath))
418
+ .trim()
419
+ .split("\n")
420
+ .map((line) => JSON.parse(line));
421
+ assert.deepEqual(observations, [
422
+ { token: "initial", update: "active" },
423
+ { token: "initial", update: "pending" },
424
+ { token: "initial", update: "rolled-back" },
425
+ ]);
426
+ assert.equal(process.env.T3CODE_TEST_SERVICE_TOKEN, "inherited");
427
+ assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n");
428
}),
429
);
430
apps/server/src/serviceLauncher.ts
+41
-3
@@ -9,6 +9,7 @@ import * as NodeCrypto from "node:crypto";
9
import * as NodeFS from "node:fs";
10
import * as NodeFSP from "node:fs/promises";
11
import * as NodePath from "node:path";
12
+import * as NodeUtil from "node:util";
13
14
import type {
15
PendingServiceUpdate,
@@ -23,6 +24,7 @@ import {
24
decodeServiceLauncherChildMessage,
25
isExactServiceVersion,
26
parseServiceState,
27
+ SERVICE_ENV_FILE,
28
SERVICE_LAUNCHER_CONTEXT_ENV,
29
SERVICE_LAUNCHER_PROTOCOL,
30
SERVICE_STATE_FILE,
@@ -85,6 +87,36 @@ async function pathExists(target: string): Promise<boolean> {
87
}
88
}
89
90
+const MANAGED_SERVICE_ENV_NAMES = new Set([
91
+ "PATH",
92
+ "T3CODE_HOME",
93
+ "T3_BOOT_SERVICE_UNIT",
94
+ SERVICE_LAUNCHER_CONTEXT_ENV,
95
+]);
96
+
97
+export async function readServiceEnvironment(
98
+ baseDir: string,
99
+ inherited: NodeJS.ProcessEnv = process.env,
100
+): Promise<NodeJS.ProcessEnv> {
101
+ const environment = { ...inherited };
102
+ let contents: string;
103
+ try {
104
+ contents = await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8");
105
+ } catch (cause) {
106
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return environment;
107
+ throw cause;
108
+ }
109
+ for (const [name, value] of Object.entries(NodeUtil.parseEnv(contents))) {
110
+ if (
111
+ /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) &&
112
+ !MANAGED_SERVICE_ENV_NAMES.has(name.toUpperCase())
113
+ ) {
114
+ environment[name] = value;
115
+ }
116
+ }
117
+ return environment;
118
+}
119
+
120
// Opened read-write: Windows refuses to flush a handle without write access.
121
async function syncFile(filePath: string): Promise<void> {
122
const handle = await NodeFSP.open(filePath, "r+");
@@ -443,14 +475,19 @@ export class Launcher {
475
#done = false;
476
readonly #completion = Promise.withResolvers<void>();
477
readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
478
+ readonly #environment: Readonly<NodeJS.ProcessEnv>;
479
480
constructor(
481
baseDir: string,
482
state: ServiceState,
450
- options: { readonly backupSpaceProbe?: Partial<BackupSpaceProbe> } = {},
483
+ options: {
484
+ readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
485
+ readonly environment?: Readonly<NodeJS.ProcessEnv>;
486
+ } = {},
487
) {
488
this.#baseDir = baseDir;
489
this.#backupSpaceProbe = options.backupSpaceProbe;
490
+ this.#environment = { ...(options.environment ?? process.env) };
491
this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
492
this.#state = state;
493
}
@@ -581,7 +618,7 @@ export class Launcher {
618
};
619
const spawnArguments = runtimeSpawnArguments(paths);
620
const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
584
- env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
621
+ env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
622
stdio: ["inherit", "inherit", "inherit", "ipc"],
623
});
624
await new Promise<void>((resolve, reject) => {
@@ -829,7 +866,8 @@ export async function main(): Promise<void> {
866
if (baseDir === undefined || baseDir === "") {
867
throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
868
}
869
+ const environment = await readServiceEnvironment(baseDir);
870
const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
871
const state = await readServiceState(statePath);
834
- await new Launcher(baseDir, state).run();
872
+ await new Launcher(baseDir, state, { environment }).run();
873
}
docs/user/background-service.md
+26
-2
@@ -37,8 +37,32 @@ installing one.
37
38
`t3 uninstall` removes the background service, the `t3` launcher, and the
39
downloaded versions after showing you the list and asking once. Your projects,
40
-threads, and settings under `~/.t3/userdata` are kept. Pass `--yes` from a
41
-script.
40
+threads, and settings under `~/.t3/userdata` are kept, along with `service.env`
41
+under T3 home. Pass `--yes` from a script.
42
+
43
+## Configure the service environment
44
+
45
+Put custom environment variables in `service.env` under the service's T3 home
46
+directory, normally `~/.t3/service.env`. This file survives service installation
47
+and updates. For example:
48
+
49
+```dotenv
50
+T3CODE_PORT=3773
51
+T3CODE_HOST=127.0.0.1
52
+```
53
+
54
+Use `KEY=VALUE` entries, quoting values that contain spaces or `#`. Values are
55
+literal: shell commands and variable expansion are not evaluated. Entries
56
+override the inherited service environment, except for `PATH`, `T3CODE_HOME`,
57
+`T3_BOOT_SERVICE_UNIT`, and `T3_SERVICE_LAUNCHER_CONTEXT` (including case variants).
58
+
59
+Run `t3 service restart` after changing the file. Changes apply when the service
60
+starts again; switching the server version alone keeps the current values.
61
+For a service installed before env-file support, run `t3 service install` once
62
+with an up-to-date CLI.
63
+A missing file is ignored; other read failures stop service startup.
64
+If the file contains credentials, restrict access to that file with `chmod 600`
65
+(for the default T3 home, `chmod 600 ~/.t3/service.env`).
66
67
## Platform support
68
docs/user/source-control.md
+5
@@ -87,6 +87,11 @@ export T3CODE_BITBUCKET_EMAIL="you@example.com"
87
export T3CODE_BITBUCKET_API_TOKEN="your-token"
88
```
89
90
+For a background service, put these `KEY=VALUE` entries in
91
+[`service.env`](./background-service.md#configure-the-service-environment)
92
+under T3 home, then run `t3 service restart`. Service installation and updates
93
+preserve that file.
94
+
95
### Azure DevOps
96
97
Install [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/), add the DevOps extension, and sign in: