Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Logger from "effect/Logger";
6import * as PlatformError from "effect/PlatformError";
7import * as Schema from "effect/Schema";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/unstable/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
12
13import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
14import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
15
16const textEncoder = new TextEncoder();
17
18const isDesktopShellEnvironmentCommandError = Schema.is(
19 DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
20);
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");
30}
31
32function makeProcess(output: string): 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(0)),
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 });
47}
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 );
65}
66
67function runShellEnvironment(input: {
68 readonly env: NodeJS.ProcessEnv;
69 readonly platform: NodeJS.Platform;
70 readonly handler: (command: ChildProcess.Command) => string;
71 readonly failure?: PlatformError.PlatformError;
72}) {
73 const environmentLayer = Layer.succeed(
74 DesktopEnvironment.DesktopEnvironment,
75 DesktopEnvironment.DesktopEnvironment.of({
76 platform: input.platform,
77 } as DesktopEnvironment.DesktopEnvironment["Service"]),
78 );
79 const spawnerLayer = Layer.succeed(
80 ChildProcessSpawner.ChildProcessSpawner,
81 ChildProcessSpawner.make((command) =>
82 input.failure === undefined
83 ? Effect.succeed(makeProcess(input.handler(command)))
84 : Effect.fail(input.failure),
85 ),
86 );
87
88 const program = Effect.gen(function* () {
89 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
90 yield* shellEnvironment.installIntoProcess;
91 }).pipe(
92 Effect.provide(
93 DesktopShellEnvironment.layer.pipe(
94 Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
95 ),
96 ),
97 );
98
99 return withProcessEnv(input.env, program);
100}
101
102describe("DesktopShellEnvironment", () => {
103 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
104 Effect.gen(function* () {
105 const env: NodeJS.ProcessEnv = {
106 SHELL: "/bin/zsh",
107 PATH: "/Users/test/.local/bin:/usr/bin",
108 };
109 const commands: ChildProcess.Command[] = [];
110
111 yield* runShellEnvironment({
112 env,
113 platform: "darwin",
114 handler: (command) => {
115 commands.push(command);
116 return envOutput({
117 PATH: "/opt/homebrew/bin:/usr/bin",
118 SSH_AUTH_SOCK: "/tmp/secretive.sock",
119 HOMEBREW_PREFIX: "/opt/homebrew",
120 });
121 },
122 });
123
124 assert.equal(commands.length, 1);
125 assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
126 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
127 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
128 assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
129 }),
130 );
131
132 it.effect("preserves inherited POSIX values when present", () =>
133 Effect.gen(function* () {
134 const env: NodeJS.ProcessEnv = {
135 SHELL: "/bin/zsh",
136 PATH: "/usr/bin",
137 SSH_AUTH_SOCK: "/tmp/inherited.sock",
138 };
139
140 yield* runShellEnvironment({
141 env,
142 platform: "darwin",
143 handler: () =>
144 envOutput({
145 PATH: "/opt/homebrew/bin:/usr/bin",
146 SSH_AUTH_SOCK: "/tmp/login-shell.sock",
147 }),
148 });
149
150 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
151 assert.equal(env.SSH_AUTH_SOCK, "/tmp/inherited.sock");
152 }),
153 );
154
155 it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
156 Effect.gen(function* () {
157 const env: NodeJS.ProcessEnv = {
158 SHELL: "/bin/zsh",
159 PATH: "/usr/bin",
160 };
161
162 yield* runShellEnvironment({
163 env,
164 platform: "linux",
165 handler: () =>
166 envOutput({
167 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
168 SSH_AUTH_SOCK: "/tmp/secretive.sock",
169 }),
170 });
171
172 assert.equal(env.PATH, "/home/linuxbrew/.linuxbrew/bin:/usr/bin");
173 assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
174 }),
175 );
176
177 it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
178 Effect.gen(function* () {
179 const env: NodeJS.ProcessEnv = {
180 SHELL: "/opt/homebrew/bin/nu",
181 PATH: "/usr/bin",
182 };
183 const commands: string[] = [];
184
185 yield* runShellEnvironment({
186 env,
187 platform: "darwin",
188 handler: (command) => {
189 if (command._tag !== "StandardCommand") return "";
190 commands.push(command.command);
191 return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
192 },
193 });
194
195 assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
196 assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
197 }),
198 );
199
200 it.effect("loads PowerShell profile environment on Windows", () =>
201 Effect.gen(function* () {
202 const env: NodeJS.ProcessEnv = {
203 PATH: "C:\\Windows\\System32",
204 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
205 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
206 USERPROFILE: "C:\\Users\\testuser",
207 };
208
209 yield* runShellEnvironment({
210 env,
211 platform: "win32",
212 handler: (command) => {
213 if (command._tag !== "StandardCommand") return "";
214 const loadProfile = !command.args.includes("-NoProfile");
215 return loadProfile
216 ? envOutput({
217 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
218 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
219 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
220 })
221 : envOutput({ PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" });
222 },
223 });
224
225 assert.equal(
226 env.PATH,
227 [
228 "C:\\Profile\\Node",
229 "C:\\Windows\\System32",
230 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
231 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
232 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
233 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
234 "C:\\Users\\testuser\\.bun\\bin",
235 "C:\\Users\\testuser\\scoop\\shims",
236 "C:\\Custom\\Bin",
237 ].join(";"),
238 );
239 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
240 assert.equal(
241 env.FNM_MULTISHELL_PATH,
242 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
243 );
244 }),
245 );
246
247 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
248 Effect.gen(function* () {
249 const env: NodeJS.ProcessEnv = {
250 SHELL: "/bin/zsh",
251 PATH: "/usr/bin",
252 XDG_CURRENT_DESKTOP: "wrong-launcher",
253 XDG_SESSION_DESKTOP: "wrong-launcher",
254 };
255
256 yield* runShellEnvironment({
257 env,
258 platform: "linux",
259 handler: () =>
260 envOutput({
261 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
262 XDG_CURRENT_DESKTOP: "KDE",
263 XDG_SESSION_DESKTOP: "KDE",
264 XDG_SESSION_TYPE: "wayland",
265 }),
266 });
267
268 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
269 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
270 assert.equal(env.XDG_SESSION_TYPE, "wayland");
271 }),
272 );
273
274 it.effect("overrides stale dbus session addresses from the login shell", () =>
275 Effect.gen(function* () {
276 const env: NodeJS.ProcessEnv = {
277 SHELL: "/bin/zsh",
278 PATH: "/usr/bin",
279 DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
280 };
281
282 yield* runShellEnvironment({
283 env,
284 platform: "linux",
285 handler: () =>
286 envOutput({
287 PATH: "/usr/bin",
288 DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
289 }),
290 });
291
292 assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
293 }),
294 );
295
296 it("resolves dbus runtime dir candidates with existence checks", () => {
297 const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
298 env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
299 uid: 1000,
300 exists: (path) => path === "/run/user/1000/bus",
301 });
302
303 assert.equal(busPath, "unix:path=/run/user/1000/bus");
304 });
305
306 it.effect("logs command failures with safe probe context and the exact cause", () => {
307 const env: NodeJS.ProcessEnv = {
308 SHELL: "/bin/bash",
309 PATH: "/usr/bin",
310 };
311 const cause = PlatformError.systemError({
312 _tag: "PermissionDenied",
313 module: "ChildProcess",
314 method: "spawn",
315 pathOrDescriptor: "/bin/bash",
316 });
317 const messages: Array<unknown> = [];
318 const logger = Logger.make(({ message }) => {
319 messages.push(message);
320 });
321
322 return runShellEnvironment({
323 env,
324 platform: "linux",
325 handler: () => "",
326 failure: cause,
327 }).pipe(
328 Effect.andThen(
329 Effect.sync(() => {
330 const errors = messages
331 .flatMap((message) => (Array.isArray(message) ? message : [message]))
332 .filter(isDesktopShellEnvironmentCommandError);
333 assert.lengthOf(errors, 1);
334 assert.equal(errors[0]?.probe, "login-shell");
335 assert.equal(errors[0]?.executable, "bash");
336 assert.equal(errors[0]?.argumentCount, 2);
337 assert.notProperty(errors[0] ?? {}, "args");
338 assert.equal(errors[0]?.cause, cause);
339 assert.notInclude(errors[0]?.message ?? "", cause.message);
340 }),
341 ),
342 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
343 );
344 });
345});