feat(web): make pairing QR codes actually scannable, with endpoint choice (#5360)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 authored and GitHub committed 2026-08-04 16:53:54 -07:00
1 parent da6e1a9678
commit fff6a5b028
3 files changed
+314 -188

No files matched your search

@@ -1,6 +1,10 @@
import type { DesktopWslState } from "@t3tools/contracts";
import type { AdvertisedEndpoint, DesktopWslState } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import {
applyWslEnableSelection,
isQrShareableEndpoint,
selectQrEndpointOption,
} from "./ConnectionsSettings.logic";
const baseWslState: DesktopWslState = {
enabled: false,
@@ -73,3 +77,89 @@ describe("applyWslEnableSelection", () => {
expect(state).toMatchObject({ enabled: true, wslOnly: true });
});
});
function makeEndpoint(overrides: Partial<AdvertisedEndpoint>): AdvertisedEndpoint {
return {
id: "desktop-lan:http://192.168.1.42:4780",
label: "Local network",
provider: { id: "desktop-core", label: "Desktop", kind: "core", isAddon: false },
httpBaseUrl: "http://192.168.1.42:4780",
wsBaseUrl: "ws://192.168.1.42:4780",
reachability: "lan",
compatibility: { hostedHttpsApp: "unknown", desktopApp: "compatible" },
source: "desktop-core",
status: "available",
...overrides,
};
}
describe("isQrShareableEndpoint", () => {
it("excludes loopback endpoints so a scanned phone never dials itself", () => {
expect(
isQrShareableEndpoint(
makeEndpoint({
id: "desktop-loopback:4780",
reachability: "loopback",
httpBaseUrl: "http://127.0.0.1:4780",
}),
),
).toBe(false);
});
it("excludes unavailable endpoints and keeps reachable ones", () => {
expect(isQrShareableEndpoint(makeEndpoint({ status: "unavailable" }))).toBe(false);
expect(isQrShareableEndpoint(makeEndpoint({}))).toBe(true);
expect(
isQrShareableEndpoint(makeEndpoint({ reachability: "private-network", status: "unknown" })),
).toBe(true);
});
});
describe("selectQrEndpointOption", () => {
const options = [
{
id: "desktop-loopback:4780",
preferenceKey: "desktop-core:loopback:http",
qrShareable: false,
},
{
id: "tailscale-ip:http://100.84.12.7:4780",
preferenceKey: "tailscale:ip:http",
qrShareable: true,
},
{
id: "tailscale-ip:http://100.84.12.8:4780",
preferenceKey: "tailscale:ip:http",
qrShareable: true,
},
{
id: "desktop-lan:http://192.168.1.42:4780",
preferenceKey: "desktop-core:lan:http",
qrShareable: true,
},
];
it("resolves an explicit selection by unique endpoint id, not the shared preference key", () => {
expect(selectQrEndpointOption(options, "tailscale-ip:http://100.84.12.8:4780", null)?.id).toBe(
"tailscale-ip:http://100.84.12.8:4780",
);
});
it("falls back to the saved default preference key when nothing is selected", () => {
expect(selectQrEndpointOption(options, null, "desktop-core:lan:http")?.id).toBe(
"desktop-lan:http://192.168.1.42:4780",
);
});
it("skips non-QR-shareable options in the fallback so the panel never opens on loopback", () => {
expect(selectQrEndpointOption(options, "tailscale-ip:gone", "nope")?.id).toBe(
"tailscale-ip:http://100.84.12.7:4780",
);
});
it("returns the first option when nothing is QR-shareable, and null when empty", () => {
const loopbackOnly = options.slice(0, 1);
expect(selectQrEndpointOption(loopbackOnly, null, null)?.id).toBe("desktop-loopback:4780");
expect(selectQrEndpointOption([], "anything", "anything")).toBeNull();
});
});
@@ -1,7 +1,50 @@
import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts";
import type { AdvertisedEndpoint, 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 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";
@@ -1,5 +1,4 @@
import {
ChevronDownIcon,
ChevronsLeftRightEllipsisIcon,
PlusIcon,
QrCodeIcon,
@@ -8,7 +7,7 @@ import {
TriangleAlertIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { type ReactNode, memo, useCallback, useMemo, useState } from "react";
import { type ReactNode, memo, useCallback, useId, useMemo, useState } from "react";
import {
AuthAccessReadScope,
AuthAccessWriteScope,
@@ -42,7 +41,11 @@ 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,
selectQrEndpointOption,
} from "./ConnectionsSettings.logic";
import {
SettingsPageContainer,
SettingsRow,
@@ -82,17 +85,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { Group, GroupSeparator } from "../ui/group";
import { AnimatedHeight } from "../AnimatedHeight";
import {
Menu,
MenuGroup,
MenuGroupLabel,
MenuItem,
MenuPopup,
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
import { Textarea } from "../ui/textarea";
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";
import { readHostedPairingRequest } from "../../hostedPairing";
@@ -506,6 +499,22 @@ function isHostedAppPairingUrl(value: string): boolean {
}
}
function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
if (isHostedAppPairingUrl(url)) {
return "Opens the hosted app, no install needed";
}
switch (endpoint.reachability) {
case "lan":
return "Devices on the same network";
case "private-network":
return "Devices on your private network";
case "public":
return "Reachable from anywhere";
case "loopback":
return "Clients on this machine";
}
}
type PairingLinkListRowProps = {
pairingLink: ServerPairingLinkRecord;
endpointUrl: string | null | undefined;
@@ -531,6 +540,11 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
[pairingLink.expiresAt],
);
const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
const [isQrPanelOpen, setIsQrPanelOpen] = useState(false);
// Ephemeral per-row choice of which endpoint the QR encodes (AdvertisedEndpoint.id);
// null falls back to the saved default endpoint.
const [qrEndpointId, setQrEndpointId] = useState<string | null>(null);
const qrPanelId = useId();
const currentOriginPairingUrl = useMemo(
() => resolveCurrentOriginPairingUrl(pairingLink.credential),
@@ -549,10 +563,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
}, [defaultEndpointKey, endpoints, pairingLink.credential]);
const endpointCopyOptions = useMemo(() => {
const options: Array<{
readonly key: string;
readonly id: string;
readonly preferenceKey: string;
readonly label: string;
readonly url: string;
readonly detail: string;
readonly qrShareable: boolean;
}> = [];
for (const endpoint of endpoints) {
if (endpoint.status === "unavailable") {
@@ -560,10 +576,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
}
const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential);
options.push({
key: endpointDefaultPreferenceKey(endpoint),
id: endpoint.id,
preferenceKey: endpointDefaultPreferenceKey(endpoint),
label: endpoint.label,
url,
detail: isHostedAppPairingUrl(url) ? "Hosted app link" : "Backend pairing URL",
detail: endpointShareHint(endpoint, url),
qrShareable: isQrShareableEndpoint(endpoint),
});
}
return options;
@@ -575,16 +593,25 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
: isLoopbackHostname(window.location.hostname)
? null
: currentOriginPairingUrl);
const revealValue = shareablePairingUrl ?? pairingLink.credential;
const isShareableHostedAppPairingUrl =
shareablePairingUrl !== null && isHostedAppPairingUrl(shareablePairingUrl);
// Value of the copy attempt that last failed. The clipboard-failure reveal
// dialog must show exactly what failed to copy, not the row's default URL.
const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
const revealValue = failedCopyValue ?? shareablePairingUrl ?? pairingLink.credential;
const isRevealValueUrl = revealValue !== pairingLink.credential;
const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);
// Never render a QR for a loopback URL, even in the manual-copy fallback.
const isRevealValueQrShareable =
endpointCopyOptions.find((option) => option.url === revealValue)?.qrShareable ?? true;
const canCopyToClipboard =
typeof window !== "undefined" &&
window.isSecureContext &&
navigator.clipboard?.writeText != null;
const { copyToClipboard } = useCopyToClipboard<"code" | "hosted-link" | "link">({
onCopy: (kind) => {
const { copyToClipboard } = useCopyToClipboard<{
value: string;
kind: "code" | "hosted-link" | "link";
}>({
onCopy: ({ kind }) => {
toastManager.add({
type: "success",
title:
@@ -601,7 +628,10 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
: "Paste it into another client to finish pairing.",
});
},
onError: (error, kind) => {
onError: (error, { value, kind }) => {
// Captured per attempt so concurrent copies cannot make the dialog
// reveal a different value than the one that failed.
setFailedCopyValue(value);
setIsRevealDialogOpen(true);
toastManager.add(
stackedThreadToast({
@@ -621,7 +651,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
const copyPairingValue = useCallback(
(value: string, kind: "code" | "hosted-link" | "link") => {
copyToClipboard(value, kind);
copyToClipboard(value, { value, kind });
},
[copyToClipboard],
);
@@ -635,97 +665,19 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
copyPairingValue(pairingLink.credential, "code");
}, [copyPairingValue, pairingLink.credential]);
const handleCopyDefaultLink = useCallback(() => {
if (!shareablePairingUrl) return;
copyPairingValue(shareablePairingUrl, copyKindForUrl(shareablePairingUrl));
}, [copyKindForUrl, copyPairingValue, shareablePairingUrl]);
const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
const primaryLabel = pairingLink.label ?? "Pairing link";
const defaultEndpointCopyOption =
endpointCopyOptions.find((option) => option.key === defaultEndpointKey) ??
endpointCopyOptions[0] ??
null;
const defaultEndpointCopyLabel = defaultEndpointCopyOption?.label ?? "URL";
const backendEndpointCopyOptions = endpointCopyOptions.filter(
(option) => !isHostedAppPairingUrl(option.url),
const selectedQrOption = selectQrEndpointOption(
endpointCopyOptions,
qrEndpointId,
defaultEndpointKey,
);
const hostedEndpointCopyOptions = endpointCopyOptions.filter((option) =>
isHostedAppPairingUrl(option.url),
);
const renderEndpointMenuItems = (
options: typeof endpointCopyOptions = endpointCopyOptions,
renderDetail = true,
) =>
options.map((option) => (
<MenuItem
key={option.key}
onClick={() => copyPairingValue(option.url, copyKindForUrl(option.url))}
>
<span className="min-w-0 flex-1">
<span className="block truncate">{option.label}</span>
{renderDetail ? (
<span className="block truncate text-[11px] text-muted-foreground">
{option.detail}
</span>
) : null}
</span>
</MenuItem>
));
const renderPairingCodeMenuItem = (renderDetail = true) => (
<MenuItem onClick={handleCopyCode}>
<span className="min-w-0 flex-1">
<span className="block truncate">Copy code</span>
{renderDetail ? (
<span className="block truncate text-[11px] text-muted-foreground">Token only</span>
) : null}
</span>
</MenuItem>
);
const renderCompactEndpointGroup = (
label: string,
options: typeof endpointCopyOptions,
includeSeparator: boolean,
) =>
options.length > 0 ? (
<>
{includeSeparator ? <MenuSeparator /> : null}
<MenuGroup>
<MenuGroupLabel>{label}</MenuGroupLabel>
{renderEndpointMenuItems(options, false)}
</MenuGroup>
</>
) : null;
const renderGroupedCopyMenuItems = (options?: { codeFirst?: boolean }) => (
<>
{options?.codeFirst ? (
<>
<MenuGroup>
<MenuGroupLabel>Pairing code</MenuGroupLabel>
{renderPairingCodeMenuItem(false)}
</MenuGroup>
{endpointCopyOptions.length > 0 ? <MenuSeparator /> : null}
</>
) : null}
{renderCompactEndpointGroup("Pairing URLs", backendEndpointCopyOptions, false)}
{renderCompactEndpointGroup(
"Hosted app link",
hostedEndpointCopyOptions,
backendEndpointCopyOptions.length > 0,
)}
{!options?.codeFirst ? (
<>
{endpointCopyOptions.length > 0 ? <MenuSeparator /> : null}
<MenuGroup>
<MenuGroupLabel>Pairing code</MenuGroupLabel>
{renderPairingCodeMenuItem(false)}
</MenuGroup>
</>
) : null}
</>
);
const qrPairingUrl = selectedQrOption?.url ?? shareablePairingUrl;
// With no endpoint list the fallback is never loopback: selectPairingEndpoint
// skips loopback and the current-origin fallback is guarded by
// isLoopbackHostname, so only an explicit loopback selection hides the QR.
const canRenderQrForSelection = selectedQrOption?.qrShareable ?? true;
if (expiresAtMs <= nowMs) {
return null;
}
@@ -740,35 +692,6 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
dotClassName="bg-amber-400"
/>
<h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
<Popover>
{shareablePairingUrl ? (
<>
<PopoverTrigger
openOnHover
delay={250}
closeDelay={100}
render={
<button
type="button"
className="inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground/50 outline-none hover:text-foreground"
aria-label="Show QR code"
/>
}
>
<QrCodeIcon aria-hidden className="size-3" />
</PopoverTrigger>
<PopoverPopup side="top" align="start" tooltipStyle className="w-max">
<QRCodeSvg
value={shareablePairingUrl}
size={88}
level="M"
marginSize={2}
title="Pairing link — scan to open on another device"
/>
</PopoverPopup>
</>
) : null}
</Popover>
</div>
<p className="text-xs text-muted-foreground" title={expiresAbsolute}>
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
@@ -782,46 +705,31 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
) : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
<Dialog open={isRevealDialogOpen} onOpenChange={setIsRevealDialogOpen}>
{shareablePairingUrl && canCopyToClipboard ? (
<Button
size="xs"
variant="outline"
aria-expanded={isQrPanelOpen}
aria-controls={qrPanelId}
onClick={() => setIsQrPanelOpen((open) => !open)}
>
<QrCodeIcon aria-hidden />
Share
</Button>
) : null}
<Dialog
open={isRevealDialogOpen}
onOpenChange={(open) => {
setIsRevealDialogOpen(open);
if (!open) setFailedCopyValue(null);
}}
>
{canCopyToClipboard ? (
<>
{shareablePairingUrl ? (
<Group aria-label="Copy selected endpoint">
<Button
size="xs"
variant="outline"
className="max-w-56"
title={`Copy pairing URL for: ${defaultEndpointCopyLabel}`}
onClick={handleCopyDefaultLink}
>
<span className="truncate">
Copy pairing URL for: {defaultEndpointCopyLabel}
</span>
</Button>
<GroupSeparator />
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="outline"
aria-label="Choose endpoint to copy"
/>
}
>
<ChevronDownIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end" className="min-w-60">
{renderGroupedCopyMenuItems()}
</MenuPopup>
</Menu>
</Group>
) : (
<Button size="xs" variant="outline" onClick={handleCopyCode}>
Copy code
</Button>
)}
</>
shareablePairingUrl ? null : (
<Button size="xs" variant="outline" onClick={handleCopyCode}>
Copy code
</Button>
)
) : (
<DialogTrigger render={<Button size="xs" variant="outline" />}>
{shareablePairingUrl ? "Show link" : "Show code"}
@@ -830,15 +738,15 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
<DialogPopup className="max-w-md">
<DialogHeader>
<DialogTitle>
{shareablePairingUrl
? isShareableHostedAppPairingUrl
{isRevealValueUrl
? isRevealValueHostedAppPairingUrl
? "Hosted app pairing link"
: "Pairing link"
: "Pairing code"}
</DialogTitle>
<DialogDescription>
{shareablePairingUrl
? isShareableHostedAppPairingUrl
{isRevealValueUrl
? isRevealValueHostedAppPairingUrl
? "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect."
: "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect."
: "Clipboard copy is unavailable here. Manually copy this code into another client."}
@@ -848,15 +756,15 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
<Textarea
readOnly
value={revealValue}
rows={shareablePairingUrl ? 4 : 3}
rows={isRevealValueUrl ? 4 : 3}
className="text-xs leading-relaxed"
onFocus={(event) => event.currentTarget.select()}
onClick={(event) => event.currentTarget.select()}
/>
{shareablePairingUrl ? (
{isRevealValueUrl && isRevealValueQrShareable ? (
<div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
<QRCodeSvg
value={shareablePairingUrl}
value={revealValue}
size={132}
level="M"
marginSize={2}
@@ -887,6 +795,91 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
</Button>
</div>
</div>
{isQrPanelOpen && qrPairingUrl !== null ? (
<div
id={qrPanelId}
className="mt-3 flex flex-col gap-4 border-t border-border/50 pt-3 sm:flex-row sm:items-start sm:justify-between"
>
<div className="min-w-0 flex-1 space-y-3">
{endpointCopyOptions.length > 1 ? (
<div
className="space-y-1.5"
role="radiogroup"
aria-label="Endpoint the pairing QR code and URL use"
>
<p className="text-[11px] text-muted-foreground/70">Reach this machine via</p>
{endpointCopyOptions.map((option) => {
const isSelected = option.id === selectedQrOption?.id;
return (
<button
key={option.id}
type="button"
role="radio"
aria-checked={isSelected}
className={cn(
"flex w-full items-baseline gap-2 rounded-lg border px-2.5 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",
isSelected
? "border-foreground/60 bg-muted/30"
: "border-border/50 hover:bg-muted/20",
)}
onClick={() => setQrEndpointId(option.id)}
>
<span
className={cn(
"text-xs font-medium",
isSelected ? "text-foreground" : "text-muted-foreground",
)}
>
{option.label}
</span>
<span className="min-w-0 truncate text-[11px] text-muted-foreground/70">
{option.detail}
</span>
</button>
);
})}
</div>
) : null}
<div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-2.5 py-1.5">
<code
title={qrPairingUrl}
className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground"
>
{qrPairingUrl}
</code>
<Button
size="xs"
variant="ghost"
className="shrink-0"
onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}
>
Copy link
</Button>
</div>
<Button size="xs" variant="ghost" onClick={handleCopyCode}>
Copy code only
</Button>
</div>
{canRenderQrForSelection ? (
<div className="w-fit shrink-0 self-center rounded-xl bg-white p-3 sm:self-start">
<QRCodeSvg
value={qrPairingUrl}
size={168}
level="M"
marginSize={1}
title="Pairing link — scan to open on another device"
/>
</div>
) : (
<div className="flex size-[192px] shrink-0 items-center justify-center self-center rounded-xl border border-border/50 p-4 sm:self-start">
<p className="text-center text-[11px] text-muted-foreground/70">
No QR for this endpoint. Another device scanning a loopback link would dial itself;
copy the URL for use on this machine instead.
</p>
</div>
)}
</div>
) : null}
</div>
);
});