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