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

DesktopShellEnvironment.test.ts

346 lines10.9 KB

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");
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 });
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 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);
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\\.local\\bin",
235 "C:\\Users\\testuser\\.bun\\bin",
236 "C:\\Users\\testuser\\scoop\\shims",
237 "C:\\Custom\\Bin",
238 ].join(";"),
239 );
240 assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
241 assert.equal(
242 env.FNM_MULTISHELL_PATH,
243 "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
244 );
245 }),
246 );
247​
248 it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
249 Effect.gen(function* () {
250 const env: NodeJS.ProcessEnv = {
251 SHELL: "/bin/zsh",
252 PATH: "/usr/bin",
253 XDG_CURRENT_DESKTOP: "wrong-launcher",
254 XDG_SESSION_DESKTOP: "wrong-launcher",
255 };
256​
257 yield* runShellEnvironment({
258 env,
259 platform: "linux",
260 handler: () =>
261 envOutput({
262 PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
263 XDG_CURRENT_DESKTOP: "KDE",
264 XDG_SESSION_DESKTOP: "KDE",
265 XDG_SESSION_TYPE: "wayland",
266 }),
267 });
268​
269 assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
270 assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
271 assert.equal(env.XDG_SESSION_TYPE, "wayland");
272 }),
273 );
274​
275 it.effect("overrides stale dbus session addresses from the login shell", () =>
276 Effect.gen(function* () {
277 const env: NodeJS.ProcessEnv = {
278 SHELL: "/bin/zsh",
279 PATH: "/usr/bin",
280 DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
281 };
282​
283 yield* runShellEnvironment({
284 env,
285 platform: "linux",
286 handler: () =>
287 envOutput({
288 PATH: "/usr/bin",
289 DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
290 }),
291 });
292​
293 assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
294 }),
295 );
296​
297 it("resolves dbus runtime dir candidates with existence checks", () => {
298 const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
299 env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
300 uid: 1000,
301 exists: (path) => path === "/run/user/1000/bus",
302 });
303​
304 assert.equal(busPath, "unix:path=/run/user/1000/bus");
305 });
306​
307 it.effect("logs command failures with safe probe context and the exact cause", () => {
308 const env: NodeJS.ProcessEnv = {
309 SHELL: "/bin/bash",
310 PATH: "/usr/bin",
311 };
312 const cause = PlatformError.systemError({
313 _tag: "PermissionDenied",
314 module: "ChildProcess",
315 method: "spawn",
316 pathOrDescriptor: "/bin/bash",
317 });
318 const messages: Array<unknown> = [];
319 const logger = Logger.make(({ message }) => {
320 messages.push(message);
321 });
322​
323 return runShellEnvironment({
324 env,
325 platform: "linux",
326 handler: () => "",
327 failure: cause,
328 }).pipe(
329 Effect.andThen(
330 Effect.sync(() => {
331 const errors = messages
332 .flatMap((message) => (Array.isArray(message) ? message : [message]))
333 .filter(isDesktopShellEnvironmentCommandError);
334 assert.lengthOf(errors, 1);
335 assert.equal(errors[0]?.probe, "login-shell");
336 assert.equal(errors[0]?.executable, "bash");
337 assert.equal(errors[0]?.argumentCount, 2);
338 assert.notProperty(errors[0] ?? {}, "args");
339 assert.equal(errors[0]?.cause, cause);
340 assert.notInclude(errors[0]?.message ?? "", cause.message);
341 }),
342 ),
343 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
344 );
345 });
346});