feat(web): zero-input pairing, a real QR, and no scanner or scopes

The console side of ADR 0001: a scanned link pairs itself, the status page
draws the daemon's actual symbol, and the second entry point for pairing
(the in-page camera scanner) is gone.

- `POST /api/v1/pair/redeem` replaced the dual-purpose `/api/v1/pair`; the
  redeem response is parsed strictly as `{token, device}` (the five-layer
  alias fallbacks for `deviceToken`/`payload.device`/… are deleted).
- `features/status/qr.ts` no longer invents "a deterministic fake QR from a
  seed" — it renders `pairCode.qr.rows` module by module (devicePixelRatio
  aware, square, token colours, redraws on theme/resize), and a mint without a
  matrix shows the link instead of a pattern that will not scan.
- `/pair/<CODE>` (daemon 302 or the SPA route) lands on
  `/connect?code=…&auto=1`, which redeems against its own origin with the
  localized device name and then navigates to `next`/`/workspaces`, dropping
  the code from the URL; a rejected code falls back to the prefilled form.
- The camera scanner (`features/connect/scan-dialog.tsx`) and its i18n keys are
  removed: phones scan with the system camera, desktops type the code. Paste a
  `pi2://pair?…` link or `/pair/CODE` still fills the form.
- Scope tracking disappears from the store, API types, device list and pairing
  metadata (`pi2-device-scopes` is no longer written or read).
- Stale default removed: link parsing falls back to the served origin's port,
  then 443/80, instead of a hard-coded 4321.
- `scripts/ui-{fixtures,mock-server,shots}.mjs` follow the new contract
  (mint carries `qr`/`bases`, redeem route, no scopes), so the visual harness
  exercises the real flow.

Verification: web typecheck clean, 299/299 tests, `vite build` green, visual
matrix 24/24 clean, and the i18n catalog has no missing keys.
This commit is contained in:
yuez committed 2026-10-27 10:44:54 +08:00
1 parent a57c874095
commit 3e35fb7ef3
20 files changed
+419 -946

No files matched your search

