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

DesktopShellEnvironment.test.ts

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