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