Open History to see the last commit
1import type { AdvertisedEndpoint, DesktopBridge, DesktopWslState } from "@t3tools/contracts";
2
3type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
4
5/**
6 * A QR code encoding a loopback URL makes the scanning device dial itself, so
7 * loopback endpoints stay copyable from the endpoint menu but are never
8 * offered as QR targets.
9 */
10export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
11 return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
12}
13
14export function isWslSettingsRowVisible(input: {
15 readonly state: DesktopWslState | null;
16 readonly error: string | null;
17}): boolean {
18 const { state, error } = input;
19 return state ? state.available || state.enabled || state.wslOnly : error !== null;
20}
21
22export type QrEndpointOption = {
23 /** Unique per endpoint instance (AdvertisedEndpoint.id); safe as a React key. */
24 readonly id: string;
25 /**
26 * Stable per endpoint *type* (endpointDefaultPreferenceKey). Multiple
27 * endpoints can share one, so it is only used to match the saved default.
28 */
29 readonly preferenceKey: string;
30 /** False for endpoints that stay copyable but must never render as a QR. */
31 readonly qrShareable: boolean;
32};
33
34/**
35 * Resolves which endpoint the share panel shows: the user's explicit pick,
36 * else the saved default endpoint, else the first QR-shareable option (so the
37 * panel never opens on a loopback QR), else the first option. A stale
38 * selectedId (endpoint disappeared) falls back rather than blanking the panel.
39 */
40export function selectQrEndpointOption<T extends QrEndpointOption>(
41 options: ReadonlyArray<T>,
42 selectedId: string | null,
43 defaultPreferenceKey: string | null,
44): T | null {
45 return (
46 (selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
47 (defaultPreferenceKey !== null
48 ? options.find((option) => option.preferenceKey === defaultPreferenceKey)
49 : undefined) ??
50 options.find((option) => option.qrShareable) ??
51 options[0] ??
52 null
53 );
54}
55
56export async function applyWslEnableSelection(input: {
57 readonly bridge: WslEnableBridge;
58 readonly mode: "both" | "wsl-only";
59 readonly nextDistro: string | null;
60 readonly persistedDistro: string | null;
61}): Promise<DesktopWslState> {
62 const { bridge, mode, nextDistro, persistedDistro } = input;
63
64 // Stage every preference before enabling. The desktop only relaunches for
65 // mode/distro changes while WSL is active, so the final enable observes the
66 // complete selection and is the only call that may relaunch.
67 await bridge.setWslOnly(mode === "wsl-only");
68 if (persistedDistro !== nextDistro) {
69 await bridge.setWslDistro(nextDistro);
70 }
71 return await bridge.setWslBackendEnabled(true);
72}