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