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 * as HostProcess from "@t3tools/shared/HostProcess";
5import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import { vi } from "vite-plus/test";
12import type * as Electron from "electron";
13
14const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({
15 focusedWebContents: vi.fn(),
16 ownerWindow: vi.fn(),
17}));
18vi.mock("electron", () => ({
19 webContents: { getFocusedWebContents: focusedWebContents },
20 BrowserWindow: { fromWebContents: ownerWindow },
21}));
22
23import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
24import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
25import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
26import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
27import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
28import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
29import * as ElectronDialog from "../../electron/ElectronDialog.ts";
30import * as ElectronWindow from "../../electron/ElectronWindow.ts";
31import * as IpcChannels from "../channels.ts";
32import * as DesktopIpc from "../DesktopIpc.ts";
33import {
34 getLocalEnvironmentBootstraps,
35 installRelayTelemetryEnabled,
36 pickProjectFavicon,
37 probeRemoteEditors,
38 readMedia,
39 syncHtmlFullscreen,
40 toLocalBackendPath,
41} from "./window.ts";
42
43const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
44 executablePath: "wsl.exe",
45 args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
46 entryPath: "/app/bin.mjs",
47 cwd: "/app",
48 env: {},
49 extendEnv: false,
50 bootstrap: {
51 mode: "desktop",
52 noBrowser: true,
53 port: 3774,
54 host: "0.0.0.0",
55 desktopBootstrapToken: "bootstrap-token",
56 tailscaleServeEnabled: false,
57 tailscaleServePort: 443,
58 },
59 bootstrapDelivery: "stdin",
60 httpBaseUrl: new URL("http://127.0.0.1:3774"),
61 captureOutput: true,
62 preflightFailure: Option.none(),
63 runningDistro: "Ubuntu",
64};
65
66const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
67 id: DesktopBackendManager.BackendInstanceId("wsl:default"),
68 label: Effect.succeed("WSL (default distro)"),
69 start: Effect.void,
70 stop: () => Effect.void,
71 currentConfig: Effect.succeedSome(readyWslConfig),
72 snapshot: Effect.succeed({
73 desiredRunning: true,
74 ready: true,
75 activePid: Option.some(123),
76 restartAttempt: 0,
77 restartScheduled: false,
78 }),
79 waitForReady: () => Effect.succeed(true),
80};
81
82const backendConfigurationLayer = Layer.succeed(
83 DesktopBackendConfiguration.DesktopBackendConfiguration,
84 {
85 resolvePrimary: Effect.die("unexpected resolvePrimary"),
86 resolvePrimaryLabel: Effect.succeed("Windows"),
87 resolveWsl: () => Effect.die("unexpected resolveWsl"),
88 currentBootstrapToken: Effect.succeed("current-window-token"),
89 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
90);
91
92const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopBackendInstance>) =>
93 Layer.merge(DesktopBackendPool.layerTest([...instances]), backendConfigurationLayer);
94
95describe("getLocalEnvironmentBootstraps", () => {
96 it.effect("hands out the current window's token to a backend launched with the secret", () =>
97 Effect.gen(function* () {
98 const result = yield* getLocalEnvironmentBootstraps.handler();
99
100 assert.deepEqual(result, [
101 {
102 id: "wsl:default",
103 label: "WSL (Ubuntu)",
104 runningDistro: "Ubuntu",
105 httpBaseUrl: "http://127.0.0.1:3774/",
106 wsBaseUrl: "ws://127.0.0.1:3774/",
107 bootstrapToken: "current-window-token",
108 },
109 ]);
110 }).pipe(
111 Effect.provide(
112 bootstrapsLayer([
113 {
114 ...defaultWslInstance,
115 currentConfig: Effect.succeedSome({
116 ...readyWslConfig,
117 bootstrap: {
118 ...readyWslConfig.bootstrap,
119 desktopBootstrapSecret: "desktop-secret",
120 },
121 }),
122 },
123 ]),
124 ),
125 ),
126 );
127
128 it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
129 const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
130 ...readyWslConfig,
131 preflightFailure: Option.some({
132 reason: "WSL probe timed out",
133 fatal: false,
134 retryLimit: 12,
135 }),
136 };
137 const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
138 ...defaultWslInstance,
139 currentConfig: Effect.succeedSome(retryingConfig),
140 snapshot: Effect.succeed({
141 desiredRunning: true,
142 ready: false,
143 activePid: Option.none(),
144 restartAttempt: 2,
145 restartScheduled: true,
146 }),
147 };
148
149 return Effect.gen(function* () {
150 const result = yield* getLocalEnvironmentBootstraps.handler();
151 assert.deepEqual(result, [
152 {
153 id: "wsl:default",
154 label: "WSL (default distro)",
155 runningDistro: null,
156 httpBaseUrl: null,
157 wsBaseUrl: null,
158 },
159 ]);
160 }).pipe(Effect.provide(bootstrapsLayer([retryingInstance])));
161 });
162
163 it.effect("omits a bounded transient bootstrap after retries stop", () => {
164 const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
165 ...defaultWslInstance,
166 currentConfig: Effect.succeedSome({
167 ...readyWslConfig,
168 preflightFailure: Option.some({
169 reason: "WSL probe timed out",
170 fatal: false,
171 retryLimit: 12,
172 }),
173 }),
174 snapshot: Effect.succeed({
175 desiredRunning: false,
176 ready: false,
177 activePid: Option.none(),
178 restartAttempt: 12,
179 restartScheduled: false,
180 }),
181 };
182
183 return Effect.gen(function* () {
184 const result = yield* getLocalEnvironmentBootstraps.handler();
185 assert.deepEqual(result, []);
186 }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance])));
187 });
188});
189
190describe("toLocalBackendPath", () => {
191 const { runningDistro: _, ...windowsConfig } = readyWslConfig;
192 it.effect("converts paths through wslpath only for backends running in WSL", () =>
193 Effect.gen(function* () {
194 const convert = (backendId: string, path = "C:\\Users\\me\\project") =>
195 toLocalBackendPath.handler({ backendId, path });
196 assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project");
197 assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project");
198 assert.strictEqual(yield* convert("wsl:missing"), null);
199 assert.strictEqual(
200 yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"),
201 "/home/me/repo",
202 );
203 assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null);
204 assert.strictEqual(
205 yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"),
206 "\\\\wsl$\\Debian\\home\\me\\repo",
207 );
208 }).pipe(
209 Effect.provide(
210 Layer.mergeAll(
211 DesktopBackendPool.layerTest([
212 {
213 ...defaultWslInstance,
214 id: DesktopBackendManager.BackendInstanceId("primary"),
215 currentConfig: Effect.succeedSome(windowsConfig),
216 },
217 defaultWslInstance,
218 ]),
219 DesktopWslEnvironment.layerTest({
220 windowsToWslPath: (distro, windowsPath) =>
221 distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project"
222 ? Option.some("/drives/c/Users/me/project")
223 : Option.none(),
224 }),
225 ),
226 ),
227 ),
228 );
229});
230
231describe("installRelayTelemetryEnabled", () => {
232 // The renderer reads this over sync IPC, so the answer must not wait on the filesystem.
233 const relayTelemetryEnabled = (
234 env: NodeJS.ProcessEnv,
235 policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0],
236 ) =>
237 Effect.gen(function* () {
238 const listeners = new Map<string, DesktopIpc.DesktopIpcSyncListener>();
239 const ipcMain: DesktopIpc.DesktopIpcMain = {
240 removeHandler: () => undefined,
241 handle: () => undefined,
242 removeAllListeners: (channel) => void listeners.delete(channel),
243 on: (channel, listener) => void listeners.set(channel, listener),
244 };
245 yield* installRelayTelemetryEnabled().pipe(
246 Effect.provideService(HostProcess.Environment, env),
247 Effect.provide(
248 Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)),
249 ),
250 );
251 const event = { returnValue: undefined as unknown };
252 listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never);
253 return event.returnValue;
254 }).pipe(Effect.scoped);
255
256 it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
257 Effect.gen(function* () {
258 assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }));
259 assert.isTrue(yield* relayTelemetryEnabled({}));
260 }),
261 );
262
263 it.effect("turns relay tracing off when the managed policy turns telemetry off", () =>
264 Effect.gen(function* () {
265 const policy = (limits: ManagedPolicyLimits) => ({
266 schemaVersion: 1 as const,
267 organization: "Example Corp",
268 limits,
269 });
270 assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false })));
271 assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false })));
272 // A policy that cannot be read fails closed.
273 assert.isFalse(
274 yield* relayTelemetryEnabled(
275 {},
276 new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }),
277 ),
278 );
279 }),
280 );
281});
282
283describe("readMedia", () => {
284 it.effect("reads http(s) media only for the main window", () =>
285 Effect.gen(function* () {
286 const mib = new Uint8Array(1024 * 1024);
287 const fetch = vi.fn(async (url: string) => {
288 if (url.endsWith("/missing.png")) return new Response("Not Found", { status: 404 });
289 if (url.endsWith("/small.png")) return new Response(new Uint8Array([1, 2]));
290 let sent = 0;
291 // 257 MiB from one reused chunk: over the cap without allocating it.
292 const huge = new ReadableStream<Uint8Array>({
293 pull: (controller) => (sent++ < 257 ? controller.enqueue(mib) : controller.close()),
294 });
295 return new Response(huge);
296 });
297 const main = {
298 webContents: { id: 1, session: { fetch } },
299 } as unknown as Electron.BrowserWindow;
300 const read = (url: string, senderId: number) =>
301 readMedia
302 .handler(url, { sender: { id: senderId } })
303 .pipe(
304 Effect.provide(
305 Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }),
306 ),
307 );
308
309 assert.strictEqual(yield* read("https://example.com/a.png", 2), null);
310 assert.strictEqual(yield* read("file:///etc/passwd", 1), null);
311 assert.strictEqual(fetch.mock.calls.length, 0);
312 assert.deepEqual(yield* read("https://example.com/small.png", 1), {
313 status: 200,
314 mimeType: "",
315 data: Buffer.from([1, 2]),
316 });
317 assert.deepEqual(yield* read("https://example.com/missing.png", 1), {
318 status: 404,
319 mimeType: "text/plain;charset=UTF-8",
320 data: new Uint8Array(),
321 });
322 assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), {
323 status: 413,
324 mimeType: "",
325 data: new Uint8Array(),
326 });
327 }),
328 );
329});
330
331describe("pickProjectFavicon", () => {
332 const pickerLayer = (
333 pickFiles: () => Effect.Effect<Array<string>>,
334 settings?: DesktopAppSettings.DesktopSettings,
335 ) =>
336 Layer.mergeAll(
337 Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
338 Layer.mock(ElectronWindow.ElectronWindow)({
339 focusedMainOrFirst: Effect.succeedNone,
340 }),
341 DesktopAppSettings.layerTest(settings),
342 );
343
344 it.effect("opens a single-image picker from the project directory", () =>
345 Effect.gen(function* () {
346 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
347 const result = yield* pickProjectFavicon
348 .handler("/project")
349 .pipe(Effect.provide(pickerLayer(pickFiles)));
350
351 assert.strictEqual(result, "/pictures/icon.png");
352 assert.deepEqual(pickFiles.mock.calls, [
353 [
354 {
355 owner: Option.none(),
356 defaultPath: Option.some("/project"),
357 multiple: false,
358 filters: [
359 {
360 name: "Images",
361 extensions: [
362 "avif",
363 "bmp",
364 "gif",
365 "ico",
366 "heic",
367 "heif",
368 "jpeg",
369 "jpg",
370 "png",
371 "svg",
372 "tif",
373 "tiff",
374 "webp",
375 "icns",
376 ],
377 },
378 ],
379 },
380 ],
381 ]);
382 }),
383 );
384
385 it.effect("does not open a picker while the local environment is off", () =>
386 Effect.gen(function* () {
387 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
388 const result = yield* pickProjectFavicon.handler("/project").pipe(
389 Effect.provide(
390 pickerLayer(pickFiles, {
391 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
392 localEnvironmentEnabled: false,
393 }),
394 ),
395 );
396
397 assert.strictEqual(result, null);
398 assert.strictEqual(pickFiles.mock.calls.length, 0);
399 }),
400 );
401});
402
403describe("syncHtmlFullscreen", () => {
404 const fullscreenWindow = (fullscreen: boolean, { animatedExit = false } = {}) => {
405 let current = fullscreen;
406 let exiting = false;
407 const queued: boolean[] = [];
408 const leaveListeners: Array<() => void> = [];
409 const leave = () => {
410 current = false;
411 for (const listener of leaveListeners) listener();
412 };
413 // Like macOS, an animated exit keeps reporting fullscreen and queues requests until it ends.
414 const setFullScreen = vi.fn((next: boolean) => {
415 if (exiting) queued.push(next);
416 else if (next) current = true;
417 else if (!current) return;
418 else if (animatedExit) exiting = true;
419 else leave();
420 });
421 const finishExit = () => {
422 exiting = false;
423 leave();
424 for (const next of queued.splice(0)) setFullScreen(next);
425 };
426 const window = {
427 webContents: { id: 1 },
428 isDestroyed: () => false,
429 isFullScreen: () => current,
430 setFullScreen,
431 on: (event: string, listener: () => void) => {
432 if (event === "leave-full-screen") leaveListeners.push(listener);
433 },
434 } as unknown as Electron.BrowserWindow;
435 const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) });
436 return { window, setFullScreen, finishExit, layer };
437 };
438 const fromMainRenderer = { sender: { id: 1 } };
439
440 it.effect("takes the screen for the app's own fullscreen element and gives it back", () => {
441 const { window, layer } = fullscreenWindow(false);
442 return Effect.gen(function* () {
443 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
444 assert.isTrue(window.isFullScreen());
445
446 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
447 assert.isFalse(window.isFullScreen());
448 }).pipe(Effect.provide(layer));
449 });
450
451 it.effect("keeps a window the user had already made fullscreen", () => {
452 const { window, setFullScreen, layer } = fullscreenWindow(true);
453 return Effect.gen(function* () {
454 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
455 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
456
457 assert.isTrue(window.isFullScreen());
458 assert.strictEqual(setFullScreen.mock.calls.length, 0);
459 }).pipe(Effect.provide(layer));
460 });
461
462 it.effect("hands the window back once the user leaves OS fullscreen during playback", () => {
463 const { window, layer } = fullscreenWindow(false);
464 return Effect.gen(function* () {
465 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
466 window.setFullScreen(false);
467 window.setFullScreen(true);
468 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
469
470 assert.isTrue(window.isFullScreen());
471 }).pipe(Effect.provide(layer));
472 });
473
474 it.effect("takes the screen again when the video returns during an animated exit", () => {
475 const { window, finishExit, layer } = fullscreenWindow(false, { animatedExit: true });
476 return Effect.gen(function* () {
477 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
478 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
479 yield* syncHtmlFullscreen.handler(true, fromMainRenderer);
480 finishExit();
481 assert.isTrue(window.isFullScreen());
482
483 yield* syncHtmlFullscreen.handler(false, fromMainRenderer);
484 finishExit();
485 assert.isFalse(window.isFullScreen());
486 }).pipe(Effect.provide(layer));
487 });
488});
489
490it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
491 "finds remote editors installed without PATH launchers",
492 () =>
493 Effect.gen(function* () {
494 const fs = yield* FileSystem.FileSystem;
495 const path = yield* Path.Path;
496 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-remote-editors-" });
497 for (const app of ["Cursor", "Visual Studio Code", "WebStorm"]) {
498 const executable = path.join(
499 home,
500 "Applications",
501 `${app}.app`,
502 app === "WebStorm" ? "Contents/MacOS/webstorm" : "Contents/Resources/app/bin/code",
503 );
504 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
505 yield* fs.writeFileString(executable, "#!/bin/sh\n");
506 yield* fs.chmod(executable, 0o755);
507 }
508 const editors = yield* probeRemoteEditors.handler(undefined).pipe(
509 Effect.provideService(HostProcess.Environment, {
510 HOME: home,
511 PATH: path.join(home, "empty"),
512 }),
513 Effect.provideService(HostProcess.Platform, "darwin"),
514 );
515 assert.include(editors, "cursor");
516 assert.include(editors, "vscode");
517 assert.include(editors, "webstorm");
518 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
519);