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

DesktopWindow.ts

1,316 lines49.1 KB

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