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

DesktopWindow.test.ts

1,099 lines43.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import * as Option from "effect/Option";
9import * as Ref from "effect/Ref";
10import * as References from "effect/References";
11import * as Schema from "effect/Schema";
12import * as TestClock from "effect/testing/TestClock";
13​
14import * as Electron from "electron";
15import { vi } from "vite-plus/test";
16​
17vi.mock("electron", async (importOriginal) => ({
18 ...(await importOriginal<typeof import("electron")>()),
19 session: {
20 fromPartition: vi.fn(() => ({
21 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
22 setPermissionRequestHandler: vi.fn(),
23 setUserAgent: vi.fn(),
24 })),
25 },
26 screen: {
27 getAllDisplays: vi.fn(() => [
28 {
29 bounds: { x: 0, y: 0, width: 1920, height: 1080 },
30 },
31 ]),
32 },
33}));
34​
35import * as DesktopAssets from "../app/DesktopAssets.ts";
36import * as DesktopConfig from "../app/DesktopConfig.ts";
37import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
38import * as DesktopState from "../app/DesktopState.ts";
39import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
40import * as ElectronMenu from "../electron/ElectronMenu.ts";
41import * as ElectronShell from "../electron/ElectronShell.ts";
42import * as ElectronTheme from "../electron/ElectronTheme.ts";
43import * as ElectronWindow from "../electron/ElectronWindow.ts";
44import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
45import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
46import * as DesktopWindow from "./DesktopWindow.ts";
47import * as PreviewManager from "../preview/Manager.ts";
48​
49const environmentInput = {
50 dirname: "/repo/apps/desktop/dist-electron",
51 homeDirectory: "/Users/alice",
52 platform: "darwin",
53 processArch: "arm64",
54 appVersion: "1.2.3",
55 appPath: "/repo",
56 isPackaged: false,
57 resourcesPath: "/repo/resources",
58 runningUnderArm64Translation: false,
59} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
60​
61function makeFakeBrowserWindow() {
62 const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
63 const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
64 const webContents = {
65 copyImageAt: vi.fn(),
66 getURL: vi.fn(() => "t3code-dev://app/"),
67 isLoadingMainFrame: vi.fn(() => false),
68 on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
69 webContentsListeners.set(eventName, listener);
70 }),
71 once: vi.fn(),
72 openDevTools: vi.fn(),
73 reload: vi.fn(),
74 replaceMisspelling: vi.fn(),
75 send: vi.fn(),
76 setWindowOpenHandler: vi.fn(),
77 };
78​
79 const window = {
80 close: vi.fn(),
81 focus: vi.fn(),
82 getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
83 getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
84 isDestroyed: vi.fn(() => false),
85 isFullScreen: vi.fn(() => false),
86 isMaximized: vi.fn(() => false),
87 isMinimized: vi.fn(() => false),
88 isVisible: vi.fn(() => true),
89 loadURL: vi.fn(() => Promise.resolve()),
90 maximize: vi.fn(),
91 on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
92 windowListeners.set(eventName, listener);
93 }),
94 once: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
95 windowListeners.set(eventName, listener);
96 }),
97 restore: vi.fn(),
98 setBackgroundColor: vi.fn(),
99 setAutoHideCursor: vi.fn(),
100 setTitle: vi.fn(),
101 setTitleBarOverlay: vi.fn(),
102 show: vi.fn(),
103 webContents,
104 };
105​
106 return {
107 window: window as unknown as Electron.BrowserWindow,
108 getBounds: window.getBounds,
109 getNormalBounds: window.getNormalBounds,
110 isDestroyed: window.isDestroyed,
111 isFullScreen: window.isFullScreen,
112 isMaximized: window.isMaximized,
113 isMinimized: window.isMinimized,
114 loadURL: window.loadURL,
115 maximize: window.maximize,
116 openDevTools: webContents.openDevTools,
117 reload: webContents.reload,
118 send: webContents.send,
119 setAutoHideCursor: window.setAutoHideCursor,
120 webContentsListeners,
121 windowListeners,
122 };
124​
125const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
126 iconPaths: Effect.succeed({
127 ico: Option.none<string>(),
128 icns: Option.none<string>(),
129 png: Option.none<string>(),
130 }),
131 resolveResourcePath: () => Effect.succeed(Option.none<string>()),
132} satisfies DesktopAssets.DesktopAssets["Service"]);
133​
134const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
135 getState: Effect.die("unexpected getState"),
136 backendConfig: Effect.succeed({
137 port: 3773,
138 bindHost: "127.0.0.1",
139 httpBaseUrl: new URL("http://127.0.0.1:3773"),
140 tailscaleServeEnabled: false,
141 tailscaleServePort: 443,
142 }),
143 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
144 setMode: () => Effect.die("unexpected setMode"),
145 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
146 getAdvertisedEndpoints: Effect.die("unexpected getAdvertisedEndpoints"),
147} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
148​
149const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
150 setApplicationMenu: () => Effect.void,
151 popupTemplate: () => Effect.void,
152 showContextMenu: () => Effect.succeed(Option.none()),
153} satisfies ElectronMenu.ElectronMenu["Service"]);
154​
155const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
156 shouldUseDarkColors: Effect.succeed(false),
157 setSource: () => Effect.void,
158 onUpdated: () => Effect.void,
159} satisfies ElectronTheme.ElectronTheme["Service"]);
160​
161const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
162 Layer.provide(
163 Layer.mergeAll(
164 NodeServices.layer,
165 DesktopConfig.layerTest({
166 T3CODE_PORT: "3773",
167 VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
168 }),
169 ),
170 ),
171);
172​
173const desktopWindowBoundsEquivalence = Schema.toEquivalence(
174 DesktopAppSettings.DesktopWindowBoundsSchema,
175);
176​
177function makeTestLayer(input: {
178 readonly window: Electron.BrowserWindow;
179 readonly createCount: Ref.Ref<number>;
180 readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
181 readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
182 readonly desktopSettings?: DesktopAppSettings.DesktopSettings;
183 readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[];
184 readonly mainWindowMaximizedUpdates?: boolean[];
185 readonly beforeMainWindowBoundsUpdate?: (
186 bounds: DesktopAppSettings.DesktopWindowBounds,
187 ) => Effect.Effect<void>;
188 readonly openedExternalUrls?: unknown[];
189}) {
190 let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
191 const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
192 get: Effect.sync(() => desktopSettings),
193 load: Effect.sync(() => desktopSettings),
194 setMainWindowBounds: (bounds, isMaximized) =>
195 Effect.gen(function* () {
196 if (input.beforeMainWindowBoundsUpdate) {
197 yield* input.beforeMainWindowBoundsUpdate(bounds);
198 }
199 const changed =
200 desktopSettings.mainWindowBounds === null ||
201 !desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) ||
202 desktopSettings.mainWindowMaximized !== isMaximized;
203 if (changed) {
204 desktopSettings = {
205 ...desktopSettings,
206 mainWindowBounds: bounds,
207 mainWindowMaximized: isMaximized,
208 };
209 input.mainWindowBoundsUpdates?.push(bounds);
210 input.mainWindowMaximizedUpdates?.push(isMaximized);
211 }
212 return { settings: desktopSettings, changed };
213 }),
214 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
215 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
216 setUpdateChannel: () => Effect.die("unexpected update channel change"),
217 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
218 setWslDistro: () => Effect.die("unexpected WSL distro change"),
219 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
220 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
221 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
222 } satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
223​
224 const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
225 create: (options) =>
226 Effect.sync(() => {
227 input.createdWindowOptions?.push(options);
228 }).pipe(
229 Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
230 Effect.as(input.window),
231 ),
232 main: Ref.get(input.mainWindow),
233 currentMainOrFirst: Ref.get(input.mainWindow),
234 focusedMainOrFirst: Ref.get(input.mainWindow),
235 setMain: (window) => Ref.set(input.mainWindow, Option.some(window)),
236 clearMain: () => Ref.set(input.mainWindow, Option.none()),
237 reveal: () => Effect.void,
238 sendAll: () => Effect.void,
239 destroyAll: Effect.void,
240 syncAllAppearance: (sync) => sync(input.window),
241 } satisfies ElectronWindow.ElectronWindow["Service"]);
242​
243 return DesktopWindow.layer.pipe(
244 Layer.provide(
245 Layer.mergeAll(
246 desktopAssetsLayer,
247 desktopEnvironmentLayer,
248 desktopAppSettingsLayer,
249 desktopServerExposureLayer,
250 DesktopState.layer,
251 electronMenuLayer,
252 Layer.succeed(ElectronShell.ElectronShell, {
253 openExternal: (url) =>
254 Effect.sync(() => {
255 input.openedExternalUrls?.push(url);
256 return true;
257 }),
258 copyText: () => Effect.void,
259 } satisfies ElectronShell.ElectronShell["Service"]),
260 electronThemeLayer,
261 electronWindowLayer,
262 Layer.mock(PreviewManager.PreviewManager)({
263 getBrowserSession: () => Effect.succeed({} as Electron.Session),
264 setMainWindow: () => Effect.void,
265 isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
266 getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
267 }),
268 ),
269 ),
270 );
272​
273// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
274// given outcomes in order (null => simulated open failure), and whose
275// currentMainOrFirst mirrors the real fallback to the first live window (the
276// splash, before any main is registered). Reveal targets are recorded so tests
277// can assert what activation actually surfaced.
278const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
279 Effect.gen(function* () {
280 const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
281 const createCalls = yield* Ref.make(0);
282 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
283 const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
284 const fallbackWindow = createOutcomes.find(
285 (window): window is Electron.BrowserWindow => window !== null,
286 );
287​
288 const currentMainOrFirst = Effect.gen(function* () {
289 const registered = yield* Ref.get(mainWindow);
290 if (Option.isSome(registered)) {
291 return registered;
292 }
293 const created = yield* Ref.get(createdWindows);
294 return Option.fromNullishOr(created[0] ?? null);
295 });
296​
297 const electronWindowShape = {
298 create: () =>
299 Effect.gen(function* () {
300 const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
301 const outcome = createOutcomes[index] ?? null;
302 if (outcome === null) {
303 return yield* new ElectronWindow.ElectronWindowCreateError({
304 options: {
305 title: null,
306 width: null,
307 height: null,
308 minWidth: null,
309 minHeight: null,
310 show: null,
311 modal: null,
312 frame: null,
313 transparent: null,
314 backgroundColor: null,
315 webPreferences: {
316 preload: null,
317 partition: null,
318 sandbox: null,
319 contextIsolation: null,
320 nodeIntegration: null,
321 webviewTag: null,
322 },
323 },
324 cause: new Error("simulated window-open failure"),
325 });
326 }
327 yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
328 return outcome;
329 }),
330 main: Ref.get(mainWindow),
331 currentMainOrFirst,
332 focusedMainOrFirst: currentMainOrFirst,
333 setMain: (window) => Ref.set(mainWindow, Option.some(window)),
334 clearMain: () => Ref.set(mainWindow, Option.none()),
335 reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
336 sendAll: () => Effect.void,
337 destroyAll: Effect.void,
338 syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
339 } satisfies ElectronWindow.ElectronWindow["Service"];
340​
341 const layer = DesktopWindow.layer.pipe(
342 Layer.provide(
343 Layer.mergeAll(
344 desktopAssetsLayer,
345 desktopEnvironmentLayer,
346 DesktopAppSettings.layerTest(),
347 desktopServerExposureLayer,
348 electronMenuLayer,
349 Layer.succeed(ElectronShell.ElectronShell, {
350 openExternal: () => Effect.succeed(true),
351 copyText: () => Effect.void,
352 } satisfies ElectronShell.ElectronShell["Service"]),
353 electronThemeLayer,
354 Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
355 Layer.mock(PreviewManager.PreviewManager)({
356 getBrowserSession: () => Effect.succeed({} as Electron.Session),
357 setMainWindow: () => Effect.void,
358 isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
359 getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
360 }),
361 ),
362 ),
363 );
364​
365 return { layer, createCalls, mainWindow, revealedWindows } as const;
366 });
367​
368describe("DesktopWindow", () => {
369 it("restores bounds only when the window fits within a connected display", () => {
370 const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
371 const displays = [
372 { x: 0, y: 0, width: 1920, height: 1080 },
373 { x: 1920, y: 0, width: 2560, height: 1440 },
374 ];
375​
376 assert.deepEqual(
377 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
378 persistedBounds,
379 );
380 assert.deepEqual(
381 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
382 DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
383 );
384 });
385​
386 it("recognizes only same-origin renderer navigations", () => {
387 assert.isTrue(
388 DesktopWindow.isSameOriginRendererNavigation({
389 applicationUrl: "t3code://app/",
390 navigationUrl: "t3code://app/settings/connections",
391 }),
392 );
393 assert.isFalse(
394 DesktopWindow.isSameOriginRendererNavigation({
395 applicationUrl: "t3code://app/",
396 navigationUrl: "https://accounts.microsoft.com/oauth",
397 }),
398 );
399 assert.isFalse(
400 DesktopWindow.isSameOriginRendererNavigation({
401 applicationUrl: "t3code://app/",
402 navigationUrl: "not a url",
403 }),
404 );
405 });
406​
407 it.effect("does not open a development window until the backend is ready", () =>
408 Effect.gen(function* () {
409 const fakeWindow = makeFakeBrowserWindow();
410 const createCount = yield* Ref.make(0);
411 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
412 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
413 const layer = makeTestLayer({
414 window: fakeWindow.window,
415 createCount,
416 mainWindow,
417 createdWindowOptions,
418 });
419​
420 yield* Effect.gen(function* () {
421 const desktopWindow = yield* DesktopWindow.DesktopWindow;
422 yield* desktopWindow.activate;
423 assert.equal(yield* Ref.get(createCount), 0);
424​
425 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
426 assert.equal(yield* Ref.get(createCount), 1);
427 assert.equal(createdWindowOptions[0]?.width, 1100);
428 assert.equal(createdWindowOptions[0]?.height, 780);
429 assert.isUndefined(createdWindowOptions[0]?.x);
430 assert.isUndefined(createdWindowOptions[0]?.y);
431 assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
432 assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
433 assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
434 assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
435 }).pipe(Effect.provide(layer));
436 }),
437 );
438​
439 it.effect("uses the persisted main window bounds when opening the window", () =>
440 Effect.gen(function* () {
441 const fakeWindow = makeFakeBrowserWindow();
442 const createCount = yield* Ref.make(0);
443 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
444 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
445 const layer = makeTestLayer({
446 window: fakeWindow.window,
447 createCount,
448 mainWindow,
449 createdWindowOptions,
450 desktopSettings: {
451 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
452 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
453 },
454 });
455​
456 yield* Effect.gen(function* () {
457 const desktopWindow = yield* DesktopWindow.DesktopWindow;
458 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
459​
460 assert.equal(createdWindowOptions[0]?.width, 1320);
461 assert.equal(createdWindowOptions[0]?.height, 880);
462 assert.equal(createdWindowOptions[0]?.x, 120);
463 assert.equal(createdWindowOptions[0]?.y, 80);
464 }).pipe(Effect.provide(layer));
465 }),
466 );
467​
468 it.effect("restores the persisted maximized state", () =>
469 Effect.gen(function* () {
470 const fakeWindow = makeFakeBrowserWindow();
471 const createCount = yield* Ref.make(0);
472 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
473 const layer = makeTestLayer({
474 window: fakeWindow.window,
475 createCount,
476 mainWindow,
477 desktopSettings: {
478 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
479 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
480 mainWindowMaximized: true,
481 },
482 });
483​
484 yield* Effect.gen(function* () {
485 const desktopWindow = yield* DesktopWindow.DesktopWindow;
486 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
487​
488 assert.equal(fakeWindow.maximize.mock.calls.length, 0);
489 const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
490 if (!readyToShow) {
491 return yield* Effect.die("window ready-to-show listener was not registered");
492 }
493 readyToShow();
494 assert.equal(fakeWindow.maximize.mock.calls.length, 1);
495 }).pipe(Effect.provide(layer));
496 }),
497 );
498​
499 it.effect("debounces move and resize bounds updates", () =>
500 Effect.gen(function* () {
501 const fakeWindow = makeFakeBrowserWindow();
502 const createCount = yield* Ref.make(0);
503 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
504 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
505 const layer = makeTestLayer({
506 window: fakeWindow.window,
507 createCount,
508 mainWindow,
509 mainWindowBoundsUpdates,
510 });
511​
512 yield* Effect.gen(function* () {
513 const desktopWindow = yield* DesktopWindow.DesktopWindow;
514 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
515​
516 const move = fakeWindow.windowListeners.get("move");
517 const resize = fakeWindow.windowListeners.get("resize");
518 if (!move || !resize) {
519 return yield* Effect.die("window bounds listeners were not registered");
520 }
521​
522 fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
523 move();
524 yield* TestClock.adjust(250);
525​
526 fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
527 resize();
528 yield* TestClock.adjust(499);
529 assert.deepEqual(mainWindowBoundsUpdates, []);
530​
531 yield* TestClock.adjust(1);
532 yield* Effect.promise(() => Promise.resolve());
533 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
534 }).pipe(Effect.provide(layer));
535 }),
536 );
537​
538 it.effect("persists normal bounds and state for a maximized window", () =>
539 Effect.gen(function* () {
540 const fakeWindow = makeFakeBrowserWindow();
541 fakeWindow.isMaximized.mockReturnValue(true);
542 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
543 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
544 const createCount = yield* Ref.make(0);
545 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
546 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
547 const mainWindowMaximizedUpdates: boolean[] = [];
548 const layer = makeTestLayer({
549 window: fakeWindow.window,
550 createCount,
551 mainWindow,
552 mainWindowBoundsUpdates,
553 mainWindowMaximizedUpdates,
554 });
555​
556 yield* Effect.gen(function* () {
557 const desktopWindow = yield* DesktopWindow.DesktopWindow;
558 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
559​
560 const close = fakeWindow.windowListeners.get("close");
561 if (!close) {
562 return yield* Effect.die("window close listener was not registered");
563 }
564 close();
565 yield* Effect.promise(() => Promise.resolve());
566​
567 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
568 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
569 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
570 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
571 }).pipe(Effect.provide(layer));
572 }),
573 );
574​
575 it.effect("persists normal bounds and state from the native maximize event", () =>
576 Effect.gen(function* () {
577 const fakeWindow = makeFakeBrowserWindow();
578 const createCount = yield* Ref.make(0);
579 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
580 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
581 const mainWindowMaximizedUpdates: boolean[] = [];
582 const layer = makeTestLayer({
583 window: fakeWindow.window,
584 createCount,
585 mainWindow,
586 mainWindowBoundsUpdates,
587 mainWindowMaximizedUpdates,
588 });
589​
590 yield* Effect.gen(function* () {
591 const desktopWindow = yield* DesktopWindow.DesktopWindow;
592 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
593​
594 const maximize = fakeWindow.windowListeners.get("maximize");
595 if (!maximize) {
596 return yield* Effect.die("window maximize listener was not registered");
597 }
598​
599 fakeWindow.isMaximized.mockReturnValue(true);
600 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
601 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
602 maximize();
603 yield* TestClock.adjust(500);
604 yield* Effect.promise(() => Promise.resolve());
605​
606 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
607 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
608 }).pipe(Effect.provide(layer));
609 }),
610 );
611​
612 it.effect("does not persist bounds that fail the domain schema", () =>
613 Effect.gen(function* () {
614 const fakeWindow = makeFakeBrowserWindow();
615 fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
616 const createCount = yield* Ref.make(0);
617 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
618 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
619 const layer = makeTestLayer({
620 window: fakeWindow.window,
621 createCount,
622 mainWindow,
623 mainWindowBoundsUpdates,
624 });
625​
626 yield* Effect.gen(function* () {
627 const desktopWindow = yield* DesktopWindow.DesktopWindow;
628 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
629​
630 const resize = fakeWindow.windowListeners.get("resize");
631 if (!resize) {
632 return yield* Effect.die("window resize listener was not registered");
633 }
634 resize();
635 yield* TestClock.adjust(500);
636 yield* Effect.promise(() => Promise.resolve());
637​
638 assert.deepEqual(mainWindowBoundsUpdates, []);
639 }).pipe(Effect.provide(layer));
640 }),
641 );
642​
643 it.effect("preserves unrestorable bounds until the user changes the window", () =>
644 Effect.gen(function* () {
645 const fakeWindow = makeFakeBrowserWindow();
646 const createCount = yield* Ref.make(0);
647 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
648 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
649 const layer = makeTestLayer({
650 window: fakeWindow.window,
651 createCount,
652 mainWindow,
653 mainWindowBoundsUpdates,
654 desktopSettings: {
655 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
656 mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
657 },
658 });
659​
660 yield* Effect.gen(function* () {
661 const desktopWindow = yield* DesktopWindow.DesktopWindow;
662 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
663​
664 const close = fakeWindow.windowListeners.get("close");
665 const move = fakeWindow.windowListeners.get("move");
666 if (!close || !move) {
667 return yield* Effect.die("window lifecycle listeners were not registered");
668 }
669​
670 close();
671 yield* Effect.promise(() => Promise.resolve());
672 assert.deepEqual(mainWindowBoundsUpdates, []);
673​
674 fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
675 move();
676 yield* TestClock.adjust(500);
677 yield* Effect.promise(() => Promise.resolve());
678 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
679 }).pipe(Effect.provide(layer));
680 }),
681 );
682​
683 it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
684 Effect.gen(function* () {
685 const fakeWindow = makeFakeBrowserWindow();
686 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
687 fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
688 const createCount = yield* Ref.make(0);
689 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
690 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
691 const layer = makeTestLayer({
692 window: fakeWindow.window,
693 createCount,
694 mainWindow,
695 mainWindowBoundsUpdates,
696 });
697​
698 yield* Effect.gen(function* () {
699 const desktopWindow = yield* DesktopWindow.DesktopWindow;
700 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
701​
702 const resize = fakeWindow.windowListeners.get("resize");
703 if (!resize) {
704 return yield* Effect.die("window resize listener was not registered");
705 }
706 resize();
707 yield* TestClock.adjust(250);
708 fakeWindow.isFullScreen.mockReturnValue(true);
709​
710 yield* desktopWindow.flushMainWindowBounds;
711​
712 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
713 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
714 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
715 }).pipe(Effect.provide(layer));
716 }),
717 );
718​
719 it.effect("flushes normal bounds when minimized before the debounce completes", () =>
720 Effect.gen(function* () {
721 const fakeWindow = makeFakeBrowserWindow();
722 fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
723 fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
724 const createCount = yield* Ref.make(0);
725 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
726 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
727 const layer = makeTestLayer({
728 window: fakeWindow.window,
729 createCount,
730 mainWindow,
731 mainWindowBoundsUpdates,
732 });
733​
734 yield* Effect.gen(function* () {
735 const desktopWindow = yield* DesktopWindow.DesktopWindow;
736 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
737​
738 const resize = fakeWindow.windowListeners.get("resize");
739 if (!resize) {
740 return yield* Effect.die("window resize listener was not registered");
741 }
742 resize();
743 yield* TestClock.adjust(250);
744 fakeWindow.isMinimized.mockReturnValue(true);
745​
746 yield* desktopWindow.flushMainWindowBounds;
747​
748 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
749 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
750 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
751 }).pipe(Effect.provide(layer));
752 }),
753 );
754​
755 it.effect("logs display lookup failures before falling back to the default size", () =>
756 Effect.gen(function* () {
757 const displayLookupFailure = new Error("screen API unavailable");
758 vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
759 throw displayLookupFailure;
760 });
761 const logRecords: Array<{
762 readonly message: unknown;
763 readonly annotations: Readonly<Record<string, unknown>>;
764 }> = [];
765 const logger = Logger.make(({ fiber, message }) => {
766 logRecords.push({
767 message,
768 annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
769 });
770 });
771 const fakeWindow = makeFakeBrowserWindow();
772 const createCount = yield* Ref.make(0);
773 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
774 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
775 const layer = makeTestLayer({
776 window: fakeWindow.window,
777 createCount,
778 mainWindow,
779 createdWindowOptions,
780 });
781​
782 yield* Effect.gen(function* () {
783 const desktopWindow = yield* DesktopWindow.DesktopWindow;
784 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
785 }).pipe(
786 Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
787 );
788​
789 const warning = logRecords.find(
790 (record) =>
791 Array.isArray(record.message) &&
792 record.message[0] === "failed to read connected displays; using defaults",
793 );
794 assert.isDefined(warning);
795 assert.strictEqual(warning.annotations.cause, displayLookupFailure);
796 assert.equal(createdWindowOptions[0]?.width, 1100);
797 assert.equal(createdWindowOptions[0]?.height, 780);
798 assert.isUndefined(createdWindowOptions[0]?.x);
799 assert.isUndefined(createdWindowOptions[0]?.y);
800 }),
801 );
802​
803 it.effect("persists the current main window bounds before the window closes", () =>
804 Effect.gen(function* () {
805 const fakeWindow = makeFakeBrowserWindow();
806 fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
807 const createCount = yield* Ref.make(0);
808 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
809 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
810 const writeStarted = yield* Deferred.make<void>();
811 const allowWrite = yield* Deferred.make<void>();
812 const flushCompleted = yield* Deferred.make<void>();
813 const layer = makeTestLayer({
814 window: fakeWindow.window,
815 createCount,
816 mainWindow,
817 mainWindowBoundsUpdates,
818 beforeMainWindowBoundsUpdate: () =>
819 Deferred.succeed(writeStarted, undefined).pipe(
820 Effect.andThen(Deferred.await(allowWrite)),
821 Effect.asVoid,
822 ),
823 });
824​
825 yield* Effect.gen(function* () {
826 const desktopWindow = yield* DesktopWindow.DesktopWindow;
827 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
828​
829 const close = fakeWindow.windowListeners.get("close");
830 if (!close) {
831 return yield* Effect.die("window close listener was not registered");
832 }
833 close();
834 yield* Deferred.await(writeStarted);
835 fakeWindow.isDestroyed.mockReturnValue(true);
836​
837 const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
838 Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
839 Effect.forkChild({ startImmediately: true }),
840 );
841 yield* Effect.yieldNow;
842 assert.isFalse(yield* Deferred.isDone(flushCompleted));
843​
844 yield* Deferred.succeed(allowWrite, undefined);
845 yield* Fiber.join(flushFiber);
846 assert.isTrue(yield* Deferred.isDone(flushCompleted));
847​
848 assert.deepEqual(mainWindowBoundsUpdates, [
849 {
850 x: 240,
851 y: 160,
852 width: 1410,
853 height: 930,
854 },
855 ]);
856 }).pipe(Effect.provide(layer));
857 }),
858 );
859​
860 it.effect("publishes native macOS fullscreen changes to the renderer", () =>
861 Effect.gen(function* () {
862 const fakeWindow = makeFakeBrowserWindow();
863 const createCount = yield* Ref.make(0);
864 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
865 const layer = makeTestLayer({
866 window: fakeWindow.window,
867 createCount,
868 mainWindow,
869 });
870​
871 yield* Effect.gen(function* () {
872 const desktopWindow = yield* DesktopWindow.DesktopWindow;
873 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
874​
875 const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
876 const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
877 if (!enterFullscreen || !leaveFullscreen) {
878 return yield* Effect.die("fullscreen listeners were not registered");
879 }
880​
881 enterFullscreen();
882 leaveFullscreen();
883 assert.deepEqual(fakeWindow.send.mock.calls, [
884 [WINDOW_FULLSCREEN_STATE_CHANNEL, true],
885 [WINDOW_FULLSCREEN_STATE_CHANNEL, false],
886 ]);
887 }).pipe(Effect.provide(layer));
888 }),
889 );
890​
891 it.effect("recovers when the development renderer is temporarily unreachable", () =>
892 Effect.gen(function* () {
893 const fakeWindow = makeFakeBrowserWindow();
894 const createCount = yield* Ref.make(0);
895 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
896 const layer = makeTestLayer({
897 window: fakeWindow.window,
898 createCount,
899 mainWindow,
900 });
901​
902 yield* Effect.gen(function* () {
903 const desktopWindow = yield* DesktopWindow.DesktopWindow;
904 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
905​
906 const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
907 const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
908 if (!didFailLoad || !didFinishLoad) {
909 return yield* Effect.die("renderer load listeners were not registered");
910 }
911​
912 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
913 assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
914​
915 yield* TestClock.adjust(100);
916 assert.deepEqual(fakeWindow.loadURL.mock.calls, [
917 ["t3code-dev://app/"],
918 ["t3code-dev://app/"],
919 ]);
920 assert.equal(fakeWindow.reload.mock.calls.length, 0);
921​
922 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
923 didFinishLoad();
924 yield* TestClock.adjust(250);
925 assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
926 assert.equal(fakeWindow.reload.mock.calls.length, 0);
927 }).pipe(Effect.provide(layer));
928 }),
929 );
930​
931 it("retries only transient failures for the development renderer", () => {
932 assert.isTrue(
933 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
934 applicationUrl: "t3code-dev://app/",
935 errorCode: -102,
936 isMainFrame: true,
937 validatedUrl: "t3code-dev://app/",
938 }),
939 );
940 assert.isFalse(
941 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
942 applicationUrl: "t3code-dev://app/",
943 errorCode: -3,
944 isMainFrame: true,
945 validatedUrl: "t3code-dev://app/",
946 }),
947 );
948 assert.isFalse(
949 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
950 applicationUrl: "t3code-dev://app/",
951 errorCode: -102,
952 isMainFrame: true,
953 validatedUrl: "https://example.com/",
954 }),
955 );
956 });
957​
958 it.effect("opens safe off-origin renderer navigations in the system browser", () =>
959 Effect.gen(function* () {
960 const fakeWindow = makeFakeBrowserWindow();
961 const createCount = yield* Ref.make(0);
962 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
963 const openedExternalUrls: unknown[] = [];
964 const layer = makeTestLayer({
965 window: fakeWindow.window,
966 createCount,
967 mainWindow,
968 openedExternalUrls,
969 });
970​
971 yield* Effect.gen(function* () {
972 const desktopWindow = yield* DesktopWindow.DesktopWindow;
973 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
974​
975 const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
976 if (!willNavigate) {
977 return yield* Effect.die("will-navigate listener was not registered");
978 }
979 let prevented = false;
980 willNavigate(
981 {
982 preventDefault: () => {
983 prevented = true;
984 },
985 },
986 "https://accounts.microsoft.com/oauth",
987 );
988 yield* Effect.promise(() => Promise.resolve());
989​
990 assert.isTrue(prevented);
991 assert.deepEqual(openedExternalUrls, ["https://accounts.microsoft.com/oauth"]);
992 }).pipe(Effect.provide(layer));
993 }),
994 );
995​
996 it.effect(
997 "retries opening the real main on activate when a failed post-readiness open left only the splash",
998 () =>
999 Effect.gen(function* () {
1000 const splash = makeFakeBrowserWindow();
1001 const main = makeFakeBrowserWindow();
1002 // create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
1003 // window-open error), #3 -> the real main on activate's retry.
1004 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
1005​
1006 yield* Effect.gen(function* () {
1007 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1008​
1009 // 1. WSL-only boot shows the connecting splash.
1010 yield* desktopWindow.showConnectingSplash;
1011 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1012​
1013 // 2. Backend reports ready, but opening the real main fails. The pool
1014 // swallows that error in production, so handleBackendReady fails
1015 // here without a registered main window -- only the splash is open.
1016 const readyExit = yield* Effect.exit(
1017 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
1018 );
1019 assert.equal(readyExit._tag, "Failure");
1020 assert.equal(yield* Ref.get(scenario.createCalls), 2);
1021 assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
1022​
1023 // 3. Activating must not mistake the splash for the main window: it
1024 // retries the open and brings up the real main instead of leaving
1025 // the user stranded on "Connecting to WSL".
1026 yield* desktopWindow.activate;
1027 assert.equal(yield* Ref.get(scenario.createCalls), 3);
1028 const registeredMain = yield* Ref.get(scenario.mainWindow);
1029 assert.isTrue(Option.isSome(registeredMain));
1030 assert.equal(Option.getOrThrow(registeredMain), main.window);
1031 }).pipe(Effect.provide(scenario.layer));
1032 }),
1033 );
1034​
1035 it.effect(
1036 "re-reveals the connecting splash on activate while the backend is still cold-booting",
1037 () =>
1038 Effect.gen(function* () {
1039 const splash = makeFakeBrowserWindow();
1040 // Only the splash is ever created; the backend never reports ready.
1041 const scenario = yield* makeSplashScenario([splash.window]);
1042​
1043 yield* Effect.gen(function* () {
1044 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1045​
1046 yield* desktopWindow.showConnectingSplash;
1047 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1048​
1049 // Taskbar/dock activation during cold boot must bring the splash back
1050 // rather than no-op and leave it hidden until the backend finishes.
1051 yield* desktopWindow.activate;
1052 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1053 assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
1054 }).pipe(Effect.provide(scenario.layer));
1055 }),
1056 );
1057​
1058 it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
1059 Effect.gen(function* () {
1060 const splash = makeFakeBrowserWindow();
1061 const main = makeFakeBrowserWindow();
1062 const scenario = yield* makeSplashScenario([splash.window, main.window]);
1063​
1064 yield* Effect.gen(function* () {
1065 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1066​
1067 yield* desktopWindow.showConnectingSplash;
1068 yield* desktopWindow.dispatchMenuAction("open-settings");
1069​
1070 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1071 assert.equal(splash.send.mock.calls.length, 0);
1072 assert.equal(main.send.mock.calls.length, 0);
1073 }).pipe(Effect.provide(scenario.layer));
1074 }),
1075 );
1076​
1077 it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
1078 Effect.gen(function* () {
1079 const splash = makeFakeBrowserWindow();
1080 const main = makeFakeBrowserWindow();
1081 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
1082​
1083 yield* Effect.gen(function* () {
1084 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1085​
1086 yield* desktopWindow.showConnectingSplash;
1087 const readyExit = yield* Effect.exit(
1088 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
1089 );
1090 assert.equal(readyExit._tag, "Failure");
1091​
1092 yield* desktopWindow.dispatchMenuAction("open-settings");
1093​
1094 assert.equal(yield* Ref.get(scenario.createCalls), 3);
1095 assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
1096 }).pipe(Effect.provide(scenario.layer));
1097 }),
1098 );
1099});