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 }),
35);
36const encodeCache = Schema.encodeSync(cacheCodec);
37const decodeCache = Schema.decodeUnknownEffect(cacheCodec);
38
39function envOutput(values: Readonly<Record<string, string>>): string {
40 return Object.entries(values)
41 .flatMap(([name, value]) => [
42 `__T3CODE_ENV_${name}_START__`,
43 value,
44 `__T3CODE_ENV_${name}_END__`,
45 ])
46 .join("\n");
47}
48
49function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildProcessHandle {
50 const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
51 return ChildProcessSpawner.makeHandle({
52 pid: ChildProcessSpawner.ProcessId(123),
53 stdout,
54 stderr: Stream.empty,
55 all: stdout,
56 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
57 isRunning: Effect.succeed(false),
58 kill: () => Effect.void,
59 stdin: Sink.drain,
60 getInputFd: () => Sink.drain,
61 getOutputFd: () => Stream.empty,
62 unref: Effect.succeed(Effect.void),
63 });
64}
65
66function makeSlowProcess(
67 output: string,
68 delay: Duration.Input,
69): ChildProcessSpawner.ChildProcessHandle {
70 const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output)));
71 return ChildProcessSpawner.makeHandle({
72 pid: ChildProcessSpawner.ProcessId(125),
73 stdout,
74 stderr: Stream.empty,
75 all: stdout,
76 exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)),
77 isRunning: Effect.succeed(true),
78 kill: () => Effect.void,
79 stdin: Sink.drain,
80 getInputFd: () => Sink.drain,
81 getOutputFd: () => Stream.empty,
82 unref: Effect.succeed(Effect.void),
83 });
84}
85
86function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
87 return ChildProcessSpawner.makeHandle({
88 pid: ChildProcessSpawner.ProcessId(124),
89 stdout: Stream.never,
90 stderr: Stream.never,
91 all: Stream.never,
92 exitCode: Effect.never,
93 isRunning: Effect.succeed(true),
94 kill: () => Effect.never,
95 stdin: Sink.drain,
96 getInputFd: () => Sink.drain,
97 getOutputFd: () => Stream.empty,
98 unref: Effect.succeed(Effect.void),
99 });
100}
101
102function withProcessEnv<A, E, R>(
103 env: NodeJS.ProcessEnv,
104 effect: Effect.Effect<A, E, R>,
105): Effect.Effect<A, E, R> {
106 return Effect.acquireUseRelease(
107 Effect.sync(() => {
108 const previous = process.env;
109 process.env = env;
110 return previous;
111 }),
112 () => effect,
113 (previous) =>
114 Effect.sync(() => {
115 process.env = previous;
116 }),
117 );
118}
119
120function runShellEnvironment(input: {
121 readonly env: NodeJS.ProcessEnv;
122 readonly platform: NodeJS.Platform;
123 readonly userShell?: string;
124 readonly stateDir?: string;
125 readonly use?: (
126 service: DesktopShellEnvironment.DesktopShellEnvironment["Service"],
127 ) => Effect.Effect<boolean, never, import("effect/Scope").Scope>;
128 readonly handler: (
129 command: ChildProcess.Command,
130 ) => string | { output: string; exitCode: number };
131 readonly failure?: PlatformError.PlatformError;
132 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
133}) {
134 const layerEnvironment = Layer.effect(
135 DesktopEnvironment.DesktopEnvironment,
136 Effect.gen(function* () {
137 const fs = yield* FileSystem.FileSystem;
138 const stateDir = input.stateDir ?? (yield* fs.makeTempDirectoryScoped());
139 return DesktopEnvironment.DesktopEnvironment.of({
140 platform: input.platform,
141 stateDir,
142 homeDirectory: "/test-home",
143 } as DesktopEnvironment.DesktopEnvironment["Service"]);
144 }),
145 ).pipe(Layer.provide(NodeServices.layer));
146 const layerSpawner = Layer.succeed(
147 ChildProcessSpawner.ChildProcessSpawner,
148 ChildProcessSpawner.make((command) => {
149 if (input.processSpawner) return input.processSpawner.spawn(command);
150 if (input.failure !== undefined) return Effect.fail(input.failure);
151 const result = input.handler(command);
152 return Effect.succeed(
153 typeof result === "string"
154 ? makeProcess(result)
155 : makeProcess(result.output, result.exitCode),
156 );
157 }),
158 );
159
160 const program = Effect.gen(function* () {
161 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
162 if (input.use) return yield* input.use(shellEnvironment);
163 const prepared = yield* shellEnvironment.awaitDiscovery;
164 assert.equal(yield* shellEnvironment.awaitDiscovery, prepared);
165 return prepared;
166 }).pipe(
167 Effect.provide(
168 DesktopShellEnvironment.layer.pipe(
169 Layer.provide(Layer.mergeAll(layerEnvironment, NodeServices.layer, layerSpawner)),
170 ),
171 ),
172 );
173
174 return Effect.acquireUseRelease(
175 Effect.sync(() =>
176 vi.spyOn(NodeOS, "userInfo").mockReturnValue({
177 ...NodeOS.userInfo(),
178 shell: input.userShell ?? null,
179 }),
180 ),
181 () => withProcessEnv(input.env, program),
182 (spy) => Effect.sync(() => spy.mockRestore()),
183 );
184}
185
186describe("DesktopShellEnvironment", () => {
187 it.effect("does not wait for discovery when the cache is missing", () =>
188 Effect.gen(function* () {
189 const started = yield* Deferred.make<void>();
190 const release = yield* Deferred.make<void>();
191 yield* runShellEnvironment({
192 env: { SHELL: "/test-shell", PATH: "/usr/bin" },
193 platform: "darwin",
194 handler: () => "",
195 processSpawner: ChildProcessSpawner.make(() =>
196 Deferred.succeed(started, undefined).pipe(
197 Effect.andThen(Deferred.await(release)),
198 Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
199 ),
200 ),
201 use: (service) =>
202 Effect.gen(function* () {
203 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
204 yield* Deferred.await(started);
205 assert.isDefined(startup.pollUnsafe());
206 yield* Deferred.succeed(release, undefined);
207 return yield* service.awaitDiscovery;
208 }),
209 });
210 }),
211 );
212
213 it.effect(
214 "reuses cached paths immediately and streams fresh discovery without keeping removed paths",
215 () =>
216 Effect.gen(function* () {
217 const fs = yield* FileSystem.FileSystem;
218 const stateDir = yield* fs.makeTempDirectoryScoped();
219 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
220 Effect.provide(NodeServices.layer),
221 );
222 const executable = yield* HostProcess.ExecutablePath;
223 const first = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
224 yield* runShellEnvironment({
225 env: first,
226 stateDir,
227 platform: "darwin",
228 handler: () =>
229 envOutput({
230 PATH: "/old/bin:/usr/bin",
231 __MISE_DIFF: "old-mise",
232 SSH_AUTH_SOCK: "/old-session.sock",
233 JAVA_HOME: "/old/java",
234 SSL_CERT_FILE: "/old/cert.pem",
235 }),
236 });
237 const cachePath = `${stateDir}/shell-environment-cache.json`;
238 const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
239 assert.equal(cached.environment.PATH, "/old/bin:/usr/bin");
240 assert.notProperty(cached.environment, "SSH_AUTH_SOCK");
241 const started = yield* Deferred.make<void>();
242 const release = yield* Deferred.make<void>();
243 const env: NodeJS.ProcessEnv = {
244 SHELL: "/bin/zsh",
245 PATH: "/launcher/bin",
246 SSH_AUTH_SOCK: "/current-session.sock",
247 };
248 const source = [
249 "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 };",
250 "for (const [name, value] of Object.entries(values)) {",
251 " if (value !== undefined) process.stdout.write('__T3CODE_ENV_' + name + '_START__\\n' + value + '\\n__T3CODE_ENV_' + name + '_END__\\n');",
252 "}",
253 ].join("\n");
254 let calls = 0;
255 yield* runShellEnvironment({
256 env,
257 stateDir,
258 platform: "darwin",
259 handler: () => "",
260 processSpawner: ChildProcessSpawner.make((command) => {
261 calls++;
262 return Deferred.succeed(started, undefined).pipe(
263 Effect.andThen(Deferred.await(release)),
264 Effect.andThen(
265 command._tag === "StandardCommand"
266 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
267 : Effect.succeed(makeProcess("")),
268 ),
269 );
270 }),
271 use: (service) =>
272 Effect.gen(function* () {
273 yield* service.installIntoProcess;
274 yield* service.installIntoProcess;
275 assert.equal(env.PATH, "/old/bin:/usr/bin:/launcher/bin");
276 assert.equal(env.SSH_AUTH_SOCK, "/current-session.sock");
277 const replay = yield* Stream.runHead(service.updates);
278 assert.isTrue(Option.isSome(replay));
279 if (Option.isSome(replay))
280 assert.equal(replay.value.environment.__MISE_DIFF, "old-mise");
281 yield* Deferred.await(started);
282 assert.equal(calls, 1);
283 yield* Deferred.succeed(release, undefined);
284 yield* service.awaitDiscovery;
285 assert.equal(env.PATH, "/fresh/bin:/launcher/bin");
286 assert.equal(env.__MISE_DIFF, "fresh-mise");
287 assert.isUndefined(env.JAVA_HOME);
288 assert.isUndefined(env.SSL_CERT_FILE);
289 const fresh = yield* Stream.runHead(service.updates);
290 assert.isTrue(Option.isSome(fresh));
291 if (Option.isSome(fresh)) {
292 assert.equal(fresh.value.environment.PATH, env.PATH);
293 assert.isTrue(fresh.value.discovered);
294 }
295 return true;
296 }),
297 });
298 const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
299 assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin");
300 assert.notProperty(refreshed.environment, "JAVA_HOME");
301 assert.notProperty(refreshed.environment, "SSL_CERT_FILE");
302 }).pipe(Effect.provide(NodeServices.layer)),
303 );
304
305 it.effect.each([
306 "not json",
307 '{"version":2,"key":"old","environment":{"PATH":"/bad/bin"}}',
308 '{"version":1,"key":"other-shell","environment":{"PATH":"/bad/bin"}}',
309 ])("ignores an unusable cache and still starts before discovery: %s", (contents) =>
310 Effect.gen(function* () {
311 const fs = yield* FileSystem.FileSystem;
312 const stateDir = yield* fs.makeTempDirectoryScoped();
313 yield* fs.writeFileString(`${stateDir}/shell-environment-cache.json`, contents);
314 const started = yield* Deferred.make<void>();
315 const release = yield* Deferred.make<void>();
316 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
317 yield* runShellEnvironment({
318 env,
319 stateDir,
320 platform: "darwin",
321 handler: () => "",
322 processSpawner: ChildProcessSpawner.make(() =>
323 Deferred.succeed(started, undefined).pipe(
324 Effect.andThen(Deferred.await(release)),
325 Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
326 ),
327 ),
328 use: (service) =>
329 Effect.gen(function* () {
330 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
331 yield* Deferred.await(started);
332 assert.isDefined(startup.pollUnsafe());
333 assert.equal(env.PATH, "/usr/bin");
334 yield* Deferred.succeed(release, undefined);
335 return yield* service.awaitDiscovery;
336 }),
337 });
338 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
339 }).pipe(Effect.provide(NodeServices.layer)),
340 );
341
342 it.effect(
343 "retains the last successful cache on refresh failure and ignores session values in the cache",
344 () =>
345 Effect.gen(function* () {
346 const fs = yield* FileSystem.FileSystem;
347 const stateDir = yield* fs.makeTempDirectoryScoped();
348 const contents = encodeCache({
349 version: 1,
350 key: '["darwin","/test-home","/bin/zsh",""]',
351 environment: {
352 PATH: "/cached/bin",
353 __MISE_DIFF: "cached-mise",
354 JAVA_HOME: "/cached/java",
355 NODE_EXTRA_CA_CERTS: "/cached/ca.pem",
356 SSL_CERT_FILE: "/cached/cert.pem",
357 SSL_CERT_DIR: "/cached/certs",
358 SSH_AUTH_SOCK: "/stale.sock",
359 NODE_OPTIONS: "--bad",
360 },
361 });
362 const cachePath = `${stateDir}/shell-environment-cache.json`;
363 yield* fs.writeFileString(cachePath, contents);
364 const env: NodeJS.ProcessEnv = {
365 SHELL: "/bin/zsh",
366 PATH: "/usr/bin",
367 __MISE_DIFF: "launcher-mise",
368 JAVA_HOME: "/launcher/java",
369 NODE_EXTRA_CA_CERTS: "/launcher/ca.pem",
370 SSL_CERT_FILE: "",
371 SSH_AUTH_SOCK: "/current.sock",
372 };
373 const prepared = yield* runShellEnvironment({
374 env,
375 stateDir,
376 platform: "darwin",
377 handler: () => "",
378 use: (service) =>
379 Effect.gen(function* () {
380 yield* service.installIntoProcess;
381 const replay = yield* Stream.runHead(service.updates);
382 assert.isTrue(Option.isSome(replay));
383 if (Option.isSome(replay)) {
384 assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java");
385 assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
386 }
387 return yield* service.awaitDiscovery;
388 }),
389 });
390 assert.isFalse(prepared);
391 assert.equal(env.PATH, "/cached/bin:/usr/bin");
392 assert.equal(env.__MISE_DIFF, "cached-mise");
393 assert.equal(env.JAVA_HOME, "/launcher/java");
394 assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
395 assert.equal(env.SSL_CERT_FILE, "");
396 assert.equal(env.SSL_CERT_DIR, "/cached/certs");
397 assert.equal(env.SSH_AUTH_SOCK, "/current.sock");
398 assert.isUndefined(env.NODE_OPTIONS);
399 assert.equal(yield* fs.readFileString(cachePath), contents);
400 }).pipe(Effect.provide(NodeServices.layer)),
401 );
402
403 it.effect("cancels background discovery when the application scope closes", () =>
404 Effect.gen(function* () {
405 const started = yield* Deferred.make<void>();
406 const stopped = yield* Deferred.make<void>();
407 yield* runShellEnvironment({
408 env: { SHELL: "/bin/zsh", PATH: "/usr/bin" },
409 platform: "darwin",
410 handler: () => "",
411 processSpawner: ChildProcessSpawner.make(() =>
412 Deferred.succeed(started, undefined).pipe(
413 Effect.andThen(Effect.never),
414 Effect.ensuring(Deferred.succeed(stopped, undefined)),
415 ),
416 ),
417 use: (service) =>
418 Effect.gen(function* () {
419 yield* service.installIntoProcess;
420 yield* Deferred.await(started);
421 return true;
422 }),
423 });
424 yield* Deferred.await(stopped);
425 }),
426 );
427
428 it.effect(
429 "captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
430 () =>
431 Effect.gen(function* () {
432 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
433 Effect.provide(NodeServices.layer),
434 );
435 const executable = yield* HostProcess.ExecutablePath;
436 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", PATH: "/usr/bin" };
437 const commands: string[] = [];
438 const source = [
439 "setTimeout(() => process.exit(99), 3000).unref();",
440 "process.stderr.write(Buffer.alloc(2 * 1024 * 1024, 120), () => {",
441 `process.stdout.write(${JSON.stringify(envOutput({ PATH: "/shell-only/bin:/usr/bin" }))});`,
442 "});",
443 ].join("\n");
444
445 yield* runShellEnvironment({
446 env,
447 platform: "linux",
448 handler: () => "",
449 processSpawner: ChildProcessSpawner.make((command) => {
450 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
451 commands.push(command.command);
452 return command.command === "/test-shell"
453 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
454 : Effect.succeed(makeProcess(""));
455 }),
456 }).pipe(Effect.provide(Logger.layer([])));
457
458 assert.equal(env.PATH, "/shell-only/bin:/usr/bin");
459 assert.deepEqual(commands, ["/test-shell"]);
460 }),
461 );
462
463 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
464 Effect.gen(function* () {
465 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
466 const commands: string[] = [];
467
468 const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) =>
469 Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]);
470 const answered = yield* runShellEnvironment({
471 env,
472 platform: "linux",
473 userShell: "/usr/local/bin/fish",
474 use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)),
475 handler: (command) => {
476 if (command._tag !== "StandardCommand") return "";
477 commands.push(command.command);
478 return command.command === "/bin/failing"
479 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
480 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
481 },
482 }).pipe(Effect.provide(Logger.layer([])));
483
484 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
485 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
486 // The account's own login shell answered.
487 assert.isTrue(answered);
488
489 // Only the platform fallback answered: its PATH can miss folders the user's shell adds.
490 const fallbackOnly = yield* runShellEnvironment({
491 env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" },
492 platform: "linux",
493 use: (service) =>
494 discovery(service).pipe(
495 Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell),
496 ),
497 handler: (command) =>
498 command._tag === "StandardCommand" && command.command === "/usr/bin/fish"
499 ? { output: "", exitCode: 7 }
500 : envOutput({ PATH: "/usr/bin" }),
501 }).pipe(Effect.provide(Logger.layer([])));
502 assert.isTrue(fallbackOnly);
503 }),
504 );
505
506 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
507 Effect.gen(function* () {
508 const env: NodeJS.ProcessEnv = {
509 SHELL: "/bin/zsh",
510 PATH: " /Users/test/.local/bin:/usr/bin",
511 };
512 const commands: ChildProcess.Command[] = [];
513
514 const prepared = yield* runShellEnvironment({
515 env,
516 platform: "darwin",
517 handler: (command) => {
518 commands.push(command);
519 return envOutput({
520 PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
521 SSH_AUTH_SOCK: "/tmp/secretive.sock",
522 HOMEBREW_PREFIX: "/opt/homebrew",
523 });
524 },
525 });
526
527 assert.equal(commands.length, 1);
528 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
529 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
530 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
531 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
532 assert.isTrue(prepared);
533 }),
534 );
535
536 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
537 Effect.gen(function* () {
538 const env: NodeJS.ProcessEnv = {
539 SHELL: "/bin/zsh",
540 PATH: "/usr/bin",
541 LANG: "en_US.UTF-8",
542 };
543
544 yield* runShellEnvironment({
545 env,
546 platform: "darwin",
547 handler: () =>
548 envOutput({
549 PATH: "/opt/homebrew/bin:/usr/bin",
550 LC_ALL: "de_DE.UTF-8",
551 }),
552 });
553
554 assert.equal(env.LANG, "en_US.UTF-8");
555 assert.equal(env.LC_ALL, undefined);
556 }),
557 );
558
559 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
560 Effect.gen(function* () {
561 const env: NodeJS.ProcessEnv = {
562 SHELL: "/bin/zsh",
563 PATH: "/usr/bin",
564 };
565
566 yield* runShellEnvironment({
567 env,
568 platform: "darwin",
569 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
570 });
571
572 assert.equal(env.LANG, undefined);
573 assert.equal(env.LC_ALL, undefined);
574 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
575 }),
576 );
577
578 it.effect("hydrates missing CA trust variables from the login shell", () =>
579 Effect.gen(function* () {
580 const env: NodeJS.ProcessEnv = {
581 SHELL: "/bin/zsh",
582 PATH: "/usr/bin",
583 SSL_CERT_DIR: "/etc/ssl/certs",
584 };
585
586 yield* runShellEnvironment({
587 env,
588 platform: "darwin",
589 handler: () =>
590 envOutput({
591 PATH: "/opt/zerobrew/bin:/usr/bin",
592 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
593 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
594 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
595 }),
596 });
597
598 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
599 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
600 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
601 }),
602 );
603
604 it.effect.each([
605 {
606 name: "hydrates both Android SDK names when neither is inherited",
607 inherited: {},
608 expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" },
609 },
610 {
611 // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell
612 // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK.
613 name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME",
614 inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" },
615 expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" },
616 },
617 ])("$name", ({ inherited, expected }) =>
618 Effect.gen(function* () {
619 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited };
620
621 yield* runShellEnvironment({
622 env,
623 platform: "darwin",
624 handler: () =>
625 envOutput({
626 PATH: "/usr/bin",
627 ANDROID_HOME: "/shell/android-home",
628 ANDROID_SDK_ROOT: "/shell/android-root",
629 }),
630 });
631
632 assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME);
633 assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT);
634 }),
635 );
636
637 it.effect("keeps mise's PATH record with the login shell PATH", () =>
638 Effect.gen(function* () {
639 const env: NodeJS.ProcessEnv = {
640 SHELL: "/bin/bash",
641 PATH: "/usr/bin",
642 };
643
644 yield* runShellEnvironment({
645 env,
646 platform: "linux",
647 handler: () =>
648 envOutput({
649 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
650 __MISE_DIFF: "mise-diff",
651 }),
652 });
653
654 assert.equal(env.__MISE_DIFF, "mise-diff");
655 }),
656 );
657
658 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
659 Effect.gen(function* () {
660 const env: NodeJS.ProcessEnv = {
661 SHELL: "/opt/homebrew/bin/nu",
662 PATH: "/usr/bin",
663 };
664 const commands: string[] = [];
665
666 const prepared = yield* runShellEnvironment({
667 env,
668 platform: "darwin",
669 handler: (command) => {
670 if (command._tag !== "StandardCommand") return "";
671 commands.push(command.command);
672 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
673 },
674 });
675
676 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
677 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
678 assert.isFalse(prepared);
679 }),
680 );
681
682 it.effect("leaves macOS preparation incomplete when no login shell returns a PATH", () =>
683 Effect.gen(function* () {
684 const prepared = yield* runShellEnvironment({
685 env: { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },
686 platform: "darwin",
687 handler: () => "",
688 });
689
690 assert.isFalse(prepared);
691 }),
692 );
693
694 it.effect("retries the user's shell when only the fallback shell answered", () =>
695 Effect.gen(function* () {
696 const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
697 const commands: string[] = [];
698 let fishReady = false;
699 yield* runShellEnvironment({
700 env,
701 platform: "linux",
702 handler: (command) => {
703 if (command._tag !== "StandardCommand") return "";
704 commands.push(command.command);
705 if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
706 return fishReady
707 ? envOutput({ PATH: "/fish/bin:/usr/bin" })
708 : { output: "", exitCode: 7 };
709 },
710 use: (service) =>
711 Effect.gen(function* () {
712 assert.isTrue(yield* service.awaitDiscovery);
713 assert.equal(env.PATH, "/usr/bin");
714 // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
715 const published = yield* service.updates.pipe(
716 Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
717 Stream.runHead,
718 Effect.forkChild({ startImmediately: true }),
719 );
720
721 fishReady = true;
722 yield* TestClock.adjust("30 seconds");
723 assert.isTrue(Option.isSome(yield* Fiber.join(published)));
724 assert.equal(env.PATH, "/fish/bin:/usr/bin");
725 return true;
726 }),
727 }).pipe(Effect.provide(Logger.layer([])));
728 assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
729
730 // With no user shell to wait for, the fallback's answer is final.
731 commands.length = 0;
732 yield* runShellEnvironment({
733 env: { PATH: "/usr/bin" },
734 platform: "linux",
735 handler: (command) => {
736 if (command._tag === "StandardCommand") commands.push(command.command);
737 return envOutput({ PATH: "/usr/bin" });
738 },
739 use: (service) =>
740 Effect.gen(function* () {
741 assert.isTrue(yield* service.awaitDiscovery);
742 yield* TestClock.adjust("5 minutes");
743 return true;
744 }),
745 }).pipe(Effect.provide(Logger.layer([])));
746 assert.deepEqual(commands, ["/bin/bash"]);
747 }),
748 );
749
750 it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
751 Effect.gen(function* () {
752 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
753 // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
754 const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make<void>());
755 const stopped = yield* Deferred.make<ChildProcess.KillOptions>();
756 let attempts = 0;
757 yield* runShellEnvironment({
758 env,
759 platform: "darwin",
760 handler: () => "",
761 processSpawner: ChildProcessSpawner.make((command) => {
762 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
763 return Effect.succeed(makeProcess(""));
764 }
765 const attempt = attempts++;
766 const spawn = Deferred.succeed(spawned[attempt]!, undefined);
767 if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
768 if (attempt === 1) {
769 return spawn.pipe(
770 Effect.andThen(
771 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
772 Deferred.succeed(stopped, command.options),
773 ),
774 ),
775 );
776 }
777 return spawn.pipe(
778 Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
779 );
780 }),
781 use: (service) =>
782 Effect.gen(function* () {
783 assert.isFalse(yield* service.awaitDiscovery);
784 const published = yield* service.updates.pipe(
785 Stream.drop(1),
786 Stream.runHead,
787 Effect.forkChild({ startImmediately: true }),
788 );
789
790 yield* TestClock.adjust("30 seconds");
791 yield* Deferred.await(spawned[1]!);
792 // pyenv waits up to 60 s on its rehash lock before the shell continues.
793 yield* TestClock.adjust("1 minute");
794 assert.isFalse(yield* Deferred.isDone(stopped));
795 yield* TestClock.adjust("1 minute");
796 const stop = yield* Deferred.await(stopped);
797 // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
798 assert.equal(stop.killSignal, "SIGTERM");
799 assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
800
801 yield* TestClock.adjust("30 seconds");
802 yield* Deferred.await(spawned[2]!);
803 yield* TestClock.adjust("20 seconds");
804 const snapshot = yield* Fiber.join(published);
805 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
806 assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
807 assert.equal(
808 Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
809 "/fresh/bin:/usr/bin",
810 );
811 return true;
812 }),
813 });
814 }),
815 );
816
817 it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
818 Effect.gen(function* () {
819 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
820 const output = envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" });
821 let shellProbes = 0;
822 yield* runShellEnvironment({
823 env,
824 platform: "darwin",
825 handler: () => "",
826 processSpawner: ChildProcessSpawner.make((command) => {
827 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
828 return Effect.succeed(makeProcess(""));
829 }
830 shellProbes += 1;
831 if (shellProbes > 1) return Effect.succeed(makeProcess(output));
832 // A cold start: the first login shell answers, but only after 7s.
833 const slow = Effect.sleep("7 seconds");
834 const stdout = Stream.fromEffect(slow.pipe(Effect.as(textEncoder.encode(output))));
835 return Effect.succeed(
836 ChildProcessSpawner.makeHandle({
837 pid: ChildProcessSpawner.ProcessId(125),
838 stdout,
839 stderr: Stream.empty,
840 all: stdout,
841 exitCode: slow.pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
842 isRunning: Effect.succeed(true),
843 kill: () => Effect.void,
844 stdin: Sink.drain,
845 getInputFd: () => Sink.drain,
846 getOutputFd: () => Stream.empty,
847 unref: Effect.succeed(Effect.void),
848 }),
849 );
850 }),
851 use: (service) =>
852 Effect.gen(function* () {
853 yield* service.installIntoProcess;
854 yield* TestClock.adjust("10 minutes");
855 return true;
856 }),
857 }).pipe(Effect.provide(Logger.layer([])));
858
859 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
860 }),
861 );
862
863 it.effect("loads PowerShell profile environment on Windows", () =>
864 Effect.gen(function* () {
865 const env: NodeJS.ProcessEnv = {
866 PATH: "C:\\Windows\\System32",
867 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
868 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
869 USERPROFILE: "C:\\Users\\testuser",
870 };
871
872 const prepared = yield* runShellEnvironment({
873 env,
874 platform: "win32",
875 handler: (command) => {
876 if (command._tag !== "StandardCommand") return "";
877 const loadProfile = !command.args.includes("-NoProfile");
878 return loadProfile
879 ? envOutput({
880 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
881 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
882 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
883 })
884 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
885 },
886 });
887
888 assert.isTrue(prepared);
889 assert.equal(
890 env.PATH,
891 [
892 "C:\\Profile\\Node",
893 "C:\\Windows\\System32",
894 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
895 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
896 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
897 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
898 "C:\\Users\\testuser\\.local\\bin",
899 "C:\\Users\\testuser\\.bun\\bin",
900 "C:\\Users\\testuser\\scoop\\shims",
901 "C:\\Custom\\Bin",
902 "C:",
903 ].join(";"),
904 );
905 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
906 assert.equal(
907 env.FNM_MULTISHELL_PATH,
908 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
909 );
910 }),
911 );
912
913 it.effect.each([false, true])(
914 "leaves Windows preparation incomplete when loadProfile=%s fails",
915 (loadProfile) =>
916 Effect.gen(function* () {
917 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
918 let calls = 0;
919 const prepared = yield* runShellEnvironment({
920 env,
921 platform: "win32",
922 handler: (command) => {
923 calls++;
924 if (command._tag !== "StandardCommand") return "";
925 return !command.args.includes("-NoProfile") === loadProfile
926 ? { output: "", exitCode: 1 }
927 : envOutput({ PATH: "C:\\Working" });
928 },
929 }).pipe(Effect.provide(Logger.layer([])));
930 assert.isFalse(prepared);
931 assert.equal(calls, 3);
932 assert.include(env.PATH, "C:\\Working");
933 assert.include(env.PATH, "C:\\Windows\\System32");
934 }),
935 );
936
937 it.effect("gives up on a Windows shell that survives the kill", () =>
938 Effect.gen(function* () {
939 const commands: Array<string> = [];
940 // Both PowerShell probes spawn pwsh, time out, then spawn powershell. Each probe's timeout
941 // is armed before its spawn runs, so waiting for the spawns keeps the clock in step.
942 const spawned = yield* Effect.forEach([0, 1, 2, 3], () => Deferred.make<void>());
943 const fiber = yield* runShellEnvironment({
944 env: { PATH: "C:\\Windows", APPDATA: "C:\\Roaming" },
945 platform: "win32",
946 handler: () => "",
947 processSpawner: ChildProcessSpawner.make((command) => {
948 const spawn = spawned[commands.length];
949 commands.push(command._tag === "StandardCommand" ? command.command : "");
950 return (spawn ? Deferred.succeed(spawn, undefined) : Effect.void).pipe(
951 Effect.andThen(
952 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => Effect.never),
953 ),
954 );
955 }),
956 }).pipe(Effect.forkChild({ startImmediately: true }));
957
958 yield* Effect.forEach(spawned.slice(0, 2), Deferred.await);
959 yield* TestClock.adjust("5 seconds");
960 yield* Effect.forEach(spawned.slice(2), Deferred.await);
961 yield* TestClock.adjust("5 seconds");
962 yield* Fiber.join(fiber);
963 assert.deepEqual([...new Set(commands)], ["pwsh.exe", "powershell.exe"]);
964 }),
965 );
966
967 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
968 Effect.gen(function* () {
969 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
970
971 yield* runShellEnvironment({
972 env,
973 platform: "win32",
974 handler: (command) =>
975 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
976 ? envOutput({ PATH: "C:\\Shell\\Bin" })
977 : "",
978 });
979
980 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
981 }),
982 );
983
984 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
985 Effect.gen(function* () {
986 const env: NodeJS.ProcessEnv = {
987 SHELL: "/bin/zsh",
988 PATH: "/usr/bin",
989 XDG_CURRENT_DESKTOP: "wrong-launcher",
990 XDG_SESSION_DESKTOP: "wrong-launcher",
991 };
992
993 yield* runShellEnvironment({
994 env,
995 platform: "linux",
996 handler: () =>
997 envOutput({
998 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
999 XDG_CURRENT_DESKTOP: "KDE",
1000 XDG_SESSION_DESKTOP: "KDE",
1001 XDG_SESSION_TYPE: "wayland",
1002 }),
1003 });
1004
1005 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
1006 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
1007 assert.equal(env.XDG_SESSION_TYPE, "wayland");
1008 }),
1009 );
1010});