Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopWindow.ts

1,037 lines40.2 KB

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