Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopShellEnvironment.test.ts

1,014 lines38.1 KB

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");
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 });
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 });
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 });
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 );
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 );
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 T3CODE_TELEMETRY_ENABLED: "false",
359 SSH_AUTH_SOCK: "/stale.sock",
360 NODE_OPTIONS: "--bad",
361 },
362 });
363 const cachePath = `${stateDir}/shell-environment-cache.json`;
364 yield* fs.writeFileString(cachePath, contents);
365 const env: NodeJS.ProcessEnv = {
366 SHELL: "/bin/zsh",
367 PATH: "/usr/bin",
368 __MISE_DIFF: "launcher-mise",
369 JAVA_HOME: "/launcher/java",
370 NODE_EXTRA_CA_CERTS: "/launcher/ca.pem",
371 SSL_CERT_FILE: "",
372 SSH_AUTH_SOCK: "/current.sock",
373 };
374 const prepared = yield* runShellEnvironment({
375 env,
376 stateDir,
377 platform: "darwin",
378 handler: () => "",
379 use: (service) =>
380 Effect.gen(function* () {
381 yield* service.installIntoProcess;
382 const replay = yield* Stream.runHead(service.updates);
383 assert.isTrue(Option.isSome(replay));
384 if (Option.isSome(replay)) {
385 assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java");
386 assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
387 }
388 return yield* service.awaitDiscovery;
389 }),
390 });
391 assert.isFalse(prepared);
392 assert.equal(env.PATH, "/cached/bin:/usr/bin");
393 assert.equal(env.__MISE_DIFF, "cached-mise");
394 assert.equal(env.JAVA_HOME, "/launcher/java");
395 assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
396 assert.equal(env.SSL_CERT_FILE, "");
397 assert.equal(env.SSL_CERT_DIR, "/cached/certs");
398 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
399 assert.equal(env.SSH_AUTH_SOCK, "/current.sock");
400 assert.isUndefined(env.NODE_OPTIONS);
401 assert.equal(yield* fs.readFileString(cachePath), contents);
402 }).pipe(Effect.provide(NodeServices.layer)),
403 );
404​
405 it.effect("cancels background discovery when the application scope closes", () =>
406 Effect.gen(function* () {
407 const started = yield* Deferred.make<void>();
408 const stopped = yield* Deferred.make<void>();
409 yield* runShellEnvironment({
410 env: { SHELL: "/bin/zsh", PATH: "/usr/bin" },
411 platform: "darwin",
412 handler: () => "",
413 processSpawner: ChildProcessSpawner.make(() =>
414 Deferred.succeed(started, undefined).pipe(
415 Effect.andThen(Effect.never),
416 Effect.ensuring(Deferred.succeed(stopped, undefined)),
417 ),
418 ),
419 use: (service) =>
420 Effect.gen(function* () {
421 yield* service.installIntoProcess;
422 yield* Deferred.await(started);
423 return true;
424 }),
425 });
426 yield* Deferred.await(stopped);
427 }),
428 );
429​
430 it.effect(
431 "captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
432 () =>
433 Effect.gen(function* () {
434 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
435 Effect.provide(NodeServices.layer),
436 );
437 const executable = yield* HostProcess.ExecutablePath;
438 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", PATH: "/usr/bin" };
439 const commands: string[] = [];
440 const source = [
441 "setTimeout(() => process.exit(99), 3000).unref();",
442 "process.stderr.write(Buffer.alloc(2 * 1024 * 1024, 120), () => {",
443 `process.stdout.write(${JSON.stringify(envOutput({ PATH: "/shell-only/bin:/usr/bin" }))});`,
444 "});",
445 ].join("\n");
446​
447 yield* runShellEnvironment({
448 env,
449 platform: "linux",
450 handler: () => "",
451 processSpawner: ChildProcessSpawner.make((command) => {
452 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
453 commands.push(command.command);
454 return command.command === "/test-shell"
455 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
456 : Effect.succeed(makeProcess(""));
457 }),
458 }).pipe(Effect.provide(Logger.layer([])));
459​
460 assert.equal(env.PATH, "/shell-only/bin:/usr/bin");
461 assert.deepEqual(commands, ["/test-shell"]);
462 }),
463 );
464​
465 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
466 Effect.gen(function* () {
467 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
468 const commands: string[] = [];
469​
470 const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) =>
471 Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]);
472 const answered = yield* runShellEnvironment({
473 env,
474 platform: "linux",
475 userShell: "/usr/local/bin/fish",
476 use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)),
477 handler: (command) => {
478 if (command._tag !== "StandardCommand") return "";
479 commands.push(command.command);
480 return command.command === "/bin/failing"
481 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
482 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
483 },
484 }).pipe(Effect.provide(Logger.layer([])));
485​
486 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
487 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
488 // The account's own login shell answered.
489 assert.isTrue(answered);
490​
491 // Only the platform fallback answered: its PATH can miss folders the user's shell adds.
492 const fallbackOnly = yield* runShellEnvironment({
493 env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" },
494 platform: "linux",
495 use: (service) =>
496 discovery(service).pipe(
497 Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell),
498 ),
499 handler: (command) =>
500 command._tag === "StandardCommand" && command.command === "/usr/bin/fish"
501 ? { output: "", exitCode: 7 }
502 : envOutput({ PATH: "/usr/bin" }),
503 }).pipe(Effect.provide(Logger.layer([])));
504 assert.isTrue(fallbackOnly);
505 }),
506 );
507​
508 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
509 Effect.gen(function* () {
510 const env: NodeJS.ProcessEnv = {
511 SHELL: "/bin/zsh",
512 PATH: " /Users/test/.local/bin:/usr/bin",
513 };
514 const commands: ChildProcess.Command[] = [];
515​
516 const prepared = yield* runShellEnvironment({
517 env,
518 platform: "darwin",
519 handler: (command) => {
520 commands.push(command);
521 return envOutput({
522 PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
523 SSH_AUTH_SOCK: "/tmp/secretive.sock",
524 HOMEBREW_PREFIX: "/opt/homebrew",
525 });
526 },
527 });
528​
529 assert.equal(commands.length, 1);
530 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
531 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
532 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
533 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
534 assert.isTrue(prepared);
535 }),
536 );
537​
538 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
539 Effect.gen(function* () {
540 const env: NodeJS.ProcessEnv = {
541 SHELL: "/bin/zsh",
542 PATH: "/usr/bin",
543 LANG: "en_US.UTF-8",
544 };
545​
546 yield* runShellEnvironment({
547 env,
548 platform: "darwin",
549 handler: () =>
550 envOutput({
551 PATH: "/opt/homebrew/bin:/usr/bin",
552 LC_ALL: "de_DE.UTF-8",
553 }),
554 });
555​
556 assert.equal(env.LANG, "en_US.UTF-8");
557 assert.equal(env.LC_ALL, undefined);
558 }),
559 );
560​
561 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
562 Effect.gen(function* () {
563 const env: NodeJS.ProcessEnv = {
564 SHELL: "/bin/zsh",
565 PATH: "/usr/bin",
566 };
567​
568 yield* runShellEnvironment({
569 env,
570 platform: "darwin",
571 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
572 });
573​
574 assert.equal(env.LANG, undefined);
575 assert.equal(env.LC_ALL, undefined);
576 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
577 }),
578 );
579​
580 it.effect("hydrates missing CA trust variables from the login shell", () =>
581 Effect.gen(function* () {
582 const env: NodeJS.ProcessEnv = {
583 SHELL: "/bin/zsh",
584 PATH: "/usr/bin",
585 SSL_CERT_DIR: "/etc/ssl/certs",
586 };
587​
588 yield* runShellEnvironment({
589 env,
590 platform: "darwin",
591 handler: () =>
592 envOutput({
593 PATH: "/opt/zerobrew/bin:/usr/bin",
594 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
595 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
596 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
597 }),
598 });
599​
600 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
601 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
602 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
603 }),
604 );
605​
606 it.effect.each([
607 {
608 name: "hydrates both Android SDK names when neither is inherited",
609 inherited: {},
610 expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" },
611 },
612 {
613 // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell
614 // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK.
615 name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME",
616 inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" },
617 expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" },
618 },
619 ])("$name", ({ inherited, expected }) =>
620 Effect.gen(function* () {
621 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited };
622​
623 yield* runShellEnvironment({
624 env,
625 platform: "darwin",
626 handler: () =>
627 envOutput({
628 PATH: "/usr/bin",
629 ANDROID_HOME: "/shell/android-home",
630 ANDROID_SDK_ROOT: "/shell/android-root",
631 }),
632 });
633​
634 assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME);
635 assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT);
636 }),
637 );
638​
639 it.effect("keeps mise's PATH record with the login shell PATH", () =>
640 Effect.gen(function* () {
641 const env: NodeJS.ProcessEnv = {
642 SHELL: "/bin/bash",
643 PATH: "/usr/bin",
644 };
645​
646 yield* runShellEnvironment({
647 env,
648 platform: "linux",
649 handler: () =>
650 envOutput({
651 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
652 __MISE_DIFF: "mise-diff",
653 }),
654 });
655​
656 assert.equal(env.__MISE_DIFF, "mise-diff");
657 }),
658 );
659​
660 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
661 Effect.gen(function* () {
662 const env: NodeJS.ProcessEnv = {
663 SHELL: "/opt/homebrew/bin/nu",
664 PATH: "/usr/bin",
665 };
666 const commands: string[] = [];
667​
668 const prepared = yield* runShellEnvironment({
669 env,
670 platform: "darwin",
671 handler: (command) => {
672 if (command._tag !== "StandardCommand") return "";
673 commands.push(command.command);
674 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
675 },
676 });
677​
678 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
679 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
680 assert.isFalse(prepared);
681 }),
682 );
683​
684 it.effect("leaves macOS preparation incomplete when no login shell returns a PATH", () =>
685 Effect.gen(function* () {
686 const prepared = yield* runShellEnvironment({
687 env: { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },
688 platform: "darwin",
689 handler: () => "",
690 });
691​
692 assert.isFalse(prepared);
693 }),
694 );
695​
696 it.effect("retries the user's shell when only the fallback shell answered", () =>
697 Effect.gen(function* () {
698 const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
699 const commands: string[] = [];
700 let fishReady = false;
701 yield* runShellEnvironment({
702 env,
703 platform: "linux",
704 handler: (command) => {
705 if (command._tag !== "StandardCommand") return "";
706 commands.push(command.command);
707 if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
708 return fishReady
709 ? envOutput({ PATH: "/fish/bin:/usr/bin" })
710 : { output: "", exitCode: 7 };
711 },
712 use: (service) =>
713 Effect.gen(function* () {
714 assert.isTrue(yield* service.awaitDiscovery);
715 assert.equal(env.PATH, "/usr/bin");
716 // The user's shell may still opt out of telemetry, so discovery has not settled.
717 assert.isFalse(yield* service.discoveryFinished);
718 // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
719 const published = yield* service.updates.pipe(
720 Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
721 Stream.runHead,
722 Effect.forkChild({ startImmediately: true }),
723 );
724​
725 fishReady = true;
726 yield* TestClock.adjust("30 seconds");
727 assert.isTrue(Option.isSome(yield* Fiber.join(published)));
728 assert.equal(env.PATH, "/fish/bin:/usr/bin");
729 return true;
730 }),
731 }).pipe(Effect.provide(Logger.layer([])));
732 assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
733​
734 // With no user shell to wait for, the fallback's answer is final.
735 commands.length = 0;
736 yield* runShellEnvironment({
737 env: { PATH: "/usr/bin" },
738 platform: "linux",
739 handler: (command) => {
740 if (command._tag === "StandardCommand") commands.push(command.command);
741 return envOutput({ PATH: "/usr/bin" });
742 },
743 use: (service) =>
744 Effect.gen(function* () {
745 assert.isTrue(yield* service.awaitDiscovery);
746 yield* TestClock.adjust("5 minutes");
747 return true;
748 }),
749 }).pipe(Effect.provide(Logger.layer([])));
750 assert.deepEqual(commands, ["/bin/bash"]);
751 }),
752 );
753​
754 it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
755 Effect.gen(function* () {
756 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
757 // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
758 const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make<void>());
759 const stopped = yield* Deferred.make<ChildProcess.KillOptions>();
760 let attempts = 0;
761 yield* runShellEnvironment({
762 env,
763 platform: "darwin",
764 handler: () => "",
765 processSpawner: ChildProcessSpawner.make((command) => {
766 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
767 return Effect.succeed(makeProcess(""));
768 }
769 const attempt = attempts++;
770 const spawn = Deferred.succeed(spawned[attempt]!, undefined);
771 if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
772 if (attempt === 1) {
773 return spawn.pipe(
774 Effect.andThen(
775 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
776 Deferred.succeed(stopped, command.options),
777 ),
778 ),
779 );
780 }
781 return spawn.pipe(
782 Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
783 );
784 }),
785 use: (service) =>
786 Effect.gen(function* () {
787 assert.isFalse(yield* service.awaitDiscovery);
788 const published = yield* service.updates.pipe(
789 Stream.drop(1),
790 Stream.runHead,
791 Effect.forkChild({ startImmediately: true }),
792 );
793​
794 yield* TestClock.adjust("30 seconds");
795 yield* Deferred.await(spawned[1]!);
796 // pyenv waits up to 60 s on its rehash lock before the shell continues.
797 yield* TestClock.adjust("1 minute");
798 assert.isFalse(yield* Deferred.isDone(stopped));
799 yield* TestClock.adjust("1 minute");
800 const stop = yield* Deferred.await(stopped);
801 // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
802 assert.equal(stop.killSignal, "SIGTERM");
803 assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
804​
805 yield* TestClock.adjust("30 seconds");
806 yield* Deferred.await(spawned[2]!);
807 yield* TestClock.adjust("20 seconds");
808 const snapshot = yield* Fiber.join(published);
809 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
810 assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
811 assert.equal(
812 Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
813 "/fresh/bin:/usr/bin",
814 );
815 return true;
816 }),
817 });
818 }),
819 );
820​
821 it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
822 Effect.gen(function* () {
823 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
824 const output = envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" });
825 let shellProbes = 0;
826 yield* runShellEnvironment({
827 env,
828 platform: "darwin",
829 handler: () => "",
830 processSpawner: ChildProcessSpawner.make((command) => {
831 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
832 return Effect.succeed(makeProcess(""));
833 }
834 shellProbes += 1;
835 if (shellProbes > 1) return Effect.succeed(makeProcess(output));
836 // A cold start: the first login shell answers, but only after 7s.
837 const slow = Effect.sleep("7 seconds");
838 const stdout = Stream.fromEffect(slow.pipe(Effect.as(textEncoder.encode(output))));
839 return Effect.succeed(
840 ChildProcessSpawner.makeHandle({
841 pid: ChildProcessSpawner.ProcessId(125),
842 stdout,
843 stderr: Stream.empty,
844 all: stdout,
845 exitCode: slow.pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
846 isRunning: Effect.succeed(true),
847 kill: () => Effect.void,
848 stdin: Sink.drain,
849 getInputFd: () => Sink.drain,
850 getOutputFd: () => Stream.empty,
851 unref: Effect.succeed(Effect.void),
852 }),
853 );
854 }),
855 use: (service) =>
856 Effect.gen(function* () {
857 yield* service.installIntoProcess;
858 yield* TestClock.adjust("10 minutes");
859 return true;
860 }),
861 }).pipe(Effect.provide(Logger.layer([])));
862​
863 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
864 }),
865 );
866​
867 it.effect("loads PowerShell profile environment on Windows", () =>
868 Effect.gen(function* () {
869 const env: NodeJS.ProcessEnv = {
870 PATH: "C:\\Windows\\System32",
871 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
872 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
873 USERPROFILE: "C:\\Users\\testuser",
874 };
875​
876 const prepared = yield* runShellEnvironment({
877 env,
878 platform: "win32",
879 handler: (command) => {
880 if (command._tag !== "StandardCommand") return "";
881 const loadProfile = !command.args.includes("-NoProfile");
882 return loadProfile
883 ? envOutput({
884 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
885 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
886 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
887 })
888 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
889 },
890 });
891​
892 assert.isTrue(prepared);
893 assert.equal(
894 env.PATH,
895 [
896 "C:\\Profile\\Node",
897 "C:\\Windows\\System32",
898 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
899 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
900 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
901 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
902 "C:\\Users\\testuser\\.local\\bin",
903 "C:\\Users\\testuser\\.bun\\bin",
904 "C:\\Users\\testuser\\scoop\\shims",
905 "C:\\Custom\\Bin",
906 "C:",
907 ].join(";"),
908 );
909 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
910 assert.equal(
911 env.FNM_MULTISHELL_PATH,
912 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
913 );
914 }),
915 );
916​
917 it.effect.each([false, true])(
918 "leaves Windows preparation incomplete when loadProfile=%s fails",
919 (loadProfile) =>
920 Effect.gen(function* () {
921 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
922 let calls = 0;
923 const prepared = yield* runShellEnvironment({
924 env,
925 platform: "win32",
926 handler: (command) => {
927 calls++;
928 if (command._tag !== "StandardCommand") return "";
929 return !command.args.includes("-NoProfile") === loadProfile
930 ? { output: "", exitCode: 1 }
931 : envOutput({ PATH: "C:\\Working" });
932 },
933 }).pipe(Effect.provide(Logger.layer([])));
934 assert.isFalse(prepared);
935 assert.equal(calls, 3);
936 assert.include(env.PATH, "C:\\Working");
937 assert.include(env.PATH, "C:\\Windows\\System32");
938 }),
939 );
940​
941 it.effect("gives up on a Windows shell that survives the kill", () =>
942 Effect.gen(function* () {
943 const commands: Array<string> = [];
944 // Both PowerShell probes spawn pwsh, time out, then spawn powershell. Each probe's timeout
945 // is armed before its spawn runs, so waiting for the spawns keeps the clock in step.
946 const spawned = yield* Effect.forEach([0, 1, 2, 3], () => Deferred.make<void>());
947 const fiber = yield* runShellEnvironment({
948 env: { PATH: "C:\\Windows", APPDATA: "C:\\Roaming" },
949 platform: "win32",
950 handler: () => "",
951 processSpawner: ChildProcessSpawner.make((command) => {
952 const spawn = spawned[commands.length];
953 commands.push(command._tag === "StandardCommand" ? command.command : "");
954 return (spawn ? Deferred.succeed(spawn, undefined) : Effect.void).pipe(
955 Effect.andThen(
956 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => Effect.never),
957 ),
958 );
959 }),
960 }).pipe(Effect.forkChild({ startImmediately: true }));
961​
962 yield* Effect.forEach(spawned.slice(0, 2), Deferred.await);
963 yield* TestClock.adjust("5 seconds");
964 yield* Effect.forEach(spawned.slice(2), Deferred.await);
965 yield* TestClock.adjust("5 seconds");
966 yield* Fiber.join(fiber);
967 assert.deepEqual([...new Set(commands)], ["pwsh.exe", "powershell.exe"]);
968 }),
969 );
970​
971 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
972 Effect.gen(function* () {
973 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
974​
975 yield* runShellEnvironment({
976 env,
977 platform: "win32",
978 handler: (command) =>
979 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
980 ? envOutput({ PATH: "C:\\Shell\\Bin" })
981 : "",
982 });
983​
984 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
985 }),
986 );
987​
988 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
989 Effect.gen(function* () {
990 const env: NodeJS.ProcessEnv = {
991 SHELL: "/bin/zsh",
992 PATH: "/usr/bin",
993 XDG_CURRENT_DESKTOP: "wrong-launcher",
994 XDG_SESSION_DESKTOP: "wrong-launcher",
995 };
996​
997 yield* runShellEnvironment({
998 env,
999 platform: "linux",
1000 handler: () =>
1001 envOutput({
1002 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
1003 XDG_CURRENT_DESKTOP: "KDE",
1004 XDG_SESSION_DESKTOP: "KDE",
1005 XDG_SESSION_TYPE: "wayland",
1006 }),
1007 });
1008​
1009 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
1010 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
1011 assert.equal(env.XDG_SESSION_TYPE, "wayland");
1012 }),
1013 );
1014});