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