Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as TestClock from "effect/testing/TestClock";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13
14import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
15import { SpawnExecutableResolution } from "@t3tools/shared/shell";
16import * as ExternalLauncher from "./externalLauncher.ts";
17
18function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
19 return ChildProcessSpawner.makeHandle({
20 pid: ChildProcessSpawner.ProcessId(1),
21 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
22 isRunning: Effect.succeed(true),
23 kill: () => Effect.void,
24 unref: Effect.sync(() => {
25 onUnref();
26 return Effect.void;
27 }),
28 stdin: Sink.drain,
29 stdout: Stream.empty,
30 stderr: Stream.empty,
31 all: Stream.empty,
32 getInputFd: () => Sink.drain,
33 getOutputFd: () => Stream.empty,
34 });
35}
36
37const testLayer = (input: {
38 readonly platform: NodeJS.Platform;
39 readonly env?: Record<string, string>;
40 readonly resolveExecutable?: (command: string) => string | undefined;
41 readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
42 readonly onUnref?: () => void;
43}) => {
44 const spawnerLayer = Layer.succeed(
45 ChildProcessSpawner.ChildProcessSpawner,
46 ChildProcessSpawner.make((command) =>
47 Effect.sync(() => {
48 assert.equal(ChildProcess.isStandardCommand(command), true);
49 if (!ChildProcess.isStandardCommand(command)) {
50 throw new Error("Expected a standard command");
51 }
52 input.onSpawn?.(command);
53 return makeMockDetachedHandle(input.onUnref);
54 }),
55 ),
56 );
57
58 return Layer.mergeAll(
59 ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer))),
60 Layer.succeed(HostProcessPlatform, input.platform),
61 Layer.succeed(
62 SpawnExecutableResolution,
63 (command) => input.resolveExecutable?.(command) ?? command,
64 ),
65 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
66 );
67};
68
69it.effect("launches the default browser through the platform command", () => {
70 let spawned: ChildProcess.StandardCommand | undefined;
71 let didUnref = false;
72 return Effect.gen(function* () {
73 const launcher = yield* ExternalLauncher.ExternalLauncher;
74
75 yield* launcher.launchBrowser("https://example.com/some path");
76
77 assert.ok(spawned);
78 assert.equal(spawned.command, "xdg-open");
79 assert.deepEqual(spawned.args, ["https://example.com/some path"]);
80 assert.equal(spawned.options.detached, true);
81 assert.equal(didUnref, true);
82 }).pipe(
83 Effect.provide(
84 testLayer({
85 platform: "linux",
86 onSpawn: (command) => {
87 spawned = command;
88 },
89 onUnref: () => {
90 didUnref = true;
91 },
92 }),
93 ),
94 );
95});
96
97it.effect("launches an installed editor with platform-safe arguments", () =>
98 Effect.gen(function* () {
99 const fileSystem = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
102 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
103
104 let spawned: ChildProcess.StandardCommand | undefined;
105 yield* Effect.gen(function* () {
106 const launcher = yield* ExternalLauncher.ExternalLauncher;
107 yield* launcher.launchEditor({
108 editor: "vscode",
109 cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
110 });
111 }).pipe(
112 Effect.provide(
113 testLayer({
114 platform: "win32",
115 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
116 resolveExecutable: (command) =>
117 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
118 onSpawn: (command) => {
119 spawned = command;
120 },
121 }),
122 ),
123 );
124
125 assert.ok(spawned);
126 assert.equal(spawned.command, '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"');
127 assert.deepEqual(spawned.args, [
128 '^"--goto^"',
129 '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
130 ]);
131 assert.equal(spawned.options.shell, true);
132 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
133);
134
135it.effect("discovers editors through the service API", () =>
136 Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
140 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
141 yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
142
143 const editors = yield* Effect.gen(function* () {
144 const launcher = yield* ExternalLauncher.ExternalLauncher;
145 return yield* launcher.resolveAvailableEditors();
146 }).pipe(
147 Effect.provide(
148 testLayer({
149 platform: "win32",
150 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
151 }),
152 ),
153 );
154
155 assert.equal(editors.includes("vscode"), true);
156 assert.equal(editors.includes("file-manager"), true);
157 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
158);
159
160it.effect("memoizes editor discovery and refreshes after the cache window", () => {
161 let statCalls = 0;
162 const fileInfo = { type: "File" } as FileSystem.File.Info;
163 const launcherLayer = ExternalLauncher.layer.pipe(
164 Layer.provide(
165 Layer.mergeAll(
166 FileSystem.layerNoop({
167 stat: () =>
168 Effect.sync(() => {
169 statCalls += 1;
170 return fileInfo;
171 }),
172 }),
173 Path.layer,
174 Layer.succeed(
175 ChildProcessSpawner.ChildProcessSpawner,
176 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
177 ),
178 ),
179 ),
180 );
181
182 return Effect.gen(function* () {
183 const launcher = yield* ExternalLauncher.ExternalLauncher;
184
185 const first = yield* launcher.resolveAvailableEditors();
186 assert.equal(first.includes("vscode"), true);
187 const statCallsAfterFirstScan = statCalls;
188 assert.isAbove(statCallsAfterFirstScan, 0);
189
190 // Past the shared command-resolution cache TTL (30s) but within the
191 // discovery cache window: the memoized set is reused without any scan.
192 yield* TestClock.adjust("31 seconds");
193 const second = yield* launcher.resolveAvailableEditors();
194 assert.deepEqual([...second], [...first]);
195 assert.equal(statCalls, statCallsAfterFirstScan);
196
197 // Past the discovery cache window the next call rescans.
198 yield* TestClock.adjust("30 seconds");
199 yield* launcher.resolveAvailableEditors();
200 assert.isAbove(statCalls, statCallsAfterFirstScan);
201 }).pipe(
202 Effect.provide(
203 Layer.mergeAll(
204 launcherLayer,
205 Layer.succeed(HostProcessPlatform, "win32"),
206 ConfigProvider.layer(
207 ConfigProvider.fromEnv({
208 env: {
209 PATH: "C:\\t3-editor-discovery-cache-test",
210 PATHEXT: ".COM;.EXE;.BAT;.CMD",
211 },
212 }),
213 ),
214 TestClock.layer(),
215 ),
216 ),
217 );
218});
219
220// A client that disconnects mid-scan interrupts the shared discovery effect on
221// the connection fiber. The cache must not retain that interrupt: doing so
222// replayed it to every later connect for the whole TTL, so `server.getConfig`
223// failed and no client could reconnect until the server restarted.
224it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => {
225 const fileInfo = { type: "File" } as FileSystem.File.Info;
226 let blockFirstScan = true;
227 let scans = 0;
228 const launcherLayer = ExternalLauncher.layer.pipe(
229 Layer.provide(
230 Layer.mergeAll(
231 FileSystem.layerNoop({
232 // The first scan parks inside `stat` so the interrupt lands while
233 // discovery is in flight, which is what a client disconnecting
234 // mid-connect does to the shared effect.
235 stat: () =>
236 Effect.gen(function* () {
237 scans += 1;
238 if (blockFirstScan) {
239 return yield* Effect.never;
240 }
241 return fileInfo;
242 }),
243 }),
244 Path.layer,
245 Layer.succeed(
246 ChildProcessSpawner.ChildProcessSpawner,
247 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
248 ),
249 ),
250 ),
251 );
252
253 return Effect.gen(function* () {
254 const launcher = yield* ExternalLauncher.ExternalLauncher;
255
256 const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
257 yield* Effect.yieldNow;
258 yield* Fiber.interrupt(fiber);
259
260 // The next connect must still get a real answer well inside the TTL.
261 blockFirstScan = false;
262 scans = 0;
263 const editors = yield* launcher.resolveAvailableEditors();
264 assert.equal(editors.includes("vscode"), true);
265 assert.isAbove(scans, 0);
266 }).pipe(
267 Effect.provide(
268 Layer.mergeAll(
269 launcherLayer,
270 Layer.succeed(HostProcessPlatform, "win32"),
271 ConfigProvider.layer(
272 ConfigProvider.fromEnv({
273 env: {
274 PATH: "C:\\t3-editor-discovery-interrupt-test",
275 PATHEXT: ".COM;.EXE;.BAT;.CMD",
276 },
277 }),
278 ),
279 ),
280 ),
281 );
282});
283
284it.effect("rejects unknown editors through the service API", () =>
285 Effect.gen(function* () {
286 const launcher = yield* ExternalLauncher.ExternalLauncher;
287 const error = yield* launcher
288 .launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
289 .pipe(Effect.flip);
290 assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
291 assert.equal(error.editor, "missing-editor");
292 assert.equal(error.message, "Unknown editor: missing-editor");
293 }).pipe(Effect.provide(testLayer({ platform: "linux", env: { PATH: "" } }))),
294);