Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, it } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Deferred from "effect/Deferred";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Logger from "effect/Logger";
12import * as PlatformError from "effect/PlatformError";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import * as Schema from "effect/Schema";
16import * as Option from "effect/Option";
17import * as ChildProcess from "effect/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import * as TestClock from "effect/testing/TestClock";
20import * as NodeOS from "node:os";
21import { vi } from "vite-plus/test";
22
23import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
24import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
25
26vi.mock("node:os", { spy: true });
27
28const textEncoder = new TextEncoder();
29const cacheCodec = Schema.fromJsonString(
30 Schema.Struct({
31 version: Schema.Number,
32 key: Schema.String,
33 environment: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),
34 fromUserShell: Schema.optionalKey(Schema.Boolean),
35 }),
36);
37const encodeCache = Schema.encodeSync(cacheCodec);
38const decodeCache = Schema.decodeUnknownEffect(cacheCodec);
39
40function envOutput(values: Readonly<Record<string, string>>): string {
41 return Object.entries(values)
42 .flatMap(([name, value]) => [
43 `__T3CODE_ENV_${name}_START__`,
44 value,
45 `__T3CODE_ENV_${name}_END__`,
46 ])
47 .join("\n");
48}
49
50function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildProcessHandle {
51 const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
52 return ChildProcessSpawner.makeHandle({
53 pid: ChildProcessSpawner.ProcessId(123),
54 stdout,
55 stderr: Stream.empty,
56 all: stdout,
57 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
58 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(exitCode) }),
59 isRunning: Effect.succeed(false),
60 kill: () => Effect.void,
61 stdin: Sink.drain,
62 getInputFd: () => Sink.drain,
63 getOutputFd: () => Stream.empty,
64 unref: Effect.succeed(Effect.void),
65 });
66}
67
68function makeSlowProcess(
69 output: string,
70 delay: Duration.Input,
71): ChildProcessSpawner.ChildProcessHandle {
72 const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
73 return ChildProcessSpawner.makeHandle({
74 pid: ChildProcessSpawner.ProcessId(125),
75 stdout,
76 stderr: Stream.empty,
77 all: stdout,
78 exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
79 exitStatus: Effect.as(Effect.sleep(delay), {
80 _tag: "Exited",
81 code: ChildProcessSpawner.ExitCode(0),
82 }),
83 isRunning: Effect.succeed(true),
84 kill: () => Effect.void,
85 stdin: Sink.drain,
86 getInputFd: () => Sink.drain,
87 getOutputFd: () => Stream.empty,
88 unref: Effect.succeed(Effect.void),
89 });
90}
91
92function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
93 return ChildProcessSpawner.makeHandle({
94 pid: ChildProcessSpawner.ProcessId(124),
95 stdout: Stream.never,
96 stderr: Stream.never,
97 all: Stream.never,
98 exitCode: Effect.never,
99 exitStatus: Effect.never,
100 isRunning: Effect.succeed(true),
101 kill: () => Effect.never,
102 stdin: Sink.drain,
103 getInputFd: () => Sink.drain,
104 getOutputFd: () => Stream.empty,
105 unref: Effect.succeed(Effect.void),
106 });
107}
108
109function withProcessEnv<A, E, R>(
110 env: NodeJS.ProcessEnv,
111 effect: Effect.Effect<A, E, R>,
112): Effect.Effect<A, E, R> {
113 return Effect.acquireUseRelease(
114 Effect.sync(() => {
115 const previous = process.env;
116 process.env = env;
117 return previous;
118 }),
119 () => effect,
120 (previous) =>
121 Effect.sync(() => {
122 process.env = previous;
123 }),
124 );
125}
126
127function runShellEnvironment(input: {
128 readonly env: NodeJS.ProcessEnv;
129 readonly platform: NodeJS.Platform;
130 readonly userShell?: string;
131 readonly stateDir?: string;
132 readonly use?: (
133 service: DesktopShellEnvironment.DesktopShellEnvironment["Service"],
134 ) => Effect.Effect<boolean, never, import("effect/Scope").Scope>;
135 readonly handler: (
136 command: ChildProcess.Command,
137 ) => string | { output: string; exitCode: number };
138 readonly failure?: PlatformError.PlatformError;
139 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
140}) {
141 const layerEnvironment = Layer.effect(
142 DesktopEnvironment.DesktopEnvironment,
143 Effect.gen(function* () {
144 const fs = yield* FileSystem.FileSystem;
145 const stateDir = input.stateDir ?? (yield* fs.makeTempDirectoryScoped());
146 return DesktopEnvironment.DesktopEnvironment.of({
147 platform: input.platform,
148 stateDir,
149 homeDirectory: "/test-home",
150 } as DesktopEnvironment.DesktopEnvironment["Service"]);
151 }),
152 ).pipe(Layer.provide(NodeServices.layer));
153 const layerSpawner = Layer.succeed(
154 ChildProcessSpawner.ChildProcessSpawner,
155 ChildProcessSpawner.make((command) => {
156 if (input.processSpawner) return input.processSpawner.spawn(command);
157 if (input.failure !== undefined) return Effect.fail(input.failure);
158 const result = input.handler(command);
159 return Effect.succeed(
160 typeof result === "string"
161 ? makeProcess(result)
162 : makeProcess(result.output, result.exitCode),
163 );
164 }),
165 );
166
167 const program = Effect.gen(function* () {
168 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
169 if (input.use) return yield* input.use(shellEnvironment);
170 const prepared = yield* shellEnvironment.awaitDiscovery;
171 assert.equal(yield* shellEnvironment.awaitDiscovery, prepared);
172 return prepared;
173 }).pipe(
174 Effect.provide(
175 DesktopShellEnvironment.layer.pipe(
176 Layer.provide(Layer.mergeAll(layerEnvironment, NodeServices.layer, layerSpawner)),
177 ),
178 ),
179 );
180
181 return Effect.acquireUseRelease(
182 Effect.sync(() =>
183 vi.spyOn(NodeOS, "userInfo").mockReturnValue({
184 ...NodeOS.userInfo(),
185 shell: input.userShell ?? null,
186 }),
187 ),
188 () => withProcessEnv(input.env, program),
189 (spy) => Effect.sync(() => spy.mockRestore()),
190 );
191}
192
193describe("DesktopShellEnvironment", () => {
194 it.effect.each([
195 { platform: "linux" as const, runtime: { APPDIR: "/opt/t3.AppDir/" }, scrub: true },
196 { platform: "linux" as const, runtime: { APPIMAGE: "/opt/T3.AppImage" }, scrub: true },
197 { platform: "linux" as const, runtime: {}, scrub: false },
198 { platform: "darwin" as const, runtime: { APPDIR: "/opt/t3.AppDir/" }, scrub: false },
199 ])(
200 "keeps AppImage mounts out of cached and discovered PATH: %j",
201 ({ platform, runtime, scrub }) =>
202 Effect.gen(function* () {
203 const fs = yield* FileSystem.FileSystem;
204 const stateDir = yield* fs.makeTempDirectoryScoped();
205 const cachePath = `${stateDir}/shell-environment-cache.json`;
206 const inheritedPath =
207 "/tmp/.mount_T3-Codold123/usr/bin:/launcher/bin:/opt/t3.AppDir/usr/bin";
208 const cachedPath = "/cached/bin:/tmp/.mount_T3-Codcache1/usr/bin";
209 const discoveredPath = "/fresh/bin:/tmp/.mount_T3-Codprobe1/usr/bin";
210 const retainedPath = "/tmp/tools:/tmp/.mount_Other123/usr/bin:/opt/t3.AppDir-backup/bin";
211 const cleanInherited = scrub
212 ? `/launcher/bin${runtime.APPDIR ? "" : ":/opt/t3.AppDir/usr/bin"}`
213 : inheritedPath;
214 const cleanCached = scrub ? "/cached/bin" : cachedPath;
215 const cleanDiscovered = scrub ? "/fresh/bin" : discoveredPath;
216 const env: NodeJS.ProcessEnv = {
217 ...runtime,
218 SHELL: "/bin/bash",
219 PATH: `${inheritedPath}:${retainedPath}`,
220 };
221 yield* fs.writeFileString(
222 cachePath,
223 encodeCache({
224 version: 1,
225 key: JSON.stringify([platform, "/test-home", "/bin/bash", ""]),
226 environment: { PATH: cachedPath, __MISE_DIFF: "cached-mise" },
227 }),
228 );
229 const started = yield* Deferred.make<void>();
230 const release = yield* Deferred.make<void>();
231 const probePath = yield* Deferred.make<string | undefined>();
232 yield* runShellEnvironment({
233 env,
234 platform,
235 stateDir,
236 handler: () => "",
237 processSpawner: ChildProcessSpawner.make((command) =>
238 Effect.gen(function* () {
239 const value =
240 command._tag === "StandardCommand" ? command.options.env?.PATH : undefined;
241 const path = typeof value === "string" ? value : undefined;
242 yield* Deferred.succeed(probePath, path);
243 yield* Deferred.succeed(started, undefined);
244 yield* Deferred.await(release);
245 return makeProcess(
246 envOutput({ PATH: `${discoveredPath}:${path}`, __MISE_DIFF: "fresh-mise" }),
247 );
248 }),
249 ),
250 use: (service) =>
251 Effect.gen(function* () {
252 yield* service.installIntoProcess;
253 const expectedCached = `${cleanCached}:${cleanInherited}:${retainedPath}`;
254 assert.equal(env.PATH, expectedCached);
255 assert.equal(env.__MISE_DIFF, "cached-mise");
256 const cached = yield* Stream.runHead(service.updates);
257 assert.equal(Option.getOrThrow(cached).environment.PATH, expectedCached);
258 yield* Deferred.await(started);
259 assert.equal(yield* Deferred.await(probePath), `${cleanInherited}:${retainedPath}`);
260 yield* Deferred.succeed(release, undefined);
261 yield* service.awaitDiscovery;
262 const expectedFresh = `${cleanDiscovered}:${cleanInherited}:${retainedPath}`;
263 assert.equal(env.PATH, expectedFresh);
264 assert.equal(env.__MISE_DIFF, "fresh-mise");
265 const fresh = yield* Stream.runHead(service.updates);
266 assert.equal(Option.getOrThrow(fresh).environment.PATH, expectedFresh);
267 return true;
268 }),
269 });
270 const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
271 assert.equal(cached.environment.PATH, env.PATH);
272 assert.equal(cached.environment.__MISE_DIFF, "fresh-mise");
273 }).pipe(Effect.provide(NodeServices.layer)),
274 );
275
276 it.effect.each([
277 { platform: "darwin" as const, env: { PATH: "/usr/bin" }, expectedPath: "/usr/bin" },
278 {
279 platform: "linux" as const,
280 env: { APPDIR: "/tmp/.mount_T3-Codnew123", PATH: ":/tmp/.mount_T3-Codold123/bin::/usr/bin:" },
281 expectedPath: "::/usr/bin:",
282 },
283 {
284 platform: "linux" as const,
285 env: { APPDIR: "/tmp/.mount_T3-Codnew123", PATH: "/tmp/.mount_T3-Codnew123/bin" },
286 expectedPath: undefined,
287 },
288 ])(
289 "does not wait for discovery when the cache is missing: %j",
290 ({ platform, env: initial, expectedPath }) =>
291 Effect.gen(function* () {
292 const started = yield* Deferred.make<void>();
293 const release = yield* Deferred.make<void>();
294 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", ...initial };
295 let probePath: string | undefined;
296 yield* runShellEnvironment({
297 env,
298 platform,
299 handler: () => "",
300 processSpawner: ChildProcessSpawner.make((command) =>
301 Effect.gen(function* () {
302 const value =
303 command._tag === "StandardCommand" ? command.options.env?.PATH : undefined;
304 probePath = typeof value === "string" ? value : undefined;
305 yield* Deferred.succeed(started, undefined);
306 yield* Deferred.await(release);
307 return makeProcess(envOutput({ PATH: "/fresh/bin" }));
308 }),
309 ),
310 use: (service) =>
311 Effect.gen(function* () {
312 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
313 yield* Deferred.await(started);
314 assert.isDefined(startup.pollUnsafe());
315 assert.equal(env.PATH, expectedPath);
316 assert.equal(probePath, expectedPath);
317 yield* Deferred.succeed(release, undefined);
318 return yield* service.awaitDiscovery;
319 }),
320 });
321 }),
322 );
323
324 it.effect(
325 "reuses cached paths immediately and streams fresh discovery without keeping removed paths",
326 () =>
327 Effect.gen(function* () {
328 const fs = yield* FileSystem.FileSystem;
329 const stateDir = yield* fs.makeTempDirectoryScoped();
330 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
331 Effect.provide(NodeServices.layer),
332 );
333 const executable = yield* HostProcess.ExecutablePath;
334 const first = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
335 yield* runShellEnvironment({
336 env: first,
337 stateDir,
338 platform: "darwin",
339 handler: () =>
340 envOutput({
341 PATH: "/old/bin:/usr/bin",
342 __MISE_DIFF: "old-mise",
343 SSH_AUTH_SOCK: "/old-session.sock",
344 JAVA_HOME: "/old/java",
345 PNPM_HOME: "/old/pnpm",
346 SSL_CERT_FILE: "/old/cert.pem",
347 }),
348 });
349 const cachePath = `${stateDir}/shell-environment-cache.json`;
350 const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
351 assert.equal(cached.environment.PATH, "/old/bin:/usr/bin");
352 assert.isTrue(cached.fromUserShell);
353 assert.equal(cached.environment.PNPM_HOME, "/old/pnpm");
354 assert.notProperty(cached.environment, "SSH_AUTH_SOCK");
355 const started = yield* Deferred.make<void>();
356 const release = yield* Deferred.make<void>();
357 const env: NodeJS.ProcessEnv = {
358 SHELL: "/bin/zsh",
359 PATH: "/launcher/bin",
360 SSH_AUTH_SOCK: "/current-session.sock",
361 };
362 const source = [
363 "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 };",
364 "for (const [name, value] of Object.entries(values)) {",
365 " if (value !== undefined) process.stdout.write('__T3CODE_ENV_' + name + '_START__\\n' + value + '\\n__T3CODE_ENV_' + name + '_END__\\n');",
366 "}",
367 ].join("\n");
368 let calls = 0;
369 yield* runShellEnvironment({
370 env,
371 stateDir,
372 platform: "darwin",
373 handler: () => "",
374 processSpawner: ChildProcessSpawner.make((command) => {
375 calls++;
376 return Deferred.succeed(started, undefined).pipe(
377 Effect.andThen(Deferred.await(release)),
378 Effect.andThen(
379 command._tag === "StandardCommand"
380 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
381 : Effect.succeed(makeProcess("")),
382 ),
383 );
384 }),
385 use: (service) =>
386 Effect.gen(function* () {
387 yield* service.installIntoProcess;
388 yield* service.installIntoProcess;
389 assert.equal(env.PATH, "/old/bin:/usr/bin:/launcher/bin");
390 assert.equal(env.SSH_AUTH_SOCK, "/current-session.sock");
391 const replay = yield* Stream.runHead(service.updates);
392 assert.isTrue(Option.isSome(replay));
393 if (Option.isSome(replay))
394 assert.equal(replay.value.environment.__MISE_DIFF, "old-mise");
395 yield* Deferred.await(started);
396 assert.equal(calls, 1);
397 yield* Deferred.succeed(release, undefined);
398 yield* service.awaitDiscovery;
399 assert.equal(env.PATH, "/fresh/bin:/launcher/bin");
400 assert.equal(env.__MISE_DIFF, "fresh-mise");
401 assert.isUndefined(env.JAVA_HOME);
402 assert.isUndefined(env.PNPM_HOME);
403 assert.isUndefined(env.SSL_CERT_FILE);
404 const fresh = yield* Stream.runHead(service.updates);
405 assert.isTrue(Option.isSome(fresh));
406 if (Option.isSome(fresh)) {
407 assert.equal(fresh.value.environment.PATH, env.PATH);
408 assert.isTrue(fresh.value.discovered);
409 }
410 return true;
411 }),
412 });
413 const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
414 assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin");
415 assert.notProperty(refreshed.environment, "JAVA_HOME");
416 assert.notProperty(refreshed.environment, "PNPM_HOME");
417 assert.notProperty(refreshed.environment, "SSL_CERT_FILE");
418 }).pipe(Effect.provide(NodeServices.layer)),
419 );
420
421 it.effect.each([
422 "not json",
423 '{"version":2,"key":"old","environment":{"PATH":"/bad/bin"}}',
424 '{"version":1,"key":"other-shell","environment":{"PATH":"/bad/bin"}}',
425 ])("ignores an unusable cache and still starts before discovery: %s", (contents) =>
426 Effect.gen(function* () {
427 const fs = yield* FileSystem.FileSystem;
428 const stateDir = yield* fs.makeTempDirectoryScoped();
429 yield* fs.writeFileString(`${stateDir}/shell-environment-cache.json`, contents);
430 const started = yield* Deferred.make<void>();
431 const release = yield* Deferred.make<void>();
432 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
433 yield* runShellEnvironment({
434 env,
435 stateDir,
436 platform: "darwin",
437 handler: () => "",
438 processSpawner: ChildProcessSpawner.make(() =>
439 Deferred.succeed(started, undefined).pipe(
440 Effect.andThen(Deferred.await(release)),
441 Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
442 ),
443 ),
444 use: (service) =>
445 Effect.gen(function* () {
446 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
447 yield* Deferred.await(started);
448 assert.isDefined(startup.pollUnsafe());
449 assert.equal(env.PATH, "/usr/bin");
450 yield* Deferred.succeed(release, undefined);
451 return yield* service.awaitDiscovery;
452 }),
453 });
454 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
455 }).pipe(Effect.provide(NodeServices.layer)),
456 );
457
458 it.effect.each([false, true])(
459 "retains the last successful cache when the user shell fails (fallback answered: %s)",
460 (fallbackAnswered) =>
461 Effect.gen(function* () {
462 const fs = yield* FileSystem.FileSystem;
463 const stateDir = yield* fs.makeTempDirectoryScoped();
464 const contents = encodeCache({
465 version: 1,
466 key: '["darwin","/test-home","/opt/homebrew/bin/fish",""]',
467 environment: {
468 PATH: "/cached/bin",
469 __MISE_DIFF: "cached-mise",
470 JAVA_HOME: "/cached/java",
471 PNPM_HOME: "/cached/pnpm",
472 NODE_EXTRA_CA_CERTS: "/cached/ca.pem",
473 SSL_CERT_FILE: "/cached/cert.pem",
474 SSL_CERT_DIR: "/cached/certs",
475 T3CODE_TELEMETRY_ENABLED: "false",
476 SSH_AUTH_SOCK: "/stale.sock",
477 NODE_OPTIONS: "--bad",
478 },
479 fromUserShell: true,
480 });
481 const cachePath = `${stateDir}/shell-environment-cache.json`;
482 yield* fs.writeFileString(cachePath, contents);
483 const env: NodeJS.ProcessEnv = {
484 SHELL: "/opt/homebrew/bin/fish",
485 PATH: "/usr/bin",
486 __MISE_DIFF: "launcher-mise",
487 JAVA_HOME: "/launcher/java",
488 NODE_EXTRA_CA_CERTS: "/launcher/ca.pem",
489 SSL_CERT_FILE: "",
490 SSH_AUTH_SOCK: "/current.sock",
491 };
492 const prepared = yield* runShellEnvironment({
493 env,
494 stateDir,
495 platform: "darwin",
496 handler: (command) =>
497 fallbackAnswered && command._tag === "StandardCommand" && command.command === "/bin/zsh"
498 ? envOutput({ PATH: "/fallback/bin", DO_NOT_TRACK: "1" })
499 : { output: "", exitCode: 7 },
500 use: (service) =>
501 Effect.gen(function* () {
502 yield* service.installIntoProcess;
503 const replay = yield* Stream.runHead(service.updates);
504 assert.isTrue(Option.isSome(replay));
505 if (Option.isSome(replay)) {
506 assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java");
507 assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
508 }
509 return yield* service.awaitDiscovery;
510 }),
511 });
512 assert.equal(prepared, fallbackAnswered);
513 // A fallback adds its folders and an opt-out the cache lacks, without hiding the cache.
514 assert.equal(
515 env.PATH,
516 fallbackAnswered ? "/cached/bin:/usr/bin:/fallback/bin" : "/cached/bin:/usr/bin",
517 );
518 assert.equal(env.DO_NOT_TRACK, fallbackAnswered ? "1" : undefined);
519 assert.equal(env.__MISE_DIFF, "cached-mise");
520 assert.equal(env.JAVA_HOME, "/launcher/java");
521 assert.equal(env.PNPM_HOME, "/cached/pnpm");
522 assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
523 assert.equal(env.SSL_CERT_FILE, "");
524 assert.equal(env.SSL_CERT_DIR, "/cached/certs");
525 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
526 assert.equal(env.SSH_AUTH_SOCK, "/current.sock");
527 assert.isUndefined(env.NODE_OPTIONS);
528 assert.equal(yield* fs.readFileString(cachePath), contents);
529 }).pipe(Effect.provide(NodeServices.layer)),
530 );
531
532 it.effect.each([
533 { cacheAge: "current", platform: "linux" },
534 { cacheAge: "pre-upgrade", platform: "linux" },
535 { cacheAge: "pre-upgrade", platform: "darwin" },
536 ] as const)(
537 "lets a later fallback answer replace a $cacheAge $platform cache that only a fallback wrote",
538 ({ cacheAge, platform }) =>
539 Effect.gen(function* () {
540 const fs = yield* FileSystem.FileSystem;
541 const stateDir = yield* fs.makeTempDirectoryScoped();
542 const cachePath = `${stateDir}/shell-environment-cache.json`;
543 const fallbackShell = platform === "darwin" ? "/bin/zsh" : "/bin/bash";
544 const launch = (fallbackPath: string) => {
545 const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
546 return runShellEnvironment({
547 env,
548 stateDir,
549 platform,
550 handler: (command) =>
551 command._tag === "StandardCommand" && command.command === fallbackShell
552 ? envOutput({ PATH: fallbackPath })
553 : { output: "", exitCode: 7 },
554 }).pipe(Effect.as(env), Effect.provide(Logger.layer([])));
555 };
556 const cachedPath = fs.readFileString(cachePath).pipe(
557 Effect.flatMap(decodeCache),
558 Effect.map((cache) => cache.environment.PATH),
559 );
560
561 if (cacheAge === "pre-upgrade") {
562 // Older releases wrote no provenance marker, even when only the fallback shell answered.
563 yield* fs.writeFileString(
564 cachePath,
565 encodeCache({
566 version: 1,
567 key: `["${platform}","/test-home","/usr/bin/fish",""]`,
568 environment: { PATH: "/fallback/bin:/usr/bin", DO_NOT_TRACK: "1" },
569 }),
570 );
571 } else {
572 yield* launch("/fallback/bin");
573 }
574 assert.equal(yield* cachedPath, "/fallback/bin:/usr/bin");
575 const env = yield* launch("/fallback2/bin");
576 assert.equal(env.PATH, "/fallback2/bin:/usr/bin");
577 assert.equal(env.DO_NOT_TRACK, cacheAge === "pre-upgrade" ? "1" : undefined);
578 assert.equal(yield* cachedPath, "/fallback2/bin:/usr/bin");
579 }).pipe(Effect.provide(NodeServices.layer)),
580 );
581
582 it.effect("cancels background discovery when the application scope closes", () =>
583 Effect.gen(function* () {
584 const started = yield* Deferred.make<void>();
585 const stopped = yield* Deferred.make<void>();
586 yield* runShellEnvironment({
587 env: { SHELL: "/bin/zsh", PATH: "/usr/bin" },
588 platform: "darwin",
589 handler: () => "",
590 processSpawner: ChildProcessSpawner.make(() =>
591 Deferred.succeed(started, undefined).pipe(
592 Effect.andThen(Effect.never),
593 Effect.ensuring(Deferred.succeed(stopped, undefined)),
594 ),
595 ),
596 use: (service) =>
597 Effect.gen(function* () {
598 yield* service.installIntoProcess;
599 yield* Deferred.await(started);
600 return true;
601 }),
602 });
603 yield* Deferred.await(stopped);
604 }),
605 );
606
607 it.effect(
608 "captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
609 () =>
610 Effect.gen(function* () {
611 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
612 Effect.provide(NodeServices.layer),
613 );
614 const executable = yield* HostProcess.ExecutablePath;
615 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", PATH: "/usr/bin" };
616 const commands: string[] = [];
617 const source = [
618 "setTimeout(() => process.exit(99), 3000).unref();",
619 "process.stderr.write(Buffer.alloc(2 * 1024 * 1024, 120), () => {",
620 `process.stdout.write(${JSON.stringify(envOutput({ PATH: "/shell-only/bin:/usr/bin" }))});`,
621 "});",
622 ].join("\n");
623
624 yield* runShellEnvironment({
625 env,
626 platform: "linux",
627 handler: () => "",
628 processSpawner: ChildProcessSpawner.make((command) => {
629 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
630 commands.push(command.command);
631 return command.command === "/test-shell"
632 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
633 : Effect.succeed(makeProcess(""));
634 }),
635 }).pipe(Effect.provide(Logger.layer([])));
636
637 assert.equal(env.PATH, "/shell-only/bin:/usr/bin");
638 assert.deepEqual(commands, ["/test-shell"]);
639 }),
640 );
641
642 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
643 Effect.gen(function* () {
644 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
645 const commands: string[] = [];
646
647 const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) =>
648 Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]);
649 const answered = yield* runShellEnvironment({
650 env,
651 platform: "linux",
652 userShell: "/usr/local/bin/fish",
653 use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)),
654 handler: (command) => {
655 if (command._tag !== "StandardCommand") return "";
656 commands.push(command.command);
657 return command.command === "/bin/failing"
658 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
659 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
660 },
661 }).pipe(Effect.provide(Logger.layer([])));
662
663 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
664 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
665 // The account's own login shell answered.
666 assert.isTrue(answered);
667
668 // Only the platform fallback answered: its PATH can miss folders the user's shell adds.
669 const fallbackOnly = yield* runShellEnvironment({
670 env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" },
671 platform: "linux",
672 use: (service) =>
673 discovery(service).pipe(
674 Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell),
675 ),
676 handler: (command) =>
677 command._tag === "StandardCommand" && command.command === "/usr/bin/fish"
678 ? { output: "", exitCode: 7 }
679 : envOutput({ PATH: "/usr/bin" }),
680 }).pipe(Effect.provide(Logger.layer([])));
681 assert.isTrue(fallbackOnly);
682 }),
683 );
684
685 it.effect("hydrates PATH, SSH_AUTH_SOCK, and DO_NOT_TRACK from the login shell on macOS", () =>
686 Effect.gen(function* () {
687 const env: NodeJS.ProcessEnv = {
688 SHELL: "/bin/zsh",
689 PATH: " /Users/test/.local/bin:/usr/bin",
690 };
691 const commands: ChildProcess.Command[] = [];
692
693 const prepared = yield* runShellEnvironment({
694 env,
695 platform: "darwin",
696 handler: (command) => {
697 commands.push(command);
698 return envOutput({
699 PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
700 SSH_AUTH_SOCK: "/tmp/secretive.sock",
701 HOMEBREW_PREFIX: "/opt/homebrew",
702 DO_NOT_TRACK: "1",
703 });
704 },
705 });
706
707 assert.equal(commands.length, 1);
708 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
709 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
710 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
711 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
712 assert.equal(env.DO_NOT_TRACK, "1");
713 assert.isTrue(prepared);
714 }),
715 );
716
717 it.effect("keeps login-shell PATH entries that contain the capture end marker", () =>
718 Effect.gen(function* () {
719 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
720
721 yield* runShellEnvironment({
722 env,
723 platform: "darwin",
724 handler: () => envOutput({ PATH: "/opt/__T3CODE_ENV_PATH_END__/bin:/usr/bin" }),
725 });
726
727 assert.equal(env.PATH, "/opt/__T3CODE_ENV_PATH_END__/bin:/usr/bin");
728 }),
729 );
730
731 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
732 Effect.gen(function* () {
733 const env: NodeJS.ProcessEnv = {
734 SHELL: "/bin/zsh",
735 PATH: "/usr/bin",
736 LANG: "en_US.UTF-8",
737 };
738
739 yield* runShellEnvironment({
740 env,
741 platform: "darwin",
742 handler: () =>
743 envOutput({
744 PATH: "/opt/homebrew/bin:/usr/bin",
745 LC_ALL: "de_DE.UTF-8",
746 }),
747 });
748
749 assert.equal(env.LANG, "en_US.UTF-8");
750 assert.equal(env.LC_ALL, undefined);
751 }),
752 );
753
754 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
755 Effect.gen(function* () {
756 const env: NodeJS.ProcessEnv = {
757 SHELL: "/bin/zsh",
758 PATH: "/usr/bin",
759 };
760
761 yield* runShellEnvironment({
762 env,
763 platform: "darwin",
764 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
765 });
766
767 assert.equal(env.LANG, undefined);
768 assert.equal(env.LC_ALL, undefined);
769 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
770 }),
771 );
772
773 it.effect("hydrates missing CA trust variables from the login shell", () =>
774 Effect.gen(function* () {
775 const env: NodeJS.ProcessEnv = {
776 SHELL: "/bin/zsh",
777 PATH: "/usr/bin",
778 SSL_CERT_DIR: "/etc/ssl/certs",
779 };
780
781 yield* runShellEnvironment({
782 env,
783 platform: "darwin",
784 handler: () =>
785 envOutput({
786 PATH: "/opt/zerobrew/bin:/usr/bin",
787 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
788 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
789 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
790 }),
791 });
792
793 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
794 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
795 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
796 }),
797 );
798
799 it.effect("hydrates a missing Azure CLI config directory from the login shell", () =>
800 Effect.gen(function* () {
801 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
802
803 yield* runShellEnvironment({
804 env,
805 platform: "darwin",
806 handler: () =>
807 envOutput({
808 PATH: "/usr/bin",
809 AZURE_CONFIG_DIR: "/Users/me/.local/share/azure",
810 }),
811 });
812
813 assert.equal(env.AZURE_CONFIG_DIR, "/Users/me/.local/share/azure");
814 }),
815 );
816
817 it.effect.each([
818 {
819 name: "hydrates both Android SDK names when neither is inherited",
820 inherited: {},
821 expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" },
822 },
823 {
824 // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell
825 // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK.
826 name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME",
827 inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" },
828 expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" },
829 },
830 ])("$name", ({ inherited, expected }) =>
831 Effect.gen(function* () {
832 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited };
833
834 yield* runShellEnvironment({
835 env,
836 platform: "darwin",
837 handler: () =>
838 envOutput({
839 PATH: "/usr/bin",
840 ANDROID_HOME: "/shell/android-home",
841 ANDROID_SDK_ROOT: "/shell/android-root",
842 }),
843 });
844
845 assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME);
846 assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT);
847 }),
848 );
849
850 it.effect("keeps mise's PATH record with the login shell PATH", () =>
851 Effect.gen(function* () {
852 const env: NodeJS.ProcessEnv = {
853 SHELL: "/bin/bash",
854 PATH: "/usr/bin",
855 };
856
857 yield* runShellEnvironment({
858 env,
859 platform: "linux",
860 handler: () =>
861 envOutput({
862 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
863 __MISE_DIFF: "mise-diff",
864 }),
865 });
866
867 assert.equal(env.__MISE_DIFF, "mise-diff");
868 }),
869 );
870
871 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
872 Effect.gen(function* () {
873 const env: NodeJS.ProcessEnv = {
874 SHELL: "/opt/homebrew/bin/nu",
875 PATH: "/usr/bin",
876 };
877 const commands: string[] = [];
878
879 const prepared = yield* runShellEnvironment({
880 env,
881 platform: "darwin",
882 handler: (command) => {
883 if (command._tag !== "StandardCommand") return "";
884 commands.push(command.command);
885 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
886 },
887 });
888
889 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
890 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
891 assert.isFalse(prepared);
892 }),
893 );
894
895 it.effect("leaves macOS preparation incomplete when no login shell returns a PATH", () =>
896 Effect.gen(function* () {
897 const prepared = yield* runShellEnvironment({
898 env: { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },
899 platform: "darwin",
900 handler: () => "",
901 });
902
903 assert.isFalse(prepared);
904 }),
905 );
906
907 it.effect("retries the user's shell when only the fallback shell answered", () =>
908 Effect.gen(function* () {
909 const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
910 const commands: string[] = [];
911 let fishReady = false;
912 yield* runShellEnvironment({
913 env,
914 platform: "linux",
915 handler: (command) => {
916 if (command._tag !== "StandardCommand") return "";
917 commands.push(command.command);
918 if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
919 return fishReady
920 ? envOutput({ PATH: "/fish/bin:/usr/bin" })
921 : { output: "", exitCode: 7 };
922 },
923 use: (service) =>
924 Effect.gen(function* () {
925 assert.isTrue(yield* service.awaitDiscovery);
926 assert.equal(env.PATH, "/usr/bin");
927 // The user's shell may still opt out of telemetry, so discovery has not settled.
928 assert.isFalse(yield* service.discoveryFinished);
929 // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
930 const published = yield* service.updates.pipe(
931 Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
932 Stream.runHead,
933 Effect.forkChild({ startImmediately: true }),
934 );
935
936 fishReady = true;
937 yield* TestClock.adjust("30 seconds");
938 assert.isTrue(Option.isSome(yield* Fiber.join(published)));
939 assert.equal(env.PATH, "/fish/bin:/usr/bin");
940 return true;
941 }),
942 }).pipe(Effect.provide(Logger.layer([])));
943 assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
944
945 // With no user shell to wait for, the fallback's answer is final.
946 commands.length = 0;
947 yield* runShellEnvironment({
948 env: { PATH: "/usr/bin" },
949 platform: "linux",
950 handler: (command) => {
951 if (command._tag === "StandardCommand") commands.push(command.command);
952 return envOutput({ PATH: "/usr/bin" });
953 },
954 use: (service) =>
955 Effect.gen(function* () {
956 assert.isTrue(yield* service.awaitDiscovery);
957 yield* TestClock.adjust("5 minutes");
958 return true;
959 }),
960 }).pipe(Effect.provide(Logger.layer([])));
961 assert.deepEqual(commands, ["/bin/bash"]);
962 }),
963 );
964
965 it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
966 Effect.gen(function* () {
967 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
968 // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
969 const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make<void>());
970 const stopped = yield* Deferred.make<ChildProcess.KillOptions>();
971 let attempts = 0;
972 yield* runShellEnvironment({
973 env,
974 platform: "darwin",
975 handler: () => "",
976 processSpawner: ChildProcessSpawner.make((command) => {
977 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
978 return Effect.succeed(makeProcess(""));
979 }
980 const attempt = attempts++;
981 const spawn = Deferred.succeed(spawned[attempt]!, undefined);
982 if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
983 if (attempt === 1) {
984 return spawn.pipe(
985 Effect.andThen(
986 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
987 Deferred.succeed(stopped, command.options),
988 ),
989 ),
990 );
991 }
992 return spawn.pipe(
993 Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
994 );
995 }),
996 use: (service) =>
997 Effect.gen(function* () {
998 assert.isFalse(yield* service.awaitDiscovery);
999 const published = yield* service.updates.pipe(
1000 Stream.drop(1),
1001 Stream.runHead,
1002 Effect.forkChild({ startImmediately: true }),
1003 );
1004
1005 yield* TestClock.adjust("30 seconds");
1006 yield* Deferred.await(spawned[1]!);
1007 // pyenv waits up to 60 s on its rehash lock before the shell continues.
1008 yield* TestClock.adjust("1 minute");
1009 assert.isFalse(yield* Deferred.isDone(stopped));
1010 yield* TestClock.adjust("1 minute");
1011 const stop = yield* Deferred.await(stopped);
1012 // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
1013 assert.equal(stop.killSignal, "SIGTERM");
1014 assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
1015
1016 yield* TestClock.adjust("30 seconds");
1017 yield* Deferred.await(spawned[2]!);
1018 yield* TestClock.adjust("20 seconds");
1019 const snapshot = yield* Fiber.join(published);
1020 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
1021 assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
1022 assert.equal(
1023 Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
1024 "/fresh/bin:/usr/bin",
1025 );
1026 return true;
1027 }),
1028 });
1029 }),
1030 );
1031
1032 it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
1033 Effect.gen(function* () {
1034 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
1035 const output = envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" });
1036 let shellProbes = 0;
1037 yield* runShellEnvironment({
1038 env,
1039 platform: "darwin",
1040 handler: () => "",
1041 processSpawner: ChildProcessSpawner.make((command) => {
1042 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
1043 return Effect.succeed(makeProcess(""));
1044 }
1045 shellProbes += 1;
1046 if (shellProbes > 1) return Effect.succeed(makeProcess(output));
1047 // A cold start: the first login shell answers, but only after 7s.
1048 const slow = Effect.sleep("7 seconds");
1049 const stdout = Stream.fromEffect(slow.pipe(Effect.as(textEncoder.encode(output))));
1050 return Effect.succeed(
1051 ChildProcessSpawner.makeHandle({
1052 pid: ChildProcessSpawner.ProcessId(125),
1053 stdout,
1054 stderr: Stream.empty,
1055 all: stdout,
1056 exitCode: slow.pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
1057 exitStatus: slow.pipe(
1058 Effect.as({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
1059 ),
1060 isRunning: Effect.succeed(true),
1061 kill: () => Effect.void,
1062 stdin: Sink.drain,
1063 getInputFd: () => Sink.drain,
1064 getOutputFd: () => Stream.empty,
1065 unref: Effect.succeed(Effect.void),
1066 }),
1067 );
1068 }),
1069 use: (service) =>
1070 Effect.gen(function* () {
1071 yield* service.installIntoProcess;
1072 yield* TestClock.adjust("10 minutes");
1073 return true;
1074 }),
1075 }).pipe(Effect.provide(Logger.layer([])));
1076
1077 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
1078 }),
1079 );
1080
1081 // The inherited PATH already holds the platform's absolute fallback dirs, so each
1082 // case only depends on whether the fixture HOME has ~/.local/bin, not on this host.
1083 it.effect.each([
1084 { platform: "linux", brewBin: "/home/linuxbrew/.linuxbrew/bin" },
1085 { platform: "darwin", brewBin: "/opt/homebrew/bin" },
1086 ] as const)(
1087 "falls back to existing CLI dirs when probes return no PATH on $platform",
1088 ({ platform, brewBin }) =>
1089 Effect.gen(function* () {
1090 const fileSystem = yield* FileSystem.FileSystem;
1091 const cases = [
1092 {
1093 localBin: true,
1094 inherited: (home: string) =>
1095 `${home}/.nvm/bin:/usr/local/bin:/usr/bin:${brewBin}:/usr/bin`,
1096 probe: "",
1097 expected: (home: string) =>
1098 `${home}/.nvm/bin:/usr/local/bin:/usr/bin:${brewBin}:${home}/.local/bin`,
1099 },
1100 {
1101 localBin: true,
1102 inherited: (home: string) => `${home}/.local/bin:/usr/local/bin:${brewBin}:/usr/bin`,
1103 probe: "",
1104 expected: (home: string) => `${home}/.local/bin:/usr/local/bin:${brewBin}:/usr/bin`,
1105 },
1106 {
1107 localBin: false,
1108 inherited: () => `/usr/local/bin:${brewBin}:/usr/bin`,
1109 probe: "",
1110 expected: () => `/usr/local/bin:${brewBin}:/usr/bin`,
1111 },
1112 {
1113 localBin: true,
1114 inherited: () => "/usr/bin",
1115 probe: envOutput({ PATH: "/opt/tools/bin:/usr/bin" }),
1116 expected: () => "/opt/tools/bin:/usr/bin",
1117 },
1118 ];
1119
1120 for (const testCase of cases) {
1121 const home = yield* fileSystem.makeTempDirectoryScoped();
1122 if (testCase.localBin) {
1123 yield* fileSystem.makeDirectory(`${home}/.local/bin`, { recursive: true });
1124 }
1125 const env: NodeJS.ProcessEnv = {
1126 HOME: home,
1127 SHELL: "/bin/zsh",
1128 PATH: testCase.inherited(home),
1129 };
1130
1131 yield* runShellEnvironment({ env, platform, handler: () => testCase.probe });
1132
1133 assert.equal(env.PATH, testCase.expected(home));
1134 }
1135 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1136 );
1137
1138 it.effect("loads PowerShell profile environment on Windows", () =>
1139 Effect.gen(function* () {
1140 const env: NodeJS.ProcessEnv = {
1141 PATH: "C:\\Windows\\System32",
1142 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1143 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1144 USERPROFILE: "C:\\Users\\testuser",
1145 };
1146
1147 const scripts: Array<string> = [];
1148 const prepared = yield* runShellEnvironment({
1149 env,
1150 platform: "win32",
1151 handler: (command) => {
1152 if (command._tag !== "StandardCommand") return "";
1153 scripts.push(String(command.args.at(-1)));
1154 const loadProfile = !command.args.includes("-NoProfile");
1155 return loadProfile
1156 ? envOutput({
1157 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
1158 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1159 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1160 })
1161 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
1162 },
1163 });
1164
1165 assert.isTrue(prepared);
1166 assert.equal(
1167 env.PATH,
1168 [
1169 "C:\\Profile\\Node",
1170 "C:\\Windows\\System32",
1171 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1172 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1173 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1174 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1175 "C:\\Users\\testuser\\.local\\bin",
1176 "C:\\Users\\testuser\\.bun\\bin",
1177 "C:\\Users\\testuser\\scoop\\shims",
1178 "C:\\Custom\\Bin",
1179 "C:",
1180 ].join(";"),
1181 );
1182 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
1183 assert.equal(
1184 env.FNM_MULTISHELL_PATH,
1185 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1186 );
1187 assert.isNotEmpty(scripts);
1188 for (const script of scripts) {
1189 assert.include(
1190 script,
1191 "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
1192 );
1193 }
1194 }),
1195 );
1196
1197 it.effect.each([false, true])(
1198 "leaves Windows preparation incomplete when loadProfile=%s fails",
1199 (loadProfile) =>
1200 Effect.gen(function* () {
1201 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
1202 let calls = 0;
1203 const prepared = yield* runShellEnvironment({
1204 env,
1205 platform: "win32",
1206 handler: (command) => {
1207 calls++;
1208 if (command._tag !== "StandardCommand") return "";
1209 return !command.args.includes("-NoProfile") === loadProfile
1210 ? { output: "", exitCode: 1 }
1211 : envOutput({ PATH: "C:\\Working" });
1212 },
1213 }).pipe(Effect.provide(Logger.layer([])));
1214 assert.isFalse(prepared);
1215 assert.equal(calls, 3);
1216 assert.include(env.PATH, "C:\\Working");
1217 assert.include(env.PATH, "C:\\Windows\\System32");
1218 }),
1219 );
1220
1221 it.effect("asks pwsh again when it timed out and only Windows PowerShell answered", () =>
1222 Effect.gen(function* () {
1223 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" };
1224 let pwshProbes = 0;
1225 yield* runShellEnvironment({
1226 env,
1227 platform: "win32",
1228 handler: () => "",
1229 processSpawner: ChildProcessSpawner.make((command) => {
1230 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
1231 if (command.command === "powershell.exe") {
1232 return Effect.succeed(makeProcess(envOutput({ PATH: "C:\\mise\\shims;C:\\Windows" })));
1233 }
1234 pwshProbes += 1;
1235 // Right after sign-in, both startup pwsh probes outlast the 5 s timeout.
1236 if (pwshProbes <= 2) return Effect.succeed(makeSlowProcess("", "1 hour"));
1237 return Effect.succeed(
1238 makeProcess(envOutput({ PATH: "C:\\mise\\installs\\node\\bin;C:\\Windows" })),
1239 );
1240 }),
1241 use: (service) =>
1242 Effect.gen(function* () {
1243 yield* service.installIntoProcess;
1244 yield* TestClock.adjust("10 minutes");
1245 return true;
1246 }),
1247 }).pipe(Effect.provide(Logger.layer([])));
1248
1249 assert.isAbove(pwshProbes, 2);
1250 assert.include(env.PATH, "C:\\mise\\installs\\node\\bin");
1251 }),
1252 );
1253
1254 it.effect.each(["timeout", "nonzero exit"] as const)(
1255 "recovers the PowerShell 7 profile PATH after a startup %s",
1256 (failure) =>
1257 Effect.gen(function* () {
1258 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" };
1259 let pwshProbes = 0;
1260 let failedProfile = false;
1261 yield* runShellEnvironment({
1262 env,
1263 platform: "win32",
1264 handler: () => "",
1265 processSpawner: ChildProcessSpawner.make((command) => {
1266 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
1267 if (command.command === "powershell.exe") {
1268 return Effect.succeed(
1269 makeProcess(envOutput({ PATH: "C:\\mise\\shims;C:\\Windows" })),
1270 );
1271 }
1272 if (failure === "nonzero exit") {
1273 if (command.args.includes("-NoProfile")) {
1274 return Effect.succeed(makeProcess(envOutput({ PATH: "C:\\Windows" })));
1275 }
1276 if (!failedProfile) {
1277 failedProfile = true;
1278 return Effect.succeed(makeProcess("", 7));
1279 }
1280 }
1281 pwshProbes += 1;
1282 // Both startup probes and their slow retries outlast their timeouts.
1283 if (failure === "timeout" && pwshProbes <= 4)
1284 return Effect.succeed(makeSlowProcess("", "1 hour"));
1285 return Effect.succeed(
1286 makeProcess(envOutput({ PATH: "C:\\mise\\installs\\node\\bin;C:\\Windows" })),
1287 );
1288 }),
1289 use: (service) =>
1290 Effect.gen(function* () {
1291 yield* service.installIntoProcess;
1292 if (failure === "timeout") {
1293 yield* TestClock.adjust("25 seconds");
1294 assert.isFalse(yield* service.awaitUserShellDiscovery);
1295 }
1296 // Windows PowerShell's PATH serves until PowerShell 7 answers.
1297 assert.isTrue(yield* service.awaitDiscovery);
1298 assert.include(env.PATH, "C:\\mise\\shims");
1299 assert.notInclude(env.PATH, "C:\\mise\\installs\\node\\bin");
1300 yield* TestClock.adjust("10 minutes");
1301 return true;
1302 }),
1303 }).pipe(Effect.provide(Logger.layer([])));
1304
1305 assert.include(env.PATH, "C:\\mise\\installs\\node\\bin");
1306 }),
1307 );
1308
1309 it.effect("gives up on a Windows shell that survives the kill", () =>
1310 Effect.gen(function* () {
1311 const commands: Array<string> = [];
1312 // Both PowerShell probes spawn pwsh, time out, wait once longer for pwsh, then spawn
1313 // powershell. Each probe's timeout is armed before its spawn runs, so waiting for the spawns
1314 // keeps the clock in step.
1315 const spawned = yield* Effect.forEach([0, 1, 2, 3, 4, 5], () => Deferred.make<void>());
1316 const fiber = yield* runShellEnvironment({
1317 env: { PATH: "C:\\Windows", APPDATA: "C:\\Roaming" },
1318 platform: "win32",
1319 handler: () => "",
1320 processSpawner: ChildProcessSpawner.make((command) => {
1321 const spawn = spawned[commands.length];
1322 commands.push(command._tag === "StandardCommand" ? command.command : "");
1323 return (spawn ? Deferred.succeed(spawn, undefined) : Effect.void).pipe(
1324 Effect.andThen(
1325 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => Effect.never),
1326 ),
1327 );
1328 }),
1329 }).pipe(Effect.forkChild({ startImmediately: true }));
1330
1331 yield* Effect.forEach(spawned.slice(0, 2), Deferred.await);
1332 yield* TestClock.adjust("5 seconds");
1333 yield* Effect.forEach(spawned.slice(2, 4), Deferred.await);
1334 yield* TestClock.adjust("20 seconds");
1335 yield* Effect.forEach(spawned.slice(4), Deferred.await);
1336 yield* TestClock.adjust("5 seconds");
1337 yield* Fiber.join(fiber);
1338 assert.deepEqual([...new Set(commands)], ["pwsh.exe", "powershell.exe"]);
1339 }),
1340 );
1341
1342 it.effect("applies saved Windows user telemetry opt-outs missing from the launcher", () =>
1343 Effect.gen(function* () {
1344 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
1345
1346 yield* runShellEnvironment({
1347 env,
1348 platform: "win32",
1349 handler: (command) =>
1350 command._tag === "StandardCommand" &&
1351 String(command.args.at(-1)).includes("T3CODE_TELEMETRY_ENABLED")
1352 ? envOutput({
1353 PATH: "C:\\Windows\\System32",
1354 T3CODE_TELEMETRY_ENABLED: "false",
1355 DO_NOT_TRACK: "1",
1356 })
1357 : envOutput({ PATH: "C:\\Windows\\System32" }),
1358 });
1359
1360 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
1361 assert.equal(env.DO_NOT_TRACK, "1");
1362 }),
1363 );
1364
1365 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
1366 Effect.gen(function* () {
1367 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
1368
1369 yield* runShellEnvironment({
1370 env,
1371 platform: "win32",
1372 handler: (command) =>
1373 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
1374 ? envOutput({ PATH: "C:\\Shell\\Bin" })
1375 : "",
1376 });
1377
1378 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
1379 }),
1380 );
1381
1382 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
1383 Effect.gen(function* () {
1384 const env: NodeJS.ProcessEnv = {
1385 SHELL: "/bin/zsh",
1386 PATH: "/usr/bin",
1387 XDG_CURRENT_DESKTOP: "wrong-launcher",
1388 XDG_SESSION_DESKTOP: "wrong-launcher",
1389 };
1390
1391 yield* runShellEnvironment({
1392 env,
1393 platform: "linux",
1394 handler: () =>
1395 envOutput({
1396 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
1397 XDG_CURRENT_DESKTOP: "KDE",
1398 XDG_SESSION_DESKTOP: "KDE",
1399 XDG_SESSION_TYPE: "wayland",
1400 }),
1401 });
1402
1403 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
1404 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
1405 assert.equal(env.XDG_SESSION_TYPE, "wayland");
1406 }),
1407 );
1408});