Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Ref from "effect/Ref";
8
9import * as Electron from "electron";
10
11import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
12
13import * as DesktopAssets from "../app/DesktopAssets.ts";
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15import { makeComponentLogger } from "../app/DesktopObservability.ts";
16import * as ElectronMenu from "../electron/ElectronMenu.ts";
17import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
18import * as ElectronShell from "../electron/ElectronShell.ts";
19import * as ElectronTheme from "../electron/ElectronTheme.ts";
20import * as ElectronWindow from "../electron/ElectronWindow.ts";
21import {
22 MENU_ACTION_CHANNEL,
23 QUIT_SHORTCUT_CHANNEL,
24 SNAP_SHOT_EVENT_CHANNEL,
25 TRACKPAD_SCROLL_END_CHANNEL,
26 WINDOW_FULLSCREEN_STATE_CHANNEL,
27} from "../ipc/channels.ts";
28import { PASSKEY_BRIDGE_ARGUMENT } from "../preview/GuestProtocol.ts";
29import * as PreviewManager from "../preview/Manager.ts";
30import * as PreviewPasskeys from "../preview/Passkeys.ts";
31import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
32import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
33import * as ElectronApp from "../electron/ElectronApp.ts";
34import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
35import { makeQuitShortcutHandler } from "./QuitHold.ts";
36
37const TITLEBAR_HEIGHT = 40;
38// Matches --workspace-topbar-height in apps/web/src/index.css. Native macOS
39// buttons are 14 points tall and do not scale with the renderer's zoom.
40const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
41const MACOS_WINDOW_BUTTON_RADIUS = 7;
42
43function syncMacosWindowButtons(window: Electron.BrowserWindow): void {
44 if (window.isDestroyed() || window.isFullScreen()) return;
45 window.setWindowButtonPosition({
46 x: 16,
47 y: Math.round(
48 (MACOS_WORKSPACE_TOPBAR_HEIGHT * window.webContents.getZoomFactor()) / 2 -
49 MACOS_WINDOW_BUTTON_RADIUS,
50 ),
51 });
52}
53
54const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
55const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
56const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
57const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
58const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
59// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
60// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
61// that dies on boot cannot reload-loop forever.
62const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
63const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
64const RENDERER_RECOVERY_WINDOW_MS = 60_000;
65const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
66 -2, // ERR_FAILED
67 -7, // ERR_TIMED_OUT
68 -9, // ERR_UNEXPECTED (custom protocol handler rejected)
69 -102, // ERR_CONNECTION_REFUSED
70 -105, // ERR_NAME_NOT_RESOLVED
71 -106, // ERR_INTERNET_DISCONNECTED
72 -118, // ERR_CONNECTION_TIMED_OUT
73]);
74
75type WindowTitleBarOptions = Pick<
76 Electron.BrowserWindowConstructorOptions,
77 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
78>;
79
80type DesktopWindowRuntimeServices =
81 | DesktopEnvironment.DesktopEnvironment
82 | DesktopAssets.DesktopAssets
83 | DesktopAppSettings.DesktopAppSettings
84 | DesktopClientSettings.DesktopClientSettings
85 | ElectronApp.ElectronApp
86 | ElectronMenu.ElectronMenu
87 | ElectronShell.ElectronShell
88 | ElectronTheme.ElectronTheme
89 | ElectronWindow.ElectronWindow
90 | DesktopRendererHistory.DesktopRendererHistory
91 | PreviewManager.PreviewManager;
92
93export type DesktopWindowError =
94 | ElectronWindow.ElectronWindowCreateError
95 | PreviewManager.PreviewManagerError;
96
97export type MainWindowZoomDirection = "in" | "out" | "reset";
98export type MainWindowContentsCommand = "reload" | "forceReload" | "toggleDevTools";
99
100export class DesktopWindow extends Context.Service<
101 DesktopWindow,
102 {
103 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
104 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
105 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
106 readonly activate: Effect.Effect<void, DesktopWindowError>;
107 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
108 // Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
109 // mode), before the WSL backend that acts as the primary is ready. It is
110 // dismissed automatically once the real main window reveals.
111 readonly showConnectingSplash: Effect.Effect<void>;
112 // Marks the primary backend as ready so `createMainIfBackendReady` and the
113 // macOS "activate without windows" path may open the real main window. The
114 // renderer now always loads the local client URL (getDesktopUrl) and connects
115 // to the backend through the connection layer, so the reported httpBaseUrl is
116 // no longer used to point the window at the backend — it is kept only for the
117 // readiness log and to preserve the callback contract the backend pool drives.
118 readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
119 // Called when the backend transitions back to "not ready" (clean stop,
120 // restart, crash). Clears the latch that lets `activate` auto-create a
121 // window so a "macOS dock click" while the backend is down doesn't
122 // produce a stranded window pointing at nothing.
123 readonly handleBackendNotReady: Effect.Effect<void>;
124 readonly flushMainWindowBounds: Effect.Effect<void>;
125 readonly prepareCaptureReveal: Effect.Effect<void>;
126 readonly dispatchMenuAction: (
127 action: string,
128 options?: { readonly reveal?: boolean },
129 ) => Effect.Effect<void, DesktopWindowError>;
130 /**
131 * Push a capture lifecycle event to the renderer. Only `started` reveals the
132 * window; the rest must not interrupt the app the user has switched to.
133 */
134 readonly dispatchSnapShotEvent: (
135 event: DesktopSnapShotEvent,
136 ) => Effect.Effect<void, DesktopWindowError>;
137 // Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
138 // menu roles act on whichever webContents has keyboard focus, so with an
139 // embedded preview WebContentsView (or DevTools) focused they zoom the
140 // guest page instead of the app UI. The menu routes here to always target
141 // the main window.
142 readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
143 // Reload and DevTools for the main window's own webContents, for the same
144 // reason as zoomMain: the Electron roles act on the focused webContents,
145 // which is a preview guest whenever a browser page has focus.
146 readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect<void>;
147 readonly syncAppearance: Effect.Effect<void>;
148 }
149>()("@t3tools/desktop/window/DesktopWindow") {}
150
151const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
152 makeComponentLogger("desktop-window");
153
154function getIconOption(
155 iconPaths: DesktopAssets.DesktopIconPaths,
156 platform: NodeJS.Platform,
157): { icon: string } | Record<string, never> {
158 if (platform === "darwin") return {}; // macOS uses .icns from app bundle
159 const ext = platform === "win32" ? "ico" : "png";
160 return Option.match(iconPaths[ext], {
161 onNone: () => ({}),
162 onSome: (icon) => ({ icon }),
163 });
164}
165
166function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
167 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
168}
169
170type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
171
172function windowFitsWithinDisplay(
173 windowBounds: DesktopAppSettings.DesktopWindowBounds,
174 displayBounds: DisplayBounds,
175): boolean {
176 return (
177 windowBounds.x >= displayBounds.x &&
178 windowBounds.y >= displayBounds.y &&
179 windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
180 windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
181 );
182}
183
184function windowBoundsEqual(
185 left: DesktopAppSettings.DesktopWindowBounds,
186 right: DesktopAppSettings.DesktopWindowBounds,
187): boolean {
188 return (
189 left.x === right.x &&
190 left.y === right.y &&
191 left.width === right.width &&
192 left.height === right.height
193 );
194}
195
196export function resolveInitialMainWindowBounds(
197 persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
198 displays: readonly DisplayBounds[],
199): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
200 if (
201 persistedBounds !== null &&
202 displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
203 ) {
204 return persistedBounds;
205 }
206 return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
207}
208
209// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
210// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
211// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
212function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
213 const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
214 const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
215 const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
216 const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
217 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>`;
218 return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
219}
220
221export function isSameOriginRendererNavigation(input: {
222 readonly applicationUrl: string;
223 readonly navigationUrl: string;
224}): boolean {
225 try {
226 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
227 } catch {
228 return false;
229 }
230}
231
232export function isRetryableDevelopmentRendererLoadFailure(input: {
233 readonly applicationUrl: string;
234 readonly errorCode: number;
235 readonly isMainFrame: boolean;
236 readonly validatedUrl: string;
237}): boolean {
238 return (
239 input.isMainFrame &&
240 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
241 isSameOriginRendererNavigation({
242 applicationUrl: input.applicationUrl,
243 navigationUrl: input.validatedUrl,
244 })
245 );
246}
247
248export function concealPendingQuitWindow(
249 window: Pick<
250 Electron.BrowserWindow,
251 "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
252 >,
253): void {
254 if (window.isDestroyed()) return;
255 if (window.isFullScreen()) {
256 window.setFullScreen(false);
257 }
258 // Electron implements window opacity on macOS and Windows. Linux keeps the
259 // release-gated quit behavior but cannot make the pending window disappear.
260 window.setOpacity(0);
261}
262
263function getWindowTitleBarOptions(
264 shouldUseDarkColors: boolean,
265 platform: NodeJS.Platform,
266): WindowTitleBarOptions {
267 if (platform === "darwin") {
268 return {
269 titleBarStyle: "hiddenInset",
270 trafficLightPosition: {
271 x: 16,
272 y: MACOS_WORKSPACE_TOPBAR_HEIGHT / 2 - MACOS_WINDOW_BUTTON_RADIUS,
273 },
274 };
275 }
276
277 return {
278 titleBarStyle: "hidden",
279 titleBarOverlay: {
280 color: TITLEBAR_COLOR,
281 height: TITLEBAR_HEIGHT,
282 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
283 },
284 };
285}
286
287function syncWindowAppearance(
288 window: Electron.BrowserWindow,
289 shouldUseDarkColors: boolean,
290 platform: NodeJS.Platform,
291): Effect.Effect<void> {
292 return Effect.sync(() => {
293 if (window.isDestroyed()) {
294 return;
295 }
296
297 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
298 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
299 if (typeof titleBarOverlay === "object") {
300 window.setTitleBarOverlay(titleBarOverlay);
301 }
302 });
303}
304
305type RevealSubscription = (listener: () => void) => void;
306
307function bindFirstRevealTrigger(
308 subscribers: readonly RevealSubscription[],
309 reveal: () => void,
310): void {
311 let revealed = false;
312 const fire = () => {
313 if (revealed) return;
314 revealed = true;
315 reveal();
316 };
317 for (const subscribe of subscribers) {
318 subscribe(fire);
319 }
320}
321
322/** @public Service construction is part of the canonical Effect module API. */
323export const make = Effect.gen(function* () {
324 const environment = yield* DesktopEnvironment.DesktopEnvironment;
325 const assets = yield* DesktopAssets.DesktopAssets;
326 const electronMenu = yield* ElectronMenu.ElectronMenu;
327 const electronShell = yield* ElectronShell.ElectronShell;
328 const electronTheme = yield* ElectronTheme.ElectronTheme;
329 const electronWindow = yield* ElectronWindow.ElectronWindow;
330 const previewManager = yield* PreviewManager.PreviewManager;
331 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
332 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
333 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
334 const electronApp = yield* ElectronApp.ElectronApp;
335 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
336 // Window-side latch for the primary backend's readiness. Set by
337 // handleBackendReady (driven by the pool's onReady callback), cleared
338 // by handleBackendNotReady (driven by onShutdown). Only consumed by
339 // createMainIfBackendReady, which gates the post-readiness window
340 // open in development and the macOS "activate without windows" path.
341 const backendReadyRef = yield* Ref.make(false);
342 // The transient "Connecting to WSL" splash window, tracked separately so it
343 // is never mistaken for the real main window.
344 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
345 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
346 const runFork = Effect.runForkWith(context);
347 const runPromise = Effect.runPromiseWith(context);
348 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
349
350 const dismissConnectingSplash = Effect.gen(function* () {
351 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
352 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
353 splash.value.close();
354 }
355 });
356
357 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
358 // which during WSL-only boot is the connecting splash. The splash is never
359 // registered via setMain, so it must be treated as "no real main window" --
360 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
361 // open (or retry) the real main. That is the failure the pool's swallowed
362 // post-readiness window-open error would otherwise strand the user in:
363 // splash up, backend ready, no main, and activation only re-reveals splash.
364 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
365 Ref.get(splashWindowRef).pipe(
366 Effect.map((splash) =>
367 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
368 ? Option.none<Electron.BrowserWindow>()
369 : window,
370 ),
371 );
372
373 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
374 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
375
376 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
377 Electron.BrowserWindow,
378 DesktopWindowError
379 > {
380 yield* previewManager.getBrowserSession();
381 const applicationUrl = getDesktopUrl(environment.isDevelopment);
382 const iconPaths = yield* assets.iconPaths;
383 const iconOption = getIconOption(iconPaths, environment.platform);
384 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
385 const persistedSettings = yield* desktopSettings.get;
386 const persistedBounds = persistedSettings.mainWindowBounds;
387 const displayBoundsResult = yield* Effect.sync(() => {
388 try {
389 return {
390 _tag: "Success" as const,
391 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
392 };
393 } catch (cause) {
394 return { _tag: "Failure" as const, cause };
395 }
396 });
397 const displayBounds =
398 displayBoundsResult._tag === "Success"
399 ? displayBoundsResult.bounds
400 : yield* logWindowWarning("failed to read connected displays; using defaults", {
401 cause: displayBoundsResult.cause,
402 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
403 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
404 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
405 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
406 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
407 }
408 const window = yield* electronWindow.create({
409 ...initialBounds,
410 minWidth: 840,
411 minHeight: 620,
412 show: false,
413 autoHideMenuBar: true,
414 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
415 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
416 ...iconOption,
417 title: environment.displayName,
418 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
419 webPreferences: {
420 preload: environment.preloadPath,
421 // The window boots hidden (show: false until ready-to-show), and
422 // Chromium throttles hidden renderers: timers coalesce and rAF stops,
423 // which stalls first paint. Boot unthrottled; the first-reveal trigger
424 // re-enables throttling so a hidden or minimized window goes back to
425 // being cheap after it has been shown once.
426 backgroundThrottling: false,
427 contextIsolation: true,
428 nodeIntegration: false,
429 sandbox: true,
430 webviewTag: true,
431 // A preview guest's fullscreen request is mirrored onto this embedder,
432 // which would otherwise put the whole window into OS fullscreen. With
433 // both sides opted out the page fills its webview and the window stays.
434 disableHtmlFullscreenWindowResize: true,
435 },
436 });
437
438 yield* rendererHistory.register(window.webContents, { surface: "main" });
439 if (environment.platform === "darwin") {
440 window.setAutoHideCursor(false);
441 }
442 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
443 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
444 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
445 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
446 if (window.isDestroyed()) {
447 return null;
448 }
449 const bounds =
450 window.isFullScreen() || window.isMaximized() || window.isMinimized()
451 ? window.getNormalBounds()
452 : window.getBounds();
453 return DesktopAppSettings.normalizeMainWindowBounds({
454 x: Math.round(bounds.x),
455 y: Math.round(bounds.y),
456 width: Math.round(bounds.width),
457 height: Math.round(bounds.height),
458 });
459 };
460 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
461 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
462 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
463 if (!boundsPersistenceEnabled) {
464 return pendingBoundsPersistFiber;
465 }
466 const bounds = readPersistableBounds();
467 if (bounds === null) {
468 return pendingBoundsPersistFiber;
469 }
470 pendingBoundsPersistFiber = runFork(
471 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
472 Effect.asVoid,
473 Effect.catch((error) =>
474 logWindowWarning("failed to persist main window bounds", {
475 message: error.message,
476 }),
477 ),
478 ),
479 );
480 return pendingBoundsPersistFiber;
481 };
482 const scheduleBoundsPersist = () => {
483 if (!boundsPersistenceEnabled) {
484 const currentBounds = readPersistableBounds();
485 if (
486 currentBounds === null ||
487 (fallbackWindowBounds !== null &&
488 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
489 window.isMaximized() === fallbackWindowMaximized)
490 ) {
491 return;
492 }
493 }
494 boundsPersistenceEnabled = true;
495 if (boundsPersistFiber !== undefined) {
496 const fiber = boundsPersistFiber;
497 boundsPersistFiber = undefined;
498 runFork(Fiber.interrupt(fiber));
499 }
500 boundsPersistFiber = runFork(
501 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
502 Effect.andThen(
503 Effect.sync(() => {
504 boundsPersistFiber = undefined;
505 void persistCurrentBounds();
506 }),
507 ),
508 ),
509 );
510 };
511 const clearBoundsPersist = () => {
512 if (boundsPersistFiber === undefined) {
513 return;
514 }
515 const fiber = boundsPersistFiber;
516 boundsPersistFiber = undefined;
517 runFork(Fiber.interrupt(fiber));
518 };
519 const flushBoundsPersist = Effect.sync(() => {
520 clearBoundsPersist();
521 return persistCurrentBounds();
522 }).pipe(
523 Effect.flatMap((fiber) =>
524 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
525 ),
526 );
527 flushMainWindowBounds = flushBoundsPersist;
528
529 yield* previewManager.setMainWindow(window);
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 // Native editing roles act on the focused contents, which may still be
562 // the host renderer when the user right-clicks inside a browser guest.
563 contents.focus();
564
565 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
566
567 if (params.misspelledWord) {
568 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
569 menuTemplate.push({
570 label: suggestion,
571 click: () => {
572 if (!contents.isDestroyed()) contents.replaceMisspelling(suggestion);
573 },
574 });
575 }
576 if (params.dictionarySuggestions.length === 0) {
577 menuTemplate.push({ label: "No suggestions", enabled: false });
578 }
579 menuTemplate.push({ type: "separator" });
580 }
581
582 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
583 menuTemplate.push(
584 {
585 label: "Copy Link",
586 click: () => {
587 void runPromise(electronShell.copyText(params.linkURL));
588 },
589 },
590 { type: "separator" },
591 );
592 }
593
594 if (params.mediaType === "image") {
595 menuTemplate.push({
596 label: "Copy Image",
597 click: () => {
598 if (!contents.isDestroyed()) contents.copyImageAt(params.x, params.y);
599 },
600 });
601 menuTemplate.push({ type: "separator" });
602 }
603
604 menuTemplate.push(
605 { role: "cut", enabled: params.editFlags.canCut },
606 { role: "copy", enabled: params.editFlags.canCopy },
607 { role: "paste", enabled: params.editFlags.canPaste },
608 { role: "selectAll", enabled: params.editFlags.canSelectAll },
609 );
610
611 void runPromise(
612 electronMenu.popupTemplate({
613 window: ownerWindow,
614 template: menuTemplate,
615 ...(params.frame ? { frame: params.frame } : {}),
616 }),
617 );
618 });
619 contents.on("did-create-window", (popup) => {
620 installContextMenu(popup, popup.webContents);
621 });
622 };
623 installContextMenu(window, window.webContents);
624 window.webContents.on("did-attach-webview", (_event, contents) => {
625 installContextMenu(window, contents);
626 void runPromise(previewManager.prepareWebview(contents));
627 });
628
629 window.webContents.setWindowOpenHandler(({ url }) => {
630 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
631 void runPromise(electronShell.openExternal(url));
632 }
633 return { action: "deny" };
634 });
635 window.webContents.on("will-navigate", (event, url) => {
636 if (
637 isSameOriginRendererNavigation({
638 applicationUrl,
639 navigationUrl: url,
640 })
641 ) {
642 return;
643 }
644
645 event.preventDefault();
646 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
647 void runPromise(electronShell.openExternal(url));
648 }
649 });
650
651 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
652 // close-terminal shortcut can outlive the terminal that handled its first
653 // press, so reject repeats before they reach the native window accelerator.
654 // Deliberate presses still flow through the renderer or native menu.
655 // Intercept the quit accelerator before the native menu sees it and apply
656 // the configured direct, hold, or double-press behavior.
657 const quitShortcutHandler = makeQuitShortcutHandler({
658 platform: environment.platform,
659 getMode: () =>
660 runPromise(
661 Effect.map(
662 clientSettings.get,
663 Option.match({
664 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
665 onSome: (settings) => settings.confirmQuit,
666 }),
667 ),
668 ),
669 notify: (hint) => {
670 if (!window.isDestroyed()) {
671 window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
672 }
673 },
674 // Keep the transparent window focused until the physical shortcut is
675 // released so its remaining repeats cannot reach the next app.
676 concealWindow: () => concealPendingQuitWindow(window),
677 quit: () => {
678 void runPromise(electronApp.quit);
679 },
680 });
681 window.webContents.on("before-input-event", (event, input) => {
682 quitShortcutHandler(event, input);
683 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
684 const modifier = environment.platform === "darwin" ? input.meta : input.control;
685 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
686 event.preventDefault();
687 }
688 });
689 window.webContents.on("input-event", (_event, input) => {
690 if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
691 });
692
693 window.on("page-title-updated", (event) => {
694 event.preventDefault();
695 window.setTitle(environment.displayName);
696 });
697 window.on("resize", scheduleBoundsPersist);
698 window.on("move", scheduleBoundsPersist);
699 window.on("maximize", scheduleBoundsPersist);
700 window.on("unmaximize", scheduleBoundsPersist);
701 window.on("close", () => {
702 runFork(flushBoundsPersist);
703 });
704
705 if (environment.platform === "darwin") {
706 window.on("enter-full-screen", () => {
707 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
708 });
709 window.on("leave-full-screen", () => {
710 syncMacosWindowButtons(window);
711 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
712 });
713 }
714
715 let developmentLoadRetryIndex = 0;
716 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
717 let rendererRecoveryTimestamps: number[] = [];
718 const clearDevelopmentLoadRetry = () => {
719 if (developmentLoadRetryFiber === undefined) {
720 return;
721 }
722 const retryFiber = developmentLoadRetryFiber;
723 developmentLoadRetryFiber = undefined;
724 runFork(Fiber.interrupt(retryFiber));
725 };
726 const loadApplication = () => {
727 if (window.isDestroyed()) {
728 return;
729 }
730 void window.loadURL(applicationUrl).catch(() => undefined);
731 };
732 const scheduleDevelopmentLoadRetry = () => {
733 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
734 return undefined;
735 }
736
737 const retryIndex = Math.min(
738 developmentLoadRetryIndex,
739 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
740 );
741 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
742 developmentLoadRetryIndex += 1;
743 developmentLoadRetryFiber = runFork(
744 Effect.sleep(retryInMs).pipe(
745 Effect.andThen(
746 Effect.sync(() => {
747 developmentLoadRetryFiber = undefined;
748 if (!window.isDestroyed()) {
749 loadApplication();
750 }
751 }),
752 ),
753 ),
754 );
755 return retryInMs;
756 };
757
758 window.webContents.on("did-finish-load", () => {
759 if (
760 environment.isDevelopment &&
761 !isSameOriginRendererNavigation({
762 applicationUrl,
763 navigationUrl: window.webContents.getURL(),
764 })
765 ) {
766 return;
767 }
768 clearDevelopmentLoadRetry();
769 developmentLoadRetryIndex = 0;
770 window.setTitle(environment.displayName);
771 if (environment.platform === "darwin") syncMacosWindowButtons(window);
772 });
773 window.webContents.on(
774 "did-fail-load",
775 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
776 if (!isMainFrame) {
777 return;
778 }
779 const retryInMs =
780 environment.isDevelopment &&
781 isRetryableDevelopmentRendererLoadFailure({
782 applicationUrl,
783 errorCode,
784 isMainFrame,
785 validatedUrl: validatedURL,
786 })
787 ? scheduleDevelopmentLoadRetry()
788 : undefined;
789 void runPromise(
790 logWindowWarning("main window failed to load", {
791 errorCode,
792 errorDescription,
793 url: validatedURL,
794 ...(retryInMs === undefined ? {} : { retryInMs }),
795 }),
796 );
797 },
798 );
799 window.webContents.on("render-process-gone", (_event, details) => {
800 const recoverable =
801 details.reason === "crashed" ||
802 details.reason === "oom" ||
803 details.reason === "abnormal-exit";
804 // Long sessions can OOM the renderer (V8 heap exhaustion from
805 // accumulated thread state). Without a reload the user is left staring
806 // at a dead white window while agents keep running invisibly, so
807 // recover by reloading — the renderer rehydrates from the backend,
808 // which is unaffected. Recovery attempts are bounded so a renderer
809 // that dies immediately on boot cannot reload-loop forever.
810 runFork(
811 Effect.gen(function* () {
812 const now = yield* Clock.currentTimeMillis;
813 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
814 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
815 );
816 const shouldRecover =
817 recoverable &&
818 !window.isDestroyed() &&
819 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
820 yield* logWindowWarning("main window render process gone", {
821 reason: details.reason,
822 exitCode: details.exitCode,
823 recovering: shouldRecover,
824 });
825 if (!shouldRecover) {
826 return;
827 }
828 rendererRecoveryTimestamps.push(now);
829 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
830 if (!window.isDestroyed()) {
831 loadApplication();
832 }
833 }),
834 );
835 });
836
837 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
838 if (environment.platform === "linux") {
839 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
840 }
841 bindFirstRevealTrigger(revealSubscribers, () => {
842 // Boot is done; hand the window back to normal hidden-window throttling
843 // (see the backgroundThrottling comment on the create options above).
844 if (!window.isDestroyed()) {
845 window.webContents.setBackgroundThrottling(true);
846 }
847 // Reveal the real window, then close the connecting splash (if any) so the
848 // two don't overlap and there's no blank gap between them.
849 if (persistedSettings.mainWindowMaximized) {
850 window.maximize();
851 }
852 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
853 });
854
855 loadApplication();
856 if (environment.isDevelopment) {
857 window.webContents.openDevTools({ mode: "detach" });
858 }
859
860 window.on("closed", () => {
861 clearDevelopmentLoadRetry();
862 clearBoundsPersist();
863 void runPromise(electronWindow.clearMain(Option.some(window)));
864 });
865
866 return window;
867 });
868
869 const createMain = Effect.gen(function* () {
870 const window = yield* createWindow();
871 yield* electronWindow.setMain(window);
872 yield* logWindowInfo("main window created");
873 return window;
874 }).pipe(Effect.withSpan("desktop.window.createMain"));
875
876 const ensureMain = Effect.gen(function* () {
877 const existingWindow = yield* currentMainWindow;
878 if (Option.isSome(existingWindow)) {
879 return existingWindow.value;
880 }
881 return yield* createMain;
882 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
883
884 const revealOrCreateMain = Effect.gen(function* () {
885 const window = yield* ensureMain;
886 yield* electronWindow.reveal(window);
887 return window;
888 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
889
890 // With the local environment disabled there is no backend to wait for: the
891 // renderer is served from bundled assets and only talks to remote environments.
892 const waitingForBackend = Effect.gen(function* () {
893 if (yield* Ref.get(backendReadyRef)) return false;
894 return (yield* desktopSettings.get).localEnvironmentEnabled;
895 });
896
897 const createMainIfBackendReady = Effect.gen(function* () {
898 if (yield* waitingForBackend) return;
899 const existingWindow = yield* currentMainWindow;
900 if (Option.isSome(existingWindow)) return;
901 yield* createMain;
902 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
903
904 const showConnectingSplash = Effect.gen(function* () {
905 // Only when nothing is shown yet: no real window, no existing splash.
906 const existingSplash = yield* Ref.get(splashWindowRef);
907 if (Option.isSome(existingSplash)) return;
908 const existingWindow = yield* electronWindow.currentMainOrFirst;
909 if (Option.isSome(existingWindow)) return;
910
911 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
912 const splash = yield* electronWindow.create({
913 width: 360,
914 height: 220,
915 resizable: false,
916 minimizable: false,
917 maximizable: false,
918 fullscreenable: false,
919 frame: false,
920 center: true,
921 show: false,
922 skipTaskbar: false,
923 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
924 title: environment.displayName,
925 webPreferences: {
926 contextIsolation: true,
927 nodeIntegration: false,
928 sandbox: true,
929 },
930 });
931 yield* rendererHistory.register(splash.webContents, { surface: "splash" });
932 yield* Ref.set(splashWindowRef, Option.some(splash));
933 splash.once("closed", () => {
934 void runPromise(Ref.set(splashWindowRef, Option.none()));
935 });
936 splash.once("ready-to-show", () => {
937 if (!splash.isDestroyed()) {
938 splash.show();
939 }
940 });
941 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
942 yield* logWindowInfo("connecting splash shown");
943 }).pipe(
944 // The splash is best-effort UX — never let it fail startup.
945 Effect.catch((error) =>
946 logWindowWarning("failed to show connecting splash", { message: error.message }),
947 ),
948 Effect.withSpan("desktop.window.showConnectingSplash"),
949 );
950
951 const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* (
952 channel: string,
953 payload: unknown,
954 { reveal = true }: { readonly reveal?: boolean } = {},
955 ) {
956 const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
957 if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
958 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
959 if (targetWindow.isDestroyed()) return;
960 const send = Effect.sync(() => {
961 if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
962 });
963 // The renderer must learn about the event even when another process refuses to
964 // yield the foreground, so send first and treat the reveal as best effort.
965 const dispatch = reveal
966 ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause)))
967 : send;
968 if (targetWindow.webContents.isLoadingMainFrame()) {
969 targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
970 return;
971 }
972 yield* dispatch;
973 });
974
975 return DesktopWindow.of({
976 createMain,
977 ensureMain,
978 revealOrCreateMain,
979 prepareCaptureReveal: Effect.gen(function* () {
980 const existingWindow = yield* currentMainWindow;
981 if (Option.isSome(existingWindow)) {
982 yield* electronWindow.prepareReveal(existingWindow.value);
983 }
984 }),
985 activate: Effect.gen(function* () {
986 const existingWindow = yield* currentMainWindow;
987 if (Option.isSome(existingWindow)) {
988 yield* electronWindow.reveal(existingWindow.value);
989 return;
990 }
991 // No real main window yet. While the backend is still cold-booting,
992 // re-reveal the connecting splash so taskbar/dock activation brings it
993 // back instead of doing nothing. Once the backend is ready we fall
994 // through to (re)create the real main -- including retrying a previously
995 // failed open the pool swallowed -- rather than latching onto the splash.
996 const backendReady = yield* Ref.get(backendReadyRef);
997 if (!backendReady) {
998 const splash = yield* Ref.get(splashWindowRef);
999 if (Option.isSome(splash)) {
1000 yield* electronWindow.reveal(splash.value);
1001 return;
1002 }
1003 }
1004 yield* createMainIfBackendReady;
1005 }).pipe(Effect.withSpan("desktop.window.activate")),
1006 createMainIfBackendReady,
1007 showConnectingSplash,
1008 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1009 yield* Ref.set(backendReadyRef, true);
1010 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1011 yield* createMainIfBackendReady;
1012 }),
1013 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1014 Effect.withSpan("desktop.window.handleBackendNotReady"),
1015 ),
1016 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
1017 Effect.withSpan("desktop.window.flushMainWindowBounds"),
1018 ),
1019 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) {
1020 yield* Effect.annotateCurrentSpan({ action });
1021 yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options);
1022 }),
1023 dispatchSnapShotEvent: Effect.fn("desktop.window.dispatchSnapShotEvent")(function* (event) {
1024 yield* Effect.annotateCurrentSpan({
1025 event: event.type,
1026 captureId: "id" in event ? (event.id ?? null) : null,
1027 });
1028 yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, {
1029 reveal: event.type === "started",
1030 });
1031 }),
1032 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
1033 yield* Effect.annotateCurrentSpan({ direction });
1034 const window = yield* focusedMainWindow;
1035 if (Option.isNone(window) || window.value.isDestroyed()) {
1036 return;
1037 }
1038 const webContents = window.value.webContents;
1039 // Same step size as the Electron zoomIn/zoomOut menu roles.
1040 webContents.setZoomLevel(
1041 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
1042 );
1043 if (environment.platform === "darwin") syncMacosWindowButtons(window.value);
1044 // Chromium pushes the new level down to embedded guests, which would zoom
1045 // the previewed page along with the app UI. The preview browser keeps its
1046 // own zoom, so put each guest back where the preview left it.
1047 yield* previewManager.reapplyZoom();
1048 }),
1049 runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) {
1050 yield* Effect.annotateCurrentSpan({ command });
1051 // The registered main window, never the focused one: with an OAuth popup
1052 // focused, Reload would otherwise reload the popup mid sign-in.
1053 const window = yield* electronWindow.main;
1054 if (Option.isNone(window) || window.value.isDestroyed()) return;
1055 const webContents = window.value.webContents;
1056 if (command === "reload") webContents.reload();
1057 else if (command === "forceReload") webContents.reloadIgnoringCache();
1058 else webContents.toggleDevTools();
1059 }),
1060 syncAppearance: Effect.gen(function* () {
1061 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
1062 yield* electronWindow.syncAllAppearance((window) =>
1063 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
1064 );
1065 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
1066 });
1067});
1068
1069export const layer = Layer.effect(DesktopWindow, make);