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 { makeQuitShortcutHandler } 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
210export function concealPendingQuitWindow(
211 window: Pick<
212 Electron.BrowserWindow,
213 "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
214 >,
215): void {
216 if (window.isDestroyed()) return;
217 if (window.isFullScreen()) {
218 window.setFullScreen(false);
219 }
220 // Electron implements window opacity on macOS and Windows. Linux keeps the
221 // release-gated quit behavior but cannot make the pending window disappear.
222 window.setOpacity(0);
223}
224
225function getWindowTitleBarOptions(
226 shouldUseDarkColors: boolean,
227 platform: NodeJS.Platform,
228): WindowTitleBarOptions {
229 if (platform === "darwin") {
230 return {
231 titleBarStyle: "hiddenInset",
232 trafficLightPosition: { x: 16, y: 18 },
233 };
234 }
235
236 return {
237 titleBarStyle: "hidden",
238 titleBarOverlay: {
239 color: TITLEBAR_COLOR,
240 height: TITLEBAR_HEIGHT,
241 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
242 },
243 };
244}
245
246function syncWindowAppearance(
247 window: Electron.BrowserWindow,
248 shouldUseDarkColors: boolean,
249 platform: NodeJS.Platform,
250): Effect.Effect<void> {
251 return Effect.sync(() => {
252 if (window.isDestroyed()) {
253 return;
254 }
255
256 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
257 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
258 if (typeof titleBarOverlay === "object") {
259 window.setTitleBarOverlay(titleBarOverlay);
260 }
261 });
262}
263
264type RevealSubscription = (listener: () => void) => void;
265
266function bindFirstRevealTrigger(
267 subscribers: readonly RevealSubscription[],
268 reveal: () => void,
269): void {
270 let revealed = false;
271 const fire = () => {
272 if (revealed) return;
273 revealed = true;
274 reveal();
275 };
276 for (const subscribe of subscribers) {
277 subscribe(fire);
278 }
279}
280
281/** @public Service construction is part of the canonical Effect module API. */
282export const make = Effect.gen(function* () {
283 const environment = yield* DesktopEnvironment.DesktopEnvironment;
284 const assets = yield* DesktopAssets.DesktopAssets;
285 const electronMenu = yield* ElectronMenu.ElectronMenu;
286 const electronShell = yield* ElectronShell.ElectronShell;
287 const electronTheme = yield* ElectronTheme.ElectronTheme;
288 const electronWindow = yield* ElectronWindow.ElectronWindow;
289 const previewManager = yield* PreviewManager.PreviewManager;
290 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
291 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
292 const electronApp = yield* ElectronApp.ElectronApp;
293 // Window-side latch for the primary backend's readiness. Set by
294 // handleBackendReady (driven by the pool's onReady callback), cleared
295 // by handleBackendNotReady (driven by onShutdown). Only consumed by
296 // createMainIfBackendReady, which gates the post-readiness window
297 // open in development and the macOS "activate without windows" path.
298 const backendReadyRef = yield* Ref.make(false);
299 // The transient "Connecting to WSL" splash window, tracked separately so it
300 // is never mistaken for the real main window.
301 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
302 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
303 const runFork = Effect.runForkWith(context);
304 const runPromise = Effect.runPromiseWith(context);
305 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
306
307 const dismissConnectingSplash = Effect.gen(function* () {
308 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
309 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
310 splash.value.close();
311 }
312 });
313
314 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
315 // which during WSL-only boot is the connecting splash. The splash is never
316 // registered via setMain, so it must be treated as "no real main window" --
317 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
318 // open (or retry) the real main. That is the failure the pool's swallowed
319 // post-readiness window-open error would otherwise strand the user in:
320 // splash up, backend ready, no main, and activation only re-reveals splash.
321 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
322 Ref.get(splashWindowRef).pipe(
323 Effect.map((splash) =>
324 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
325 ? Option.none<Electron.BrowserWindow>()
326 : window,
327 ),
328 );
329
330 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
331 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
332
333 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
334 Electron.BrowserWindow,
335 DesktopWindowError
336 > {
337 yield* previewManager.getBrowserSession();
338 const applicationUrl = getDesktopUrl(environment.isDevelopment);
339 const iconPaths = yield* assets.iconPaths;
340 const iconOption = getIconOption(iconPaths, environment.platform);
341 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
342 const persistedSettings = yield* desktopSettings.get;
343 const persistedBounds = persistedSettings.mainWindowBounds;
344 const displayBoundsResult = yield* Effect.sync(() => {
345 try {
346 return {
347 _tag: "Success" as const,
348 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
349 };
350 } catch (cause) {
351 return { _tag: "Failure" as const, cause };
352 }
353 });
354 const displayBounds =
355 displayBoundsResult._tag === "Success"
356 ? displayBoundsResult.bounds
357 : yield* logWindowWarning("failed to read connected displays; using defaults", {
358 cause: displayBoundsResult.cause,
359 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
360 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
361 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
362 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
363 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
364 }
365 const window = yield* electronWindow.create({
366 ...initialBounds,
367 minWidth: 840,
368 minHeight: 620,
369 show: false,
370 autoHideMenuBar: true,
371 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
372 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
373 ...iconOption,
374 title: environment.displayName,
375 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
376 webPreferences: {
377 preload: environment.preloadPath,
378 // The window boots hidden (show: false until ready-to-show), and
379 // Chromium throttles hidden renderers: timers coalesce and rAF stops,
380 // which stalls first paint. Boot unthrottled; the first-reveal trigger
381 // re-enables throttling so a hidden or minimized window goes back to
382 // being cheap after it has been shown once.
383 backgroundThrottling: false,
384 contextIsolation: true,
385 nodeIntegration: false,
386 sandbox: true,
387 webviewTag: true,
388 },
389 });
390
391 if (environment.platform === "darwin") {
392 window.setAutoHideCursor(false);
393 }
394 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
395 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
396 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
397 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
398 if (window.isDestroyed()) {
399 return null;
400 }
401 const bounds =
402 window.isFullScreen() || window.isMaximized() || window.isMinimized()
403 ? window.getNormalBounds()
404 : window.getBounds();
405 return DesktopAppSettings.normalizeMainWindowBounds({
406 x: Math.round(bounds.x),
407 y: Math.round(bounds.y),
408 width: Math.round(bounds.width),
409 height: Math.round(bounds.height),
410 });
411 };
412 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
413 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
414 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
415 if (!boundsPersistenceEnabled) {
416 return pendingBoundsPersistFiber;
417 }
418 const bounds = readPersistableBounds();
419 if (bounds === null) {
420 return pendingBoundsPersistFiber;
421 }
422 pendingBoundsPersistFiber = runFork(
423 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
424 Effect.asVoid,
425 Effect.catch((error) =>
426 logWindowWarning("failed to persist main window bounds", {
427 message: error.message,
428 }),
429 ),
430 ),
431 );
432 return pendingBoundsPersistFiber;
433 };
434 const scheduleBoundsPersist = () => {
435 if (!boundsPersistenceEnabled) {
436 const currentBounds = readPersistableBounds();
437 if (
438 currentBounds === null ||
439 (fallbackWindowBounds !== null &&
440 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
441 window.isMaximized() === fallbackWindowMaximized)
442 ) {
443 return;
444 }
445 }
446 boundsPersistenceEnabled = true;
447 if (boundsPersistFiber !== undefined) {
448 const fiber = boundsPersistFiber;
449 boundsPersistFiber = undefined;
450 runFork(Fiber.interrupt(fiber));
451 }
452 boundsPersistFiber = runFork(
453 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
454 Effect.andThen(
455 Effect.sync(() => {
456 boundsPersistFiber = undefined;
457 void persistCurrentBounds();
458 }),
459 ),
460 ),
461 );
462 };
463 const clearBoundsPersist = () => {
464 if (boundsPersistFiber === undefined) {
465 return;
466 }
467 const fiber = boundsPersistFiber;
468 boundsPersistFiber = undefined;
469 runFork(Fiber.interrupt(fiber));
470 };
471 const flushBoundsPersist = Effect.sync(() => {
472 clearBoundsPersist();
473 return persistCurrentBounds();
474 }).pipe(
475 Effect.flatMap((fiber) =>
476 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
477 ),
478 );
479 flushMainWindowBounds = flushBoundsPersist;
480
481 yield* previewManager.setMainWindow(window);
482 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
483 if (
484 typeof params.partition !== "string" ||
485 !previewManager.isBrowserPartition(params.partition)
486 ) {
487 event.preventDefault();
488 return;
489 }
490 webPreferences.sandbox = true;
491 webPreferences.nodeIntegration = false;
492 webPreferences.nodeIntegrationInSubFrames = false;
493 webPreferences.contextIsolation = false;
494 });
495
496 window.webContents.on("context-menu", (event, params) => {
497 event.preventDefault();
498
499 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
500
501 if (params.misspelledWord) {
502 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
503 menuTemplate.push({
504 label: suggestion,
505 click: () => window.webContents.replaceMisspelling(suggestion),
506 });
507 }
508 if (params.dictionarySuggestions.length === 0) {
509 menuTemplate.push({ label: "No suggestions", enabled: false });
510 }
511 menuTemplate.push({ type: "separator" });
512 }
513
514 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
515 menuTemplate.push(
516 {
517 label: "Copy Link",
518 click: () => {
519 void runPromise(electronShell.copyText(params.linkURL));
520 },
521 },
522 { type: "separator" },
523 );
524 }
525
526 if (params.mediaType === "image") {
527 menuTemplate.push({
528 label: "Copy Image",
529 click: () => window.webContents.copyImageAt(params.x, params.y),
530 });
531 menuTemplate.push({ type: "separator" });
532 }
533
534 menuTemplate.push(
535 { role: "cut", enabled: params.editFlags.canCut },
536 { role: "copy", enabled: params.editFlags.canCopy },
537 { role: "paste", enabled: params.editFlags.canPaste },
538 { role: "selectAll", enabled: params.editFlags.canSelectAll },
539 );
540
541 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
542 });
543
544 window.webContents.setWindowOpenHandler(({ url }) => {
545 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
546 void runPromise(electronShell.openExternal(url));
547 }
548 return { action: "deny" };
549 });
550 window.webContents.on("will-navigate", (event, url) => {
551 if (
552 isSameOriginRendererNavigation({
553 applicationUrl,
554 navigationUrl: url,
555 })
556 ) {
557 return;
558 }
559
560 event.preventDefault();
561 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
562 void runPromise(electronShell.openExternal(url));
563 }
564 });
565
566 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
567 // close-terminal shortcut can outlive the terminal that handled its first
568 // press, so reject repeats before they reach the native window accelerator.
569 // Deliberate presses still flow through the renderer or native menu.
570 // Intercept the quit accelerator before the native menu sees it and apply
571 // the configured direct, hold, or double-press behavior.
572 const quitShortcutHandler = makeQuitShortcutHandler({
573 platform: environment.platform,
574 getMode: () =>
575 runPromise(
576 Effect.map(
577 clientSettings.get,
578 Option.match({
579 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
580 onSome: (settings) => settings.confirmQuit,
581 }),
582 ),
583 ),
584 notify: (hint) => {
585 if (!window.isDestroyed()) {
586 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
587 }
588 },
589 // Keep the transparent window focused until the physical shortcut is
590 // released so its remaining repeats cannot reach the next app.
591 concealWindow: () => concealPendingQuitWindow(window),
592 quit: () => {
593 void runPromise(electronApp.quit);
594 },
595 });
596 window.webContents.on("before-input-event", (event, input) => {
597 quitShortcutHandler(event, input);
598 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
599 const modifier = environment.platform === "darwin" ? input.meta : input.control;
600 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
601 event.preventDefault();
602 }
603 });
604
605 window.on("page-title-updated", (event) => {
606 event.preventDefault();
607 window.setTitle(environment.displayName);
608 });
609 window.on("resize", scheduleBoundsPersist);
610 window.on("move", scheduleBoundsPersist);
611 window.on("maximize", scheduleBoundsPersist);
612 window.on("unmaximize", scheduleBoundsPersist);
613 window.on("close", () => {
614 runFork(flushBoundsPersist);
615 });
616
617 if (environment.platform === "darwin") {
618 window.on("enter-full-screen", () => {
619 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
620 });
621 window.on("leave-full-screen", () => {
622 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
623 });
624 }
625
626 let developmentLoadRetryIndex = 0;
627 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
628 let rendererRecoveryTimestamps: number[] = [];
629 const clearDevelopmentLoadRetry = () => {
630 if (developmentLoadRetryFiber === undefined) {
631 return;
632 }
633 const retryFiber = developmentLoadRetryFiber;
634 developmentLoadRetryFiber = undefined;
635 runFork(Fiber.interrupt(retryFiber));
636 };
637 const loadApplication = () => {
638 if (window.isDestroyed()) {
639 return;
640 }
641 void window.loadURL(applicationUrl).catch(() => undefined);
642 };
643 const scheduleDevelopmentLoadRetry = () => {
644 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
645 return undefined;
646 }
647
648 const retryIndex = Math.min(
649 developmentLoadRetryIndex,
650 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
651 );
652 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
653 developmentLoadRetryIndex += 1;
654 developmentLoadRetryFiber = runFork(
655 Effect.sleep(retryInMs).pipe(
656 Effect.andThen(
657 Effect.sync(() => {
658 developmentLoadRetryFiber = undefined;
659 if (!window.isDestroyed()) {
660 loadApplication();
661 }
662 }),
663 ),
664 ),
665 );
666 return retryInMs;
667 };
668
669 window.webContents.on("did-finish-load", () => {
670 if (
671 environment.isDevelopment &&
672 !isSameOriginRendererNavigation({
673 applicationUrl,
674 navigationUrl: window.webContents.getURL(),
675 })
676 ) {
677 return;
678 }
679 clearDevelopmentLoadRetry();
680 developmentLoadRetryIndex = 0;
681 window.setTitle(environment.displayName);
682 });
683 window.webContents.on(
684 "did-fail-load",
685 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
686 if (!isMainFrame) {
687 return;
688 }
689 const retryInMs =
690 environment.isDevelopment &&
691 isRetryableDevelopmentRendererLoadFailure({
692 applicationUrl,
693 errorCode,
694 isMainFrame,
695 validatedUrl: validatedURL,
696 })
697 ? scheduleDevelopmentLoadRetry()
698 : undefined;
699 void runPromise(
700 logWindowWarning("main window failed to load", {
701 errorCode,
702 errorDescription,
703 url: validatedURL,
704 ...(retryInMs === undefined ? {} : { retryInMs }),
705 }),
706 );
707 },
708 );
709 window.webContents.on("render-process-gone", (_event, details) => {
710 const recoverable =
711 details.reason === "crashed" ||
712 details.reason === "oom" ||
713 details.reason === "abnormal-exit";
714 // Long sessions can OOM the renderer (V8 heap exhaustion from
715 // accumulated thread state). Without a reload the user is left staring
716 // at a dead white window while agents keep running invisibly, so
717 // recover by reloading — the renderer rehydrates from the backend,
718 // which is unaffected. Recovery attempts are bounded so a renderer
719 // that dies immediately on boot cannot reload-loop forever.
720 runFork(
721 Effect.gen(function* () {
722 const now = yield* Clock.currentTimeMillis;
723 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
724 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
725 );
726 const shouldRecover =
727 recoverable &&
728 !window.isDestroyed() &&
729 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
730 yield* logWindowWarning("main window render process gone", {
731 reason: details.reason,
732 exitCode: details.exitCode,
733 recovering: shouldRecover,
734 });
735 if (!shouldRecover) {
736 return;
737 }
738 rendererRecoveryTimestamps.push(now);
739 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
740 if (!window.isDestroyed()) {
741 loadApplication();
742 }
743 }),
744 );
745 });
746
747 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
748 if (environment.platform === "linux") {
749 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
750 }
751 bindFirstRevealTrigger(revealSubscribers, () => {
752 // Boot is done; hand the window back to normal hidden-window throttling
753 // (see the backgroundThrottling comment on the create options above).
754 if (!window.isDestroyed()) {
755 window.webContents.setBackgroundThrottling(true);
756 }
757 // Reveal the real window, then close the connecting splash (if any) so the
758 // two don't overlap and there's no blank gap between them.
759 if (persistedSettings.mainWindowMaximized) {
760 window.maximize();
761 }
762 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
763 });
764
765 loadApplication();
766 if (environment.isDevelopment) {
767 window.webContents.openDevTools({ mode: "detach" });
768 }
769
770 window.on("closed", () => {
771 clearDevelopmentLoadRetry();
772 clearBoundsPersist();
773 void runPromise(electronWindow.clearMain(Option.some(window)));
774 });
775
776 return window;
777 });
778
779 const createMain = Effect.gen(function* () {
780 const window = yield* createWindow();
781 yield* electronWindow.setMain(window);
782 yield* logWindowInfo("main window created");
783 return window;
784 }).pipe(Effect.withSpan("desktop.window.createMain"));
785
786 const ensureMain = Effect.gen(function* () {
787 const existingWindow = yield* currentMainWindow;
788 if (Option.isSome(existingWindow)) {
789 return existingWindow.value;
790 }
791 return yield* createMain;
792 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
793
794 const revealOrCreateMain = Effect.gen(function* () {
795 const window = yield* ensureMain;
796 yield* electronWindow.reveal(window);
797 return window;
798 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
799
800 const createMainIfBackendReady = Effect.gen(function* () {
801 const backendReady = yield* Ref.get(backendReadyRef);
802 if (!backendReady) return;
803 const existingWindow = yield* currentMainWindow;
804 if (Option.isSome(existingWindow)) return;
805 yield* createMain;
806 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
807
808 const showConnectingSplash = Effect.gen(function* () {
809 // Only when nothing is shown yet: no real window, no existing splash.
810 const existingSplash = yield* Ref.get(splashWindowRef);
811 if (Option.isSome(existingSplash)) return;
812 const existingWindow = yield* electronWindow.currentMainOrFirst;
813 if (Option.isSome(existingWindow)) return;
814
815 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
816 const splash = yield* electronWindow.create({
817 width: 360,
818 height: 220,
819 resizable: false,
820 minimizable: false,
821 maximizable: false,
822 fullscreenable: false,
823 frame: false,
824 center: true,
825 show: false,
826 skipTaskbar: false,
827 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
828 title: environment.displayName,
829 webPreferences: {
830 contextIsolation: true,
831 nodeIntegration: false,
832 sandbox: true,
833 },
834 });
835 yield* Ref.set(splashWindowRef, Option.some(splash));
836 splash.once("closed", () => {
837 void runPromise(Ref.set(splashWindowRef, Option.none()));
838 });
839 splash.once("ready-to-show", () => {
840 if (!splash.isDestroyed()) {
841 splash.show();
842 }
843 });
844 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
845 yield* logWindowInfo("connecting splash shown");
846 }).pipe(
847 // The splash is best-effort UX — never let it fail startup.
848 Effect.catch((error) =>
849 logWindowWarning("failed to show connecting splash", { message: error.message }),
850 ),
851 Effect.withSpan("desktop.window.showConnectingSplash"),
852 );
853
854 return DesktopWindow.of({
855 createMain,
856 ensureMain,
857 revealOrCreateMain,
858 activate: Effect.gen(function* () {
859 const existingWindow = yield* currentMainWindow;
860 if (Option.isSome(existingWindow)) {
861 yield* electronWindow.reveal(existingWindow.value);
862 return;
863 }
864 // No real main window yet. While the backend is still cold-booting,
865 // re-reveal the connecting splash so taskbar/dock activation brings it
866 // back instead of doing nothing. Once the backend is ready we fall
867 // through to (re)create the real main -- including retrying a previously
868 // failed open the pool swallowed -- rather than latching onto the splash.
869 const backendReady = yield* Ref.get(backendReadyRef);
870 if (!backendReady) {
871 const splash = yield* Ref.get(splashWindowRef);
872 if (Option.isSome(splash)) {
873 yield* electronWindow.reveal(splash.value);
874 return;
875 }
876 }
877 yield* createMainIfBackendReady;
878 }).pipe(Effect.withSpan("desktop.window.activate")),
879 createMainIfBackendReady,
880 showConnectingSplash,
881 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
882 yield* Ref.set(backendReadyRef, true);
883 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
884 yield* createMainIfBackendReady;
885 }),
886 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
887 Effect.withSpan("desktop.window.handleBackendNotReady"),
888 ),
889 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
890 Effect.withSpan("desktop.window.flushMainWindowBounds"),
891 ),
892 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
893 yield* Effect.annotateCurrentSpan({ action });
894 const existingWindow = yield* focusedMainWindow;
895 if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
896 return;
897 }
898 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
899
900 const send = () => {
901 if (targetWindow.isDestroyed()) return;
902 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
903 void runPromise(electronWindow.reveal(targetWindow));
904 };
905
906 if (targetWindow.webContents.isLoadingMainFrame()) {
907 targetWindow.webContents.once("did-finish-load", send);
908 return;
909 }
910
911 send();
912 }),
913 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
914 yield* Effect.annotateCurrentSpan({ direction });
915 const window = yield* focusedMainWindow;
916 if (Option.isNone(window) || window.value.isDestroyed()) {
917 return;
918 }
919 const webContents = window.value.webContents;
920 // Same step size as the Electron zoomIn/zoomOut menu roles.
921 webContents.setZoomLevel(
922 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
923 );
924 // Chromium pushes the new level down to embedded guests, which would zoom
925 // the previewed page along with the app UI. The preview browser keeps its
926 // own zoom, so put each guest back where the preview left it.
927 yield* previewManager.reapplyZoom();
928 }),
929 syncAppearance: Effect.gen(function* () {
930 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
931 yield* electronWindow.syncAllAppearance((window) =>
932 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
933 );
934 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
935 });
936});
937
938export const layer = Layer.effect(DesktopWindow, make);