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