TypeScript
fix(desktop): stop blocking the renderer during topology polling (#19300)
Daniyal6bcbb9519ba0
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.tsindex 47b342c47de..383c4bbd153 100644--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts@@ -40,6 +40,7 @@ import {import {getAppBranding,getLocalEnvironmentBootstraps,+ readLocalEnvironmentBootstraps,getLocalEnvironmentBearerToken,getRelayTelemetryEnabled,getSystemLocale,@@ -100,6 +101,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"yield* ipc.handleSync(getSystemLocale);yield* ipc.handleSync(getWindowFullscreenState);yield* ipc.handleSync(getLocalEnvironmentBootstraps);+ yield* ipc.handle(readLocalEnvironmentBootstraps);yield* ipc.handleSync(getLocalEnvironmentEnabled);yield* ipc.handle(setLocalEnvironmentEnabled);yield* ipc.handle(getLocalEnvironmentBearerToken);diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.tsindex 9066cf6f1a6..924d20775cd 100644--- a/apps/desktop/src/ipc/methods/window.ts+++ b/apps/desktop/src/ipc/methods/window.ts@@ -99,57 +99,68 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({}),});-export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,- result: Schema.Array(DesktopEnvironmentBootstrapSchema),- handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {- const pool = yield* DesktopBackendPool.DesktopBackendPool;- const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;- const instances = yield* pool.list;- const bootstraps: DesktopEnvironmentBootstrap[] = [];- for (const instance of instances) {- const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;- const config = yield* instance.currentConfig;- const snapshot = yield* instance.snapshot;- if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {- const fatalPreflight =- Option.isSome(config) &&- Option.isSome(config.value.preflightFailure) &&- config.value.preflightFailure.value.fatal;- const stoppedPreflight =- Option.isSome(config) &&- Option.isSome(config.value.preflightFailure) &&- (!snapshot.desiredRunning || !snapshot.restartScheduled);- if (isPrimary || fatalPreflight || stoppedPreflight) continue;- bootstraps.push({- id: instance.id,- label: yield* instance.label,- runningDistro: null,- httpBaseUrl: null,- wsBaseUrl: null,- });- continue;- }- const { bootstrap, httpBaseUrl } = config.value;- const runningDistro = config.value.runningDistro ?? null;+const readLocalEnvironmentBootstrapSnapshot = Effect.fn(+ "desktop.ipc.window.getLocalEnvironmentBootstraps",+)(function* () {+ const pool = yield* DesktopBackendPool.DesktopBackendPool;+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const instances = yield* pool.list;+ const bootstraps: DesktopEnvironmentBootstrap[] = [];+ for (const instance of instances) {+ const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;+ const config = yield* instance.currentConfig;+ const snapshot = yield* instance.snapshot;+ if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {+ const fatalPreflight =+ Option.isSome(config) &&+ Option.isSome(config.value.preflightFailure) &&+ config.value.preflightFailure.value.fatal;+ const stoppedPreflight =+ Option.isSome(config) &&+ Option.isSome(config.value.preflightFailure) &&+ (!snapshot.desiredRunning || !snapshot.restartScheduled);+ if (isPrimary || fatalPreflight || stoppedPreflight) continue;bootstraps.push({id: instance.id,- label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,- runningDistro,- httpBaseUrl: httpBaseUrl.href,- wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),- // A backend launched with the desktop secret accepts whichever token the secret derives- // for the current window, so hand out that one rather than the token frozen into its- // launch config.- ...(bootstrap.desktopBootstrapSecret- ? { bootstrapToken: yield* configuration.currentBootstrapToken }- : bootstrap.desktopBootstrapToken- ? { bootstrapToken: bootstrap.desktopBootstrapToken }- : {}),+ label: yield* instance.label,+ runningDistro: null,+ httpBaseUrl: null,+ wsBaseUrl: null,});+ continue;}- return bootstraps;- }),+ const { bootstrap, httpBaseUrl } = config.value;+ const runningDistro = config.value.runningDistro ?? null;+ bootstraps.push({+ id: instance.id,+ label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,+ runningDistro,+ httpBaseUrl: httpBaseUrl.href,+ wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),+ // A backend launched with the desktop secret accepts whichever token the secret derives+ // for the current window, so hand out that one rather than the token frozen into its+ // launch config.+ ...(bootstrap.desktopBootstrapSecret+ ? { bootstrapToken: yield* configuration.currentBootstrapToken }+ : bootstrap.desktopBootstrapToken+ ? { bootstrapToken: bootstrap.desktopBootstrapToken }+ : {}),+ });+ }+ return bootstraps;+});++export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({+ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,+ result: Schema.Array(DesktopEnvironmentBootstrapSchema),+ handler: readLocalEnvironmentBootstrapSnapshot,+});++export const readLocalEnvironmentBootstraps = DesktopIpc.makeIpcMethod({+ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,+ payload: Schema.Void,+ result: Schema.Array(DesktopEnvironmentBootstrapSchema),+ handler: readLocalEnvironmentBootstrapSnapshot,});function extractWslDistroFromEnvironmentId(envId: string): string | null {diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex bffa02d9ca4..9fe0e9efa15 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -12,6 +12,7 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";import * as IpcChannels from "./ipc/channels.ts";import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";+import { createPreloadSnapshot } from "./preloadSnapshot.ts";const SNAP_SHOT_EVENT_TYPES = new Set(["requested",@@ -74,6 +75,18 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;}+const readBootstraps = (+ result: unknown,+): ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]> =>+ Array.isArray(result) ? result : [];+const localEnvironmentBootstraps = createPreloadSnapshot(+ () => readBootstraps(ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),+ async () =>+ readBootstraps(await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),+);+// Changes take effect on relaunch, so renderer reads can reuse the startup value.+let localEnvironmentEnabled: boolean | undefined;+contextBridge.exposeInMainWorld("desktopBridge", {getAppBranding: () => {const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL);@@ -103,17 +116,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);return typeof result === "string" ? result : null;},- getLocalEnvironmentBootstraps: () => {- const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);- if (!Array.isArray(result)) {- return [];- }- return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;- },+ getLocalEnvironmentBootstraps: localEnvironmentBootstraps.read,+ readLocalEnvironmentBootstraps: localEnvironmentBootstraps.refresh,getLocalEnvironmentBearerToken: () =>ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),getLocalEnvironmentEnabled: () =>- ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false,+ (localEnvironmentEnabled ??=+ ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false),setLocalEnvironmentEnabled: (enabled) =>ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled),getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),diff --git a/apps/desktop/src/preloadSnapshot.test.ts b/apps/desktop/src/preloadSnapshot.test.tsnew file mode 100644index 00000000000..05783e83003--- /dev/null+++ b/apps/desktop/src/preloadSnapshot.test.ts@@ -0,0 +1,45 @@+import { expect, it, vi } from "vite-plus/test";++import { createPreloadSnapshot } from "./preloadSnapshot.ts";++it("serves the startup snapshot while a shared asynchronous refresh is pending", async () => {+ const initial = ["primary"];+ const latest = Promise.withResolvers<string[]>();+ const readInitial = vi.fn(() => initial);+ const readLatest = vi.fn(() => latest.promise);+ const snapshot = createPreloadSnapshot(readInitial, readLatest);++ expect(snapshot.read()).toBe(initial);+ const first = snapshot.refresh();+ const second = snapshot.refresh();+ expect(snapshot.read()).toBe(initial);+ expect(snapshot.read()).toBe(initial);+ expect(readInitial).toHaveBeenCalledTimes(1);+ expect(readLatest).toHaveBeenCalledTimes(1);++ const connected = ["primary", "wsl"];+ latest.resolve(connected);+ expect(await first).toBe(connected);+ expect(await second).toBe(connected);+ expect(snapshot.read()).toBe(connected);+ expect(readInitial).toHaveBeenCalledTimes(1);+});++it("retains an async snapshot through failure and replaces it on successful recovery", async () => {+ const connected = ["primary", "wsl"];+ const readInitial = vi.fn(() => ["stale"]);+ const readLatest = vi+ .fn<() => Promise<string[]>>()+ .mockResolvedValueOnce(connected)+ .mockRejectedValueOnce(new Error("IPC unavailable"))+ .mockResolvedValueOnce([]);+ const snapshot = createPreloadSnapshot(readInitial, readLatest);++ await snapshot.refresh();+ expect(snapshot.read()).toBe(connected);+ await expect(snapshot.refresh()).rejects.toThrow("IPC unavailable");+ expect(snapshot.read()).toBe(connected);+ await expect(snapshot.refresh()).resolves.toEqual([]);+ expect(snapshot.read()).toEqual([]);+ expect(readInitial).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/preloadSnapshot.ts b/apps/desktop/src/preloadSnapshot.tsnew file mode 100644index 00000000000..4fe34b2719f--- /dev/null+++ b/apps/desktop/src/preloadSnapshot.ts@@ -0,0 +1,23 @@+export function createPreloadSnapshot<T>(readInitial: () => T, readLatest: () => Promise<T>) {+ let snapshot: { readonly value: T } | undefined;+ let pending: Promise<T> | undefined;++ return {+ read: () => {+ snapshot ??= { value: readInitial() };+ return snapshot.value;+ },+ refresh: () => {+ if (pending !== undefined) return pending;+ pending = readLatest()+ .then((value) => {+ snapshot = { value };+ return value;+ })+ .finally(() => {+ pending = undefined;+ });+ return pending;+ },+ };+}diff --git a/apps/web/src/connection/desktopLocal.test.ts b/apps/web/src/connection/desktopLocal.test.tsindex 7a31aa18209..e8a5496ad8a 100644--- a/apps/web/src/connection/desktopLocal.test.ts+++ b/apps/web/src/connection/desktopLocal.test.ts@@ -7,7 +7,7 @@ import {EnvironmentId,PRIMARY_LOCAL_ENVIRONMENT_ID,} from "@t3tools/contracts";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import {createDesktopSecondaryBootstrapsReader,@@ -55,7 +55,52 @@ describe("desktop local connection identity", () => {});describe("desktop local topology reads", () => {- it("reuses snapshots when polling returns fresh objects for the same topology", () => {+ it("refreshes topology asynchronously, retaining identity through unchanged reads and failures", async () => {+ const secondary: DesktopEnvironmentBootstrap = {+ id: "wsl:default",+ label: "WSL",+ runningDistro: "Ubuntu",+ httpBaseUrl: "http://127.0.0.1:4000",+ wsBaseUrl: "ws://127.0.0.1:4000",+ bootstrapToken: "bootstrap-1",+ };+ let entries = [secondary, { ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }];+ let cached = entries;+ const getLocalEnvironmentBootstraps = vi.fn(() => cached);+ const readLocalEnvironmentBootstraps = vi.fn(async () => {+ cached = entries.map((entry) => ({ ...entry }));+ return cached;+ });+ const reader = createDesktopSecondaryBootstrapsReader(() => ({+ getLocalEnvironmentBootstraps,+ readLocalEnvironmentBootstraps,+ }));++ const connected = await reader.refresh();+ expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] });+ expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();+ if (connected._tag !== "Success") throw new Error("expected connected topology");++ const unchanged = await reader.refresh();+ if (unchanged._tag !== "Success") throw new Error("expected unchanged topology");+ expect(unchanged.bootstraps).toBe(connected.bootstraps);+ expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();+ expect(reader.readSnapshot()).toBe(connected.bootstraps);++ const cause = new Error("IPC unavailable");+ readLocalEnvironmentBootstraps.mockRejectedValueOnce(cause);+ expect(await reader.refresh()).toEqual({ _tag: "Failure", cause });+ expect(reader.readSnapshot()).toBe(connected.bootstraps);++ entries = [];+ const removed = await reader.refresh();+ expect(removed).toEqual({ _tag: "Success", bootstraps: [] });+ if (removed._tag !== "Success") throw new Error("expected empty topology");+ expect(reader.readSnapshot()).toBe(removed.bootstraps);+ expect(removed.bootstraps).not.toBe(connected.bootstraps);+ });++ it("reuses snapshots when polling returns fresh objects for the same topology", async () => {const secondary: DesktopEnvironmentBootstrap = {id: "wsl:default",label: "WSL",@@ -70,11 +115,16 @@ describe("desktop local topology reads", () => {}));const connected = reader.readSnapshot();+ const refreshed = await reader.refresh();+ expect(refreshed).toEqual({ _tag: "Success", bootstraps: [secondary] });+ if (refreshed._tag !== "Success") throw new Error("expected legacy topology");+ expect(refreshed.bootstraps).toBe(connected);expect(reader.readSnapshot()).toBe(connected);expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: connected });expect(reader.readSnapshot()).toBe(connected);entries = [];+ expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] });const empty = reader.readSnapshot();expect(empty).toEqual([]);expect(reader.readSnapshot()).toBe(empty);diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.tsindex 57f9495521c..85abb94b9bd 100644--- a/apps/web/src/connection/desktopLocal.ts+++ b/apps/web/src/connection/desktopLocal.ts@@ -47,6 +47,7 @@ export type DesktopSecondaryBootstrapsRead =export interface DesktopSecondaryBootstrapsReader {readonly readResult: () => DesktopSecondaryBootstrapsRead;+ readonly refresh: () => Promise<DesktopSecondaryBootstrapsRead>;readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;}@@ -55,10 +56,36 @@ export interface DesktopSecondaryBootstrapsReader {* consumers cannot temporarily disagree with the platform's retained registrations.*/export function createDesktopSecondaryBootstrapsReader(- resolveBridge: () => Pick<DesktopBridge, "getLocalEnvironmentBootstraps"> | undefined,+ resolveBridge: () =>+ | Pick<DesktopBridge, "getLocalEnvironmentBootstraps" | "readLocalEnvironmentBootstraps">+ | undefined,): DesktopSecondaryBootstrapsReader {let snapshot: ReadonlyArray<DesktopEnvironmentBootstrap> = [];+ const updateSnapshot = (+ entries: ReadonlyArray<DesktopEnvironmentBootstrap>,+ ): DesktopSecondaryBootstrapsRead => {+ const next = entries.filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);+ if (+ next.length !== snapshot.length ||+ next.some((entry, index) => {+ const previous = snapshot[index];+ return (+ previous === undefined ||+ entry.id !== previous.id ||+ entry.label !== previous.label ||+ entry.runningDistro !== previous.runningDistro ||+ entry.httpBaseUrl !== previous.httpBaseUrl ||+ entry.wsBaseUrl !== previous.wsBaseUrl ||+ entry.bootstrapToken !== previous.bootstrapToken+ );+ })+ ) {+ snapshot = next;+ }+ return { _tag: "Success", bootstraps: snapshot };+ };+const readResult = (): DesktopSecondaryBootstrapsRead => {const bridge = resolveBridge();if (bridge === undefined) {@@ -66,27 +93,7 @@ export function createDesktopSecondaryBootstrapsReader(return { _tag: "Success", bootstraps: snapshot };}try {- const next = bridge- .getLocalEnvironmentBootstraps()- .filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);- if (- next.length !== snapshot.length ||- next.some((entry, index) => {- const previous = snapshot[index];- return (- previous === undefined ||- entry.id !== previous.id ||- entry.label !== previous.label ||- entry.runningDistro !== previous.runningDistro ||- entry.httpBaseUrl !== previous.httpBaseUrl ||- entry.wsBaseUrl !== previous.wsBaseUrl ||- entry.bootstrapToken !== previous.bootstrapToken- );- })- ) {- snapshot = next;- }- return { _tag: "Success", bootstraps: snapshot };+ return updateSnapshot(bridge.getLocalEnvironmentBootstraps());} catch (cause) {return { _tag: "Failure", cause };}@@ -94,6 +101,15 @@ export function createDesktopSecondaryBootstrapsReader(return {readResult,+ refresh: async () => {+ const bridge = resolveBridge();+ if (bridge?.readLocalEnvironmentBootstraps === undefined) return readResult();+ try {+ return updateSnapshot(await bridge.readLocalEnvironmentBootstraps());+ } catch (cause) {+ return { _tag: "Failure", cause };+ }+ },readSnapshot: () => {const result = readResult();return result._tag === "Success" ? result.bootstraps : snapshot;@@ -105,8 +121,8 @@ const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader(() => window.desktopBridge,);-export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {- return desktopSecondaryBootstrapsReader.readResult();+export function readDesktopSecondaryBootstrapsResult(): Promise<DesktopSecondaryBootstrapsRead> {+ return desktopSecondaryBootstrapsReader.refresh();}export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex 0f3a263f611..24ca4804415 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -640,7 +640,7 @@ const layerPlatformConnectionSource = Layer.effect(}}- const topologyRead = readDesktopSecondaryBootstrapsResult();+ const topologyRead = yield* Effect.promise(readDesktopSecondaryBootstrapsResult);for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(previous,topologyRead,diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.mdindex 3ac6703ad6a..6b6fa927ab8 100644--- a/docs/internals/performance-regressions.md+++ b/docs/internals/performance-regressions.md@@ -98,7 +98,10 @@ viewport, including a small overscan region. Cached badges remain available whilreleased. Local Git status reads skip divergence calculations; callers that need ahead/behindcounts keep the full status path. Cached fetch failures share the existing backoff and log onlythe actual failed attempt. Unchanged desktop environment bootstrap reads retain their array-identity so polling does not invalidate subscribers.+identity so polling does not invalidate subscribers. The desktop preload keeps the synchronous+startup snapshot, while topology polling refreshes it through asynchronous IPC. Recurring+`sendSync` calls block the renderer behind unrelated main-process work, even when the returned+snapshot is unchanged.Local trace records and provider event logs use asynchronous, serialized file writes and rotation.Batching synchronous appends still stalls the server event loop on slow storage, especially ondiff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 4cf76a56c37..50da7ed9391 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1046,6 +1046,8 @@ export interface DesktopBridge {*/getSystemLocale?: () => string | null;getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];+ /** Refresh the preload snapshot without blocking the renderer on synchronous IPC. */+ readLocalEnvironmentBootstraps?: () => Promise<readonly DesktopEnvironmentBootstrap[]>;getLocalEnvironmentEnabled?: () => boolean;setLocalEnvironmentEnabled?: (enabled: boolean) => Promise<void>;getLocalEnvironmentBearerToken: () => Promise<string>;