diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 6a1b1c62e7471..d13b46bb5b30c 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -8,6 +8,7 @@ import { getConnectionCatalog, setConnectionCatalog } from "./methods/connection import { getHostEnvironmentId, getLocalEnvironmentEnabled, + getLocalEnvironmentEnabledSync, setLocalEnvironmentEnabled, } from "./methods/localEnvironment.ts"; import { @@ -36,6 +37,7 @@ import { import { getAppBranding, getLocalEnvironmentBootstraps, + getLocalEnvironmentBootstrapsSync, getLocalEnvironmentBearerToken, installRelayTelemetryEnabled, getSystemLocale, @@ -100,8 +102,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getPreferredSystemLanguages); yield* ipc.handleSync(getWindowFullscreenState); - yield* ipc.handleSync(getLocalEnvironmentBootstraps); - yield* ipc.handleSync(getLocalEnvironmentEnabled); + // Topology polls answer from the renderer's snapshot; sync serves only its first, pre-reply read. + yield* ipc.handle(getLocalEnvironmentBootstraps); + yield* ipc.handle(getLocalEnvironmentEnabled); + yield* ipc.handleSync(getLocalEnvironmentBootstrapsSync); + yield* ipc.handleSync(getLocalEnvironmentEnabledSync); yield* ipc.handle(setLocalEnvironmentEnabled); yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 33dd9e272df7d..4179531ab9cd4 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -38,7 +38,11 @@ export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry- export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps"; +export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_SYNC_CHANNEL = + "desktop:get-local-environment-bootstraps-sync"; export const GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:get-local-environment-enabled"; +export const GET_LOCAL_ENVIRONMENT_ENABLED_SYNC_CHANNEL = + "desktop:get-local-environment-enabled-sync"; export const SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:set-local-environment-enabled"; export const GET_HOST_ENVIRONMENT_ID_CHANNEL = "desktop:get-host-environment-id"; export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL = diff --git a/apps/desktop/src/ipc/methods/localEnvironment.test.ts b/apps/desktop/src/ipc/methods/localEnvironment.test.ts index 36e89eb880c15..c46c7dff0954a 100644 --- a/apps/desktop/src/ipc/methods/localEnvironment.test.ts +++ b/apps/desktop/src/ipc/methods/localEnvironment.test.ts @@ -71,12 +71,12 @@ describe("local environment IPC", () => { ); return Effect.gen(function* () { yield* setLocalEnvironmentEnabled.handler(false); - assert.isFalse(yield* getLocalEnvironmentEnabled.handler()); + assert.isFalse(yield* getLocalEnvironmentEnabled.handler(undefined)); yield* setLocalEnvironmentEnabled.handler(false); assert.deepEqual(relaunchReasons, ["localEnvironmentEnabled=false"]); yield* setLocalEnvironmentEnabled.handler(true); - assert.isTrue(yield* getLocalEnvironmentEnabled.handler()); + assert.isTrue(yield* getLocalEnvironmentEnabled.handler(undefined)); const appSettings = yield* DesktopAppSettings.DesktopAppSettings; assert.isTrue((yield* appSettings.get).wslBackendEnabled); assert.deepEqual(relaunchReasons, [ diff --git a/apps/desktop/src/ipc/methods/localEnvironment.ts b/apps/desktop/src/ipc/methods/localEnvironment.ts index 3c5c2c63d77da..ffc75819deb90 100644 --- a/apps/desktop/src/ipc/methods/localEnvironment.ts +++ b/apps/desktop/src/ipc/methods/localEnvironment.ts @@ -8,13 +8,24 @@ import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as IpcChannels from "../channels.ts"; import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts"; -export const getLocalEnvironmentEnabled = makeSyncIpcMethod({ - channel: IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, - result: Schema.Boolean, - handler: Effect.fn("desktop.ipc.localEnvironment.getEnabled")(function* () { +const readLocalEnvironmentEnabled = Effect.fn("desktop.ipc.localEnvironment.getEnabled")( + function* () { const appSettings = yield* DesktopAppSettings.DesktopAppSettings; return (yield* appSettings.get).localEnvironmentEnabled; - }), + }, +); + +export const getLocalEnvironmentEnabled = makeIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, + payload: Schema.Void, + result: Schema.Boolean, + handler: () => readLocalEnvironmentEnabled(), +}); + +export const getLocalEnvironmentEnabledSync = makeSyncIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_SYNC_CHANNEL, + result: Schema.Boolean, + handler: () => readLocalEnvironmentEnabled(), }); export const setLocalEnvironmentEnabled = makeIpcMethod({ diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 376f85d2baf9d..02e5a7609f488 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -93,7 +93,7 @@ const bootstrapsLayer = (instances: ReadonlyArray { it.effect("hands out the current window's token to a backend launched with the secret", () => Effect.gen(function* () { - const result = yield* getLocalEnvironmentBootstraps.handler(); + const result = yield* getLocalEnvironmentBootstraps.handler(undefined); assert.deepEqual(result, [ { @@ -145,7 +145,7 @@ describe("getLocalEnvironmentBootstraps", () => { }; return Effect.gen(function* () { - const result = yield* getLocalEnvironmentBootstraps.handler(); + const result = yield* getLocalEnvironmentBootstraps.handler(undefined); assert.deepEqual(result, [ { id: "wsl:default", @@ -179,7 +179,7 @@ describe("getLocalEnvironmentBootstraps", () => { }; return Effect.gen(function* () { - const result = yield* getLocalEnvironmentBootstraps.handler(); + const result = yield* getLocalEnvironmentBootstraps.handler(undefined); assert.deepEqual(result, []); }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance]))); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index e0eea5c74c9ed..16d276e635ea8 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -125,55 +125,66 @@ 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 readLocalEnvironmentBootstraps = 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), - // Use the current window's derived token; the launch config's token may be stale. - ...(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), + // Use the current window's derived token; the launch config's token may be stale. + ...(bootstrap.desktopBootstrapSecret + ? { bootstrapToken: yield* configuration.currentBootstrapToken } + : bootstrap.desktopBootstrapToken + ? { bootstrapToken: bootstrap.desktopBootstrapToken } + : {}), + }); + } + return bootstraps; +}); + +export const getLocalEnvironmentBootstraps = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL, + payload: Schema.Void, + result: Schema.Array(DesktopEnvironmentBootstrapSchema), + handler: () => readLocalEnvironmentBootstraps(), +}); + +export const getLocalEnvironmentBootstrapsSync = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_SYNC_CHANNEL, + result: Schema.Array(DesktopEnvironmentBootstrapSchema), + handler: () => readLocalEnvironmentBootstraps(), }); function extractWslDistroFromEnvironmentId(envId: string): string | null { diff --git a/apps/desktop/src/preload.test.ts b/apps/desktop/src/preload.test.ts new file mode 100644 index 0000000000000..dd9c1318ad7fe --- /dev/null +++ b/apps/desktop/src/preload.test.ts @@ -0,0 +1,110 @@ +import type { DesktopBridge } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import * as IpcChannels from "./ipc/channels.ts"; + +const { sendSync, invoke, exposed } = vi.hoisted(() => ({ + sendSync: vi.fn(), + invoke: vi.fn(), + exposed: {} as Record, +})); + +vi.mock("electron", () => ({ + contextBridge: { + exposeInMainWorld: (_name: string, bridge: Record) => { + for (const key of Object.keys(exposed)) delete exposed[key]; + Object.assign(exposed, bridge); + }, + }, + ipcRenderer: { sendSync, invoke, on: vi.fn(), removeListener: vi.fn() }, + webFrame: { getZoomFactor: () => 1 }, + webUtils: { getPathForFile: vi.fn() }, +})); + +vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() })); + +vi.stubGlobal("window", { addEventListener: vi.fn(), localStorage: {} }); +vi.stubGlobal("document", { + addEventListener: vi.fn(), + fullscreenElement: null, + documentElement: { style: { setProperty: vi.fn() } }, +}); + +const bootstraps = [ + { + id: "primary", + label: "Primary", + runningDistro: null, + httpBaseUrl: "http://127.0.0.1:3773/", + wsBaseUrl: "ws://127.0.0.1:3773/", + }, +]; + +let refresh: { resolve: (value: unknown) => void } | undefined; +let failingRefreshes = false; + +const answerRefresh = (channel: string): Promise => { + if (channel !== IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL) { + return Promise.resolve(undefined); + } + if (failingRefreshes) return Promise.reject(new Error("ipc unavailable")); + return new Promise((resolve) => { + refresh = { resolve }; + }); +}; + +// Either topology channel: the cold read moved to its own one, but every call still blocks. +const topologySyncCalls = () => + sendSync.mock.calls.filter(([name]) => String(name).includes("local-environment")); + +// The refresh only exists when the preload asks for it; the sync path never does. +const resolveRefresh = (value: unknown) => refresh?.resolve(value); + +// The refresh resolves through invoke().then().catch().finally(); three turns reach the assignment. +const drainRefresh = async () => { + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); +}; + +const loadBridge = async () => { + vi.resetModules(); + sendSync.mockReset(); + invoke.mockReset(); + refresh = undefined; + failingRefreshes = false; + sendSync.mockImplementation((channel: string) => + String(channel).includes("local-environment-bootstraps") ? [] : null, + ); + invoke.mockImplementation(answerRefresh); + await import("./preload.ts"); + return exposed as unknown as DesktopBridge; +}; + +describe("preload topology snapshots", () => { + it("answers later reads from the snapshot instead of sendSync", async () => { + const bridge = await loadBridge(); + + expect(bridge.getLocalEnvironmentBootstraps()).toEqual([]); + expect(topologySyncCalls()).toHaveLength(1); + + resolveRefresh(bootstraps); + await drainRefresh(); + + expect(bridge.getLocalEnvironmentBootstraps()).toEqual(bootstraps); + expect(topologySyncCalls()).toHaveLength(1); + }); + + it("keeps the last snapshot when a refresh fails", async () => { + const bridge = await loadBridge(); + + bridge.getLocalEnvironmentBootstraps(); + expect(topologySyncCalls()).toHaveLength(1); + resolveRefresh(bootstraps); + await drainRefresh(); + failingRefreshes = true; + + expect(bridge.getLocalEnvironmentBootstraps()).toEqual(bootstraps); + expect(topologySyncCalls()).toHaveLength(1); + }); +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 5bf05668b5a98..3ebb371e8b56b 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -86,6 +86,65 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) { return result as Awaited>; } +/** + * Every topology poll used to run sendSync, so a busy main process stalled the renderer's + * UI thread and dropped keystrokes. Reads answer from the last snapshot and refresh it in + * the background; sendSync survives only for the first read, which lands before the first + * reply and must still see the real value. + */ +function makeSnapshotReader( + asyncChannel: string, + syncChannel: string, + decode: (value: unknown) => T | undefined, +): () => T | undefined { + let snapshot: T | undefined; + let refreshing = false; + const refresh = () => { + if (refreshing) return; + refreshing = true; + try { + void ipcRenderer + .invoke(asyncChannel) + .then((value) => { + const next = decode(value); + if (next !== undefined) snapshot = next; + }) + .catch(() => undefined) + .finally(() => { + refreshing = false; + }); + } catch { + refreshing = false; + } + }; + // Warm the snapshot before the page's first read, so that read usually skips sendSync too. + refresh(); + return () => { + if (snapshot === undefined) { + try { + const cold = decode(ipcRenderer.sendSync(syncChannel)); + if (cold !== undefined) snapshot = cold; + } catch {} + } + refresh(); + return snapshot; + }; +} + +const readLocalEnvironmentBootstraps = makeSnapshotReader( + IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL, + IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_SYNC_CHANNEL, + (value) => + Array.isArray(value) + ? (value as ReturnType) + : undefined, +); +const readLocalEnvironmentEnabled = makeSnapshotReader( + IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, + IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_SYNC_CHANNEL, + (value) => (typeof value === "boolean" ? value : undefined), +); + contextBridge.exposeInMainWorld("desktopBridge", { getAppBranding: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL); @@ -126,17 +185,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { ); return Array.isArray(result) ? result.filter((tag) => typeof tag === "string") : []; }, - getLocalEnvironmentBootstraps: () => { - const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL); - if (!Array.isArray(result)) { - return []; - } - return result as ReturnType; - }, + getLocalEnvironmentBootstraps: () => readLocalEnvironmentBootstraps() ?? [], getLocalEnvironmentBearerToken: () => ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL), - getLocalEnvironmentEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false, + getLocalEnvironmentEnabled: () => readLocalEnvironmentEnabled() ?? true, setLocalEnvironmentEnabled: (enabled) => ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled), getHostEnvironmentId: () => ipcRenderer.invoke(IpcChannels.GET_HOST_ENVIRONMENT_ID_CHANNEL),