Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7
8import * as Electron from "electron";
9
10import * as DesktopAssets from "../app/DesktopAssets.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import { makeComponentLogger } from "../app/DesktopObservability.ts";
13import * as ElectronMenu from "../electron/ElectronMenu.ts";
14import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
15import * as ElectronShell from "../electron/ElectronShell.ts";
16import * as ElectronTheme from "../electron/ElectronTheme.ts";
17import * as ElectronWindow from "../electron/ElectronWindow.ts";
18import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
19import * as PreviewManager from "../preview/Manager.ts";
20import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
21
22const TITLEBAR_HEIGHT = 40;
23const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
24const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
25const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
26const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
27const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
28const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
29 -2, // ERR_FAILED
30 -7, // ERR_TIMED_OUT
31 -9, // ERR_UNEXPECTED (custom protocol handler rejected)
32 -102, // ERR_CONNECTION_REFUSED
33 -105, // ERR_NAME_NOT_RESOLVED
34 -106, // ERR_INTERNET_DISCONNECTED
35 -118, // ERR_CONNECTION_TIMED_OUT
36]);
37
38type WindowTitleBarOptions = Pick<
39 Electron.BrowserWindowConstructorOptions,
40 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
41>;
42
43type DesktopWindowRuntimeServices =
44 | DesktopEnvironment.DesktopEnvironment
45 | DesktopAssets.DesktopAssets
46 | DesktopAppSettings.DesktopAppSettings
47 | ElectronMenu.ElectronMenu
48 | ElectronShell.ElectronShell
49 | ElectronTheme.ElectronTheme
50 | ElectronWindow.ElectronWindow
51 | PreviewManager.PreviewManager;
52
53export type DesktopWindowError =
54 | ElectronWindow.ElectronWindowCreateError
55 | PreviewManager.PreviewManagerError;
56
57export class DesktopWindow extends Context.Service<
58 DesktopWindow,
59 {
60 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
61 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
62 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
63 readonly activate: Effect.Effect<void, DesktopWindowError>;
64 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
65 // Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
66 // mode), before the WSL backend that serves the renderer is ready. It is
67 // dismissed automatically once the real main window reveals.
68 readonly showConnectingSplash: Effect.Effect<void>;
69 // Marks the primary backend as ready so `createMainIfBackendReady` and the
70 // macOS "activate without windows" path may open the real main window. The
71 // renderer now always loads the local client URL (getDesktopUrl) and connects
72 // to the backend through the connection layer, so the reported httpBaseUrl is
73 // no longer used to point the window at the backend — it is kept only for the
74 // readiness log and to preserve the callback contract the backend pool drives.
75 readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
76 // Called when the backend transitions back to "not ready" (clean stop,
77 // restart, crash). Clears the latch that lets `activate` auto-create a
78 // window so a "macOS dock click" while the backend is down doesn't
79 // produce a stranded window pointing at nothing.
80 readonly handleBackendNotReady: Effect.Effect<void>;
81 readonly flushMainWindowBounds: Effect.Effect<void>;
82 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
83 readonly syncAppearance: Effect.Effect<void>;
84 }
85>()("@t3tools/desktop/window/DesktopWindow") {}
86
87const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
88 makeComponentLogger("desktop-window");
89
90function getIconOption(
91 iconPaths: DesktopAssets.DesktopIconPaths,
92 platform: NodeJS.Platform,
93): { icon: string } | Record<string, never> {
94 if (platform === "darwin") return {}; // macOS uses .icns from app bundle
95 const ext = platform === "win32" ? "ico" : "png";
96 return Option.match(iconPaths[ext], {
97 onNone: () => ({}),
98 onSome: (icon) => ({ icon }),
99 });
100}
101
102function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
103 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
104}
105
106type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
107
108function windowFitsWithinDisplay(
109 windowBounds: DesktopAppSettings.DesktopWindowBounds,
110 displayBounds: DisplayBounds,
111): boolean {
112 return (
113 windowBounds.x >= displayBounds.x &&
114 windowBounds.y >= displayBounds.y &&
115 windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
116 windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
117 );
118}
119
120function windowBoundsEqual(
121 left: DesktopAppSettings.DesktopWindowBounds,
122 right: DesktopAppSettings.DesktopWindowBounds,
123): boolean {
124 return (
125 left.x === right.x &&
126 left.y === right.y &&
127 left.width === right.width &&
128 left.height === right.height
129 );
130}
131
132export function resolveInitialMainWindowBounds(
133 persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
134 displays: readonly DisplayBounds[],
135): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
136 if (
137 persistedBounds !== null &&
138 displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
139 ) {
140 return persistedBounds;
141 }
142 return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
143}
144
145// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
146// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
147// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
148function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
149 const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
150 const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
151 const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
152 const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
153 const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
154 return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
155}
156
157export function isSameOriginRendererNavigation(input: {
158 readonly applicationUrl: string;
159 readonly navigationUrl: string;
160}): boolean {
161 try {
162 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
163 } catch {
164 return false;
165 }
166}
167
168export function isRetryableDevelopmentRendererLoadFailure(input: {
169 readonly applicationUrl: string;
170 readonly errorCode: number;
171 readonly isMainFrame: boolean;
172 readonly validatedUrl: string;
173}): boolean {
174 return (
175 input.isMainFrame &&
176 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
177 isSameOriginRendererNavigation({
178 applicationUrl: input.applicationUrl,
179 navigationUrl: input.validatedUrl,
180 })
181 );
182}
183
184function getWindowTitleBarOptions(
185 shouldUseDarkColors: boolean,
186 platform: NodeJS.Platform,
187): WindowTitleBarOptions {
188 if (platform === "darwin") {
189 return {
190 titleBarStyle: "hiddenInset",
191 trafficLightPosition: { x: 16, y: 18 },
192 };
193 }
194
195 return {
196 titleBarStyle: "hidden",
197 titleBarOverlay: {
198 color: TITLEBAR_COLOR,
199 height: TITLEBAR_HEIGHT,
200 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
201 },
202 };
203}
204
205function syncWindowAppearance(
206 window: Electron.BrowserWindow,
207 shouldUseDarkColors: boolean,
208 platform: NodeJS.Platform,
209): Effect.Effect<void> {
210 return Effect.sync(() => {
211 if (window.isDestroyed()) {
212 return;
213 }
214
215 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
216 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
217 if (typeof titleBarOverlay === "object") {
218 window.setTitleBarOverlay(titleBarOverlay);
219 }
220 });
221}
222
223type RevealSubscription = (listener: () => void) => void;
224
225function bindFirstRevealTrigger(
226 subscribers: readonly RevealSubscription[],
227 reveal: () => void,
228): void {
229 let revealed = false;
230 const fire = () => {
231 if (revealed) return;
232 revealed = true;
233 reveal();
234 };
235 for (const subscribe of subscribers) {
236 subscribe(fire);
237 }
238}
239
240export const make = Effect.gen(function* () {
241 const environment = yield* DesktopEnvironment.DesktopEnvironment;
242 const assets = yield* DesktopAssets.DesktopAssets;
243 const electronMenu = yield* ElectronMenu.ElectronMenu;
244 const electronShell = yield* ElectronShell.ElectronShell;
245 const electronTheme = yield* ElectronTheme.ElectronTheme;
246 const electronWindow = yield* ElectronWindow.ElectronWindow;
247 const previewManager = yield* PreviewManager.PreviewManager;
248 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
249 // Window-side latch for the primary backend's readiness. Set by
250 // handleBackendReady (driven by the pool's onReady callback), cleared
251 // by handleBackendNotReady (driven by onShutdown). Only consumed by
252 // createMainIfBackendReady, which gates the post-readiness window
253 // open in development and the macOS "activate without windows" path.
254 const backendReadyRef = yield* Ref.make(false);
255 // The transient "Connecting to WSL" splash window, tracked separately so it
256 // is never mistaken for the real main window.
257 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
258 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
259 const runFork = Effect.runForkWith(context);
260 const runPromise = Effect.runPromiseWith(context);
261 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
262
263 const dismissConnectingSplash = Effect.gen(function* () {
264 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
265 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
266 splash.value.close();
267 }
268 });
269
270 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
271 // which during WSL-only boot is the connecting splash. The splash is never
272 // registered via setMain, so it must be treated as "no real main window" --
273 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
274 // open (or retry) the real main. That is the failure the pool's swallowed
275 // post-readiness window-open error would otherwise strand the user in:
276 // splash up, backend ready, no main, and activation only re-reveals splash.
277 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
278 Ref.get(splashWindowRef).pipe(
279 Effect.map((splash) =>
280 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
281 ? Option.none<Electron.BrowserWindow>()
282 : window,
283 ),
284 );
285
286 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
287 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
288
289 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
290 Electron.BrowserWindow,
291 DesktopWindowError
292 > {
293 yield* previewManager.getBrowserSession();
294 const applicationUrl = getDesktopUrl(environment.isDevelopment);
295 const iconPaths = yield* assets.iconPaths;
296 const iconOption = getIconOption(iconPaths, environment.platform);
297 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
298 const persistedSettings = yield* desktopSettings.get;
299 const persistedBounds = persistedSettings.mainWindowBounds;
300 const displayBoundsResult = yield* Effect.sync(() => {
301 try {
302 return {
303 _tag: "Success" as const,
304 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
305 };
306 } catch (cause) {
307 return { _tag: "Failure" as const, cause };
308 }
309 });
310 const displayBounds =
311 displayBoundsResult._tag === "Success"
312 ? displayBoundsResult.bounds
313 : yield* logWindowWarning("failed to read connected displays; using defaults", {
314 cause: displayBoundsResult.cause,
315 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
316 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
317 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
318 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
319 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
320 }
321 const window = yield* electronWindow.create({
322 ...initialBounds,
323 minWidth: 840,
324 minHeight: 620,
325 show: false,
326 autoHideMenuBar: true,
327 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
328 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
329 ...iconOption,
330 title: environment.displayName,
331 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
332 webPreferences: {
333 preload: environment.preloadPath,
334 backgroundThrottling: false,
335 contextIsolation: true,
336 nodeIntegration: false,
337 sandbox: true,
338 webviewTag: true,
339 },
340 });
341
342 if (environment.platform === "darwin") {
343 window.setAutoHideCursor(false);
344 }
345 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
346 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
347 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
348 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
349 if (window.isDestroyed()) {
350 return null;
351 }
352 const bounds =
353 window.isFullScreen() || window.isMaximized() || window.isMinimized()
354 ? window.getNormalBounds()
355 : window.getBounds();
356 return DesktopAppSettings.normalizeMainWindowBounds({
357 x: Math.round(bounds.x),
358 y: Math.round(bounds.y),
359 width: Math.round(bounds.width),
360 height: Math.round(bounds.height),
361 });
362 };
363 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
364 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
365 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
366 if (!boundsPersistenceEnabled) {
367 return pendingBoundsPersistFiber;
368 }
369 const bounds = readPersistableBounds();
370 if (bounds === null) {
371 return pendingBoundsPersistFiber;
372 }
373 pendingBoundsPersistFiber = runFork(
374 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
375 Effect.asVoid,
376 Effect.catch((error) =>
377 logWindowWarning("failed to persist main window bounds", {
378 message: error.message,
379 }),
380 ),
381 ),
382 );
383 return pendingBoundsPersistFiber;
384 };
385 const scheduleBoundsPersist = () => {
386 if (!boundsPersistenceEnabled) {
387 const currentBounds = readPersistableBounds();
388 if (
389 currentBounds === null ||
390 (fallbackWindowBounds !== null &&
391 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
392 window.isMaximized() === fallbackWindowMaximized)
393 ) {
394 return;
395 }
396 }
397 boundsPersistenceEnabled = true;
398 if (boundsPersistFiber !== undefined) {
399 const fiber = boundsPersistFiber;
400 boundsPersistFiber = undefined;
401 runFork(Fiber.interrupt(fiber));
402 }
403 boundsPersistFiber = runFork(
404 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
405 Effect.andThen(
406 Effect.sync(() => {
407 boundsPersistFiber = undefined;
408 void persistCurrentBounds();
409 }),
410 ),
411 ),
412 );
413 };
414 const clearBoundsPersist = () => {
415 if (boundsPersistFiber === undefined) {
416 return;
417 }
418 const fiber = boundsPersistFiber;
419 boundsPersistFiber = undefined;
420 runFork(Fiber.interrupt(fiber));
421 };
422 const flushBoundsPersist = Effect.sync(() => {
423 clearBoundsPersist();
424 return persistCurrentBounds();
425 }).pipe(
426 Effect.flatMap((fiber) =>
427 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
428 ),
429 );
430 flushMainWindowBounds = flushBoundsPersist;
431
432 yield* previewManager.setMainWindow(window);
433 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
434 if (
435 typeof params.partition !== "string" ||
436 !previewManager.isBrowserPartition(params.partition)
437 ) {
438 event.preventDefault();
439 return;
440 }
441 webPreferences.sandbox = true;
442 webPreferences.nodeIntegration = false;
443 webPreferences.nodeIntegrationInSubFrames = false;
444 webPreferences.contextIsolation = false;
445 });
446
447 window.webContents.on("context-menu", (event, params) => {
448 event.preventDefault();
449
450 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
451
452 if (params.misspelledWord) {
453 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
454 menuTemplate.push({
455 label: suggestion,
456 click: () => window.webContents.replaceMisspelling(suggestion),
457 });
458 }
459 if (params.dictionarySuggestions.length === 0) {
460 menuTemplate.push({ label: "No suggestions", enabled: false });
461 }
462 menuTemplate.push({ type: "separator" });
463 }
464
465 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
466 menuTemplate.push(
467 {
468 label: "Copy Link",
469 click: () => {
470 void runPromise(electronShell.copyText(params.linkURL));
471 },
472 },
473 { type: "separator" },
474 );
475 }
476
477 if (params.mediaType === "image") {
478 menuTemplate.push({
479 label: "Copy Image",
480 click: () => window.webContents.copyImageAt(params.x, params.y),
481 });
482 menuTemplate.push({ type: "separator" });
483 }
484
485 menuTemplate.push(
486 { role: "cut", enabled: params.editFlags.canCut },
487 { role: "copy", enabled: params.editFlags.canCopy },
488 { role: "paste", enabled: params.editFlags.canPaste },
489 { role: "selectAll", enabled: params.editFlags.canSelectAll },
490 );
491
492 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
493 });
494
495 window.webContents.setWindowOpenHandler(({ url }) => {
496 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
497 void runPromise(electronShell.openExternal(url));
498 }
499 return { action: "deny" };
500 });
501 window.webContents.on("will-navigate", (event, url) => {
502 if (
503 isSameOriginRendererNavigation({
504 applicationUrl,
505 navigationUrl: url,
506 })
507 ) {
508 return;
509 }
510
511 event.preventDefault();
512 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
513 void runPromise(electronShell.openExternal(url));
514 }
515 });
516
517 window.on("page-title-updated", (event) => {
518 event.preventDefault();
519 window.setTitle(environment.displayName);
520 });
521 window.on("resize", scheduleBoundsPersist);
522 window.on("move", scheduleBoundsPersist);
523 window.on("maximize", scheduleBoundsPersist);
524 window.on("unmaximize", scheduleBoundsPersist);
525 window.on("close", () => {
526 runFork(flushBoundsPersist);
527 });
528
529 if (environment.platform === "darwin") {
530 window.on("enter-full-screen", () => {
531 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
532 });
533 window.on("leave-full-screen", () => {
534 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
535 });
536 }
537
538 let developmentLoadRetryIndex = 0;
539 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
540 const clearDevelopmentLoadRetry = () => {
541 if (developmentLoadRetryFiber === undefined) {
542 return;
543 }
544 const retryFiber = developmentLoadRetryFiber;
545 developmentLoadRetryFiber = undefined;
546 runFork(Fiber.interrupt(retryFiber));
547 };
548 const loadApplication = () => {
549 if (window.isDestroyed()) {
550 return;
551 }
552 void window.loadURL(applicationUrl).catch(() => undefined);
553 };
554 const scheduleDevelopmentLoadRetry = () => {
555 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
556 return undefined;
557 }
558
559 const retryIndex = Math.min(
560 developmentLoadRetryIndex,
561 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
562 );
563 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
564 developmentLoadRetryIndex += 1;
565 developmentLoadRetryFiber = runFork(
566 Effect.sleep(retryInMs).pipe(
567 Effect.andThen(
568 Effect.sync(() => {
569 developmentLoadRetryFiber = undefined;
570 if (!window.isDestroyed()) {
571 loadApplication();
572 }
573 }),
574 ),
575 ),
576 );
577 return retryInMs;
578 };
579
580 window.webContents.on("did-finish-load", () => {
581 if (
582 environment.isDevelopment &&
583 !isSameOriginRendererNavigation({
584 applicationUrl,
585 navigationUrl: window.webContents.getURL(),
586 })
587 ) {
588 return;
589 }
590 clearDevelopmentLoadRetry();
591 developmentLoadRetryIndex = 0;
592 window.setTitle(environment.displayName);
593 });
594 window.webContents.on(
595 "did-fail-load",
596 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
597 if (!isMainFrame) {
598 return;
599 }
600 const retryInMs =
601 environment.isDevelopment &&
602 isRetryableDevelopmentRendererLoadFailure({
603 applicationUrl,
604 errorCode,
605 isMainFrame,
606 validatedUrl: validatedURL,
607 })
608 ? scheduleDevelopmentLoadRetry()
609 : undefined;
610 void runPromise(
611 logWindowWarning("main window failed to load", {
612 errorCode,
613 errorDescription,
614 url: validatedURL,
615 ...(retryInMs === undefined ? {} : { retryInMs }),
616 }),
617 );
618 },
619 );
620 window.webContents.on("render-process-gone", (_event, details) => {
621 void runPromise(
622 logWindowWarning("main window render process gone", {
623 reason: details.reason,
624 exitCode: details.exitCode,
625 }),
626 );
627 });
628
629 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
630 if (environment.platform === "linux") {
631 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
632 }
633 bindFirstRevealTrigger(revealSubscribers, () => {
634 // Reveal the real window, then close the connecting splash (if any) so the
635 // two don't overlap and there's no blank gap between them.
636 if (persistedSettings.mainWindowMaximized) {
637 window.maximize();
638 }
639 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
640 });
641
642 loadApplication();
643 if (environment.isDevelopment) {
644 window.webContents.openDevTools({ mode: "detach" });
645 }
646
647 window.on("closed", () => {
648 clearDevelopmentLoadRetry();
649 clearBoundsPersist();
650 void runPromise(electronWindow.clearMain(Option.some(window)));
651 });
652
653 return window;
654 });
655
656 const createMain = Effect.gen(function* () {
657 const window = yield* createWindow();
658 yield* electronWindow.setMain(window);
659 yield* logWindowInfo("main window created");
660 return window;
661 }).pipe(Effect.withSpan("desktop.window.createMain"));
662
663 const ensureMain = Effect.gen(function* () {
664 const existingWindow = yield* currentMainWindow;
665 if (Option.isSome(existingWindow)) {
666 return existingWindow.value;
667 }
668 return yield* createMain;
669 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
670
671 const revealOrCreateMain = Effect.gen(function* () {
672 const window = yield* ensureMain;
673 yield* electronWindow.reveal(window);
674 return window;
675 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
676
677 const createMainIfBackendReady = Effect.gen(function* () {
678 const backendReady = yield* Ref.get(backendReadyRef);
679 if (!backendReady) return;
680 const existingWindow = yield* currentMainWindow;
681 if (Option.isSome(existingWindow)) return;
682 yield* createMain;
683 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
684
685 const showConnectingSplash = Effect.gen(function* () {
686 // Only when nothing is shown yet: no real window, no existing splash.
687 const existingSplash = yield* Ref.get(splashWindowRef);
688 if (Option.isSome(existingSplash)) return;
689 const existingWindow = yield* electronWindow.currentMainOrFirst;
690 if (Option.isSome(existingWindow)) return;
691
692 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
693 const splash = yield* electronWindow.create({
694 width: 360,
695 height: 220,
696 resizable: false,
697 minimizable: false,
698 maximizable: false,
699 fullscreenable: false,
700 frame: false,
701 center: true,
702 show: false,
703 skipTaskbar: false,
704 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
705 title: environment.displayName,
706 webPreferences: {
707 contextIsolation: true,
708 nodeIntegration: false,
709 sandbox: true,
710 },
711 });
712 yield* Ref.set(splashWindowRef, Option.some(splash));
713 splash.once("closed", () => {
714 void runPromise(Ref.set(splashWindowRef, Option.none()));
715 });
716 splash.once("ready-to-show", () => {
717 if (!splash.isDestroyed()) {
718 splash.show();
719 }
720 });
721 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
722 yield* logWindowInfo("connecting splash shown");
723 }).pipe(
724 // The splash is best-effort UX — never let it fail startup.
725 Effect.catch((error) =>
726 logWindowWarning("failed to show connecting splash", { message: error.message }),
727 ),
728 Effect.withSpan("desktop.window.showConnectingSplash"),
729 );
730
731 return DesktopWindow.of({
732 createMain,
733 ensureMain,
734 revealOrCreateMain,
735 activate: Effect.gen(function* () {
736 const existingWindow = yield* currentMainWindow;
737 if (Option.isSome(existingWindow)) {
738 yield* electronWindow.reveal(existingWindow.value);
739 return;
740 }
741 // No real main window yet. While the backend is still cold-booting,
742 // re-reveal the connecting splash so taskbar/dock activation brings it
743 // back instead of doing nothing. Once the backend is ready we fall
744 // through to (re)create the real main -- including retrying a previously
745 // failed open the pool swallowed -- rather than latching onto the splash.
746 const backendReady = yield* Ref.get(backendReadyRef);
747 if (!backendReady) {
748 const splash = yield* Ref.get(splashWindowRef);
749 if (Option.isSome(splash)) {
750 yield* electronWindow.reveal(splash.value);
751 return;
752 }
753 }
754 yield* createMainIfBackendReady;
755 }).pipe(Effect.withSpan("desktop.window.activate")),
756 createMainIfBackendReady,
757 showConnectingSplash,
758 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
759 yield* Ref.set(backendReadyRef, true);
760 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
761 yield* createMainIfBackendReady;
762 }),
763 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
764 Effect.withSpan("desktop.window.handleBackendNotReady"),
765 ),
766 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
767 Effect.withSpan("desktop.window.flushMainWindowBounds"),
768 ),
769 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
770 yield* Effect.annotateCurrentSpan({ action });
771 const existingWindow = yield* focusedMainWindow;
772 if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
773 return;
774 }
775 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
776
777 const send = () => {
778 if (targetWindow.isDestroyed()) return;
779 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
780 void runPromise(electronWindow.reveal(targetWindow));
781 };
782
783 if (targetWindow.webContents.isLoadingMainFrame()) {
784 targetWindow.webContents.once("did-finish-load", send);
785 return;
786 }
787
788 send();
789 }),
790 syncAppearance: Effect.gen(function* () {
791 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
792 yield* electronWindow.syncAllAppearance((window) =>
793 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
794 );
795 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
796 });
797});
798
799export const layer = Layer.effect(DesktopWindow, make);