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