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