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

DesktopWindow.ts

1,330 lines49.9 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("Cut", { $context: "Edit menu item" })),
756 enabled: params.editFlags.canCut,
757 },
758 {
759 role: "copy",
760 label: m(msg("Copy", { $context: "Edit menu item" })),
761 enabled: params.editFlags.canCopy,
762 },
763 {
764 role: "paste",
765 label: m(msg("Paste", { $context: "Edit menu item" })),
766 enabled: params.editFlags.canPaste,
767 },
768 {
769 role: "selectAll",
770 label: m(msg("Select All", { $context: "Edit menu item" })),
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 }),
781 );
782 });
783 contents.on("did-create-window", (popup) => {
784 installContextMenu(popup, popup.webContents, isBrowserContents);
785 });
786 };
787 installContextMenu(window, window.webContents);
788 window.webContents.on("did-attach-webview", (_event, contents) => {
789 installContextMenu(window, contents, true);
790 void runPromise(previewManager.prepareWebview(contents));
791 });
792​
793 // Popups from every frame in this window arrive here without a caller, so only web links
794 // pass. The app opens editors and other applications over IPC.
795 window.webContents.setWindowOpenHandler(({ url }) => {
796 if (Option.isSome(ElectronShell.parseWebExternalUrl(url))) {
797 void runPromise(electronShell.openExternal(url));
798 }
799 return { action: "deny" };
800 });
801 // Chromium asks this before handing a navigation to an OS protocol handler, and grants it
802 // when nothing answers. External links are opened through ElectronShell only.
803 window.webContents.session.setPermissionRequestHandler((_contents, permission, callback) =>
804 callback(permission !== "openExternal"),
805 );
806 // macOS's native checker follows the system languages; elsewhere Chromium keeps en-US.
807 if (environment.platform !== "darwin") {
808 const session = window.webContents.session;
809 const spellCheckerLanguages = resolveSpellCheckerLanguages(
810 session.getSpellCheckerLanguages(),
811 yield* electronApp.preferredSystemLanguages,
812 session.availableSpellCheckerLanguages,
813 );
814 if (spellCheckerLanguages) session.setSpellCheckerLanguages(spellCheckerLanguages);
815 }
816 window.webContents.on("will-navigate", (event, url) => {
817 if (
818 isSameOriginRendererNavigation({
819 applicationUrl,
820 navigationUrl: url,
821 })
822 ) {
823 return;
824 }
825​
826 event.preventDefault();
827 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
828 void runPromise(electronShell.openExternal(url));
829 }
830 });
831​
832 const quitShortcutHandler = makeQuitShortcutHandler({
833 platform: environment.platform,
834 getMode: () =>
835 runPromise(
836 Effect.map(
837 clientSettings.get,
838 Option.match({
839 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
840 onSome: (settings) => settings.confirmQuit,
841 }),
842 ),
843 ),
844 notify: (hint) => {
845 if (!window.isDestroyed()) {
846 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
847 }
848 },
849 // Hold focus until shortcut release so remaining repeats cannot reach the next app.
850 concealWindow: () => concealPendingQuitWindow(window),
851 quit: () => {
852 void runPromise(electronApp.quit);
853 },
854 });
855 window.webContents.on("before-input-event", (event, input) => {
856 quitShortcutHandler(event, input);
857 if (window.isDestroyed()) return;
858 // Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut.
859 window.webContents.setIgnoreMenuShortcuts(
860 (environment.platform === "darwin" ? input.meta : input.control) &&
861 !input.alt &&
862 !input.shift &&
863 input.key.toLowerCase() === "w",
864 );
865 // A held Cmd/Ctrl+W closes one tab or terminal, not each one behind it.
866 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
867 const modifier = environment.platform === "darwin" ? input.meta : input.control;
868 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
869 event.preventDefault();
870 }
871 });
872 window.webContents.on("input-event", (_event, input) => {
873 if (window.isDestroyed()) return;
874 if (input.type === "gestureScrollBegin") {
875 window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL);
876 } else if (input.type === "gestureScrollEnd") {
877 window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
878 }
879 });
880 // Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event.
881 window.webContents.on("zoom-changed", (_event, direction) => {
882 if (window.isDestroyed()) return;
883 runFork(zoomWindow(window, direction));
884 });
885​
886 // The renderer titles the window after the open thread; only a blank title
887 // falls back to the app name.
888 window.on("page-title-updated", (event, title) => {
889 if (title.trim() !== "") return;
890 event.preventDefault();
891 window.setTitle(environment.displayName);
892 });
893 window.on("resize", scheduleBoundsPersist);
894 window.on("move", scheduleBoundsPersist);
895 window.on("maximize", scheduleBoundsPersist);
896 window.on("unmaximize", scheduleBoundsPersist);
897 window.on("close", () => {
898 runFork(flushBoundsPersist);
899 });
900​
901 if (environment.platform === "darwin") {
902 // Mouse drivers can deliver Back/Forward as macOS swipe gestures instead of buttons.
903 window.on("swipe", (_event, direction) => {
904 const history = window.webContents.navigationHistory;
905 if (direction === "left" && history.canGoBack()) history.goBack();
906 else if (direction === "right" && history.canGoForward()) history.goForward();
907 });
908 window.on("enter-full-screen", () => {
909 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
910 });
911 window.on("leave-full-screen", () => {
912 syncMacosWindowButtons(window);
913 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
914 });
915 }
916​
917 let developmentLoadRetryIndex = 0;
918 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
919 let rendererRecoveryTimestamps: number[] = [];
920 const clearDevelopmentLoadRetry = () => {
921 if (developmentLoadRetryFiber === undefined) {
922 return;
923 }
924 const retryFiber = developmentLoadRetryFiber;
925 developmentLoadRetryFiber = undefined;
926 runFork(Fiber.interrupt(retryFiber));
927 };
928 const loadApplication = () => {
929 if (window.isDestroyed()) {
930 return;
931 }
932 void window.loadURL(applicationUrl).catch(() => undefined);
933 };
934 const scheduleDevelopmentLoadRetry = () => {
935 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
936 return undefined;
937 }
938​
939 const retryIndex = Math.min(
940 developmentLoadRetryIndex,
941 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
942 );
943 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
944 developmentLoadRetryIndex += 1;
945 developmentLoadRetryFiber = runFork(
946 Effect.sleep(retryInMs).pipe(
947 Effect.andThen(
948 Effect.sync(() => {
949 developmentLoadRetryFiber = undefined;
950 if (!window.isDestroyed()) {
951 loadApplication();
952 }
953 }),
954 ),
955 ),
956 );
957 return retryInMs;
958 };
959​
960 window.webContents.on("did-finish-load", () => {
961 if (
962 environment.isDevelopment &&
963 !isSameOriginRendererNavigation({
964 applicationUrl,
965 navigationUrl: window.webContents.getURL(),
966 })
967 ) {
968 return;
969 }
970 clearDevelopmentLoadRetry();
971 developmentLoadRetryIndex = 0;
972 if (environment.platform === "darwin") syncMacosWindowButtons(window);
973 });
974 window.webContents.on(
975 "did-fail-load",
976 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
977 if (!isMainFrame) {
978 return;
979 }
980 const retryInMs =
981 environment.isDevelopment &&
982 isRetryableDevelopmentRendererLoadFailure({
983 applicationUrl,
984 errorCode,
985 isMainFrame,
986 validatedUrl: validatedURL,
987 })
988 ? scheduleDevelopmentLoadRetry()
989 : undefined;
990 void runPromise(
991 logWindowWarning("main window failed to load", {
992 errorCode,
993 errorDescription,
994 url: validatedURL,
995 ...(retryInMs === undefined ? {} : { retryInMs }),
996 }),
997 );
998 },
999 );
1000 window.webContents.on("render-process-gone", (_event, details) => {
1001 const recoverable =
1002 details.reason === "crashed" ||
1003 details.reason === "oom" ||
1004 details.reason === "killed" ||
1005 details.reason === "abnormal-exit";
1006​
1007 runFork(
1008 Effect.gen(function* () {
1009 const now = yield* Clock.currentTimeMillis;
1010 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
1011 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
1012 );
1013 const shouldRecover = recoverable && !window.isDestroyed();
1014 // Past the budget, wait for the oldest attempt to leave the window instead of
1015 // giving up, so a crash loop backs off but never leaves the window blank.
1016 const oldestAttempt =
1017 rendererRecoveryTimestamps.length >= RENDERER_RECOVERY_MAX_ATTEMPTS
1018 ? rendererRecoveryTimestamps[
1019 rendererRecoveryTimestamps.length - RENDERER_RECOVERY_MAX_ATTEMPTS
1021 : undefined;
1022 const reloadInMs =
1023 oldestAttempt === undefined
1024 ? RENDERER_RECOVERY_RELOAD_DELAY_MS
1025 : Math.max(
1026 RENDERER_RECOVERY_RELOAD_DELAY_MS,
1027 oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now,
1028 );
1029 yield* logWindowWarning("main window render process gone", {
1030 reason: details.reason,
1031 exitCode: details.exitCode,
1032 recovering: shouldRecover,
1033 ...(shouldRecover ? { reloadInMs } : {}),
1034 });
1035 if (!shouldRecover) {
1036 return;
1038 rendererRecoveryTimestamps.push(now + reloadInMs);
1039 yield* Effect.sleep(reloadInMs);
1040 if (!window.isDestroyed()) {
1041 loadApplication();
1043 }),
1044 );
1045 });
1046​
1047 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
1048 if (environment.platform === "linux") {
1049 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
1051 let rendererReady = false;
1052 let firstRevealComplete = false;
1053 const revealWhenReady = Effect.gen(function* () {
1054 if (
1055 !rendererReady ||
1056 firstRevealComplete ||
1057 window.isDestroyed() ||
1058 (yield* Ref.get(desktopState.quitting))
1060 return;
1061 firstRevealComplete = true;
1062 pendingMainReveals.delete(window);
1063 window.webContents.setBackgroundThrottling(true);
1064 if (persistedSettings.mainWindowMaximized) window.maximize();
1065 yield* electronWindow.reveal(window);
1066 yield* dismissConnectingSplash;
1067 });
1068 pendingMainReveals.set(window, revealWhenReady);
1069 bindFirstRevealTrigger(revealSubscribers, () => {
1070 rendererReady = true;
1071 void runPromise(revealWhenReady);
1072 });
1073​
1074 // Desktop IPC only answers the main window, so register it before its renderer can call in.
1075 yield* electronWindow.setMain(window);
1076 remoteRequestHeaderOwner = window;
1077 const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy(
1078 window.webContents.session,
1080 desktopOrigin: getDesktopOrigin(environment.isDevelopment),
1081 mainWebContentsId: window.webContents.id,
1082 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
1083 devServerOrigin: Option.getOrUndefined(
1084 Option.map(environment.devServerUrl, (url) => url.origin),
1085 ),
1086 isDevelopment: environment.isDevelopment,
1087 },
1088 );
1089 loadApplication();
1090 if (environment.isDevelopment) {
1091 window.webContents.openDevTools({ mode: "detach" });
1093​
1094 window.on("closed", () => {
1095 if (!backendHasStarted) mainClosedDuringStartup = true;
1096 clearDevelopmentLoadRetry();
1097 clearBoundsPersist();
1098 if (remoteRequestHeaderOwner === window) {
1099 remoteRequestHeaderOwner = null;
1100 detachRemoteRequestHeaders();
1102 void runPromise(electronWindow.clearMain(Option.some(window)));
1103 });
1104​
1105 return Option.some(window);
1106 });
1107​
1108 const createMain = Effect.gen(function* () {
1109 const window = yield* createWindow();
1110 if (Option.isSome(window)) {
1111 mainClosedDuringStartup = false;
1112 yield* logWindowInfo("main window created");
1114 return window;
1115 }).pipe(Effect.withSpan("desktop.window.createMain"));
1116​
1117 const ensureMain = Effect.gen(function* () {
1118 if (yield* Ref.get(desktopState.quitting)) return Option.none<Electron.BrowserWindow>();
1119 const existingWindow = yield* electronWindow.main;
1120 if (Option.isSome(existingWindow)) {
1121 return existingWindow;
1123 return yield* createMain;
1124 }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain"));
1125​
1126 const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
1127 Option.match(window, {
1128 onNone: () => Effect.interrupt,
1129 onSome: Effect.succeed,
1130 });
1131​
1132 const revealOrCreateMain = Effect.gen(function* () {
1133 const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
1134 yield* revealMain(window);
1135 return window;
1136 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
1137​
1138 const waitingForBackend = Effect.gen(function* () {
1139 if (yield* Ref.get(backendReadyRef)) return false;
1140 return (yield* desktopSettings.get).localEnvironmentEnabled;
1141 });
1142​
1143 const createMainIfBackendReady = Effect.gen(function* () {
1144 if (yield* Ref.get(desktopState.quitting)) return;
1145 if (yield* waitingForBackend) return;
1146 yield* ensureMain;
1147 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
1148​
1149 const showConnectingSplash = Effect.gen(function* () {
1150 if (yield* Ref.get(desktopState.quitting)) return;
1151 const existingSplash = yield* Ref.get(splashWindowRef);
1152 if (Option.isSome(existingSplash)) return;
1153 const existingWindow = yield* electronWindow.currentMainOrFirst;
1154 if (Option.isSome(existingWindow)) return;
1155​
1156 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1157 if (yield* Ref.get(desktopState.quitting)) return;
1158 const splash = yield* electronWindow.create({
1159 width: 360,
1160 height: 220,
1161 resizable: false,
1162 minimizable: false,
1163 maximizable: false,
1164 fullscreenable: false,
1165 frame: false,
1166 center: true,
1167 show: false,
1168 skipTaskbar: false,
1169 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
1170 title: environment.displayName,
1171 webPreferences: {
1172 contextIsolation: true,
1173 nodeIntegration: false,
1174 sandbox: true,
1175 },
1176 });
1177 if (yield* Ref.get(desktopState.quitting)) {
1178 yield* electronWindow.destroyAll;
1179 return;
1181 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
1182 yield* Ref.set(splashWindowRef, Option.some(splash));
1183 let renderedUrl: string | undefined;
1184 const progressFiber = runFork(
1185 Effect.gen(function* () {
1186 if (splash.isDestroyed() || (yield* Ref.get(desktopState.quitting))) return;
1187 const progress = yield* Ref.get(desktopState.databaseMigrationProgress);
1188 const url = buildConnectingSplashDataUrl(shouldUseDarkColors, progress);
1189 if (url === renderedUrl) return;
1190 const loaded = yield* Effect.promise(() =>
1191 splash.loadURL(url).then(
1192 () => true,
1193 () => false,
1194 ),
1195 );
1196 if (loaded) renderedUrl = url;
1197 }).pipe(Effect.repeat(Schedule.spaced("1 second"))),
1198 );
1199 splash.once("closed", () => {
1200 runFork(
1201 Fiber.interrupt(progressFiber).pipe(
1202 Effect.andThen(Ref.set(splashWindowRef, Option.none())),
1203 ),
1204 );
1205 });
1206 splash.once("ready-to-show", () => {
1207 if (!splash.isDestroyed()) {
1208 splash.show();
1210 });
1211 yield* logWindowInfo("connecting splash shown");
1212 }).pipe(
1213 Effect.catch((error) =>
1214 logWindowWarning("failed to show connecting splash", { message: error.message }),
1215 ),
1216 Effect.withSpan("desktop.window.showConnectingSplash"),
1217 );
1218​
1219 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
1220 channel: string,
1221 payload: unknown,
1222 { reveal = true }: { readonly reveal?: boolean } = {},
1223 ) {
1224 if (yield* Ref.get(desktopState.quitting)) return;
1225 // Only the main renderer loads the app preload that listens on these channels.
1226 const existingWindow = yield* electronWindow.main;
1227 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
1228 const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
1229 if (Option.isNone(window) || window.value.isDestroyed()) return;
1230 const targetWindow = window.value;
1231 const send = Effect.sync(() => {
1232 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
1233 });
1234 // Send before best-effort reveal; another process may refuse to yield foreground focus.
1235 const dispatch = reveal
1236 ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause)))
1237 : send;
1238 if (targetWindow.webContents.isLoadingMainFrame()) {
1239 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
1240 return;
1242 yield* dispatch;
1243 });
1244​
1245 return DesktopWindow.of({
1246 createMain: createMain.pipe(Effect.flatMap(requireWindow)),
1247 ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)),
1248 revealOrCreateMain,
1249 prepareCaptureReveal: Effect.gen(function* () {
1250 const existingWindow = yield* currentMainWindow;
1251 if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) {
1252 yield* electronWindow.prepareReveal(existingWindow.value);
1254 }),
1255 activate: Effect.gen(function* () {
1256 if (yield* Ref.get(desktopState.quitting)) return;
1257 const existingWindow = yield* currentMainWindow;
1258 if (Option.isSome(existingWindow)) {
1259 yield* revealMain(existingWindow.value);
1260 return;
1262 if (mainClosedDuringStartup) {
1263 yield* ensureMain;
1264 return;
1266 const backendReady = yield* Ref.get(backendReadyRef);
1267 if (!backendReady) {
1268 const splash = yield* Ref.get(splashWindowRef);
1269 if (Option.isSome(splash)) {
1270 yield* electronWindow.reveal(splash.value);
1271 return;
1274 yield* createMainIfBackendReady;
1275 }).pipe(Effect.withSpan("desktop.window.activate")),
1276 createMainIfBackendReady,
1277 showConnectingSplash,
1278 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1279 backendHasStarted = true;
1280 yield* Ref.set(backendReadyRef, true);
1281 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1282 if (!mainClosedDuringStartup) yield* createMainIfBackendReady;
1283 }),
1284 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1285 Effect.withSpan("desktop.window.handleBackendNotReady"),
1286 ),
1287 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
1288 Effect.withSpan("desktop.window.flushMainWindowBounds"),
1289 ),
1290 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
1291 yield* Effect.annotateCurrentSpan({ action });
1292 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
1293 }),
1294 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
1295 yield* Effect.annotateCurrentSpan({
1296 event: event.type,
1297 captureId: "id" in event ? (event.id ?? null) : null,
1298 });
1299 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
1300 reveal: event.type === "started",
1301 });
1302 }),
1303 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
1304 yield* Effect.annotateCurrentSpan({ direction });
1305 const window = yield* electronWindow.main;
1306 if (Option.isNone(window) || window.value.isDestroyed()) {
1307 return;
1309 yield* zoomWindow(window.value, direction);
1310 }),
1311 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1312 yield* Effect.annotateCurrentSpan({ command });
1313 // A focused OAuth popup must not receive the app's Reload command.
1314 const window = yield* electronWindow.main;
1315 if (Option.isNone(window) || window.value.isDestroyed()) return;
1316 const webContents = window.value.webContents;
1317 if (command === "reload") webContents.reload();
1318 else if (command === "forceReload") webContents.reloadIgnoringCache();
1319 else webContents.toggleDevTools();
1320 }),
1321 syncAppearance: Effect.gen(function* () {
1322 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1323 yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) =>
1324 syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform),
1325 );
1326 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1327 });
1328});
1329​
1330export const layer = Layer.effect(DesktopWindow, make);