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

DesktopShellEnvironment.test.ts

454 lines15.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 Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import * as PlatformError from "effect/PlatformError";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13import * as NodeOS from "node:os";
14import { vi } from "vite-plus/test";
15​
16import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
17import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
18​
19vi.mock("node:os", { spy: true });
20​
21const textEncoder = new TextEncoder();
22​
23function envOutput(values: Readonly<Record<string, string>>): string {
24 return Object.entries(values)
25 .flatMap(([name, value]) => [
26 `__T3CODE_ENV_${name}_START__`,
27 value,
28 `__T3CODE_ENV_${name}_END__`,
29 ])
30 .join("\n");
32​
33function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildProcessHandle {
34 const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
35 return ChildProcessSpawner.makeHandle({
36 pid: ChildProcessSpawner.ProcessId(123),
37 stdout,
38 stderr: Stream.empty,
39 all: stdout,
40 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
41 isRunning: Effect.succeed(false),
42 kill: () => Effect.void,
43 stdin: Sink.drain,
44 getInputFd: () => Sink.drain,
45 getOutputFd: () => Stream.empty,
46 unref: Effect.succeed(Effect.void),
47 });
49​
50function withProcessEnv<A, E, R>(
51 env: NodeJS.ProcessEnv,
52 effect: Effect.Effect<A, E, R>,
53): Effect.Effect<A, E, R> {
54 return Effect.acquireUseRelease(
55 Effect.sync(() => {
56 const previous = process.env;
57 process.env = env;
58 return previous;
59 }),
60 () => effect,
61 (previous) =>
62 Effect.sync(() => {
63 process.env = previous;
64 }),
65 );
67​
68function runShellEnvironment(input: {
69 readonly env: NodeJS.ProcessEnv;
70 readonly platform: NodeJS.Platform;
71 readonly userShell?: string;
72 readonly handler: (
73 command: ChildProcess.Command,
74 ) => string | { output: string; exitCode: number };
75 readonly failure?: PlatformError.PlatformError;
76 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
77}) {
78 const layerEnvironment = Layer.succeed(
79 DesktopEnvironment.DesktopEnvironment,
80 DesktopEnvironment.DesktopEnvironment.of({
81 platform: input.platform,
82 } as DesktopEnvironment.DesktopEnvironment["Service"]),
83 );
84 const layerSpawner = Layer.succeed(
85 ChildProcessSpawner.ChildProcessSpawner,
86 ChildProcessSpawner.make((command) => {
87 if (input.processSpawner) return input.processSpawner.spawn(command);
88 if (input.failure !== undefined) return Effect.fail(input.failure);
89 const result = input.handler(command);
90 return Effect.succeed(
91 typeof result === "string"
92 ? makeProcess(result)
93 : makeProcess(result.output, result.exitCode),
94 );
95 }),
96 );
97​
98 const program = Effect.gen(function* () {
99 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
100 const prepared = yield* shellEnvironment.installIntoProcess;
101 assert.equal(yield* shellEnvironment.installIntoProcess, prepared);
102 return prepared;
103 }).pipe(
104 Effect.provide(
105 DesktopShellEnvironment.layer.pipe(
106 Layer.provide(Layer.mergeAll(layerEnvironment, NodeServices.layer, layerSpawner)),
107 ),
108 ),
109 );
110​
111 return Effect.acquireUseRelease(
112 Effect.sync(() =>
113 vi.spyOn(NodeOS, "userInfo").mockReturnValue({
114 ...NodeOS.userInfo(),
115 shell: input.userShell ?? null,
116 }),
117 ),
118 () => withProcessEnv(input.env, program),
119 (spy) => Effect.sync(() => spy.mockRestore()),
120 );
122​
123describe("DesktopShellEnvironment", () => {
124 it.effect(
125 "captures the login-shell PATH when startup writes more than a pipe buffer to stderr",
126 () =>
127 Effect.gen(function* () {
128 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe(
129 Effect.provide(NodeServices.layer),
130 );
131 const executable = yield* HostProcess.ExecutablePath;
132 const env: NodeJS.ProcessEnv = { SHELL: "/test-shell", PATH: "/usr/bin" };
133 const commands: string[] = [];
134 const source = [
135 "setTimeout(() => process.exit(99), 3000).unref();",
136 "process.stderr.write(Buffer.alloc(2 * 1024 * 1024, 120), () => {",
137 `process.stdout.write(${JSON.stringify(envOutput({ PATH: "/shell-only/bin:/usr/bin" }))});`,
138 "});",
139 ].join("\n");
140​
141 yield* runShellEnvironment({
142 env,
143 platform: "linux",
144 handler: () => "",
145 processSpawner: ChildProcessSpawner.make((command) => {
146 if (command._tag !== "StandardCommand") return Effect.succeed(makeProcess(""));
147 commands.push(command.command);
148 return command.command === "/test-shell"
149 ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options))
150 : Effect.succeed(makeProcess(""));
151 }),
152 }).pipe(Effect.provide(Logger.layer([])));
153​
154 assert.equal(env.PATH, "/shell-only/bin:/usr/bin");
155 assert.deepEqual(commands, ["/test-shell"]);
156 }),
157 );
158​
159 it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
160 Effect.gen(function* () {
161 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
162 const commands: string[] = [];
163​
164 yield* runShellEnvironment({
165 env,
166 platform: "linux",
167 userShell: "/usr/local/bin/fish",
168 handler: (command) => {
169 if (command._tag !== "StandardCommand") return "";
170 commands.push(command.command);
171 return command.command === "/bin/failing"
172 ? { output: envOutput({ PATH: "/failed/bin" }), exitCode: 7 }
173 : envOutput({ PATH: "/home/test/.local/bin:/usr/bin" });
174 },
175 }).pipe(Effect.provide(Logger.layer([])));
176​
177 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
178 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
179 }),
180 );
181​
182 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
183 Effect.gen(function* () {
184 const env: NodeJS.ProcessEnv = {
185 SHELL: "/bin/zsh",
186 PATH: "/Users/test/.local/bin:/usr/bin",
187 };
188 const commands: ChildProcess.Command[] = [];
189​
190 const prepared = yield* runShellEnvironment({
191 env,
192 platform: "darwin",
193 handler: (command) => {
194 commands.push(command);
195 return envOutput({
196 PATH: "/opt/homebrew/bin:/usr/bin",
197 SSH_AUTH_SOCK: "/tmp/secretive.sock",
198 HOMEBREW_PREFIX: "/opt/homebrew",
199 });
200 },
201 });
202​
203 assert.equal(commands.length, 1);
204 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
205 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
206 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
207 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
208 assert.isTrue(prepared);
209 }),
210 );
211​
212 it.effect("does not mix login-shell locale categories into an inherited locale", () =>
213 Effect.gen(function* () {
214 const env: NodeJS.ProcessEnv = {
215 SHELL: "/bin/zsh",
216 PATH: "/usr/bin",
217 LANG: "en_US.UTF-8",
218 };
219​
220 yield* runShellEnvironment({
221 env,
222 platform: "darwin",
223 handler: () =>
224 envOutput({
225 PATH: "/opt/homebrew/bin:/usr/bin",
226 LC_ALL: "de_DE.UTF-8",
227 }),
228 });
229​
230 assert.equal(env.LANG, "en_US.UTF-8");
231 assert.equal(env.LC_ALL, undefined);
232 }),
233 );
234​
235 it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
236 Effect.gen(function* () {
237 const env: NodeJS.ProcessEnv = {
238 SHELL: "/bin/zsh",
239 PATH: "/usr/bin",
240 };
241​
242 yield* runShellEnvironment({
243 env,
244 platform: "darwin",
245 handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
246 });
247​
248 assert.equal(env.LANG, undefined);
249 assert.equal(env.LC_ALL, undefined);
250 assert.equal(env.LC_CTYPE, "en_US.UTF-8");
251 }),
252 );
253​
254 it.effect("hydrates missing CA trust variables from the login shell", () =>
255 Effect.gen(function* () {
256 const env: NodeJS.ProcessEnv = {
257 SHELL: "/bin/zsh",
258 PATH: "/usr/bin",
259 SSL_CERT_DIR: "/etc/ssl/certs",
260 };
261​
262 yield* runShellEnvironment({
263 env,
264 platform: "darwin",
265 handler: () =>
266 envOutput({
267 PATH: "/opt/zerobrew/bin:/usr/bin",
268 SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem",
269 SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates",
270 NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem",
271 }),
272 });
273​
274 assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem");
275 assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs");
276 assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem");
277 }),
278 );
279​
280 it.effect("keeps mise's PATH record with the login shell PATH", () =>
281 Effect.gen(function* () {
282 const env: NodeJS.ProcessEnv = {
283 SHELL: "/bin/bash",
284 PATH: "/usr/bin",
285 };
286​
287 yield* runShellEnvironment({
288 env,
289 platform: "linux",
290 handler: () =>
291 envOutput({
292 PATH: "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
293 __MISE_DIFF: "mise-diff",
294 }),
295 });
296​
297 assert.equal(env.__MISE_DIFF, "mise-diff");
298 }),
299 );
300​
301 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
302 Effect.gen(function* () {
303 const env: NodeJS.ProcessEnv = {
304 SHELL: "/opt/homebrew/bin/nu",
305 PATH: "/usr/bin",
306 };
307 const commands: string[] = [];
308​
309 const prepared = yield* runShellEnvironment({
310 env,
311 platform: "darwin",
312 handler: (command) => {
313 if (command._tag !== "StandardCommand") return "";
314 commands.push(command.command);
315 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
316 },
317 });
318​
319 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
320 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
321 assert.isFalse(prepared);
322 }),
323 );
324​
325 it.effect("leaves macOS preparation incomplete when no login shell returns a PATH", () =>
326 Effect.gen(function* () {
327 const prepared = yield* runShellEnvironment({
328 env: { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },
329 platform: "darwin",
330 handler: () => "",
331 });
332​
333 assert.isFalse(prepared);
334 }),
335 );
336​
337 it.effect("loads PowerShell profile environment on Windows", () =>
338 Effect.gen(function* () {
339 const env: NodeJS.ProcessEnv = {
340 PATH: "C:\\Windows\\System32",
341 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
342 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
343 USERPROFILE: "C:\\Users\\testuser",
344 };
345​
346 const prepared = yield* runShellEnvironment({
347 env,
348 platform: "win32",
349 handler: (command) => {
350 if (command._tag !== "StandardCommand") return "";
351 const loadProfile = !command.args.includes("-NoProfile");
352 return loadProfile
353 ? envOutput({
354 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
355 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
356 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
357 })
358 : envOutput({ PATH: 'C:\\Custom\\Bin;C:";C:\\Windows\\System32' });
359 },
360 });
361​
362 assert.isTrue(prepared);
363 assert.equal(
364 env.PATH,
365 [
366 "C:\\Profile\\Node",
367 "C:\\Windows\\System32",
368 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
369 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
370 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
371 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
372 "C:\\Users\\testuser\\.local\\bin",
373 "C:\\Users\\testuser\\.bun\\bin",
374 "C:\\Users\\testuser\\scoop\\shims",
375 "C:\\Custom\\Bin",
376 "C:",
377 ].join(";"),
378 );
379 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
380 assert.equal(
381 env.FNM_MULTISHELL_PATH,
382 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
383 );
384 }),
385 );
386​
387 it.effect.each([false, true])(
388 "leaves Windows preparation incomplete when loadProfile=%s fails",
389 (loadProfile) =>
390 Effect.gen(function* () {
391 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
392 let calls = 0;
393 const prepared = yield* runShellEnvironment({
394 env,
395 platform: "win32",
396 handler: (command) => {
397 calls++;
398 if (command._tag !== "StandardCommand") return "";
399 return !command.args.includes("-NoProfile") === loadProfile
400 ? { output: "", exitCode: 1 }
401 : envOutput({ PATH: "C:\\Working" });
402 },
403 }).pipe(Effect.provide(Logger.layer([])));
404 assert.isFalse(prepared);
405 assert.equal(calls, 3);
406 assert.include(env.PATH, "C:\\Working");
407 assert.include(env.PATH, "C:\\Windows\\System32");
408 }),
409 );
410​
411 it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
412 Effect.gen(function* () {
413 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
414​
415 yield* runShellEnvironment({
416 env,
417 platform: "win32",
418 handler: (command) =>
419 command._tag === "StandardCommand" && command.args.includes("-NoProfile")
420 ? envOutput({ PATH: "C:\\Shell\\Bin" })
421 : "",
422 });
423​
424 assert.deepEqual(env, { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" });
425 }),
426 );
427​
428 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
429 Effect.gen(function* () {
430 const env: NodeJS.ProcessEnv = {
431 SHELL: "/bin/zsh",
432 PATH: "/usr/bin",
433 XDG_CURRENT_DESKTOP: "wrong-launcher",
434 XDG_SESSION_DESKTOP: "wrong-launcher",
435 };
436​
437 yield* runShellEnvironment({
438 env,
439 platform: "linux",
440 handler: () =>
441 envOutput({
442 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
443 XDG_CURRENT_DESKTOP: "KDE",
444 XDG_SESSION_DESKTOP: "KDE",
445 XDG_SESSION_TYPE: "wayland",
446 }),
447 });
448​
449 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
450 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
451 assert.equal(env.XDG_SESSION_TYPE, "wayland");
452 }),
453 );
454});