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

DesktopWindow.test.ts

1,101 lines43.2 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 backgroundThrottling: null,
319 sandbox: null,
320 contextIsolation: null,
321 nodeIntegration: null,
322 webviewTag: null,
323 },
324 },
325 cause: new Error("simulated window-open failure"),
326 });
327 }
328 yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
329 return outcome;
330 }),
331 main: Ref.get(mainWindow),
332 currentMainOrFirst,
333 focusedMainOrFirst: currentMainOrFirst,
334 setMain: (window) => Ref.set(mainWindow, Option.some(window)),
335 clearMain: () => Ref.set(mainWindow, Option.none()),
336 reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
337 sendAll: () => Effect.void,
338 destroyAll: Effect.void,
339 syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
340 } satisfies ElectronWindow.ElectronWindow["Service"];
341​
342 const layer = DesktopWindow.layer.pipe(
343 Layer.provide(
344 Layer.mergeAll(
345 desktopAssetsLayer,
346 desktopEnvironmentLayer,
347 DesktopAppSettings.layerTest(),
348 desktopServerExposureLayer,
349 electronMenuLayer,
350 Layer.succeed(ElectronShell.ElectronShell, {
351 openExternal: () => Effect.succeed(true),
352 copyText: () => Effect.void,
353 } satisfies ElectronShell.ElectronShell["Service"]),
354 electronThemeLayer,
355 Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
356 Layer.mock(PreviewManager.PreviewManager)({
357 getBrowserSession: () => Effect.succeed({} as Electron.Session),
358 setMainWindow: () => Effect.void,
359 isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
360 getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
361 }),
362 ),
363 ),
364 );
365​
366 return { layer, createCalls, mainWindow, revealedWindows } as const;
367 });
368​
369describe("DesktopWindow", () => {
370 it("restores bounds only when the window fits within a connected display", () => {
371 const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
372 const displays = [
373 { x: 0, y: 0, width: 1920, height: 1080 },
374 { x: 1920, y: 0, width: 2560, height: 1440 },
375 ];
376​
377 assert.deepEqual(
378 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
379 persistedBounds,
380 );
381 assert.deepEqual(
382 DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
383 DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
384 );
385 });
386​
387 it("recognizes only same-origin renderer navigations", () => {
388 assert.isTrue(
389 DesktopWindow.isSameOriginRendererNavigation({
390 applicationUrl: "t3code://app/",
391 navigationUrl: "t3code://app/settings/connections",
392 }),
393 );
394 assert.isFalse(
395 DesktopWindow.isSameOriginRendererNavigation({
396 applicationUrl: "t3code://app/",
397 navigationUrl: "https://accounts.microsoft.com/oauth",
398 }),
399 );
400 assert.isFalse(
401 DesktopWindow.isSameOriginRendererNavigation({
402 applicationUrl: "t3code://app/",
403 navigationUrl: "not a url",
404 }),
405 );
406 });
407​
408 it.effect("does not open a development window until the backend is ready", () =>
409 Effect.gen(function* () {
410 const fakeWindow = makeFakeBrowserWindow();
411 const createCount = yield* Ref.make(0);
412 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
413 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
414 const layer = makeTestLayer({
415 window: fakeWindow.window,
416 createCount,
417 mainWindow,
418 createdWindowOptions,
419 });
420​
421 yield* Effect.gen(function* () {
422 const desktopWindow = yield* DesktopWindow.DesktopWindow;
423 yield* desktopWindow.activate;
424 assert.equal(yield* Ref.get(createCount), 0);
425​
426 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
427 assert.equal(yield* Ref.get(createCount), 1);
428 assert.equal(createdWindowOptions[0]?.width, 1100);
429 assert.equal(createdWindowOptions[0]?.height, 780);
430 assert.isUndefined(createdWindowOptions[0]?.x);
431 assert.isUndefined(createdWindowOptions[0]?.y);
432 assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
433 assert.isFalse(createdWindowOptions[0]?.webPreferences?.backgroundThrottling);
434 assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
435 assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
436 assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
437 }).pipe(Effect.provide(layer));
438 }),
439 );
440​
441 it.effect("uses the persisted main window bounds when opening the window", () =>
442 Effect.gen(function* () {
443 const fakeWindow = makeFakeBrowserWindow();
444 const createCount = yield* Ref.make(0);
445 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
446 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
447 const layer = makeTestLayer({
448 window: fakeWindow.window,
449 createCount,
450 mainWindow,
451 createdWindowOptions,
452 desktopSettings: {
453 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
454 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
455 },
456 });
457​
458 yield* Effect.gen(function* () {
459 const desktopWindow = yield* DesktopWindow.DesktopWindow;
460 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
461​
462 assert.equal(createdWindowOptions[0]?.width, 1320);
463 assert.equal(createdWindowOptions[0]?.height, 880);
464 assert.equal(createdWindowOptions[0]?.x, 120);
465 assert.equal(createdWindowOptions[0]?.y, 80);
466 }).pipe(Effect.provide(layer));
467 }),
468 );
469​
470 it.effect("restores the persisted maximized state", () =>
471 Effect.gen(function* () {
472 const fakeWindow = makeFakeBrowserWindow();
473 const createCount = yield* Ref.make(0);
474 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
475 const layer = makeTestLayer({
476 window: fakeWindow.window,
477 createCount,
478 mainWindow,
479 desktopSettings: {
480 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
481 mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
482 mainWindowMaximized: true,
483 },
484 });
485​
486 yield* Effect.gen(function* () {
487 const desktopWindow = yield* DesktopWindow.DesktopWindow;
488 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
489​
490 assert.equal(fakeWindow.maximize.mock.calls.length, 0);
491 const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
492 if (!readyToShow) {
493 return yield* Effect.die("window ready-to-show listener was not registered");
494 }
495 readyToShow();
496 assert.equal(fakeWindow.maximize.mock.calls.length, 1);
497 }).pipe(Effect.provide(layer));
498 }),
499 );
500​
501 it.effect("debounces move and resize bounds updates", () =>
502 Effect.gen(function* () {
503 const fakeWindow = makeFakeBrowserWindow();
504 const createCount = yield* Ref.make(0);
505 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
506 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
507 const layer = makeTestLayer({
508 window: fakeWindow.window,
509 createCount,
510 mainWindow,
511 mainWindowBoundsUpdates,
512 });
513​
514 yield* Effect.gen(function* () {
515 const desktopWindow = yield* DesktopWindow.DesktopWindow;
516 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
517​
518 const move = fakeWindow.windowListeners.get("move");
519 const resize = fakeWindow.windowListeners.get("resize");
520 if (!move || !resize) {
521 return yield* Effect.die("window bounds listeners were not registered");
522 }
523​
524 fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
525 move();
526 yield* TestClock.adjust(250);
527​
528 fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
529 resize();
530 yield* TestClock.adjust(499);
531 assert.deepEqual(mainWindowBoundsUpdates, []);
532​
533 yield* TestClock.adjust(1);
534 yield* Effect.promise(() => Promise.resolve());
535 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
536 }).pipe(Effect.provide(layer));
537 }),
538 );
539​
540 it.effect("persists normal bounds and state for a maximized window", () =>
541 Effect.gen(function* () {
542 const fakeWindow = makeFakeBrowserWindow();
543 fakeWindow.isMaximized.mockReturnValue(true);
544 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
545 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
546 const createCount = yield* Ref.make(0);
547 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
548 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
549 const mainWindowMaximizedUpdates: boolean[] = [];
550 const layer = makeTestLayer({
551 window: fakeWindow.window,
552 createCount,
553 mainWindow,
554 mainWindowBoundsUpdates,
555 mainWindowMaximizedUpdates,
556 });
557​
558 yield* Effect.gen(function* () {
559 const desktopWindow = yield* DesktopWindow.DesktopWindow;
560 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
561​
562 const close = fakeWindow.windowListeners.get("close");
563 if (!close) {
564 return yield* Effect.die("window close listener was not registered");
565 }
566 close();
567 yield* Effect.promise(() => Promise.resolve());
568​
569 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
570 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
571 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
572 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
573 }).pipe(Effect.provide(layer));
574 }),
575 );
576​
577 it.effect("persists normal bounds and state from the native maximize event", () =>
578 Effect.gen(function* () {
579 const fakeWindow = makeFakeBrowserWindow();
580 const createCount = yield* Ref.make(0);
581 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
582 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
583 const mainWindowMaximizedUpdates: boolean[] = [];
584 const layer = makeTestLayer({
585 window: fakeWindow.window,
586 createCount,
587 mainWindow,
588 mainWindowBoundsUpdates,
589 mainWindowMaximizedUpdates,
590 });
591​
592 yield* Effect.gen(function* () {
593 const desktopWindow = yield* DesktopWindow.DesktopWindow;
594 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
595​
596 const maximize = fakeWindow.windowListeners.get("maximize");
597 if (!maximize) {
598 return yield* Effect.die("window maximize listener was not registered");
599 }
600​
601 fakeWindow.isMaximized.mockReturnValue(true);
602 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
603 fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
604 maximize();
605 yield* TestClock.adjust(500);
606 yield* Effect.promise(() => Promise.resolve());
607​
608 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
609 assert.deepEqual(mainWindowMaximizedUpdates, [true]);
610 }).pipe(Effect.provide(layer));
611 }),
612 );
613​
614 it.effect("does not persist bounds that fail the domain schema", () =>
615 Effect.gen(function* () {
616 const fakeWindow = makeFakeBrowserWindow();
617 fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
618 const createCount = yield* Ref.make(0);
619 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
620 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
621 const layer = makeTestLayer({
622 window: fakeWindow.window,
623 createCount,
624 mainWindow,
625 mainWindowBoundsUpdates,
626 });
627​
628 yield* Effect.gen(function* () {
629 const desktopWindow = yield* DesktopWindow.DesktopWindow;
630 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
631​
632 const resize = fakeWindow.windowListeners.get("resize");
633 if (!resize) {
634 return yield* Effect.die("window resize listener was not registered");
635 }
636 resize();
637 yield* TestClock.adjust(500);
638 yield* Effect.promise(() => Promise.resolve());
639​
640 assert.deepEqual(mainWindowBoundsUpdates, []);
641 }).pipe(Effect.provide(layer));
642 }),
643 );
644​
645 it.effect("preserves unrestorable bounds until the user changes the window", () =>
646 Effect.gen(function* () {
647 const fakeWindow = makeFakeBrowserWindow();
648 const createCount = yield* Ref.make(0);
649 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
650 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
651 const layer = makeTestLayer({
652 window: fakeWindow.window,
653 createCount,
654 mainWindow,
655 mainWindowBoundsUpdates,
656 desktopSettings: {
657 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
658 mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
659 },
660 });
661​
662 yield* Effect.gen(function* () {
663 const desktopWindow = yield* DesktopWindow.DesktopWindow;
664 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
665​
666 const close = fakeWindow.windowListeners.get("close");
667 const move = fakeWindow.windowListeners.get("move");
668 if (!close || !move) {
669 return yield* Effect.die("window lifecycle listeners were not registered");
670 }
671​
672 close();
673 yield* Effect.promise(() => Promise.resolve());
674 assert.deepEqual(mainWindowBoundsUpdates, []);
675​
676 fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
677 move();
678 yield* TestClock.adjust(500);
679 yield* Effect.promise(() => Promise.resolve());
680 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
681 }).pipe(Effect.provide(layer));
682 }),
683 );
684​
685 it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
686 Effect.gen(function* () {
687 const fakeWindow = makeFakeBrowserWindow();
688 fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
689 fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
690 const createCount = yield* Ref.make(0);
691 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
692 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
693 const layer = makeTestLayer({
694 window: fakeWindow.window,
695 createCount,
696 mainWindow,
697 mainWindowBoundsUpdates,
698 });
699​
700 yield* Effect.gen(function* () {
701 const desktopWindow = yield* DesktopWindow.DesktopWindow;
702 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
703​
704 const resize = fakeWindow.windowListeners.get("resize");
705 if (!resize) {
706 return yield* Effect.die("window resize listener was not registered");
707 }
708 resize();
709 yield* TestClock.adjust(250);
710 fakeWindow.isFullScreen.mockReturnValue(true);
711​
712 yield* desktopWindow.flushMainWindowBounds;
713​
714 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
715 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
716 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
717 }).pipe(Effect.provide(layer));
718 }),
719 );
720​
721 it.effect("flushes normal bounds when minimized before the debounce completes", () =>
722 Effect.gen(function* () {
723 const fakeWindow = makeFakeBrowserWindow();
724 fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
725 fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
726 const createCount = yield* Ref.make(0);
727 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
728 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
729 const layer = makeTestLayer({
730 window: fakeWindow.window,
731 createCount,
732 mainWindow,
733 mainWindowBoundsUpdates,
734 });
735​
736 yield* Effect.gen(function* () {
737 const desktopWindow = yield* DesktopWindow.DesktopWindow;
738 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
739​
740 const resize = fakeWindow.windowListeners.get("resize");
741 if (!resize) {
742 return yield* Effect.die("window resize listener was not registered");
743 }
744 resize();
745 yield* TestClock.adjust(250);
746 fakeWindow.isMinimized.mockReturnValue(true);
747​
748 yield* desktopWindow.flushMainWindowBounds;
749​
750 assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
751 assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
752 assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
753 }).pipe(Effect.provide(layer));
754 }),
755 );
756​
757 it.effect("logs display lookup failures before falling back to the default size", () =>
758 Effect.gen(function* () {
759 const displayLookupFailure = new Error("screen API unavailable");
760 vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
761 throw displayLookupFailure;
762 });
763 const logRecords: Array<{
764 readonly message: unknown;
765 readonly annotations: Readonly<Record<string, unknown>>;
766 }> = [];
767 const logger = Logger.make(({ fiber, message }) => {
768 logRecords.push({
769 message,
770 annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
771 });
772 });
773 const fakeWindow = makeFakeBrowserWindow();
774 const createCount = yield* Ref.make(0);
775 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
776 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
777 const layer = makeTestLayer({
778 window: fakeWindow.window,
779 createCount,
780 mainWindow,
781 createdWindowOptions,
782 });
783​
784 yield* Effect.gen(function* () {
785 const desktopWindow = yield* DesktopWindow.DesktopWindow;
786 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
787 }).pipe(
788 Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
789 );
790​
791 const warning = logRecords.find(
792 (record) =>
793 Array.isArray(record.message) &&
794 record.message[0] === "failed to read connected displays; using defaults",
795 );
796 assert.isDefined(warning);
797 assert.strictEqual(warning.annotations.cause, displayLookupFailure);
798 assert.equal(createdWindowOptions[0]?.width, 1100);
799 assert.equal(createdWindowOptions[0]?.height, 780);
800 assert.isUndefined(createdWindowOptions[0]?.x);
801 assert.isUndefined(createdWindowOptions[0]?.y);
802 }),
803 );
804​
805 it.effect("persists the current main window bounds before the window closes", () =>
806 Effect.gen(function* () {
807 const fakeWindow = makeFakeBrowserWindow();
808 fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
809 const createCount = yield* Ref.make(0);
810 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
811 const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
812 const writeStarted = yield* Deferred.make<void>();
813 const allowWrite = yield* Deferred.make<void>();
814 const flushCompleted = yield* Deferred.make<void>();
815 const layer = makeTestLayer({
816 window: fakeWindow.window,
817 createCount,
818 mainWindow,
819 mainWindowBoundsUpdates,
820 beforeMainWindowBoundsUpdate: () =>
821 Deferred.succeed(writeStarted, undefined).pipe(
822 Effect.andThen(Deferred.await(allowWrite)),
823 Effect.asVoid,
824 ),
825 });
826​
827 yield* Effect.gen(function* () {
828 const desktopWindow = yield* DesktopWindow.DesktopWindow;
829 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
830​
831 const close = fakeWindow.windowListeners.get("close");
832 if (!close) {
833 return yield* Effect.die("window close listener was not registered");
834 }
835 close();
836 yield* Deferred.await(writeStarted);
837 fakeWindow.isDestroyed.mockReturnValue(true);
838​
839 const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
840 Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
841 Effect.forkChild({ startImmediately: true }),
842 );
843 yield* Effect.yieldNow;
844 assert.isFalse(yield* Deferred.isDone(flushCompleted));
845​
846 yield* Deferred.succeed(allowWrite, undefined);
847 yield* Fiber.join(flushFiber);
848 assert.isTrue(yield* Deferred.isDone(flushCompleted));
849​
850 assert.deepEqual(mainWindowBoundsUpdates, [
851 {
852 x: 240,
853 y: 160,
854 width: 1410,
855 height: 930,
856 },
857 ]);
858 }).pipe(Effect.provide(layer));
859 }),
860 );
861​
862 it.effect("publishes native macOS fullscreen changes to the renderer", () =>
863 Effect.gen(function* () {
864 const fakeWindow = makeFakeBrowserWindow();
865 const createCount = yield* Ref.make(0);
866 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
867 const layer = makeTestLayer({
868 window: fakeWindow.window,
869 createCount,
870 mainWindow,
871 });
872​
873 yield* Effect.gen(function* () {
874 const desktopWindow = yield* DesktopWindow.DesktopWindow;
875 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
876​
877 const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
878 const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
879 if (!enterFullscreen || !leaveFullscreen) {
880 return yield* Effect.die("fullscreen listeners were not registered");
881 }
882​
883 enterFullscreen();
884 leaveFullscreen();
885 assert.deepEqual(fakeWindow.send.mock.calls, [
886 [WINDOW_FULLSCREEN_STATE_CHANNEL, true],
887 [WINDOW_FULLSCREEN_STATE_CHANNEL, false],
888 ]);
889 }).pipe(Effect.provide(layer));
890 }),
891 );
892​
893 it.effect("recovers when the development renderer is temporarily unreachable", () =>
894 Effect.gen(function* () {
895 const fakeWindow = makeFakeBrowserWindow();
896 const createCount = yield* Ref.make(0);
897 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
898 const layer = makeTestLayer({
899 window: fakeWindow.window,
900 createCount,
901 mainWindow,
902 });
903​
904 yield* Effect.gen(function* () {
905 const desktopWindow = yield* DesktopWindow.DesktopWindow;
906 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
907​
908 const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
909 const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
910 if (!didFailLoad || !didFinishLoad) {
911 return yield* Effect.die("renderer load listeners were not registered");
912 }
913​
914 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
915 assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
916​
917 yield* TestClock.adjust(100);
918 assert.deepEqual(fakeWindow.loadURL.mock.calls, [
919 ["t3code-dev://app/"],
920 ["t3code-dev://app/"],
921 ]);
922 assert.equal(fakeWindow.reload.mock.calls.length, 0);
923​
924 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
925 didFinishLoad();
926 yield* TestClock.adjust(250);
927 assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
928 assert.equal(fakeWindow.reload.mock.calls.length, 0);
929 }).pipe(Effect.provide(layer));
930 }),
931 );
932​
933 it("retries only transient failures for the development renderer", () => {
934 assert.isTrue(
935 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
936 applicationUrl: "t3code-dev://app/",
937 errorCode: -102,
938 isMainFrame: true,
939 validatedUrl: "t3code-dev://app/",
940 }),
941 );
942 assert.isFalse(
943 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
944 applicationUrl: "t3code-dev://app/",
945 errorCode: -3,
946 isMainFrame: true,
947 validatedUrl: "t3code-dev://app/",
948 }),
949 );
950 assert.isFalse(
951 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
952 applicationUrl: "t3code-dev://app/",
953 errorCode: -102,
954 isMainFrame: true,
955 validatedUrl: "https://example.com/",
956 }),
957 );
958 });
959​
960 it.effect("opens safe off-origin renderer navigations in the system browser", () =>
961 Effect.gen(function* () {
962 const fakeWindow = makeFakeBrowserWindow();
963 const createCount = yield* Ref.make(0);
964 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
965 const openedExternalUrls: unknown[] = [];
966 const layer = makeTestLayer({
967 window: fakeWindow.window,
968 createCount,
969 mainWindow,
970 openedExternalUrls,
971 });
972​
973 yield* Effect.gen(function* () {
974 const desktopWindow = yield* DesktopWindow.DesktopWindow;
975 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
976​
977 const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
978 if (!willNavigate) {
979 return yield* Effect.die("will-navigate listener was not registered");
980 }
981 let prevented = false;
982 willNavigate(
983 {
984 preventDefault: () => {
985 prevented = true;
986 },
987 },
988 "https://accounts.microsoft.com/oauth",
989 );
990 yield* Effect.promise(() => Promise.resolve());
991​
992 assert.isTrue(prevented);
993 assert.deepEqual(openedExternalUrls, ["https://accounts.microsoft.com/oauth"]);
994 }).pipe(Effect.provide(layer));
995 }),
996 );
997​
998 it.effect(
999 "retries opening the real main on activate when a failed post-readiness open left only the splash",
1000 () =>
1001 Effect.gen(function* () {
1002 const splash = makeFakeBrowserWindow();
1003 const main = makeFakeBrowserWindow();
1004 // create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
1005 // window-open error), #3 -> the real main on activate's retry.
1006 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
1007​
1008 yield* Effect.gen(function* () {
1009 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1010​
1011 // 1. WSL-only boot shows the connecting splash.
1012 yield* desktopWindow.showConnectingSplash;
1013 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1014​
1015 // 2. Backend reports ready, but opening the real main fails. The pool
1016 // swallows that error in production, so handleBackendReady fails
1017 // here without a registered main window -- only the splash is open.
1018 const readyExit = yield* Effect.exit(
1019 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
1020 );
1021 assert.equal(readyExit._tag, "Failure");
1022 assert.equal(yield* Ref.get(scenario.createCalls), 2);
1023 assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
1024​
1025 // 3. Activating must not mistake the splash for the main window: it
1026 // retries the open and brings up the real main instead of leaving
1027 // the user stranded on "Connecting to WSL".
1028 yield* desktopWindow.activate;
1029 assert.equal(yield* Ref.get(scenario.createCalls), 3);
1030 const registeredMain = yield* Ref.get(scenario.mainWindow);
1031 assert.isTrue(Option.isSome(registeredMain));
1032 assert.equal(Option.getOrThrow(registeredMain), main.window);
1033 }).pipe(Effect.provide(scenario.layer));
1034 }),
1035 );
1036​
1037 it.effect(
1038 "re-reveals the connecting splash on activate while the backend is still cold-booting",
1039 () =>
1040 Effect.gen(function* () {
1041 const splash = makeFakeBrowserWindow();
1042 // Only the splash is ever created; the backend never reports ready.
1043 const scenario = yield* makeSplashScenario([splash.window]);
1044​
1045 yield* Effect.gen(function* () {
1046 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1047​
1048 yield* desktopWindow.showConnectingSplash;
1049 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1050​
1051 // Taskbar/dock activation during cold boot must bring the splash back
1052 // rather than no-op and leave it hidden until the backend finishes.
1053 yield* desktopWindow.activate;
1054 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1055 assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
1056 }).pipe(Effect.provide(scenario.layer));
1057 }),
1058 );
1059​
1060 it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
1061 Effect.gen(function* () {
1062 const splash = makeFakeBrowserWindow();
1063 const main = makeFakeBrowserWindow();
1064 const scenario = yield* makeSplashScenario([splash.window, main.window]);
1065​
1066 yield* Effect.gen(function* () {
1067 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1068​
1069 yield* desktopWindow.showConnectingSplash;
1070 yield* desktopWindow.dispatchMenuAction("open-settings");
1071​
1072 assert.equal(yield* Ref.get(scenario.createCalls), 1);
1073 assert.equal(splash.send.mock.calls.length, 0);
1074 assert.equal(main.send.mock.calls.length, 0);
1075 }).pipe(Effect.provide(scenario.layer));
1076 }),
1077 );
1078​
1079 it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
1080 Effect.gen(function* () {
1081 const splash = makeFakeBrowserWindow();
1082 const main = makeFakeBrowserWindow();
1083 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
1084​
1085 yield* Effect.gen(function* () {
1086 const desktopWindow = yield* DesktopWindow.DesktopWindow;
1087​
1088 yield* desktopWindow.showConnectingSplash;
1089 const readyExit = yield* Effect.exit(
1090 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
1091 );
1092 assert.equal(readyExit._tag, "Failure");
1093​
1094 yield* desktopWindow.dispatchMenuAction("open-settings");
1095​
1096 assert.equal(yield* Ref.get(scenario.createCalls), 3);
1097 assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
1098 }).pipe(Effect.provide(scenario.layer));
1099 }),
1100 );
1101});