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 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
429
430 const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* (
431 window: Electron.BrowserWindow,
432 direction: MainWindowZoomDirection,
433 ) {
434 const webContents = window.webContents;
435 webContents.setZoomLevel(
436 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
437 );
438 if (environment.platform === "darwin") syncMacosWindowButtons(window);
439 // App zoom propagates to guests; restore each preview's own zoom.
440 yield* previewManager.reapplyZoom();
441 });
442
443 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
444 Option.Option<Electron.BrowserWindow>,
445 DesktopWindowError
446 > {
447 if (yield* Ref.get(desktopState.quitting)) return Option.none();
448 yield* previewManager.getBrowserSession();
449 const applicationUrl = getDesktopUrl(environment.isDevelopment);
450 const iconPaths = yield* assets.iconPaths;
451 const iconOption = getIconOption(iconPaths, environment.platform);
452 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
453 const persistedSettings = yield* desktopSettings.get;
454 const persistedBounds = persistedSettings.mainWindowBounds;
455 const displayBoundsResult = yield* Effect.sync(() => {
456 try {
457 return {
458 _tag: "Success" as const,
459 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
460 };
461 } catch (cause) {
462 return { _tag: "Failure" as const, cause };
463 }
464 });
465 const displayBounds =
466 displayBoundsResult._tag === "Success"
467 ? displayBoundsResult.bounds
468 : yield* logWindowWarning("failed to read connected displays; using defaults", {
469 cause: displayBoundsResult.cause,
470 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
471 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
472 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
473 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
474 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
475 }
476 if (yield* Ref.get(desktopState.quitting)) return Option.none();
477 const window = yield* electronWindow.create({
478 ...initialBounds,
479 minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width,
480 minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height,
481 show: false,
482 autoHideMenuBar: true,
483 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
484 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
485 ...iconOption,
486 title: environment.displayName,
487 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
488 webPreferences: {
489 preload: environment.preloadPath,
490 // Hidden-renderer throttling stalls first paint; re-enable it after the first reveal.
491 backgroundThrottling: false,
492 contextIsolation: true,
493 nodeIntegration: false,
494 sandbox: true,
495 webviewTag: true,
496 // Guest fullscreen propagates to the embedder; both must opt out to keep it inside the webview.
497 // The app's own fullscreen elements reach OS fullscreen through syncHtmlFullscreen.
498 disableHtmlFullscreenWindowResize: true,
499 },
500 });
501 if (yield* Ref.get(desktopState.quitting)) {
502 yield* electronWindow.destroyAll;
503 return Option.none();
504 }
505
506 pendingMainReveals.set(window, Effect.void);
507 yield* rendererHistory.register(window.webContents, { surface: "main" });
508 if (environment.platform === "darwin") {
509 window.setAutoHideCursor(false);
510 }
511 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
512 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
513 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
514 let lastPersistableState: {
515 readonly bounds: DesktopAppSettings.DesktopWindowBounds;
516 readonly isMaximized: boolean;
517 } | null = null;
518 const readPersistableState = () => {
519 if (window.isDestroyed()) {
520 return null;
521 }
522 // Minimized windows report stale state on some platforms (macOS: not maximized, the
523 // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing.
524 if (window.isMinimized()) {
525 return lastPersistableState;
526 }
527 const isMaximized = window.isMaximized();
528 const bounds =
529 window.isFullScreen() || isMaximized
530 ? normalBoundsOnWindowDisplay(
531 window.getNormalBounds(),
532 window.getBounds(),
533 readDisplayBoundsOrEmpty(),
534 )
535 : window.getBounds();
536 const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({
537 x: Math.round(bounds.x),
538 y: Math.round(bounds.y),
539 width: Math.round(bounds.width),
540 height: Math.round(bounds.height),
541 });
542 lastPersistableState =
543 persistableBounds === null ? null : { bounds: persistableBounds, isMaximized };
544 return lastPersistableState;
545 };
546 const fallbackWindowBounds = boundsPersistenceEnabled
547 ? null
548 : (readPersistableState()?.bounds ?? null);
549 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
550 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
551 if (!boundsPersistenceEnabled) {
552 return pendingBoundsPersistFiber;
553 }
554 const state = readPersistableState();
555 if (state === null) {
556 return pendingBoundsPersistFiber;
557 }
558 pendingBoundsPersistFiber = runFork(
559 desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe(
560 Effect.asVoid,
561 Effect.catch((error) =>
562 logWindowWarning("failed to persist main window bounds", {
563 message: error.message,
564 }),
565 ),
566 ),
567 );
568 return pendingBoundsPersistFiber;
569 };
570 const scheduleBoundsPersist = () => {
571 const state = readPersistableState();
572 if (
573 !boundsPersistenceEnabled &&
574 (state === null ||
575 (fallbackWindowBounds !== null &&
576 windowBoundsEqual(state.bounds, fallbackWindowBounds) &&
577 state.isMaximized === fallbackWindowMaximized))
578 ) {
579 return;
580 }
581 boundsPersistenceEnabled = true;
582 if (boundsPersistFiber !== undefined) {
583 const fiber = boundsPersistFiber;
584 boundsPersistFiber = undefined;
585 runFork(Fiber.interrupt(fiber));
586 }
587 boundsPersistFiber = runFork(
588 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
589 Effect.andThen(
590 Effect.sync(() => {
591 boundsPersistFiber = undefined;
592 void persistCurrentBounds();
593 }),
594 ),
595 ),
596 );
597 };
598 const clearBoundsPersist = () => {
599 if (boundsPersistFiber === undefined) {
600 return;
601 }
602 const fiber = boundsPersistFiber;
603 boundsPersistFiber = undefined;
604 runFork(Fiber.interrupt(fiber));
605 };
606 const flushBoundsPersist = Effect.sync(() => {
607 clearBoundsPersist();
608 return persistCurrentBounds();
609 }).pipe(
610 Effect.flatMap((fiber) =>
611 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
612 ),
613 );
614 flushMainWindowBounds = flushBoundsPersist;
615
616 yield* previewManager.setMainWindow(window);
617 if (yield* Ref.get(desktopState.quitting)) {
618 yield* electronWindow.destroyAll;
619 return Option.none();
620 }
621 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
622 if (
623 typeof params.partition !== "string" ||
624 !previewManager.isBrowserPartition(params.partition)
625 ) {
626 event.preventDefault();
627 return;
628 }
629 webPreferences.sandbox = true;
630 webPreferences.nodeIntegration = false;
631 webPreferences.nodeIntegrationInSubFrames = false;
632 webPreferences.contextIsolation = false;
633 webPreferences.disableHtmlFullscreenWindowResize = true;
634 if (previewPasskeys.bridgeEnabled) {
635 webPreferences.additionalArguments = [
636 ...(webPreferences.additionalArguments ?? []),
637 PASSKEY_BRIDGE_ARGUMENT,
638 ];
639 }
640 if (!primaryPaste.enabled) {
641 webPreferences.additionalArguments = [
642 ...(webPreferences.additionalArguments ?? []),
643 PRIMARY_PASTE_DISABLED_ARGUMENT,
644 ];
645 }
646 });
647
648 const contextMenuContents = new WeakSet<Electron.WebContents>();
649 const installContextMenu = (
650 ownerWindow: Electron.BrowserWindow,
651 contents: Electron.WebContents,
652 ): void => {
653 if (contextMenuContents.has(contents)) return;
654 contextMenuContents.add(contents);
655 contents.on("context-menu", (event, params) => {
656 event.preventDefault();
657 if (contents.isDestroyed() || ownerWindow.isDestroyed()) return;
658 // Right-clicking a guest may leave native editing roles targeting the host renderer.
659 contents.focus();
660
661 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
662
663 if (params.misspelledWord) {
664 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
665 menuTemplate.push({
666 label: suggestion,
667 click: () => {
668 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
669 },
670 });
671 }
672 if (params.dictionarySuggestions.length === 0) {
673 menuTemplate.push({ label: "No suggestions", enabled: false });
674 }
675 menuTemplate.push({ type: "separator" });
676 }
677
678 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
679 menuTemplate.push(
680 {
681 label: "Copy Link",
682 click: () => {
683 void runPromise(electronShell.copyText(params.linkURL));
684 },
685 },
686 { type: "separator" },
687 );
688 }
689
690 const mailtoAddress = parseMailtoAddress(params.linkURL);
691 if (Option.isSome(mailtoAddress)) {
692 menuTemplate.push(
693 {
694 label: "Copy Email Address",
695 click: () => {
696 void runPromise(electronShell.copyText(mailtoAddress.value));
697 },
698 },
699 { type: "separator" },
700 );
701 }
702
703 if (params.mediaType === "image") {
704 menuTemplate.push({
705 label: "Copy Image",
706 click: () => {
707 void runPromise(
708 Effect.tryPromise({
709 try: () => copyContextMenuImage(contents, params),
710 catch: (cause) => new ContextMenuImageCopyError({ cause }),
711 }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))),
712 );
713 },
714 });
715 menuTemplate.push({ type: "separator" });
716 }
717
718 menuTemplate.push(
719 { role: "cut", enabled: params.editFlags.canCut },
720 { role: "copy", enabled: params.editFlags.canCopy },
721 { role: "paste", enabled: params.editFlags.canPaste },
722 { role: "selectAll", enabled: params.editFlags.canSelectAll },
723 );
724
725 void runPromise(
726 electronMenu.popupTemplate({
727 window: ownerWindow,
728 template: menuTemplate,
729 ...(params.frame ? { frame: params.frame } : {}),
730 }),
731 );
732 });
733 contents.on("did-create-window", (popup) => {
734 installContextMenu(popup, popup.webContents);
735 });
736 };
737 installContextMenu(window, window.webContents);
738 window.webContents.on("did-attach-webview", (_event, contents) => {
739 installContextMenu(window, contents);
740 void runPromise(previewManager.prepareWebview(contents));
741 });
742
743 window.webContents.setWindowOpenHandler(({ url }) => {
744 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
745 void runPromise(electronShell.openExternal(url));
746 }
747 return { action: "deny" };
748 });
749 window.webContents.on("will-navigate", (event, url) => {
750 if (
751 isSameOriginRendererNavigation({
752 applicationUrl,
753 navigationUrl: url,
754 })
755 ) {
756 return;
757 }
758
759 event.preventDefault();
760 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
761 void runPromise(electronShell.openExternal(url));
762 }
763 });
764
765 const quitShortcutHandler = makeQuitShortcutHandler({
766 platform: environment.platform,
767 getMode: () =>
768 runPromise(
769 Effect.map(
770 clientSettings.get,
771 Option.match({
772 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
773 onSome: (settings) => settings.confirmQuit,
774 }),
775 ),
776 ),
777 notify: (hint) => {
778 if (!window.isDestroyed()) {
779 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
780 }
781 },
782 // Hold focus until shortcut release so remaining repeats cannot reach the next app.
783 concealWindow: () => concealPendingQuitWindow(window),
784 quit: () => {
785 void runPromise(electronApp.quit);
786 },
787 });
788 window.webContents.on("before-input-event", (event, input) => {
789 quitShortcutHandler(event, input);
790 if (window.isDestroyed()) return;
791 // Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut.
792 window.webContents.setIgnoreMenuShortcuts(
793 (environment.platform === "darwin" ? input.meta : input.control) &&
794 !input.alt &&
795 !input.shift &&
796 input.key.toLowerCase() === "w",
797 );
798 // A held Cmd/Ctrl+W closes one tab or terminal, not each one behind it.
799 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
800 const modifier = environment.platform === "darwin" ? input.meta : input.control;
801 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
802 event.preventDefault();
803 }
804 });
805 window.webContents.on("input-event", (_event, input) => {
806 if (window.isDestroyed()) return;
807 if (input.type === "gestureScrollBegin") {
808 window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL);
809 } else if (input.type === "gestureScrollEnd") {
810 window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
811 }
812 });
813 // Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event.
814 window.webContents.on("zoom-changed", (_event, direction) => {
815 if (window.isDestroyed()) return;
816 runFork(zoomWindow(window, direction));
817 });
818
819 // The renderer titles the window after the open thread; only a blank title
820 // falls back to the app name.
821 window.on("page-title-updated", (event, title) => {
822 if (title.trim() !== "") return;
823 event.preventDefault();
824 window.setTitle(environment.displayName);
825 });
826 window.on("resize", scheduleBoundsPersist);
827 window.on("move", scheduleBoundsPersist);
828 window.on("maximize", scheduleBoundsPersist);
829 window.on("unmaximize", scheduleBoundsPersist);
830 window.on("close", () => {
831 runFork(flushBoundsPersist);
832 });
833
834 if (environment.platform === "darwin") {
835 // Mouse drivers can deliver Back/Forward as macOS swipe gestures instead of buttons.
836 window.on("swipe", (_event, direction) => {
837 const history = window.webContents.navigationHistory;
838 if (direction === "left" && history.canGoBack()) history.goBack();
839 else if (direction === "right" && history.canGoForward()) history.goForward();
840 });
841 window.on("enter-full-screen", () => {
842 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
843 });
844 window.on("leave-full-screen", () => {
845 syncMacosWindowButtons(window);
846 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
847 });
848 }
849
850 let developmentLoadRetryIndex = 0;
851 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
852 let rendererRecoveryTimestamps: number[] = [];
853 const clearDevelopmentLoadRetry = () => {
854 if (developmentLoadRetryFiber === undefined) {
855 return;
856 }
857 const retryFiber = developmentLoadRetryFiber;
858 developmentLoadRetryFiber = undefined;
859 runFork(Fiber.interrupt(retryFiber));
860 };
861 const loadApplication = () => {
862 if (window.isDestroyed()) {
863 return;
864 }
865 void window.loadURL(applicationUrl).catch(() => undefined);
866 };
867 const scheduleDevelopmentLoadRetry = () => {
868 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
869 return undefined;
870 }
871
872 const retryIndex = Math.min(
873 developmentLoadRetryIndex,
874 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
875 );
876 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
877 developmentLoadRetryIndex += 1;
878 developmentLoadRetryFiber = runFork(
879 Effect.sleep(retryInMs).pipe(
880 Effect.andThen(
881 Effect.sync(() => {
882 developmentLoadRetryFiber = undefined;
883 if (!window.isDestroyed()) {
884 loadApplication();
885 }
886 }),
887 ),
888 ),
889 );
890 return retryInMs;
891 };
892
893 window.webContents.on("did-finish-load", () => {
894 if (
895 environment.isDevelopment &&
896 !isSameOriginRendererNavigation({
897 applicationUrl,
898 navigationUrl: window.webContents.getURL(),
899 })
900 ) {
901 return;
902 }
903 clearDevelopmentLoadRetry();
904 developmentLoadRetryIndex = 0;
905 if (environment.platform === "darwin") syncMacosWindowButtons(window);
906 });
907 window.webContents.on(
908 "did-fail-load",
909 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
910 if (!isMainFrame) {
911 return;
912 }
913 const retryInMs =
914 environment.isDevelopment &&
915 isRetryableDevelopmentRendererLoadFailure({
916 applicationUrl,
917 errorCode,
918 isMainFrame,
919 validatedUrl: validatedURL,
920 })
921 ? scheduleDevelopmentLoadRetry()
922 : undefined;
923 void runPromise(
924 logWindowWarning("main window failed to load", {
925 errorCode,
926 errorDescription,
927 url: validatedURL,
928 ...(retryInMs === undefined ? {} : { retryInMs }),
929 }),
930 );
931 },
932 );
933 window.webContents.on("render-process-gone", (_event, details) => {
934 const recoverable =
935 details.reason === "crashed" ||
936 details.reason === "oom" ||
937 details.reason === "killed" ||
938 details.reason === "abnormal-exit";
939
940 runFork(
941 Effect.gen(function* () {
942 const now = yield* Clock.currentTimeMillis;
943 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
944 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
945 );
946 const shouldRecover =
947 recoverable &&
948 !window.isDestroyed() &&
949 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
950 yield* logWindowWarning("main window render process gone", {
951 reason: details.reason,
952 exitCode: details.exitCode,
953 recovering: shouldRecover,
954 });
955 if (!shouldRecover) {
956 return;
957 }
958 rendererRecoveryTimestamps.push(now);
959 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
960 if (!window.isDestroyed()) {
961 loadApplication();
962 }
963 }),
964 );
965 });
966
967 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
968 if (environment.platform === "linux") {
969 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
970 }
971 let rendererReady = false;
972 let firstRevealComplete = false;
973 const revealWhenReady = Effect.gen(function* () {
974 if (
975 !rendererReady ||
976 firstRevealComplete ||
977 window.isDestroyed() ||
978 (yield* Ref.get(desktopState.quitting))
979 )
980 return;
981 firstRevealComplete = true;
982 pendingMainReveals.delete(window);
983 window.webContents.setBackgroundThrottling(true);
984 if (persistedSettings.mainWindowMaximized) window.maximize();
985 yield* electronWindow.reveal(window);
986 yield* dismissConnectingSplash;
987 });
988 pendingMainReveals.set(window, revealWhenReady);
989 bindFirstRevealTrigger(revealSubscribers, () => {
990 rendererReady = true;
991 void runPromise(revealWhenReady);
992 });
993
994 // Desktop IPC only answers the main window, so register it before its renderer can call in.
995 yield* electronWindow.setMain(window);
996 loadApplication();
997 if (environment.isDevelopment) {
998 window.webContents.openDevTools({ mode: "detach" });
999 }
1000
1001 window.on("closed", () => {
1002 if (!backendHasStarted) mainClosedDuringStartup = true;
1003 clearDevelopmentLoadRetry();
1004 clearBoundsPersist();
1005 void runPromise(electronWindow.clearMain(Option.some(window)));
1006 });
1007
1008 return Option.some(window);
1009 });
1010
1011 const createMain = Effect.gen(function* () {
1012 const window = yield* createWindow();
1013 if (Option.isSome(window)) {
1014 mainClosedDuringStartup = false;
1015 yield* logWindowInfo("main window created");
1016 }
1017 return window;
1018 }).pipe(Effect.withSpan("desktop.window.createMain"));
1019
1020 const ensureMain = Effect.gen(function* () {
1021 if (yield* Ref.get(desktopState.quitting)) return Option.none<Electron.BrowserWindow>();
1022 const existingWindow = yield* currentMainWindow;
1023 if (Option.isSome(existingWindow)) {
1024 return existingWindow;
1025 }
1026 return yield* createMain;
1027 }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain"));
1028
1029 const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
1030 Option.match(window, {
1031 onNone: () => Effect.interrupt,
1032 onSome: Effect.succeed,
1033 });
1034
1035 const revealOrCreateMain = Effect.gen(function* () {
1036 const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
1037 yield* revealMain(window);
1038 return window;
1039 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
1040
1041 const waitingForBackend = Effect.gen(function* () {
1042 if (yield* Ref.get(backendReadyRef)) return false;
1043 return (yield* desktopSettings.get).localEnvironmentEnabled;
1044 });
1045
1046 const createMainIfBackendReady = Effect.gen(function* () {
1047 if (yield* Ref.get(desktopState.quitting)) return;
1048 if (yield* waitingForBackend) return;
1049 yield* ensureMain;
1050 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
1051
1052 const showConnectingSplash = Effect.gen(function* () {
1053 if (yield* Ref.get(desktopState.quitting)) return;
1054 const existingSplash = yield* Ref.get(splashWindowRef);
1055 if (Option.isSome(existingSplash)) return;
1056 const existingWindow = yield* electronWindow.currentMainOrFirst;
1057 if (Option.isSome(existingWindow)) return;
1058
1059 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1060 if (yield* Ref.get(desktopState.quitting)) return;
1061 const splash = yield* electronWindow.create({
1062 width: 360,
1063 height: 220,
1064 resizable: false,
1065 minimizable: false,
1066 maximizable: false,
1067 fullscreenable: false,
1068 frame: false,
1069 center: true,
1070 show: false,
1071 skipTaskbar: false,
1072 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
1073 title: environment.displayName,
1074 webPreferences: {
1075 contextIsolation: true,
1076 nodeIntegration: false,
1077 sandbox: true,
1078 },
1079 });
1080 if (yield* Ref.get(desktopState.quitting)) {
1081 yield* electronWindow.destroyAll;
1082 return;
1083 }
1084 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
1085 yield* Ref.set(splashWindowRef, Option.some(splash));
1086 splash.once("closed", () => {
1087 void runPromise(Ref.set(splashWindowRef, Option.none()));
1088 });
1089 splash.once("ready-to-show", () => {
1090 if (!splash.isDestroyed()) {
1091 splash.show();
1092 }
1093 });
1094 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
1095 yield* logWindowInfo("connecting splash shown");
1096 }).pipe(
1097 Effect.catch((error) =>
1098 logWindowWarning("failed to show connecting splash", { message: error.message }),
1099 ),
1100 Effect.withSpan("desktop.window.showConnectingSplash"),
1101 );
1102
1103 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
1104 channel: string,
1105 payload: unknown,
1106 { reveal = true }: { readonly reveal?: boolean } = {},
1107 ) {
1108 if (yield* Ref.get(desktopState.quitting)) return;
1109 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
1110 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
1111 const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
1112 if (Option.isNone(window) || window.value.isDestroyed()) return;
1113 const targetWindow = window.value;
1114 const send = Effect.sync(() => {
1115 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
1116 });
1117 // Send before best-effort reveal; another process may refuse to yield foreground focus.
1118 const dispatch = reveal
1119 ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause)))
1120 : send;
1121 if (targetWindow.webContents.isLoadingMainFrame()) {
1122 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
1123 return;
1124 }
1125 yield* dispatch;
1126 });
1127
1128 return DesktopWindow.of({
1129 createMain: createMain.pipe(Effect.flatMap(requireWindow)),
1130 ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)),
1131 revealOrCreateMain,
1132 prepareCaptureReveal: Effect.gen(function* () {
1133 const existingWindow = yield* currentMainWindow;
1134 if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) {
1135 yield* electronWindow.prepareReveal(existingWindow.value);
1136 }
1137 }),
1138 activate: Effect.gen(function* () {
1139 if (yield* Ref.get(desktopState.quitting)) return;
1140 const existingWindow = yield* currentMainWindow;
1141 if (Option.isSome(existingWindow)) {
1142 yield* revealMain(existingWindow.value);
1143 return;
1144 }
1145 if (mainClosedDuringStartup) {
1146 yield* ensureMain;
1147 return;
1148 }
1149 const backendReady = yield* Ref.get(backendReadyRef);
1150 if (!backendReady) {
1151 const splash = yield* Ref.get(splashWindowRef);
1152 if (Option.isSome(splash)) {
1153 yield* electronWindow.reveal(splash.value);
1154 return;
1155 }
1156 }
1157 yield* createMainIfBackendReady;
1158 }).pipe(Effect.withSpan("desktop.window.activate")),
1159 createMainIfBackendReady,
1160 showConnectingSplash,
1161 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1162 backendHasStarted = true;
1163 yield* Ref.set(backendReadyRef, true);
1164 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1165 if (!mainClosedDuringStartup) yield* createMainIfBackendReady;
1166 }),
1167 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1168 Effect.withSpan("desktop.window.handleBackendNotReady"),
1169 ),
1170 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
1171 Effect.withSpan("desktop.window.flushMainWindowBounds"),
1172 ),
1173 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
1174 yield* Effect.annotateCurrentSpan({ action });
1175 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
1176 }),
1177 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
1178 yield* Effect.annotateCurrentSpan({
1179 event: event.type,
1180 captureId: "id" in event ? (event.id ?? null) : null,
1181 });
1182 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
1183 reveal: event.type === "started",
1184 });
1185 }),
1186 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
1187 yield* Effect.annotateCurrentSpan({ direction });
1188 const window = yield* electronWindow.main;
1189 if (Option.isNone(window) || window.value.isDestroyed()) {
1190 return;
1191 }
1192 yield* zoomWindow(window.value, direction);
1193 }),
1194 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1195 yield* Effect.annotateCurrentSpan({ command });
1196 // A focused OAuth popup must not receive the app's Reload command.
1197 const window = yield* electronWindow.main;
1198 if (Option.isNone(window) || window.value.isDestroyed()) return;
1199 const webContents = window.value.webContents;
1200 if (command === "reload") webContents.reload();
1201 else if (command === "forceReload") webContents.reloadIgnoringCache();
1202 else webContents.toggleDevTools();
1203 }),
1204 syncAppearance: Effect.gen(function* () {
1205 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1206 yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) =>
1207 syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform),
1208 );
1209 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1210 });
1211});
1212
1213export const layer = Layer.effect(DesktopWindow, make);