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