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

DesktopShellEnvironment.test.ts

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