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

window.test.ts

651 lines24.2 KB

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