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

DesktopShellEnvironment.test.ts

1,133 lines43.6 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.each([
188 { platform: "linux" as const, runtime: { APPDIR: "/opt/t3.AppDir/" }, scrub: true },
189 { platform: "linux" as const, runtime: { APPIMAGE: "/opt/T3.AppImage" }, scrub: true },
190 { platform: "linux" as const, runtime: {}, scrub: false },
191 { platform: "darwin" as const, runtime: { APPDIR: "/opt/t3.AppDir/" }, scrub: false },
192 ])(
193 "keeps AppImage mounts out of cached and discovered PATH: %j",
194 ({ platform, runtime, scrub }) =>
195 Effect.gen(function* () {
196 const fs = yield* FileSystem.FileSystem;
197 const stateDir = yield* fs.makeTempDirectoryScoped();
198 const cachePath = `${stateDir}/shell-environment-cache.json`;
199 const inheritedPath =
200 "/tmp/.mount_T3-Codold123/usr/bin:/launcher/bin:/opt/t3.AppDir/usr/bin";
201 const cachedPath = "/cached/bin:/tmp/.mount_T3-Codcache1/usr/bin";
202 const discoveredPath = "/fresh/bin:/tmp/.mount_T3-Codprobe1/usr/bin";
203 const retainedPath = "/tmp/tools:/tmp/.mount_Other123/usr/bin:/opt/t3.AppDir-backup/bin";
204 const cleanInherited = scrub
205 ? `/launcher/bin${runtime.APPDIR ? "" : ":/opt/t3.AppDir/usr/bin"}`
206 : inheritedPath;
207 const cleanCached = scrub ? "/cached/bin" : cachedPath;
208 const cleanDiscovered = scrub ? "/fresh/bin" : discoveredPath;
209 const env: NodeJS.ProcessEnv = {
210 ...runtime,
211 SHELL: "/bin/bash",
212 PATH: `${inheritedPath}:${retainedPath}`,
213 };
214 yield* fs.writeFileString(
215 cachePath,
216 encodeCache({
217 version: 1,
218 key: JSON.stringify([platform, "/test-home", "/bin/bash", ""]),
219 environment: { PATH: cachedPath, __MISE_DIFF: "cached-mise" },
220 }),
221 );
222 const started = yield* Deferred.make<void>();
223 const release = yield* Deferred.make<void>();
224 const probePath = yield* Deferred.make<string | undefined>();
225 yield* runShellEnvironment({
226 env,
227 platform,
228 stateDir,
229 handler: () => "",
230 processSpawner: ChildProcessSpawner.make((command) =>
231 Effect.gen(function* () {
232 const value =
233 command._tag === "StandardCommand" ? command.options.env?.PATH : undefined;
234 const path = typeof value === "string" ? value : undefined;
235 yield* Deferred.succeed(probePath, path);
236 yield* Deferred.succeed(started, undefined);
237 yield* Deferred.await(release);
238 return makeProcess(
239 envOutput({ PATH: `${discoveredPath}:${path}`, __MISE_DIFF: "fresh-mise" }),
240 );
241 }),
242 ),
243 use: (service) =>
244 Effect.gen(function* () {
245 yield* service.installIntoProcess;
246 const expectedCached = `${cleanCached}:${cleanInherited}:${retainedPath}`;
247 assert.equal(env.PATH, expectedCached);
248 assert.equal(env.__MISE_DIFF, "cached-mise");
249 const cached = yield* Stream.runHead(service.updates);
250 assert.equal(Option.getOrThrow(cached).environment.PATH, expectedCached);
251 yield* Deferred.await(started);
252 assert.equal(yield* Deferred.await(probePath), `${cleanInherited}:${retainedPath}`);
253 yield* Deferred.succeed(release, undefined);
254 yield* service.awaitDiscovery;
255 const expectedFresh = `${cleanDiscovered}:${cleanInherited}:${retainedPath}`;
256 assert.equal(env.PATH, expectedFresh);
257 assert.equal(env.__MISE_DIFF, "fresh-mise");
258 const fresh = yield* Stream.runHead(service.updates);
259 assert.equal(Option.getOrThrow(fresh).environment.PATH, expectedFresh);
260 return true;
261 }),
262 });
263 const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
264 assert.equal(cached.environment.PATH, env.PATH);
265 assert.equal(cached.environment.__MISE_DIFF, "fresh-mise");
266 }).pipe(Effect.provide(NodeServices.layer)),
267 );
268​
269 it.effect.each([
270 { platform: "darwin" as const, env: { PATH: "/usr/bin" }, expectedPath: "/usr/bin" },
271 {
272 platform: "linux" as const,
273 env: { APPDIR: "/tmp/.mount_T3-Codnew123", PATH: ":/tmp/.mount_T3-Codold123/bin::/usr/bin:" },
274 expectedPath: "::/usr/bin:",
275 },
276 {
277 platform: "linux" as const,
278 env: { APPDIR: "/tmp/.mount_T3-Codnew123", PATH: "/tmp/.mount_T3-Codnew123/bin" },
279 expectedPath: undefined,
280 },
281 ])(
282 "does not wait for discovery when the cache is missing: %j",
283 ({ platform, env: initial, expectedPath }) =>
284 Effect.gen(function* () {
285 const started = yield* Deferred.make<void>();
286 const release = yield* Deferred.make<void>();
287 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", ...initial };
288 let probePath: string | undefined;
289 yield* runShellEnvironment({
290 env,
291 platform,
292 handler: () => "",
293 processSpawner: ChildProcessSpawner.make((command) =>
294 Effect.gen(function* () {
295 const value =
296 command._tag === "StandardCommand" ? command.options.env?.PATH : undefined;
297 probePath = typeof value === "string" ? value : undefined;
298 yield* Deferred.succeed(started, undefined);
299 yield* Deferred.await(release);
300 return makeProcess(envOutput({ PATH: "/fresh/bin" }));
301 }),
302 ),
303 use: (service) =>
304 Effect.gen(function* () {
305 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
306 yield* Deferred.await(started);
307 assert.isDefined(startup.pollUnsafe());
308 assert.equal(env.PATH, expectedPath);
309 assert.equal(probePath, expectedPath);
310 yield* Deferred.succeed(release, undefined);
311 return yield* service.awaitDiscovery;
312 }),
313 });
314 }),
315 );
316​
317 it.effect(
318 "reuses cached paths immediately and streams fresh discovery without keeping removed paths",
319 () =>
320 Effect.gen(function* () {
321 const fs = yield* FileSystem.FileSystem;
322 const stateDir = yield* fs.makeTempDirectoryScoped();
323 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
324 Effect.provide(NodeServices.layer),
325 );
326 const executable = yield* HostProcess.ExecutablePath;
327 const first = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
328 yield* runShellEnvironment({
329 env: first,
330 stateDir,
331 platform: "darwin",
332 handler: () =>
333 envOutput({
334 PATH: "/old/bin:/usr/bin",
335 __MISE_DIFF: "old-mise",
336 SSH_AUTH_SOCK: "/old-session.sock",
337 JAVA_HOME: "/old/java",
338 PNPM_HOME: "/old/pnpm",
339 SSL_CERT_FILE: "/old/cert.pem",
340 }),
341 });
342 const cachePath = `${stateDir}/shell-environment-cache.json`;
343 const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
344 assert.equal(cached.environment.PATH, "/old/bin:/usr/bin");
345 assert.equal(cached.environment.PNPM_HOME, "/old/pnpm");
346 assert.notProperty(cached.environment, "SSH_AUTH_SOCK");
347 const started = yield* Deferred.make<void>();
348 const release = yield* Deferred.make<void>();
349 const env: NodeJS.ProcessEnv = {
350 SHELL: "/bin/zsh",
351 PATH: "/launcher/bin",
352 SSH_AUTH_SOCK: "/current-session.sock",
353 };
354 const source = [
355 "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 };",
356 "for (const [name, value] of Object.entries(values)) {",
357 " if (value !== undefined) process.stdout.write('__T3CODE_ENV_' + name + '_START__\\n' + value + '\\n__T3CODE_ENV_' + name + '_END__\\n');",
358 "}",
359 ].join("\n");
360 let calls = 0;
361 yield* runShellEnvironment({
362 env,
363 stateDir,
364 platform: "darwin",
365 handler: () => "",
366 processSpawner: ChildProcessSpawner.make((command) => {
367 calls++;
368 return Deferred.succeed(started, undefined).pipe(
369 Effect.andThen(Deferred.await(release)),
370 Effect.andThen(
371 command._tag === "StandardCommand"
372 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
373 : Effect.succeed(makeProcess("")),
374 ),
375 );
376 }),
377 use: (service) =>
378 Effect.gen(function* () {
379 yield* service.installIntoProcess;
380 yield* service.installIntoProcess;
381 assert.equal(env.PATH, "/old/bin:/usr/bin:/launcher/bin");
382 assert.equal(env.SSH_AUTH_SOCK, "/current-session.sock");
383 const replay = yield* Stream.runHead(service.updates);
384 assert.isTrue(Option.isSome(replay));
385 if (Option.isSome(replay))
386 assert.equal(replay.value.environment.__MISE_DIFF, "old-mise");
387 yield* Deferred.await(started);
388 assert.equal(calls, 1);
389 yield* Deferred.succeed(release, undefined);
390 yield* service.awaitDiscovery;
391 assert.equal(env.PATH, "/fresh/bin:/launcher/bin");
392 assert.equal(env.__MISE_DIFF, "fresh-mise");
393 assert.isUndefined(env.JAVA_HOME);
394 assert.isUndefined(env.PNPM_HOME);
395 assert.isUndefined(env.SSL_CERT_FILE);
396 const fresh = yield* Stream.runHead(service.updates);
397 assert.isTrue(Option.isSome(fresh));
398 if (Option.isSome(fresh)) {
399 assert.equal(fresh.value.environment.PATH, env.PATH);
400 assert.isTrue(fresh.value.discovered);
401 }
402 return true;
403 }),
404 });
405 const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache));
406 assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin");
407 assert.notProperty(refreshed.environment, "JAVA_HOME");
408 assert.notProperty(refreshed.environment, "PNPM_HOME");
409 assert.notProperty(refreshed.environment, "SSL_CERT_FILE");
410 }).pipe(Effect.provide(NodeServices.layer)),
411 );
412​
413 it.effect.each([
414 "not json",
415 '{"version":2,"key":"old","environment":{"PATH":"/bad/bin"}}',
416 '{"version":1,"key":"other-shell","environment":{"PATH":"/bad/bin"}}',
417 ])("ignores an unusable cache and still starts before discovery: %s", (contents) =>
418 Effect.gen(function* () {
419 const fs = yield* FileSystem.FileSystem;
420 const stateDir = yield* fs.makeTempDirectoryScoped();
421 yield* fs.writeFileString(`${stateDir}/shell-environment-cache.json`, contents);
422 const started = yield* Deferred.make<void>();
423 const release = yield* Deferred.make<void>();
424 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
425 yield* runShellEnvironment({
426 env,
427 stateDir,
428 platform: "darwin",
429 handler: () => "",
430 processSpawner: ChildProcessSpawner.make(() =>
431 Deferred.succeed(started, undefined).pipe(
432 Effect.andThen(Deferred.await(release)),
433 Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))),
434 ),
435 ),
436 use: (service) =>
437 Effect.gen(function* () {
438 const startup = yield* service.installIntoProcess.pipe(Effect.forkChild);
439 yield* Deferred.await(started);
440 assert.isDefined(startup.pollUnsafe());
441 assert.equal(env.PATH, "/usr/bin");
442 yield* Deferred.succeed(release, undefined);
443 return yield* service.awaitDiscovery;
444 }),
445 });
446 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
447 }).pipe(Effect.provide(NodeServices.layer)),
448 );
449​
450 it.effect(
451 "retains the last successful cache on refresh failure and ignores session values in the cache",
452 () =>
453 Effect.gen(function* () {
454 const fs = yield* FileSystem.FileSystem;
455 const stateDir = yield* fs.makeTempDirectoryScoped();
456 const contents = encodeCache({
457 version: 1,
458 key: '["darwin","/test-home","/bin/zsh",""]',
459 environment: {
460 PATH: "/cached/bin",
461 __MISE_DIFF: "cached-mise",
462 JAVA_HOME: "/cached/java",
463 PNPM_HOME: "/cached/pnpm",
464 NODE_EXTRA_CA_CERTS: "/cached/ca.pem",
465 SSL_CERT_FILE: "/cached/cert.pem",
466 SSL_CERT_DIR: "/cached/certs",
467 T3CODE_TELEMETRY_ENABLED: "false",
468 SSH_AUTH_SOCK: "/stale.sock",
469 NODE_OPTIONS: "--bad",
470 },
471 });
472 const cachePath = `${stateDir}/shell-environment-cache.json`;
473 yield* fs.writeFileString(cachePath, contents);
474 const env: NodeJS.ProcessEnv = {
475 SHELL: "/bin/zsh",
476 PATH: "/usr/bin",
477 __MISE_DIFF: "launcher-mise",
478 JAVA_HOME: "/launcher/java",
479 NODE_EXTRA_CA_CERTS: "/launcher/ca.pem",
480 SSL_CERT_FILE: "",
481 SSH_AUTH_SOCK: "/current.sock",
482 };
483 const prepared = yield* runShellEnvironment({
484 env,
485 stateDir,
486 platform: "darwin",
487 handler: () => "",
488 use: (service) =>
489 Effect.gen(function* () {
490 yield* service.installIntoProcess;
491 const replay = yield* Stream.runHead(service.updates);
492 assert.isTrue(Option.isSome(replay));
493 if (Option.isSome(replay)) {
494 assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java");
495 assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
496 }
497 return yield* service.awaitDiscovery;
498 }),
499 });
500 assert.isFalse(prepared);
501 assert.equal(env.PATH, "/cached/bin:/usr/bin");
502 assert.equal(env.__MISE_DIFF, "cached-mise");
503 assert.equal(env.JAVA_HOME, "/launcher/java");
504 assert.equal(env.PNPM_HOME, "/cached/pnpm");
505 assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem");
506 assert.equal(env.SSL_CERT_FILE, "");
507 assert.equal(env.SSL_CERT_DIR, "/cached/certs");
508 assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false");
509 assert.equal(env.SSH_AUTH_SOCK, "/current.sock");
510 assert.isUndefined(env.NODE_OPTIONS);
511 assert.equal(yield* fs.readFileString(cachePath), contents);
512 }).pipe(Effect.provide(NodeServices.layer)),
513 );
514​
515 it.effect("cancels background discovery when the application scope closes", () =>
516 Effect.gen(function* () {
517 const started = yield* Deferred.make<void>();
518 const stopped = yield* Deferred.make<void>();
519 yield* runShellEnvironment({
520 env: { SHELL: "/bin/zsh", PATH: "/usr/bin" },
521 platform: "darwin",
522 handler: () => "",
523 processSpawner: ChildProcessSpawner.make(() =>
524 Deferred.succeed(started, undefined).pipe(
525 Effect.andThen(Effect.never),
526 Effect.ensuring(Deferred.succeed(stopped, undefined)),
527 ),
528 ),
529 use: (service) =>
530 Effect.gen(function* () {
531 yield* service.installIntoProcess;
532 yield* Deferred.await(started);
533 return true;
534 }),
535 });
536 yield* Deferred.await(stopped);
537 }),
538 );
539​
540 it.effect(
541 "captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
542 () =>
543 Effect.gen(function* () {
544 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
545 Effect.provide(NodeServices.layer),
546 );
547 const executable = yield* HostProcess.ExecutablePath;
548 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", PATH: "/usr/bin" };
549 const commands: string[] = [];
550 const source = [
551 "setTimeout(() => process.exit(99), 3000).unref();",
552 "process.stderr.write(Buffer.alloc(2 * 1024 * 1024, 120), () => {",
553 `process.stdout.write(${JSON.stringify(envOutput({ PATH: "/shell-only/bin:/usr/bin" }))});`,
554 "});",
555 ].join("\n");
556​
557 yield* runShellEnvironment({
558 env,
559 platform: "linux",
560 handler: () => "",
561 processSpawner: ChildProcessSpawner.make((command) => {
562 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
563 commands.push(command.command);
564 return command.command === "/test-shell"
565 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
566 : Effect.succeed(makeProcess(""));
567 }),
568 }).pipe(Effect.provide(Logger.layer([])));
569​
570 assert.equal(env.PATH, "/shell-only/bin:/usr/bin");
571 assert.deepEqual(commands, ["/test-shell"]);
572 }),
573 );
574​
575 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
576 Effect.gen(function* () {
577 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
578 const commands: string[] = [];
579​
580 const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) =>
581 Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]);
582 const answered = yield* runShellEnvironment({
583 env,
584 platform: "linux",
585 userShell: "/usr/local/bin/fish",
586 use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)),
587 handler: (command) => {
588 if (command._tag !== "StandardCommand") return "";
589 commands.push(command.command);
590 return command.command === "/bin/failing"
591 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
592 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
593 },
594 }).pipe(Effect.provide(Logger.layer([])));
595​
596 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
597 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
598 // The account's own login shell answered.
599 assert.isTrue(answered);
600​
601 // Only the platform fallback answered: its PATH can miss folders the user's shell adds.
602 const fallbackOnly = yield* runShellEnvironment({
603 env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" },
604 platform: "linux",
605 use: (service) =>
606 discovery(service).pipe(
607 Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell),
608 ),
609 handler: (command) =>
610 command._tag === "StandardCommand" && command.command === "/usr/bin/fish"
611 ? { output: "", exitCode: 7 }
612 : envOutput({ PATH: "/usr/bin" }),
613 }).pipe(Effect.provide(Logger.layer([])));
614 assert.isTrue(fallbackOnly);
615 }),
616 );
617​
618 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
619 Effect.gen(function* () {
620 const env: NodeJS.ProcessEnv = {
621 SHELL: "/bin/zsh",
622 PATH: " /Users/test/.local/bin:/usr/bin",
623 };
624 const commands: ChildProcess.Command[] = [];
625​
626 const prepared = yield* runShellEnvironment({
627 env,
628 platform: "darwin",
629 handler: (command) => {
630 commands.push(command);
631 return envOutput({
632 PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ",
633 SSH_AUTH_SOCK: "/tmp/secretive.sock",
634 HOMEBREW_PREFIX: "/opt/homebrew",
635 });
636 },
637 });
638​
639 assert.equal(commands.length, 1);
640 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
641 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin");
642 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
643 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
644 assert.isTrue(prepared);
645 }),
646 );
647​
648 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
649 Effect.gen(function* () {
650 const env: NodeJS.ProcessEnv = {
651 SHELL: "/bin/zsh",
652 PATH: "/usr/bin",
653 LANG: "en_US.UTF-8",
654 };
655​
656 yield* runShellEnvironment({
657 env,
658 platform: "darwin",
659 handler: () =>
660 envOutput({
661 PATH: "/opt/homebrew/bin:/usr/bin",
662 LC_ALL: "de_DE.UTF-8",
663 }),
664 });
665​
666 assert.equal(env.LANG, "en_US.UTF-8");
667 assert.equal(env.LC_ALL, undefined);
668 }),
669 );
670​
671 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
672 Effect.gen(function* () {
673 const env: NodeJS.ProcessEnv = {
674 SHELL: "/bin/zsh",
675 PATH: "/usr/bin",
676 };
677​
678 yield* runShellEnvironment({
679 env,
680 platform: "darwin",
681 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
682 });
683​
684 assert.equal(env.LANG, undefined);
685 assert.equal(env.LC_ALL, undefined);
686 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
687 }),
688 );
689​
690 it.effect("hydrates missing CA trust variables from the login shell", () =>
691 Effect.gen(function* () {
692 const env: NodeJS.ProcessEnv = {
693 SHELL: "/bin/zsh",
694 PATH: "/usr/bin",
695 SSL_CERT_DIR: "/etc/ssl/certs",
696 };
697​
698 yield* runShellEnvironment({
699 env,
700 platform: "darwin",
701 handler: () =>
702 envOutput({
703 PATH: "/opt/zerobrew/bin:/usr/bin",
704 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
705 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
706 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
707 }),
708 });
709​
710 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
711 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
712 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
713 }),
714 );
715​
716 it.effect.each([
717 {
718 name: "hydrates both Android SDK names when neither is inherited",
719 inherited: {},
720 expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" },
721 },
722 {
723 // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell
724 // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK.
725 name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME",
726 inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" },
727 expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" },
728 },
729 ])("$name", ({ inherited, expected }) =>
730 Effect.gen(function* () {
731 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited };
732​
733 yield* runShellEnvironment({
734 env,
735 platform: "darwin",
736 handler: () =>
737 envOutput({
738 PATH: "/usr/bin",
739 ANDROID_HOME: "/shell/android-home",
740 ANDROID_SDK_ROOT: "/shell/android-root",
741 }),
742 });
743​
744 assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME);
745 assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT);
746 }),
747 );
748​
749 it.effect("keeps mise's PATH record with the login shell PATH", () =>
750 Effect.gen(function* () {
751 const env: NodeJS.ProcessEnv = {
752 SHELL: "/bin/bash",
753 PATH: "/usr/bin",
754 };
755​
756 yield* runShellEnvironment({
757 env,
758 platform: "linux",
759 handler: () =>
760 envOutput({
761 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
762 __MISE_DIFF: "mise-diff",
763 }),
764 });
765​
766 assert.equal(env.__MISE_DIFF, "mise-diff");
767 }),
768 );
769​
770 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
771 Effect.gen(function* () {
772 const env: NodeJS.ProcessEnv = {
773 SHELL: "/opt/homebrew/bin/nu",
774 PATH: "/usr/bin",
775 };
776 const commands: string[] = [];
777​
778 const prepared = yield* runShellEnvironment({
779 env,
780 platform: "darwin",
781 handler: (command) => {
782 if (command._tag !== "StandardCommand") return "";
783 commands.push(command.command);
784 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
785 },
786 });
787​
788 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
789 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
790 assert.isFalse(prepared);
791 }),
792 );
793​
794 it.effect("leaves macOS preparation incomplete when no login shell returns a PATH", () =>
795 Effect.gen(function* () {
796 const prepared = yield* runShellEnvironment({
797 env: { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },
798 platform: "darwin",
799 handler: () => "",
800 });
801​
802 assert.isFalse(prepared);
803 }),
804 );
805​
806 it.effect("retries the user's shell when only the fallback shell answered", () =>
807 Effect.gen(function* () {
808 const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" };
809 const commands: string[] = [];
810 let fishReady = false;
811 yield* runShellEnvironment({
812 env,
813 platform: "linux",
814 handler: (command) => {
815 if (command._tag !== "StandardCommand") return "";
816 commands.push(command.command);
817 if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" });
818 return fishReady
819 ? envOutput({ PATH: "/fish/bin:/usr/bin" })
820 : { output: "", exitCode: 7 };
821 },
822 use: (service) =>
823 Effect.gen(function* () {
824 assert.isTrue(yield* service.awaitDiscovery);
825 assert.equal(env.PATH, "/usr/bin");
826 // The user's shell may still opt out of telemetry, so discovery has not settled.
827 assert.isFalse(yield* service.discoveryFinished);
828 // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await.
829 const published = yield* service.updates.pipe(
830 Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"),
831 Stream.runHead,
832 Effect.forkChild({ startImmediately: true }),
833 );
834​
835 fishReady = true;
836 yield* TestClock.adjust("30 seconds");
837 assert.isTrue(Option.isSome(yield* Fiber.join(published)));
838 assert.equal(env.PATH, "/fish/bin:/usr/bin");
839 return true;
840 }),
841 }).pipe(Effect.provide(Logger.layer([])));
842 assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]);
843​
844 // With no user shell to wait for, the fallback's answer is final.
845 commands.length = 0;
846 yield* runShellEnvironment({
847 env: { PATH: "/usr/bin" },
848 platform: "linux",
849 handler: (command) => {
850 if (command._tag === "StandardCommand") commands.push(command.command);
851 return envOutput({ PATH: "/usr/bin" });
852 },
853 use: (service) =>
854 Effect.gen(function* () {
855 assert.isTrue(yield* service.awaitDiscovery);
856 yield* TestClock.adjust("5 minutes");
857 return true;
858 }),
859 }).pipe(Effect.provide(Logger.layer([])));
860 assert.deepEqual(commands, ["/bin/bash"]);
861 }),
862 );
863​
864 it.effect("gives background retries time for a locked or slow shell, then publishes", () =>
865 Effect.gen(function* () {
866 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
867 // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one.
868 const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make<void>());
869 const stopped = yield* Deferred.make<ChildProcess.KillOptions>();
870 let attempts = 0;
871 yield* runShellEnvironment({
872 env,
873 platform: "darwin",
874 handler: () => "",
875 processSpawner: ChildProcessSpawner.make((command) => {
876 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
877 return Effect.succeed(makeProcess(""));
878 }
879 const attempt = attempts++;
880 const spawn = Deferred.succeed(spawned[attempt]!, undefined);
881 if (attempt === 0) return spawn.pipe(Effect.as(makeProcess("")));
882 if (attempt === 1) {
883 return spawn.pipe(
884 Effect.andThen(
885 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () =>
886 Deferred.succeed(stopped, command.options),
887 ),
888 ),
889 );
890 }
891 return spawn.pipe(
892 Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")),
893 );
894 }),
895 use: (service) =>
896 Effect.gen(function* () {
897 assert.isFalse(yield* service.awaitDiscovery);
898 const published = yield* service.updates.pipe(
899 Stream.drop(1),
900 Stream.runHead,
901 Effect.forkChild({ startImmediately: true }),
902 );
903​
904 yield* TestClock.adjust("30 seconds");
905 yield* Deferred.await(spawned[1]!);
906 // pyenv waits up to 60 s on its rehash lock before the shell continues.
907 yield* TestClock.adjust("1 minute");
908 assert.isFalse(yield* Deferred.isDone(stopped));
909 yield* TestClock.adjust("1 minute");
910 const stop = yield* Deferred.await(stopped);
911 // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips.
912 assert.equal(stop.killSignal, "SIGTERM");
913 assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000);
914​
915 yield* TestClock.adjust("30 seconds");
916 yield* Deferred.await(spawned[2]!);
917 yield* TestClock.adjust("20 seconds");
918 const snapshot = yield* Fiber.join(published);
919 assert.equal(env.PATH, "/fresh/bin:/usr/bin");
920 assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered);
921 assert.equal(
922 Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined,
923 "/fresh/bin:/usr/bin",
924 );
925 return true;
926 }),
927 });
928 }),
929 );
930​
931 it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () =>
932 Effect.gen(function* () {
933 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" };
934 const output = envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" });
935 let shellProbes = 0;
936 yield* runShellEnvironment({
937 env,
938 platform: "darwin",
939 handler: () => "",
940 processSpawner: ChildProcessSpawner.make((command) => {
941 if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") {
942 return Effect.succeed(makeProcess(""));
943 }
944 shellProbes += 1;
945 if (shellProbes > 1) return Effect.succeed(makeProcess(output));
946 // A cold start: the first login shell answers, but only after 7s.
947 const slow = Effect.sleep("7 seconds");
948 const stdout = Stream.fromEffect(slow.pipe(Effect.as(textEncoder.encode(output))));
949 return Effect.succeed(
950 ChildProcessSpawner.makeHandle({
951 pid: ChildProcessSpawner.ProcessId(125),
952 stdout,
953 stderr: Stream.empty,
954 all: stdout,
955 exitCode: slow.pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
956 isRunning: Effect.succeed(true),
957 kill: () => Effect.void,
958 stdin: Sink.drain,
959 getInputFd: () => Sink.drain,
960 getOutputFd: () => Stream.empty,
961 unref: Effect.succeed(Effect.void),
962 }),
963 );
964 }),
965 use: (service) =>
966 Effect.gen(function* () {
967 yield* service.installIntoProcess;
968 yield* TestClock.adjust("10 minutes");
969 return true;
970 }),
971 }).pipe(Effect.provide(Logger.layer([])));
972​
973 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
974 }),
975 );
976​
977 it.effect("loads PowerShell profile environment on Windows", () =>
978 Effect.gen(function* () {
979 const env: NodeJS.ProcessEnv = {
980 PATH: "C:\\Windows\\System32",
981 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
982 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
983 USERPROFILE: "C:\\Users\\testuser",
984 };
985​
986 const scripts: Array<string> = [];
987 const prepared = yield* runShellEnvironment({
988 env,
989 platform: "win32",
990 handler: (command) => {
991 if (command._tag !== "StandardCommand") return "";
992 scripts.push(String(command.args.at(-1)));
993 const loadProfile = !command.args.includes("-NoProfile");
994 return loadProfile
995 ? envOutput({
996 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
997 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
998 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
999 })
1000 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
1001 },
1002 });
1003​
1004 assert.isTrue(prepared);
1005 assert.equal(
1006 env.PATH,
1008 "C:\\Profile\\Node",
1009 "C:\\Windows\\System32",
1010 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1011 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1012 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1013 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1014 "C:\\Users\\testuser\\.local\\bin",
1015 "C:\\Users\\testuser\\.bun\\bin",
1016 "C:\\Users\\testuser\\scoop\\shims",
1017 "C:\\Custom\\Bin",
1018 "C:",
1019 ].join(";"),
1020 );
1021 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
1022 assert.equal(
1023 env.FNM_MULTISHELL_PATH,
1024 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1025 );
1026 assert.isNotEmpty(scripts);
1027 for (const script of scripts) {
1028 assert.include(
1029 script,
1030 "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
1031 );
1033 }),
1034 );
1035​
1036 it.effect.each([false, true])(
1037 "leaves Windows preparation incomplete when loadProfile=%s fails",
1038 (loadProfile) =>
1039 Effect.gen(function* () {
1040 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
1041 let calls = 0;
1042 const prepared = yield* runShellEnvironment({
1043 env,
1044 platform: "win32",
1045 handler: (command) => {
1046 calls++;
1047 if (command._tag !== "StandardCommand") return "";
1048 return !command.args.includes("-NoProfile") === loadProfile
1049 ? { output: "", exitCode: 1 }
1050 : envOutput({ PATH: "C:\\Working" });
1051 },
1052 }).pipe(Effect.provide(Logger.layer([])));
1053 assert.isFalse(prepared);
1054 assert.equal(calls, 3);
1055 assert.include(env.PATH, "C:\\Working");
1056 assert.include(env.PATH, "C:\\Windows\\System32");
1057 }),
1058 );
1059​
1060 it.effect("gives up on a Windows shell that survives the kill", () =>
1061 Effect.gen(function* () {
1062 const commands: Array<string> = [];
1063 // Both PowerShell probes spawn pwsh, time out, then spawn powershell. Each probe's timeout
1064 // is armed before its spawn runs, so waiting for the spawns keeps the clock in step.
1065 const spawned = yield* Effect.forEach([0, 1, 2, 3], () => Deferred.make<void>());
1066 const fiber = yield* runShellEnvironment({
1067 env: { PATH: "C:\\Windows", APPDATA: "C:\\Roaming" },
1068 platform: "win32",
1069 handler: () => "",
1070 processSpawner: ChildProcessSpawner.make((command) => {
1071 const spawn = spawned[commands.length];
1072 commands.push(command._tag === "StandardCommand" ? command.command : "");
1073 return (spawn ? Deferred.succeed(spawn, undefined) : Effect.void).pipe(
1074 Effect.andThen(
1075 Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => Effect.never),
1076 ),
1077 );
1078 }),
1079 }).pipe(Effect.forkChild({ startImmediately: true }));
1080​
1081 yield* Effect.forEach(spawned.slice(0, 2), Deferred.await);
1082 yield* TestClock.adjust("5 seconds");
1083 yield* Effect.forEach(spawned.slice(2), Deferred.await);
1084 yield* TestClock.adjust("5 seconds");
1085 yield* Fiber.join(fiber);
1086 assert.deepEqual([...new Set(commands)], ["pwsh.exe", "powershell.exe"]);
1087 }),
1088 );
1089​
1090 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
1091 Effect.gen(function* () {
1092 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
1093​
1094 yield* runShellEnvironment({
1095 env,
1096 platform: "win32",
1097 handler: (command) =>
1098 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
1099 ? envOutput({ PATH: "C:\\Shell\\Bin" })
1100 : "",
1101 });
1102​
1103 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
1104 }),
1105 );
1106​
1107 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
1108 Effect.gen(function* () {
1109 const env: NodeJS.ProcessEnv = {
1110 SHELL: "/bin/zsh",
1111 PATH: "/usr/bin",
1112 XDG_CURRENT_DESKTOP: "wrong-launcher",
1113 XDG_SESSION_DESKTOP: "wrong-launcher",
1114 };
1115​
1116 yield* runShellEnvironment({
1117 env,
1118 platform: "linux",
1119 handler: () =>
1120 envOutput({
1121 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
1122 XDG_CURRENT_DESKTOP: "KDE",
1123 XDG_SESSION_DESKTOP: "KDE",
1124 XDG_SESSION_TYPE: "wayland",
1125 }),
1126 });
1127​
1128 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
1129 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
1130 assert.equal(env.XDG_SESSION_TYPE, "wayland");
1131 }),
1132 );
1133});