Skip to content

Commit d977005

Browse files
daniyal-shjuliusmarminge
authored andcommitted
fix(desktop): stop blocking the renderer during topology polling (#19300)
Co-authored-by: Julius Marminge <[email protected]> (cherry picked from commit 6bcbb95)
1 parent f9c1d02 commit d977005

10 files changed

Lines changed: 244 additions & 83 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
import {
4141
getAppBranding,
4242
getLocalEnvironmentBootstraps,
43+
readLocalEnvironmentBootstraps,
4344
getLocalEnvironmentBearerToken,
4445
getRelayTelemetryEnabled,
4546
getSystemLocale,
@@ -100,6 +101,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
100101
yield* ipc.handleSync(getSystemLocale);
101102
yield* ipc.handleSync(getWindowFullscreenState);
102103
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
104+
yield* ipc.handle(readLocalEnvironmentBootstraps);
103105
yield* ipc.handleSync(getLocalEnvironmentEnabled);
104106
yield* ipc.handle(setLocalEnvironmentEnabled);
105107
yield* ipc.handle(getLocalEnvironmentBearerToken);

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

Lines changed: 58 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -99,57 +99,68 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
9999
}),
100100
});
101101

102-
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
103-
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
104-
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
105-
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
106-
const pool = yield* DesktopBackendPool.DesktopBackendPool;
107-
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
108-
const instances = yield* pool.list;
109-
const bootstraps: DesktopEnvironmentBootstrap[] = [];
110-
for (const instance of instances) {
111-
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
112-
const config = yield* instance.currentConfig;
113-
const snapshot = yield* instance.snapshot;
114-
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
115-
const fatalPreflight =
116-
Option.isSome(config) &&
117-
Option.isSome(config.value.preflightFailure) &&
118-
config.value.preflightFailure.value.fatal;
119-
const stoppedPreflight =
120-
Option.isSome(config) &&
121-
Option.isSome(config.value.preflightFailure) &&
122-
(!snapshot.desiredRunning || !snapshot.restartScheduled);
123-
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
124-
bootstraps.push({
125-
id: instance.id,
126-
label: yield* instance.label,
127-
runningDistro: null,
128-
httpBaseUrl: null,
129-
wsBaseUrl: null,
130-
});
131-
continue;
132-
}
133-
const { bootstrap, httpBaseUrl } = config.value;
134-
const runningDistro = config.value.runningDistro ?? null;
102+
const readLocalEnvironmentBootstrapSnapshot = Effect.fn(
103+
"desktop.ipc.window.getLocalEnvironmentBootstraps",
104+
)(function* () {
105+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
106+
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
107+
const instances = yield* pool.list;
108+
const bootstraps: DesktopEnvironmentBootstrap[] = [];
109+
for (const instance of instances) {
110+
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
111+
const config = yield* instance.currentConfig;
112+
const snapshot = yield* instance.snapshot;
113+
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
114+
const fatalPreflight =
115+
Option.isSome(config) &&
116+
Option.isSome(config.value.preflightFailure) &&
117+
config.value.preflightFailure.value.fatal;
118+
const stoppedPreflight =
119+
Option.isSome(config) &&
120+
Option.isSome(config.value.preflightFailure) &&
121+
(!snapshot.desiredRunning || !snapshot.restartScheduled);
122+
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
135123
bootstraps.push({
136124
id: instance.id,
137-
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
138-
runningDistro,
139-
httpBaseUrl: httpBaseUrl.href,
140-
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
141-
// A backend launched with the desktop secret accepts whichever token the secret derives
142-
// for the current window, so hand out that one rather than the token frozen into its
143-
// launch config.
144-
...(bootstrap.desktopBootstrapSecret
145-
? { bootstrapToken: yield* configuration.currentBootstrapToken }
146-
: bootstrap.desktopBootstrapToken
147-
? { bootstrapToken: bootstrap.desktopBootstrapToken }
148-
: {}),
125+
label: yield* instance.label,
126+
runningDistro: null,
127+
httpBaseUrl: null,
128+
wsBaseUrl: null,
149129
});
130+
continue;
150131
}
151-
return bootstraps;
152-
}),
132+
const { bootstrap, httpBaseUrl } = config.value;
133+
const runningDistro = config.value.runningDistro ?? null;
134+
bootstraps.push({
135+
id: instance.id,
136+
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
137+
runningDistro,
138+
httpBaseUrl: httpBaseUrl.href,
139+
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
140+
// A backend launched with the desktop secret accepts whichever token the secret derives
141+
// for the current window, so hand out that one rather than the token frozen into its
142+
// launch config.
143+
...(bootstrap.desktopBootstrapSecret
144+
? { bootstrapToken: yield* configuration.currentBootstrapToken }
145+
: bootstrap.desktopBootstrapToken
146+
? { bootstrapToken: bootstrap.desktopBootstrapToken }
147+
: {}),
148+
});
149+
}
150+
return bootstraps;
151+
});
152+
153+
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
154+
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
155+
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
156+
handler: readLocalEnvironmentBootstrapSnapshot,
157+
});
158+
159+
export const readLocalEnvironmentBootstraps = DesktopIpc.makeIpcMethod({
160+
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
161+
payload: Schema.Void,
162+
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
163+
handler: readLocalEnvironmentBootstrapSnapshot,
153164
});
154165

