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