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