155166
function extractWslDistroFromEnvironmentId(envId: string): string | null {

‎apps/desktop/src/preload.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
1212

1313
import * as IpcChannels from "./ipc/channels.ts";
1414
import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";
15+
import { createPreloadSnapshot } from "./preloadSnapshot.ts";
1516

1617
const SNAP_SHOT_EVENT_TYPES = new Set([
1718
"requested",
@@ -74,6 +75,18 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
7475
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
7576
}
7677

78+
const readBootstraps = (
79+
result: unknown,
80+
): ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]> =>
81+
Array.isArray(result) ? result : [];
82+
const localEnvironmentBootstraps = createPreloadSnapshot(
83+
() => readBootstraps(ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
84+
async () =>
85+
readBootstraps(await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
86+
);
87+
// Changes take effect on relaunch, so renderer reads can reuse the startup value.
88+
let localEnvironmentEnabled: boolean | undefined;
89+
7790
contextBridge.exposeInMainWorld("desktopBridge", {
7891
getAppBranding: () => {
7992
const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL);
@@ -103,17 +116,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {
103116
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
104117
return typeof result === "string" ? result : null;
105118
},
106-
getLocalEnvironmentBootstraps: () => {
107-
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
108-
if (!Array.isArray(result)) {
109-
return [];
110-
}
111-
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
112-
},
119+
getLocalEnvironmentBootstraps: localEnvironmentBootstraps.read,
120+
readLocalEnvironmentBootstraps: localEnvironmentBootstraps.refresh,
113121
getLocalEnvironmentBearerToken: () =>
114122
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
115123
getLocalEnvironmentEnabled: () =>
116-
ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false,
124+
(localEnvironmentEnabled ??=
125+
ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false),
117126
setLocalEnvironmentEnabled: (enabled) =>
118127
ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled),
119128
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { expect, it, vi } from "vite-plus/test";
2+
3+
import { createPreloadSnapshot } from "./preloadSnapshot.ts";
4+
5+
it("serves the startup snapshot while a shared asynchronous refresh is pending", async () => {
6+
const initial = ["primary"];
7+
const latest = Promise.withResolvers<string[]>();
8+
const readInitial = vi.fn(() => initial);
9+
const readLatest = vi.fn(() => latest.promise);
10+
const snapshot = createPreloadSnapshot(readInitial, readLatest);
11+
12+
expect(snapshot.read()).toBe(initial);
13+
const first = snapshot.refresh();
14+
const second = snapshot.refresh();
15+
expect(snapshot.read()).toBe(initial);
16+
expect(snapshot.read()).toBe(initial);
17+
expect(readInitial).toHaveBeenCalledTimes(1);
18+
expect(readLatest).toHaveBeenCalledTimes(1);
19+
20+
const connected = ["primary", "wsl"];
21+
latest.resolve(connected);
22+
expect(await first).toBe(connected);
23+
expect(await second).toBe(connected);
24+
expect(snapshot.read()).toBe(connected);
25+
expect(readInitial).toHaveBeenCalledTimes(1);
26+
});
27+
28+
it("retains an async snapshot through failure and replaces it on successful recovery", async () => {
29+
const connected = ["primary", "wsl"];
30+
const readInitial = vi.fn(() => ["stale"]);
31+
const readLatest = vi
32+
.fn<() => Promise<string[]>>()
33+
.mockResolvedValueOnce(connected)
34+
.mockRejectedValueOnce(new Error("IPC unavailable"))
35+
.mockResolvedValueOnce([]);
36+
const snapshot = createPreloadSnapshot(readInitial, readLatest);
37+
38+
await snapshot.refresh();
39+
expect(snapshot.read()).toBe(connected);
40+
await expect(snapshot.refresh()).rejects.toThrow("IPC unavailable");
41+
expect(snapshot.read()).toBe(connected);
42+
await expect(snapshot.refresh()).resolves.toEqual([]);
43+
expect(snapshot.read()).toEqual([]);
44+
expect(readInitial).not.toHaveBeenCalled();
45+
});
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export function createPreloadSnapshot<T>(readInitial: () => T, readLatest: () => Promise<T>) {
2+
let snapshot: { readonly value: T } | undefined;
3+
let pending: Promise<T> | undefined;
4+
5+
return {
6+
read: () => {
7+
snapshot ??= { value: readInitial() };
8+
return snapshot.value;
9+
},
10+
refresh: () => {
11+
if (pending !== undefined) return pending;
12+
pending = readLatest()
13+
.then((value) => {
14+
snapshot = { value };
15+
return value;
16+
})
17+
.finally(() => {
18+
pending = undefined;
19+
});
20+
return pending;
21+
},
22+
};
23+
}

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

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,55 @@
11
import { type DesktopEnvironmentBootstrap, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
2-
import { describe, expect, it } from "vite-plus/test";
2+
import { describe, expect, it, vi } from "vite-plus/test";
33

44
import { createDesktopSecondaryBootstrapsReader } from "./desktopLocal";
55

66
describe("desktop local topology reads", () => {
7-
it("reuses snapshots when polling returns fresh objects for the same topology", () => {
7+
it("refreshes topology asynchronously, retaining identity through unchanged reads and failures", async () => {
8+
const secondary: DesktopEnvironmentBootstrap = {
9+
id: "wsl:default",
10+
label: "WSL",
11+
runningDistro: "Ubuntu",
12+
httpBaseUrl: "http://127.0.0.1:4000",
13+
wsBaseUrl: "ws://127.0.0.1:4000",
14+
bootstrapToken: "bootstrap-1",
15+
};
16+
let entries = [secondary, { ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }];
17+
let cached = entries;
18+
const getLocalEnvironmentBootstraps = vi.fn(() => cached);
19+
const readLocalEnvironmentBootstraps = vi.fn(async () => {
20+
cached = entries.map((entry) => ({ ...entry }));
21+
return cached;
22+
});
23+
const reader = createDesktopSecondaryBootstrapsReader(() => ({
24+
getLocalEnvironmentBootstraps,
25+
readLocalEnvironmentBootstraps,
26+
}));
27+
28+
const connected = await reader.refresh();
29+
expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] });
30+
expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
31+
if (connected._tag !== "Success") throw new Error("expected connected topology");
32+
33+
const unchanged = await reader.refresh();
34+
if (unchanged._tag !== "Success") throw new Error("expected unchanged topology");
35+
expect(unchanged.bootstraps).toBe(connected.bootstraps);
36+
expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
37+
expect(reader.readSnapshot()).toBe(connected.bootstraps);
38+
39+
const cause = new Error("IPC unavailable");
40+
readLocalEnvironmentBootstraps.mockRejectedValueOnce(cause);
41+
expect(await reader.refresh()).toEqual({ _tag: "Failure", cause });
42+
expect(reader.readSnapshot()).toBe(connected.bootstraps);
43+
44+
entries = [];
45+
const removed = await reader.refresh();
46+
expect(removed).toEqual({ _tag: "Success", bootstraps: [] });
47+
if (removed._tag !== "Success") throw new Error("expected empty topology");
48+
expect(reader.readSnapshot()).toBe(removed.bootstraps);
49+
expect(removed.bootstraps).not.toBe(connected.bootstraps);
50+
});
51+
52+
it("reuses snapshots when polling returns fresh objects for the same topology", async () => {
853
const secondary: DesktopEnvironmentBootstrap = {
954
id: "wsl:default",
1055
label: "WSL",
@@ -19,11 +64,16 @@ describe("desktop local topology reads", () => {
1964
}));
2065

2166
const connected = reader.readSnapshot();
67+
const refreshed = await reader.refresh();
68+
expect(refreshed).toEqual({ _tag: "Success", bootstraps: [secondary] });
69+
if (refreshed._tag !== "Success") throw new Error("expected legacy topology");
70+
expect(refreshed.bootstraps).toBe(connected);
2271
expect(reader.readSnapshot()).toBe(connected);
2372
expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: connected });
2473
expect(reader.readSnapshot()).toBe(connected);
2574

2675
entries = [];
76+
expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] });
2777
const empty = reader.readSnapshot();
2878
expect(empty).toEqual([]);
2979
expect(reader.readSnapshot()).toBe(empty);

0 commit comments

Comments
 (0)