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