# Files changed · PR \#19300 · pingdotgg/t3code

[View on GitCafe](https://git.cafe/pingdotgg/t3code/pull/19300/diffs)

Repository: [pingdotgg/t3code](https://git.cafe/pingdotgg/t3code)

Visibility: public

[fix\(desktop\): stop blocking the renderer during topology polling](https://git.cafe/pingdotgg/t3code/pull/19300.md)

Version: 3

Head commit: 362656905f7733df5bb71504607aa6b21ce4d668

Base commit: 55ba1baa559ee73b9db177da07f56000774371f2

Comparison base: 55ba1baa559ee73b9db177da07f56000774371f2

Showing up to 20 entries from this revision. If the pull request changes, reopen the first page before continuing.

## apps/desktop/src/ipc/DesktopIpcHandlers.ts

Status: modified; +2; −0

```diff
@@ -40,6 +40,7 @@
 import {
   getAppBranding,
   getLocalEnvironmentBootstraps,
+  readLocalEnvironmentBootstraps,
   getLocalEnvironmentBearerToken,
   getRelayTelemetryEnabled,
   getSystemLocale,
@@ -100,6 +101,7 @@
   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);
```

## apps/desktop/src/ipc/methods/window.ts

Status: modified; +58; −47

```diff
@@ -99,59 +99,70 @@
   }),
 });
 
+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;
-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;
       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;
     }
+    const { bootstrap, httpBaseUrl } = config.value;
+    const runningDistro = config.value.runningDistro ?? null;
-    return bootstraps;
+    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 {
   if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
     return null;
```

## apps/desktop/src/preload.ts

Status: modified; +17; −8

```diff
@@ -12,6 +12,7 @@
 
 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 @@
   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 @@
     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: () =>
+    (localEnvironmentEnabled ??=
+      ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false),
-    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),
```

## apps/desktop/src/preloadSnapshot.test.ts

Status: added; +45; −0

```diff
@@ -1,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();
+});
```

## apps/desktop/src/preloadSnapshot.ts

Status: added; +23; −0

```diff
@@ -1,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;
+    },
+  };
+}
```

## apps/web/src/connection/desktopLocal.test.ts

Status: modified; +52; −2

```diff
@@ -7,7 +7,7 @@
   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,7 @@
 });
 
 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",
@@ -64,17 +64,67 @@
       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",
+      runningDistro: "Ubuntu",
+      httpBaseUrl: "http://127.0.0.1:4000",
+      wsBaseUrl: "ws://127.0.0.1:4000",
+      bootstrapToken: "bootstrap-1",
+    };
     let entries = [secondary];
     const reader = createDesktopSecondaryBootstrapsReader(() => ({
       getLocalEnvironmentBootstraps: () => entries.map((entry) => ({ ...entry })),
     }));
 
     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);
```

## apps/web/src/connection/desktopLocal.ts

Status: modified; +40; −24

```diff
@@ -47,6 +47,7 @@
 
 export interface DesktopSecondaryBootstrapsReader {
   readonly readResult: () => DesktopSecondaryBootstrapsRead;
+  readonly refresh: () => Promise<DesktopSecondaryBootstrapsRead>;
   readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;
 }
 
@@ -55,10 +56,36 @@
  * 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 @@
       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 @@
 
   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 @@
   () => window.desktopBridge,
 );
 
-export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {
-  return desktopSecondaryBootstrapsReader.readResult();
+export function readDesktopSecondaryBootstrapsResult(): Promise<DesktopSecondaryBootstrapsRead> {
+  return desktopSecondaryBootstrapsReader.refresh();
 }
 
 export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
```

## apps/web/src/connection/platform.ts

Status: modified; +1; −1

```diff
@@ -640,7 +640,7 @@
         }
       }
 
-      const topologyRead = readDesktopSecondaryBootstrapsResult();
+      const topologyRead = yield* Effect.promise(readDesktopSecondaryBootstrapsResult);
       for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
         previous,
         topologyRead,
```

## docs/internals/performance-regressions.md

Status: modified; +4; −1

```diff
@@ -98,7 +98,10 @@
 released. Local Git status reads skip divergence calculations; callers that need ahead/behind
 counts keep the full status path. Cached fetch failures share the existing backoff and log only
 the actual failed attempt. Unchanged desktop environment bootstrap reads retain their array
+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
-identity so polling does not invalidate subscribers.
+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 on
```

## packages/contracts/src/ipc.ts

Status: modified; +2; −0

```diff
@@ -1046,6 +1046,8 @@
    */
   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>;
```
