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