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

window.test.ts

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