Skip to content
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type { DesktopWslState } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import {
applyWslEnableSelection,
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
} from "./ConnectionsSettings.logic";

const baseWslState: DesktopWslState = {
enabled: false,
Expand All @@ -11,6 +16,25 @@ const baseWslState: DesktopWslState = {
preflightError: null,
};

describe("isWslSettingsRowVisible", () => {
it("shows the retry row when the WSL state failed to load", () => {
expect(isWslSettingsRowVisible({ state: null, error: "load failed" })).toBe(true);
});

it("hides an unavailable and unused WSL snapshot", () => {
expect(
isWslSettingsRowVisible({
state: { ...baseWslState, available: false, wslOnly: false },
error: null,
}),
).toBe(false);
});

it("shows an available WSL snapshot", () => {
expect(isWslSettingsRowVisible({ state: baseWslState, error: null })).toBe(true);
});
});

describe("applyWslEnableSelection", () => {
it("clears WSL-only and updates the distro before enabling both backends", async () => {
const calls: Array<string> = [];
Expand Down
51 changes: 51 additions & 0 deletions apps/web/src/components/settings/ConnectionsSettings.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,57 @@ import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts";

type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;

/**
* A QR code encoding a loopback URL makes the scanning device dial itself, so
* loopback endpoints stay copyable from the endpoint menu but are never
* offered as QR targets.
*/
export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
}

export function isWslSettingsRowVisible(input: {
readonly state: DesktopWslState | null;
readonly error: string | null;
}): boolean {
const { state, error } = input;
return state ? state.available || state.enabled || state.wslOnly : error !== null;
}

export type QrEndpointOption = {
/** Unique per endpoint instance (AdvertisedEndpoint.id); safe as a React key. */
readonly id: string;
/**
* Stable per endpoint *type* (endpointDefaultPreferenceKey). Multiple
* endpoints can share one, so it is only used to match the saved default.
*/
readonly preferenceKey: string;
/** False for endpoints that stay copyable but must never render as a QR. */
readonly qrShareable: boolean;
};

/**
* Resolves which endpoint the share panel shows: the user's explicit pick,
* else the saved default endpoint, else the first QR-shareable option (so the
* panel never opens on a loopback QR), else the first option. A stale
* selectedId (endpoint disappeared) falls back rather than blanking the panel.
*/
export function selectQrEndpointOption<T extends QrEndpointOption>(
options: ReadonlyArray<T>,
selectedId: string | null,
defaultPreferenceKey: string | null,
): T | null {
return (
(selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
(defaultPreferenceKey !== null
? options.find((option) => option.preferenceKey === defaultPreferenceKey)
: undefined) ??
options.find((option) => option.qrShareable) ??
options[0] ??
null
);
}

export async function applyWslEnableSelection(input: {
readonly bridge: WslEnableBridge;
readonly mode: "both" | "wsl-only";
Expand Down
22 changes: 16 additions & 6 deletions apps/web/src/components/settings/ConnectionsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { cn } from "../../lib/utils";
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import {
applyWslEnableSelection,
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
} from "./ConnectionsSettings.logic";
import {
SettingsPageContainer,
SettingsRow,
Expand Down Expand Up @@ -2747,10 +2752,13 @@ export function ConnectionsSettings() {
// retry so the row doesn't flicker away, and the button reflects the
// loading state. With no error we simply haven't loaded yet (or WSL
// management isn't available), so render nothing.
if (desktopWslError && canManageLocalBackend) {
if (
isWslSettingsRowVisible({ state: null, error: desktopWslError }) &&
canManageLocalBackend
) {
return (
<SettingsRow
title="WSL backend"
{...searchableSetting("wsl-backend")}
description="Couldn't load the WSL backend state."
status={<span className="block text-destructive">{desktopWslError}</span>}
control={
Expand All @@ -2775,11 +2783,13 @@ export function ConnectionsSettings() {
// be stranded on a WSL preference they can't clear, so render a recovery
// row that switches back to Windows. When WSL is unavailable AND unused,
// there's nothing to recover — keep the section hidden as before.
if (!isWslSettingsRowVisible({ state: desktopWslState, error: desktopWslError })) {
return null;
}
if (!desktopWslState.available) {
if (!desktopWslState.enabled && !desktopWslState.wslOnly) return null;
return (
<SettingsRow
title="WSL backend"
{...searchableSetting("wsl-backend")}
description="WSL is no longer available, so the Windows backend is running instead. Switch off the WSL backend to clear this preference."
status={
desktopWslError ? (
Expand Down Expand Up @@ -2816,7 +2826,7 @@ export function ConnectionsSettings() {
return (
<>
<SettingsRow
title="WSL backend"
{...searchableSetting("wsl-backend")}
description="Run a second backend inside a WSL distro alongside the Windows one. Pick a distro to start it; pick Off to stop it. Projects opened against the WSL backend live on the Linux side; Windows projects stay where they are."
status={
desktopWslError ? (
Expand Down
23 changes: 22 additions & 1 deletion apps/web/src/components/settings/SettingsSidebarNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
type ComponentType,
type KeyboardEvent,
} from "react";
import { useEnvironmentQuery } from "~/state/query";
import { desktopWslStateAtom } from "~/state/desktopWslState";
import {
ArchiveIcon,
ArrowLeftIcon,
Expand All @@ -22,6 +24,8 @@ import {
} from "lucide-react";
import { useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";

import { isElectron } from "~/env";
import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Kbd } from "../ui/kbd";
Expand All @@ -38,6 +42,7 @@ import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3Conne
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
SETTINGS_SEARCH_ITEMS,
SETTINGS_SECTION_LABELS,
type SettingsPath,
type SettingsSearchItem,
Expand Down Expand Up @@ -79,10 +84,26 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const searchInputRef = useRef<HTMLInputElement>(null);
const [query, setQuery] = useState("");
const [activeResultIndex, setActiveResultIndex] = useState(0);
const results = useMemo(() => searchSettings(query), [query]);
const desktopWsl = useEnvironmentQuery(isElectron ? desktopWslStateAtom : null);
const searchableItems = useMemo(() => {
const wslState = desktopWsl.data;
const rowRenders = isWslSettingsRowVisible({
state: wslState,
error: desktopWsl.error,
});
if (rowRenders) {
return SETTINGS_SEARCH_ITEMS;
}
return SETTINGS_SEARCH_ITEMS.filter((item) => item.id !== "wsl-backend");
}, [desktopWsl.data, desktopWsl.error]);
const results = useMemo(() => searchSettings(query, searchableItems), [query, searchableItems]);
const isSearching = query.trim().length > 0;
const hasResults = results.length > 0;

useEffect(() => {
setActiveResultIndex((index) => Math.min(index, Math.max(results.length - 1, 0)));
}, [results.length]);
Comment on lines +103 to +105

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the selected result when WSL visibility changes

When the asynchronous WSL query inserts or removes its search item, clamping only the numeric index can silently select a different setting. For example, with the broad query e, if “Archived threads” is selected while WSL is absent, inserting “WSL backend” immediately before it leaves the index unchanged but makes WSL active, so pressing Enter opens the wrong setting. Preserve the active result by ID or reset the selection when result identities or ordering change.

Useful? React with 👍 / 👎.


useEffect(() => {
const result = results[activeResultIndex];
if (!result) return;
Expand Down
9 changes: 9 additions & 0 deletions apps/web/src/components/settings/settingsSearch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ describe("searchSettings", () => {
expect(searchSettings(" ", ITEMS)).toEqual([]);
});

it("registers the WSL backend as a desktop-only setting", () => {
expect(SETTINGS_SEARCH_ITEMS).toContainEqual({
id: "wsl-backend",
title: "WSL backend",
to: "/settings/connections",
desktopOnly: true,
windowsOnly: true,
});
});
it("keeps catalog result ids unique", () => {
const ids = SETTINGS_SEARCH_ITEMS.map((item) => item.id);
expect(new Set(ids).size).toBe(ids.length);
Expand Down
23 changes: 22 additions & 1 deletion apps/web/src/components/settings/settingsSearch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isElectron } from "~/env";
import { isWindowsPlatform } from "~/lib/utils";
export type SettingsPath =
| "/settings/general"
| "/settings/appearance"
Expand All @@ -13,6 +15,12 @@ export interface SettingsSearchItem {
readonly title: string;
readonly to: SettingsPath;
readonly targetId?: string;
// Its row only renders in the desktop app, so a browser result would land on
// an anchor that isn't there.
readonly desktopOnly?: boolean;
// Its row only renders on Windows desktop, so other desktop platforms must
// not expose a result that points to a missing anchor.
readonly windowsOnly?: boolean;
}

/**
Expand Down Expand Up @@ -167,6 +175,13 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/beta",
targetId: "sidebar-v2",
},
{
id: "wsl-backend",
title: "WSL backend",
to: "/settings/connections",
desktopOnly: true,
windowsOnly: true,
},
{
id: "archive",
title: "Archived threads",
Expand Down Expand Up @@ -209,5 +224,11 @@ export function searchSettings(
const normalizedQuery = normalizeSearchText(query);
if (normalizedQuery.length === 0) return [];

return items.filter((item) => normalizeSearchText(item.title).includes(normalizedQuery));
return items.filter(
(item) =>
(isElectron || item.desktopOnly !== true) &&
(!item.windowsOnly ||
isWindowsPlatform(typeof navigator === "undefined" ? "" : navigator.platform)) &&
normalizeSearchText(item.title).includes(normalizedQuery),
);
}
Loading