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