The best way to control Claude Code, Codex and more from any computer or phone
fix(desktop): discover shell environment without blocking startup (#28556)
Yash Singh committed
Nov 1, 2026 at 05:04 UTC
8b4de61b8b4fa902873ec0d0cd88aef2bc3716a7
15 files changed
+914
-66
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+4
@@ -8,6 +8,7 @@ import * as Layer from "effect/Layer";
8
import * as ManagedRuntime from "effect/ManagedRuntime";
9
import * as Option from "effect/Option";
10
import * as Path from "effect/Path";
11
+import * as Stream from "effect/Stream";
12
import { ChildProcessSpawner } from "effect/process";
13
14
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -22,6 +23,8 @@ import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
23
const layerShellEnvironment = (prepared = true) =>
24
Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
25
installIntoProcess: Effect.succeed(prepared),
26
+ awaitDiscovery: Effect.succeed(prepared),
27
+ updates: Stream.empty,
28
});
29
30
const layerBackendConfiguration = (prepared = true) =>
@@ -237,6 +240,7 @@ describe("DesktopBackendConfiguration", () => {
240
assert.equal(first.cwd, environment.backendCwd);
241
assert.equal(first.captureOutput, true);
242
assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
243
+ assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1");
244
assert.isUndefined(first.env.T3CODE_PORT);
245
assert.isUndefined(first.env.T3CODE_MODE);
246
assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+1
@@ -532,6 +532,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
532
env: {
533
...backendChildEnvPatch(),
534
ELECTRON_RUN_AS_NODE: "1",
535
+ T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
536
T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
537
},
538
extendEnv: true,
apps/desktop/src/main.ts
+1
-1
@@ -186,10 +186,10 @@ const layerDesktopAppActivation = DesktopAppActivation.layer.pipe(
186
const layerDesktopBackend = DesktopBackendPool.layer.pipe(
187
Layer.provideMerge(DesktopAppIdentity.layer),
188
Layer.provideMerge(DesktopBackendConfiguration.layer),
189
- Layer.provideMerge(DesktopShellEnvironment.layer),
189
Layer.provideMerge(DesktopWslEnvironment.layer),
190
Layer.provideMerge(DesktopWslServerTree.layer),
191
Layer.provideMerge(DesktopTelemetryPublisher.layer),
192
+ Layer.provideMerge(DesktopShellEnvironment.layer),
193
Layer.provideMerge(layerDesktopWindow),
194
);
195
apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+272
-7
@@ -3,11 +3,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { assert, describe, it } from "@effect/vitest";
4
import * as HostProcess from "@t3tools/shared/HostProcess";
5
import * as Effect from "effect/Effect";
6
+import * as Deferred from "effect/Deferred";
7
+import * as FileSystem from "effect/FileSystem";
8
import * as Layer from "effect/Layer";
9
import * as Logger from "effect/Logger";
10
import * as PlatformError from "effect/PlatformError";
11
import * as Sink from "effect/Sink";
12
import * as Stream from "effect/Stream";
13
+import * as Schema from "effect/Schema";
14
+import * as Option from "effect/Option";
15
import * as ChildProcess from "effect/process/ChildProcess";
16
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17
import * as NodeOS from "node:os";
@@ -19,6 +23,15 @@ import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
23
vi.mock("node:os", { spy: true });
24
25
const textEncoder = new TextEncoder();
26
+const cacheCodec = Schema.fromJsonString(
27
+ Schema.Struct({
28
+ version: Schema.Number,
29
+ key: Schema.String,
30
+ environment: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),
31
+ }),
32
+);
33
+const encodeCache = Schema.encodeSync(cacheCodec);
34
+const decodeCache = Schema.decodeUnknownEffect(cacheCodec);
35
36
function envOutput(values: Readonly<Record<string, string>>): string {
37
return Object.entries(values)
@@ -69,18 +82,28 @@ function runShellEnvironment(input: {
82
readonly env: NodeJS.ProcessEnv;
83
readonly platform: NodeJS.Platform;
84
readonly userShell?: string;
85
+ readonly stateDir?: string;
86
+ readonly use?: (
87
+ service: DesktopShellEnvironment.DesktopShellEnvironment["Service"],
88
+ ) => Effect.Effect<boolean, never, import("effect/Scope").Scope>;
89
readonly handler: (
90
command: ChildProcess.Command,
91
) => string | { output: string; exitCode: number };
92
readonly failure?: PlatformError.PlatformError;
93
readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
94
}) {
78
- const layerEnvironment = Layer.succeed(
95
+ const layerEnvironment = Layer.effect(
96
DesktopEnvironment.DesktopEnvironment,
80
- DesktopEnvironment.DesktopEnvironment.of({
81
- platform: input.platform,
82
- } as DesktopEnvironment.DesktopEnvironment["Service"]),
83
- );
97
+ Effect.gen(function* () {
98
+ const fs = yield* FileSystem.FileSystem;
99
+ const stateDir = input.stateDir ?? (yield* fs.makeTempDirectoryScoped());
100
+ return DesktopEnvironment.DesktopEnvironment.of({
101
+ platform: input.platform,
102
+ stateDir,
103
+ homeDirectory: "/test-home",
104
+ } as DesktopEnvironment.DesktopEnvironment["Service"]);
105
+ }),
106
+ ).pipe(Layer.provide(NodeServices.layer));
107
const layerSpawner = Layer.succeed(
108
ChildProcessSpawner.ChildProcessSpawner,
109
ChildProcessSpawner.make((command) => {
@@ -97,8 +120,9 @@ function runShellEnvironment(input: {
120
121
const program = Effect.gen(function* () {
122
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
100
- const prepared = yield* shellEnvironment.installIntoProcess;
101
- assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
123
+ if (input.use) return yield* input.use(shellEnvironment);
124
+ const prepared = yield* shellEnvironment.awaitDiscovery;
125
+ assert.equal(yield* shellEnvironment.awaitDiscovery, prepared);
126
return prepared;
127
}).pipe(
128
Effect.provide(
@@ -121,6 +145,247 @@ function runShellEnvironment(input: {
145
}
146
147
describe("DesktopShellEnvironment", () => {
148
+ it.effect("does not wait for discovery when the cache is missing", () =>
149
+ Effect.gen(function* () {
150
+ const started = yield* Deferred.make<void>();
151
+ const release = yield* Deferred.make<void>();
152
+ yield* runShellEnvironment({
153
+ env: { SHELL: "/test-shell", PATH: "/usr/bin" },
154
+ platform: "darwin",
155
+ handler: () => "",
156
+ processSpawner: ChildProcessSpawner.make(() =>
157
+ Deferred.succeed(started, undefined).pipe(
158
+ Effect.andThen(Deferred.await(release)),
159
+ Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
160
+ ),
161
+ ),
162
+ use: (service) =>
163
+ Effect.gen(function* () {
164
+ const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
165
+ yield* Deferred.await(started);
166
+ assert.isDefined(startup.pollUnsafe());
167
+ yield* Deferred.succeed(release, undefined);
168
+ return yield* service.awaitDiscovery;
169
+ }),
170
+ });
171
+ }),
172
+ );
173
+
174
+ it.effect(
175
+ "reuses cached paths immediately and streams fresh discovery without keeping removed paths",
176
+ () =>
177
+ Effect.gen(function* () {
178
+ const fs = yield* FileSystem.FileSystem;
179
+ const stateDir = yield* fs.makeTempDirectoryScoped();
180
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
181
+ Effect.provide(NodeServices.layer),
182
+ );
183
+ const executable = yield* HostProcess.ExecutablePath;
184
+ const first = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
185
+ yield* runShellEnvironment({
186
+ env: first,
187
+ stateDir,
188
+ platform: "darwin",
189
+ handler: () =>
190
+ envOutput({
191
+ PATH: "/old/bin:/usr/bin",
192
+ __MISE_DIFF: "old-mise",
193
+ SSH_AUTH_SOCK: "/old-session.sock",
194
+ JAVA_HOME: "/old/java",
195
+ SSL_CERT_FILE: "/old/cert.pem",
196
+ }),
197
+ });
198
+ const cachePath = `${stateDir}/shell-environment-cache.json`;
199
+ const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
200
+ assert.equal(cached.environment.PATH, "/old/bin:/usr/bin");
201
+ assert.notProperty(cached.environment, "SSH_AUTH_SOCK");
202
+ const started = yield* Deferred.make<void>();
203
+ const release = yield* Deferred.make<void>();
204
+ const env: NodeJS.ProcessEnv = {
205
+ SHELL: "/bin/zsh",
206
+ PATH: "/launcher/bin",
207
+ SSH_AUTH_SOCK: "/current-session.sock",
208
+ };
209
+ const source = [
210
+ "const values = { PATH: '/fresh/bin:' + process.env.PATH, __MISE_DIFF: 'fresh-mise', JAVA_HOME: process.env.JAVA_HOME, SSL_CERT_FILE: process.env.SSL_CERT_FILE };",
211
+ "for (const [name, value] of Object.entries(values)) {",
212
+ " if (value !== undefined) process.stdout.write('__T3CODE_ENV_' + name + '_START__\\n' + value + '\\n__T3CODE_ENV_' + name + '_END__\\n');",
213
+ "}",
214
+ ].join("\n");
215
+ let calls = 0;
216
+ yield* runShellEnvironment({
217
+ env,
218
+ stateDir,
219
+ platform: "darwin",
220
+ handler: () => "",
221
+ processSpawner: ChildProcessSpawner.make((command) => {
222
+ calls++;
223
+ return Deferred.succeed(started, undefined).pipe(
224
+ Effect.andThen(Deferred.await(release)),
225
+ Effect.andThen(
226
+ command._tag === "StandardCommand"
227
+ ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
228
+ : Effect.succeed(makeProcess("")),
229
+ ),
230
+ );
231
+ }),
232
+ use: (service) =>
233
+ Effect.gen(function* () {
234
+ yield* service.installIntoProcess;
235
+ yield* service.installIntoProcess;
236
+ assert.equal(env.PATH, "/old/bin:/usr/bin:/launcher/bin");
237
+ assert.equal(env.SSH_AUTH_SOCK, "/current-session.sock");
238
+ const replay = yield* Stream.runHead(service.updates);
239
+ assert.isTrue(Option.isSome(replay));
240
+ if (Option.isSome(replay))
241
+ assert.equal(replay.value.environment.__MISE_DIFF, "old-mise");
242
+ yield* Deferred.await(started);
243
+ assert.equal(calls, 1);
244
+ yield* Deferred.succeed(release, undefined);
245
+ yield* service.awaitDiscovery;
246
+ assert.equal(env.PATH, "/fresh/bin:/launcher/bin");
247
+ assert.equal(env.__MISE_DIFF, "fresh-mise");
248
+ assert.isUndefined(env.JAVA_HOME);
249
+ assert.isUndefined(env.SSL_CERT_FILE);
250
+ const fresh = yield* Stream.runHead(service.updates);
251
+ assert.isTrue(Option.isSome(fresh));
252
+ if (Option.isSome(fresh)) {
253
+ assert.equal(fresh.value.environment.PATH, env.PATH);
254
+ assert.isTrue(fresh.value.discovered);
255
+ }
256
+ return true;
257
+ }),
258
+ });
259
+ const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
260
+ assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin");
261
+ assert.notProperty(refreshed.environment, "JAVA_HOME");
262
+ assert.notProperty(refreshed.environment, "SSL_CERT_FILE");
263
+ }).pipe(Effect.provide(NodeServices.layer)),
264
+ );
265
+
266
+ it.effect.each([
267
+ "not json",
268
+ '{"version":2,"key":"old","environment":{"PATH":"/bad/bin"}}',
269
+ '{"version":1,"key":"other-shell","environment":{"PATH":"/bad/bin"}}',
270
+ ])("ignores an unusable cache and still starts before discovery: %s", (contents) =>
271
+ Effect.gen(function* () {
272
+ const fs = yield* FileSystem.FileSystem;
273
+ const stateDir = yield* fs.makeTempDirectoryScoped();
274
+ yield* fs.writeFileString(`${stateDir}/shell-environment-cache.json`, contents);
275
+ const started = yield* Deferred.make<void>();
276
+ const release = yield* Deferred.make<void>();
277
+ const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
278
+ yield* runShellEnvironment({
279
+ env,
280
+ stateDir,
281
+ platform: "darwin",
282
+ handler: () => "",
283
+ processSpawner: ChildProcessSpawner.make(() =>
284
+ Deferred.succeed(started, undefined).pipe(
285
+ Effect.andThen(Deferred.await(release)),
286
+ Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
287
+ ),
288
+ ),
289
+ use: (service) =>
290
+ Effect.gen(function* () {
291
+ const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
292
+ yield* Deferred.await(started);
293
+ assert.isDefined(startup.pollUnsafe());
294
+ assert.equal(env.PATH, "/usr/bin");
295
+ yield* Deferred.succeed(release, undefined);
296
+ return yield* service.awaitDiscovery;
297
+ }),
298
+ });
299
+ assert.equal(env.PATH, "/fresh/bin:/usr/bin");
300
+ }).pipe(Effect.provide(NodeServices.layer)),
301
+ );
302
+
303
+ it.effect(
304
+ "retains the last successful cache on refresh failure and ignores session values in the cache",
305
+ () =>
306
+ Effect.gen(function* () {
307
+ const fs = yield* FileSystem.FileSystem;
308
+ const stateDir = yield* fs.makeTempDirectoryScoped();
309
+ const contents = encodeCache({
310
+ version: 1,
311
+ key: '["darwin","/test-home","/bin/zsh",""]',
312
+ environment: {
313
+ PATH: "/cached/bin",
314
+ __MISE_DIFF: "cached-mise",
315
+ JAVA_HOME: "/cached/java",
316
+ NODE_EXTRA_CA_CERTS: "/cached/ca.pem",
317
+ SSL_CERT_FILE: "/cached/cert.pem",
318
+ SSL_CERT_DIR: "/cached/certs",
319
+ SSH_AUTH_SOCK: "/stale.sock",
320
+ NODE_OPTIONS: "--bad",
321
+ },
322
+ });
323
+ const cachePath = `${stateDir}/shell-environment-cache.json`;
324
+ yield* fs.writeFileString(cachePath, contents);
325
+ const env: NodeJS.ProcessEnv = {
326
+ SHELL: "/bin/zsh",
327
+ PATH: "/usr/bin",
328
+ __MISE_DIFF: "launcher-mise",
329
+ JAVA_HOME: "/launcher/java",
330
+ NODE_EXTRA_CA_CERTS: "/launcher/ca.pem",
331
+ SSL_CERT_FILE: "",
332
+ SSH_AUTH_SOCK: "/current.sock",
333
+ };
334
+ const prepared = yield* runShellEnvironment({
335
+ env,
336
+ stateDir,
337
+ platform: "darwin",
338
+ handler: () => "",
339
+ use: (service) =>
340
+ Effect.gen(function* () {
341
+ yield* service.installIntoProcess;
342
+ const replay = yield* Stream.runHead(service.updates);
343
+ assert.isTrue(Option.isSome(replay));
344
+ if (Option.isSome(replay)) {
345
+ assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java");
346
+ assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
347
+ }
348
+ return yield* service.awaitDiscovery;
349
+ }),
350
+ });
351
+ assert.isFalse(prepared);
352
+ assert.equal(env.PATH, "/cached/bin:/usr/bin");
353
+ assert.equal(env.__MISE_DIFF, "cached-mise");
354
+ assert.equal(env.JAVA_HOME, "/launcher/java");
355
+ assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
356
+ assert.equal(env.SSL_CERT_FILE, "");
357
+ assert.equal(env.SSL_CERT_DIR, "/cached/certs");
358
+ assert.equal(env.SSH_AUTH_SOCK, "/current.sock");
359
+ assert.isUndefined(env.NODE_OPTIONS);
360
+ assert.equal(yield* fs.readFileString(cachePath), contents);
361
+ }).pipe(Effect.provide(NodeServices.layer)),
362
+ );
363
+
364
+ it.effect("cancels background discovery when the application scope closes", () =>
365
+ Effect.gen(function* () {
366
+ const started = yield* Deferred.make<void>();
367
+ const stopped = yield* Deferred.make<void>();
368
+ yield* runShellEnvironment({
369
+ env: { SHELL: "/bin/zsh", PATH: "/usr/bin" },
370
+ platform: "darwin",
371
+ handler: () => "",
372
+ processSpawner: ChildProcessSpawner.make(() =>
373
+ Deferred.succeed(started, undefined).pipe(
374
+ Effect.andThen(Effect.never),
375
+ Effect.ensuring(Deferred.succeed(stopped, undefined)),
376
+ ),
377
+ ),
378
+ use: (service) =>
379
+ Effect.gen(function* () {
380
+ yield* service.installIntoProcess;
381
+ yield* Deferred.await(started);
382
+ return true;
383
+ }),
384
+ });
385
+ yield* Deferred.await(stopped);
386
+ }),
387
+ );
388
+
389
it.effect(
390
"captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
391
() =>
apps/desktop/src/shell/DesktopShellEnvironment.ts
+159
-23
@@ -1,4 +1,6 @@
1
+import { DesktopShellEnvironmentSnapshot, ShellEnvironmentPatch } from "@t3tools/contracts";
2
import {
3
+ applyShellEnvironment,
4
buildEnvironmentCaptureCommand,
5
listLoginShellCandidates,
6
setWindowsPath,
@@ -6,6 +8,11 @@ import {
8
import * as Context from "effect/Context";
9
import * as Duration from "effect/Duration";
10
import * as Effect from "effect/Effect";
11
+import * as Deferred from "effect/Deferred";
12
+import * as Path from "effect/Path";
13
+import * as PubSub from "effect/PubSub";
14
+import * as Ref from "effect/Ref";
15
+import * as Scope from "effect/Scope";
16
import * as FileSystem from "effect/FileSystem";
17
import * as Layer from "effect/Layer";
18
import * as Option from "effect/Option";
@@ -68,8 +75,10 @@ export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErr
75
export class DesktopShellEnvironment extends Context.Service<
76
DesktopShellEnvironment,
77
{
71
- // Reuses the installation result; false leaves server hydration enabled.
78
+ // Desktop owns discovery, including on cache misses; the backend receives updates over fd4.
79
readonly installIntoProcess: Effect.Effect<boolean>;
80
+ readonly awaitDiscovery: Effect.Effect<boolean>;
81
+ readonly updates: Stream.Stream<DesktopShellEnvironmentSnapshot>;
82
}
83
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
84
@@ -97,6 +106,7 @@ const LOGIN_SHELL_ENV_NAMES = [
106
"T3CODE_TELEMETRY_ENABLED",
107
"T3CODE_GITHUB_APP_CLIENT_ID",
108
"__MISE_DIFF",
109
+ "JAVA_HOME",
110
] as const;
111
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
112
const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
@@ -244,6 +254,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
254
readonly probe: DesktopShellEnvironmentProbe;
255
readonly command: string;
256
readonly args: ReadonlyArray<string>;
257
+ readonly env: NodeJS.ProcessEnv;
258
readonly timeout: Duration.Duration;
259
readonly shell?: boolean;
260
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
@@ -253,6 +264,8 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
264
const child = yield* spawner.spawn(
265
ChildProcess.make(input.command, input.args, {
266
shell: input.shell ?? false,
267
+ env: input.env,
268
+ extendEnv: false,
269
stdin: "ignore",
270
stdout: "pipe",
271
stderr: "ignore",
@@ -308,6 +321,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
321
const readLoginShellEnvironment = (
322
shell: string,
323
names: ReadonlyArray<string>,
324
+ env: NodeJS.ProcessEnv,
325
): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
326
names.length === 0
327
? Effect.succeed({})
@@ -315,20 +329,24 @@ const readLoginShellEnvironment = (
329
probe: "login-shell",
330
command: shell,
331
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
332
+ env,
333
timeout: LOGIN_SHELL_TIMEOUT,
334
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
335
321
-const readLaunchctlPath = runCommandOutput({
322
- probe: "launchctl-path",
323
- command: "/bin/launchctl",
324
- args: ["getenv", "PATH"],
325
- timeout: LAUNCHCTL_TIMEOUT,
326
-}).pipe(Effect.map(trimNonEmpty));
336
+const readLaunchctlPath = (env: NodeJS.ProcessEnv) =>
337
+ runCommandOutput({
338
+ env,
339
+ probe: "launchctl-path",
340
+ command: "/bin/launchctl",
341
+ args: ["getenv", "PATH"],
342
+ timeout: LAUNCHCTL_TIMEOUT,
343
+ }).pipe(Effect.map(trimNonEmpty));
344
345
const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
346
function* (
347
names: ReadonlyArray<string>,
348
options: WindowsProbeOptions,
349
+ env: NodeJS.ProcessEnv,
350
): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
351
if (names.length === 0) return {};
352
@@ -345,6 +363,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
363
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
364
command,
365
args,
366
+ env,
367
timeout: LOGIN_SHELL_TIMEOUT,
368
});
369
const environment = extractEnvironment(output, names);
@@ -363,8 +382,8 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
382
): Effect.fn.Return<boolean, never, ChildProcessSpawner.ChildProcessSpawner> {
383
const [noProfile, profile] = yield* Effect.all(
384
[
366
- readWindowsEnvironment(["PATH"], { loadProfile: false }),
367
- readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
385
+ readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env),
386
+ readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env),
387
],
388
{ concurrency: 2 },
389
);
@@ -402,14 +421,14 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
421
for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
422
Object.assign(
423
shellEnvironment,
405
- yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
424
+ yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env),
425
);
426
if (shellEnvironment.PATH) break;
427
}
428
429
const launchctlPath =
430
config.platform === "darwin" && !shellEnvironment.PATH
412
- ? yield* readLaunchctlPath
431
+ ? yield* readLaunchctlPath(config.env)
432
: Option.none<string>();
433
const mergedPath = mergePaths(config.platform, [
434
trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
@@ -450,6 +469,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
469
"SSL_CERT_FILE",
470
"SSL_CERT_DIR",
471
"NODE_EXTRA_CA_CERTS",
472
+ "JAVA_HOME",
473
"T3CODE_TELEMETRY_ENABLED",
474
"T3CODE_GITHUB_APP_CLIENT_ID",
475
] as const) {
@@ -512,24 +532,140 @@ const installShellEnvironment = (
532
return Effect.succeed(false);
533
};
534
535
+const ShellEnvironmentCache = Schema.fromJsonString(
536
+ Schema.Struct({
537
+ version: Schema.Literal(1),
538
+ key: Schema.String,
539
+ environment: ShellEnvironmentPatch,
540
+ }),
541
+);
542
+const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
543
+const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache);
544
+const encodeCache = Schema.encodeEffect(ShellEnvironmentCache);
545
+const CACHED_ENV_NAMES = [
546
+ "PATH",
547
+ "__MISE_DIFF",
548
+ "HOMEBREW_PREFIX",
549
+ "HOMEBREW_CELLAR",
550
+ "HOMEBREW_REPOSITORY",
551
+ "JAVA_HOME",
552
+ "SSL_CERT_FILE",
553
+ "SSL_CERT_DIR",
554
+ "NODE_EXTRA_CA_CERTS",
555
+] as const;
556
+
557
/** @public */
558
export const make = Effect.gen(function* () {
559
const environment = yield* DesktopEnvironment.DesktopEnvironment;
560
const fileSystem = yield* FileSystem.FileSystem;
561
+ const path = yield* Path.Path;
562
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
520
- const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
521
- yield* Effect.cached(
522
- installShellEnvironment({
523
- env: process.env,
524
- platform: environment.platform,
525
- }).pipe(
526
- Effect.provideService(FileSystem.FileSystem, fileSystem),
527
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
528
- Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
529
- ),
563
+ const scope = yield* Scope.Scope;
564
+ const env = process.env;
565
+ const inherited = { ...env };
566
+ const key = encodeCacheKey([
567
+ environment.platform,
568
+ environment.homeDirectory,
569
+ inherited.SHELL ?? "",
570
+ inherited.ZDOTDIR ?? "",
571
+ ]);
572
+ const cachePath = path.join(environment.stateDir, "shell-environment-cache.json");
573
+ const changes = yield* PubSub.unbounded<DesktopShellEnvironmentSnapshot>();
574
+ const latest = yield* Ref.make<Option.Option<DesktopShellEnvironmentSnapshot>>(Option.none());
575
+ const discovered = yield* Deferred.make<boolean>();
576
+ const publish = Effect.fn("desktop.shellEnvironment.publish")(function* (
577
+ patch: ShellEnvironmentPatch,
578
+ discovered = false,
579
+ ) {
580
+ applyShellEnvironment(env, patch, environment.platform);
581
+ const message: DesktopShellEnvironmentSnapshot = {
582
+ version: 1,
583
+ type: "shellEnvironment",
584
+ discovered,
585
+ platform: environment.platform,
586
+ environment: patch,
587
+ };
588
+ yield* Ref.set(latest, Option.some(message));
589
+ yield* PubSub.publish(changes, message);
590
+ });
591
+ const refresh = Effect.gen(function* () {
592
+ // Refresh from the inherited baseline so removed cached paths and values do not survive.
593
+ const fresh = { ...inherited };
594
+ const prepared = yield* installShellEnvironment({ env: fresh, platform: environment.platform });
595
+ const patch = Object.fromEntries(
596
+ Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
597
);
531
-
532
- return DesktopShellEnvironment.of({ installIntoProcess });
598
+ if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared);
599
+ if (prepared) {
600
+ const cached = Object.fromEntries(
601
+ CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])),
602
+ );
603
+ const persist = Effect.gen(function* () {
604
+ const encoded = yield* encodeCache({ version: 1, key, environment: cached });
605
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
606
+ yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 });
607
+ yield* fileSystem.rename(cachePath + ".tmp", cachePath);
608
+ });
609
+ yield* persist.pipe(
610
+ Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
611
+ );
612
+ }
613
+ return prepared;
614
+ }).pipe(
615
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
616
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
617
+ Effect.withSpan("desktop.shellEnvironment.refresh"),
618
+ Effect.onExit((exit) => Deferred.done(discovered, exit)),
619
+ );
620
+ const installIntoProcess = yield* Effect.cached(
621
+ Effect.gen(function* () {
622
+ const cache = yield* fileSystem
623
+ .readFileString(cachePath)
624
+ .pipe(Effect.flatMap(decodeCache), Effect.option);
625
+ if (Option.isSome(cache) && cache.value.key === key) {
626
+ const cached = Object.fromEntries(
627
+ CACHED_ENV_NAMES.flatMap((name) => {
628
+ const value = cache.value.environment[name];
629
+ // mise's metadata must describe the cached PATH entries restored alongside it.
630
+ if (name !== "PATH" && name !== "__MISE_DIFF" && inherited[name] !== undefined)
631
+ return [];
632
+ return typeof value === "string" ? [[name, value]] : [];
633
+ }),
634
+ );
635
+ const baseline = { ...inherited };
636
+ const cachedPath = cached.PATH;
637
+ if (cachedPath) {
638
+ cached.PATH = Option.getOrElse(
639
+ mergePaths(environment.platform, [Option.some(cachedPath), readEnvPath(inherited)]),
640
+ () => cachedPath,
641
+ );
642
+ }
643
+ applyShellEnvironment(baseline, cached, environment.platform);
644
+ yield* publish(
645
+ Object.fromEntries(
646
+ Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, baseline[name] ?? null]),
647
+ ),
648
+ );
649
+ }
650
+ yield* Effect.forkIn(refresh, scope);
651
+ return true;
652
+ }).pipe(Effect.withSpan("desktop.shellEnvironment.installIntoProcess")),
653
+ );
654
+ const updates = Stream.unwrap(
655
+ Effect.gen(function* () {
656
+ const subscription = yield* PubSub.subscribe(changes);
657
+ const snapshot = yield* Ref.get(latest);
658
+ return Stream.concat(
659
+ Option.isSome(snapshot) ? Stream.make(snapshot.value) : Stream.empty,
660
+ Stream.fromSubscription(subscription),
661
+ );
662
+ }),
663
+ );
664
+ return DesktopShellEnvironment.of({
665
+ installIntoProcess,
666
+ awaitDiscovery: installIntoProcess.pipe(Effect.andThen(Deferred.await(discovered))),
667
+ updates,
668
+ });
669
});
670
671
export const layer = Layer.effect(DesktopShellEnvironment, make);
apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts
+60
-29
@@ -1,6 +1,8 @@
1
import * as NodeServices from "@effect/platform-node/NodeServices";
2
import { assert, describe, it } from "@effect/vitest";
3
import * as Deferred from "effect/Deferred";
4
+import * as Context from "effect/Context";
5
+import * as Option from "effect/Option";
6
import * as Duration from "effect/Duration";
7
import * as Effect from "effect/Effect";
8
import * as Exit from "effect/Exit";
@@ -8,6 +10,7 @@ import * as FileSystem from "effect/FileSystem";
10
import * as Layer from "effect/Layer";
11
import * as Schema from "effect/Schema";
12
import * as Scope from "effect/Scope";
13
+import * as Stream from "effect/Stream";
14
import * as TestClock from "effect/testing/TestClock";
15
16
import type * as Electron from "electron";
@@ -18,6 +21,7 @@ import * as ElectronApp from "../electron/ElectronApp.ts";
21
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
22
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
23
import * as DesktopRendererHistory from "./DesktopRendererHistory.ts";
24
+import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
25
26
const layerHistory = Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, {
27
register: () => Effect.void,
@@ -57,39 +61,66 @@ function layerElectronApp(
61
}
62
63
describe("DesktopTelemetryPublisher", () => {
60
- it.effect("stops when its scope closes during an Electron telemetry sample", () =>
61
- Effect.gen(function* () {
62
- const pollStarted = yield* Deferred.make<void>();
63
- const blockPoll = yield* Deferred.make<void>();
64
- const layerPower = Layer.succeed(
65
- ElectronPowerMonitor.ElectronPowerMonitor,
66
- ElectronPowerMonitor.ElectronPowerMonitor.of({
67
- isOnBatteryPower: Effect.succeed(false),
68
- getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
69
- Effect.andThen(Deferred.await(blockPoll)),
70
- Effect.as(0),
64
+ it.effect(
65
+ "forwards shell discovery while a telemetry sample is pending and stops on scope close",
66
+ () =>
67
+ Effect.gen(function* () {
68
+ const pollStarted = yield* Deferred.make<void>();
69
+ const blockPoll = yield* Deferred.make<void>();
70
+ const layerPower = Layer.succeed(
71
+ ElectronPowerMonitor.ElectronPowerMonitor,
72
+ ElectronPowerMonitor.ElectronPowerMonitor.of({
73
+ isOnBatteryPower: Effect.succeed(false),
74
+ getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
75
+ Effect.andThen(Deferred.await(blockPoll)),
76
+ Effect.as(0),
77
+ ),
78
+ getSystemIdleState: () => Effect.succeed("active"),
79
+ getCurrentThermalState: Effect.succeed("nominal"),
80
+ onSimpleEvent: () => Effect.void,
81
+ onThermalStateChange: () => Effect.void,
82
+ onSpeedLimitChange: () => Effect.void,
83
+ }),
84
+ );
85
+ const layer = DesktopTelemetryPublisher.layer.pipe(
86
+ Layer.provide(
87
+ Layer.mergeAll(
88
+ layerElectronApp([]),
89
+ layerPower,
90
+ layerHistory,
91
+ Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
92
+ installIntoProcess: Effect.succeed(true),
93
+ awaitDiscovery: Effect.succeed(true),
94
+ updates: Stream.make({
95
+ version: 1,
96
+ type: "shellEnvironment",
97
+ discovered: true,
98
+ platform: "darwin",
99
+ environment: { PATH: "/discovered/bin" },
100
+ }),
101
+ }),
102
+ ),
103
),
72
- getSystemIdleState: () => Effect.succeed("active"),
73
- getCurrentThermalState: Effect.succeed("nominal"),
74
- onSimpleEvent: () => Effect.void,
75
- onThermalStateChange: () => Effect.void,
76
- onSpeedLimitChange: () => Effect.void,
77
- }),
78
- );
79
- const layer = DesktopTelemetryPublisher.layer.pipe(
80
- Layer.provide(Layer.mergeAll(layerElectronApp([]), layerPower, layerHistory)),
81
- );
82
- const scope = yield* Scope.make();
104
+ );
105
+ const scope = yield* Scope.make();
106
84
- yield* Layer.buildWithScope(layer, scope);
85
- yield* Deferred.await(pollStarted);
107
+ const context = yield* Layer.buildWithScope(layer, scope);
108
+ const publisher = Context.get(context, DesktopTelemetryPublisher.DesktopTelemetryPublisher);
109
+ const update = yield* publisher.encoded.pipe(
110
+ Stream.filter((bytes) => new TextDecoder().decode(bytes).includes("shellEnvironment")),
111
+ Stream.runHead,
112
+ );
113
+ assert.isTrue(Option.isSome(update));
114
+ if (Option.isSome(update))
115
+ assert.include(new TextDecoder().decode(update.value), "/discovered/bin");
116
+ yield* Deferred.await(pollStarted);
117
87
- const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
88
- yield* Effect.yieldNow;
89
- yield* Effect.yieldNow;
118
+ const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
119
+ yield* Effect.yieldNow;
120
+ yield* Effect.yieldNow;
121
91
- assert.isDefined(closeFiber.pollUnsafe());
92
- }),
122
+ assert.isDefined(closeFiber.pollUnsafe());
123
+ }),
124
);
125
});
126
apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts
+3
-1
@@ -24,6 +24,7 @@ import * as Stream from "effect/Stream";
24
import * as ElectronApp from "../electron/ElectronApp.ts";
25
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
26
import * as DesktopRendererHistory from "./DesktopRendererHistory.ts";
27
+import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
28
29
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
30
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
@@ -146,6 +147,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
147
const electronApp = yield* ElectronApp.ElectronApp;
148
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
149
const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
150
+ const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
151
yield* electronApp.whenReady;
152
153
const initialPowerState: PowerState = {
@@ -400,7 +402,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
402
type: "desktopTelemetryHello",
403
electronPid: process.pid,
404
} as const),
403
- Stream.merge(snapshots, updateReports),
405
+ Stream.merge(Stream.merge(snapshots, updateReports), shellEnvironment.updates),
406
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
407
408
const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts
+184
-1
@@ -1,12 +1,195 @@
1
// @effect-diagnostics nodeBuiltinImport:off
2
3
import { it } from "@effect/vitest";
4
+import * as NodeTls from "node:tls";
5
+import * as NodeCrypto from "node:crypto";
6
+import * as NodeServices from "@effect/platform-node/NodeServices";
7
import * as Effect from "effect/Effect";
8
+import * as Cause from "effect/Cause";
9
+import * as FileSystem from "effect/FileSystem";
10
+import * as Logger from "effect/Logger";
11
+import * as Path from "effect/Path";
12
+import * as Stream from "effect/Stream";
13
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
import { describe, expect } from "vite-plus/test";
15
7
-import { requireDesktopTelemetryWriteProgress } from "./DesktopTelemetryReceiver.ts";
16
+import {
17
+ makeApplyDesktopShellEnvironmentSnapshot,
18
+ requireDesktopTelemetryWriteProgress,
19
+} from "./DesktopTelemetryReceiver.ts";
20
21
describe("DesktopTelemetryReceiver", () => {
22
+ it.live(
23
+ "preserves system and bundled roots when the first snapshot withdraws overlapping extras",
24
+ () =>
25
+ Effect.gen(function* () {
26
+ const fs = yield* FileSystem.FileSystem;
27
+ const path = yield* Path.Path;
28
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
29
+ const directory = yield* fs.makeTempDirectoryScoped();
30
+ const certificatePath = path.join(directory, "startup-extra-ca.pem");
31
+ yield* fs.writeFileString(
32
+ certificatePath,
33
+ [...NodeTls.getCACertificates("system"), ...NodeTls.rootCertificates].join("\n"),
34
+ );
35
+ const child = yield* spawner.spawn(
36
+ ChildProcess.make(
37
+ process.execPath,
38
+ [
39
+ "--use-bundled-ca",
40
+ "--use-system-ca",
41
+ "--input-type=module",
42
+ "--eval",
43
+ `
44
+import * as NodeAssert from "node:assert/strict";
45
+import * as NodeCrypto from "node:crypto";
46
+import * as NodeTls from "node:tls";
47
+import * as Effect from "effect/Effect";
48
+import * as NodeServices from "@effect/platform-node/NodeServices";
49
+import { makeApplyDesktopShellEnvironmentSnapshot } from ${JSON.stringify(new URL("./DesktopTelemetryReceiver.ts", import.meta.url).href)};
50
+const fingerprints = (certificates) => [...new Set(certificates.map((pem) => new NodeCrypto.X509Certificate(pem).fingerprint256))].sort();
51
+const expected = fingerprints([...NodeTls.getCACertificates("bundled"), ...NodeTls.getCACertificates("system")]);
52
+const applySnapshot = makeApplyDesktopShellEnvironmentSnapshot(process.env, process.platform);
53
+await Effect.runPromise(applySnapshot({
54
+ version: 1,
55
+ type: "shellEnvironment",
56
+ platform: process.platform,
57
+ discovered: true,
58
+ environment: { NODE_EXTRA_CA_CERTS: null },
59
+}).pipe(Effect.provide(NodeServices.layer)));
60
+NodeAssert.equal(process.env.NODE_EXTRA_CA_CERTS, undefined);
61
+NodeAssert.deepEqual(fingerprints(NodeTls.getCACertificates("default")), expected);
62
+`,
63
+ ],
64
+ {
65
+ cwd: path.resolve(import.meta.dirname, "../.."),
66
+ env: { NODE_OPTIONS: "", NODE_EXTRA_CA_CERTS: certificatePath },
67
+ },
68
+ ),
69
+ );
70
+ const result = yield* Effect.all(
71
+ {
72
+ stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
73
+ exitCode: child.exitCode.pipe(Effect.map(Number)),
74
+ },
75
+ { concurrency: "unbounded" },
76
+ );
77
+ expect(result.exitCode, result.stderr).toBe(0);
78
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
79
+ );
80
+
81
+ it.effect("updates live TLS trust when shell certificates arrive after startup", () =>
82
+ Effect.gen(function* () {
83
+ const fs = yield* FileSystem.FileSystem;
84
+ const path = yield* Path.Path;
85
+ const directory = yield* fs.makeTempDirectoryScoped();
86
+ const certificatePath = path.join(directory, "extra-ca.pem");
87
+ const original = NodeTls.getCACertificates("default");
88
+ yield* Effect.addFinalizer(() =>
89
+ Effect.sync(() => NodeTls.setDefaultCACertificates(original)),
90
+ );
91
+ const baseline = NodeTls.rootCertificates[0]!;
92
+ const extra = NodeTls.rootCertificates[1]!;
93
+ const replacement = NodeTls.rootCertificates[2]!;
94
+ NodeTls.setDefaultCACertificates([baseline]);
95
+ yield* fs.writeFileString(certificatePath, `${extra}\n${replacement}`);
96
+ const environment: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" };
97
+ const applySnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, "darwin");
98
+ const message = {
99
+ version: 1,
100
+ type: "shellEnvironment",
101
+ platform: "darwin",
102
+ discovered: true,
103
+ environment: { NODE_EXTRA_CA_CERTS: certificatePath },
104
+ } as const;
105
+ const fingerprints = (certificates: ReadonlyArray<string>) =>
106
+ certificates.map((pem) => new NodeCrypto.X509Certificate(pem).fingerprint256).sort();
107
+ yield* applySnapshot({ ...message, platform: "win32" });
108
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline]));
109
+ expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBe("1");
110
+ yield* applySnapshot(message);
111
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
112
+ fingerprints([baseline, extra, replacement]),
113
+ );
114
+ expect(environment.NODE_EXTRA_CA_CERTS).toBe(certificatePath);
115
+ expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBeUndefined();
116
+
117
+ yield* fs.writeFileString(certificatePath, replacement);
118
+ yield* applySnapshot(message);
119
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
120
+ fingerprints([baseline, replacement]),
121
+ );
122
+
123
+ yield* fs.writeFileString(
124
+ certificatePath,
125
+ "-----BEGIN CERTIFICATE-----\ninvalid\n-----END CERTIFICATE-----",
126
+ );
127
+ yield* applySnapshot(message);
128
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
129
+ fingerprints([baseline, replacement]),
130
+ );
131
+ yield* fs.remove(certificatePath);
132
+ const warnings: Array<Logger.Options<unknown>> = [];
133
+ yield* applySnapshot(message).pipe(
134
+ Effect.provide(
135
+ Logger.layer([Logger.make((entry) => warnings.push(entry))], {
136
+ mergeWithExisting: false,
137
+ }),
138
+ ),
139
+ );
140
+ expect(warnings).toHaveLength(1);
141
+ expect(warnings[0]!.message).toEqual(["Failed to update desktop shell TLS certificates."]);
142
+ expect(Cause.squash(warnings[0]!.cause)).toMatchObject({ _tag: "PlatformError" });
143
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(
144
+ fingerprints([baseline, replacement]),
145
+ );
146
+
147
+ yield* applySnapshot({ ...message, environment: { NODE_EXTRA_CA_CERTS: null } });
148
+ expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline]));
149
+ expect(environment.NODE_EXTRA_CA_CERTS).toBeUndefined();
150
+
151
+ NodeTls.setDefaultCACertificates([]);
152
+ yield* fs.writeFileString(certificatePath, extra);
153
+ const applyOpaqueTrust = makeApplyDesktopShellEnvironmentSnapshot(environment, "darwin");
154
+ yield* applyOpaqueTrust(message);
155
+ expect(NodeTls.getCACertificates("default")).toEqual([]);
156
+ expect(environment.NODE_EXTRA_CA_CERTS).toBe(certificatePath);
157
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
158
+ );
159
+
160
+ it.effect.each([
161
+ { platform: "darwin", discovered: true, applied: true, pending: false },
162
+ { platform: "win32", discovered: true, applied: false, pending: true },
163
+ { platform: "darwin", discovered: false, applied: true, pending: true },
164
+ ])(
165
+ "applies platform=$platform discovered=$discovered with pending=$pending",
166
+ ({ platform, discovered, applied, pending }) =>
167
+ Effect.gen(function* () {
168
+ const environment: NodeJS.ProcessEnv = {
169
+ PATH: "/old/bin",
170
+ JAVA_HOME: "/old/java",
171
+ UNRELATED: "keep",
172
+ T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
173
+ };
174
+ yield* makeApplyDesktopShellEnvironmentSnapshot(
175
+ environment,
176
+ "darwin",
177
+ )({
178
+ version: 1,
179
+ type: "shellEnvironment",
180
+ platform,
181
+ discovered,
182
+ environment: { PATH: "/fresh/bin", JAVA_HOME: null },
183
+ });
184
+ expect(environment).toEqual({
185
+ PATH: applied ? "/fresh/bin" : "/old/bin",
186
+ ...(applied ? {} : { JAVA_HOME: "/old/java" }),
187
+ UNRELATED: "keep",
188
+ ...(pending ? { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" } : {}),
189
+ });
190
+ }).pipe(Effect.provide(NodeServices.layer)),
191
+ );
192
+
193
it.effect("models a zero-byte control write as a stalled descriptor", () =>
194
Effect.gen(function* () {
195
const error = yield* requireDesktopTelemetryWriteProgress(7, 42, 0).pipe(Effect.flip);
apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
+77
@@ -1,22 +1,28 @@
1
// @effect-diagnostics nodeBuiltinImport:off
2
import * as NodeFS from "node:fs";
3
import * as NodeNet from "node:net";
4
+import * as NodeTls from "node:tls";
5
6
import * as NodeStream from "@effect/platform-node/NodeStream";
7
import {
8
DesktopHostTelemetryMessage,
9
type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
10
type DesktopHostTelemetrySnapshot,
11
+ type DesktopShellEnvironmentSnapshot,
12
DesktopTelemetryControlMessage,
13
type DesktopUpdateChannel,
14
type DesktopUpdateStatusReport,
15
type ResourceTelemetrySourceStatus,
16
} from "@t3tools/contracts";
17
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
18
+import * as HostProcess from "@t3tools/shared/HostProcess";
19
+import { applyShellEnvironment } from "@t3tools/shared/shell";
20
+import * as Cause from "effect/Cause";
21
import * as Context from "effect/Context";
22
import * as DateTime from "effect/DateTime";
23
import * as Duration from "effect/Duration";
24
import * as Effect from "effect/Effect";
25
+import * as FileSystem from "effect/FileSystem";
26
import * as Layer from "effect/Layer";
27
import * as Option from "effect/Option";
28
import * as PubSub from "effect/PubSub";
@@ -202,6 +208,70 @@ export class DesktopTelemetryReceiver extends Context.Service<
208
}
209
>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
210
211
+class DesktopShellCertificatesUpdateFailed extends Schema.TaggedError<DesktopShellCertificatesUpdateFailed>()(
212
+ "DesktopShellCertificatesUpdateFailed",
213
+ { cause: Schema.Defect() },
214
+) {
215
+ override get message(): string {
216
+ return "Failed to update desktop shell TLS certificates.";
217
+ }
218
+}
219
+
220
+export function makeApplyDesktopShellEnvironmentSnapshot(
221
+ environment: NodeJS.ProcessEnv,
222
+ platform: NodeJS.Platform,
223
+) {
224
+ let baseCertificates: Array<string> | undefined;
225
+ return Effect.fn("resourceTelemetry.desktopTelemetryReceiver.applyShellEnvironment")(function* (
226
+ message: DesktopShellEnvironmentSnapshot,
227
+ ) {
228
+ if (message.platform !== platform) return;
229
+ // Node's first default-CA enumeration consults process.env, so capture it before the patch.
230
+ if (message.environment.NODE_EXTRA_CA_CERTS !== undefined && baseCertificates === undefined) {
231
+ // Remove only the startup extras, preserving duplicates from bundled or system trust.
232
+ const extras = [...NodeTls.getCACertificates("extra")];
233
+ baseCertificates = NodeTls.getCACertificates("default").filter((certificate) => {
234
+ const index = extras.indexOf(certificate);
235
+ if (index === -1) return true;
236
+ extras.splice(index, 1);
237
+ return false;
238
+ });
239
+ }
240
+ applyShellEnvironment(environment, message.environment, platform);
241
+ if (message.environment.NODE_EXTRA_CA_CERTS !== undefined) {
242
+ yield* Effect.gen(function* () {
243
+ const certificates = baseCertificates;
244
+ // --use-openssl-ca roots are not enumerable; replacing the list would discard them.
245
+ if (certificates === undefined || certificates.length === 0) {
246
+ yield* Effect.logWarning(
247
+ "Preserving non-enumerable TLS trust. Restart to apply updated desktop shell certificates.",
248
+ );
249
+ return;
250
+ }
251
+ const fs = yield* FileSystem.FileSystem;
252
+ const file = message.environment.NODE_EXTRA_CA_CERTS;
253
+ const bundle = file ? yield* fs.readFileString(file) : undefined;
254
+ yield* Effect.try({
255
+ try: () => {
256
+ const extras =
257
+ bundle?.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
258
+ if (bundle?.trim() && extras.length === 0) {
259
+ throw new Error("No PEM certificates found.");
260
+ }
261
+ NodeTls.setDefaultCACertificates([...certificates, ...extras]);
262
+ },
263
+ catch: (cause) => new DesktopShellCertificatesUpdateFailed({ cause }),
264
+ });
265
+ }).pipe(
266
+ Effect.catch((cause) =>
267
+ Effect.logWarning("Failed to update desktop shell TLS certificates.", Cause.fail(cause)),
268
+ ),
269
+ );
270
+ }
271
+ if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
272
+ });
273
+}
274
+
275
const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
276
const encodeControlMessage = Schema.encodeEffect(
277
Schema.fromJsonString(DesktopTelemetryControlMessage),
@@ -328,6 +398,9 @@ export function requireDesktopTelemetryWriteProgress(
398
/** @public */
399
export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () {
400
const config = yield* ServerConfig.ServerConfig;
401
+ const environment = yield* HostProcess.Environment;
402
+ const platform = yield* HostProcess.Platform;
403
+ const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform);
404
const serverSettings = yield* ServerSettings.ServerSettingsService;
405
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
406
const receiverStartedAt = yield* DateTime.now;
@@ -523,6 +596,10 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
596
);
597
}
598
599
+ if (message.type === "shellEnvironment") {
600
+ return recordContact.pipe(Effect.andThen(applyShellSnapshot(message)));
601
+ }
602
+
603
if (message.type === "desktopUpdateStatus") {
604
return recordContact.pipe(
605
Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))),
apps/server/src/telemetry/AnalyticsService.test.ts
+26
@@ -165,6 +165,32 @@ const sendFor = (
165
});
166
167
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
168
+ it.effect("waits for desktop shell consent and honors a late telemetry opt-out", () =>
169
+ Effect.gen(function* () {
170
+ const env: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" };
171
+ const batches = yield* sendFor(
172
+ 0,
173
+ respondWithStatus(204),
174
+ Effect.gen(function* () {
175
+ const analytics = yield* AnalyticsService.AnalyticsService;
176
+ yield* analytics.record("test.before-discovery");
177
+ yield* analytics.flush;
178
+ env.T3CODE_TELEMETRY_ENABLED = "false";
179
+ delete env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
180
+ yield* analytics.record("test.opted-out");
181
+ yield* analytics.flush;
182
+ env.T3CODE_TELEMETRY_ENABLED = "true";
183
+ yield* analytics.record("test.allowed");
184
+ yield* analytics.flush;
185
+ }),
186
+ ).pipe(Effect.provideService(HostProcess.Environment, env));
187
+ assert.deepEqual(
188
+ batches.flat().map((event) => event.event),
189
+ ["test.allowed"],
190
+ );
191
+ }),
192
+ );
193
+
194
it.effect("client owner reports cannot use up the server's owner cap", () =>
195
Effect.gen(function* () {
196
const batches = yield* sendFor(
apps/server/src/telemetry/AnalyticsService.ts
+23
-2
@@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
3
import type { ClientOs } from "@t3tools/contracts";
4
import * as Clock from "effect/Clock";
5
import * as Config from "effect/Config";
6
+import * as ConfigProvider from "effect/ConfigProvider";
7
import * as Context from "effect/Context";
8
import * as Crypto from "effect/Crypto";
9
import * as DateTime from "effect/DateTime";
@@ -116,6 +117,26 @@ function serverOsFromNodePlatform(platform: string): ClientOs {
117
/** @public */
118
export const make = Effect.gen(function* () {
119
const telemetryConfig = yield* TelemetryEnvConfig;
120
+ const hostEnvironment = yield* HostProcess.Environment;
121
+ const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1";
122
+ // A cached PATH does not establish consent from the current login shell.
123
+ const telemetryEnabled = Effect.suspend(() => {
124
+ if (!telemetryConfig.enabled) return Effect.succeed(false);
125
+ if (!awaitingShellConsent) return Effect.succeed(true);
126
+ if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1")
127
+ return Effect.succeed(false);
128
+ const preference = hostEnvironment.T3CODE_TELEMETRY_ENABLED;
129
+ return Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(
130
+ Config.withDefault(true),
131
+ Effect.provideService(
132
+ ConfigProvider.ConfigProvider,
133
+ ConfigProvider.fromEnv({
134
+ env: preference === undefined ? {} : { T3CODE_TELEMETRY_ENABLED: preference },
135
+ }),
136
+ ),
137
+ Effect.orElseSucceed(() => false),
138
+ );
139
+ });
140
const httpClient = yield* HttpClient.HttpClient;
141
const serverConfig = yield* ServerConfig.ServerConfig;
142
const { distinctId, installId } = yield* getTelemetryIdentity;
@@ -172,7 +193,7 @@ export const make = Effect.gen(function* () {
193
const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
194
events: ReadonlyArray<BufferedAnalyticsEvent>,
195
) {
175
- if (!telemetryConfig.enabled || !distinctId) return;
196
+ if (!(yield* telemetryEnabled) || !distinctId) return;
197
198
const payload = {
199
api_key: telemetryConfig.posthogKey,
@@ -284,7 +305,7 @@ export const make = Effect.gen(function* () {
305
306
const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
307
function* (event, properties) {
287
- if (!telemetryConfig.enabled || !distinctId) return;
308
+ if (!(yield* telemetryEnabled) || !distinctId) return;
309
310
// Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
311
const uuid = yield* Effect.exit(crypto.randomUUIDv7());
apps/server/src/usage/UsageService.test.ts
+1
@@ -2639,6 +2639,7 @@ describe("UsageService", () => {
2639
2640
it.live("reports saved usage of a removed directory only for windows it reaches", () =>
2641
Effect.gen(function* () {
2642
+ yield* TestClock.setTime(Date.parse("2026-08-12T00:00:00Z"));
2643
const { transcript, settings, home } = yield* setup;
2644
// Saved usage is pruned after the retention window, so pin "now" near the write.
2645
yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z"));
packages/contracts/src/resourceTelemetry.ts
+40
@@ -295,8 +295,48 @@ export const DesktopUpdateStatusReport = Schema.Struct({
295
});
296
export type DesktopUpdateStatusReport = typeof DesktopUpdateStatusReport.Type;
297
298
+export const ShellEnvironmentPatch = Schema.Struct({
299
+ PATH: Schema.optionalKey(Schema.NullOr(Schema.String)),
300
+ DBUS_SESSION_BUS_ADDRESS: Schema.optionalKey(Schema.NullOr(Schema.String)),
301
+ DISPLAY: Schema.optionalKey(Schema.NullOr(Schema.String)),
302
+ LANG: Schema.optionalKey(Schema.NullOr(Schema.String)),
303
+ LC_ALL: Schema.optionalKey(Schema.NullOr(Schema.String)),
304
+ LC_CTYPE: Schema.optionalKey(Schema.NullOr(Schema.String)),
305
+ SSH_AUTH_SOCK: Schema.optionalKey(Schema.NullOr(Schema.String)),
306
+ HOMEBREW_PREFIX: Schema.optionalKey(Schema.NullOr(Schema.String)),
307
+ HOMEBREW_CELLAR: Schema.optionalKey(Schema.NullOr(Schema.String)),
308
+ HOMEBREW_REPOSITORY: Schema.optionalKey(Schema.NullOr(Schema.String)),
309
+ XDG_CONFIG_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)),
310
+ XDG_CURRENT_DESKTOP: Schema.optionalKey(Schema.NullOr(Schema.String)),
311
+ XDG_DATA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)),
312
+ XDG_RUNTIME_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)),
313
+ XDG_SESSION_DESKTOP: Schema.optionalKey(Schema.NullOr(Schema.String)),
314
+ XDG_SESSION_TYPE: Schema.optionalKey(Schema.NullOr(Schema.String)),
315
+ WAYLAND_DISPLAY: Schema.optionalKey(Schema.NullOr(Schema.String)),
316
+ SSL_CERT_FILE: Schema.optionalKey(Schema.NullOr(Schema.String)),
317
+ SSL_CERT_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)),
318
+ NODE_EXTRA_CA_CERTS: Schema.optionalKey(Schema.NullOr(Schema.String)),
319
+ T3CODE_TELEMETRY_ENABLED: Schema.optionalKey(Schema.NullOr(Schema.String)),
320
+ T3CODE_GITHUB_APP_CLIENT_ID: Schema.optionalKey(Schema.NullOr(Schema.String)),
321
+ __MISE_DIFF: Schema.optionalKey(Schema.NullOr(Schema.String)),
322
+ JAVA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)),
323
+ FNM_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)),
324
+ FNM_MULTISHELL_PATH: Schema.optionalKey(Schema.NullOr(Schema.String)),
325
+});
326
+export type ShellEnvironmentPatch = typeof ShellEnvironmentPatch.Type;
327
+
328
+export const DesktopShellEnvironmentSnapshot = Schema.Struct({
329
+ version: Schema.Literal(1),
330
+ type: Schema.Literal("shellEnvironment"),
331
+ discovered: Schema.Boolean,
332
+ platform: Schema.String,
333
+ environment: ShellEnvironmentPatch,
334
+});
335
+export type DesktopShellEnvironmentSnapshot = typeof DesktopShellEnvironmentSnapshot.Type;
336
+
337
export const DesktopHostTelemetryMessage = Schema.Union([
338
DesktopHostTelemetryHello,
339
+ DesktopShellEnvironmentSnapshot,
340
DesktopHostTelemetrySnapshot,
341
DesktopUpdateStatusReport,
342
]);
packages/shared/src/shell.test.ts
+48
@@ -2,6 +2,8 @@
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { it as effectIt } from "@effect/vitest";
4
import * as HostProcess from "@t3tools/shared/HostProcess";
5
+import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
6
+import * as Schema from "effect/Schema";
7
import * as Effect from "effect/Effect";
8
import * as Fiber from "effect/Fiber";
9
import * as FileSystem from "effect/FileSystem";
@@ -14,6 +16,7 @@ import * as NodePath from "node:path";
16
import { describe, expect, it, vi } from "vite-plus/test";
17
18
import {
19
+ applyShellEnvironment,
20
CommandAvailability,
21
CommandResolutionCache,
22
type CommandAvailabilityChecker,
@@ -35,6 +38,8 @@ import {
38
XcodeGitLocation,
39
} from "./shell.ts";
40
41
+const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMessage);
42
+
43
const nativeProbe = vi.hoisted(() => ({
44
execFile: vi.fn<typeof import("node:child_process").execFile>(),
45
}));
@@ -1045,3 +1050,46 @@ effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
1050
}),
1051
);
1052
});
1053
+
1054
+describe("desktop shell environment updates", () => {
1055
+ it.each(["win32", "linux", "darwin"] as const)(
1056
+ "applies shell updates with %s PATH semantics",
1057
+ (platform) => {
1058
+ const message = decodeDesktopHostMessage({
1059
+ version: 1,
1060
+ type: "shellEnvironment",
1061
+ discovered: true,
1062
+ platform,
1063
+ environment: {
1064
+ PATH: "C:\\fresh",
1065
+ FNM_DIR: null,
1066
+ __MISE_DIFF: null,
1067
+ SSH_AUTH_SOCK: "/current.sock",
1068
+ NODE_OPTIONS: "--bad",
1069
+ },
1070
+ });
1071
+ expect(message.type).toBe("shellEnvironment");
1072
+ if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update");
1073
+ const env: NodeJS.ProcessEnv = {
1074
+ Path: "C:\\stale",
1075
+ FNM_DIR: "stale",
1076
+ __MISE_DIFF: "stale",
1077
+ UNRELATED: "keep",
1078
+ };
1079
+ applyShellEnvironment(env, message.environment, platform);
1080
+ expect(env).toEqual({
1081
+ PATH: "C:\\fresh",
1082
+ ...(platform === "win32" ? {} : { Path: "C:\\stale" }),
1083
+ SSH_AUTH_SOCK: "/current.sock",
1084
+ UNRELATED: "keep",
1085
+ });
1086
+ env.Path = "C:\\stale";
1087
+ env.path = "C:\\other";
1088
+ applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform);
1089
+ expect(env).toEqual({
1090
+ ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }),
1091
+ UNRELATED: "keep",
1092
+ });
1093
+ },
1094
+ );
1095
+});
packages/shared/src/shell.ts
+15
-2
@@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem";
10
import * as Option from "effect/Option";
11
import * as Path from "effect/Path";
12
13
+import type { ShellEnvironmentPatch } from "@t3tools/contracts";
14
import * as HostProcess from "./HostProcess.ts";
15
import * as Context from "effect/Context";
16
const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
@@ -908,13 +909,13 @@ function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<strin
909
}
910
911
/** Keep one PATH spelling in copied Windows environment records. */
911
-export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
912
+export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
913
for (const key of Object.keys(env)) {
914
if (key.toUpperCase() === "PATH") {
915
delete env[key];
916
}
917
}
917
- env.PATH = value;
918
+ if (value !== null) env.PATH = value;
919
}
920
921
function mergeWindowsEnv(
@@ -965,3 +966,15 @@ export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironm
966
? { ...baselinePatch, ...profiledPatch }
967
: baselinePatch;
968
});
969
+
970
+export function applyShellEnvironment(
971
+ env: NodeJS.ProcessEnv,
972
+ patch: ShellEnvironmentPatch,
973
+ platform: NodeJS.Platform,
974
+): void {
975
+ for (const [key, value] of Object.entries(patch)) {
976
+ if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
977
+ else if (value === null) delete env[key];
978
+ else env[key] = value;
979
+ }
980
+}