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

DesktopWindow.ts

920 lines35.3 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";
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 { makeQuitHoldHandler } 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 });
127​
128function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
129 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
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 );
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 );
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;
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)}`;
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 }
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 );
209​
210function getWindowTitleBarOptions(
211 shouldUseDarkColors: boolean,
212 platform: NodeJS.Platform,
213): WindowTitleBarOptions {
214 if (platform === "darwin") {
215 return {
216 titleBarStyle: "hiddenInset",
217 trafficLightPosition: { x: 16, y: 18 },
218 };
219 }
220​
221 return {
222 titleBarStyle: "hidden",
223 titleBarOverlay: {
224 color: TITLEBAR_COLOR,
225 height: TITLEBAR_HEIGHT,
226 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
227 },
228 };
230​
231function syncWindowAppearance(
232 window: Electron.BrowserWindow,
233 shouldUseDarkColors: boolean,
234 platform: NodeJS.Platform,
235): Effect.Effect<void> {
236 return Effect.sync(() => {
237 if (window.isDestroyed()) {
238 return;
239 }
240​
241 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
242 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
243 if (typeof titleBarOverlay === "object") {
244 window.setTitleBarOverlay(titleBarOverlay);
245 }
246 });
248​
249type RevealSubscription = (listener: () => void) => void;
250​
251function bindFirstRevealTrigger(
252 subscribers: readonly RevealSubscription[],
253 reveal: () => void,
254): void {
255 let revealed = false;
256 const fire = () => {
257 if (revealed) return;
258 revealed = true;
259 reveal();
260 };
261 for (const subscribe of subscribers) {
262 subscribe(fire);
263 }
265​
266export const make = Effect.gen(function* () {
267 const environment = yield* DesktopEnvironment.DesktopEnvironment;
268 const assets = yield* DesktopAssets.DesktopAssets;
269 const electronMenu = yield* ElectronMenu.ElectronMenu;
270 const electronShell = yield* ElectronShell.ElectronShell;
271 const electronTheme = yield* ElectronTheme.ElectronTheme;
272 const electronWindow = yield* ElectronWindow.ElectronWindow;
273 const previewManager = yield* PreviewManager.PreviewManager;
274 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
275 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
276 const electronApp = yield* ElectronApp.ElectronApp;
277 // Window-side latch for the primary backend's readiness. Set by
278 // handleBackendReady (driven by the pool's onReady callback), cleared
279 // by handleBackendNotReady (driven by onShutdown). Only consumed by
280 // createMainIfBackendReady, which gates the post-readiness window
281 // open in development and the macOS "activate without windows" path.
282 const backendReadyRef = yield* Ref.make(false);
283 // The transient "Connecting to WSL" splash window, tracked separately so it
284 // is never mistaken for the real main window.
285 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
286 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
287 const runFork = Effect.runForkWith(context);
288 const runPromise = Effect.runPromiseWith(context);
289 let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
290​
291 const dismissConnectingSplash = Effect.gen(function* () {
292 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
293 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
294 splash.value.close();
295 }
296 });
297​
298 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
299 // which during WSL-only boot is the connecting splash. The splash is never
300 // registered via setMain, so it must be treated as "no real main window" --
301 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
302 // open (or retry) the real main. That is the failure the pool's swallowed
303 // post-readiness window-open error would otherwise strand the user in:
304 // splash up, backend ready, no main, and activation only re-reveals splash.
305 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
306 Ref.get(splashWindowRef).pipe(
307 Effect.map((splash) =>
308 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
309 ? Option.none<Electron.BrowserWindow>()
310 : window,
311 ),
312 );
313​
314 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
315 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
316​
317 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
318 Electron.BrowserWindow,
319 DesktopWindowError
320 > {
321 yield* previewManager.getBrowserSession();
322 const applicationUrl = getDesktopUrl(environment.isDevelopment);
323 const iconPaths = yield* assets.iconPaths;
324 const iconOption = getIconOption(iconPaths, environment.platform);
325 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
326 const persistedSettings = yield* desktopSettings.get;
327 const persistedBounds = persistedSettings.mainWindowBounds;
328 const displayBoundsResult = yield* Effect.sync(() => {
329 try {
330 return {
331 _tag: "Success" as const,
332 bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
333 };
334 } catch (cause) {
335 return { _tag: "Failure" as const, cause };
336 }
337 });
338 const displayBounds =
339 displayBoundsResult._tag === "Success"
340 ? displayBoundsResult.bounds
341 : yield* logWindowWarning("failed to read connected displays; using defaults", {
342 cause: displayBoundsResult.cause,
343 }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
344 const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
345 const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
346 if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
347 yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
348 }
349 const window = yield* electronWindow.create({
350 ...initialBounds,
351 minWidth: 840,
352 minHeight: 620,
353 show: false,
354 autoHideMenuBar: true,
355 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
356 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
357 ...iconOption,
358 title: environment.displayName,
359 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
360 webPreferences: {
361 preload: environment.preloadPath,
362 // The window boots hidden (show: false until ready-to-show), and
363 // Chromium throttles hidden renderers: timers coalesce and rAF stops,
364 // which stalls first paint. Boot unthrottled; the first-reveal trigger
365 // re-enables throttling so a hidden or minimized window goes back to
366 // being cheap after it has been shown once.
367 backgroundThrottling: false,
368 contextIsolation: true,
369 nodeIntegration: false,
370 sandbox: true,
371 webviewTag: true,
372 },
373 });
374​
375 if (environment.platform === "darwin") {
376 window.setAutoHideCursor(false);
377 }
378 let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
379 let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
380 let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
381 const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
382 if (window.isDestroyed()) {
383 return null;
384 }
385 const bounds =
386 window.isFullScreen() || window.isMaximized() || window.isMinimized()
387 ? window.getNormalBounds()
388 : window.getBounds();
389 return DesktopAppSettings.normalizeMainWindowBounds({
390 x: Math.round(bounds.x),
391 y: Math.round(bounds.y),
392 width: Math.round(bounds.width),
393 height: Math.round(bounds.height),
394 });
395 };
396 const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
397 const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
398 const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
399 if (!boundsPersistenceEnabled) {
400 return pendingBoundsPersistFiber;
401 }
402 const bounds = readPersistableBounds();
403 if (bounds === null) {
404 return pendingBoundsPersistFiber;
405 }
406 pendingBoundsPersistFiber = runFork(
407 desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
408 Effect.asVoid,
409 Effect.catch((error) =>
410 logWindowWarning("failed to persist main window bounds", {
411 message: error.message,
412 }),
413 ),
414 ),
415 );
416 return pendingBoundsPersistFiber;
417 };
418 const scheduleBoundsPersist = () => {
419 if (!boundsPersistenceEnabled) {
420 const currentBounds = readPersistableBounds();
421 if (
422 currentBounds === null ||
423 (fallbackWindowBounds !== null &&
424 windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
425 window.isMaximized() === fallbackWindowMaximized)
426 ) {
427 return;
428 }
429 }
430 boundsPersistenceEnabled = true;
431 if (boundsPersistFiber !== undefined) {
432 const fiber = boundsPersistFiber;
433 boundsPersistFiber = undefined;
434 runFork(Fiber.interrupt(fiber));
435 }
436 boundsPersistFiber = runFork(
437 Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
438 Effect.andThen(
439 Effect.sync(() => {
440 boundsPersistFiber = undefined;
441 void persistCurrentBounds();
442 }),
443 ),
444 ),
445 );
446 };
447 const clearBoundsPersist = () => {
448 if (boundsPersistFiber === undefined) {
449 return;
450 }
451 const fiber = boundsPersistFiber;
452 boundsPersistFiber = undefined;
453 runFork(Fiber.interrupt(fiber));
454 };
455 const flushBoundsPersist = Effect.sync(() => {
456 clearBoundsPersist();
457 return persistCurrentBounds();
458 }).pipe(
459 Effect.flatMap((fiber) =>
460 fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
461 ),
462 );
463 flushMainWindowBounds = flushBoundsPersist;
464​
465 yield* previewManager.setMainWindow(window);
466 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
467 if (
468 typeof params.partition !== "string" ||
469 !previewManager.isBrowserPartition(params.partition)
470 ) {
471 event.preventDefault();
472 return;
473 }
474 webPreferences.sandbox = true;
475 webPreferences.nodeIntegration = false;
476 webPreferences.nodeIntegrationInSubFrames = false;
477 webPreferences.contextIsolation = false;
478 });
479​
480 window.webContents.on("context-menu", (event, params) => {
481 event.preventDefault();
482​
483 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
484​
485 if (params.misspelledWord) {
486 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
487 menuTemplate.push({
488 label: suggestion,
489 click: () => window.webContents.replaceMisspelling(suggestion),
490 });
491 }
492 if (params.dictionarySuggestions.length === 0) {
493 menuTemplate.push({ label: "No suggestions", enabled: false });
494 }
495 menuTemplate.push({ type: "separator" });
496 }
497​
498 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
499 menuTemplate.push(
500 {
501 label: "Copy Link",
502 click: () => {
503 void runPromise(electronShell.copyText(params.linkURL));
504 },
505 },
506 { type: "separator" },
507 );
508 }
509​
510 if (params.mediaType === "image") {
511 menuTemplate.push({
512 label: "Copy Image",
513 click: () => window.webContents.copyImageAt(params.x, params.y),
514 });
515 menuTemplate.push({ type: "separator" });
516 }
517​
518 menuTemplate.push(
519 { role: "cut", enabled: params.editFlags.canCut },
520 { role: "copy", enabled: params.editFlags.canCopy },
521 { role: "paste", enabled: params.editFlags.canPaste },
522 { role: "selectAll", enabled: params.editFlags.canSelectAll },
523 );
524​
525 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
526 });
527​
528 window.webContents.setWindowOpenHandler(({ url }) => {
529 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
530 void runPromise(electronShell.openExternal(url));
531 }
532 return { action: "deny" };
533 });
534 window.webContents.on("will-navigate", (event, url) => {
535 if (
536 isSameOriginRendererNavigation({
537 applicationUrl,
538 navigationUrl: url,
539 })
540 ) {
541 return;
542 }
543​
544 event.preventDefault();
545 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
546 void runPromise(electronShell.openExternal(url));
547 }
548 });
549​
550 // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
551 // close-terminal shortcut can outlive the terminal that handled its first
552 // press, so reject repeats before they reach the native window accelerator.
553 // Deliberate presses still flow through the renderer or native menu.
554 // Chrome-style hold-to-quit: intercept the quit accelerator before the
555 // native menu sees it and only quit after the shortcut is held. The
556 // renderer shows the "Hold to Quit" hint via QUIT_SHORTCUT_CHANNEL.
557 const quitHoldHandler = makeQuitHoldHandler({
558 platform: environment.platform,
559 isEnabled: () =>
560 runPromise(
561 Effect.map(
562 clientSettings.get,
563 Option.match({
564 onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
565 onSome: (settings) => settings.confirmQuit,
566 }),
567 ),
568 ),
569 notify: (state) => {
570 if (!window.isDestroyed()) {
571 window.webContents.send(QUIT_SHORTCUT_CHANNEL, state);
572 }
573 },
574 quit: () => {
575 void runPromise(electronApp.quit);
576 },
577 });
578 window.webContents.on("before-input-event", (event, input) => {
579 quitHoldHandler(event, input);
580 if (input.type !== "keyDown" || !input.isAutoRepeat) return;
581 const modifier = environment.platform === "darwin" ? input.meta : input.control;
582 if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
583 event.preventDefault();
584 }
585 });
586​
587 window.on("page-title-updated", (event) => {
588 event.preventDefault();
589 window.setTitle(environment.displayName);
590 });
591 window.on("resize", scheduleBoundsPersist);
592 window.on("move", scheduleBoundsPersist);
593 window.on("maximize", scheduleBoundsPersist);
594 window.on("unmaximize", scheduleBoundsPersist);
595 window.on("close", () => {
596 runFork(flushBoundsPersist);
597 });
598​
599 if (environment.platform === "darwin") {
600 window.on("enter-full-screen", () => {
601 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
602 });
603 window.on("leave-full-screen", () => {
604 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
605 });
606 }
607​
608 let developmentLoadRetryIndex = 0;
609 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
610 let rendererRecoveryTimestamps: number[] = [];
611 const clearDevelopmentLoadRetry = () => {
612 if (developmentLoadRetryFiber === undefined) {
613 return;
614 }
615 const retryFiber = developmentLoadRetryFiber;
616 developmentLoadRetryFiber = undefined;
617 runFork(Fiber.interrupt(retryFiber));
618 };
619 const loadApplication = () => {
620 if (window.isDestroyed()) {
621 return;
622 }
623 void window.loadURL(applicationUrl).catch(() => undefined);
624 };
625 const scheduleDevelopmentLoadRetry = () => {
626 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
627 return undefined;
628 }
629​
630 const retryIndex = Math.min(
631 developmentLoadRetryIndex,
632 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
633 );
634 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
635 developmentLoadRetryIndex += 1;
636 developmentLoadRetryFiber = runFork(
637 Effect.sleep(retryInMs).pipe(
638 Effect.andThen(
639 Effect.sync(() => {
640 developmentLoadRetryFiber = undefined;
641 if (!window.isDestroyed()) {
642 loadApplication();
643 }
644 }),
645 ),
646 ),
647 );
648 return retryInMs;
649 };
650​
651 window.webContents.on("did-finish-load", () => {
652 if (
653 environment.isDevelopment &&
654 !isSameOriginRendererNavigation({
655 applicationUrl,
656 navigationUrl: window.webContents.getURL(),
657 })
658 ) {
659 return;
660 }
661 clearDevelopmentLoadRetry();
662 developmentLoadRetryIndex = 0;
663 window.setTitle(environment.displayName);
664 });
665 window.webContents.on(
666 "did-fail-load",
667 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
668 if (!isMainFrame) {
669 return;
670 }
671 const retryInMs =
672 environment.isDevelopment &&
673 isRetryableDevelopmentRendererLoadFailure({
674 applicationUrl,
675 errorCode,
676 isMainFrame,
677 validatedUrl: validatedURL,
678 })
679 ? scheduleDevelopmentLoadRetry()
680 : undefined;
681 void runPromise(
682 logWindowWarning("main window failed to load", {
683 errorCode,
684 errorDescription,
685 url: validatedURL,
686 ...(retryInMs === undefined ? {} : { retryInMs }),
687 }),
688 );
689 },
690 );
691 window.webContents.on("render-process-gone", (_event, details) => {
692 const recoverable =
693 details.reason === "crashed" ||
694 details.reason === "oom" ||
695 details.reason === "abnormal-exit";
696 // Long sessions can OOM the renderer (V8 heap exhaustion from
697 // accumulated thread state). Without a reload the user is left staring
698 // at a dead white window while agents keep running invisibly, so
699 // recover by reloading — the renderer rehydrates from the backend,
700 // which is unaffected. Recovery attempts are bounded so a renderer
701 // that dies immediately on boot cannot reload-loop forever.
702 runFork(
703 Effect.gen(function* () {
704 const now = yield* Clock.currentTimeMillis;
705 rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
706 (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
707 );
708 const shouldRecover =
709 recoverable &&
710 !window.isDestroyed() &&
711 rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
712 yield* logWindowWarning("main window render process gone", {
713 reason: details.reason,
714 exitCode: details.exitCode,
715 recovering: shouldRecover,
716 });
717 if (!shouldRecover) {
718 return;
719 }
720 rendererRecoveryTimestamps.push(now);
721 yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
722 if (!window.isDestroyed()) {
723 loadApplication();
724 }
725 }),
726 );
727 });
728​
729 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
730 if (environment.platform === "linux") {
731 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
732 }
733 bindFirstRevealTrigger(revealSubscribers, () => {
734 // Boot is done; hand the window back to normal hidden-window throttling
735 // (see the backgroundThrottling comment on the create options above).
736 if (!window.isDestroyed()) {
737 window.webContents.setBackgroundThrottling(true);
738 }
739 // Reveal the real window, then close the connecting splash (if any) so the
740 // two don't overlap and there's no blank gap between them.
741 if (persistedSettings.mainWindowMaximized) {
742 window.maximize();
743 }
744 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
745 });
746​
747 loadApplication();
748 if (environment.isDevelopment) {
749 window.webContents.openDevTools({ mode: "detach" });
750 }
751​
752 window.on("closed", () => {
753 clearDevelopmentLoadRetry();
754 clearBoundsPersist();
755 void runPromise(electronWindow.clearMain(Option.some(window)));
756 });
757​
758 return window;
759 });
760​
761 const createMain = Effect.gen(function* () {
762 const window = yield* createWindow();
763 yield* electronWindow.setMain(window);
764 yield* logWindowInfo("main window created");
765 return window;
766 }).pipe(Effect.withSpan("desktop.window.createMain"));
767​
768 const ensureMain = Effect.gen(function* () {
769 const existingWindow = yield* currentMainWindow;
770 if (Option.isSome(existingWindow)) {
771 return existingWindow.value;
772 }
773 return yield* createMain;
774 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
775​
776 const revealOrCreateMain = Effect.gen(function* () {
777 const window = yield* ensureMain;
778 yield* electronWindow.reveal(window);
779 return window;
780 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
781​
782 const createMainIfBackendReady = Effect.gen(function* () {
783 const backendReady = yield* Ref.get(backendReadyRef);
784 if (!backendReady) return;
785 const existingWindow = yield* currentMainWindow;
786 if (Option.isSome(existingWindow)) return;
787 yield* createMain;
788 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
789​
790 const showConnectingSplash = Effect.gen(function* () {
791 // Only when nothing is shown yet: no real window, no existing splash.
792 const existingSplash = yield* Ref.get(splashWindowRef);
793 if (Option.isSome(existingSplash)) return;
794 const existingWindow = yield* electronWindow.currentMainOrFirst;
795 if (Option.isSome(existingWindow)) return;
796​
797 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
798 const splash = yield* electronWindow.create({
799 width: 360,
800 height: 220,
801 resizable: false,
802 minimizable: false,
803 maximizable: false,
804 fullscreenable: false,
805 frame: false,
806 center: true,
807 show: false,
808 skipTaskbar: false,
809 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
810 title: environment.displayName,
811 webPreferences: {
812 contextIsolation: true,
813 nodeIntegration: false,
814 sandbox: true,
815 },
816 });
817 yield* Ref.set(splashWindowRef, Option.some(splash));
818 splash.once("closed", () => {
819 void runPromise(Ref.set(splashWindowRef, Option.none()));
820 });
821 splash.once("ready-to-show", () => {
822 if (!splash.isDestroyed()) {
823 splash.show();
824 }
825 });
826 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
827 yield* logWindowInfo("connecting splash shown");
828 }).pipe(
829 // The splash is best-effort UX — never let it fail startup.
830 Effect.catch((error) =>
831 logWindowWarning("failed to show connecting splash", { message: error.message }),
832 ),
833 Effect.withSpan("desktop.window.showConnectingSplash"),
834 );
835​
836 return DesktopWindow.of({
837 createMain,
838 ensureMain,
839 revealOrCreateMain,
840 activate: Effect.gen(function* () {
841 const existingWindow = yield* currentMainWindow;
842 if (Option.isSome(existingWindow)) {
843 yield* electronWindow.reveal(existingWindow.value);
844 return;
845 }
846 // No real main window yet. While the backend is still cold-booting,
847 // re-reveal the connecting splash so taskbar/dock activation brings it
848 // back instead of doing nothing. Once the backend is ready we fall
849 // through to (re)create the real main -- including retrying a previously
850 // failed open the pool swallowed -- rather than latching onto the splash.
851 const backendReady = yield* Ref.get(backendReadyRef);
852 if (!backendReady) {
853 const splash = yield* Ref.get(splashWindowRef);
854 if (Option.isSome(splash)) {
855 yield* electronWindow.reveal(splash.value);
856 return;
857 }
858 }
859 yield* createMainIfBackendReady;
860 }).pipe(Effect.withSpan("desktop.window.activate")),
861 createMainIfBackendReady,
862 showConnectingSplash,
863 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
864 yield* Ref.set(backendReadyRef, true);
865 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
866 yield* createMainIfBackendReady;
867 }),
868 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
869 Effect.withSpan("desktop.window.handleBackendNotReady"),
870 ),
871 flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
872 Effect.withSpan("desktop.window.flushMainWindowBounds"),
873 ),
874 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
875 yield* Effect.annotateCurrentSpan({ action });
876 const existingWindow = yield* focusedMainWindow;
877 if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
878 return;
879 }
880 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
881​
882 const send = () => {
883 if (targetWindow.isDestroyed()) return;
884 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
885 void runPromise(electronWindow.reveal(targetWindow));
886 };
887​
888 if (targetWindow.webContents.isLoadingMainFrame()) {
889 targetWindow.webContents.once("did-finish-load", send);
890 return;
891 }
892​
893 send();
894 }),
895 zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
896 yield* Effect.annotateCurrentSpan({ direction });
897 const window = yield* focusedMainWindow;
898 if (Option.isNone(window) || window.value.isDestroyed()) {
899 return;
900 }
901 const webContents = window.value.webContents;
902 // Same step size as the Electron zoomIn/zoomOut menu roles.
903 webContents.setZoomLevel(
904 direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
905 );
906 // Chromium pushes the new level down to embedded guests, which would zoom
907 // the previewed page along with the app UI. The preview browser keeps its
908 // own zoom, so put each guest back where the preview left it.
909 yield* previewManager.reapplyZoom();
910 }),
911 syncAppearance: Effect.gen(function* () {
912 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
913 yield* electronWindow.syncAllAppearance((window) =>
914 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
915 );
916 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
917 });
918});
919​
920export const layer = Layer.effect(DesktopWindow, make);