Skip to content
Closed
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
9 changes: 7 additions & 2 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { getConnectionCatalog, setConnectionCatalog } from "./methods/connection
import {
getHostEnvironmentId,
getLocalEnvironmentEnabled,
getLocalEnvironmentEnabledSync,
setLocalEnvironmentEnabled,
} from "./methods/localEnvironment.ts";
import {
Expand Down Expand Up @@ -36,6 +37,7 @@ import {
import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBootstrapsSync,
getLocalEnvironmentBearerToken,
installRelayTelemetryEnabled,
getSystemLocale,
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/ipc/methods/localEnvironment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, [
Expand Down
21 changes: 16 additions & 5 deletions apps/desktop/src/ipc/methods/localEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
6 changes: 3 additions & 3 deletions apps/desktop/src/ipc/methods/window.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopB
describe("getLocalEnvironmentBootstraps", () => {
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, [
{
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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])));
});
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 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 {
Expand Down
110 changes: 110 additions & 0 deletions apps/desktop/src/preload.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>,
}));

vi.mock("electron", () => ({
contextBridge: {
exposeInMainWorld: (_name: string, bridge: Record<string, unknown>) => {
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<unknown> => {
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);
});
});
Loading
Loading