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

DesktopWindow.ts

1,228 lines46.0 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";
8import * as Schema from "effect/Schema";
9import * as Semaphore from "effect/Semaphore";
10​
11import * as Electron from "electron";
12import { msg } from "gt-i18n";
13​
14import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
15​
16import * as DesktopAssets from "../app/DesktopAssets.ts";
17import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
18import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts";
19import { makeComponentLogger } from "../app/DesktopObservability.ts";
20import * as DesktopState from "../app/DesktopState.ts";
21import * as ElectronMenu from "../electron/ElectronMenu.ts";
22import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
23import * as ElectronShell from "../electron/ElectronShell.ts";
24import * as ElectronTheme from "../electron/ElectronTheme.ts";
25import * as ElectronWindow from "../electron/ElectronWindow.ts";
26import {
27 MENU_ACTION_CHANNEL,
28 QUIT_SHORTCUT_CHANNEL,
29 SNAP_SHOT_EVENT_CHANNEL,
30 TRACKPAD_SCROLL_BEGIN_CHANNEL,
31 TRACKPAD_SCROLL_END_CHANNEL,
32 WINDOW_FULLSCREEN_STATE_CHANNEL,
33} from "../ipc/channels.ts";
34import {
35 PASSKEY_BRIDGE_ARGUMENT,
36 PRIMARY_PASTE_DISABLED_ARGUMENT,
37} from "../preview/GuestProtocol.ts";
38import * as PreviewManager from "../preview/Manager.ts";
39import * as PreviewPasskeys from "../preview/Passkeys.ts";
40import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
41import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
42import * as ElectronApp from "../electron/ElectronApp.ts";
43import { m } from "../i18n/messages.ts";
44import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
45import { makeQuitShortcutHandler } from "./QuitHold.ts";
46import { copyContextMenuImage } from "./ContextMenuImage.ts";
47​
48const TITLEBAR_HEIGHT = 40;
49​
50class ContextMenuImageCopyError extends Schema.TaggedError<ContextMenuImageCopyError>()(
51 "ContextMenuImageCopyError",
52 { cause: Schema.Defect() },
53) {
54 override get message(): string {
55 return "Could not copy the context-menu image.";
56 }
58// Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom.
59const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
60const MACOS_WINDOW_BUTTON_RADIUS = 7;
61​
62function parseMailtoAddress(rawUrl: string): Option.Option<string> {
63 let url: URL;
64 try {
65 url = new URL(rawUrl);
66 } catch {
67 return Option.none();
68 }
69 if (url.protocol !== "mailto:" || url.pathname === "") return Option.none();
70 try {
71 return Option.some(decodeURIComponent(url.pathname));
72 } catch {
73 return Option.some(url.pathname);
74 }
76​
77function syncMacosWindowButtons(window: Electron.BrowserWindow): void {
78 if (window.isDestroyed() || window.isFullScreen()) return;
79 window.setWindowButtonPosition({
80 x: 16,
81 y: Math.round(
82 (MACOS_WORKSPACE_TOPBAR_HEIGHT * window.webContents.getZoomFactor()) / 2 -
83 MACOS_WINDOW_BUTTON_RADIUS,
84 ),
85 });
87​
88const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
89const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
90const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
91const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
92const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
93const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
94const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
95const RENDERER_RECOVERY_WINDOW_MS = 60_000;
96const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]);
97​
98type WindowTitleBarOptions = Pick<
99 Electron.BrowserWindowConstructorOptions,
100 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
101>;
102​
103type DesktopWindowRuntimeServices =
104 | DesktopEnvironment.DesktopEnvironment
105 | DesktopState.DesktopState
106 | DesktopAssets.DesktopAssets
107 | DesktopAppSettings.DesktopAppSettings
108 | DesktopClientSettings.DesktopClientSettings
109 | ElectronApp.ElectronApp
110 | ElectronMenu.ElectronMenu
111 | ElectronShell.ElectronShell
112 | ElectronTheme.ElectronTheme
113 | ElectronWindow.ElectronWindow
114 | DesktopRendererHistory.DesktopRendererHistory
115 | PreviewManager.PreviewManager;
116​
117export type DesktopWindowError =
118 | ElectronWindow.ElectronWindowCreateError
119 | PreviewManager.PreviewManagerError;
120​
121export type MainWindowZoomDirection = "in" | "out" | "reset";
122export type MainWindowContentsCommand = "reload" | "forceReload" | "toggleDevTools";
123​
124export class DesktopWindow extends Context.Service<
125 DesktopWindow,
126 {
127 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
128 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
129 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
130 readonly activate: Effect.Effect<void, DesktopWindowError>;
131 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
132 readonly showConnectingSplash: Effect.Effect<void>;
133 readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
134 readonly handleBackendNotReady: Effect.Effect<void>;
135 readonly flushMainWindowBounds: Effect.Effect<void>;
136 readonly prepareCaptureReveal: Effect.Effect<void>;
137 readonly dispatchMenuAction: (
138 action: string,
139 options?: { readonly reveal?: boolean },
140 ) => Effect.Effect<void, DesktopWindowError>;
141 readonly dispatchSnapShotEvent: (
142 event: DesktopSnapShotEvent,
143 ) => Effect.Effect<void, DesktopWindowError>;
144 // Electron zoom roles target focused guests; zoomMain must always target the app.
145 readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
146 readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect<void>;
147 readonly syncAppearance: Effect.Effect<void>;
148 }
149>()("@t3tools/desktop/window/DesktopWindow") {}
150​
151const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
152 makeComponentLogger("desktop-window");
153​
154function getIconOption(
155 iconPaths: DesktopAssets.DesktopIconPaths,
156 platform: NodeJS.Platform,
157): { icon: string } | Record<string, never> {
158 if (platform === "darwin") return {};
159 const ext = platform === "win32" ? "ico" : "png";
160 return Option.match(iconPaths[ext], {
161 onNone: () => ({}),
162 onSome: (icon) => ({ icon }),
163 });
165​
166function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
167 return shouldUseDarkColors ? "#000000" : "#ffffff";
169​
170type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
171​
172// A window snapped to a display edge can be reported 1px past that edge.
173const SAVED_BOUNDS_EDGE_TOLERANCE_PX = 1;
174​
175function windowFitsWithinDisplay(
176 windowBounds: DesktopAppSettings.DesktopWindowBounds,
177 displayBounds: DisplayBounds,
178): boolean {
179 const tolerance = SAVED_BOUNDS_EDGE_TOLERANCE_PX;
180 return (
181 windowBounds.x >= displayBounds.x - tolerance &&
182 windowBounds.y >= displayBounds.y - tolerance &&
183 windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width + tolerance &&
184 windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height + tolerance
185 );
187​
188function overlapArea(left: DisplayBounds, right: DisplayBounds): number {
189 const width = Math.min(left.x + left.width, right.x + right.width) - Math.max(left.x, right.x);
190 const height = Math.min(left.y + left.height, right.y + right.height) - Math.max(left.y, right.y);
191 return width > 0 && height > 0 ? width * height : 0;
193​
194function displayMatching(
195 bounds: DisplayBounds,
196 displays: readonly DisplayBounds[],
197): DisplayBounds | undefined {
198 let match: DisplayBounds | undefined;
199 let matchArea = 0;
200 for (const display of displays) {
201 const area = overlapArea(bounds, display);
202 if (area > matchArea) {
203 match = display;
204 matchArea = area;
205 }
206 }
207 return match;
209​
210// Normal bounds of a maximized window can sit on, or straddle into, another display than the window.
211function normalBoundsOnWindowDisplay(
212 normalBounds: DisplayBounds,
213 windowBounds: DisplayBounds,
214 displays: readonly DisplayBounds[],
215): DisplayBounds {
216 const target = displayMatching(windowBounds, displays);
217 if (target === undefined || windowFitsWithinDisplay(normalBounds, target)) {
218 return normalBounds;
219 }
220 const source = displayMatching(normalBounds, displays) ?? target;
221 const width = Math.min(normalBounds.width, target.width);
222 const height = Math.min(normalBounds.height, target.height);
223 const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);
224 return {
225 x: clamp(target.x + normalBounds.x - source.x, target.x, target.x + target.width - width),
226 y: clamp(target.y + normalBounds.y - source.y, target.y, target.y + target.height - height),
227 width,
228 height,
229 };
231​
232function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] {
233 try {
234 return Electron.screen.getAllDisplays().map((display) => display.bounds);
235 } catch {
236 return [];
237 }
239​
240function windowBoundsEqual(
241 left: DesktopAppSettings.DesktopWindowBounds,
242 right: DesktopAppSettings.DesktopWindowBounds,
243): boolean {
244 return (
245 left.x === right.x &&
246 left.y === right.y &&
247 left.width === right.width &&
248 left.height === right.height
249 );
251​
252export function resolveInitialMainWindowBounds(
253 persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
254 displays: readonly DisplayBounds[],
255): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
256 if (
257 persistedBounds !== null &&
258 displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
259 ) {
260 return persistedBounds;
261 }
262 return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
264​
265function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
266 const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
267 const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
268 const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
269 const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
270 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>`;
271 return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
273​
274export function isSameOriginRendererNavigation(input: {
275 readonly applicationUrl: string;
276 readonly navigationUrl: string;
277}): boolean {
278 try {
279 const applicationUrl = new URL(input.applicationUrl);
280 const navigationUrl = new URL(input.navigationUrl);
281 // Node serializes custom-scheme origins as "null", even for different hosts and schemes.
282 return (
283 applicationUrl.host !== "" &&
284 navigationUrl.protocol === applicationUrl.protocol &&
285 navigationUrl.host === applicationUrl.host
286 );
287 } catch {
288 return false;
289 }
291​
292function isRetryableDevelopmentRendererLoadFailure(input: {
293 readonly applicationUrl: string;
294 readonly errorCode: number;
295 readonly isMainFrame: boolean;
296 readonly validatedUrl: string;
297}): boolean {
298 return (
299 input.isMainFrame &&
300 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
301 isSameOriginRendererNavigation({
302 applicationUrl: input.applicationUrl,
303 navigationUrl: input.validatedUrl,
304 })
305 );
307​
308function concealPendingQuitWindow(
309 window: Pick<
310 Electron.BrowserWindow,
311 "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
312 >,
313): void {
314 if (window.isDestroyed()) return;
315 if (window.isFullScreen()) {
316 window.setFullScreen(false);
317 }
318 // Linux lacks Electron window opacity; release-gated quits remain visible there.
319 window.setOpacity(0);
321​
322function getWindowTitleBarOptions(
323 shouldUseDarkColors: boolean,
324 platform: NodeJS.Platform,
325): WindowTitleBarOptions {
326 if (platform === "darwin") {
327 return {
328 titleBarStyle: "hiddenInset",
329 trafficLightPosition: {
330 x: 16,
331 y: MACOS_WORKSPACE_TOPBAR_HEIGHT / 2 - MACOS_WINDOW_BUTTON_RADIUS,
332 },
333 };
334 }
335​
336 return {
337 titleBarStyle: "hidden",
338 titleBarOverlay: {
339 color: TITLEBAR_COLOR,
340 height: TITLEBAR_HEIGHT,
341 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
342 },
343 };
345​
346function syncWindowAppearance(
347 window: Electron.BrowserWindow,
348 hasTitleBarOverlay: boolean,
349 shouldUseDarkColors: boolean,
350 platform: NodeJS.Platform,
351): Effect.Effect<void> {
352 return Effect.sync(() => {
353 if (window.isDestroyed()) {
354 return;
355 }
356​
357 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
358 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
359 if (hasTitleBarOverlay && typeof titleBarOverlay === "object") {
360 window.setTitleBarOverlay(titleBarOverlay);
361 }
362 });
364​
365type RevealSubscription = (listener: () => void) => void;
366​
367function bindFirstRevealTrigger(
368 subscribers: readonly RevealSubscription[],
369 reveal: () => void,
370): void {
371 let revealed = false;
372 const fire = () => {
373 if (revealed) return;
374 revealed = true;
375 reveal();
376 };
377 for (const subscribe of subscribers) {
378 subscribe(fire);
379 }
381​
382/** @public */
383export const make = Effect.gen(function* () {
384 const environment = yield* DesktopEnvironment.DesktopEnvironment;
385 const desktopState = yield* DesktopState.DesktopState;
386 const assets = yield* DesktopAssets.DesktopAssets;
387 const electronMenu = yield* ElectronMenu.ElectronMenu;
388 const electronShell = yield* ElectronShell.ElectronShell;
389 const electronTheme = yield* ElectronTheme.ElectronTheme;
390 const electronWindow = yield* ElectronWindow.ElectronWindow;
391 const previewManager = yield* PreviewManager.PreviewManager;
392 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
393 const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste;
394 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
395 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
396 const electronApp = yield* ElectronApp.ElectronApp;
397 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
398 const backendReadyRef = yield* Ref.make(false);
399 let backendHasStarted = false;
400 let mainClosedDuringStartup = false;
401 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
402 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
403 const runFork = Effect.runForkWith(context);
404 const runPromise = Effect.runPromiseWith(context);
405 const mainWindowMutex = yield* Semaphore.make(1);
406 const pendingMainReveals = new WeakMap<Electron.BrowserWindow, Effect.Effect<void>>();
407 const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) =>
408 Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)),
409 );
410 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
411​
412 const dismissConnectingSplash = Effect.gen(function* () {
413 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
414 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
415 splash.value.close();
416 }
417 });
418​
419 // Electron's first-window fallback can select the unregistered connecting splash; exclude it so main creation retries.
420 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
421 Ref.get(splashWindowRef).pipe(
422 Effect.map((splash) =>
423 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
424 ? Option.none<Electron.BrowserWindow>()
425 : window,
426 ),
427 );
428​
429 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
430​
431 const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* (
432 window: Electron.BrowserWindow,
433 direction: MainWindowZoomDirection,
434 ) {
435 const webContents = window.webContents;
436 webContents.setZoomLevel(
437 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
438 );
439 if (environment.platform === "darwin") syncMacosWindowButtons(window);
440 // App zoom propagates to guests; restore each preview's own zoom.
441 yield* previewManager.reapplyZoom();
442 });
443​
444 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
445 Option.Option<Electron.BrowserWindow>,
446 DesktopWindowError
447 > {
448 if (yield* Ref.get(desktopState.quitting)) return Option.none();
449 yield* previewManager.getBrowserSession();
450 const applicationUrl = getDesktopUrl(environment.isDevelopment);
451 const iconPaths = yield* assets.iconPaths;
452 const iconOption = getIconOption(iconPaths, environment.platform);
453 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
454 const persistedSettings = yield* desktopSettings.get;
455 const persistedBounds = persistedSettings.mainWindowBounds;
456 const displayBoundsResult = yield* Effect.sync(() => {
457 try {
458 return {
459 _tag: "Success" as const,
460 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
461 };
462 } catch (cause) {
463 return { _tag: "Failure" as const, cause };
464 }
465 });
466 const displayBounds =
467 displayBoundsResult._tag === "Success"
468 ? displayBoundsResult.bounds
469 : yield* logWindowWarning("failed to read connected displays; using defaults", {
470 cause: displayBoundsResult.cause,
471 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
472 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
473 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
474 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
475 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
476 }
477 if (yield* Ref.get(desktopState.quitting)) return Option.none();
478 const window = yield* electronWindow.create({
479 ...initialBounds,
480 minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width,
481 minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height,
482 show: false,
483 autoHideMenuBar: true,
484 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
485 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
486 ...iconOption,
487 title: environment.displayName,
488 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
489 webPreferences: {
490 preload: environment.preloadPath,
491 // Hidden-renderer throttling stalls first paint; re-enable it after the first reveal.
492 backgroundThrottling: false,
493 contextIsolation: true,
494 nodeIntegration: false,
495 sandbox: true,
496 webviewTag: true,
497 // Guest fullscreen propagates to the embedder; both must opt out to keep it inside the webview.
498 // The app's own fullscreen elements reach OS fullscreen through syncHtmlFullscreen.
499 disableHtmlFullscreenWindowResize: true,
500 },
501 });
502 if (yield* Ref.get(desktopState.quitting)) {
503 yield* electronWindow.destroyAll;
504 return Option.none();
505 }
506​
507 pendingMainReveals.set(window, Effect.void);
508 yield* rendererHistory.register(window.webContents, { surface: "main" });
509 if (environment.platform === "darwin") {
510 window.setAutoHideCursor(false);
511 }
512 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
513 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
514 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
515 let lastPersistableState: {
516 readonly bounds: DesktopAppSettings.DesktopWindowBounds;
517 readonly isMaximized: boolean;
518 } | null = null;
519 const readPersistableState = () => {
520 if (window.isDestroyed()) {
521 return null;
522 }
523 // Minimized windows report stale state on some platforms (macOS: not maximized, the
524 // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing.
525 if (window.isMinimized()) {
526 return lastPersistableState;
527 }
528 const isMaximized = window.isMaximized();
529 const bounds =
530 window.isFullScreen() || isMaximized
531 ? normalBoundsOnWindowDisplay(
532 window.getNormalBounds(),
533 window.getBounds(),
534 readDisplayBoundsOrEmpty(),
535 )
536 : window.getBounds();
537 const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({
538 x: Math.round(bounds.x),
539 y: Math.round(bounds.y),
540 width: Math.round(bounds.width),
541 height: Math.round(bounds.height),
542 });
543 lastPersistableState =
544 persistableBounds === null ? null : { bounds: persistableBounds, isMaximized };
545 return lastPersistableState;
546 };
547 const fallbackWindowBounds = boundsPersistenceEnabled
548 ? null
549 : (readPersistableState()?.bounds ?? null);
550 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
551 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
552 if (!boundsPersistenceEnabled) {
553 return pendingBoundsPersistFiber;
554 }
555 const state = readPersistableState();
556 if (state === null) {
557 return pendingBoundsPersistFiber;
558 }
559 pendingBoundsPersistFiber = runFork(
560 desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe(
561 Effect.asVoid,
562 Effect.catch((error) =>
563 logWindowWarning("failed to persist main window bounds", {
564 message: error.message,
565 }),
566 ),
567 ),
568 );
569 return pendingBoundsPersistFiber;
570 };
571 const scheduleBoundsPersist = () => {
572 const state = readPersistableState();
573 if (
574 !boundsPersistenceEnabled &&
575 (state === null ||
576 (fallbackWindowBounds !== null &&
577 windowBoundsEqual(state.bounds, fallbackWindowBounds) &&
578 state.isMaximized === fallbackWindowMaximized))
579 ) {
580 return;
581 }
582 boundsPersistenceEnabled = true;
583 if (boundsPersistFiber !== undefined) {
584 const fiber = boundsPersistFiber;
585 boundsPersistFiber = undefined;
586 runFork(Fiber.interrupt(fiber));
587 }
588 boundsPersistFiber = runFork(
589 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
590 Effect.andThen(
591 Effect.sync(() => {
592 boundsPersistFiber = undefined;
593 void persistCurrentBounds();
594 }),
595 ),
596 ),
597 );
598 };
599 const clearBoundsPersist = () => {
600 if (boundsPersistFiber === undefined) {
601 return;
602 }
603 const fiber = boundsPersistFiber;
604 boundsPersistFiber = undefined;
605 runFork(Fiber.interrupt(fiber));
606 };
607 const flushBoundsPersist = Effect.sync(() => {
608 clearBoundsPersist();
609 return persistCurrentBounds();
610 }).pipe(
611 Effect.flatMap((fiber) =>
612 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
613 ),
614 );
615 flushMainWindowBounds = flushBoundsPersist;
616​
617 yield* previewManager.setMainWindow(window);
618 if (yield* Ref.get(desktopState.quitting)) {
619 yield* electronWindow.destroyAll;
620 return Option.none();
621 }
622 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
623 if (
624 typeof params.partition !== "string" ||
625 !previewManager.isBrowserPartition(params.partition)
626 ) {
627 event.preventDefault();
628 return;
629 }
630 webPreferences.sandbox = true;
631 webPreferences.nodeIntegration = false;
632 webPreferences.nodeIntegrationInSubFrames = false;
633 webPreferences.contextIsolation = false;
634 webPreferences.disableHtmlFullscreenWindowResize = true;
635 if (previewPasskeys.bridgeEnabled) {
636 webPreferences.additionalArguments = [
637 ...(webPreferences.additionalArguments ?? []),
638 PASSKEY_BRIDGE_ARGUMENT,
639 ];
640 }
641 if (!primaryPaste.enabled) {
642 webPreferences.additionalArguments = [
643 ...(webPreferences.additionalArguments ?? []),
644 PRIMARY_PASTE_DISABLED_ARGUMENT,
645 ];
646 }
647 });
648​
649 const contextMenuContents = new WeakSet<Electron.WebContents>();
650 const installContextMenu = (
651 ownerWindow: Electron.BrowserWindow,
652 contents: Electron.WebContents,
653 ): void => {
654 if (contextMenuContents.has(contents)) return;
655 contextMenuContents.add(contents);
656 contents.on("context-menu", (event, params) => {
657 event.preventDefault();
658 if (contents.isDestroyed() || ownerWindow.isDestroyed()) return;
659 // Right-clicking a guest may leave native editing roles targeting the host renderer.
660 contents.focus();
661​
662 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
663​
664 if (params.misspelledWord) {
665 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
666 menuTemplate.push({
667 label: suggestion,
668 click: () => {
669 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
670 },
671 });
672 }
673 if (params.dictionarySuggestions.length === 0) {
674 menuTemplate.push({ label: m(msg("No suggestions")), enabled: false });
675 }
676 menuTemplate.push({ type: "separator" });
677 }
678​
679 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
680 menuTemplate.push(
681 {
682 label: m(msg("Copy Link")),
683 click: () => {
684 void runPromise(electronShell.copyText(params.linkURL));
685 },
686 },
687 { type: "separator" },
688 );
689 }
690​
691 const mailtoAddress = parseMailtoAddress(params.linkURL);
692 if (Option.isSome(mailtoAddress)) {
693 menuTemplate.push(
694 {
695 label: m(msg("Copy Email Address")),
696 click: () => {
697 void runPromise(electronShell.copyText(mailtoAddress.value));
698 },
699 },
700 { type: "separator" },
701 );
702 }
703​
704 if (params.mediaType === "image") {
705 menuTemplate.push({
706 label: m(msg("Copy Image")),
707 click: () => {
708 void runPromise(
709 Effect.tryPromise({
710 try: () => copyContextMenuImage(contents, params),
711 catch: (cause) => new ContextMenuImageCopyError({ cause }),
712 }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))),
713 );
714 },
715 });
716 menuTemplate.push({ type: "separator" });
717 }
718​
719 menuTemplate.push(
720 { role: "cut", enabled: params.editFlags.canCut },
721 { role: "copy", enabled: params.editFlags.canCopy },
722 { role: "paste", enabled: params.editFlags.canPaste },
723 { role: "selectAll", enabled: params.editFlags.canSelectAll },
724 );
725​
726 void runPromise(
727 electronMenu.popupTemplate({
728 window: ownerWindow,
729 template: menuTemplate,
730 ...(params.frame ? { frame: params.frame } : {}),
731 }),
732 );
733 });
734 contents.on("did-create-window", (popup) => {
735 installContextMenu(popup, popup.webContents);
736 });
737 };
738 installContextMenu(window, window.webContents);
739 window.webContents.on("did-attach-webview", (_event, contents) => {
740 installContextMenu(window, contents);
741 void runPromise(previewManager.prepareWebview(contents));
742 });
743​
744 window.webContents.setWindowOpenHandler(({ url }) => {
745 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
746 void runPromise(electronShell.openExternal(url));
747 }
748 return { action: "deny" };
749 });
750 window.webContents.on("will-navigate", (event, url) => {
751 if (
752 isSameOriginRendererNavigation({
753 applicationUrl,
754 navigationUrl: url,
755 })
756 ) {
757 return;
758 }
759​
760 event.preventDefault();
761 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
762 void runPromise(electronShell.openExternal(url));
763 }
764 });
765​
766 const quitShortcutHandler = makeQuitShortcutHandler({
767 platform: environment.platform,
768 getMode: () =>
769 runPromise(
770 Effect.map(
771 clientSettings.get,
772 Option.match({
773 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
774 onSome: (settings) => settings.confirmQuit,
775 }),
776 ),
777 ),
778 notify: (hint) => {
779 if (!window.isDestroyed()) {
780 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
781 }
782 },
783 // Hold focus until shortcut release so remaining repeats cannot reach the next app.
784 concealWindow: () => concealPendingQuitWindow(window),
785 quit: () => {
786 void runPromise(electronApp.quit);
787 },
788 });
789 window.webContents.on("before-input-event", (event, input) => {
790 quitShortcutHandler(event, input);
791 if (window.isDestroyed()) return;
792 // Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut.
793 window.webContents.setIgnoreMenuShortcuts(
794 (environment.platform === "darwin" ? input.meta : input.control) &&
795 !input.alt &&
796 !input.shift &&
797 input.key.toLowerCase() === "w",
798 );
799 // A held Cmd/Ctrl+W closes one tab or terminal, not each one behind it.
800 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
801 const modifier = environment.platform === "darwin" ? input.meta : input.control;
802 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
803 event.preventDefault();
804 }
805 });
806 window.webContents.on("input-event", (_event, input) => {
807 if (window.isDestroyed()) return;
808 if (input.type === "gestureScrollBegin") {
809 window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL);
810 } else if (input.type === "gestureScrollEnd") {
811 window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
812 }
813 });
814 // Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event.
815 window.webContents.on("zoom-changed", (_event, direction) => {
816 if (window.isDestroyed()) return;
817 runFork(zoomWindow(window, direction));
818 });
819​
820 // The renderer titles the window after the open thread; only a blank title
821 // falls back to the app name.
822 window.on("page-title-updated", (event, title) => {
823 if (title.trim() !== "") return;
824 event.preventDefault();
825 window.setTitle(environment.displayName);
826 });
827 window.on("resize", scheduleBoundsPersist);
828 window.on("move", scheduleBoundsPersist);
829 window.on("maximize", scheduleBoundsPersist);
830 window.on("unmaximize", scheduleBoundsPersist);
831 window.on("close", () => {
832 runFork(flushBoundsPersist);
833 });
834​
835 if (environment.platform === "darwin") {
836 // Mouse drivers can deliver Back/Forward as macOS swipe gestures instead of buttons.
837 window.on("swipe", (_event, direction) => {
838 const history = window.webContents.navigationHistory;
839 if (direction === "left" && history.canGoBack()) history.goBack();
840 else if (direction === "right" && history.canGoForward()) history.goForward();
841 });
842 window.on("enter-full-screen", () => {
843 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
844 });
845 window.on("leave-full-screen", () => {
846 syncMacosWindowButtons(window);
847 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
848 });
849 }
850​
851 let developmentLoadRetryIndex = 0;
852 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
853 let rendererRecoveryTimestamps: number[] = [];
854 const clearDevelopmentLoadRetry = () => {
855 if (developmentLoadRetryFiber === undefined) {
856 return;
857 }
858 const retryFiber = developmentLoadRetryFiber;
859 developmentLoadRetryFiber = undefined;
860 runFork(Fiber.interrupt(retryFiber));
861 };
862 const loadApplication = () => {
863 if (window.isDestroyed()) {
864 return;
865 }
866 void window.loadURL(applicationUrl).catch(() => undefined);
867 };
868 const scheduleDevelopmentLoadRetry = () => {
869 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
870 return undefined;
871 }
872​
873 const retryIndex = Math.min(
874 developmentLoadRetryIndex,
875 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
876 );
877 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
878 developmentLoadRetryIndex += 1;
879 developmentLoadRetryFiber = runFork(
880 Effect.sleep(retryInMs).pipe(
881 Effect.andThen(
882 Effect.sync(() => {
883 developmentLoadRetryFiber = undefined;
884 if (!window.isDestroyed()) {
885 loadApplication();
886 }
887 }),
888 ),
889 ),
890 );
891 return retryInMs;
892 };
893​
894 window.webContents.on("did-finish-load", () => {
895 if (
896 environment.isDevelopment &&
897 !isSameOriginRendererNavigation({
898 applicationUrl,
899 navigationUrl: window.webContents.getURL(),
900 })
901 ) {
902 return;
903 }
904 clearDevelopmentLoadRetry();
905 developmentLoadRetryIndex = 0;
906 if (environment.platform === "darwin") syncMacosWindowButtons(window);
907 });
908 window.webContents.on(
909 "did-fail-load",
910 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
911 if (!isMainFrame) {
912 return;
913 }
914 const retryInMs =
915 environment.isDevelopment &&
916 isRetryableDevelopmentRendererLoadFailure({
917 applicationUrl,
918 errorCode,
919 isMainFrame,
920 validatedUrl: validatedURL,
921 })
922 ? scheduleDevelopmentLoadRetry()
923 : undefined;
924 void runPromise(
925 logWindowWarning("main window failed to load", {
926 errorCode,
927 errorDescription,
928 url: validatedURL,
929 ...(retryInMs === undefined ? {} : { retryInMs }),
930 }),
931 );
932 },
933 );
934 window.webContents.on("render-process-gone", (_event, details) => {
935 const recoverable =
936 details.reason === "crashed" ||
937 details.reason === "oom" ||
938 details.reason === "killed" ||
939 details.reason === "abnormal-exit";
940​
941 runFork(
942 Effect.gen(function* () {
943 const now = yield* Clock.currentTimeMillis;
944 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
945 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
946 );
947 const shouldRecover = recoverable && !window.isDestroyed();
948 // Past the budget, wait for the oldest attempt to leave the window instead of
949 // giving up, so a crash loop backs off but never leaves the window blank.
950 const oldestAttempt =
951 rendererRecoveryTimestamps.length >= RENDERER_RECOVERY_MAX_ATTEMPTS
952 ? rendererRecoveryTimestamps[
953 rendererRecoveryTimestamps.length - RENDERER_RECOVERY_MAX_ATTEMPTS
954 ]
955 : undefined;
956 const reloadInMs =
957 oldestAttempt === undefined
958 ? RENDERER_RECOVERY_RELOAD_DELAY_MS
959 : Math.max(
960 RENDERER_RECOVERY_RELOAD_DELAY_MS,
961 oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now,
962 );
963 yield* logWindowWarning("main window render process gone", {
964 reason: details.reason,
965 exitCode: details.exitCode,
966 recovering: shouldRecover,
967 ...(shouldRecover ? { reloadInMs } : {}),
968 });
969 if (!shouldRecover) {
970 return;
971 }
972 rendererRecoveryTimestamps.push(now + reloadInMs);
973 yield* Effect.sleep(reloadInMs);
974 if (!window.isDestroyed()) {
975 loadApplication();
976 }
977 }),
978 );
979 });
980​
981 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
982 if (environment.platform === "linux") {
983 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
984 }
985 let rendererReady = false;
986 let firstRevealComplete = false;
987 const revealWhenReady = Effect.gen(function* () {
988 if (
989 !rendererReady ||
990 firstRevealComplete ||
991 window.isDestroyed() ||
992 (yield* Ref.get(desktopState.quitting))
993 )
994 return;
995 firstRevealComplete = true;
996 pendingMainReveals.delete(window);
997 window.webContents.setBackgroundThrottling(true);
998 if (persistedSettings.mainWindowMaximized) window.maximize();
999 yield* electronWindow.reveal(window);
1000 yield* dismissConnectingSplash;
1001 });
1002 pendingMainReveals.set(window, revealWhenReady);
1003 bindFirstRevealTrigger(revealSubscribers, () => {
1004 rendererReady = true;
1005 void runPromise(revealWhenReady);
1006 });
1007​
1008 // Desktop IPC only answers the main window, so register it before its renderer can call in.
1009 yield* electronWindow.setMain(window);
1010 loadApplication();
1011 if (environment.isDevelopment) {
1012 window.webContents.openDevTools({ mode: "detach" });
1014​
1015 window.on("closed", () => {
1016 if (!backendHasStarted) mainClosedDuringStartup = true;
1017 clearDevelopmentLoadRetry();
1018 clearBoundsPersist();
1019 void runPromise(electronWindow.clearMain(Option.some(window)));
1020 });
1021​
1022 return Option.some(window);
1023 });
1024​
1025 const createMain = Effect.gen(function* () {
1026 const window = yield* createWindow();
1027 if (Option.isSome(window)) {
1028 mainClosedDuringStartup = false;
1029 yield* logWindowInfo("main window created");
1031 return window;
1032 }).pipe(Effect.withSpan("desktop.window.createMain"));
1033​
1034 const ensureMain = Effect.gen(function* () {
1035 if (yield* Ref.get(desktopState.quitting)) return Option.none<Electron.BrowserWindow>();
1036 const existingWindow = yield* electronWindow.main;
1037 if (Option.isSome(existingWindow)) {
1038 return existingWindow;
1040 return yield* createMain;
1041 }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain"));
1042​
1043 const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
1044 Option.match(window, {
1045 onNone: () => Effect.interrupt,
1046 onSome: Effect.succeed,
1047 });
1048​
1049 const revealOrCreateMain = Effect.gen(function* () {
1050 const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
1051 yield* revealMain(window);
1052 return window;
1053 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
1054​
1055 const waitingForBackend = Effect.gen(function* () {
1056 if (yield* Ref.get(backendReadyRef)) return false;
1057 return (yield* desktopSettings.get).localEnvironmentEnabled;
1058 });
1059​
1060 const createMainIfBackendReady = Effect.gen(function* () {
1061 if (yield* Ref.get(desktopState.quitting)) return;
1062 if (yield* waitingForBackend) return;
1063 yield* ensureMain;
1064 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
1065​
1066 const showConnectingSplash = Effect.gen(function* () {
1067 if (yield* Ref.get(desktopState.quitting)) return;
1068 const existingSplash = yield* Ref.get(splashWindowRef);
1069 if (Option.isSome(existingSplash)) return;
1070 const existingWindow = yield* electronWindow.currentMainOrFirst;
1071 if (Option.isSome(existingWindow)) return;
1072​
1073 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1074 if (yield* Ref.get(desktopState.quitting)) return;
1075 const splash = yield* electronWindow.create({
1076 width: 360,
1077 height: 220,
1078 resizable: false,
1079 minimizable: false,
1080 maximizable: false,
1081 fullscreenable: false,
1082 frame: false,
1083 center: true,
1084 show: false,
1085 skipTaskbar: false,
1086 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
1087 title: environment.displayName,
1088 webPreferences: {
1089 contextIsolation: true,
1090 nodeIntegration: false,
1091 sandbox: true,
1092 },
1093 });
1094 if (yield* Ref.get(desktopState.quitting)) {
1095 yield* electronWindow.destroyAll;
1096 return;
1098 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
1099 yield* Ref.set(splashWindowRef, Option.some(splash));
1100 splash.once("closed", () => {
1101 void runPromise(Ref.set(splashWindowRef, Option.none()));
1102 });
1103 splash.once("ready-to-show", () => {
1104 if (!splash.isDestroyed()) {
1105 splash.show();
1107 });
1108 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
1109 yield* logWindowInfo("connecting splash shown");
1110 }).pipe(
1111 Effect.catch((error) =>
1112 logWindowWarning("failed to show connecting splash", { message: error.message }),
1113 ),
1114 Effect.withSpan("desktop.window.showConnectingSplash"),
1115 );
1116​
1117 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
1118 channel: string,
1119 payload: unknown,
1120 { reveal = true }: { readonly reveal?: boolean } = {},
1121 ) {
1122 if (yield* Ref.get(desktopState.quitting)) return;
1123 // Only the main renderer loads the app preload that listens on these channels.
1124 const existingWindow = yield* electronWindow.main;
1125 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
1126 const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
1127 if (Option.isNone(window) || window.value.isDestroyed()) return;
1128 const targetWindow = window.value;
1129 const send = Effect.sync(() => {
1130 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
1131 });
1132 // Send before best-effort reveal; another process may refuse to yield foreground focus.
1133 const dispatch = reveal
1134 ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause)))
1135 : send;
1136 if (targetWindow.webContents.isLoadingMainFrame()) {
1137 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
1138 return;
1140 yield* dispatch;
1141 });
1142​
1143 return DesktopWindow.of({
1144 createMain: createMain.pipe(Effect.flatMap(requireWindow)),
1145 ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)),
1146 revealOrCreateMain,
1147 prepareCaptureReveal: Effect.gen(function* () {
1148 const existingWindow = yield* currentMainWindow;
1149 if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) {
1150 yield* electronWindow.prepareReveal(existingWindow.value);
1152 }),
1153 activate: Effect.gen(function* () {
1154 if (yield* Ref.get(desktopState.quitting)) return;
1155 const existingWindow = yield* currentMainWindow;
1156 if (Option.isSome(existingWindow)) {
1157 yield* revealMain(existingWindow.value);
1158 return;
1160 if (mainClosedDuringStartup) {
1161 yield* ensureMain;
1162 return;
1164 const backendReady = yield* Ref.get(backendReadyRef);
1165 if (!backendReady) {
1166 const splash = yield* Ref.get(splashWindowRef);
1167 if (Option.isSome(splash)) {
1168 yield* electronWindow.reveal(splash.value);
1169 return;
1172 yield* createMainIfBackendReady;
1173 }).pipe(Effect.withSpan("desktop.window.activate")),
1174 createMainIfBackendReady,
1175 showConnectingSplash,
1176 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1177 backendHasStarted = true;
1178 yield* Ref.set(backendReadyRef, true);
1179 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1180 if (!mainClosedDuringStartup) yield* createMainIfBackendReady;
1181 }),
1182 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1183 Effect.withSpan("desktop.window.handleBackendNotReady"),
1184 ),
1185 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
1186 Effect.withSpan("desktop.window.flushMainWindowBounds"),
1187 ),
1188 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
1189 yield* Effect.annotateCurrentSpan({ action });
1190 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
1191 }),
1192 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
1193 yield* Effect.annotateCurrentSpan({
1194 event: event.type,
1195 captureId: "id" in event ? (event.id ?? null) : null,
1196 });
1197 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
1198 reveal: event.type === "started",
1199 });
1200 }),
1201 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
1202 yield* Effect.annotateCurrentSpan({ direction });
1203 const window = yield* electronWindow.main;
1204 if (Option.isNone(window) || window.value.isDestroyed()) {
1205 return;
1207 yield* zoomWindow(window.value, direction);
1208 }),
1209 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1210 yield* Effect.annotateCurrentSpan({ command });
1211 // A focused OAuth popup must not receive the app's Reload command.
1212 const window = yield* electronWindow.main;
1213 if (Option.isNone(window) || window.value.isDestroyed()) return;
1214 const webContents = window.value.webContents;
1215 if (command === "reload") webContents.reload();
1216 else if (command === "forceReload") webContents.reloadIgnoringCache();
1217 else webContents.toggleDevTools();
1218 }),
1219 syncAppearance: Effect.gen(function* () {
1220 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1221 yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) =>
1222 syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform),
1223 );
1224 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1225 });
1226});
1227​
1228export const layer = Layer.effect(DesktopWindow, make);