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