Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBootstrapsAsync,
getLocalEnvironmentBearerToken,
installRelayTelemetryEnabled,
getSystemLocale,
Expand Down Expand Up @@ -101,6 +102,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getPreferredSystemLanguages);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBootstrapsAsync);
yield* ipc.handleSync(getLocalEnvironmentEnabled);
yield* ipc.handle(setLocalEnvironmentEnabled);
yield* ipc.handle(getHostEnvironmentId);
Expand Down
101 changes: 56 additions & 45 deletions apps/desktop/src/ipc/methods/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 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),
// 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.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
handler: readLocalEnvironmentBootstrapSnapshot,
});

export const getLocalEnvironmentBootstrapsAsync = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
handler: readLocalEnvironmentBootstrapSnapshot,
});

function extractWslDistroFromEnvironmentId(envId: string): string | null {
Expand Down
67 changes: 67 additions & 0 deletions apps/desktop/src/preload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { ipcRenderer } from "electron";
import { expect, it, vi } from "vite-plus/test";

import * as IpcChannels from "./ipc/channels.ts";

const { exposed, sendSync } = vi.hoisted(() => ({
exposed: new Map<string, unknown>(),
sendSync: vi.fn((channel: string): unknown =>
channel === "desktop:get-local-environment-enabled" ? true : [],
),
}));

vi.mock("electron", () => ({
contextBridge: {
exposeInMainWorld: (key: string, api: unknown) => exposed.set(key, api),
},
ipcRenderer: {
sendSync,
invoke: vi.fn(async () => undefined),
on: vi.fn(),
removeListener: vi.fn(),
},
webFrame: { getZoomFactor: () => 1 },
webUtils: { getPathForFile: () => "" },
}));
vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() }));

it("topology polling reads the cache and refreshes it without synchronous IPC", async () => {
vi.stubGlobal("window", {
addEventListener: () => {},
localStorage: { getItem: () => null, setItem: () => {} },
});
vi.stubGlobal("document", {
addEventListener: () => {},
fullscreenElement: null,
documentElement: { style: { setProperty: () => {} } },
});
await import("./preload.ts");
const bridge = exposed.get("desktopBridge") as DesktopBridge;
sendSync.mockClear();

// sendSync freezes the renderer until main answers; only the first read may use it.
for (let poll = 0; poll < 5; poll += 1) {
bridge.getLocalEnvironmentBootstraps();
bridge.getLocalEnvironmentEnabled();
}
const syncCalls = (channel: string) =>
sendSync.mock.calls.filter(([called]) => called === channel).length;
expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)).toBeLessThanOrEqual(1);
expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1);

const wsl = {
id: "wsl:Ubuntu",
label: "WSL (Ubuntu)",
runningDistro: "Ubuntu",
httpBaseUrl: "http://127.0.0.1:4000/",
wsBaseUrl: "ws://127.0.0.1:4000/",
};
vi.mocked(ipcRenderer.invoke).mockResolvedValueOnce([wsl]).mockResolvedValueOnce([]);
sendSync.mockClear();
await bridge.refreshLocalEnvironmentBootstraps?.();
expect(bridge.getLocalEnvironmentBootstraps()).toEqual([wsl]);
await bridge.refreshLocalEnvironmentBootstraps?.();
expect(bridge.getLocalEnvironmentBootstraps()).toEqual([]);
expect(sendSync).not.toHaveBeenCalled();
});
30 changes: 22 additions & 8 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,18 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}

const readBootstraps = (
result: unknown,
): ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]> =>
Array.isArray(result) ? result : [];
// sendSync blocks the renderer until the main process answers, so it runs once for the first
// paint; topology polling refreshes this cache over async IPC instead.
let localEnvironmentBootstraps:
| ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>
| undefined;
// 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);
Expand Down Expand Up @@ -125,17 +137,19 @@ 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<DesktopBridge["getLocalEnvironmentBootstraps"]>;
},
getLocalEnvironmentBootstraps: () =>
(localEnvironmentBootstraps ??= readBootstraps(
ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL),
)),
refreshLocalEnvironmentBootstraps: async () =>
(localEnvironmentBootstraps = readBootstraps(
await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL),
)),
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),
getHostEnvironmentId: () => ipcRenderer.invoke(IpcChannels.GET_HOST_ENVIRONMENT_ID_CHANNEL),
Expand Down
30 changes: 30 additions & 0 deletions apps/web/src/connection/desktopLocal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,36 @@ import { describe, expect, it } from "vite-plus/test";
import { createDesktopSecondaryBootstrapsReader } from "./desktopLocal";

describe("desktop local topology reads", () => {
it("refreshes topology over the async bridge read, keeping the snapshot through failures", async () => {
const secondary: DesktopEnvironmentBootstrap = {
id: "wsl:Ubuntu",
label: "WSL (Ubuntu)",
runningDistro: "Ubuntu",
httpBaseUrl: "http://127.0.0.1:4000",
wsBaseUrl: "ws://127.0.0.1:4000",
};
let cached: ReadonlyArray<DesktopEnvironmentBootstrap> = [];
let refresh = async () => [{ ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }, secondary];
const reader = createDesktopSecondaryBootstrapsReader(() => ({
getLocalEnvironmentBootstraps: () => cached,
refreshLocalEnvironmentBootstraps: async () => (cached = await refresh()),
}));

expect(reader.readSnapshot()).toEqual([]);
const connected = await reader.refresh();
expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] });
expect(reader.readSnapshot()).toEqual([secondary]);

const cause = new Error("IPC unavailable");
refresh = () => Promise.reject(cause);
expect(await reader.refresh()).toEqual({ _tag: "Failure", cause });
expect(reader.readSnapshot()).toEqual([secondary]);

refresh = async () => [];
expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] });
expect(reader.readSnapshot()).toEqual([]);
});

it("reuses snapshots when polling returns fresh objects for the same topology", () => {
const secondary: DesktopEnvironmentBootstrap = {
id: "wsl:default",
Expand Down
64 changes: 40 additions & 24 deletions apps/web/src/connection/desktopLocal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,50 +38,66 @@ export type DesktopSecondaryBootstrapsRead =

export interface DesktopSecondaryBootstrapsReader {
readonly readResult: () => DesktopSecondaryBootstrapsRead;
readonly refresh: () => Promise<DesktopSecondaryBootstrapsRead>;
readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;
}

/** Empty reads clear the snapshot; failed reads retain platform registrations. */
export function createDesktopSecondaryBootstrapsReader(
resolveBridge: () => Pick<DesktopBridge, "getLocalEnvironmentBootstraps"> | undefined,
resolveBridge: () =>
| Pick<DesktopBridge, "getLocalEnvironmentBootstraps" | "refreshLocalEnvironmentBootstraps">
| 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) {
if (snapshot.length > 0) snapshot = [];
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 };
}
};

return {
readResult,
refresh: async () => {
const bridge = resolveBridge();
if (bridge?.refreshLocalEnvironmentBootstraps === undefined) return readResult();
try {
return updateSnapshot(await bridge.refreshLocalEnvironmentBootstraps());
} catch (cause) {
return { _tag: "Failure", cause };
}
},
readSnapshot: () => {
const result = readResult();
return result._tag === "Success" ? result.bootstraps : snapshot;
Expand All @@ -93,8 +109,8 @@ const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader(
() => window.desktopBridge,
);

export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {
return desktopSecondaryBootstrapsReader.readResult();
export function refreshDesktopSecondaryBootstraps(): Promise<DesktopSecondaryBootstrapsRead> {
return desktopSecondaryBootstrapsReader.refresh();
}

export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
Expand Down
Loading
Loading