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

DesktopWindow.ts

631 lines23.6 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7​
8import type * as Electron from "electron";
9​
10import * as DesktopAssets from "../app/DesktopAssets.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import { makeComponentLogger } from "../app/DesktopObservability.ts";
13import * as ElectronMenu from "../electron/ElectronMenu.ts";
14import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
15import * as ElectronShell from "../electron/ElectronShell.ts";
16import * as ElectronTheme from "../electron/ElectronTheme.ts";
17import * as ElectronWindow from "../electron/ElectronWindow.ts";
18import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
19import * as PreviewManager from "../preview/Manager.ts";
20​
21const TITLEBAR_HEIGHT = 40;
22const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
23const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
24const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
25const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
26const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
27 -2, // ERR_FAILED
28 -7, // ERR_TIMED_OUT
29 -9, // ERR_UNEXPECTED (custom protocol handler rejected)
30 -102, // ERR_CONNECTION_REFUSED
31 -105, // ERR_NAME_NOT_RESOLVED
32 -106, // ERR_INTERNET_DISCONNECTED
33 -118, // ERR_CONNECTION_TIMED_OUT
34]);
35​
36type WindowTitleBarOptions = Pick<
37 Electron.BrowserWindowConstructorOptions,
38 "titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
39>;
40​
41type DesktopWindowRuntimeServices =
42 | DesktopEnvironment.DesktopEnvironment
43 | DesktopAssets.DesktopAssets
44 | ElectronMenu.ElectronMenu
45 | ElectronShell.ElectronShell
46 | ElectronTheme.ElectronTheme
47 | ElectronWindow.ElectronWindow
48 | PreviewManager.PreviewManager;
49​
50export type DesktopWindowError =
51 | ElectronWindow.ElectronWindowCreateError
52 | PreviewManager.PreviewManagerError;
53​
54export class DesktopWindow extends Context.Service<
55 DesktopWindow,
56 {
57 readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
58 readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
59 readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
60 readonly activate: Effect.Effect<void, DesktopWindowError>;
61 readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
62 // Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
63 // mode), before the WSL backend that serves the renderer is ready. It is
64 // dismissed automatically once the real main window reveals.
65 readonly showConnectingSplash: Effect.Effect<void>;
66 // Marks the primary backend as ready so `createMainIfBackendReady` and the
67 // macOS "activate without windows" path may open the real main window. The
68 // renderer now always loads the local client URL (getDesktopUrl) and connects
69 // to the backend through the connection layer, so the reported httpBaseUrl is
70 // no longer used to point the window at the backend — it is kept only for the
71 // readiness log and to preserve the callback contract the backend pool drives.
72 readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
73 // Called when the backend transitions back to "not ready" (clean stop,
74 // restart, crash). Clears the latch that lets `activate` auto-create a
75 // window so a "macOS dock click" while the backend is down doesn't
76 // produce a stranded window pointing at nothing.
77 readonly handleBackendNotReady: Effect.Effect<void>;
78 readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
79 readonly syncAppearance: Effect.Effect<void>;
80 }
81>()("@v12/desktop/window/DesktopWindow") {}
82​
83const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
84 makeComponentLogger("desktop-window");
85​
86function getIconOption(
87 iconPaths: DesktopAssets.DesktopIconPaths,
88 platform: NodeJS.Platform,
89): { icon: string } | Record<string, never> {
90 if (platform === "darwin") return {}; // macOS uses .icns from app bundle
91 const ext = platform === "win32" ? "ico" : "png";
92 return Option.match(iconPaths[ext], {
93 onNone: () => ({}),
94 onSome: (icon) => ({ icon }),
95 });
97​
98function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
99 return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
101​
102// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
103// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
104// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
105function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
106 const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
107 const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
108 const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
109 const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
110 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>`;
111 return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
113​
114export function isSameOriginRendererNavigation(input: {
115 readonly applicationUrl: string;
116 readonly navigationUrl: string;
117}): boolean {
118 try {
119 return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
120 } catch {
121 return false;
122 }
124​
125export function isRetryableDevelopmentRendererLoadFailure(input: {
126 readonly applicationUrl: string;
127 readonly errorCode: number;
128 readonly isMainFrame: boolean;
129 readonly validatedUrl: string;
130}): boolean {
131 return (
132 input.isMainFrame &&
133 DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
134 isSameOriginRendererNavigation({
135 applicationUrl: input.applicationUrl,
136 navigationUrl: input.validatedUrl,
137 })
138 );
140​
141function getWindowTitleBarOptions(
142 shouldUseDarkColors: boolean,
143 platform: NodeJS.Platform,
144): WindowTitleBarOptions {
145 if (platform === "darwin") {
146 return {
147 titleBarStyle: "hiddenInset",
148 trafficLightPosition: { x: 16, y: 18 },
149 };
150 }
151​
152 return {
153 titleBarStyle: "hidden",
154 titleBarOverlay: {
155 color: TITLEBAR_COLOR,
156 height: TITLEBAR_HEIGHT,
157 symbolColor: shouldUseDarkColors ? TITLEBAR_DARK_SYMBOL_COLOR : TITLEBAR_LIGHT_SYMBOL_COLOR,
158 },
159 };
161​
162function syncWindowAppearance(
163 window: Electron.BrowserWindow,
164 shouldUseDarkColors: boolean,
165 platform: NodeJS.Platform,
166): Effect.Effect<void> {
167 return Effect.sync(() => {
168 if (window.isDestroyed()) {
169 return;
170 }
171​
172 window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
173 const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
174 if (typeof titleBarOverlay === "object") {
175 window.setTitleBarOverlay(titleBarOverlay);
176 }
177 });
179​
180type RevealSubscription = (listener: () => void) => void;
181​
182function bindFirstRevealTrigger(
183 subscribers: readonly RevealSubscription[],
184 reveal: () => void,
185): void {
186 let revealed = false;
187 const fire = () => {
188 if (revealed) return;
189 revealed = true;
190 reveal();
191 };
192 for (const subscribe of subscribers) {
193 subscribe(fire);
194 }
196​
197export const make = Effect.gen(function* () {
198 const environment = yield* DesktopEnvironment.DesktopEnvironment;
199 const assets = yield* DesktopAssets.DesktopAssets;
200 const electronMenu = yield* ElectronMenu.ElectronMenu;
201 const electronShell = yield* ElectronShell.ElectronShell;
202 const electronTheme = yield* ElectronTheme.ElectronTheme;
203 const electronWindow = yield* ElectronWindow.ElectronWindow;
204 const previewManager = yield* PreviewManager.PreviewManager;
205 // Window-side latch for the primary backend's readiness. Set by
206 // handleBackendReady (driven by the pool's onReady callback), cleared
207 // by handleBackendNotReady (driven by onShutdown). Only consumed by
208 // createMainIfBackendReady, which gates the post-readiness window
209 // open in development and the macOS "activate without windows" path.
210 const backendReadyRef = yield* Ref.make(false);
211 // The transient "Connecting to WSL" splash window, tracked separately so it
212 // is never mistaken for the real main window.
213 const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
214 const context = yield* Effect.context<DesktopWindowRuntimeServices>();
215 const runFork = Effect.runForkWith(context);
216 const runPromise = Effect.runPromiseWith(context);
217​
218 const dismissConnectingSplash = Effect.gen(function* () {
219 const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
220 if (Option.isSome(splash) && !splash.value.isDestroyed()) {
221 splash.value.close();
222 }
223 });
224​
225 // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
226 // which during WSL-only boot is the connecting splash. The splash is never
227 // registered via setMain, so it must be treated as "no real main window" --
228 // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
229 // open (or retry) the real main. That is the failure the pool's swallowed
230 // post-readiness window-open error would otherwise strand the user in:
231 // splash up, backend ready, no main, and activation only re-reveals splash.
232 const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
233 Ref.get(splashWindowRef).pipe(
234 Effect.map((splash) =>
235 Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
236 ? Option.none<Electron.BrowserWindow>()
237 : window,
238 ),
239 );
240​
241 const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
242 const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
243​
244 const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
245 Electron.BrowserWindow,
246 DesktopWindowError
247 > {
248 yield* previewManager.getBrowserSession();
249 const applicationUrl = getDesktopUrl(environment.isDevelopment);
250 const iconPaths = yield* assets.iconPaths;
251 const iconOption = getIconOption(iconPaths, environment.platform);
252 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
253 const window = yield* electronWindow.create({
254 width: 1100,
255 height: 780,
256 minWidth: 840,
257 minHeight: 620,
258 show: false,
259 autoHideMenuBar: true,
260 ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
261 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
262 ...iconOption,
263 title: environment.displayName,
264 ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
265 webPreferences: {
266 preload: environment.preloadPath,
267 contextIsolation: true,
268 nodeIntegration: false,
269 sandbox: true,
270 webviewTag: true,
271 },
272 });
273​
274 if (environment.platform === "darwin") {
275 window.setAutoHideCursor(false);
276 }
277​
278 yield* previewManager.setMainWindow(window);
279 window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
280 if (
281 typeof params.partition !== "string" ||
282 !previewManager.isBrowserPartition(params.partition)
283 ) {
284 event.preventDefault();
285 return;
286 }
287 webPreferences.sandbox = true;
288 webPreferences.nodeIntegration = false;
289 webPreferences.nodeIntegrationInSubFrames = false;
290 webPreferences.contextIsolation = false;
291 });
292​
293 window.webContents.on("context-menu", (event, params) => {
294 event.preventDefault();
295​
296 const menuTemplate: Electron.MenuItemConstructorOptions[] = [];
297​
298 if (params.misspelledWord) {
299 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
300 menuTemplate.push({
301 label: suggestion,
302 click: () => window.webContents.replaceMisspelling(suggestion),
303 });
304 }
305 if (params.dictionarySuggestions.length === 0) {
306 menuTemplate.push({ label: "No suggestions", enabled: false });
307 }
308 menuTemplate.push({ type: "separator" });
309 }
310​
311 if (Option.isSome(ElectronShell.parseSafeExternalUrl(params.linkURL))) {
312 menuTemplate.push(
313 {
314 label: "Copy Link",
315 click: () => {
316 void runPromise(electronShell.copyText(params.linkURL));
317 },
318 },
319 { type: "separator" },
320 );
321 }
322​
323 if (params.mediaType === "image") {
324 menuTemplate.push({
325 label: "Copy Image",
326 click: () => window.webContents.copyImageAt(params.x, params.y),
327 });
328 menuTemplate.push({ type: "separator" });
329 }
330​
331 menuTemplate.push(
332 { role: "cut", enabled: params.editFlags.canCut },
333 { role: "copy", enabled: params.editFlags.canCopy },
334 { role: "paste", enabled: params.editFlags.canPaste },
335 { role: "selectAll", enabled: params.editFlags.canSelectAll },
336 );
337​
338 void runPromise(electronMenu.popupTemplate({ window, template: menuTemplate }));
339 });
340​
341 window.webContents.setWindowOpenHandler(({ url }) => {
342 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
343 void runPromise(electronShell.openExternal(url));
344 }
345 return { action: "deny" };
346 });
347 window.webContents.on("will-navigate", (event, url) => {
348 if (
349 isSameOriginRendererNavigation({
350 applicationUrl,
351 navigationUrl: url,
352 })
353 ) {
354 return;
355 }
356​
357 event.preventDefault();
358 if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
359 void runPromise(electronShell.openExternal(url));
360 }
361 });
362​
363 window.on("page-title-updated", (event) => {
364 event.preventDefault();
365 window.setTitle(environment.displayName);
366 });
367​
368 if (environment.platform === "darwin") {
369 window.on("enter-full-screen", () => {
370 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
371 });
372 window.on("leave-full-screen", () => {
373 window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
374 });
375 }
376​
377 let developmentLoadRetryIndex = 0;
378 let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
379 const clearDevelopmentLoadRetry = () => {
380 if (developmentLoadRetryFiber === undefined) {
381 return;
382 }
383 const retryFiber = developmentLoadRetryFiber;
384 developmentLoadRetryFiber = undefined;
385 runFork(Fiber.interrupt(retryFiber));
386 };
387 const loadApplication = () => {
388 if (window.isDestroyed()) {
389 return;
390 }
391 void window.loadURL(applicationUrl).catch(() => undefined);
392 };
393 const scheduleDevelopmentLoadRetry = () => {
394 if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
395 return undefined;
396 }
397​
398 const retryIndex = Math.min(
399 developmentLoadRetryIndex,
400 DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
401 );
402 const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
403 developmentLoadRetryIndex += 1;
404 developmentLoadRetryFiber = runFork(
405 Effect.sleep(retryInMs).pipe(
406 Effect.andThen(
407 Effect.sync(() => {
408 developmentLoadRetryFiber = undefined;
409 if (!window.isDestroyed()) {
410 loadApplication();
411 }
412 }),
413 ),
414 ),
415 );
416 return retryInMs;
417 };
418​
419 window.webContents.on("did-finish-load", () => {
420 if (
421 environment.isDevelopment &&
422 !isSameOriginRendererNavigation({
423 applicationUrl,
424 navigationUrl: window.webContents.getURL(),
425 })
426 ) {
427 return;
428 }
429 clearDevelopmentLoadRetry();
430 developmentLoadRetryIndex = 0;
431 window.setTitle(environment.displayName);
432 });
433 window.webContents.on(
434 "did-fail-load",
435 (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
436 if (!isMainFrame) {
437 return;
438 }
439 const retryInMs =
440 environment.isDevelopment &&
441 isRetryableDevelopmentRendererLoadFailure({
442 applicationUrl,
443 errorCode,
444 isMainFrame,
445 validatedUrl: validatedURL,
446 })
447 ? scheduleDevelopmentLoadRetry()
448 : undefined;
449 void runPromise(
450 logWindowWarning("main window failed to load", {
451 errorCode,
452 errorDescription,
453 url: validatedURL,
454 ...(retryInMs === undefined ? {} : { retryInMs }),
455 }),
456 );
457 },
458 );
459 window.webContents.on("render-process-gone", (_event, details) => {
460 void runPromise(
461 logWindowWarning("main window render process gone", {
462 reason: details.reason,
463 exitCode: details.exitCode,
464 }),
465 );
466 });
467​
468 const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
469 if (environment.platform === "linux") {
470 revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
471 }
472 bindFirstRevealTrigger(revealSubscribers, () => {
473 // Reveal the real window, then close the connecting splash (if any) so the
474 // two don't overlap and there's no blank gap between them.
475 void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
476 });
477​
478 loadApplication();
479 if (environment.isDevelopment) {
480 window.webContents.openDevTools({ mode: "detach" });
481 }
482​
483 window.on("closed", () => {
484 clearDevelopmentLoadRetry();
485 void runPromise(electronWindow.clearMain(Option.some(window)));
486 });
487​
488 return window;
489 });
490​
491 const createMain = Effect.gen(function* () {
492 const window = yield* createWindow();
493 yield* electronWindow.setMain(window);
494 yield* logWindowInfo("main window created");
495 return window;
496 }).pipe(Effect.withSpan("desktop.window.createMain"));
497​
498 const ensureMain = Effect.gen(function* () {
499 const existingWindow = yield* currentMainWindow;
500 if (Option.isSome(existingWindow)) {
501 return existingWindow.value;
502 }
503 return yield* createMain;
504 }).pipe(Effect.withSpan("desktop.window.ensureMain"));
505​
506 const revealOrCreateMain = Effect.gen(function* () {
507 const window = yield* ensureMain;
508 yield* electronWindow.reveal(window);
509 return window;
510 }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
511​
512 const createMainIfBackendReady = Effect.gen(function* () {
513 const backendReady = yield* Ref.get(backendReadyRef);
514 if (!backendReady) return;
515 const existingWindow = yield* currentMainWindow;
516 if (Option.isSome(existingWindow)) return;
517 yield* createMain;
518 }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
519​
520 const showConnectingSplash = Effect.gen(function* () {
521 // Only when nothing is shown yet: no real window, no existing splash.
522 const existingSplash = yield* Ref.get(splashWindowRef);
523 if (Option.isSome(existingSplash)) return;
524 const existingWindow = yield* electronWindow.currentMainOrFirst;
525 if (Option.isSome(existingWindow)) return;
526​
527 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
528 const splash = yield* electronWindow.create({
529 width: 360,
530 height: 220,
531 resizable: false,
532 minimizable: false,
533 maximizable: false,
534 fullscreenable: false,
535 frame: false,
536 center: true,
537 show: false,
538 skipTaskbar: false,
539 backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
540 title: environment.displayName,
541 webPreferences: {
542 contextIsolation: true,
543 nodeIntegration: false,
544 sandbox: true,
545 },
546 });
547 yield* Ref.set(splashWindowRef, Option.some(splash));
548 splash.once("closed", () => {
549 void runPromise(Ref.set(splashWindowRef, Option.none()));
550 });
551 splash.once("ready-to-show", () => {
552 if (!splash.isDestroyed()) {
553 splash.show();
554 }
555 });
556 void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
557 yield* logWindowInfo("connecting splash shown");
558 }).pipe(
559 // The splash is best-effort UX — never let it fail startup.
560 Effect.catch((error) =>
561 logWindowWarning("failed to show connecting splash", { message: error.message }),
562 ),
563 Effect.withSpan("desktop.window.showConnectingSplash"),
564 );
565​
566 return DesktopWindow.of({
567 createMain,
568 ensureMain,
569 revealOrCreateMain,
570 activate: Effect.gen(function* () {
571 const existingWindow = yield* currentMainWindow;
572 if (Option.isSome(existingWindow)) {
573 yield* electronWindow.reveal(existingWindow.value);
574 return;
575 }
576 // No real main window yet. While the backend is still cold-booting,
577 // re-reveal the connecting splash so taskbar/dock activation brings it
578 // back instead of doing nothing. Once the backend is ready we fall
579 // through to (re)create the real main -- including retrying a previously
580 // failed open the pool swallowed -- rather than latching onto the splash.
581 const backendReady = yield* Ref.get(backendReadyRef);
582 if (!backendReady) {
583 const splash = yield* Ref.get(splashWindowRef);
584 if (Option.isSome(splash)) {
585 yield* electronWindow.reveal(splash.value);
586 return;
587 }
588 }
589 yield* createMainIfBackendReady;
590 }).pipe(Effect.withSpan("desktop.window.activate")),
591 createMainIfBackendReady,
592 showConnectingSplash,
593 handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
594 yield* Ref.set(backendReadyRef, true);
595 yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
596 yield* createMainIfBackendReady;
597 }),
598 handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
599 Effect.withSpan("desktop.window.handleBackendNotReady"),
600 ),
601 dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
602 yield* Effect.annotateCurrentSpan({ action });
603 const existingWindow = yield* focusedMainWindow;
604 if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
605 return;
606 }
607 const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
608​
609 const send = () => {
610 if (targetWindow.isDestroyed()) return;
611 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
612 void runPromise(electronWindow.reveal(targetWindow));
613 };
614​
615 if (targetWindow.webContents.isLoadingMainFrame()) {
616 targetWindow.webContents.once("did-finish-load", send);
617 return;
618 }
619​
620 send();
621 }),
622 syncAppearance: Effect.gen(function* () {
623 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
624 yield* electronWindow.syncAllAppearance((window) =>
625 syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
626 );
627 }).pipe(Effect.withSpan("desktop.window.syncAppearance")),
628 });
629});
630​
631export const layer = Layer.effect(DesktopWindow, make);