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