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

DesktopWindow.ts

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