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