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

DesktopWindow.test.ts

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