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

DesktopWindow.ts

1,129 lines42.2 KB

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