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 contextIsolation: true,
335 nodeIntegration: false,
336 sandbox: true,
337 webviewTag: true,
338 },
339 });
340
341 if (environment.platform === "darwin") {
342 window.setAutoHideCursor(false);
343 }
344 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
345 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
346 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
347 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
348 if (window.isDestroyed()) {
349 return null;
350 }
351 const bounds =
352 window.isFullScreen() || window.isMaximized() || window.isMinimized()
353 ? window.getNormalBounds()
354 : window.getBounds();
355 return DesktopAppSettings.normalizeMainWindowBounds({
356 x: Math.round(bounds.x),
357 y: Math.round(bounds.y),
358 width: Math.round(bounds.width),
359 height: Math.round(bounds.height),
360 });
361 };
362 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
363 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
364 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
365 if (!boundsPersistenceEnabled) {
366 return pendingBoundsPersistFiber;
367 }
368 const bounds = readPersistableBounds();
369 if (bounds === null) {
370 return pendingBoundsPersistFiber;
371 }
372 pendingBoundsPersistFiber = runFork(
373 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
374 Effect.asVoid,
375 Effect.catch((error) =>
376 logWindowWarning("failed to persist main window bounds", {
377 message: error.message,
378 }),
379 ),
380 ),
381 );
382 return pendingBoundsPersistFiber;
383 };
384 const scheduleBoundsPersist = () => {
385 if (!boundsPersistenceEnabled) {
386 const currentBounds = readPersistableBounds();
387 if (
388 currentBounds === null ||
389 (fallbackWindowBounds !== null &&
390 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
391 window.isMaximized() === fallbackWindowMaximized)
392 ) {
393 return;
394 }
395 }
396 boundsPersistenceEnabled = true;
397 if (boundsPersistFiber !== undefined) {
398 const fiber = boundsPersistFiber;
399 boundsPersistFiber = undefined;
400 runFork(Fiber.interrupt(fiber));
401 }
402 boundsPersistFiber = runFork(
403 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
404 Effect.andThen(
405 Effect.sync(() => {
406 boundsPersistFiber = undefined;
407 void persistCurrentBounds();
408 }),
409 ),
410 ),
411 );
412 };
413 const clearBoundsPersist = () => {
414 if (boundsPersistFiber === undefined) {
415 return;
416 }
417 const fiber = boundsPersistFiber;
418 boundsPersistFiber = undefined;
419 runFork(Fiber.interrupt(fiber));
420 };
421 const flushBoundsPersist = Effect.sync(() => {
422 clearBoundsPersist();
423 return persistCurrentBounds();
424 }).pipe(
425 Effect.flatMap((fiber) =>
426 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
427 ),
428 );
429 flushMainWindowBounds = flushBoundsPersist;
430
431 yield* previewManager.setMainWindow(window);
432 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
433 if (
434 typeof params.partition !== "string" ||
435 !previewManager.isBrowserPartition(params.partition)
436 ) {
437 event.preventDefault();
438 return;
439 }
440 webPreferences.sandbox = true;
441 webPreferences.nodeIntegration = false;
442 webPreferences.nodeIntegrationInSubFrames = false;
443 webPreferences.contextIsolation = false;
444 });
445
446 window.webContents.on("context-menu", (event, params) => {
447 event.preventDefault();
448
449 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
450
451 if (params.misspelledWord) {
452 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
453 menuTemplate.push({
454 label: suggestion,
455 click: () => window.webContents.replaceMisspelling(suggestion),
456 });
457 }
458 if (params.dictionarySuggestions.length === 0) {
459 menuTemplate.push({ label: "No suggestions", enabled: false });
460 }
461 menuTemplate.push({ type: "separator" });
462 }
463
464 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
465 menuTemplate.push(
466 {
467 label: "Copy Link",
468 click: () => {
469 void runPromise(electronShell.copyText(params.linkURL));
470 },
471 },
472 { type: "separator" },
473 );
474 }
475
476 if (params.mediaType === "image") {
477 menuTemplate.push({
478 label: "Copy Image",
479 click: () => window.webContents.copyImageAt(params.x, params.y),
480 });
481 menuTemplate.push({ type: "separator" });
482 }
483
484 menuTemplate.push(
485 { role: "cut", enabled: params.editFlags.canCut },
486 { role: "copy", enabled: params.editFlags.canCopy },
487 { role: "paste", enabled: params.editFlags.canPaste },
488 { role: "selectAll", enabled: params.editFlags.canSelectAll },
489 );
490
491 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
492 });
493
494 window.webContents.setWindowOpenHandler(({ url }) => {
495 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
496 void runPromise(electronShell.openExternal(url));
497 }
498 return { action: "deny" };
499 });
500 window.webContents.on("will-navigate", (event, url) => {
501 if (
502 isSameOriginRendererNavigation({
503 applicationUrl,
504 navigationUrl: url,
505 })
506 ) {
507 return;
508 }
509
510 event.preventDefault();
511 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
512 void runPromise(electronShell.openExternal(url));
513 }
514 });
515
516 window.on("page-title-updated", (event) => {
517 event.preventDefault();
518 window.setTitle(environment.displayName);
519 });
520 window.on("resize", scheduleBoundsPersist);
521 window.on("move", scheduleBoundsPersist);
522 window.on("maximize", scheduleBoundsPersist);
523 window.on("unmaximize", scheduleBoundsPersist);
524 window.on("close", () => {
525 runFork(flushBoundsPersist);
526 });
527
528 if (environment.platform === "darwin") {
529 window.on("enter-full-screen", () => {
530 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
531 });
532 window.on("leave-full-screen", () => {
533 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
534 });
535 }
536
537 let developmentLoadRetryIndex = 0;
538 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
539 const clearDevelopmentLoadRetry = () => {
540 if (developmentLoadRetryFiber === undefined) {
541 return;
542 }
543 const retryFiber = developmentLoadRetryFiber;
544 developmentLoadRetryFiber = undefined;
545 runFork(Fiber.interrupt(retryFiber));
546 };
547 const loadApplication = () => {
548 if (window.isDestroyed()) {
549 return;
550 }
551 void window.loadURL(applicationUrl).catch(() => undefined);
552 };
553 const scheduleDevelopmentLoadRetry = () => {
554 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
555 return undefined;
556 }
557
558 const retryIndex = Math.min(
559 developmentLoadRetryIndex,
560 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
561 );
562 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
563 developmentLoadRetryIndex += 1;
564 developmentLoadRetryFiber = runFork(
565 Effect.sleep(retryInMs).pipe(
566 Effect.andThen(
567 Effect.sync(() => {
568 developmentLoadRetryFiber = undefined;
569 if (!window.isDestroyed()) {
570 loadApplication();
571 }
572 }),
573 ),
574 ),
575 );
576 return retryInMs;
577 };
578
579 window.webContents.on("did-finish-load", () => {
580 if (
581 environment.isDevelopment &&
582 !isSameOriginRendererNavigation({
583 applicationUrl,
584 navigationUrl: window.webContents.getURL(),
585 })
586 ) {
587 return;
588 }
589 clearDevelopmentLoadRetry();
590 developmentLoadRetryIndex = 0;
591 window.setTitle(environment.displayName);
592 });
593 window.webContents.on(
594 "did-fail-load",
595 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
596 if (!isMainFrame) {
597 return;
598 }
599 const retryInMs =
600 environment.isDevelopment &&
601 isRetryableDevelopmentRendererLoadFailure({
602 applicationUrl,
603 errorCode,
604 isMainFrame,
605 validatedUrl: validatedURL,
606 })
607 ? scheduleDevelopmentLoadRetry()
608 : undefined;
609 void runPromise(
610 logWindowWarning("main window failed to load", {
611 errorCode,
612 errorDescription,
613 url: validatedURL,
614 ...(retryInMs === undefined ? {} : { retryInMs }),
615 }),
616 );
617 },
618 );
619 window.webContents.on("render-process-gone", (_event, details) => {
620 void runPromise(
621 logWindowWarning("main window render process gone", {
622 reason: details.reason,
623 exitCode: details.exitCode,
624 }),
625 );
626 });
627
628 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
629 if (environment.platform === "linux") {
630 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
631 }
632 bindFirstRevealTrigger(revealSubscribers, () => {
633 // Reveal the real window, then close the connecting splash (if any) so the
634 // two don't overlap and there's no blank gap between them.
635 if (persistedSettings.mainWindowMaximized) {
636 window.maximize();
637 }
638 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
639 });
640
641 loadApplication();
642 if (environment.isDevelopment) {
643 window.webContents.openDevTools({ mode: "detach" });
644 }
645
646 window.on("closed", () => {
647 clearDevelopmentLoadRetry();
648 clearBoundsPersist();
649 void runPromise(electronWindow.clearMain(Option.some(window)));
650 });
651
652 return window;
653 });
654
655 const createMain = Effect.gen(function* () {
656 const window = yield* createWindow();
657 yield* electronWindow.setMain(window);
658 yield* logWindowInfo("main window created");
659 return window;
660 }).pipe(Effect.withSpan("desktop.window.createMain"));
661
662 const ensureMain = Effect.gen(function* () {
663 const existingWindow = yield* currentMainWindow;
664 if (Option.isSome(existingWindow)) {
665 return existingWindow.value;
666 }
667 return yield* createMain;
668 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
669
670 const revealOrCreateMain = Effect.gen(function* () {
671 const window = yield* ensureMain;
672 yield* electronWindow.reveal(window);
673 return window;
674 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
675
676 const createMainIfBackendReady = Effect.gen(function* () {
677 const backendReady = yield* Ref.get(backendReadyRef);
678 if (!backendReady) return;
679 const existingWindow = yield* currentMainWindow;
680 if (Option.isSome(existingWindow)) return;
681 yield* createMain;
682 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
683
684 const showConnectingSplash = Effect.gen(function* () {
685 // Only when nothing is shown yet: no real window, no existing splash.
686 const existingSplash = yield* Ref.get(splashWindowRef);
687 if (Option.isSome(existingSplash)) return;
688 const existingWindow = yield* electronWindow.currentMainOrFirst;
689 if (Option.isSome(existingWindow)) return;
690
691 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
692 const splash = yield* electronWindow.create({
693 width: 360,
694 height: 220,
695 resizable: false,
696 minimizable: false,
697 maximizable: false,
698 fullscreenable: false,
699 frame: false,
700 center: true,
701 show: false,
702 skipTaskbar: false,
703 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
704 title: environment.displayName,
705 webPreferences: {
706 contextIsolation: true,
707 nodeIntegration: false,
708 sandbox: true,
709 },
710 });
711 yield* Ref.set(splashWindowRef, Option.some(splash));
712 splash.once("closed", () => {
713 void runPromise(Ref.set(splashWindowRef, Option.none()));
714 });
715 splash.once("ready-to-show", () => {
716 if (!splash.isDestroyed()) {
717 splash.show();
718 }
719 });
720 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
721 yield* logWindowInfo("connecting splash shown");
722 }).pipe(
723 // The splash is best-effort UX — never let it fail startup.
724 Effect.catch((error) =>
725 logWindowWarning("failed to show connecting splash", { message: error.message }),
726 ),
727 Effect.withSpan("desktop.window.showConnectingSplash"),
728 );
729
730 return DesktopWindow.of({
731 createMain,
732 ensureMain,
733 revealOrCreateMain,
734 activate: Effect.gen(function* () {
735 const existingWindow = yield* currentMainWindow;
736 if (Option.isSome(existingWindow)) {
737 yield* electronWindow.reveal(existingWindow.value);
738 return;
739 }
740 // No real main window yet. While the backend is still cold-booting,
741 // re-reveal the connecting splash so taskbar/dock activation brings it
742 // back instead of doing nothing. Once the backend is ready we fall
743 // through to (re)create the real main -- including retrying a previously
744 // failed open the pool swallowed -- rather than latching onto the splash.
745 const backendReady = yield* Ref.get(backendReadyRef);
746 if (!backendReady) {
747 const splash = yield* Ref.get(splashWindowRef);
748 if (Option.isSome(splash)) {
749 yield* electronWindow.reveal(splash.value);
750 return;
751 }
752 }
753 yield* createMainIfBackendReady;
754 }).pipe(Effect.withSpan("desktop.window.activate")),
755 createMainIfBackendReady,
756 showConnectingSplash,
757 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
758 yield* Ref.set(backendReadyRef, true);
759 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
760 yield* createMainIfBackendReady;
761 }),
762 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
763 Effect.withSpan("desktop.window.handleBackendNotReady"),
764 ),
765 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
766 Effect.withSpan("desktop.window.flushMainWindowBounds"),
767 ),
768 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
769 yield* Effect.annotateCurrentSpan({ action });
770 const existingWindow = yield* focusedMainWindow;
771 if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
772 return;
773 }
774 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
775
776 const send = () => {
777 if (targetWindow.isDestroyed()) return;
778 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
779 void runPromise(electronWindow.reveal(targetWindow));
780 };
781
782 if (targetWindow.webContents.isLoadingMainFrame()) {
783 targetWindow.webContents.once("did-finish-load", send);
784 return;
785 }
786
787 send();
788 }),
789 syncAppearance: Effect.gen(function* () {
790 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
791 yield* electronWindow.syncAllAppearance((window) =>
792 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
793 );
794 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
795 });
796});
797
798export const layer = Layer.effect(DesktopWindow, make);