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

DesktopWindow.ts

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