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

os-jank.test.ts

337 lines11.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { CommandAvailability, WindowsShellEnvironment } from "@t3tools/shared/shell";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7// @effect-diagnostics-next-line nodeBuiltinImport:off -- Observe the existing synchronous shell probe without launching the user's login shell.
8import * as NodeChildProcess from "node:child_process";
9// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fake login shell is a script the real probe spawns.
10import * as NodeFS from "node:fs";
11import * as NodeOS from "node:os";
12// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fake login shell is a script the real probe spawns.
13import * as NodePath from "node:path";
14import { assert, it, vi } from "vite-plus/test";
15​
16import {
17 fixPath,
18 hydratePosixHome,
19 refreshPathFromLoginShell,
20 refreshWindowsPath,
21} from "./os-jank.ts";
22​
23vi.mock("node:child_process", { spy: true });
24​
25it("hydrates HOME independently of a blank process HOME", () => {
26 const originalHome = process.env.HOME;
27 const env: NodeJS.ProcessEnv = { HOME: " " };
28​
29 try {
30 process.env.HOME = " ";
31 hydratePosixHome(env);
32 } finally {
33 if (originalHome === undefined) {
34 delete process.env.HOME;
35 } else {
36 process.env.HOME = originalHome;
37 }
38 }
39​
40 assert.equal(env.HOME, NodeOS.userInfo().homedir);
41});
42​
43it("preserves an explicitly configured HOME", () => {
44 const env: NodeJS.ProcessEnv = { HOME: "/custom/home" };
45​
46 hydratePosixHome(env, () => {
47 throw new Error("HOME lookup should not run");
48 });
49​
50 assert.equal(env.HOME, "/custom/home");
51});
52​
53effectIt.effect("hydrates PATH when the desktop handoff is absent", () =>
54 Effect.acquireUseRelease(
55 Effect.sync(() =>
56 vi
57 .spyOn(NodeChildProcess, "execFileSync")
58 .mockReturnValue("__T3CODE_ENV_PATH_START__\n/opt/tools/bin\n__T3CODE_ENV_PATH_END__\n"),
59 ),
60 (probe) =>
61 Effect.gen(function* () {
62 const env: NodeJS.ProcessEnv = { SHELL: "/bin/bash", PATH: "/usr/bin" };
63​
64 yield* fixPath().pipe(
65 Effect.provideService(HostProcess.Platform, "linux"),
66 Effect.provideService(HostProcess.Environment, env),
67 Effect.provide(NodeServices.layer),
68 );
69​
70 assert.equal(probe.mock.calls.length, 1);
71 assert.equal(env.PATH, "/opt/tools/bin:/usr/bin");
72 }),
73 (probe) => Effect.sync(() => probe.mockRestore()),
74 ),
75);
76​
77// The inherited PATH already holds the absolute fallback dirs, so each case only
78// depends on whether the fixture HOME has ~/.local/bin, not on this host.
79effectIt.effect("falls back to existing CLI dirs when probes return no PATH", () =>
80 Effect.gen(function* () {
81 const fileSystem = yield* FileSystem.FileSystem;
82 const cases = [
83 {
84 localBin: true,
85 inherited: (home: string) =>
86 `${home}/.nvm/bin:/usr/local/bin:/usr/bin:/opt/homebrew/bin:/usr/bin`,
87 probe: "",
88 expected: (home: string) =>
89 `${home}/.nvm/bin:/usr/local/bin:/usr/bin:/opt/homebrew/bin:${home}/.local/bin`,
90 },
91 {
92 localBin: false,
93 inherited: () => "/usr/local/bin:/opt/homebrew/bin:/usr/bin",
94 probe: "",
95 expected: () => "/usr/local/bin:/opt/homebrew/bin:/usr/bin",
96 },
97 {
98 localBin: true,
99 inherited: () => "/usr/bin",
100 probe: "__T3CODE_ENV_PATH_START__\n/opt/tools/bin\n__T3CODE_ENV_PATH_END__\n",
101 expected: () => "/opt/tools/bin:/usr/bin",
102 },
103 ];
104​
105 for (const testCase of cases) {
106 const home = yield* fileSystem.makeTempDirectoryScoped();
107 if (testCase.localBin) {
108 yield* fileSystem.makeDirectory(`${home}/.local/bin`, { recursive: true });
109 }
110 const env: NodeJS.ProcessEnv = {
111 HOME: home,
112 SHELL: "/bin/zsh",
113 PATH: testCase.inherited(home),
114 };
115​
116 yield* Effect.acquireUseRelease(
117 Effect.sync(() =>
118 vi.spyOn(NodeChildProcess, "execFileSync").mockReturnValue(testCase.probe),
119 ),
120 () =>
121 fixPath().pipe(
122 Effect.provideService(HostProcess.Platform, "darwin"),
123 Effect.provideService(HostProcess.Environment, env),
124 ),
125 (probe) => Effect.sync(() => probe.mockRestore()),
126 );
127​
128 assert.equal(env.PATH, testCase.expected(home));
129 }
130 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
131);
132​
133const timedOut = (file: string) =>
134 Object.assign(new Error(`spawnSync ${file} ETIMEDOUT`), { code: "ETIMEDOUT" });
135​
136effectIt.effect("waits longer for a login shell that times out at startup", () =>
137 Effect.acquireUseRelease(
138 Effect.sync(() =>
139 vi.spyOn(NodeChildProcess, "execFileSync").mockImplementation((file, _args, options) => {
140 // This profile takes 8 seconds while the machine is under load.
141 if ((options?.timeout ?? 0) < 8_000) throw timedOut(String(file));
142 return "__T3CODE_ENV_PATH_START__\n/opt/tools/bin\n__T3CODE_ENV_PATH_END__\n";
143 }),
144 ),
145 () =>
146 Effect.gen(function* () {
147 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
148​
149 yield* fixPath().pipe(
150 Effect.provideService(HostProcess.Platform, "linux"),
151 Effect.provideService(HostProcess.Environment, env),
152 Effect.provide(NodeServices.layer),
153 );
154​
155 assert.equal(env.PATH, "/opt/tools/bin:/usr/bin");
156 }),
157 (probe) => Effect.sync(() => probe.mockRestore()),
158 ),
159);
160​
161effectIt.effect("waits longer for only one hung login shell", () =>
162 Effect.acquireUseRelease(
163 Effect.sync(() =>
164 vi.spyOn(NodeChildProcess, "execFileSync").mockImplementation((file) => {
165 throw timedOut(String(file));
166 }),
167 ),
168 (probe) =>
169 Effect.gen(function* () {
170 const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
171​
172 yield* fixPath().pipe(
173 Effect.provideService(HostProcess.Platform, "linux"),
174 Effect.provideService(HostProcess.Environment, env),
175 Effect.provide(NodeServices.layer),
176 );
177​
178 const timeouts = probe.mock.calls.map(([, , options]) => options?.timeout);
179 assert.equal(timeouts.filter((timeout) => (timeout ?? 0) > 5_000).length, 1);
180 }),
181 (probe) => Effect.sync(() => probe.mockRestore()),
182 ),
183);
184​
185effectIt.effect("keeps mise's PATH record with the login shell PATH", () =>
186 Effect.acquireUseRelease(
187 Effect.sync(() =>
188 vi
189 .spyOn(NodeChildProcess, "execFileSync")
190 .mockReturnValue(
191 [
192 "__T3CODE_ENV_PATH_START__",
193 "/home/me/.local/bin:/mise/installs/claude/latest:/mise/shims",
194 "__T3CODE_ENV_PATH_END__",
195 "__T3CODE_ENV___MISE_DIFF_START__",
196 "mise-diff",
197 "__T3CODE_ENV___MISE_DIFF_END__",
198 ].join("\n"),
199 ),
200 ),
201 () =>
202 Effect.gen(function* () {
203 const env: NodeJS.ProcessEnv = { SHELL: "/bin/bash", PATH: "/usr/bin" };
204​
205 yield* fixPath().pipe(
206 Effect.provideService(HostProcess.Platform, "linux"),
207 Effect.provideService(HostProcess.Environment, env),
208 Effect.provide(NodeServices.layer),
209 );
210​
211 assert.equal(env.__MISE_DIFF, "mise-diff");
212 }),
213 (probe) => Effect.sync(() => probe.mockRestore()),
214 ),
215);
216​
217effectIt.effect(
218 "hydrates missing JAVA_HOME and feature flags from the login shell and keeps explicit ones",
219 () =>
220 Effect.acquireUseRelease(
221 Effect.sync(() =>
222 vi
223 .spyOn(NodeChildProcess, "execFileSync")
224 .mockReturnValue(
225 [
226 "__T3CODE_ENV_PATH_START__",
227 "/opt/homebrew/bin",
228 "__T3CODE_ENV_PATH_END__",
229 "__T3CODE_ENV_JAVA_HOME_START__",
230 "/opt/homebrew/opt/openjdk@17",
231 "__T3CODE_ENV_JAVA_HOME_END__",
232 "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_START__",
233 "tanstack_source",
234 "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_END__",
235 ].join("\n"),
236 ),
237 ),
238 () =>
239 Effect.gen(function* () {
240 const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" };
241 const explicit: NodeJS.ProcessEnv = {
242 SHELL: "/bin/zsh",
243 PATH: "/usr/bin",
244 JAVA_HOME: "/custom/jdk",
245 T3CODE_FEATURE_FLAGS: "",
246 };
247​
248 for (const env of [missing, explicit]) {
249 yield* fixPath().pipe(
250 Effect.provideService(HostProcess.Platform, "darwin"),
251 Effect.provideService(HostProcess.Environment, env),
252 Effect.provide(NodeServices.layer),
253 );
254 }
255​
256 assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17");
257 assert.equal(explicit.JAVA_HOME, "/custom/jdk");
258 assert.equal(missing.T3CODE_FEATURE_FLAGS, "tanstack_source");
259 assert.equal(explicit.T3CODE_FEATURE_FLAGS, "");
260 }),
261 (probe) => Effect.sync(() => probe.mockRestore()),
262 ),
263);
264​
265// Like a profile running `eval "$(fnm env)"`: each login shell gets a new multishell folder.
266const fnmLoginShell = (dir: string) => {
267 const shell = NodePath.join(dir, "bash");
268 NodeFS.writeFileSync(
269 shell,
270 [
271 "#!/bin/sh",
272 `n=$(cat "${dir}/count" 2>/dev/null || echo 0); n=$((n + 1)); echo "$n" > "${dir}/count"`,
273 `multishell="/run/user/1000/fnm_multishells/$((1000 + n))_17956/bin"`,
274 // `fnm env` prepends to the server's PATH the shell inherited (handed over in `path`).
275 `path="$multishell:/home/me/.local/share/fnm:$(cat "${dir}/path")"`,
276 'printf "__T3CODE_ENV_PATH_START__\\n%s\\n__T3CODE_ENV_PATH_END__\\n" "$path"',
277 'printf "__T3CODE_ENV_FNM_MULTISHELL_PATH_START__\\n%s\\n__T3CODE_ENV_FNM_MULTISHELL_PATH_END__\\n" "${multishell%/bin}"',
278 ].join("\n"),
279 { mode: 0o755 },
280 );
281 return shell;
282};
283​
284effectIt.effect("re-reading an fnm login shell does not pile up its multishell folders", () =>
285 Effect.gen(function* () {
286 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-fnm-"));
287 const env: NodeJS.ProcessEnv = { SHELL: fnmLoginShell(dir), PATH: "/usr/bin" };
288​
289 for (let read = 0; read < 3; read++) {
290 NodeFS.writeFileSync(NodePath.join(dir, "path"), env.PATH ?? "");
291 yield* refreshPathFromLoginShell().pipe(
292 Effect.provideService(HostProcess.Platform, "linux"),
293 Effect.provideService(HostProcess.Environment, env),
294 Effect.provide(NodeServices.layer),
295 );
296 }
297 NodeFS.rmSync(dir, { recursive: true, force: true });
298​
299 const multishells = (env.PATH ?? "")
300 .split(":")
301 .filter((entry) => entry.includes("fnm_multishells"));
302 assert.isAtMost(multishells.length, 1, env.PATH);
303 }),
304);
305​
306effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
307 Effect.gen(function* () {
308 const env: NodeJS.ProcessEnv = { Path: "C:\\Windows" };
309​
310 yield* fixPath().pipe(
311 Effect.provideService(HostProcess.Platform, "win32"),
312 Effect.provideService(HostProcess.Environment, env),
313 Effect.provideService(WindowsShellEnvironment, () => Effect.succeed({ PATH: "C:\\Tools" })),
314 Effect.provideService(CommandAvailability, () => Effect.succeed(true)),
315 Effect.provide(NodeServices.layer),
316 );
317​
318 assert.deepEqual(env, { PATH: "C:\\Tools;C:\\Windows" });
319 }),
320);
321​
322effectIt.effect("adds a directory an installer wrote to the registry after launch", () =>
323 Effect.gen(function* () {
324 const env: NodeJS.ProcessEnv = { Path: "C:\\Tools;C:\\Windows" };
325 const installed = "C:\\Users\\me\\AppData\\Local\\cursor-agent";
326​
327 yield* refreshWindowsPath().pipe(
328 Effect.provideService(HostProcess.Platform, "win32"),
329 Effect.provideService(HostProcess.Environment, env),
330 Effect.provideService(WindowsShellEnvironment, () =>
331 Effect.succeed({ PATH: `C:\\Windows;${installed}` }),
332 ),
333 );
334​
335 assert.deepEqual(env, { PATH: `C:\\Tools;C:\\Windows;${installed}` });
336 }),
337);