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