Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { ManagedPolicyLimits } from "@t3tools/contracts";
4import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts";
5import { resolveEditorCommand } from "@t3tools/shared/editor";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { makePathDirectoryListings, PathDirectoryListings } from "@t3tools/shared/shell";
8import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Stream from "effect/Stream";
15import * as TestClock from "effect/testing/TestClock";
16import { vi } from "vite-plus/test";
17import type * as Electron from "electron";
18
19const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({
20 focusedWebContents: vi.fn(),
21 ownerWindow: vi.fn(),
22}));
23vi.mock("electron", () => ({
24 webContents: { getFocusedWebContents: focusedWebContents },
25 BrowserWindow: { fromWebContents: ownerWindow },
26}));
27
28import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
29import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
30import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
31import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
32import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts";
33import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
34import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
35import * as ElectronDialog from "../../electron/ElectronDialog.ts";
36import * as ElectronWindow from "../../electron/ElectronWindow.ts";
37import * as IpcChannels from "../channels.ts";
38import * as DesktopIpc from "../DesktopIpc.ts";
39import {
40 getLocalEnvironmentBootstraps,
41 installRelayTelemetryEnabled,
42 pickProjectFavicon,
43 probeRemoteEditors,
44 readMedia,
45 syncHtmlFullscreen,
46 toLocalBackendPath,
47} from "./window.ts";
48
49const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
50 executablePath: "wsl.exe",
51 args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
52 entryPath: "/app/bin.mjs",
53 cwd: "/app",
54 env: {},
55 extendEnv: false,
56 bootstrap: {
57 mode: "desktop",
58 noBrowser: true,
59 port: 3774,
60 host: "0.0.0.0",
61 desktopBootstrapToken: "bootstrap-token",
62 tailscaleServeEnabled: false,
63 tailscaleServePort: 443,
64 },
65 bootstrapDelivery: "stdin",
66 httpBaseUrl: new URL("http://127.0.0.1:3774"),
67 captureOutput: true,
68 preflightFailure: Option.none(),
69 runningDistro: "Ubuntu",
70};
71
72const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
73 id: DesktopBackendManager.BackendInstanceId("wsl:default"),
74 label: Effect.succeed("WSL (default distro)"),
75 start: Effect.void,
76 stop: () => Effect.void,
77 currentConfig: Effect.succeedSome(readyWslConfig),
78 snapshot: Effect.succeed({
79 desiredRunning: true,
80 ready: true,
81 activePid: Option.some(123),
82 restartAttempt: 0,
83 restartScheduled: false,
84 }),
85 waitForReady: () => Effect.succeed(true),
86};
87
88const backendConfigurationLayer = Layer.succeed(
89 DesktopBackendConfiguration.DesktopBackendConfiguration,
90 {
91 resolvePrimary: Effect.die("unexpected resolvePrimary"),
92 resolvePrimaryLabel: Effect.succeed("Windows"),
93 resolveWsl: () => Effect.die("unexpected resolveWsl"),
94 currentBootstrapToken: Effect.succeed("current-window-token"),
95 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
96);
97
98const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopBackendInstance>) =>
99 Layer.merge(DesktopBackendPool.layerTest([...instances]), backendConfigurationLayer);
100
101describe("getLocalEnvironmentBootstraps", () => {
102 it.effect("hands out the current window's token to a backend launched with the secret", () =>
103 Effect.gen(function* () {
104 const result = yield* getLocalEnvironmentBootstraps.handler();
105
106 assert.deepEqual(result, [
107 {
108 id: "wsl:default",
109 label: "WSL (Ubuntu)",
110 runningDistro: "Ubuntu",
111 httpBaseUrl: "http://127.0.0.1:3774/",
112 wsBaseUrl: "ws://127.0.0.1:3774/",
113 bootstrapToken: "current-window-token",
114 },
115 ]);
116 }).pipe(
117 Effect.provide(
118 bootstrapsLayer([
119 {
120 ...defaultWslInstance,
121 currentConfig: Effect.succeedSome({
122 ...readyWslConfig,
123 bootstrap: {
124 ...readyWslConfig.bootstrap,
125 desktopBootstrapSecret: "desktop-secret",
126 },
127 }),
128 },
129 ]),
130 ),
131 ),
132 );
133
134 it.effect("includes the token only once the backend has reported ready", () =>
135 Effect.gen(function* () {
136 const result = yield* getLocalEnvironmentBootstraps.handler();
137
138 assert.deepEqual(result, [
139 {
140 id: "wsl:default",
141 label: "WSL (Ubuntu)",
142 runningDistro: "Ubuntu",
143 httpBaseUrl: "http://127.0.0.1:3774/",
144 wsBaseUrl: "ws://127.0.0.1:3774/",
145 },
146 ]);
147 }).pipe(
148 Effect.provide(
149 bootstrapsLayer([
150 {
151 ...defaultWslInstance,
152 snapshot: Effect.succeed({
153 desiredRunning: true,
154 ready: false,
155 activePid: Option.some(123),
156 restartAttempt: 0,
157 restartScheduled: false,
158 }),
159 },
160 ]),
161 ),
162 ),
163 );
164
165 it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
166 const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
167 ...readyWslConfig,
168 preflightFailure: Option.some({
169 reason: "WSL probe timed out",
170 fatal: false,
171 retryLimit: 12,
172 }),
173 };
174 const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
175 ...defaultWslInstance,
176 currentConfig: Effect.succeedSome(retryingConfig),
177 snapshot: Effect.succeed({
178 desiredRunning: true,
179 ready: false,
180 activePid: Option.none(),
181 restartAttempt: 2,
182 restartScheduled: true,
183 }),
184 };
185
186 return Effect.gen(function* () {
187 const result = yield* getLocalEnvironmentBootstraps.handler();
188 assert.deepEqual(result, [
189 {
190 id: "wsl:default",
191 label: "WSL (default distro)",
192 runningDistro: null,
193 httpBaseUrl: null,
194 wsBaseUrl: null,
195 },
196 ]);
197 }).pipe(Effect.provide(bootstrapsLayer([retryingInstance])));
198 });
199
200 it.effect("omits a bounded transient bootstrap after retries stop", () => {
201 const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
202 ...defaultWslInstance,
203 currentConfig: Effect.succeedSome({
204 ...readyWslConfig,
205 preflightFailure: Option.some({
206 reason: "WSL probe timed out",
207 fatal: false,
208 retryLimit: 12,
209 }),
210 }),
211 snapshot: Effect.succeed({
212 desiredRunning: false,
213 ready: false,
214 activePid: Option.none(),
215 restartAttempt: 12,
216 restartScheduled: false,
217 }),
218 };
219
220 return Effect.gen(function* () {
221 const result = yield* getLocalEnvironmentBootstraps.handler();
222 assert.deepEqual(result, []);
223 }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance])));
224 });
225});
226
227describe("toLocalBackendPath", () => {
228 const { runningDistro: _, ...windowsConfig } = readyWslConfig;
229 it.effect("converts paths through wslpath only for backends running in WSL", () =>
230 Effect.gen(function* () {
231 const convert = (backendId: string, path = "C:\\Users\\me\\project") =>
232 toLocalBackendPath.handler({ backendId, path });
233 assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project");
234 assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project");
235 assert.strictEqual(yield* convert("wsl:missing"), null);
236 assert.strictEqual(
237 yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"),
238 "/home/me/repo",
239 );
240 assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null);
241 assert.strictEqual(
242 yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"),
243 "\\\\wsl$\\Debian\\home\\me\\repo",
244 );
245 }).pipe(
246 Effect.provide(
247 Layer.mergeAll(
248 DesktopBackendPool.layerTest([
249 {
250 ...defaultWslInstance,
251 id: DesktopBackendManager.BackendInstanceId("primary"),
252 currentConfig: Effect.succeedSome(windowsConfig),
253 },
254 defaultWslInstance,
255 ]),
256 DesktopWslEnvironment.layerTest({
257 windowsToWslPath: (distro, windowsPath) =>
258 distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project"
259 ? Option.some("/drives/c/Users/me/project")
260 : Option.none(),
261 }),
262 ),
263 ),
264 ),
265 );
266});
267
268describe("installRelayTelemetryEnabled", () => {
269 // The renderer reads this over sync IPC, so the answer must not wait on the filesystem.
270 const relayTelemetryEnabled = (
271 env: NodeJS.ProcessEnv,
272 policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0],
273 loginShellEnv: NodeJS.ProcessEnv = {},
274 ) =>
275 Effect.gen(function* () {
276 const listeners = new Map<string, DesktopIpc.DesktopIpcSyncListener>();
277 const ipcMain: DesktopIpc.DesktopIpcMain = {
278 removeHandler: () => undefined,
279 handle: () => undefined,
280 removeAllListeners: (channel) => void listeners.delete(channel),
281 on: (channel, listener) => void listeners.set(channel, listener),
282 };
283 let discoveryFinished = false;
284 const ask = () => {
285 const event = { returnValue: undefined as unknown };
286 listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never);
287 return event.returnValue;
288 };
289 yield* installRelayTelemetryEnabled().pipe(
290 Effect.provideService(HostProcess.Environment, env),
291 Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, {
292 installIntoProcess: Effect.succeed(true),
293 awaitDiscovery: Effect.succeed(true),
294 awaitUserShellDiscovery: Effect.succeed(true),
295 discoveryFinished: Effect.sync(() => discoveryFinished),
296 updates: Stream.empty,
297 }),
298 Effect.provide(
299 Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)),
300 ),
301 );
302 const beforeDiscovery = ask();
303 // The login shell's values land in the process env after startup has installed handlers.
304 Object.assign(env, loginShellEnv);
305 discoveryFinished = true;
306 return { beforeDiscovery, afterDiscovery: ask() };
307 }).pipe(Effect.scoped);
308
309 it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
310 Effect.gen(function* () {
311 assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), {
312 beforeDiscovery: false,
313 afterDiscovery: false,
314 });
315 // Undecided until the login shell is read, so the renderer asks again instead of opting out.
316 assert.deepEqual(yield* relayTelemetryEnabled({}), {
317 beforeDiscovery: null,
318 afterDiscovery: true,
319 });
320 assert.deepEqual(
321 yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }),
322 { beforeDiscovery: null, afterDiscovery: false },
323 );
324 }),
325 );
326
327 it.effect("turns relay tracing off when the managed policy turns telemetry off", () =>
328 Effect.gen(function* () {
329 const policy = (limits: ManagedPolicyLimits) => ({
330 schemaVersion: 1 as const,
331 organization: "Example Corp",
332 limits,
333 });
334 const after = function* (...args: Parameters<typeof relayTelemetryEnabled>) {
335 return (yield* relayTelemetryEnabled(...args)).afterDiscovery;
336 };
337 assert.isFalse(yield* after({}, policy({ telemetry: false })));
338 assert.isTrue(yield* after({}, policy({ webhookTasks: false })));
339 // A policy that cannot be read fails closed.
340 assert.isFalse(
341 yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })),
342 );
343 }),
344 );
345});
346
347describe("readMedia", () => {
348 it.effect("reads http(s) media only for the main window", () =>
349 Effect.gen(function* () {
350 const mib = new Uint8Array(1024 * 1024);
351 const fetch = vi.fn(async (url: string) => {
352 if (url.endsWith("/missing.png")) return new Response("Not Found", { status: 404 });
353 if (url.endsWith("/small.png")) return new Response(new Uint8Array([1, 2]));
354 let sent = 0;
355 // 257 MiB from one reused chunk: over the cap without allocating it.
356 const huge = new ReadableStream<Uint8Array>({
357 pull: (controller) => (sent++ < 257 ? controller.enqueue(mib) : controller.close()),
358 });
359 return new Response(huge);
360 });
361 const main = {
362 webContents: { id: 1, session: { fetch } },
363 } as unknown as Electron.BrowserWindow;
364 const read = (url: string, senderId: number) =>
365 readMedia
366 .handler(url, { sender: { id: senderId } })
367 .pipe(
368 Effect.provide(
369 Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }),
370 ),
371 );
372
373 assert.strictEqual(yield* read("https://example.com/a.png", 2), null);
374 assert.strictEqual(yield* read("file:///etc/passwd", 1), null);
375 assert.strictEqual(fetch.mock.calls.length, 0);
376 assert.deepEqual(yield* read("https://example.com/small.png", 1), {
377 status: 200,
378 mimeType: "",
379 data: Buffer.from([1, 2]),
380 });
381 assert.deepEqual(yield* read("https://example.com/missing.png", 1), {
382 status: 404,
383 mimeType: "text/plain;charset=UTF-8",
384 data: new Uint8Array(),
385 });
386 assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), {
387 status: 413,
388 mimeType: "",
389 data: new Uint8Array(),
390 });
391 }),
392 );
393});
394
395describe("pickProjectFavicon", () => {
396 const pickerLayer = (
397 pickFiles: () => Effect.Effect<Array<string>>,
398 settings?: DesktopAppSettings.DesktopSettings,
399 ) =>
400 Layer.mergeAll(
401 Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
402 Layer.mock(ElectronWindow.ElectronWindow)({
403 focusedMainOrFirst: Effect.succeedNone,
404 }),
405 DesktopAppSettings.layerTest(settings),
406 );
407
408 it.effect("opens a single-image picker from the project directory", () =>
409 Effect.gen(function* () {
410 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
411 const result = yield* pickProjectFavicon
412 .handler("/project")
413 .pipe(Effect.provide(pickerLayer(pickFiles)));
414
415 assert.strictEqual(result, "/pictures/icon.png");
416 assert.deepEqual(pickFiles.mock.calls, [
417 [
418 {
419 owner: Option.none(),
420 defaultPath: Option.some("/project"),
421 multiple: false,
422 filters: [
423 {
424 name: "Images",
425 extensions: [
426 "avif",
427 "bmp",
428 "gif",
429 "ico",
430 "heic",
431 "heif",
432 "jpeg",
433 "jpg",
434 "png",
435 "svg",
436 "tif",
437 "tiff",
438 "webp",
439 "icns",
440 ],
441 },
442 ],
443 },
444 ],
445 ]);
446 }),
447 );
448
449 it.effect("does not open a picker while the local environment is off", () =>
450 Effect.gen(function* () {
451 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
452 const result = yield* pickProjectFavicon.handler("/project").pipe(
453 Effect.provide(
454 pickerLayer(pickFiles, {
455 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
456 localEnvironmentEnabled: false,
457 }),
458 ),
459 );
460
461 assert.strictEqual(result, null);
462 assert.strictEqual(pickFiles.mock.calls.length, 0);
463 }),
464 );
465});
466
467describe("syncHtmlFullscreen", () => {
468 const fullscreenWindow = (fullscreen: boolean, { animatedExit = false } = {}) => {
469 let current = fullscreen;
470 let exiting = false;
471 const queued: boolean[] = [];
472 const leaveListeners: Array<() => void> = [];
473 const leave = () => {
474 current = false;
475 for (const listener of leaveListeners) listener();
476 };
477 // Like macOS, an animated exit keeps reporting fullscreen and queues requests until it ends.
478 const setFullScreen = vi.fn((next: boolean) => {
479 if (exiting) queued.push(next);
480 else if (next) current = true;
481 else if (!current) return;
482 else if (animatedExit) exiting = true;
483 else leave();
484 });
485 const finishExit = () => {
486 exiting = false;
487 leave();
488 for (const next of queued.splice(0)) setFullScreen(next);
489 };
490 const window = {
491 webContents: { id: 1 },
492 isDestroyed: () => false,
493 isFullScreen: () => current,
494 setFullScreen,
495 on: (event: string, listener: () => void) => {
496 if (event === "leave-full-screen") leaveListeners.push(listener);
497 },
498 } as unknown as Electron.BrowserWindow;
499 const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) });
500 return { window, setFullScreen, finishExit, layer };
501 };
502 const fromMainRenderer = { sender: { id: 1 } };
503
504 it.effect("takes the screen for the app's own fullscreen element and gives it back", () => {
505 const { window, layer } = fullscreenWindow(false);
506 return Effect.gen(function* () {
507 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
508 assert.isTrue(window.isFullScreen());
509
510 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
511 assert.isFalse(window.isFullScreen());
512 }).pipe(Effect.provide(layer));
513 });
514
515 it.effect("keeps a window the user had already made fullscreen", () => {
516 const { window, setFullScreen, layer } = fullscreenWindow(true);
517 return Effect.gen(function* () {
518 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
519 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
520
521 assert.isTrue(window.isFullScreen());
522 assert.strictEqual(setFullScreen.mock.calls.length, 0);
523 }).pipe(Effect.provide(layer));
524 });
525
526 it.effect("hands the window back once the user leaves OS fullscreen during playback", () => {
527 const { window, layer } = fullscreenWindow(false);
528 return Effect.gen(function* () {
529 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
530 window.setFullScreen(false);
531 window.setFullScreen(true);
532 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
533
534 assert.isTrue(window.isFullScreen());
535 }).pipe(Effect.provide(layer));
536 });
537
538 it.effect("takes the screen again when the video returns during an animated exit", () => {
539 const { window, finishExit, layer } = fullscreenWindow(false, { animatedExit: true });
540 return Effect.gen(function* () {
541 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
542 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
543 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
544 finishExit();
545 assert.isTrue(window.isFullScreen());
546
547 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
548 finishExit();
549 assert.isFalse(window.isFullScreen());
550 }).pipe(Effect.provide(layer));
551 });
552});
553
554it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
555 "finds remote editors installed without PATH launchers",
556 () =>
557 Effect.gen(function* () {
558 const fs = yield* FileSystem.FileSystem;
559 const path = yield* Path.Path;
560 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-remote-editors-" });
561 for (const app of ["Cursor", "Visual Studio Code", "WebStorm"]) {
562 const executable = path.join(
563 home,
564 "Applications",
565 `${app}.app`,
566 app === "WebStorm" ? "Contents/MacOS/webstorm" : "Contents/Resources/app/bin/code",
567 );
568 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
569 yield* fs.writeFileString(executable, "#!/bin/sh\n");
570 yield* fs.chmod(executable, 0o755);
571 }
572 const editors = yield* probeRemoteEditors.handler(undefined).pipe(
573 Effect.provideService(HostProcess.Environment, {
574 HOME: home,
575 PATH: path.join(home, "empty"),
576 }),
577 Effect.provideService(HostProcess.Platform, "darwin"),
578 );
579 assert.include(editors, "cursor");
580 assert.include(editors, "vscode");
581 assert.include(editors, "webstorm");
582 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
583);
584
585describe("probeRemoteEditors PATH scan", () => {
586 const FIXTURE_MTIME = 1_767_225_600;
587 const platform = HostProcess.Platform.defaultValue();
588 const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command);
589
590 const makeFakePath = Effect.fnUntraced(function* () {
591 const fs = yield* FileSystem.FileSystem;
592 const path = yield* Path.Path;
593 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" });
594 const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name));
595 for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true });
596 // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order.
597 for (const [dir, command] of [
598 [dirs[2]!, "webstorm"],
599 [dirs[0]!, "cursor"],
600 [dirs[3]!, "code"],
601 [dirs[1]!, "zeditor"],
602 ] as const) {
603 const file = path.join(dir, launcherName(command));
604 yield* fs.writeFileString(file, "#!/bin/sh\n");
605 if (platform !== "win32") yield* fs.chmod(file, 0o755);
606 }
607 // A listing of a directory changed moments ago is not kept, so age them past that window.
608 for (const dir of dirs) yield* fs.utimes(dir, FIXTURE_MTIME, FIXTURE_MTIME);
609 yield* TestClock.setTime((FIXTURE_MTIME + 60) * 1000);
610 return {
611 root,
612 env: {
613 HOME: root,
614 USERPROFILE: root,
615 PATH: dirs.join(platform === "win32" ? ";" : ":"),
616 PATHEXT: ".COM;.EXE;.BAT;.CMD",
617 },
618 };
619 });
620
621 const countingFileSystem = (reads: Map<string, number>) =>
622 Layer.effect(
623 FileSystem.FileSystem,
624 Effect.gen(function* () {
625 const fs = yield* FileSystem.FileSystem;
626 return FileSystem.FileSystem.of({
627 ...fs,
628 readDirectory: (target, options) => {
629 reads.set(target, (reads.get(target) ?? 0) + 1);
630 return fs.readDirectory(target, options);
631 },
632 });
633 }),
634 ).pipe(Layer.provideMerge(NodeServices.layer));
635
636 const serialReference = (env: Record<string, string>) =>
637 Effect.gen(function* () {
638 const available: Array<string> = [];
639 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
640 const editor = EDITORS.find((candidate) => candidate.id === editorId);
641 if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
642 available.push(editorId);
643 }
644 }
645 return available;
646 });
647
648 it.effect("finds the editors a serial scan finds, listing each PATH directory at most once", () =>
649 Effect.gen(function* () {
650 const { env: baseEnv } = yield* makeFakePath();
651 const delimiter = platform === "win32" ? ";" : ":";
652 const reads = new Map<string, number>();
653 // Distinct PATH values keep one scan from answering the other out of the resolution cache.
654 const serialEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` };
655 const probeEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` };
656 const serial = yield* serialReference(serialEnv).pipe(
657 Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings),
658 );
659 const probed = yield* probeRemoteEditors
660 .handler(undefined)
661 .pipe(
662 Effect.provideService(HostProcess.Environment, probeEnv),
663 Effect.provideService(HostProcess.Platform, platform),
664 Effect.provide(countingFileSystem(reads)),
665 Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings),
666 );
667 // The host can add editors from app folders the fixture can't redirect (e.g. /Applications).
668 const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"];
669 assert.deepStrictEqual(
670 serial.filter((id) => fixtureEditors.includes(id)),
671 fixtureEditors,
672 );
673 assert.deepStrictEqual(probed, serial);
674 // Only PATH entries count: resolveEditorCommand also reads app folders such as /Applications
675 // on macOS. PATH directories are listed on Windows only, once even for concurrent probes.
676 const pathReads = probeEnv.PATH.split(delimiter)
677 .filter((entry) => entry.length > 0)
678 .map((entry) => reads.get(entry) ?? 0);
679 assert.strictEqual(Math.max(...pathReads), platform === "win32" ? 1 : 0);
680 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
681 );
682});