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

DesktopWindow.ts

1,212 lines45.1 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";
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 }
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 }
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 });
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 });
163​
164function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
165 return shouldUseDarkColors ? "#000000" : "#ffffff";
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 );
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;
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;
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 };
229​
230function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] {
231 try {
232 return Electron.screen.getAllDisplays().map((display) => display.bounds);
233 } catch {
234 return [];
235 }
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 );
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;
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)}`;
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 }
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 );
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);
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 };
343​
344function syncWindowAppearance(
345 window: Electron.BrowserWindow,
346 shouldUseDarkColors: boolean,
347 platform: NodeJS.Platform,
348): Effect.Effect<void> {
349 return Effect.sync(() => {
350 if (window.isDestroyed()) {
351 return;
352 }
353​
354 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
355 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
356 if (typeof titleBarOverlay === "object") {
357 window.setTitleBarOverlay(titleBarOverlay);
358 }
359 });
361​
362type RevealSubscription = (listener: () => void) => void;
363​
364function bindFirstRevealTrigger(
365 subscribers: readonly RevealSubscription[],
366 reveal: () => void,
367): void {
368 let revealed = false;
369 const fire = () => {
370 if (revealed) return;
371 revealed = true;
372 reveal();
373 };
374 for (const subscribe of subscribers) {
375 subscribe(fire);
376 }
378​
379/** @public */
380export const make = Effect.gen(function* () {
381 const environment = yield* DesktopEnvironment.DesktopEnvironment;
382 const desktopState = yield* DesktopState.DesktopState;
383 const assets = yield* DesktopAssets.DesktopAssets;
384 const electronMenu = yield* ElectronMenu.ElectronMenu;
385 const electronShell = yield* ElectronShell.ElectronShell;
386 const electronTheme = yield* ElectronTheme.ElectronTheme;
387 const electronWindow = yield* ElectronWindow.ElectronWindow;
388 const previewManager = yield* PreviewManager.PreviewManager;
389 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
390 const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste;
391 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
392 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
393 const electronApp = yield* ElectronApp.ElectronApp;
394 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
395 const backendReadyRef = yield* Ref.make(false);
396 let backendHasStarted = false;
397 let mainClosedDuringStartup = false;
398 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
399 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
400 const runFork = Effect.runForkWith(context);
401 const runPromise = Effect.runPromiseWith(context);
402 const mainWindowMutex = yield* Semaphore.make(1);
403 const pendingMainReveals = new WeakMap<Electron.BrowserWindow, Effect.Effect<void>>();
404 const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) =>
405 Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)),
406 );
407 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
408​
409 const dismissConnectingSplash = Effect.gen(function* () {
410 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
411 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
412 splash.value.close();
413 }
414 });
415​
416 // Electron's first-window fallback can select the unregistered connecting splash; exclude it so main creation retries.
417 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
418 Ref.get(splashWindowRef).pipe(
419 Effect.map((splash) =>
420 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
421 ? Option.none<Electron.BrowserWindow>()
422 : window,
423 ),
424 );
425​
426 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
427 const focusedMainWindow = electronWindow.focusedMainOrFirst.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 =
946 recoverable &&
947 !window.isDestroyed() &&
948 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
949 yield* logWindowWarning("main window render process gone", {
950 reason: details.reason,
951 exitCode: details.exitCode,
952 recovering: shouldRecover,
953 });
954 if (!shouldRecover) {
955 return;
956 }
957 rendererRecoveryTimestamps.push(now);
958 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
959 if (!window.isDestroyed()) {
960 loadApplication();
961 }
962 }),
963 );
964 });
965​
966 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
967 if (environment.platform === "linux") {
968 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
969 }
970 let rendererReady = false;
971 let firstRevealComplete = false;
972 const revealWhenReady = Effect.gen(function* () {
973 if (
974 !rendererReady ||
975 firstRevealComplete ||
976 window.isDestroyed() ||
977 (yield* Ref.get(desktopState.quitting))
978 )
979 return;
980 firstRevealComplete = true;
981 pendingMainReveals.delete(window);
982 window.webContents.setBackgroundThrottling(true);
983 if (persistedSettings.mainWindowMaximized) window.maximize();
984 yield* electronWindow.reveal(window);
985 yield* dismissConnectingSplash;
986 });
987 pendingMainReveals.set(window, revealWhenReady);
988 bindFirstRevealTrigger(revealSubscribers, () => {
989 rendererReady = true;
990 void runPromise(revealWhenReady);
991 });
992​
993 // Desktop IPC only answers the main window, so register it before its renderer can call in.
994 yield* electronWindow.setMain(window);
995 loadApplication();
996 if (environment.isDevelopment) {
997 window.webContents.openDevTools({ mode: "detach" });
998 }
999​
1000 window.on("closed", () => {
1001 if (!backendHasStarted) mainClosedDuringStartup = true;
1002 clearDevelopmentLoadRetry();
1003 clearBoundsPersist();
1004 void runPromise(electronWindow.clearMain(Option.some(window)));
1005 });
1006​
1007 return Option.some(window);
1008 });
1009​
1010 const createMain = Effect.gen(function* () {
1011 const window = yield* createWindow();
1012 if (Option.isSome(window)) {
1013 mainClosedDuringStartup = false;
1014 yield* logWindowInfo("main window created");
1016 return window;
1017 }).pipe(Effect.withSpan("desktop.window.createMain"));
1018​
1019 const ensureMain = Effect.gen(function* () {
1020 if (yield* Ref.get(desktopState.quitting)) return Option.none<Electron.BrowserWindow>();
1021 const existingWindow = yield* currentMainWindow;
1022 if (Option.isSome(existingWindow)) {
1023 return existingWindow;
1025 return yield* createMain;
1026 }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain"));
1027​
1028 const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
1029 Option.match(window, {
1030 onNone: () => Effect.interrupt,
1031 onSome: Effect.succeed,
1032 });
1033​
1034 const revealOrCreateMain = Effect.gen(function* () {
1035 const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
1036 yield* revealMain(window);
1037 return window;
1038 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
1039​
1040 const waitingForBackend = Effect.gen(function* () {
1041 if (yield* Ref.get(backendReadyRef)) return false;
1042 return (yield* desktopSettings.get).localEnvironmentEnabled;
1043 });
1044​
1045 const createMainIfBackendReady = Effect.gen(function* () {
1046 if (yield* Ref.get(desktopState.quitting)) return;
1047 if (yield* waitingForBackend) return;
1048 yield* ensureMain;
1049 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
1050​
1051 const showConnectingSplash = Effect.gen(function* () {
1052 if (yield* Ref.get(desktopState.quitting)) return;
1053 const existingSplash = yield* Ref.get(splashWindowRef);
1054 if (Option.isSome(existingSplash)) return;
1055 const existingWindow = yield* electronWindow.currentMainOrFirst;
1056 if (Option.isSome(existingWindow)) return;
1057​
1058 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1059 if (yield* Ref.get(desktopState.quitting)) return;
1060 const splash = yield* electronWindow.create({
1061 width: 360,
1062 height: 220,
1063 resizable: false,
1064 minimizable: false,
1065 maximizable: false,
1066 fullscreenable: false,
1067 frame: false,
1068 center: true,
1069 show: false,
1070 skipTaskbar: false,
1071 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
1072 title: environment.displayName,
1073 webPreferences: {
1074 contextIsolation: true,
1075 nodeIntegration: false,
1076 sandbox: true,
1077 },
1078 });
1079 if (yield* Ref.get(desktopState.quitting)) {
1080 yield* electronWindow.destroyAll;
1081 return;
1083 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
1084 yield* Ref.set(splashWindowRef, Option.some(splash));
1085 splash.once("closed", () => {
1086 void runPromise(Ref.set(splashWindowRef, Option.none()));
1087 });
1088 splash.once("ready-to-show", () => {
1089 if (!splash.isDestroyed()) {
1090 splash.show();
1092 });
1093 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
1094 yield* logWindowInfo("connecting splash shown");
1095 }).pipe(
1096 Effect.catch((error) =>
1097 logWindowWarning("failed to show connecting splash", { message: error.message }),
1098 ),
1099 Effect.withSpan("desktop.window.showConnectingSplash"),
1100 );
1101​
1102 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
1103 channel: string,
1104 payload: unknown,
1105 { reveal = true }: { readonly reveal?: boolean } = {},
1106 ) {
1107 if (yield* Ref.get(desktopState.quitting)) return;
1108 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
1109 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
1110 const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
1111 if (Option.isNone(window) || window.value.isDestroyed()) return;
1112 const targetWindow = window.value;
1113 const send = Effect.sync(() => {
1114 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
1115 });
1116 // Send before best-effort reveal; another process may refuse to yield foreground focus.
1117 const dispatch = reveal
1118 ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause)))
1119 : send;
1120 if (targetWindow.webContents.isLoadingMainFrame()) {
1121 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
1122 return;
1124 yield* dispatch;
1125 });
1126​
1127 return DesktopWindow.of({
1128 createMain: createMain.pipe(Effect.flatMap(requireWindow)),
1129 ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)),
1130 revealOrCreateMain,
1131 prepareCaptureReveal: Effect.gen(function* () {
1132 const existingWindow = yield* currentMainWindow;
1133 if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) {
1134 yield* electronWindow.prepareReveal(existingWindow.value);
1136 }),
1137 activate: Effect.gen(function* () {
1138 if (yield* Ref.get(desktopState.quitting)) return;
1139 const existingWindow = yield* currentMainWindow;
1140 if (Option.isSome(existingWindow)) {
1141 yield* revealMain(existingWindow.value);
1142 return;
1144 if (mainClosedDuringStartup) {
1145 yield* ensureMain;
1146 return;
1148 const backendReady = yield* Ref.get(backendReadyRef);
1149 if (!backendReady) {
1150 const splash = yield* Ref.get(splashWindowRef);
1151 if (Option.isSome(splash)) {
1152 yield* electronWindow.reveal(splash.value);
1153 return;
1156 yield* createMainIfBackendReady;
1157 }).pipe(Effect.withSpan("desktop.window.activate")),
1158 createMainIfBackendReady,
1159 showConnectingSplash,
1160 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1161 backendHasStarted = true;
1162 yield* Ref.set(backendReadyRef, true);
1163 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1164 if (!mainClosedDuringStartup) yield* createMainIfBackendReady;
1165 }),
1166 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1167 Effect.withSpan("desktop.window.handleBackendNotReady"),
1168 ),
1169 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
1170 Effect.withSpan("desktop.window.flushMainWindowBounds"),
1171 ),
1172 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
1173 yield* Effect.annotateCurrentSpan({ action });
1174 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
1175 }),
1176 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
1177 yield* Effect.annotateCurrentSpan({
1178 event: event.type,
1179 captureId: "id" in event ? (event.id ?? null) : null,
1180 });
1181 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
1182 reveal: event.type === "started",
1183 });
1184 }),
1185 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
1186 yield* Effect.annotateCurrentSpan({ direction });
1187 const window = yield* electronWindow.main;
1188 if (Option.isNone(window) || window.value.isDestroyed()) {
1189 return;
1191 yield* zoomWindow(window.value, direction);
1192 }),
1193 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1194 yield* Effect.annotateCurrentSpan({ command });
1195 // A focused OAuth popup must not receive the app's Reload command.
1196 const window = yield* electronWindow.main;
1197 if (Option.isNone(window) || window.value.isDestroyed()) return;
1198 const webContents = window.value.webContents;
1199 if (command === "reload") webContents.reload();
1200 else if (command === "forceReload") webContents.reloadIgnoringCache();
1201 else webContents.toggleDevTools();
1202 }),
1203 syncAppearance: Effect.gen(function* () {
1204 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1205 yield* electronWindow.syncAllAppearance((window) =>
1206 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
1207 );
1208 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1209 });
1210});
1211​
1212export const layer = Layer.effect(DesktopWindow, make);