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

DesktopWindow.ts

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