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 const contextMenuContents = new WeakSet<Electron.WebContents>();
509 const installContextMenu = (
510 ownerWindow: Electron.BrowserWindow,
511 contents: Electron.WebContents,
512 ): void => {
513 if (contextMenuContents.has(contents)) return;
514 contextMenuContents.add(contents);
515 contents.on("context-menu", (event, params) => {
516 event.preventDefault();
517 if (contents.isDestroyed() || ownerWindow.isDestroyed()) return;
518 // Native editing roles act on the focused contents, which may still be
519 // the host renderer when the user right-clicks inside a browser guest.
520 contents.focus();
521
522 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
523
524 if (params.misspelledWord) {
525 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
526 menuTemplate.push({
527 label: suggestion,
528 click: () => {
529 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
530 },
531 });
532 }
533 if (params.dictionarySuggestions.length === 0) {
534 menuTemplate.push({ label: "No suggestions", enabled: false });
535 }
536 menuTemplate.push({ type: "separator" });
537 }
538
539 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
540 menuTemplate.push(
541 {
542 label: "Copy Link",
543 click: () => {
544 void runPromise(electronShell.copyText(params.linkURL));
545 },
546 },
547 { type: "separator" },
548 );
549 }
550
551 if (params.mediaType === "image") {
552 menuTemplate.push({
553 label: "Copy Image",
554 click: () => {
555 if (!contents.isDestroyed()) contents.copyImageAt(params.x, params.y);
556 },
557 });
558 menuTemplate.push({ type: "separator" });
559 }
560
561 menuTemplate.push(
562 { role: "cut", enabled: params.editFlags.canCut },
563 { role: "copy", enabled: params.editFlags.canCopy },
564 { role: "paste", enabled: params.editFlags.canPaste },
565 { role: "selectAll", enabled: params.editFlags.canSelectAll },
566 );
567
568 void runPromise(
569 electronMenu.popupTemplate({
570 window: ownerWindow,
571 template: menuTemplate,
572 ...(params.frame ? { frame: params.frame } : {}),
573 }),
574 );
575 });
576 contents.on("did-create-window", (popup) => {
577 installContextMenu(popup, popup.webContents);
578 });
579 };
580 installContextMenu(window, window.webContents);
581 window.webContents.on("did-attach-webview", (_event, contents) => {
582 installContextMenu(window, contents);
583 });
584
585 window.webContents.setWindowOpenHandler(({ url }) => {
586 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
587 void runPromise(electronShell.openExternal(url));
588 }
589 return { action: "deny" };
590 });
591 window.webContents.on("will-navigate", (event, url) => {
592 if (
593 isSameOriginRendererNavigation({
594 applicationUrl,
595 navigationUrl: url,
596 })
597 ) {
598 return;
599 }
600
601 event.preventDefault();
602 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
603 void runPromise(electronShell.openExternal(url));
604 }
605 });
606
607 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
608 // close-terminal shortcut can outlive the terminal that handled its first
609 // press, so reject repeats before they reach the native window accelerator.
610 // Deliberate presses still flow through the renderer or native menu.
611 // Intercept the quit accelerator before the native menu sees it and apply
612 // the configured direct, hold, or double-press behavior.
613 const quitShortcutHandler = makeQuitShortcutHandler({
614 platform: environment.platform,
615 getMode: () =>
616 runPromise(
617 Effect.map(
618 clientSettings.get,
619 Option.match({
620 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
621 onSome: (settings) => settings.confirmQuit,
622 }),
623 ),
624 ),
625 notify: (hint) => {
626 if (!window.isDestroyed()) {
627 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
628 }
629 },
630 // Keep the transparent window focused until the physical shortcut is
631 // released so its remaining repeats cannot reach the next app.
632 concealWindow: () => concealPendingQuitWindow(window),
633 quit: () => {
634 void runPromise(electronApp.quit);
635 },
636 });
637 window.webContents.on("before-input-event", (event, input) => {
638 quitShortcutHandler(event, input);
639 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
640 const modifier = environment.platform === "darwin" ? input.meta : input.control;
641 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
642 event.preventDefault();
643 }
644 });
645
646 window.on("page-title-updated", (event) => {
647 event.preventDefault();
648 window.setTitle(environment.displayName);
649 });
650 window.on("resize", scheduleBoundsPersist);
651 window.on("move", scheduleBoundsPersist);
652 window.on("maximize", scheduleBoundsPersist);
653 window.on("unmaximize", scheduleBoundsPersist);
654 window.on("close", () => {
655 runFork(flushBoundsPersist);
656 });
657
658 if (environment.platform === "darwin") {
659 window.on("enter-full-screen", () => {
660 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
661 });
662 window.on("leave-full-screen", () => {
663 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
664 });
665 }
666
667 let developmentLoadRetryIndex = 0;
668 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
669 let rendererRecoveryTimestamps: number[] = [];
670 const clearDevelopmentLoadRetry = () => {
671 if (developmentLoadRetryFiber === undefined) {
672 return;
673 }
674 const retryFiber = developmentLoadRetryFiber;
675 developmentLoadRetryFiber = undefined;
676 runFork(Fiber.interrupt(retryFiber));
677 };
678 const loadApplication = () => {
679 if (window.isDestroyed()) {
680 return;
681 }
682 void window.loadURL(applicationUrl).catch(() => undefined);
683 };
684 const scheduleDevelopmentLoadRetry = () => {
685 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
686 return undefined;
687 }
688
689 const retryIndex = Math.min(
690 developmentLoadRetryIndex,
691 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
692 );
693 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
694 developmentLoadRetryIndex += 1;
695 developmentLoadRetryFiber = runFork(
696 Effect.sleep(retryInMs).pipe(
697 Effect.andThen(
698 Effect.sync(() => {
699 developmentLoadRetryFiber = undefined;
700 if (!window.isDestroyed()) {
701 loadApplication();
702 }
703 }),
704 ),
705 ),
706 );
707 return retryInMs;
708 };
709
710 window.webContents.on("did-finish-load", () => {
711 if (
712 environment.isDevelopment &&
713 !isSameOriginRendererNavigation({
714 applicationUrl,
715 navigationUrl: window.webContents.getURL(),
716 })
717 ) {
718 return;
719 }
720 clearDevelopmentLoadRetry();
721 developmentLoadRetryIndex = 0;
722 window.setTitle(environment.displayName);
723 });
724 window.webContents.on(
725 "did-fail-load",
726 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
727 if (!isMainFrame) {
728 return;
729 }
730 const retryInMs =
731 environment.isDevelopment &&
732 isRetryableDevelopmentRendererLoadFailure({
733 applicationUrl,
734 errorCode,
735 isMainFrame,
736 validatedUrl: validatedURL,
737 })
738 ? scheduleDevelopmentLoadRetry()
739 : undefined;
740 void runPromise(
741 logWindowWarning("main window failed to load", {
742 errorCode,
743 errorDescription,
744 url: validatedURL,
745 ...(retryInMs === undefined ? {} : { retryInMs }),
746 }),
747 );
748 },
749 );
750 window.webContents.on("render-process-gone", (_event, details) => {
751 const recoverable =
752 details.reason === "crashed" ||
753 details.reason === "oom" ||
754 details.reason === "abnormal-exit";
755 // Long sessions can OOM the renderer (V8 heap exhaustion from
756 // accumulated thread state). Without a reload the user is left staring
757 // at a dead white window while agents keep running invisibly, so
758 // recover by reloading — the renderer rehydrates from the backend,
759 // which is unaffected. Recovery attempts are bounded so a renderer
760 // that dies immediately on boot cannot reload-loop forever.
761 runFork(
762 Effect.gen(function* () {
763 const now = yield* Clock.currentTimeMillis;
764 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
765 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
766 );
767 const shouldRecover =
768 recoverable &&
769 !window.isDestroyed() &&
770 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
771 yield* logWindowWarning("main window render process gone", {
772 reason: details.reason,
773 exitCode: details.exitCode,
774 recovering: shouldRecover,
775 });
776 if (!shouldRecover) {
777 return;
778 }
779 rendererRecoveryTimestamps.push(now);
780 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
781 if (!window.isDestroyed()) {
782 loadApplication();
783 }
784 }),
785 );
786 });
787
788 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
789 if (environment.platform === "linux") {
790 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
791 }
792 bindFirstRevealTrigger(revealSubscribers, () => {
793 // Boot is done; hand the window back to normal hidden-window throttling
794 // (see the backgroundThrottling comment on the create options above).
795 if (!window.isDestroyed()) {
796 window.webContents.setBackgroundThrottling(true);
797 }
798 // Reveal the real window, then close the connecting splash (if any) so the
799 // two don't overlap and there's no blank gap between them.
800 if (persistedSettings.mainWindowMaximized) {
801 window.maximize();
802 }
803 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
804 });
805
806 loadApplication();
807 if (environment.isDevelopment) {
808 window.webContents.openDevTools({ mode: "detach" });
809 }
810
811 window.on("closed", () => {
812 clearDevelopmentLoadRetry();
813 clearBoundsPersist();
814 void runPromise(electronWindow.clearMain(Option.some(window)));
815 });
816
817 return window;
818 });
819
820 const createMain = Effect.gen(function* () {
821 const window = yield* createWindow();
822 yield* electronWindow.setMain(window);
823 yield* logWindowInfo("main window created");
824 return window;
825 }).pipe(Effect.withSpan("desktop.window.createMain"));
826
827 const ensureMain = Effect.gen(function* () {
828 const existingWindow = yield* currentMainWindow;
829 if (Option.isSome(existingWindow)) {
830 return existingWindow.value;
831 }
832 return yield* createMain;
833 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
834
835 const revealOrCreateMain = Effect.gen(function* () {
836 const window = yield* ensureMain;
837 yield* electronWindow.reveal(window);
838 return window;
839 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
840
841 const createMainIfBackendReady = Effect.gen(function* () {
842 const backendReady = yield* Ref.get(backendReadyRef);
843 if (!backendReady) return;
844 const existingWindow = yield* currentMainWindow;
845 if (Option.isSome(existingWindow)) return;
846 yield* createMain;
847 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
848
849 const showConnectingSplash = Effect.gen(function* () {
850 // Only when nothing is shown yet: no real window, no existing splash.
851 const existingSplash = yield* Ref.get(splashWindowRef);
852 if (Option.isSome(existingSplash)) return;
853 const existingWindow = yield* electronWindow.currentMainOrFirst;
854 if (Option.isSome(existingWindow)) return;
855
856 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
857 const splash = yield* electronWindow.create({
858 width: 360,
859 height: 220,
860 resizable: false,
861 minimizable: false,
862 maximizable: false,
863 fullscreenable: false,
864 frame: false,
865 center: true,
866 show: false,
867 skipTaskbar: false,
868 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
869 title: environment.displayName,
870 webPreferences: {
871 contextIsolation: true,
872 nodeIntegration: false,
873 sandbox: true,
874 },
875 });
876 yield* Ref.set(splashWindowRef, Option.some(splash));
877 splash.once("closed", () => {
878 void runPromise(Ref.set(splashWindowRef, Option.none()));
879 });
880 splash.once("ready-to-show", () => {
881 if (!splash.isDestroyed()) {
882 splash.show();
883 }
884 });
885 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
886 yield* logWindowInfo("connecting splash shown");
887 }).pipe(
888 // The splash is best-effort UX — never let it fail startup.
889 Effect.catch((error) =>
890 logWindowWarning("failed to show connecting splash", { message: error.message }),
891 ),
892 Effect.withSpan("desktop.window.showConnectingSplash"),
893 );
894
895 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
896 channel: string,
897 payload: unknown,
898 { reveal = true }: { readonly reveal?: boolean } = {},
899 ) {
900 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
901 if (Option.isNone(existingWindow) && (!reveal || !(yield* Ref.get(backendReadyRef)))) return;
902 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
903 if (targetWindow.isDestroyed()) return;
904 const send = Effect.sync(() => {
905 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
906 });
907 // The renderer must learn about the event even when another process refuses to
908 // yield the foreground, so send first and treat the reveal as best effort.
909 const dispatch = reveal
910 ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause)))
911 : send;
912 if (targetWindow.webContents.isLoadingMainFrame()) {
913 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
914 return;
915 }
916 yield* dispatch;
917 });
918
919 return DesktopWindow.of({
920 createMain,
921 ensureMain,
922 revealOrCreateMain,
923 prepareCaptureReveal: Effect.gen(function* () {
924 const existingWindow = yield* currentMainWindow;
925 if (Option.isSome(existingWindow)) {
926 yield* electronWindow.prepareReveal(existingWindow.value);
927 }
928 }),
929 activate: Effect.gen(function* () {
930 const existingWindow = yield* currentMainWindow;
931 if (Option.isSome(existingWindow)) {
932 yield* electronWindow.reveal(existingWindow.value);
933 return;
934 }
935 // No real main window yet. While the backend is still cold-booting,
936 // re-reveal the connecting splash so taskbar/dock activation brings it
937 // back instead of doing nothing. Once the backend is ready we fall
938 // through to (re)create the real main -- including retrying a previously
939 // failed open the pool swallowed -- rather than latching onto the splash.
940 const backendReady = yield* Ref.get(backendReadyRef);
941 if (!backendReady) {
942 const splash = yield* Ref.get(splashWindowRef);
943 if (Option.isSome(splash)) {
944 yield* electronWindow.reveal(splash.value);
945 return;
946 }
947 }
948 yield* createMainIfBackendReady;
949 }).pipe(Effect.withSpan("desktop.window.activate")),
950 createMainIfBackendReady,
951 showConnectingSplash,
952 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
953 yield* Ref.set(backendReadyRef, true);
954 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
955 yield* createMainIfBackendReady;
956 }),
957 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
958 Effect.withSpan("desktop.window.handleBackendNotReady"),
959 ),
960 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
961 Effect.withSpan("desktop.window.flushMainWindowBounds"),
962 ),
963 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
964 yield* Effect.annotateCurrentSpan({ action });
965 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
966 }),
967 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
968 yield* Effect.annotateCurrentSpan({
969 event: event.type,
970 captureId: "id" in event ? (event.id ?? null) : null,
971 });
972 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
973 reveal: event.type === "started",
974 });
975 }),
976 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
977 yield* Effect.annotateCurrentSpan({ direction });
978 const window = yield* focusedMainWindow;
979 if (Option.isNone(window) || window.value.isDestroyed()) {
980 return;
981 }
982 const webContents = window.value.webContents;
983 // Same step size as the Electron zoomIn/zoomOut menu roles.
984 webContents.setZoomLevel(
985 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
986 );
987 // Chromium pushes the new level down to embedded guests, which would zoom
988 // the previewed page along with the app UI. The preview browser keeps its
989 // own zoom, so put each guest back where the preview left it.
990 yield* previewManager.reapplyZoom();
991 }),
992 syncAppearance: Effect.gen(function* () {
993 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
994 yield* electronWindow.syncAllAppearance((window) =>
995 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
996 );
997 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
998 });
999});
1000
1001export const layer = Layer.effect(DesktopWindow, make);