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

DesktopWindow.ts

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