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

DesktopWindow.ts

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