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

DesktopWindow.ts

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