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

DesktopWindow.ts

1,257 lines46.7 KB

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