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