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