+51 -11
View File
@@ -26,6 +26,40 @@ export const MOCK_DAEMON_ID = "d-mock-0f3a9c";
const MINUTE = 60_000; const MINUTE = 60_000;
/**
* 21×21 module grid for the mock pairing code (`rows` are `"0"`/`"1"` strings,
* no quiet zone). This is **not** a real QR encoding — the daemon's encoder
* lives in `src/core/qr.ts`; the harness only needs a plausible grid with the
* three finder patterns so the status page renders a real matrix.
*/
function mockQrRows(text, size = 21) {
const grid = Array.from({ length: size }, () => Array.from({ length: size }, () => "0"));
const finder = (ox, oy) => {
for (let y = 0; y < 7; y += 1) {
for (let x = 0; x < 7; x += 1) {
const ring = x === 0 || y === 0 || x === 6 || y === 6;
const core = x >= 2 && x <= 4 && y >= 2 && y <= 4;
grid[oy + y][ox + x] = ring || core ? "1" : "0";
}
}
};
finder(0, 0);
finder(size - 7, 0);
finder(0, size - 7);
let state = 2166136261;
for (const char of text) state = (state * 31 + char.charCodeAt(0)) >>> 0;
for (let y = 0; y < size; y += 1) {
for (let x = 0; x < size; x += 1) {
const inFinder = (x < 8 && y < 8) || (x > size - 9 && y < 8) || (x < 8 && y > size - 9);
if (inFinder) continue;
state = (state * 1103515245 + 12345) >>> 0;
grid[y][x] = state % 100 < 48 ? "1" : "0";
}
}
return grid.map((row) => row.join(""));
}
/** Fixed "now" for the running instance; callers may override. */ /** Fixed "now" for the running instance; callers may override. */
export function buildFixtures(now = Date.now()) { export function buildFixtures(now = Date.now()) {
const iso = (ts) => new Date(ts).toISOString(); const iso = (ts) => new Date(ts).toISOString();
@@ -785,7 +819,6 @@ export function buildFixtures(now = Date.now()) {
deviceId: "dev-local", deviceId: "dev-local",
name: "local browser", name: "local browser",
kind: "laptop", kind: "laptop",
scopes: ["read", "steer", "apply"],
lastSeenAt: now - 15_000, lastSeenAt: now - 15_000,
lastActiveAt: now - 15_000, lastActiveAt: now - 15_000,
createdAt: now - 26 * 3_600_000, createdAt: now - 26 * 3_600_000,
@@ -796,7 +829,6 @@ export function buildFixtures(now = Date.now()) {
deviceId: "dev-phone", deviceId: "dev-phone",
name: "Pixel 8 · pi2", name: "Pixel 8 · pi2",
kind: "phone", kind: "phone",
scopes: ["read", "steer"],
lastSeenAt: now - 47 * MINUTE, lastSeenAt: now - 47 * MINUTE,
lastActiveAt: now - 47 * MINUTE, lastActiveAt: now - 47 * MINUTE,
createdAt: now - 9 * 86_400_000, createdAt: now - 9 * 86_400_000,
@@ -807,7 +839,6 @@ export function buildFixtures(now = Date.now()) {
deviceId: "dev-tablet", deviceId: "dev-tablet",
name: "iPad Air", name: "iPad Air",
kind: "tablet", kind: "tablet",
scopes: ["read"],
lastSeenAt: now - 6 * 86_400_000, lastSeenAt: now - 6 * 86_400_000,
lastActiveAt: now - 6 * 86_400_000, lastActiveAt: now - 6 * 86_400_000,
createdAt: now - 40 * 86_400_000, createdAt: now - 40 * 86_400_000,
@@ -885,6 +916,21 @@ export function buildFixtures(now = Date.now()) {
const sessionById = new Map(sessions.map((session) => [session.sessionId, session])); const sessionById = new Map(sessions.map((session) => [session.sessionId, session]));
// `POST /api/v1/pair` mint payload: the daemon picks the URL and encodes it
// server-side, so the client never re-derives either (docs/protocol.md §3.2).
const pairCode = {
accepted: true,
code: "QK7M-2XPD",
url: "http://192.168.2.10:4321/pair/QK7M2XPD",
expiresAt: now + 10 * MINUTE,
nonce: "n-9f2c1a",
qr: { version: 1, ecc: "M", mask: 3, size: 21, rows: mockQrRows("http://192.168.2.10:4321/pair/QK7M2XPD") },
bases: [
{ kind: "loopback", name: "lo", address: "127.0.0.1:4321", url: "http://127.0.0.1:4321" },
{ kind: "lan", name: "eth0", address: "192.168.2.10:4321", url: "http://192.168.2.10:4321" },
],
};
return { return {
info: { ...info, port: undefined }, info: { ...info, port: undefined },
health, health,
@@ -896,14 +942,8 @@ export function buildFixtures(now = Date.now()) {
modelProviders, modelProviders,
resources, resources,
diagnostics, diagnostics,
/** `GET /api/v1/pair` mint response (no code in the body). */ /** `POST /api/v1/pair` mint response (code + QR matrix + reachable bases). */
pairCode: { pairCode,
accepted: true,
code: "QK7M-2XPD",
url: "http://127.0.0.1:4321/pair/QK7M-2XPD",
expiresAt: now + 10 * MINUTE,
nonce: "n-9f2c1a",
},
/** `attention` flattened per workspace for `GET /api/v1/attention`. */ /** `attention` flattened per workspace for `GET /api/v1/attention`. */
attentionByWorkspace: (workspaceId) => attentionByWorkspace: (workspaceId) =>
sessions sessions
+11 -9
View File
@@ -196,7 +196,6 @@ const DEVICE_PUBLIC = {
id: "dev-local", id: "dev-local",
name: "local browser", name: "local browser",
kind: "laptop", kind: "laptop",
scopes: ["read", "steer", "apply"],
}; };
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
@@ -314,18 +313,21 @@ async function handleApi(req, res, url) {
url: `http://127.0.0.1:${SERVER_PORT}/#t=${encodeURIComponent(MOCK_DEVICE_TOKEN)}`, url: `http://127.0.0.1:${SERVER_PORT}/#t=${encodeURIComponent(MOCK_DEVICE_TOKEN)}`,
}); });
} }
// Mint: authenticated, returns the code + QR matrix + reachable bases.
if (pathname === "/api/v1/pair" && method === "POST") { if (pathname === "/api/v1/pair" && method === "POST") {
const body = await readBody(req).catch(() => ({})); await readBody(req).catch(() => ({}));
if (typeof body.code === "string") {
// Public redeem: the fixture code pairs the browser as a laptop.
if (body.code.replace(/[\s-]/g, "").toUpperCase() !== FIXTURES.pairCode.code.replace(/-/g, "")) {
return unauthorized(res, "pairing code is invalid or expired");
}
return sendJson(res, 200, { token: MOCK_DEVICE_TOKEN, device: DEVICE_PUBLIC });
}
if (OPTIONS.pairOnly) return unauthorized(res); if (OPTIONS.pairOnly) return unauthorized(res);
return sendJson(res, 200, { accepted: true, ...FIXTURES.pairCode }); return sendJson(res, 200, { accepted: true, ...FIXTURES.pairCode });
} }
// Public redeem: the code *is* the capability, no bearer required. It answers
// `{token,device}` and stays available under `--pair-only`.
if (pathname === "/api/v1/pair/redeem" && method === "POST") {
const body = await readBody(req).catch(() => ({}));
if (String(body.code ?? "").replace(/[\s-]/g, "").toUpperCase() !== FIXTURES.pairCode.code.replace(/-/g, "")) {
return unauthorized(res, "pairing code is invalid or expired");
}
return sendJson(res, 200, { token: MOCK_DEVICE_TOKEN, device: DEVICE_PUBLIC });
}
/* Everything below needs a device token (and is refused in --pair-only). */ /* Everything below needs a device token (and is refused in --pair-only). */
if (OPTIONS.pairOnly) return unauthorized(res); if (OPTIONS.pairOnly) return unauthorized(res);
-1
View File
@@ -274,7 +274,6 @@ function storageState(origin, { paired, theme }) {
{ name: "pi2-connection", value: "paired" }, { name: "pi2-connection", value: "paired" },
{ name: "pi2-endpoint", value: origin }, { name: "pi2-endpoint", value: origin },
{ name: "pi2-device-token", value: "mock-device-token-0000000000000000000000" }, { name: "pi2-device-token", value: "mock-device-token-0000000000000000000000" },
{ name: "pi2-device-scopes", value: JSON.stringify(["read", "steer", "apply"]) },
{ name: "pi2-device", value: "visual harness" }, { name: "pi2-device", value: "visual harness" },
{ name: "pi2-connected-at", value: String(Date.now()) }, { name: "pi2-connected-at", value: String(Date.now()) },
{ name: "pi2-theme", value: theme }, { name: "pi2-theme", value: theme },
+56 -3
View File
@@ -7,7 +7,7 @@ import { Field, Input } from "@/components/ui/input";
import { toast } from "@/components/ui/toast"; import { toast } from "@/components/ui/toast";
import { ApiError, errorI18nKey } from "@/lib/api"; import { ApiError, errorI18nKey } from "@/lib/api";
import { PAIR_CODE_LENGTH, isPairCode, normalizePairCode, parseEndpoint } from "./pairing"; import { PAIR_CODE_LENGTH, isPairCode, normalizePairCode, parseEndpoint, parsePairLink } from "./pairing";
export interface ManualConnectInput { export interface ManualConnectInput {
endpoint: string; endpoint: string;
@@ -61,6 +61,8 @@ export function ManualConnectForm({
}: ManualConnectFormProps) { }: ManualConnectFormProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const id = useId(); const id = useId();
const [link, setLink] = useState("");
const [linkError, setLinkError] = useState<string | null>(null);
const [host, setHost] = useState(() => initialHost ?? ""); const [host, setHost] = useState(() => initialHost ?? "");
const [port, setPort] = useState(() => initialPort ?? defaultPort); const [port, setPort] = useState(() => initialPort ?? defaultPort);
const [code, setCode] = useState(() => normalizePairCode(initialCode ?? "")); const [code, setCode] = useState(() => normalizePairCode(initialCode ?? ""));
@@ -93,7 +95,24 @@ export function ManualConnectForm({
setCodeError(null); setCodeError(null);
setFormError(null); setFormError(null);
const parsed = parseEndpoint(host, port); // 整段粘贴的配对链接(`pi2://pair?…` / `…/pair/CODE`)先拆成地址 + 端口 + 配对码,
// 拆不出内容时留在链接输入框上报错。
const pastedLink = parsePairLink(link) ?? parsePairLink(host);
if (link.trim() && !parsePairLink(link)) {
setLinkError(t("connect.invalidLink"));
return;
}
setLinkError(null);
const hostValue = pastedLink ? pastedLink.hostname : host;
const portValue = pastedLink ? String(pastedLink.port) : port;
const codeValue = pastedLink ? pastedLink.code : code;
if (pastedLink) {
setHost(pastedLink.hostname);
setPort(String(pastedLink.port));
setCode(pastedLink.code);
}
const parsed = parseEndpoint(hostValue, portValue);
if ("error" in parsed) { if ("error" in parsed) {
if (parsed.error === "host") { if (parsed.error === "host") {
setHostError(t("connect.hostRequired")); setHostError(t("connect.hostRequired"));
@@ -110,7 +129,7 @@ export function ManualConnectForm({
return; return;
} }
const normalized = normalizePairCode(code); const normalized = normalizePairCode(codeValue);
if (!normalized) { if (!normalized) {
setCodeError(t("connect.pairCodeRequired")); setCodeError(t("connect.pairCodeRequired"));
return; return;
@@ -141,6 +160,40 @@ export function ManualConnectForm({
return ( return (
<div className="cn-manual" id={formId} hidden={!expanded} data-testid="connect-manual-panel"> <div className="cn-manual" id={formId} hidden={!expanded} data-testid="connect-manual-panel">
<form className="cn-form" noValidate onSubmit={(event) => void submit(event)}> <form className="cn-form" noValidate onSubmit={(event) => void submit(event)}>
<Field
label={t("connect.pairingLink")}
htmlFor={`${id}-link`}
hint={t("connect.pasteHint", { defaultValue: "Paste the link from the QR code" })}
error={linkError}
>
<Input
id={`${id}-link`}
data-testid="connect-link"
type="text"
inputMode="url"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
placeholder={t("connect.pastePlaceholder")}
value={link}
onChange={(event) => {
const text = event.target.value;
setLink(text);
setLinkError(null);
// 能解析就立即回填,用户只需再按一次连接。
const target = parsePairLink(text);
if (!target) return;
setHost(target.hostname);
setPort(String(target.port));
setCode(target.code);
portEdited.current = true;
setHostError(null);
setPortError(null);
setCodeError(null);
}}
/>
</Field>
<div className="cn-row"> <div className="cn-row">
<Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}> <Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}>
<Input <Input
+15 -51
View File
@@ -2,21 +2,16 @@ import { ApiError, apiRequest, type InfoResponse } from "@/lib/api";
import { NEXT_FALLBACK, safeNext } from "@/lib/routing"; import { NEXT_FALLBACK, safeNext } from "@/lib/routing";
export const PAIR_META_KEY = "pi2-pair-meta"; export const PAIR_META_KEY = "pi2-pair-meta";
export const PAIR_SCOPES = ["read", "steer", "apply"] as const;
/** Public redeem endpoint: no bearer token required (docs/protocol.md §3.2). */ /** Public redeem endpoint: no bearer token required (docs/protocol.md §3.2). */
export const PAIR_REDEEM_PATH = "/api/v1/pair"; export const PAIR_REDEEM_PATH = "/api/v1/pair/redeem";
/** The daemon mints 8-character uppercase alphanumeric pairing codes. */ /** The daemon mints 8-character uppercase alphanumeric pairing codes. */
export const PAIR_CODE_LENGTH = 8; export const PAIR_CODE_LENGTH = 8;
export const PAIR_CODE_PATTERN = /^[A-Z0-9]{8}$/; export const PAIR_CODE_PATTERN = /^[A-Z0-9]{8}$/;
export const DEFAULT_PAIR_PORT = 4321;
/** Scope assumed when a paired device did not report any (older daemons). */
export const DEFAULT_DEVICE_SCOPES = ["read"] as const;
export type DeviceKind = "phone" | "laptop" | "tablet"; export type DeviceKind = "phone" | "laptop" | "tablet";
export interface PairMeta { export interface PairMeta {
scopes: string[];
deviceName?: string; deviceName?: string;
kind?: DeviceKind; kind?: DeviceKind;
server?: Partial<InfoResponse> & { name?: string; hostname?: string; version?: string; pluginVersion?: string }; server?: Partial<InfoResponse> & { name?: string; hostname?: string; version?: string; pluginVersion?: string };
@@ -33,12 +28,9 @@ export interface PairTarget {
export interface RedeemResult { export interface RedeemResult {
token: string; token: string;
scopes: string[];
deviceId?: string; deviceId?: string;
deviceName?: string; deviceName?: string;
kind?: DeviceKind; kind?: DeviceKind;
server?: PairMeta["server"];
raw: unknown;
} }
export interface ParsedEndpoint { export interface ParsedEndpoint {
@@ -59,9 +51,6 @@ function firstString(...values: unknown[]): string | undefined {
return undefined; return undefined;
} }
function stringList(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
}
/** /**
* Uppercase and drop everything that is not `[A-Z0-9]` — pairing codes are * Uppercase and drop everything that is not `[A-Z0-9]` — pairing codes are
@@ -180,7 +169,9 @@ function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairT
const hostParam = firstString(params.get("host"), params.get("hostname"), params.get("endpoint")); const hostParam = firstString(params.get("host"), params.get("hostname"), params.get("endpoint"));
const proto = firstString(params.get("proto"), params.get("protocol"))?.toLowerCase(); const proto = firstString(params.get("proto"), params.get("protocol"))?.toLowerCase();
const portParam = firstString(params.get("port")) ?? String(DEFAULT_PAIR_PORT); // A link without a port resolves against the port this console was served
// from, falling back to the scheme default — never a literal.
const portParam = firstString(params.get("port")) ?? defaultPairPort(proto === "https" ? "https" : "http");
let target: ParsedEndpoint | null = null; let target: ParsedEndpoint | null = null;
if (hostParam) { if (hostParam) {
@@ -190,7 +181,7 @@ function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairT
target = "error" in parsed ? null : parsed; target = "error" in parsed ? null : parsed;
} }
// A pi2:// link without a host only makes sense against a known endpoint // A pi2:// link without a host only makes sense against a known endpoint
// (the scan dialog passes the stored one); never guess from the browser origin. // (the caller passes the stored one); never guess from the browser origin.
target ??= endpointFrom(fallbackEndpoint); target ??= endpointFrom(fallbackEndpoint);
if (!target) return null; if (!target) return null;
@@ -257,13 +248,14 @@ export function pairingOrigin(endpoint: string): string {
.replace(/\/+$/, ""); .replace(/\/+$/, "");
} }
function normalizeScopes(values: string[]): string[] { /** Port this console was served from, else the scheme default (`443`/`80`). */
const unique = [...new Set(values.map((value) => value.trim()).filter(Boolean))]; function defaultPairPort(protocol: "http" | "https"): string {
return unique.length ? unique : [...DEFAULT_DEVICE_SCOPES]; if (typeof window !== "undefined" && window.location.port) return window.location.port;
return protocol === "https" ? "443" : "80";
} }
/** /**
* Redeem a pairing code against the public `POST <origin>/api/v1/pair` * Redeem a pairing code against the public `POST <origin>/api/v1/pair/redeem`
* endpoint: `{code,kind,deviceName}` → `{token,device}`. * endpoint: `{code,kind,deviceName}` → `{token,device}`.
*/ */
export async function redeemPairing(input: { export async function redeemPairing(input: {
@@ -286,13 +278,10 @@ export async function redeemPairing(input: {
signal: input.signal, signal: input.signal,
}); });
const payload = asRecord(response.payload); // 文档契约只有 `{token,device:{id,name,kind}}`,不再兜底历史别名。
const result = asRecord(response.result);
const body = asRecord(response) ?? {}; const body = asRecord(response) ?? {};
const device = const device = asRecord(body.device);
asRecord(body.device) ?? asRecord(result?.device) ?? asRecord(payload?.device) ?? asRecord(payload); const token = firstString(body.token);
// `{token,device}` is the documented shape; keep the older aliases as a fallback.
const token = firstString(body.token, body.deviceToken, device?.token, result?.token, payload?.token);
if (!token) { if (!token) {
throw new ApiError({ throw new ApiError({
code: "E_UNAUTHORIZED", code: "E_UNAUTHORIZED",
@@ -301,22 +290,11 @@ export async function redeemPairing(input: {
}); });
} }
const scopes = normalizeScopes([
...stringList(body.scopes),
...stringList(device?.scopes),
...stringList(result?.scopes),
]);
return { return {
token, token,
scopes, deviceId: firstString(device?.id),
deviceId: firstString(device?.id, body.deviceId, device?.deviceId, result?.deviceId), deviceName: firstString(device?.name) ?? deviceName,
deviceName: firstString(device?.name, deviceName),
kind: (firstString(device?.kind) as DeviceKind | undefined) ?? kind, kind: (firstString(device?.kind) as DeviceKind | undefined) ?? kind,
server:
(asRecord(body.server) as PairMeta["server"] | undefined) ??
(asRecord(result?.server) as PairMeta["server"] | undefined),
raw: response,
}; };
} }
@@ -328,7 +306,6 @@ export function readPairMeta(): PairMeta | null {
const record = asRecord(parsed); const record = asRecord(parsed);
if (!record) return null; if (!record) return null;
return { return {
scopes: stringList(record.scopes),
deviceName: typeof record.deviceName === "string" ? record.deviceName : undefined, deviceName: typeof record.deviceName === "string" ? record.deviceName : undefined,
kind: record.kind === "phone" || record.kind === "laptop" || record.kind === "tablet" ? record.kind : undefined, kind: record.kind === "phone" || record.kind === "laptop" || record.kind === "tablet" ? record.kind : undefined,
server: asRecord(record.server) as PairMeta["server"] | undefined, server: asRecord(record.server) as PairMeta["server"] | undefined,
@@ -362,16 +339,3 @@ export function clearPairMeta(): void {
export function safePairNext(raw: string | null | undefined): string { export function safePairNext(raw: string | null | undefined): string {
return safeNext(raw, NEXT_FALLBACK); return safeNext(raw, NEXT_FALLBACK);
} }
/** Ordered scope list for the paired summary: stored device scopes win over /info capabilities. */
export function scopesForIdentity(
meta: PairMeta | null,
info: InfoResponse | null | undefined,
storedScopes?: string[] | null,
): string[] {
if (storedScopes?.length) return storedScopes;
if (meta?.scopes.length) return meta.scopes;
const capabilities = Array.isArray(info?.capabilities) ? info.capabilities : [];
const derived = capabilities.filter((capability) => (PAIR_SCOPES as readonly string[]).includes(capability));
return derived.length ? derived : [...DEFAULT_DEVICE_SCOPES];
}
-252
View File
@@ -1,252 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { parsePairLink, type PairTarget } from "./pairing";
interface DetectedBarcode {
rawValue?: string;
}
interface BarcodeDetectorLike {
detect(source: CanvasImageSource): Promise<DetectedBarcode[]>;
}
type BarcodeDetectorCtor = new (options?: { formats?: string[] }) => BarcodeDetectorLike;
function barcodeDetectorCtor(): BarcodeDetectorCtor | undefined {
return (window as unknown as { BarcodeDetector?: BarcodeDetectorCtor }).BarcodeDetector;
}
export interface ScanDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onFound: (target: PairTarget) => void;
fallbackEndpoint?: string | null;
}
/**
* Camera preview + BarcodeDetector loop, with the design's paste-link fallback
* whenever the browser, permission or secure context cannot scan.
*/
export function ScanDialog({ open, onOpenChange, onFound, fallbackEndpoint }: ScanDialogProps) {
const { t } = useTranslation();
const [attempt, setAttempt] = useState(0);
const [live, setLive] = useState(false);
const [status, setStatus] = useState("");
const [pasteOpen, setPasteOpen] = useState(false);
const [paste, setPaste] = useState("");
const [pasteInvalid, setPasteInvalid] = useState(false);
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const detectorRef = useRef<BarcodeDetectorLike | null>(null);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const finishingRef = useRef(false);
useEffect(() => {
if (!open) return;
let cancelled = false;
finishingRef.current = false;
setPasteOpen(false);
setPasteInvalid(false);
setStatus(t("connect.startingCamera"));
function stopCamera() {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
const stream = streamRef.current;
if (stream) {
for (const track of stream.getTracks()) track.stop();
streamRef.current = null;
}
detectorRef.current = null;
if (videoRef.current) videoRef.current.srcObject = null;
setLive(false);
}
function finish(raw: string) {
const target = parsePairLink(raw, fallbackEndpoint);
if (!target) {
setPasteInvalid(true);
setStatus(t("connect.invalidLink"));
setPasteOpen(true);
return;
}
if (finishingRef.current) return;
finishingRef.current = true;
stopCamera();
onFound(target);
onOpenChange(false);
}
async function scanFrame() {
if (cancelled || finishingRef.current) return;
const detector = detectorRef.current;
const video = videoRef.current;
if (!detector || !video) return;
try {
const codes = await detector.detect(video);
const raw = codes[0]?.rawValue;
if (raw) finish(raw);
} catch {
/* a single failed frame should not stop the loop */
}
}
async function startCamera() {
stopCamera();
if (!window.isSecureContext) {
setStatus(t("connect.secureRequired"));
setPasteOpen(true);
return;
}
if (!navigator.mediaDevices?.getUserMedia) {
setStatus(t("connect.cameraUnsupported"));
setPasteOpen(true);
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: { facingMode: { ideal: "environment" } },
});
if (cancelled) {
for (const track of stream.getTracks()) track.stop();
return;
}
streamRef.current = stream;
const video = videoRef.current;
if (video) {
video.srcObject = stream;
await video.play().catch(() => undefined);
}
setLive(true);
const Ctor = barcodeDetectorCtor();
if (Ctor) {
try {
detectorRef.current = new Ctor({ formats: ["qr_code"] });
} catch {
detectorRef.current = null;
}
}
if (detectorRef.current) {
setStatus(t("connect.aim"));
timerRef.current = setInterval(() => void scanFrame(), 300);
} else {
setStatus(t("connect.noAutoDetect"));
setPasteOpen(true);
}
} catch (error) {
const denied =
error instanceof DOMException &&
(error.name === "NotAllowedError" || error.name === "SecurityError");
setStatus(t(denied ? "connect.permissionDenied" : "connect.cameraFailed"));
setPasteOpen(true);
}
}
void startCamera();
return () => {
cancelled = true;
stopCamera();
};
}, [attempt, fallbackEndpoint, onFound, onOpenChange, open, t]);
function identify() {
const target = parsePairLink(paste, fallbackEndpoint);
if (!target) {
setPasteInvalid(true);
setStatus(t("connect.invalidLink"));
setPasteOpen(true);
return;
}
setPasteInvalid(false);
onFound(target);
onOpenChange(false);
}
return (
<Modal
open={open}
onOpenChange={onOpenChange}
title={t("connect.scanTitle")}
size="wide"
footer={
<Button variant="ghost" onClick={() => onOpenChange(false)}>
{t("common.close")}
</Button>
}
>
<div className="cn-scan">
<div className={live ? "cn-scan__viewport is-live" : "cn-scan__viewport"}>
<video
ref={videoRef}
className="cn-scan__video"
autoPlay
playsInline
muted
aria-label={t("connect.cameraPreview")}
/>
<div className="cn-scan__placeholder">
<span className="cn-ico">
<Icon name="scan" size={28} />
</span>
<span>{t("connect.cameraPreview")}</span>
</div>
<div className="cn-scan__frame" aria-hidden="true" />
</div>
<div className="cn-scan__state" role="status" aria-live="polite">
{status}
</div>
<p className="cn-hint">{t("connect.scanHint")}</p>
<details
className="cn-fold"
open={pasteOpen}
onToggle={(event) => setPasteOpen(event.currentTarget.open)}
>
<summary>{t("connect.cantScan")}</summary>
<div className="cn-fold__body">
<Input
type="text"
autoComplete="off"
spellCheck={false}
className={pasteInvalid ? "is-invalid" : undefined}
placeholder={t("connect.pastePlaceholder")}
aria-label={t("connect.pairingLink")}
value={paste}
onChange={(event) => {
setPaste(event.target.value);
setPasteInvalid(false);
}}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
event.preventDefault();
identify();
}
}}
/>
<Button variant="primary" onClick={identify}>
{t("connect.identify")}
</Button>
</div>
</details>
<div className="cn-scan__actions">
<Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}>
<Icon name="refresh" />
{t("connect.retryCamera")}
</Button>
</div>
</div>
</Modal>
);
}
+38 -30
View File
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
import { ConfirmDialog } from "@/components/shared/confirm-dialog"; import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time"; import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { KV } from "@/components/ui/kv"; import { KV } from "@/components/ui/kv";
import { toast } from "@/components/ui/toast"; import { toast } from "@/components/ui/toast";
@@ -54,28 +53,42 @@ function Address({ label, value }: { label: string; value: string }) {
); );
} }
function QrCanvas({ seed, label }: { seed: string; label: string }) { /**
* 画 daemon 下发的真矩阵:`rows` 每行一串 `0`/`1`。主题切换和容器缩放时重绘。
*/
function QrCanvas({ rows, label }: { rows: string[]; label: string }) {
const ref = useRef<HTMLCanvasElement | null>(null); const ref = useRef<HTMLCanvasElement | null>(null);
useEffect(() => { useEffect(() => {
const canvas = ref.current; const canvas = ref.current;
if (!canvas) return; if (!canvas) return;
const draw = () => drawQr(canvas, seed); const draw = () => drawQr(canvas, rows);
draw(); draw();
if (typeof MutationObserver === "undefined") return; window.addEventListener("resize", draw);
const observer = new MutationObserver(draw); const observer =
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] }); typeof MutationObserver === "undefined" ? null : new MutationObserver(draw);
return () => observer.disconnect(); observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
}, [seed]); return () => {
window.removeEventListener("resize", draw);
observer?.disconnect();
};
}, [rows]);
return <canvas ref={ref} className="qr-canvas" role="img" aria-label={label} />; return (
<canvas
ref={ref}
className="qr-canvas"
role="img"
aria-label={label}
data-qr-size={rows.length}
/>
);
} }
export interface ConnectionCardProps { export interface ConnectionCardProps {
server: ServerIdentity; server: ServerIdentity;
deviceName: string; deviceName: string;
scopes: string[];
connectedAt: number | null; connectedAt: number | null;
loading: boolean; loading: boolean;
error: string | null; error: string | null;
@@ -95,15 +108,14 @@ export function pairMinutesLeft(expiresAt: number | null | undefined, now = Date
} }
/** /**
* Card 7 — two internal columns: addresses / mDNS / endpoint / device / scopes * Card 7 — two internal columns: addresses / mDNS / endpoint / device / pairing
* / pairing code / security notes on the left, the square QR with the pairing * code / security notes on the left, the QR with the pairing hint and the expiry
* hint and the expiry on the right. Both actions are non-primary (the status * on the right. Both actions are non-primary (the status page carries 0 primary
* page carries 0 primary buttons). * buttons).
*/ */
export function ConnectionCard({ export function ConnectionCard({
server, server,
deviceName, deviceName,
scopes,
connectedAt, connectedAt,
loading, loading,
error, error,
@@ -117,7 +129,10 @@ export function ConnectionCard({
const { t } = useTranslation(); const { t } = useTranslation();
const [confirmOpen, setConfirmOpen] = useState(false); const [confirmOpen, setConfirmOpen] = useState(false);
const code = String(pairCode?.code ?? "").trim(); const code = String(pairCode?.code ?? "").trim();
const url = String(pairCode?.url ?? "").trim() || (code ? `${server.networkAddress}/#pair=${code}` : ""); // URL 由 daemon 决定(mint 时选好 base),客户端不再拼接。
const url = String(pairCode?.url ?? "").trim();
/** 真矩阵;URL 过长时 daemon 不下发 `qr`,此时只展示可点/可拷的链接。 */
const qrRows = Array.isArray(pairCode?.qr?.rows) ? pairCode.qr.rows : [];
const minutes = pairMinutesLeft(pairCode?.expiresAt); const minutes = pairMinutesLeft(pairCode?.expiresAt);
return ( return (
@@ -146,19 +161,6 @@ export function ConnectionCard({
<CopyButton value={server.endpoint} label={t("connect.endpoint")} /> <CopyButton value={server.endpoint} label={t("connect.endpoint")} />
</KV> </KV>
<KV label={t("connect.device")}>{deviceName || "—"}</KV> <KV label={t("connect.device")}>{deviceName || "—"}</KV>
<KV label={t("status.tokenScopes")} valueClassName="status-scopes__wrap">
{scopes.length ? (
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
) : (
<span className="faint">—</span>
)}
</KV>
<KV label={t("status.lastConnected")}> <KV label={t("status.lastConnected")}>
<RelativeTime ts={connectedAt} /> <RelativeTime ts={connectedAt} />
</KV> </KV>
@@ -192,7 +194,13 @@ export function ConnectionCard({
<div className="conn-right"> <div className="conn-right">
<div className="qr-wrap"> <div className="qr-wrap">
{code ? <QrCanvas seed={url || code} label={t("status.qrAria")} /> : null} {qrRows.length ? (
<QrCanvas rows={qrRows} label={t("status.qrAria")} />
) : url ? (
<code className="qr-link mono" data-testid="pair-url">
{url}
</code>
) : null}
<div className="pair-hint faint"> <div className="pair-hint faint">
<Icon name="phone" /> <Icon name="phone" />
<span>{t("status.pairHint")}</span> <span>{t("status.pairHint")}</span>
+2 -12
View File
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons"; import { Icon, type IconName } from "@/components/icons";
import { ConfirmDialog } from "@/components/shared/confirm-dialog"; import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time"; import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import type { DeviceEntry } from "@/features/status/queries"; import type { DeviceEntry } from "@/features/status/queries";
@@ -34,7 +33,7 @@ export interface DevicesCardProps {
onRevoke: (device: DeviceEntry) => Promise<void>; onRevoke: (device: DeviceEntry) => Promise<void>;
} }
/** Card 6 — paired devices with kind icon, scopes, last active and confirm-revoke. */ /** Card 6 — paired devices with kind icon, last active and confirm-revoke. */
export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: DevicesCardProps) { export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: DevicesCardProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [target, setTarget] = useState<DeviceEntry | null>(null); const [target, setTarget] = useState<DeviceEntry | null>(null);
@@ -61,7 +60,6 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
) : ( ) : (
<div className="device-list"> <div className="device-list">
{visible.map((device) => { {visible.map((device) => {
const scopes = Array.isArray(device.scopes) ? device.scopes : [];
return ( return (
<div className="device-row" key={deviceKey(device)} data-device-id={deviceKey(device)}> <div className="device-row" key={deviceKey(device)} data-device-id={deviceKey(device)}>
<span className="device-icon"> <span className="device-icon">
@@ -69,15 +67,7 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
</span> </span>
<div className="grow device-main"> <div className="grow device-main">
<div className="device-name truncate">{device.name}</div> <div className="device-name truncate">{device.name}</div>
<div className="device-meta"> <div className="device-meta faint">{device.kind}</div>
<span className="status-scopes">
{scopes.map((scope) => (
<Badge key={scope} className="badge--outline">
{scope}
</Badge>
))}
</span>
</div>
</div> </div>
<span className="device-time faint"> <span className="device-time faint">
<RelativeTime ts={deviceLastActive(device)} /> <RelativeTime ts={deviceLastActive(device)} />
+54 -30
View File
@@ -1,9 +1,32 @@
/** /**
* Port of the prototype's `App.drawQR`: a deterministic fake QR derived from a * Renders the daemon's real QR matrix (`pairCode.qr.rows`, one `"0"`/`"1"`
* seed string. Colors come from the design tokens only, so a theme switch * string per row) into a square canvas.
* redraws the same pattern with the dark surfaces. *
* 渲染要点:
* - `rows` 已是去掉静区的模块矩阵,渲染器自己负责留白和颜色;
* - 按 devicePixelRatio 放大位图(避免糊),CSS 宽度自适应容器且最多 200px;
* - 颜色只取 token:前景 `--foreground`、底色 `--card`,主题切换后重绘;
* - `rows` 为空或不是方阵时清空画布(不画任何占位图)。
*/ */
export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
/** Upper bound of the CSS square; the container may be narrower. */
export const QR_MAX_CSS_SIZE = 200;
/** Quiet zone in modules, drawn on the card background. */
const QUIET_MODULES = 3;
function cssSize(canvas: HTMLCanvasElement): number {
const parent = canvas.parentElement;
const available = parent?.clientWidth || canvas.clientWidth || QR_MAX_CSS_SIZE;
return Math.max(0, Math.min(QR_MAX_CSS_SIZE, available));
}
function isMatrix(rows: string[]): boolean {
const size = rows.length;
if (!size) return false;
return rows.every((row) => typeof row === "string" && row.length === size && /^[01]+$/.test(row));
}
export function drawQr(canvas: HTMLCanvasElement, rows: string[]): void {
let context: CanvasRenderingContext2D | null = null; let context: CanvasRenderingContext2D | null = null;
try { try {
context = canvas.getContext("2d"); context = canvas.getContext("2d");
@@ -12,41 +35,42 @@ export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
} }
if (!context) return; if (!context) return;
const n = 25; // 空矩阵:清掉上一张码,不留伪图案。
const cell = 8; if (!isMatrix(rows)) {
canvas.width = n * cell; canvas.width = 0;
canvas.height = n * cell; canvas.height = 0;
context.clearRect(0, 0, canvas.width, canvas.height);
return;
}
const size = rows.length;
const dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
const css = Math.round(cssSize(canvas)) || QR_MAX_CSS_SIZE;
canvas.width = Math.round(css * dpr);
canvas.height = Math.round(css * dpr);
const styles = getComputedStyle(document.documentElement); const styles = getComputedStyle(document.documentElement);
const cardColor = styles.getPropertyValue("--card").trim() || "transparent"; const cardColor = styles.getPropertyValue("--card").trim() || "transparent";
const foregroundColor = styles.getPropertyValue("--foreground").trim() || "currentColor"; const foregroundColor = styles.getPropertyValue("--foreground").trim() || "currentColor";
// 静区 + 模块网格都按 devicePixelRatio 缩放,保持正方形。
const total = size + QUIET_MODULES * 2;
const module = canvas.width / total;
context.fillStyle = cardColor; context.fillStyle = cardColor;
context.fillRect(0, 0, canvas.width, canvas.height); context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = foregroundColor; context.fillStyle = foregroundColor;
let state = 0; for (let y = 0; y < size; y += 1) {
for (const char of seed) state = (state * 31 + char.charCodeAt(0)) >>> 0; const row = rows[y] ?? "";
const random = () => { for (let x = 0; x < size; x += 1) {
state = (state * 1103515245 + 12345) >>> 0; if (row[x] !== "1") continue;
return state / 4294967296; // 取整像素边界,避免相邻模块间的缝。
}; const left = Math.round((x + QUIET_MODULES) * module);
const top = Math.round((y + QUIET_MODULES) * module);
const finder = (x: number, y: number) => { const right = Math.round((x + QUIET_MODULES + 1) * module);
context?.fillRect(x * cell, y * cell, 7 * cell, 7 * cell); const bottom = Math.round((y + QUIET_MODULES + 1) * module);
context?.clearRect((x + 1) * cell, (y + 1) * cell, 5 * cell, 5 * cell); context.fillRect(left, top, right - left, bottom - top);
context?.fillRect((x + 2) * cell, (y + 2) * cell, 3 * cell, 3 * cell);
if (context) context.fillStyle = foregroundColor;
};
for (let y = 0; y < n; y += 1) {
for (let x = 0; x < n; x += 1) {
const inFinder = (x < 8 && y < 8) || (x > n - 9 && y < 8) || (x < 8 && y > n - 9);
if (!inFinder && random() > 0.52) context.fillRect(x * cell, y * cell, cell, cell);
} }
} }
finder(0, 0);
finder(n - 7, 0);
finder(0, n - 7);
} }
+6 -4
View File
@@ -20,7 +20,6 @@ export interface DeviceEntry {
deviceId?: string; deviceId?: string;
name: string; name: string;
kind: string; kind: string;
scopes: string[];
/** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */ /** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */
lastActiveAt?: number | null; lastActiveAt?: number | null;
lastSeenAt?: number | null; lastSeenAt?: number | null;
@@ -52,9 +51,10 @@ export async function fetchModels(workspaceId: string, signal?: AbortSignal): Pr
} }
/** /**
* `/api/v1/pair` is public for redemption (`{code,…}`) and *authenticated* for * `POST /api/v1/pair` is authenticated and mints a code:
* minting: an authenticated `POST` with no `code` returns * `{accepted,code,url,expiresAt,nonce,qr,bases}`, where `qr` carries the opaque
* `{accepted,code,url,expiresAt,nonce}` (docs/protocol.md §3.2). * matrix (version 1–10, EC level M, no quiet zone) and is absent when the URL
* is too long to encode (docs/protocol.md §3.2).
*/ */
export interface PairCodeResponse { export interface PairCodeResponse {
accepted?: boolean; accepted?: boolean;
@@ -62,6 +62,8 @@ export interface PairCodeResponse {
url?: string; url?: string;
expiresAt?: number; expiresAt?: number;
nonce?: string; nonce?: string;
qr?: { version: number; ecc: string; mask: number; size: number; rows: string[] };
bases?: { kind: string; name: string; address: string; url: string }[];
} }
/** Pairing codes are short-lived; 10 minutes matches `auth.pairCreate`'s default. */ /** Pairing codes are short-lived; 10 minutes matches `auth.pairCreate`'s default. */
+1 -3
View File
@@ -280,7 +280,6 @@ export interface DeviceInfo {
deviceId: string; deviceId: string;
name: string; name: string;
kind: "phone" | "laptop" | "tablet"; kind: "phone" | "laptop" | "tablet";
scopes: string[];
lastActiveAt: number | null; lastActiveAt: number | null;
} }
@@ -312,7 +311,6 @@ export interface PairRequest {
export interface PairResponse { export interface PairResponse {
token?: string; token?: string;
deviceId?: string; deviceId?: string;
scopes?: string[];
server?: Partial<InfoResponse>; server?: Partial<InfoResponse>;
[key: string]: unknown; [key: string]: unknown;
} }
@@ -351,7 +349,7 @@ export const api = {
request<PairResponse>("/api/v1/pair", { method: "POST", body: {}, baseUrl, signal }), request<PairResponse>("/api/v1/pair", { method: "POST", body: {}, baseUrl, signal }),
/** Public redeem endpoint (no bearer required): `{code,kind,deviceName}` → `{token,device}`. */ /** Public redeem endpoint (no bearer required): `{code,kind,deviceName}` → `{token,device}`. */
pairRedeem: (body: PairRequest, baseUrl?: string, signal?: AbortSignal) => pairRedeem: (body: PairRequest, baseUrl?: string, signal?: AbortSignal) =>
request<PairResponse>("/api/v1/pair", { method: "POST", body, baseUrl, signal, skipAuthReset: true }), request<PairResponse>("/api/v1/pair/redeem", { method: "POST", body, baseUrl, signal, skipAuthReset: true }),
}; };
export { request as apiRequest }; export { request as apiRequest };
+4 -30
View File
@@ -413,19 +413,12 @@
"common.stop": "Stop", "common.stop": "Stop",
"connect.addTitle": "Connection settings", "connect.addTitle": "Connection settings",
"connect.address": "Address", "connect.address": "Address",
"connect.aim": "Point the back camera at the QR code on the pi2 server",
"connect.backToWorkspaces": "Back to workspaces", "connect.backToWorkspaces": "Back to workspaces",
"connect.cameraFailed": "Could not open the camera (no device available). Paste the pairing link instead.",
"connect.cameraPreview": "Camera preview",
"connect.cameraUnsupported": "This browser does not support camera access. Paste the pairing link below.",
"connect.cantScan": "Can't scan? Paste the pairing link",
"connect.collapseManual": "Hide manual connection", "connect.collapseManual": "Hide manual connection",
"connect.confirmTitle": "Confirm connection",
"connect.connect": "Connect", "connect.connect": "Connect",
"connect.connected": "Connected: {name}", "connect.connected": "Connected: {name}",
"connect.connecting": "Connecting…", "connect.connecting": "Connecting…",
"connect.defaultDeviceName": "Web console", "connect.defaultDeviceName": "Web console",
"connect.demoScan": "Demo: simulate scan",
"connect.details": "Connection details", "connect.details": "Connection details",
"connect.device": "Device", "connect.device": "Device",
"connect.deviceName": "Device name", "connect.deviceName": "Device name",
@@ -434,13 +427,13 @@
"connect.disconnectText": "This clears the saved connection and token in this browser; you will need to pair again.", "connect.disconnectText": "This clears the saved connection and token in this browser; you will need to pair again.",
"connect.disconnectTitle": "Disconnect", "connect.disconnectTitle": "Disconnect",
"connect.disconnected": "Disconnected", "connect.disconnected": "Disconnected",
"connect.emptyText": "Enter the address, or scan a pi2 pairing code to get started.", "connect.emptyText": "Enter the address and the 8-character pairing code shown on the pi2 server.",
"connect.emptyTitle": "Connect your pi2 server", "connect.emptyTitle": "Connect your pi2 server",
"connect.endpoint": "Endpoint", "connect.endpoint": "Endpoint",
"connect.expandManual": "Show manual connection", "connect.expandManual": "Show manual connection",
"connect.failed": "Connection failed. Check the address and pairing code.", "connect.failed": "Connection failed. Check the address and pairing code.",
"connect.featureOne": "Workspaces and sessions in real time", "connect.featureOne": "Workspaces and sessions in real time",
"connect.featureThree": "Scoped read / steer / apply access", "connect.featureThree": "Pair once from your phone — no config, no mode switch",
"connect.featureTwo": "Subagents and background tasks in one place", "connect.featureTwo": "Subagents and background tasks in one place",
"connect.heroText": "One browser, one pi2 instance — continue your Neovim sessions from any device.", "connect.heroText": "One browser, one pi2 instance — continue your Neovim sessions from any device.",
"connect.heroTitle": "Connect your pi2", "connect.heroTitle": "Connect your pi2",
@@ -448,14 +441,10 @@
"connect.hostPlaceholder": "192.168.2.10 or http://…:4321", "connect.hostPlaceholder": "192.168.2.10 or http://…:4321",
"connect.hostRequired": "Enter the server address", "connect.hostRequired": "Enter the server address",
"connect.hostname": "Hostname", "connect.hostname": "Hostname",
"connect.identify": "Identify",
"connect.invalidLink": "Could not parse it. Paste the full pi2://pair link.", "connect.invalidLink": "Could not parse it. Paste the full pi2://pair link.",
"connect.lastConnected": "Last connected", "connect.lastConnected": "Last connected",
"connect.manual": "Connect manually", "connect.manual": "Connect manually",
"connect.name": "Name", "connect.name": "Name",
"connect.noAutoDetect": "Camera is on. This browser cannot decode QR codes automatically; paste the pairing link.",
"connect.notPairQr": "Not a pi2 pairing QR code. Try another.",
"connect.or": "or",
"connect.os": "OS", "connect.os": "OS",
"connect.pairCode": "Pairing code", "connect.pairCode": "Pairing code",
"connect.pairCodeHint": "The 8-character code shown by the pi2 server.", "connect.pairCodeHint": "The 8-character code shown by the pi2 server.",
@@ -467,31 +456,17 @@
"connect.pairHint": "Scan the pairing QR code shown by the pi2 server; you will confirm before connecting.", "connect.pairHint": "Scan the pairing QR code shown by the pi2 server; you will confirm before connecting.",
"connect.pairingAuto": "Pairing this device…", "connect.pairingAuto": "Pairing this device…",
"connect.pairingLink": "Pairing link", "connect.pairingLink": "Pairing link",
"connect.pastePlaceholder": "Paste a pi2://pair?… pairing link", "connect.pasteHint": "Paste the pairing link instead of typing host and code",
"connect.permissionDenied": "Camera permission was denied. Allow access in browser settings and try again.", "connect.pastePlaceholder": "Paste a pi2://pair?… or /pair/CODE link",
"connect.piVersion": "pi version", "connect.piVersion": "pi version",
"connect.pluginVersion": "Plugin version", "connect.pluginVersion": "Plugin version",
"connect.port": "Port", "connect.port": "Port",
"connect.portInvalid": "Port must be 1–65535", "connect.portInvalid": "Port must be 1–65535",
"connect.recognized": "QR code recognized",
"connect.reconnect": "Re-pair", "connect.reconnect": "Re-pair",
"connect.retryCamera": "Retry camera",
"connect.scan": "Scan to pair",
"connect.scanHint": "Scan the pairing QR code shown by the pi2 server. You'll confirm before connecting.",
"connect.scanLead": "Found a pi2 pairing payload. Make sure the QR code comes from a device you trust.",
"connect.scanTitle": "Scan pairing code",
"connect.scanWarning": "After connecting, this device can read and write sessions and dispatch subagents.", "connect.scanWarning": "After connecting, this device can read and write sessions and dispatch subagents.",
"connect.scannedNote": "Scanned pairing",
"connect.scope.apply": "Apply",
"connect.scope.read": "Read",
"connect.scope.steer": "Steer",
"connect.scopeHint": "Scope granted to this device: {scope}",
"connect.scopes": "Scopes",
"connect.secureBadge": "Token stays on this device", "connect.secureBadge": "Token stays on this device",
"connect.secureNote": "Camera access requires HTTPS (or localhost); the token is stored only in this browser.", "connect.secureNote": "Camera access requires HTTPS (or localhost); the token is stored only in this browser.",
"connect.secureRequired": "Camera access requires HTTPS (or localhost). Paste the pairing link below instead.",
"connect.server": "Server", "connect.server": "Server",
"connect.startingCamera": "Starting camera…",
"connect.statePaired": "Connected", "connect.statePaired": "Connected",
"connect.stateUnpaired": "Not connected", "connect.stateUnpaired": "Not connected",
"connect.subtitle": "Connect this browser to your pi2 instance and review pairing details.", "connect.subtitle": "Connect this browser to your pi2 instance and review pairing details.",
@@ -658,7 +633,6 @@
"status.tasks": "Background tasks", "status.tasks": "Background tasks",
"status.tasksError": "Failed to load background tasks", "status.tasksError": "Failed to load background tasks",
"status.title": "Server status", "status.title": "Server status",
"status.tokenScopes": "Token scopes",
"status.updated": "updated {time}", "status.updated": "updated {time}",
"status.uptime": "Uptime", "status.uptime": "Uptime",
"status.workspaces": "Workspaces", "status.workspaces": "Workspaces",
+4 -30
View File
@@ -413,19 +413,12 @@
"common.stop": "停止", "common.stop": "停止",
"connect.addTitle": "连接设置", "connect.addTitle": "连接设置",
"connect.address": "地址", "connect.address": "地址",
"connect.aim": "将设备背面对准 pi2 服务器上的二维码",
"connect.backToWorkspaces": "返回工作空间", "connect.backToWorkspaces": "返回工作空间",
"connect.cameraFailed": "无法打开摄像头(可能没有可用设备)。请改用配对链接。",
"connect.cameraPreview": "摄像头预览",
"connect.cameraUnsupported": "当前浏览器不支持摄像头,请改用下方配对链接。",
"connect.cantScan": "无法扫码?粘贴配对链接",
"connect.collapseManual": "收起手动连接", "connect.collapseManual": "收起手动连接",
"connect.confirmTitle": "确认连接",
"connect.connect": "连接", "connect.connect": "连接",
"connect.connected": "已连接:{name}", "connect.connected": "已连接:{name}",
"connect.connecting": "正在连接…", "connect.connecting": "正在连接…",
"connect.defaultDeviceName": "Web 控制台", "connect.defaultDeviceName": "Web 控制台",
"connect.demoScan": "演示:模拟扫码",
"connect.details": "连接详情", "connect.details": "连接详情",
"connect.device": "设备", "connect.device": "设备",
"connect.deviceName": "设备名", "connect.deviceName": "设备名",
@@ -434,13 +427,13 @@
"connect.disconnectText": "将清除此浏览器保存的连接与 Token,需要重新配对才能继续。", "connect.disconnectText": "将清除此浏览器保存的连接与 Token,需要重新配对才能继续。",
"connect.disconnectTitle": "断开连接", "connect.disconnectTitle": "断开连接",
"connect.disconnected": "已断开连接", "connect.disconnected": "已断开连接",
"connect.emptyText": "填写地址,或扫码配对 pi2 服务器后即可开始。", "connect.emptyText": "填写地址,以及 pi2 服务器上显示的 8 位配对码即可开始。",
"connect.emptyTitle": "连接 pi2 服务器", "connect.emptyTitle": "连接 pi2 服务器",
"connect.endpoint": "地址", "connect.endpoint": "地址",
"connect.expandManual": "展开手动连接", "connect.expandManual": "展开手动连接",
"connect.failed": "连接失败,请检查地址与配对码", "connect.failed": "连接失败,请检查地址与配对码",
"connect.featureOne": "工作空间与会话实时同步", "connect.featureOne": "工作空间与会话实时同步",
"connect.featureThree": "只读 / 操控 / 应用 分级授权", "connect.featureThree": "手机扫码即配对,无需配置、无需切换模式",
"connect.featureTwo": "子代理与后台任务一处掌控", "connect.featureTwo": "子代理与后台任务一处掌控",
"connect.heroText": "一个浏览器连接一个 pi2 实例,在任意设备上继续你的 Neovim 会话。", "connect.heroText": "一个浏览器连接一个 pi2 实例,在任意设备上继续你的 Neovim 会话。",
"connect.heroTitle": "连接你的 pi2", "connect.heroTitle": "连接你的 pi2",
@@ -448,14 +441,10 @@
"connect.hostPlaceholder": "192.168.2.10 或 http://…:4321", "connect.hostPlaceholder": "192.168.2.10 或 http://…:4321",
"connect.hostRequired": "请输入服务器地址", "connect.hostRequired": "请输入服务器地址",
"connect.hostname": "Hostname", "connect.hostname": "Hostname",
"connect.identify": "识别",
"connect.invalidLink": "无法识别,请粘贴完整的 pi2://pair 链接", "connect.invalidLink": "无法识别,请粘贴完整的 pi2://pair 链接",
"connect.lastConnected": "最后连接", "connect.lastConnected": "最后连接",
"connect.manual": "手动连接", "connect.manual": "手动连接",
"connect.name": "名称", "connect.name": "名称",
"connect.noAutoDetect": "摄像头已开启。当前浏览器不支持自动识别,请粘贴配对链接。",
"connect.notPairQr": "这不是 pi2 配对二维码,请换一个",
"connect.or": "或",
"connect.os": "系统", "connect.os": "系统",
"connect.pairCode": "配对码", "connect.pairCode": "配对码",
"connect.pairCodeHint": "pi2 服务器上显示的 8 位配对码。", "connect.pairCodeHint": "pi2 服务器上显示的 8 位配对码。",
@@ -467,31 +456,17 @@
"connect.pairHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。", "connect.pairHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
"connect.pairingAuto": "正在配对这台设备…", "connect.pairingAuto": "正在配对这台设备…",
"connect.pairingLink": "配对链接", "connect.pairingLink": "配对链接",
"connect.pastePlaceholder": "粘贴 pi2://pair?… 配对链接", "connect.pasteHint": "也可以直接粘贴配对链接,省去填写地址与配对码",
"connect.permissionDenied": "摄像头权限被拒绝。请在浏览器设置中允许访问后重试。", "connect.pastePlaceholder": "粘贴 pi2://pair?… 或 /pair/CODE 链接",
"connect.piVersion": "pi 版本", "connect.piVersion": "pi 版本",
"connect.pluginVersion": "插件版本", "connect.pluginVersion": "插件版本",
"connect.port": "端口", "connect.port": "端口",
"connect.portInvalid": "端口必须是 1–65535", "connect.portInvalid": "端口必须是 1–65535",
"connect.recognized": "已识别二维码",
"connect.reconnect": "重新配对", "connect.reconnect": "重新配对",
"connect.retryCamera": "重试摄像头",
"connect.scan": "扫码配对",
"connect.scanHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
"connect.scanLead": "已识别到 pi2 配对信息。请确认二维码来自你信任的设备。",
"connect.scanTitle": "扫码配对",
"connect.scanWarning": "连接后该设备可读写会话并派发子代理。", "connect.scanWarning": "连接后该设备可读写会话并派发子代理。",
"connect.scannedNote": "扫码配对",
"connect.scope.apply": "写入",
"connect.scope.read": "读取",
"connect.scope.steer": "操作",
"connect.scopeHint": "此设备获得的权限:{scope}",
"connect.scopes": "权限",
"connect.secureBadge": "Token 仅保存在本机", "connect.secureBadge": "Token 仅保存在本机",
"connect.secureNote": "摄像头需要 HTTPS(或 localhost);Token 仅保存在此浏览器。", "connect.secureNote": "摄像头需要 HTTPS(或 localhost);Token 仅保存在此浏览器。",
"connect.secureRequired": "摄像头需要 HTTPS(或 localhost)安全环境,请改用下方配对链接。",
"connect.server": "服务器", "connect.server": "服务器",
"connect.startingCamera": "正在启动摄像头…",
"connect.statePaired": "已连接", "connect.statePaired": "已连接",
"connect.stateUnpaired": "未连接", "connect.stateUnpaired": "未连接",
"connect.subtitle": "连接本机 pi2 实例,查看配对与连接信息。", "connect.subtitle": "连接本机 pi2 实例,查看配对与连接信息。",
@@ -658,7 +633,6 @@
"status.tasks": "后台任务", "status.tasks": "后台任务",
"status.tasksError": "加载后台任务失败", "status.tasksError": "加载后台任务失败",
"status.title": "服务器状态", "status.title": "服务器状态",
"status.tokenScopes": "Token 权限",
"status.updated": "{time}更新", "status.updated": "{time}更新",
"status.uptime": "已运行时长", "status.uptime": "已运行时长",
"status.workspaces": "工作空间数", "status.workspaces": "工作空间数",
+12 -202
View File
@@ -7,7 +7,6 @@ import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { RelativeTime } from "@/components/shared/relative-time"; import { RelativeTime } from "@/components/shared/relative-time";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog";
import { KV } from "@/components/ui/kv"; import { KV } from "@/components/ui/kv";
import { StatusDot } from "@/components/ui/status-dot"; import { StatusDot } from "@/components/ui/status-dot";
import { toast } from "@/components/ui/toast"; import { toast } from "@/components/ui/toast";
@@ -22,12 +21,10 @@ import {
readPairMeta, readPairMeta,
redeemPairing, redeemPairing,
safePairNext, safePairNext,
scopesForIdentity,
writePairMeta, writePairMeta,
type PairMeta, type PairMeta,
type PairTarget, type PairTarget,
} from "@/features/connect/pairing"; } from "@/features/connect/pairing";
import { ScanDialog } from "@/features/connect/scan-dialog";
import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server"; import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server";
import { useInfoQuery } from "@/features/status/queries"; import { useInfoQuery } from "@/features/status/queries";
import { getDeviceToken, setDeviceToken } from "@/lib/api"; import { getDeviceToken, setDeviceToken } from "@/lib/api";
@@ -35,13 +32,6 @@ import { useConnectionStore } from "@/stores/connection";
import "@/styles/pages/connect.css"; import "@/styles/pages/connect.css";
function scopeTone(scope: string): "default" | "info" | "ok" {
if (scope === "read") return "default";
if (scope === "steer") return "info";
if (scope === "apply") return "ok";
return "default";
}
/** /**
* Port default for the manual form. The loaded daemon info wins; otherwise the * Port default for the manual form. The loaded daemon info wins; otherwise the
* port this console was served from, else the scheme default. Never a literal. * port this console was served from, else the scheme default. Never a literal.
@@ -74,19 +64,11 @@ export function ConnectPage() {
const connectedAt = useConnectionStore((state) => state.connectedAt); const connectedAt = useConnectionStore((state) => state.connectedAt);
const wsState = useConnectionStore((state) => state.wsState); const wsState = useConnectionStore((state) => state.wsState);
const storedServer = useConnectionStore((state) => state.server); const storedServer = useConnectionStore((state) => state.server);
const storedScopes = useConnectionStore((state) => state.scopes);
const [meta, setMeta] = useState<PairMeta | null>(() => readPairMeta()); const [meta, setMeta] = useState<PairMeta | null>(() => readPairMeta());
const [scanOpen, setScanOpen] = useState(false); /** Connected state: the re-pair panel (the manual form) expands in place. */
const [pending, setPending] = useState<PairTarget | null>(null);
const [pairError, setPairError] = useState<string | null>(null);
const [redeeming, setRedeeming] = useState(false);
/** Manual pairing form: collapsed by default in both states. */
const [manualOpen, setManualOpen] = useState(() => codeParam !== "");
/** Connected state: the re-pair panel expands in place. */
const [repairOpen, setRepairOpen] = useState(false); const [repairOpen, setRepairOpen] = useState(false);
const [repairManualOpen, setRepairManualOpen] = useState(false); /** `/connect?…&auto=1` (from a `/pair/<CODE>` link): pair with no input. */
/** `/connect?…&auto=1` (from a scanned `/pair/<CODE>` link): pair with no input. */
const autoParam = useMemo(() => { const autoParam = useMemo(() => {
const raw = search.get("auto"); const raw = search.get("auto");
return raw === "1" || raw === "true"; return raw === "1" || raw === "true";
@@ -120,7 +102,6 @@ export function ConnectPage() {
fetchedAt: info.dataUpdatedAt || null, fetchedAt: info.dataUpdatedAt || null,
nameFallback: storedServer?.name || meta?.server?.name, nameFallback: storedServer?.name || meta?.server?.name,
}); });
const scopes = scopesForIdentity(meta, info.data, storedScopes);
const defaultDeviceName = t("connect.defaultDeviceName"); const defaultDeviceName = t("connect.defaultDeviceName");
const osLabel = info.data?.os || info.data?.platform || server.os || "—"; const osLabel = info.data?.os || info.data?.platform || server.os || "—";
const uptimeSeconds = const uptimeSeconds =
@@ -128,9 +109,9 @@ export function ConnectPage() {
const defaultPort = defaultPortFor(info.data?.port ?? server.port); const defaultPort = defaultPortFor(info.data?.port ?? server.port);
/** /**
* One pairing path for the scan/confirm dialog and the manual form: * One pairing path for the zero-input link and the manual form: redeem
* redeem against the public endpoint, persist token + scopes, then follow * against the public endpoint, persist token + metadata, then follow the
* the allow-listed `next`. * allow-listed `next`.
*/ */
const finishPairing = useCallback( const finishPairing = useCallback(
async (target: PairTarget, deviceName: string) => { async (target: PairTarget, deviceName: string) => {
@@ -140,17 +121,15 @@ export function ConnectPage() {
deviceName, deviceName,
}); });
setDeviceToken(result.token); setDeviceToken(result.token);
connect({ endpoint: target.endpoint, deviceName, token: result.token, scopes: result.scopes }); connect({ endpoint: target.endpoint, deviceName, token: result.token });
const nextMeta: PairMeta = { const nextMeta: PairMeta = {
scopes: result.scopes,
deviceName, deviceName,
kind: result.kind, kind: result.kind,
server: result.server,
pairedAt: Date.now(), pairedAt: Date.now(),
}; };
writePairMeta(nextMeta); writePairMeta(nextMeta);
setMeta(nextMeta); setMeta(nextMeta);
toast.success(t("connect.connected", { name: result.server?.name || target.name })); toast.success(t("connect.connected", { name: target.name }));
navigate({ href: next }); navigate({ href: next });
}, },
[connect, navigate, next, t], [connect, navigate, next, t],
@@ -204,45 +183,14 @@ export function ConnectPage() {
); );
} }
const handleFound = useCallback((target: PairTarget) => {
setPairError(null);
setPending(target);
}, []);
async function confirmPending() {
if (!pending || redeeming) return;
setRedeeming(true);
setPairError(null);
try {
await finishPairing(pending, defaultDeviceName);
setPending(null);
} catch (error) {
const message = t(pairErrorMessage(error));
setPairError(message);
toast.error(message);
} finally {
setRedeeming(false);
}
}
function handleDisconnect() { function handleDisconnect() {
disconnect(); disconnect();
clearPairMeta(); clearPairMeta();
setMeta(null); setMeta(null);
setRepairOpen(false); setRepairOpen(false);
setManualOpen(false);
toast.success(t("connect.disconnected")); toast.success(t("connect.disconnected"));
} }
function toggleRepair() {
setRepairOpen((open) => {
const nextOpen = !open;
// Collapsing also collapses the form so re-opening is never "half open".
if (!nextOpen) setRepairManualOpen(false);
return nextOpen;
});
}
function renderManualForm(expanded: boolean, primary: boolean) { function renderManualForm(expanded: boolean, primary: boolean) {
return ( return (
<ManualConnectForm <ManualConnectForm
@@ -260,28 +208,6 @@ export function ConnectPage() {
); );
} }
function manualToggle(expanded: boolean, onToggle: () => void) {
return (
<Button
variant="ghost"
className="cn-toggle"
aria-expanded={expanded}
aria-controls={formId}
aria-label={
expanded
? t("connect.collapseManual", { defaultValue: "Hide manual connection" })
: t("connect.expandManual", { defaultValue: "Show manual connection" })
}
onClick={onToggle}
>
<span className="cn-ico cn-toggle__chev">
<Icon name="chevron-down" />
</span>
<span>{t("connect.manual")}</span>
</Button>
);
}
/** Connected: summary + back (primary by default) / re-pair / disconnect. */ /** Connected: summary + back (primary by default) / re-pair / disconnect. */
function connectedPanel() { function connectedPanel() {
return ( return (
@@ -303,24 +229,6 @@ export function ConnectPage() {
</KV> </KV>
<KV label={t("connect.version")}>{info.data?.version || meta?.server?.version || "—"}</KV> <KV label={t("connect.version")}>{info.data?.version || meta?.server?.version || "—"}</KV>
<KV label={t("connect.device")}>{storedDeviceName || meta?.deviceName || "—"}</KV> <KV label={t("connect.device")}>{storedDeviceName || meta?.deviceName || "—"}</KV>
<KV label={t("connect.scopes")} className="cn-kv--badges">
{scopes.length ? (
<span className="cn-scopes">
{scopes.map((scope) => (
<Badge
key={scope}
className="badge--outline"
tone={scopeTone(scope)}
title={t("connect.scopeHint", { scope })}
>
{t(`connect.scope.${scope}`, { defaultValue: scope })}
</Badge>
))}
</span>
) : (
<span className="faint">—</span>
)}
</KV>
<KV label={t("connect.lastConnected")}> <KV label={t("connect.lastConnected")}>
<RelativeTime ts={connectedAt || meta?.pairedAt || null} /> <RelativeTime ts={connectedAt || meta?.pairedAt || null} />
</KV> </KV>
@@ -342,9 +250,9 @@ export function ConnectPage() {
aria-expanded={repairOpen} aria-expanded={repairOpen}
aria-controls="cn-repair" aria-controls="cn-repair"
data-testid="connect-repair" data-testid="connect-repair"
onClick={toggleRepair} onClick={() => setRepairOpen((open) => !open)}
> >
<Icon name="scan" /> <Icon name="refresh" />
{t("connect.reconnect")} {t("connect.reconnect")}
</Button> </Button>
</div> </div>
@@ -360,22 +268,7 @@ export function ConnectPage() {
</div> </div>
<div className="cn-repair" id="cn-repair" hidden={!repairOpen} data-testid="connect-repair-panel"> <div className="cn-repair" id="cn-repair" hidden={!repairOpen} data-testid="connect-repair-panel">
<div className="cn-pair"> {renderManualForm(repairOpen, repairOpen)}
<Button
variant={repairOpen && !repairManualOpen ? "primary" : "default"}
className="cn-pair__btn"
data-testid="connect-repair-scan"
onClick={() => setScanOpen(true)}
>
<Icon name="scan" />
{t("connect.scan")}
</Button>
<div className="cn-or" aria-hidden="true">
<span>{t("connect.or", { defaultValue: "or" })}</span>
</div>
{manualToggle(repairManualOpen, () => setRepairManualOpen((open) => !open))}
</div>
{renderManualForm(repairManualOpen, repairOpen && repairManualOpen)}
</div> </div>
<details className="cn-details"> <details className="cn-details">
@@ -412,7 +305,7 @@ export function ConnectPage() {
); );
} }
/** Unconnected: scan-to-pair is the single primary until the form opens. */ /** Unconnected: the manual form is the single path and the primary action. */
function unconnectedPanel() { function unconnectedPanel() {
return ( return (
<section className="card card--quiet cn-card" aria-labelledby="cn-card-title"> <section className="card card--quiet cn-card" aria-labelledby="cn-card-title">
@@ -436,23 +329,7 @@ export function ConnectPage() {
</div> </div>
) : null} ) : null}
<div className="cn-pair"> {renderManualForm(true, true)}
<Button
variant={manualOpen ? "default" : "primary"}
className="cn-pair__btn"
data-testid="connect-scan"
onClick={() => setScanOpen(true)}
>
<Icon name="scan" />
{t("connect.scan")}
</Button>
<div className="cn-or" aria-hidden="true">
<span>{t("connect.or", { defaultValue: "or" })}</span>
</div>
{manualToggle(manualOpen, () => setManualOpen((open) => !open))}
</div>
{renderManualForm(manualOpen, manualOpen)}
</section> </section>
); );
} }
@@ -477,73 +354,6 @@ export function ConnectPage() {
</div> </div>
</div> </div>
<ScanDialog
open={scanOpen}
onOpenChange={setScanOpen}
onFound={handleFound}
fallbackEndpoint={storedEndpoint}
/>
<Modal
open={pending != null}
onOpenChange={(open) => {
if (!open && !redeeming) setPending(null);
}}
title={t("connect.confirmTitle")}
footer={
<>
<Button
variant="ghost"
data-testid="connect-confirm-cancel"
onClick={() => {
setPairError(null);
setPending(null);
}}
disabled={redeeming}
>
{t("common.cancel")}
</Button>
<Button
variant="primary"
data-testid="connect-confirm-connect"
onClick={() => void confirmPending()}
disabled={redeeming}
>
{redeeming ? t("connect.connecting") : t("connect.connect")}
</Button>
</>
}
>
{pending ? (
<div>
<p className="cn-lead">{t("connect.scanLead")}</p>
<div className="cn-confirm">
<KV label={t("connect.server")}>{pending.name || pending.hostname}</KV>
<KV label={t("connect.endpoint")} mono>
{pending.hostname}:{pending.port}
</KV>
<KV label={t("connect.pairCode")} mono>
{maskSecret(pending.code)}
</KV>
</div>
<div className="cn-warn">
<span className="cn-ico">
<Icon name="alert" />
</span>
<span>{t("connect.scanWarning")}</span>
</div>
{pairError ? (
<div className="cn-error" role="alert">
<span className="cn-ico">
<Icon name="alert" />
</span>
<span>{pairError}</span>
</div>
) : null}
</div>
) : null}
</Modal>
<ConfirmDialog <ConfirmDialog
open={disconnectOpen} open={disconnectOpen}
onOpenChange={setDisconnectOpen} onOpenChange={setDisconnectOpen}
-3
View File
@@ -11,7 +11,6 @@ import { toast } from "@/components/ui/toast";
import { import {
clearPairMeta, clearPairMeta,
readPairMeta, readPairMeta,
scopesForIdentity,
} from "@/features/connect/pairing"; } from "@/features/connect/pairing";
import { ConnectionCard } from "@/features/status/connection-card"; import { ConnectionCard } from "@/features/status/connection-card";
import { deviceKey, DevicesCard } from "@/features/status/devices-card"; import { deviceKey, DevicesCard } from "@/features/status/devices-card";
@@ -84,7 +83,6 @@ export function StatusPage() {
const models = useModelsQuery(modelsWorkspaceId); const models = useModelsQuery(modelsWorkspaceId);
const meta = useMemo(() => readPairMeta(), []); const meta = useMemo(() => readPairMeta(), []);
const scopes = scopesForIdentity(meta, info.data);
const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined); const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined);
const server = deriveServerIdentity({ const server = deriveServerIdentity({
@@ -242,7 +240,6 @@ export function StatusPage() {
<ConnectionCard <ConnectionCard
server={server} server={server}
deviceName={storedDeviceName || meta?.deviceName || ""} deviceName={storedDeviceName || meta?.deviceName || ""}
scopes={scopes}
connectedAt={connectedAt || meta?.pairedAt || null} connectedAt={connectedAt || meta?.pairedAt || null}
loading={info.isPending} loading={info.isPending}
error={info.isError ? translatedError(info.error, "status.infoError", t) : null} error={info.isError ? translatedError(info.error, "status.infoError", t) : null}
+2 -32
View File
@@ -8,9 +8,6 @@ export const CONNECTION_KEY = "pi2-connection";
export const ENDPOINT_KEY = "pi2-endpoint"; export const ENDPOINT_KEY = "pi2-endpoint";
export const DEVICE_KEY = "pi2-device"; export const DEVICE_KEY = "pi2-device";
export const CONNECTED_AT_KEY = "pi2-connected-at"; export const CONNECTED_AT_KEY = "pi2-connected-at";
export const SCOPES_KEY = "pi2-device-scopes";
/** Scope assumed for devices paired before scopes were persisted. */
export const DEFAULT_CONNECTION_SCOPES = ["read"] as const;
function read(key: string): string | null { function read(key: string): string | null {
try { try {
@@ -36,26 +33,6 @@ function drop(key: string): void {
} }
} }
/** Persisted device scopes; defaults to `["read"]` when absent or unreadable. */
function readScopes(): string[] {
const raw = read(SCOPES_KEY);
if (!raw) return [...DEFAULT_CONNECTION_SCOPES];
try {
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) {
const scopes = parsed.filter((item): item is string => typeof item === "string" && item.trim() !== "");
return scopes.length ? scopes : [...DEFAULT_CONNECTION_SCOPES];
}
} catch {
/* fall through to the default */
}
return [...DEFAULT_CONNECTION_SCOPES];
}
function writeScopes(scopes: string[]): void {
write(SCOPES_KEY, JSON.stringify(scopes.length ? scopes : DEFAULT_CONNECTION_SCOPES));
}
export type PairingState = "paired" | "unpaired"; export type PairingState = "paired" | "unpaired";
export interface ConnectionStore { export interface ConnectionStore {
@@ -65,14 +42,12 @@ export interface ConnectionStore {
deviceName: string; deviceName: string;
connectedAt: number; connectedAt: number;
token: string | null; token: string | null;
/** Device scopes granted by the daemon when this browser was paired. */
scopes: string[];
server: InfoResponse | null; server: InfoResponse | null;
wsState: WsConnectionState; wsState: WsConnectionState;
isPaired: () => boolean; isPaired: () => boolean;
refreshFromStorage: () => void; refreshFromStorage: () => void;
connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null; scopes?: string[] }) => void; connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void;
disconnect: () => void; disconnect: () => void;
setServer: (server: InfoResponse | null) => void; setServer: (server: InfoResponse | null) => void;
setWsState: (state: WsConnectionState) => void; setWsState: (state: WsConnectionState) => void;
@@ -86,7 +61,6 @@ function initialState() {
deviceName: read(DEVICE_KEY) ?? "", deviceName: read(DEVICE_KEY) ?? "",
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0, connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
token: getDeviceToken(), token: getDeviceToken(),
scopes: readScopes(),
server: null as InfoResponse | null, server: null as InfoResponse | null,
wsState: "idle" as WsConnectionState, wsState: "idle" as WsConnectionState,
}; };
@@ -99,12 +73,11 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
refreshFromStorage: () => set(initialState()), refreshFromStorage: () => set(initialState()),
connect: ({ endpoint, deviceName, token, scopes } = {}) => { connect: ({ endpoint, deviceName, token } = {}) => {
const now = Date.now(); const now = Date.now();
if (endpoint) write(ENDPOINT_KEY, endpoint); if (endpoint) write(ENDPOINT_KEY, endpoint);
if (deviceName) write(DEVICE_KEY, deviceName); if (deviceName) write(DEVICE_KEY, deviceName);
if (token !== undefined) setDeviceToken(token); if (token !== undefined) setDeviceToken(token);
if (scopes !== undefined) writeScopes(scopes);
write(CONNECTED_AT_KEY, String(now)); write(CONNECTED_AT_KEY, String(now));
write(CONNECTION_KEY, "paired"); write(CONNECTION_KEY, "paired");
set({ set({
@@ -113,7 +86,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
deviceName: deviceName ?? get().deviceName, deviceName: deviceName ?? get().deviceName,
connectedAt: now, connectedAt: now,
token: getDeviceToken(), token: getDeviceToken(),
scopes: scopes !== undefined ? readScopes() : get().scopes,
}); });
}, },
@@ -121,7 +93,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
drop(ENDPOINT_KEY); drop(ENDPOINT_KEY);
drop(DEVICE_KEY); drop(DEVICE_KEY);
drop(CONNECTED_AT_KEY); drop(CONNECTED_AT_KEY);
drop(SCOPES_KEY);
setDeviceToken(null); setDeviceToken(null);
write(CONNECTION_KEY, "unpaired"); write(CONNECTION_KEY, "unpaired");
set({ set({
@@ -130,7 +101,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
deviceName: "", deviceName: "",
connectedAt: 0, connectedAt: 0,
token: null, token: null,
scopes: [...DEFAULT_CONNECTION_SCOPES],
server: null, server: null,
wsState: "idle", wsState: "idle",
}); });
+2 -139
View File
@@ -102,7 +102,7 @@
} }
.cn-card__sub { color: var(--muted-foreground); font-size: var(--fs-sm); line-height: var(--lh-body); } .cn-card__sub { color: var(--muted-foreground); font-size: var(--fs-sm); line-height: var(--lh-body); }
/* ---------- unconnected: one primary (scan) ---------- */ /* ---------- unconnected: the manual form is the single path ---------- */
.cn-qr { .cn-qr {
display: grid; display: grid;
place-items: center; place-items: center;
@@ -115,29 +115,6 @@
color: var(--faint); color: var(--faint);
} }
.cn-qr svg { width: 34px; height: 34px; display: block; } .cn-qr svg { width: 34px; height: 34px; display: block; }
.cn-pair { display: flex; flex-direction: column; gap: var(--space-2); }
.cn-pair .btn { width: 100%; justify-content: center; }
.cn-or {
display: flex;
align-items: center;
gap: 10px;
color: var(--faint);
font-size: var(--fs-2xs);
text-transform: uppercase;
letter-spacing: .06em;
}
.cn-or::before,
.cn-or::after {
content: "";
height: 1px;
flex: 1;
background: var(--border-subtle);
}
.cn-toggle { color: var(--muted-foreground); }
.cn-toggle:hover { color: var(--foreground); }
.cn-toggle__chev svg { transition: transform var(--dur) var(--ease-out); }
.cn-toggle[aria-expanded="true"] .cn-toggle__chev svg { transform: rotate(180deg); }
/* ---------- connected: summary card ---------- */ /* ---------- connected: summary card ---------- */
.cn-state { gap: var(--space-3); } .cn-state { gap: var(--space-3); }
.cn-state__head { .cn-state__head {
@@ -168,8 +145,6 @@
.cn-kvs .kv { padding: 4px 0; } .cn-kvs .kv { padding: 4px 0; }
.cn-kvs .kv > .kv-key { flex: none; font-size: var(--fs-xs); color: var(--faint); } .cn-kvs .kv > .kv-key { flex: none; font-size: var(--fs-xs); color: var(--faint); }
.cn-kvs .kv > .kv-val { font-size: var(--fs-sm); font-variant-numeric: tabular-nums; } .cn-kvs .kv > .kv-val { font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
.cn-kv--badges { align-items: center; }
.cn-scopes { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: var(--space-1); }
.cn-actions { .cn-actions {
display: flex; display: flex;
@@ -267,111 +242,6 @@
.cn .btn .cn-ico svg { width: 15px; height: 15px; display: block; } .cn .btn .cn-ico svg { width: 15px; height: 15px; display: block; }
.cn .btn svg { width: 15px; height: 15px; } .cn .btn svg { width: 15px; height: 15px; }
/* ---------- scan modal ---------- */
.cn-scan { display: flex; flex-direction: column; gap: var(--space-3); }
.cn-scan .btn { min-height: 2.5rem; }
.cn-scan__viewport {
position: relative;
width: 100%;
aspect-ratio: 4 / 3;
max-height: 46dvh;
display: grid;
place-items: center;
overflow: hidden;
background: var(--surface-1);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
transition: background var(--dur) var(--ease-out);
}
.cn-scan__video {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
opacity: 0;
transition: opacity var(--dur) var(--ease-out);
}
.cn-scan__viewport.is-live .cn-scan__video { opacity: 1; }
.cn-scan__placeholder {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-2);
padding: var(--space-4);
text-align: center;
color: var(--muted-foreground);
font-size: var(--fs-sm);
}
.cn-scan__placeholder .cn-ico svg { width: 28px; height: 28px; }
.cn-scan__viewport.is-live .cn-scan__placeholder { display: none; }
.cn-scan__frame {
position: absolute;
inset: 15%;
border: 2px solid color-mix(in oklch, var(--primary) 75%, transparent);
border-radius: var(--radius-lg);
box-shadow: 0 0 0 100vmax color-mix(in oklch, var(--background) 45%, transparent);
pointer-events: none;
}
.cn-scan__viewport:not(.is-live) .cn-scan__frame { display: none; }
.cn-scan__state { font-size: var(--fs-sm); color: var(--muted-foreground); min-height: 1.4em; }
.cn-hint { font-size: var(--fs-xs); color: var(--faint); }
/* paste-link fallback */
.cn-fold { border-top: 1px solid var(--border-subtle); padding-top: var(--space-1); }
.cn-fold > summary {
display: flex;
align-items: center;
gap: 6px;
min-height: 2.5rem;
cursor: pointer;
list-style: none;
font-size: var(--fs-sm);
font-weight: 550;
color: var(--muted-foreground);
transition: color var(--dur-fast) var(--ease-out);
}
.cn-fold > summary::-webkit-details-marker { display: none; }
.cn-fold > summary::before {
content: "▸";
display: inline-block;
width: 1.1em;
transition: transform var(--dur-fast) var(--ease-out);
}
.cn-fold[open] > summary::before { content: "▾"; }
.cn-fold > summary:hover { color: var(--foreground); }
.cn-fold__body { display: flex; gap: var(--space-2); padding-top: var(--space-2); }
.cn-fold__body .input { min-width: 0; }
.cn-fold .input.is-invalid {
border-color: var(--destructive);
box-shadow: 0 0 0 3px color-mix(in oklch, var(--destructive) 20%, transparent);
}
.cn-scan__actions { display: flex; flex-wrap: wrap; gap: var(--space-2); }
/* scan → confirm dialog body */
.cn-lead { font-size: var(--fs-sm); color: var(--muted-foreground); margin-bottom: var(--space-3); }
.cn-confirm {
display: flex;
flex-direction: column;
gap: 2px;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius);
background: var(--surface-1);
border: 1px solid var(--border-subtle);
}
.cn-confirm .kv { padding: 2px 0; }
.cn-warn {
display: flex;
align-items: flex-start;
gap: 8px;
margin-top: var(--space-3);
font-size: var(--fs-sm);
color: var(--muted-foreground);
}
.cn-warn .cn-ico { margin-top: 2px; color: var(--warn); }
/* ---------- <900: single column, centred brand ---------- */ /* ---------- <900: single column, centred brand ---------- */
@media (max-width: 899px) { @media (max-width: 899px) {
.cn-hero { align-items: center; text-align: center; } .cn-hero { align-items: center; text-align: center; }
@@ -388,12 +258,9 @@
.cn-hero__title { font-size: var(--fs-xl); } .cn-hero__title { font-size: var(--fs-xl); }
.cn-features { gap: 6px; } .cn-features { gap: 6px; }
.cn .card--quiet { padding: var(--space-4); } .cn .card--quiet { padding: var(--space-4); }
.cn .btn, .cn .btn { min-height: 44px; }
.cn-scan .btn { min-height: 44px; }
.cn .input { min-height: 44px; } .cn .input { min-height: 44px; }
.cn-details > summary { min-height: 44px; } .cn-details > summary { min-height: 44px; }
.cn-fold > summary { min-height: 44px; }
.cn-scan .input { min-height: 44px; }
.cn-actions { flex-direction: column; align-items: stretch; } .cn-actions { flex-direction: column; align-items: stretch; }
.cn-actions__main { flex-direction: column; align-items: stretch; } .cn-actions__main { flex-direction: column; align-items: stretch; }
.cn-actions .btn, .cn-actions .btn,
@@ -401,8 +268,4 @@
.cn-row { grid-template-columns: minmax(0, 1fr); } .cn-row { grid-template-columns: minmax(0, 1fr); }
.cn-form__foot .btn, .cn-form__foot .btn,
.cn-submit { width: 100%; } .cn-submit { width: 100%; }
.cn-fold__body { flex-direction: column; }
.cn-fold__body .btn { width: 100%; }
.cn-kv--badges { flex-direction: column; align-items: flex-start; gap: var(--space-1); }
.cn-scopes { justify-content: flex-start; }
} }
+15 -4
View File
@@ -276,9 +276,8 @@
.device-icon svg { width: 16px; height: 16px; } .device-icon svg { width: 16px; height: 16px; }
.device-main { min-width: 0; } .device-main { min-width: 0; }
.device-name { font-size: var(--fs-sm); font-weight: var(--fw-medium); } .device-name { font-size: var(--fs-sm); font-weight: var(--fw-medium); }
.device-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 2px; } .device-meta { margin-top: 2px; }
.device-time { flex: none; font-size: var(--fs-xs); } .device-time { flex: none; font-size: var(--fs-xs); }
.status-scopes { display: inline-flex; flex-wrap: wrap; gap: 4px; min-width: 0; }
.status-icon-btn { width: 28px; height: 28px; color: var(--faint); } .status-icon-btn { width: 28px; height: 28px; color: var(--faint); }
.status-icon-btn:hover { .status-icon-btn:hover {
color: var(--destructive); color: var(--destructive);
@@ -356,10 +355,8 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
word-break: break-all; word-break: break-all;
} }
.conn-kv .status-scopes__wrap { justify-content: flex-start; }
/* the endpoint address spans both columns so it is never folded in half */ /* the endpoint address spans both columns so it is never folded in half */
.conn-kv .status-kv--wide { grid-column: 1 / -1; } .conn-kv .status-kv--wide { grid-column: 1 / -1; }
.status-scopes__wrap { display: flex; justify-content: flex-end; min-width: 0; }
.pair-code-block { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; } .pair-code-block { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.pair-code { .pair-code {
@@ -399,6 +396,20 @@
border: 1px solid var(--border-subtle); border: 1px solid var(--border-subtle);
border-radius: var(--radius); border-radius: var(--radius);
} }
/* no `qr` payload (URL too long): the link itself is the pairing surface */
.qr-link {
display: block;
width: 100%;
padding: 8px 10px;
border-radius: var(--radius);
border: 1px dashed var(--border-subtle);
background: var(--card);
color: var(--muted-foreground);
font-size: var(--fs-xs);
line-height: 1.45;
overflow-wrap: anywhere;
word-break: break-all;
}
.pair-hint { display: flex; align-items: flex-start; gap: 5px; font-size: var(--fs-xs); line-height: 1.45; } .pair-hint { display: flex; align-items: flex-start; gap: 5px; font-size: var(--fs-xs); line-height: 1.45; }
.pair-hint svg { width: 13px; height: 13px; flex: none; margin-top: 2px; } .pair-hint svg { width: 13px; height: 13px; flex: none; margin-top: 2px; }
.pair-expiry { font-size: var(--fs-xs); white-space: nowrap; } .pair-expiry { font-size: var(--fs-xs); white-space: nowrap; }
+71 -97
View File
@@ -31,11 +31,11 @@ function routes() {
]; ];
} }
/** `POST <origin>/api/v1/pair` → `{token, device}` (the public redeem contract). */ /** `POST <origin>/api/v1/pair/redeem` → `{token, device}` (the public redeem contract). */
function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute { function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
return { return {
method: "POST", method: "POST",
path: "/api/v1/pair", path: "/api/v1/pair/redeem",
handler: () => ({ handler: () => ({
status: reply.status ?? 200, status: reply.status ?? 200,
body: reply.body ?? { body: reply.body ?? {
@@ -44,7 +44,6 @@ function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
id: "dev-7c1", id: "dev-7c1",
name: "My browser", name: "My browser",
kind: "laptop", kind: "laptop",
scopes: ["read", "steer"],
lastSeenAt: 1_700_000_000_000, lastSeenAt: 1_700_000_000_000,
}, },
}, },
@@ -54,31 +53,35 @@ function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
interface PairCall { interface PairCall {
origin: string; origin: string;
path: string;
body: Record<string, unknown>; body: Record<string, unknown>;
} }
/** Every recorded `POST` to the pairing surface (mint or redeem). */
function pairCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] { function pairCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] {
return fetchMock.mock.calls return fetchMock.mock.calls
.filter(([input, init]) => { .filter(([input, init]) => {
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
return new URL(raw, "http://localhost").pathname === "/api/v1/pair" && (init?.method ?? "GET") === "POST"; const path = new URL(raw, "http://localhost").pathname;
return path.startsWith("/api/v1/pair") && (init?.method ?? "GET") === "POST";
}) })
.map(([input, init]) => { .map(([input, init]) => {
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(raw, "http://localhost"); const url = new URL(raw, "http://localhost");
return { origin: url.origin, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> }; return {
origin: url.origin,
path: url.pathname,
body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown>,
};
}); });
} }
/** Expand the collapsed manual form (both states use the same toggle labels). */ function redeemCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] {
function expandManual() { return pairCalls(fetchMock).filter((call) => call.path === "/api/v1/pair/redeem");
const toggle = document.querySelector<HTMLButtonElement>('.cn-toggle[aria-expanded="false"]');
if (!toggle) throw new Error("manual toggle not found");
fireEvent.click(toggle);
return toggle;
} }
function fillManualForm(values: { host?: string; port?: string; code?: string; device?: string }) { function fillManualForm(values: { host?: string; port?: string; code?: string; device?: string; link?: string }) {
if (values.link !== undefined) fireEvent.change(screen.getByTestId("connect-link"), { target: { value: values.link } });
if (values.host !== undefined) fireEvent.change(screen.getByTestId("connect-host"), { target: { value: values.host } }); if (values.host !== undefined) fireEvent.change(screen.getByTestId("connect-host"), { target: { value: values.host } });
if (values.port !== undefined) fireEvent.change(screen.getByTestId("connect-port"), { target: { value: values.port } }); if (values.port !== undefined) fireEvent.change(screen.getByTestId("connect-port"), { target: { value: values.port } });
if (values.code !== undefined) { if (values.code !== undefined) {
@@ -117,37 +120,22 @@ describe("ConnectPage", () => {
expect(document.querySelector(".cn-col .cn-card.card--quiet")).not.toBeNull(); expect(document.querySelector(".cn-col .cn-card.card--quiet")).not.toBeNull();
}); });
it("keeps a single primary (scan) and the manual form collapsed by default", async () => { it("keeps the manual form expanded as the single primary action", async () => {
mockApi([pairRoute()]); mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false }); await renderPage(routes(), "/connect", { paired: false });
const scan = screen.getByTestId("connect-scan"); // The camera scanner is gone: the form is the only path and it is open.
expect(scan).toHaveClass("btn--primary"); expect(screen.queryByTestId("connect-scan")).toBeNull();
expect(primaries()).toHaveLength(1);
const panel = screen.getByTestId("connect-manual-panel"); const panel = screen.getByTestId("connect-manual-panel");
expect(panel).toHaveAttribute("hidden");
// Expanding moves the primary onto the form submit and focuses the host field.
expandManual();
expect(panel).not.toHaveAttribute("hidden"); expect(panel).not.toHaveAttribute("hidden");
expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary"); expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
expect(screen.getByTestId("connect-scan")).not.toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1); expect(primaries()).toHaveLength(1);
expect(screen.getByTestId("connect-host")).toHaveFocus(); expect(screen.getByTestId("connect-host")).toHaveFocus();
// Collapsing hands the primary back to the scan button.
const toggle = document.querySelector<HTMLButtonElement>('.cn-toggle[aria-expanded="true"]');
fireEvent.click(toggle as HTMLButtonElement);
expect(panel).toHaveAttribute("hidden");
expect(screen.getByTestId("connect-scan")).toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1);
}); });
it("defaults the port to the port this console was served from, never a literal", async () => { it("defaults the port to the port this console was served from, never a literal", async () => {
mockApi([pairRoute()]); mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false }); await renderPage(routes(), "/connect", { paired: false });
expandManual();
const port = screen.getByTestId("connect-port"); const port = screen.getByTestId("connect-port");
const servedPort = window.location.port || (window.location.protocol === "https:" ? "443" : "80"); const servedPort = window.location.port || (window.location.protocol === "https:" ? "443" : "80");
@@ -167,14 +155,12 @@ describe("ConnectPage", () => {
await waitFor(() => expect(screen.getByTestId("connect-repair")).toBeInTheDocument()); await waitFor(() => expect(screen.getByTestId("connect-repair")).toBeInTheDocument());
fireEvent.click(screen.getByTestId("connect-repair")); fireEvent.click(screen.getByTestId("connect-repair"));
expandManual();
await waitFor(() => expect(screen.getByTestId("connect-port")).toHaveValue("7676")); await waitFor(() => expect(screen.getByTestId("connect-port")).toHaveValue("7676"));
}); });
it("validates host, port and the 8-character pairing code inline without calling the daemon", async () => { it("validates host, port and the 8-character pairing code inline without calling the daemon", async () => {
const fetchMock = mockApi([pairRoute()]); const fetchMock = mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false }); await renderPage(routes(), "/connect", { paired: false });
expandManual();
const submit = screen.getByTestId("connect-submit"); const submit = screen.getByTestId("connect-submit");
fireEvent.click(submit); fireEvent.click(submit);
@@ -198,17 +184,41 @@ describe("ConnectPage", () => {
it("labels the third field as a pairing code and uppercases input", async () => { it("labels the third field as a pairing code and uppercases input", async () => {
mockApi([pairRoute()]); mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false }); await renderPage(routes(), "/connect", { paired: false });
expandManual();
expect(screen.getByLabelText("Pairing code")).toBe(screen.getByTestId("connect-pair-code")); expect(screen.getByLabelText("Pairing code")).toBe(screen.getByTestId("connect-pair-code"));
fillManualForm({ code: "ab-cd12 34" }); fillManualForm({ code: "ab-cd12 34" });
expect(screen.getByTestId("connect-pair-code")).toHaveValue("ABCD1234"); expect(screen.getByTestId("connect-pair-code")).toHaveValue("ABCD1234");
}); });
it("redeems a manual pairing against /api/v1/pair, stores token + scopes and redirects", async () => { it("prefills host, port and code from a pasted pi2:// pairing link", async () => {
mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false });
fillManualForm({ link: "pi2://pair?host=192.168.2.10&port=4321&code=AB-CD-12-34" });
expect(screen.getByTestId("connect-host")).toHaveValue("192.168.2.10");
expect(screen.getByTestId("connect-port")).toHaveValue("4321");
expect(screen.getByTestId("connect-pair-code")).toHaveValue("ABCD1234");
});
it("prefills from a pasted /pair/CODE link and reports an unparseable one", async () => {
mockApi([pairRoute()]);
await renderPage(routes(), "/connect", { paired: false });
fillManualForm({ link: "/pair/ABCD1234" });
expect(screen.getByTestId("connect-host")).toHaveValue(window.location.hostname);
expect(screen.getByTestId("connect-port")).toHaveValue(window.location.port);
expect(screen.getByTestId("connect-pair-code")).toHaveValue("ABCD1234");
fillManualForm({ link: "https://example.invalid/nothing-here" });
fireEvent.click(screen.getByTestId("connect-submit"));
expect(
await screen.findByText("Could not parse it. Paste the full pi2://pair link."),
).toBeInTheDocument();
});
it("redeems a manual pairing against /api/v1/pair/redeem, stores the token and redirects", async () => {
const fetchMock = mockApi([pairRoute()]); const fetchMock = mockApi([pairRoute()]);
const { router } = await renderPage(routes(), "/connect", { paired: false }); const { router } = await renderPage(routes(), "/connect", { paired: false });
expandManual();
fillManualForm({ host: "192.168.2.10", port: "4321", code: "abcd1234", device: "My browser" }); fillManualForm({ host: "192.168.2.10", port: "4321", code: "abcd1234", device: "My browser" });
fireEvent.click(screen.getByTestId("connect-submit")); fireEvent.click(screen.getByTestId("connect-submit"));
@@ -216,12 +226,13 @@ describe("ConnectPage", () => {
await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test")); await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test"));
expect(localStorage.getItem("pi2-endpoint")).toBe("http://192.168.2.10:4321"); expect(localStorage.getItem("pi2-endpoint")).toBe("http://192.168.2.10:4321");
expect(localStorage.getItem("pi2-connection")).toBe("paired"); expect(localStorage.getItem("pi2-connection")).toBe("paired");
expect(JSON.parse(localStorage.getItem("pi2-device-scopes") ?? "[]")).toEqual(["read", "steer"]);
const calls = pairCalls(fetchMock); const calls = redeemCalls(fetchMock);
expect(calls).toHaveLength(1); expect(calls).toHaveLength(1);
expect(calls[0]?.origin).toBe("http://192.168.2.10:4321"); expect(calls[0]?.origin).toBe("http://192.168.2.10:4321");
expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "My browser" }); expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "My browser" });
// The mint path is not the redeem path anymore.
expect(pairCalls(fetchMock).filter((call) => call.path === "/api/v1/pair")).toHaveLength(0);
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces")); await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
expect(await screen.findByText("Workspaces destination")).toBeInTheDocument(); expect(await screen.findByText("Workspaces destination")).toBeInTheDocument();
@@ -239,14 +250,15 @@ describe("ConnectPage", () => {
await waitFor(() => expect(localStorage.getItem("pi2-connection")).toBe("paired")); await waitFor(() => expect(localStorage.getItem("pi2-connection")).toBe("paired"));
expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test"); expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test");
expect(localStorage.getItem("pi2-endpoint")).toBe(origin); expect(localStorage.getItem("pi2-endpoint")).toBe(origin);
expect(JSON.parse(localStorage.getItem("pi2-device-scopes") ?? "[]")).toEqual(["read", "steer"]);
const calls = pairCalls(fetchMock); const calls = redeemCalls(fetchMock);
expect(calls).toHaveLength(1); expect(calls).toHaveLength(1);
expect(calls[0]?.origin).toBe(origin); expect(calls[0]?.origin).toBe(origin);
expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "Web console" }); expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "Web console" });
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces")); await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
// `code` and `auto` are consumed, not kept in the URL.
expect(router.state.location.searchStr).toBe("");
expect(await screen.findByText("Workspaces destination")).toBeInTheDocument(); expect(await screen.findByText("Workspaces destination")).toBeInTheDocument();
}); });
@@ -278,14 +290,13 @@ describe("ConnectPage", () => {
const { router } = await renderPage(routes(), "/connect?next=%2Fchat%2F01a15368%3Fworkspace%3Dws-1", { const { router } = await renderPage(routes(), "/connect?next=%2Fchat%2F01a15368%3Fworkspace%3Dws-1", {
paired: false, paired: false,
}); });
expandManual();
fillManualForm({ host: "192.168.2.10", port: "4321", code: "ABCD1234", device: "My browser" }); fillManualForm({ host: "192.168.2.10", port: "4321", code: "ABCD1234", device: "My browser" });
fireEvent.click(screen.getByTestId("connect-submit")); fireEvent.click(screen.getByTestId("connect-submit"));
await waitFor(() => expect(router.state.location.pathname).toBe("/chat/01a15368")); await waitFor(() => expect(router.state.location.pathname).toBe("/chat/01a15368"));
expect(router.state.location.search).toMatchObject({ workspace: "ws-1" }); expect(router.state.location.search).toMatchObject({ workspace: "ws-1" });
expect(pairCalls(fetchMock)).toHaveLength(1); expect(redeemCalls(fetchMock)).toHaveLength(1);
}); });
it("shows a localized inline error for a wrong or expired code and stays unpaired", async () => { it("shows a localized inline error for a wrong or expired code and stays unpaired", async () => {
@@ -296,7 +307,6 @@ describe("ConnectPage", () => {
}), }),
]); ]);
const { router } = await renderPage(routes(), "/connect", { paired: false }); const { router } = await renderPage(routes(), "/connect", { paired: false });
expandManual();
fillManualForm({ host: "192.168.2.10", port: "4321", code: "ZZZZ9999", device: "My browser" }); fillManualForm({ host: "192.168.2.10", port: "4321", code: "ZZZZ9999", device: "My browser" });
fireEvent.click(screen.getByTestId("connect-submit")); fireEvent.click(screen.getByTestId("connect-submit"));
@@ -310,53 +320,13 @@ describe("ConnectPage", () => {
expect(screen.getByTestId("connect-submit")).toBeEnabled(); expect(screen.getByTestId("connect-submit")).toBeEnabled();
}); });
it("warns then pairs from a pasted pi2 pair link through the confirmation dialog", async () => { it("shows the connected summary with server identity and one primary", async () => {
const fetchMock = mockApi([pairRoute()]);
const { router } = await renderPage(routes(), "/connect", { paired: false });
fireEvent.click(screen.getByTestId("connect-scan"));
const link = await screen.findByLabelText("Pairing link");
fireEvent.change(link, {
target: { value: "pi2://pair?host=192.168.2.10&port=4321&code=ABCD1234" },
});
fireEvent.click(screen.getByRole("button", { name: "Identify" }));
// Confirmation dialog: host:port + masked code, and its buttons must be clickable.
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText("192.168.2.10:4321")).toBeInTheDocument();
expect(within(dialog).getByText("…234")).toBeInTheDocument();
fireEvent.click(screen.getByTestId("connect-confirm-connect"));
await waitFor(() => expect(localStorage.getItem("pi2-connection")).toBe("paired"));
expect(pairCalls(fetchMock)[0]?.body).toMatchObject({ code: "ABCD1234" });
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
});
it("cancel on the confirmation dialog leaves the connection untouched", async () => {
const fetchMock = mockApi([pairRoute()]);
const { router } = await renderPage(routes(), "/connect", { paired: false });
fireEvent.click(screen.getByTestId("connect-scan"));
const link = await screen.findByLabelText("Pairing link");
fireEvent.change(link, { target: { value: "pi2://pair?host=192.168.2.10&code=ABCD1234" } });
fireEvent.click(screen.getByRole("button", { name: "Identify" }));
await screen.findByRole("dialog");
fireEvent.click(screen.getByTestId("connect-confirm-cancel"));
await waitFor(() => expect(screen.queryByTestId("connect-confirm-cancel")).not.toBeInTheDocument());
expect(pairCalls(fetchMock)).toHaveLength(0);
expect(localStorage.getItem("pi2-connection")).toBeNull();
expect(router.state.location.pathname).toBe("/connect");
});
it("shows the connected summary with server identity, device scopes and one primary", async () => {
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]); mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
await renderPage(routes(), "/connect", { await renderPage(routes(), "/connect", {
paired: true, paired: true,
storage: { storage: {
"pi2-device": "Test browser", "pi2-device": "Test browser",
"pi2-endpoint": "http://192.168.2.10:4321", "pi2-endpoint": "http://192.168.2.10:4321",
"pi2-device-scopes": JSON.stringify(["read", "steer"]),
}, },
}); });
@@ -366,9 +336,9 @@ describe("ConnectPage", () => {
expect(screen.getByText("http://192.168.2.10:4321")).toBeInTheDocument(); expect(screen.getByText("http://192.168.2.10:4321")).toBeInTheDocument();
expect(screen.getByText("0.4.2")).toBeInTheDocument(); expect(screen.getByText("0.4.2")).toBeInTheDocument();
expect(screen.getByText("Test browser")).toBeInTheDocument(); expect(screen.getByText("Test browser")).toBeInTheDocument();
expect(screen.getByText("Read")).toBeInTheDocument(); // Scopes are gone from the console entirely.
expect(screen.getByText("Steer")).toBeInTheDocument(); expect(screen.queryByText("Scopes")).not.toBeInTheDocument();
expect(screen.queryByText("Apply")).not.toBeInTheDocument(); expect(screen.queryByText("Read")).not.toBeInTheDocument();
// Back to workspaces is the single primary while the re-pair panel is closed. // Back to workspaces is the single primary while the re-pair panel is closed.
expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary"); expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary");
@@ -378,7 +348,7 @@ describe("ConnectPage", () => {
expect(document.querySelector(".cn-details__body")?.textContent).toContain("…"); expect(document.querySelector(".cn-details__body")?.textContent).toContain("…");
}); });
it("re-pairs in place and hands the single primary to the scan button, then to the form", async () => { it("re-pairs in place and hands the single primary to the form, then back", async () => {
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]); mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
await renderPage(routes(), "/connect", { await renderPage(routes(), "/connect", {
paired: true, paired: true,
@@ -389,19 +359,13 @@ describe("ConnectPage", () => {
fireEvent.click(repair); fireEvent.click(repair);
const panel = screen.getByTestId("connect-repair-panel"); const panel = screen.getByTestId("connect-repair-panel");
expect(panel).not.toHaveAttribute("hidden"); expect(panel).not.toHaveAttribute("hidden");
expect(screen.getByTestId("connect-repair-scan")).toHaveClass("btn--primary"); expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
expect(screen.getByTestId("connect-back")).not.toHaveClass("btn--primary"); expect(screen.getByTestId("connect-back")).not.toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1); expect(primaries()).toHaveLength(1);
expandManual(); // Collapsing the panel returns the primary to "back to workspaces".
expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
expect(screen.getByTestId("connect-repair-scan")).not.toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1);
// Collapsing the panel also collapses the form and returns to one primary.
fireEvent.click(repair); fireEvent.click(repair);
expect(panel).toHaveAttribute("hidden"); expect(panel).toHaveAttribute("hidden");
expect(screen.getByTestId("connect-manual-panel")).toHaveAttribute("hidden");
expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary"); expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1); expect(primaries()).toHaveLength(1);
}); });
@@ -421,9 +385,9 @@ describe("ConnectPage", () => {
await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBeNull()); await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBeNull());
expect(localStorage.getItem("pi2-connection")).toBe("unpaired"); expect(localStorage.getItem("pi2-connection")).toBe("unpaired");
expect(await screen.findByRole("button", { name: "Scan to pair" })).toBeInTheDocument(); expect(await screen.findByRole("heading", { name: "Connect your pi2 server" })).toBeInTheDocument();
expect(screen.queryByText("Current connection")).not.toBeInTheDocument(); expect(screen.queryByText("Current connection")).not.toBeInTheDocument();
expect(screen.getByTestId("connect-scan")).toHaveClass("btn--primary"); expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
expect(primaries()).toHaveLength(1); expect(primaries()).toHaveLength(1);
}); });
}); });
@@ -447,6 +411,16 @@ describe("parsePairLink", () => {
}); });
}); });
it("falls back to the served port (never a literal) when a link omits one", () => {
const servedPort = window.location.port || (window.location.protocol === "https:" ? "443" : "80");
expect(parsePairLink("pi2://pair?host=pi2.local&code=ABCD1234")).toMatchObject({
endpoint: `http://pi2.local:${servedPort}`,
});
expect(parsePairLink("pi2://pair?host=pi2.local&proto=https&code=ABCD1234")).toMatchObject({
endpoint: `https://pi2.local:${servedPort}`,
});
});
it("parses http(s) /pair/<CODE> links", () => { it("parses http(s) /pair/<CODE> links", () => {
expect(parsePairLink("https://192.168.2.10:4321/pair/ABCD1234")).toMatchObject({ expect(parsePairLink("https://192.168.2.10:4321/pair/ABCD1234")).toMatchObject({
endpoint: "https://192.168.2.10:4321", endpoint: "https://192.168.2.10:4321",
+75 -3
View File
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commandCalls, mockApi, type MockRoute } from "./helpers/api-mock"; import { commandCalls, mockApi, type MockRoute } from "./helpers/api-mock";
import { renderPage } from "./helpers/render-page"; import { renderPage } from "./helpers/render-page";
import { drawQr } from "@/features/status/qr";
import { setLanguage } from "@/lib/i18n"; import { setLanguage } from "@/lib/i18n";
import { StatusPage } from "@/pages/status"; import { StatusPage } from "@/pages/status";
import { useConnectionStore } from "@/stores/connection"; import { useConnectionStore } from "@/stores/connection";
@@ -74,12 +75,19 @@ const modelsBody = {
], ],
}; };
/** A 21×21 byte-mode matrix (`rows` are `"0"`/`"1"`, no quiet zone). */
const qrRows = Array.from({ length: 21 }, (_, y) =>
Array.from({ length: 21 }, (_, x) => ((x * 7 + y * 3 + (x ^ y)) % 5 < 2 ? "1" : "0")).join(""),
);
const pairBody = { const pairBody = {
accepted: true, accepted: true,
code: "ABCD1234", code: "ABCD1234",
url: "http://127.0.0.1:4321/pair/ABCD1234", url: "http://127.0.0.1:4321/pair/ABCD1234",
expiresAt: Date.now() + 9 * 60_000, expiresAt: Date.now() + 9 * 60_000,
nonce: "nonce-1", nonce: "nonce-1",
qr: { version: 1, ecc: "M", mask: 3, size: 21, rows: qrRows },
bases: [{ kind: "lan", name: "eth0", address: "192.168.2.10:4321", url: "http://192.168.2.10:4321" }],
}; };
const tasksBody = { const tasksBody = {
@@ -107,7 +115,6 @@ const devicesBody = [
id: "dev-1", id: "dev-1",
name: "Pixel", name: "Pixel",
kind: "phone", kind: "phone",
scopes: ["read", "steer"],
createdAt: Date.now() - 90_000, createdAt: Date.now() - 90_000,
lastSeenAt: Date.now() - 60_000, lastSeenAt: Date.now() - 60_000,
revokedAt: null, revokedAt: null,
@@ -177,6 +184,48 @@ afterEach(() => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
describe("drawQr", () => {
function fakeCanvas(width: number) {
const fills: number[][] = [];
const context = {
fillStyle: "",
fillRect: (...args: number[]) => fills.push(args),
clearRect: () => undefined,
};
const canvas = {
width: 0,
height: 0,
clientWidth: width,
parentElement: null,
getContext: () => context,
};
return { canvas, fills };
}
it("paints one square per dark module, capped at 200px and scaled by dpr", () => {
const { canvas, fills } = fakeCanvas(480);
drawQr(canvas as unknown as HTMLCanvasElement, qrRows);
const dpr = window.devicePixelRatio || 1;
expect(canvas.width).toBe(200 * dpr);
expect(canvas.height).toBe(200 * dpr);
// background + one fillRect per `1` module (no fake pattern).
const dark = qrRows.reduce((total, row) => total + [...row].filter((cell) => cell === "1").length, 0);
expect(fills).toHaveLength(dark + 1);
});
it("clears the canvas for an empty or ragged matrix", () => {
const { canvas, fills } = fakeCanvas(200);
drawQr(canvas as unknown as HTMLCanvasElement, []);
expect(fills).toHaveLength(0);
expect(canvas.width).toBe(0);
drawQr(canvas as unknown as HTMLCanvasElement, ["101", "10"]);
expect(fills).toHaveLength(0);
expect(canvas.width).toBe(0);
});
});
describe("StatusPage", () => { describe("StatusPage", () => {
it("renders the four metric tiles, one count line and no primary button", async () => { it("renders the four metric tiles, one count line and no primary button", async () => {
mockApi(apiRoutes()); mockApi(apiRoutes());
@@ -275,12 +324,15 @@ describe("StatusPage", () => {
await waitFor(() => expect(screen.getByTestId("ws-status")).toHaveTextContent("Connected")); await waitFor(() => expect(screen.getByTestId("ws-status")).toHaveTextContent("Connected"));
}); });
it("mints a pairing code and shows it with a square QR and the expiry hint", async () => { it("mints a pairing code and renders the daemon's QR matrix with the expiry hint", async () => {
const fetchMock = mockApi(apiRoutes()); const fetchMock = mockApi(apiRoutes());
await renderPage(routes(), "/status", { paired: true }); await renderPage(routes(), "/status", { paired: true });
expect(await screen.findByTestId("pairing-code")).toHaveTextContent("ABCD1234"); expect(await screen.findByTestId("pairing-code")).toHaveTextContent("ABCD1234");
expect(screen.getByRole("img", { name: "Pairing QR code" })).toHaveClass("qr-canvas"); const canvas = screen.getByRole("img", { name: "Pairing QR code" });
expect(canvas).toHaveClass("qr-canvas");
// 真矩阵:模块数就是 daemon 下发的 `qr.size` / `rows.length`,不是种子图案。
expect(canvas).toHaveAttribute("data-qr-size", String(qrRows.length));
expect(screen.getByText("Expires in 9 min")).toBeInTheDocument(); expect(screen.getByText("Expires in 9 min")).toBeInTheDocument();
expect(screen.getByText(/Pairing code expires in \d+ minutes/)).toBeInTheDocument(); expect(screen.getByText(/Pairing code expires in \d+ minutes/)).toBeInTheDocument();
@@ -293,6 +345,26 @@ describe("StatusPage", () => {
expect(calls[0]?.body).toEqual({ ttlSec: 600 }); expect(calls[0]?.body).toEqual({ ttlSec: 600 });
}); });
it("shows the pairing URL instead of a QR when the daemon omits the matrix", async () => {
mockApi(
apiRoutes([
{
method: "POST",
path: "/api/v1/pair",
handler: () => {
const { qr: _qr, ...withoutQr } = pairBody;
return { body: withoutQr };
},
},
]),
);
await renderPage(routes(), "/status", { paired: true });
expect(await screen.findByTestId("pairing-code")).toHaveTextContent("ABCD1234");
expect(screen.queryByRole("img", { name: "Pairing QR code" })).toBeNull();
expect(screen.getByTestId("pair-url")).toHaveTextContent("http://127.0.0.1:4321/pair/ABCD1234");
});
it("offers a retry when minting a pairing code fails", async () => { it("offers a retry when minting a pairing code fails", async () => {
let attempts = 0; let attempts = 0;
mockApi( mockApi(