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:
1 parent
a57c874095
commit
3e35fb7ef3
20 files changed
+417
-944
No files matched your search
+51
-11
@@ -26,6 +26,40 @@ export const MOCK_DAEMON_ID = "d-mock-0f3a9c";
|
||||
|
||||
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. */
|
||||
export function buildFixtures(now = Date.now()) {
|
||||
const iso = (ts) => new Date(ts).toISOString();
|
||||
@@ -785,7 +819,6 @@ export function buildFixtures(now = Date.now()) {
|
||||
deviceId: "dev-local",
|
||||
name: "local browser",
|
||||
kind: "laptop",
|
||||
scopes: ["read", "steer", "apply"],
|
||||
lastSeenAt: now - 15_000,
|
||||
lastActiveAt: now - 15_000,
|
||||
createdAt: now - 26 * 3_600_000,
|
||||
@@ -796,7 +829,6 @@ export function buildFixtures(now = Date.now()) {
|
||||
deviceId: "dev-phone",
|
||||
name: "Pixel 8 · pi2",
|
||||
kind: "phone",
|
||||
scopes: ["read", "steer"],
|
||||
lastSeenAt: now - 47 * MINUTE,
|
||||
lastActiveAt: now - 47 * MINUTE,
|
||||
createdAt: now - 9 * 86_400_000,
|
||||
@@ -807,7 +839,6 @@ export function buildFixtures(now = Date.now()) {
|
||||
deviceId: "dev-tablet",
|
||||
name: "iPad Air",
|
||||
kind: "tablet",
|
||||
scopes: ["read"],
|
||||
lastSeenAt: now - 6 * 86_400_000,
|
||||
lastActiveAt: now - 6 * 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]));
|
||||
|
||||
// `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 {
|
||||
info: { ...info, port: undefined },
|
||||
health,
|
||||
@@ -896,14 +942,8 @@ export function buildFixtures(now = Date.now()) {
|
||||
modelProviders,
|
||||
resources,
|
||||
diagnostics,
|
||||
/** `GET /api/v1/pair` mint response (no code in the body). */
|
||||
pairCode: {
|
||||
accepted: true,
|
||||
code: "QK7M-2XPD",
|
||||
url: "http://127.0.0.1:4321/pair/QK7M-2XPD",
|
||||
expiresAt: now + 10 * MINUTE,
|
||||
nonce: "n-9f2c1a",
|
||||
},
|
||||
/** `POST /api/v1/pair` mint response (code + QR matrix + reachable bases). */
|
||||
pairCode,
|
||||
/** `attention` flattened per workspace for `GET /api/v1/attention`. */
|
||||
attentionByWorkspace: (workspaceId) =>
|
||||
sessions
|
||||
|
||||
@@ -196,7 +196,6 @@ const DEVICE_PUBLIC = {
|
||||
id: "dev-local",
|
||||
name: "local browser",
|
||||
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)}`,
|
||||
});
|
||||
}
|
||||
// Mint: authenticated, returns the code + QR matrix + reachable bases.
|
||||
if (pathname === "/api/v1/pair" && method === "POST") {
|
||||
await readBody(req).catch(() => ({}));
|
||||
if (OPTIONS.pairOnly) return unauthorized(res);
|
||||
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 (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, "")) {
|
||||
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 });
|
||||
}
|
||||
if (OPTIONS.pairOnly) return unauthorized(res);
|
||||
return sendJson(res, 200, { accepted: true, ...FIXTURES.pairCode });
|
||||
}
|
||||
|
||||
/* Everything below needs a device token (and is refused in --pair-only). */
|
||||
if (OPTIONS.pairOnly) return unauthorized(res);
|
||||
|
||||
@@ -274,7 +274,6 @@ function storageState(origin, { paired, theme }) {
|
||||
{ name: "pi2-connection", value: "paired" },
|
||||
{ name: "pi2-endpoint", value: origin },
|
||||
{ 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-connected-at", value: String(Date.now()) },
|
||||
{ name: "pi2-theme", value: theme },
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Field, Input } from "@/components/ui/input";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
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 {
|
||||
endpoint: string;
|
||||
@@ -61,6 +61,8 @@ export function ManualConnectForm({
|
||||
}: ManualConnectFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [link, setLink] = useState("");
|
||||
const [linkError, setLinkError] = useState<string | null>(null);
|
||||
const [host, setHost] = useState(() => initialHost ?? "");
|
||||
const [port, setPort] = useState(() => initialPort ?? defaultPort);
|
||||
const [code, setCode] = useState(() => normalizePairCode(initialCode ?? ""));
|
||||
@@ -93,7 +95,24 @@ export function ManualConnectForm({
|
||||
setCodeError(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 (parsed.error === "host") {
|
||||
setHostError(t("connect.hostRequired"));
|
||||
@@ -110,7 +129,7 @@ export function ManualConnectForm({
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = normalizePairCode(code);
|
||||
const normalized = normalizePairCode(codeValue);
|
||||
if (!normalized) {
|
||||
setCodeError(t("connect.pairCodeRequired"));
|
||||
return;
|
||||
@@ -141,6 +160,40 @@ export function ManualConnectForm({
|
||||
return (
|
||||
<div className="cn-manual" id={formId} hidden={!expanded} data-testid="connect-manual-panel">
|
||||
<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">
|
||||
<Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}>
|
||||
<Input
|
||||
|
||||
@@ -2,21 +2,16 @@ import { ApiError, apiRequest, type InfoResponse } from "@/lib/api";
|
||||
import { NEXT_FALLBACK, safeNext } from "@/lib/routing";
|
||||
|
||||
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). */
|
||||
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. */
|
||||
export const PAIR_CODE_LENGTH = 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 interface PairMeta {
|
||||
scopes: string[];
|
||||
deviceName?: string;
|
||||
kind?: DeviceKind;
|
||||
server?: Partial<InfoResponse> & { name?: string; hostname?: string; version?: string; pluginVersion?: string };
|
||||
@@ -33,12 +28,9 @@ export interface PairTarget {
|
||||
|
||||
export interface RedeemResult {
|
||||
token: string;
|
||||
scopes: string[];
|
||||
deviceId?: string;
|
||||
deviceName?: string;
|
||||
kind?: DeviceKind;
|
||||
server?: PairMeta["server"];
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export interface ParsedEndpoint {
|
||||
@@ -59,9 +51,6 @@ function firstString(...values: unknown[]): string | 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
|
||||
@@ -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 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;
|
||||
if (hostParam) {
|
||||
@@ -190,7 +181,7 @@ function parsePi2PairLink(text: string, fallbackEndpoint?: string | null): PairT
|
||||
target = "error" in parsed ? null : parsed;
|
||||
}
|
||||
// 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);
|
||||
if (!target) return null;
|
||||
|
||||
@@ -257,13 +248,14 @@ export function pairingOrigin(endpoint: string): string {
|
||||
.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function normalizeScopes(values: string[]): string[] {
|
||||
const unique = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
|
||||
return unique.length ? unique : [...DEFAULT_DEVICE_SCOPES];
|
||||
/** Port this console was served from, else the scheme default (`443`/`80`). */
|
||||
function defaultPairPort(protocol: "http" | "https"): string {
|
||||
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}`.
|
||||
*/
|
||||
export async function redeemPairing(input: {
|
||||
@@ -286,13 +278,10 @@ export async function redeemPairing(input: {
|
||||
signal: input.signal,
|
||||
});
|
||||
|
||||
const payload = asRecord(response.payload);
|
||||
const result = asRecord(response.result);
|
||||
// 文档契约只有 `{token,device:{id,name,kind}}`,不再兜底历史别名。
|
||||
const body = asRecord(response) ?? {};
|
||||
const device =
|
||||
asRecord(body.device) ?? asRecord(result?.device) ?? asRecord(payload?.device) ?? asRecord(payload);
|
||||
// `{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);
|
||||
const device = asRecord(body.device);
|
||||
const token = firstString(body.token);
|
||||
if (!token) {
|
||||
throw new ApiError({
|
||||
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 {
|
||||
token,
|
||||
scopes,
|
||||
deviceId: firstString(device?.id, body.deviceId, device?.deviceId, result?.deviceId),
|
||||
deviceName: firstString(device?.name, deviceName),
|
||||
deviceId: firstString(device?.id),
|
||||
deviceName: firstString(device?.name) ?? deviceName,
|
||||
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);
|
||||
if (!record) return null;
|
||||
return {
|
||||
scopes: stringList(record.scopes),
|
||||
deviceName: typeof record.deviceName === "string" ? record.deviceName : undefined,
|
||||
kind: record.kind === "phone" || record.kind === "laptop" || record.kind === "tablet" ? record.kind : 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 {
|
||||
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];
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
|
||||
import { Icon } from "@/components/icons";
|
||||
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { KV } from "@/components/ui/kv";
|
||||
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);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
const draw = () => drawQr(canvas, seed);
|
||||
const draw = () => drawQr(canvas, rows);
|
||||
draw();
|
||||
|
||||
if (typeof MutationObserver === "undefined") return;
|
||||
const observer = new MutationObserver(draw);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
|
||||
return () => observer.disconnect();
|
||||
}, [seed]);
|
||||
window.addEventListener("resize", draw);
|
||||
const observer =
|
||||
typeof MutationObserver === "undefined" ? null : new MutationObserver(draw);
|
||||
observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
|
||||
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 {
|
||||
server: ServerIdentity;
|
||||
deviceName: string;
|
||||
scopes: string[];
|
||||
connectedAt: number | null;
|
||||
loading: boolean;
|
||||
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
|
||||
* / pairing code / security notes on the left, the square QR with the pairing
|
||||
* hint and the expiry on the right. Both actions are non-primary (the status
|
||||
* page carries 0 primary buttons).
|
||||
* Card 7 — two internal columns: addresses / mDNS / endpoint / device / pairing
|
||||
* code / security notes on the left, the QR with the pairing hint and the expiry
|
||||
* on the right. Both actions are non-primary (the status page carries 0 primary
|
||||
* buttons).
|
||||
*/
|
||||
export function ConnectionCard({
|
||||
server,
|
||||
deviceName,
|
||||
scopes,
|
||||
connectedAt,
|
||||
loading,
|
||||
error,
|
||||
@@ -117,7 +129,10 @@ export function ConnectionCard({
|
||||
const { t } = useTranslation();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
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);
|
||||
|
||||
return (
|
||||
@@ -146,19 +161,6 @@ export function ConnectionCard({
|
||||
<CopyButton value={server.endpoint} label={t("connect.endpoint")} />
|
||||
</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")}>
|
||||
<RelativeTime ts={connectedAt} />
|
||||
</KV>
|
||||
@@ -192,7 +194,13 @@ export function ConnectionCard({
|
||||
|
||||
<div className="conn-right">
|
||||
<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">
|
||||
<Icon name="phone" />
|
||||
<span>{t("status.pairHint")}</span>
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { DeviceEntry } from "@/features/status/queries";
|
||||
|
||||
@@ -34,7 +33,7 @@ export interface DevicesCardProps {
|
||||
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) {
|
||||
const { t } = useTranslation();
|
||||
const [target, setTarget] = useState<DeviceEntry | null>(null);
|
||||
@@ -61,7 +60,6 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
|
||||
) : (
|
||||
<div className="device-list">
|
||||
{visible.map((device) => {
|
||||
const scopes = Array.isArray(device.scopes) ? device.scopes : [];
|
||||
return (
|
||||
<div className="device-row" key={deviceKey(device)} data-device-id={deviceKey(device)}>
|
||||
<span className="device-icon">
|
||||
@@ -69,15 +67,7 @@ export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: Devi
|
||||
</span>
|
||||
<div className="grow device-main">
|
||||
<div className="device-name truncate">{device.name}</div>
|
||||
<div className="device-meta">
|
||||
<span className="status-scopes">
|
||||
{scopes.map((scope) => (
|
||||
<Badge key={scope} className="badge--outline">
|
||||
{scope}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="device-meta faint">{device.kind}</div>
|
||||
</div>
|
||||
<span className="device-time faint">
|
||||
<RelativeTime ts={deviceLastActive(device)} />
|
||||
|
||||
@@ -1,9 +1,32 @@
|
||||
/**
|
||||
* Port of the prototype's `App.drawQR`: a deterministic fake QR derived from a
|
||||
* seed string. Colors come from the design tokens only, so a theme switch
|
||||
* redraws the same pattern with the dark surfaces.
|
||||
* Renders the daemon's real QR matrix (`pairCode.qr.rows`, one `"0"`/`"1"`
|
||||
* string per row) into a square canvas.
|
||||
*
|
||||
* 渲染要点:
|
||||
* - `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;
|
||||
try {
|
||||
context = canvas.getContext("2d");
|
||||
@@ -12,41 +35,42 @@ export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
|
||||
}
|
||||
if (!context) return;
|
||||
|
||||
const n = 25;
|
||||
const cell = 8;
|
||||
canvas.width = n * cell;
|
||||
canvas.height = n * cell;
|
||||
// 空矩阵:清掉上一张码,不留伪图案。
|
||||
if (!isMatrix(rows)) {
|
||||
canvas.width = 0;
|
||||
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 cardColor = styles.getPropertyValue("--card").trim() || "transparent";
|
||||
const foregroundColor = styles.getPropertyValue("--foreground").trim() || "currentColor";
|
||||
|
||||
// 静区 + 模块网格都按 devicePixelRatio 缩放,保持正方形。
|
||||
const total = size + QUIET_MODULES * 2;
|
||||
const module = canvas.width / total;
|
||||
|
||||
context.fillStyle = cardColor;
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.fillStyle = foregroundColor;
|
||||
|
||||
let state = 0;
|
||||
for (const char of seed) state = (state * 31 + char.charCodeAt(0)) >>> 0;
|
||||
const random = () => {
|
||||
state = (state * 1103515245 + 12345) >>> 0;
|
||||
return state / 4294967296;
|
||||
};
|
||||
|
||||
const finder = (x: number, y: number) => {
|
||||
context?.fillRect(x * cell, y * cell, 7 * cell, 7 * cell);
|
||||
context?.clearRect((x + 1) * cell, (y + 1) * cell, 5 * cell, 5 * cell);
|
||||
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);
|
||||
for (let y = 0; y < size; y += 1) {
|
||||
const row = rows[y] ?? "";
|
||||
for (let x = 0; x < size; x += 1) {
|
||||
if (row[x] !== "1") continue;
|
||||
// 取整像素边界,避免相邻模块间的缝。
|
||||
const left = Math.round((x + QUIET_MODULES) * module);
|
||||
const top = Math.round((y + QUIET_MODULES) * module);
|
||||
const right = Math.round((x + QUIET_MODULES + 1) * module);
|
||||
const bottom = Math.round((y + QUIET_MODULES + 1) * module);
|
||||
context.fillRect(left, top, right - left, bottom - top);
|
||||
}
|
||||
}
|
||||
|
||||
finder(0, 0);
|
||||
finder(n - 7, 0);
|
||||
finder(0, n - 7);
|
||||
}
|
||||
@@ -20,7 +20,6 @@ export interface DeviceEntry {
|
||||
deviceId?: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
scopes: string[];
|
||||
/** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */
|
||||
lastActiveAt?: 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
|
||||
* minting: an authenticated `POST` with no `code` returns
|
||||
* `{accepted,code,url,expiresAt,nonce}` (docs/protocol.md §3.2).
|
||||
* `POST /api/v1/pair` is authenticated and mints a code:
|
||||
* `{accepted,code,url,expiresAt,nonce,qr,bases}`, where `qr` carries the opaque
|
||||
* 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 {
|
||||
accepted?: boolean;
|
||||
@@ -62,6 +62,8 @@ export interface PairCodeResponse {
|
||||
url?: string;
|
||||
expiresAt?: number;
|
||||
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. */
|
||||
|
||||
+1
-3
@@ -280,7 +280,6 @@ export interface DeviceInfo {
|
||||
deviceId: string;
|
||||
name: string;
|
||||
kind: "phone" | "laptop" | "tablet";
|
||||
scopes: string[];
|
||||
lastActiveAt: number | null;
|
||||
}
|
||||
|
||||
@@ -312,7 +311,6 @@ export interface PairRequest {
|
||||
export interface PairResponse {
|
||||
token?: string;
|
||||
deviceId?: string;
|
||||
scopes?: string[];
|
||||
server?: Partial<InfoResponse>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -351,7 +349,7 @@ export const api = {
|
||||
request<PairResponse>("/api/v1/pair", { method: "POST", body: {}, baseUrl, signal }),
|
||||
/** Public redeem endpoint (no bearer required): `{code,kind,deviceName}` → `{token,device}`. */
|
||||
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 };
|
||||
+4
-30
@@ -413,19 +413,12 @@
|
||||
"common.stop": "Stop",
|
||||
"connect.addTitle": "Connection settings",
|
||||
"connect.address": "Address",
|
||||
"connect.aim": "Point the back camera at the QR code on the pi2 server",
|
||||
"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.confirmTitle": "Confirm connection",
|
||||
"connect.connect": "Connect",
|
||||
"connect.connected": "Connected: {name}",
|
||||
"connect.connecting": "Connecting…",
|
||||
"connect.defaultDeviceName": "Web console",
|
||||
"connect.demoScan": "Demo: simulate scan",
|
||||
"connect.details": "Connection details",
|
||||
"connect.device": "Device",
|
||||
"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.disconnectTitle": "Disconnect",
|
||||
"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.endpoint": "Endpoint",
|
||||
"connect.expandManual": "Show manual connection",
|
||||
"connect.failed": "Connection failed. Check the address and pairing code.",
|
||||
"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.heroText": "One browser, one pi2 instance — continue your Neovim sessions from any device.",
|
||||
"connect.heroTitle": "Connect your pi2",
|
||||
@@ -448,14 +441,10 @@
|
||||
"connect.hostPlaceholder": "192.168.2.10 or http://…:4321",
|
||||
"connect.hostRequired": "Enter the server address",
|
||||
"connect.hostname": "Hostname",
|
||||
"connect.identify": "Identify",
|
||||
"connect.invalidLink": "Could not parse it. Paste the full pi2://pair link.",
|
||||
"connect.lastConnected": "Last connected",
|
||||
"connect.manual": "Connect manually",
|
||||
"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.pairCode": "Pairing code",
|
||||
"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.pairingAuto": "Pairing this device…",
|
||||
"connect.pairingLink": "Pairing link",
|
||||
"connect.pastePlaceholder": "Paste a pi2://pair?… pairing link",
|
||||
"connect.permissionDenied": "Camera permission was denied. Allow access in browser settings and try again.",
|
||||
"connect.pasteHint": "Paste the pairing link instead of typing host and code",
|
||||
"connect.pastePlaceholder": "Paste a pi2://pair?… or /pair/CODE link",
|
||||
"connect.piVersion": "pi version",
|
||||
"connect.pluginVersion": "Plugin version",
|
||||
"connect.port": "Port",
|
||||
"connect.portInvalid": "Port must be 1–65535",
|
||||
"connect.recognized": "QR code recognized",
|
||||
"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.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.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.startingCamera": "Starting camera…",
|
||||
"connect.statePaired": "Connected",
|
||||
"connect.stateUnpaired": "Not connected",
|
||||
"connect.subtitle": "Connect this browser to your pi2 instance and review pairing details.",
|
||||
@@ -658,7 +633,6 @@
|
||||
"status.tasks": "Background tasks",
|
||||
"status.tasksError": "Failed to load background tasks",
|
||||
"status.title": "Server status",
|
||||
"status.tokenScopes": "Token scopes",
|
||||
"status.updated": "updated {time}",
|
||||
"status.uptime": "Uptime",
|
||||
"status.workspaces": "Workspaces",
|
||||
|
||||
+4
-30
@@ -413,19 +413,12 @@
|
||||
"common.stop": "停止",
|
||||
"connect.addTitle": "连接设置",
|
||||
"connect.address": "地址",
|
||||
"connect.aim": "将设备背面对准 pi2 服务器上的二维码",
|
||||
"connect.backToWorkspaces": "返回工作空间",
|
||||
"connect.cameraFailed": "无法打开摄像头(可能没有可用设备)。请改用配对链接。",
|
||||
"connect.cameraPreview": "摄像头预览",
|
||||
"connect.cameraUnsupported": "当前浏览器不支持摄像头,请改用下方配对链接。",
|
||||
"connect.cantScan": "无法扫码?粘贴配对链接",
|
||||
"connect.collapseManual": "收起手动连接",
|
||||
"connect.confirmTitle": "确认连接",
|
||||
"connect.connect": "连接",
|
||||
"connect.connected": "已连接:{name}",
|
||||
"connect.connecting": "正在连接…",
|
||||
"connect.defaultDeviceName": "Web 控制台",
|
||||
"connect.demoScan": "演示:模拟扫码",
|
||||
"connect.details": "连接详情",
|
||||
"connect.device": "设备",
|
||||
"connect.deviceName": "设备名",
|
||||
@@ -434,13 +427,13 @@
|
||||
"connect.disconnectText": "将清除此浏览器保存的连接与 Token,需要重新配对才能继续。",
|
||||
"connect.disconnectTitle": "断开连接",
|
||||
"connect.disconnected": "已断开连接",
|
||||
"connect.emptyText": "填写地址,或扫码配对 pi2 服务器后即可开始。",
|
||||
"connect.emptyText": "填写地址,以及 pi2 服务器上显示的 8 位配对码即可开始。",
|
||||
"connect.emptyTitle": "连接 pi2 服务器",
|
||||
"connect.endpoint": "地址",
|
||||
"connect.expandManual": "展开手动连接",
|
||||
"connect.failed": "连接失败,请检查地址与配对码",
|
||||
"connect.featureOne": "工作空间与会话实时同步",
|
||||
"connect.featureThree": "只读 / 操控 / 应用 分级授权",
|
||||
"connect.featureThree": "手机扫码即配对,无需配置、无需切换模式",
|
||||
"connect.featureTwo": "子代理与后台任务一处掌控",
|
||||
"connect.heroText": "一个浏览器连接一个 pi2 实例,在任意设备上继续你的 Neovim 会话。",
|
||||
"connect.heroTitle": "连接你的 pi2",
|
||||
@@ -448,14 +441,10 @@
|
||||
"connect.hostPlaceholder": "192.168.2.10 或 http://…:4321",
|
||||
"connect.hostRequired": "请输入服务器地址",
|
||||
"connect.hostname": "Hostname",
|
||||
"connect.identify": "识别",
|
||||
"connect.invalidLink": "无法识别,请粘贴完整的 pi2://pair 链接",
|
||||
"connect.lastConnected": "最后连接",
|
||||
"connect.manual": "手动连接",
|
||||
"connect.name": "名称",
|
||||
"connect.noAutoDetect": "摄像头已开启。当前浏览器不支持自动识别,请粘贴配对链接。",
|
||||
"connect.notPairQr": "这不是 pi2 配对二维码,请换一个",
|
||||
"connect.or": "或",
|
||||
"connect.os": "系统",
|
||||
"connect.pairCode": "配对码",
|
||||
"connect.pairCodeHint": "pi2 服务器上显示的 8 位配对码。",
|
||||
@@ -467,31 +456,17 @@
|
||||
"connect.pairHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
|
||||
"connect.pairingAuto": "正在配对这台设备…",
|
||||
"connect.pairingLink": "配对链接",
|
||||
"connect.pastePlaceholder": "粘贴 pi2://pair?… 配对链接",
|
||||
"connect.permissionDenied": "摄像头权限被拒绝。请在浏览器设置中允许访问后重试。",
|
||||
"connect.pasteHint": "也可以直接粘贴配对链接,省去填写地址与配对码",
|
||||
"connect.pastePlaceholder": "粘贴 pi2://pair?… 或 /pair/CODE 链接",
|
||||
"connect.piVersion": "pi 版本",
|
||||
"connect.pluginVersion": "插件版本",
|
||||
"connect.port": "端口",
|
||||
"connect.portInvalid": "端口必须是 1–65535",
|
||||
"connect.recognized": "已识别二维码",
|
||||
"connect.reconnect": "重新配对",
|
||||
"connect.retryCamera": "重试摄像头",
|
||||
"connect.scan": "扫码配对",
|
||||
"connect.scanHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
|
||||
"connect.scanLead": "已识别到 pi2 配对信息。请确认二维码来自你信任的设备。",
|
||||
"connect.scanTitle": "扫码配对",
|
||||
"connect.scanWarning": "连接后该设备可读写会话并派发子代理。",
|
||||
"connect.scannedNote": "扫码配对",
|
||||
"connect.scope.apply": "写入",
|
||||
"connect.scope.read": "读取",
|
||||
"connect.scope.steer": "操作",
|
||||
"connect.scopeHint": "此设备获得的权限:{scope}",
|
||||
"connect.scopes": "权限",
|
||||
"connect.secureBadge": "Token 仅保存在本机",
|
||||
"connect.secureNote": "摄像头需要 HTTPS(或 localhost);Token 仅保存在此浏览器。",
|
||||
"connect.secureRequired": "摄像头需要 HTTPS(或 localhost)安全环境,请改用下方配对链接。",
|
||||
"connect.server": "服务器",
|
||||
"connect.startingCamera": "正在启动摄像头…",
|
||||
"connect.statePaired": "已连接",
|
||||
"connect.stateUnpaired": "未连接",
|
||||
"connect.subtitle": "连接本机 pi2 实例,查看配对与连接信息。",
|
||||
@@ -658,7 +633,6 @@
|
||||
"status.tasks": "后台任务",
|
||||
"status.tasksError": "加载后台任务失败",
|
||||
"status.title": "服务器状态",
|
||||
"status.tokenScopes": "Token 权限",
|
||||
"status.updated": "{time}更新",
|
||||
"status.uptime": "已运行时长",
|
||||
"status.workspaces": "工作空间数",
|
||||
|
||||
+12
-202
@@ -7,7 +7,6 @@ import { ConfirmDialog } from "@/components/shared/confirm-dialog";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { KV } from "@/components/ui/kv";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
@@ -22,12 +21,10 @@ import {
|
||||
readPairMeta,
|
||||
redeemPairing,
|
||||
safePairNext,
|
||||
scopesForIdentity,
|
||||
writePairMeta,
|
||||
type PairMeta,
|
||||
type PairTarget,
|
||||
} from "@/features/connect/pairing";
|
||||
import { ScanDialog } from "@/features/connect/scan-dialog";
|
||||
import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server";
|
||||
import { useInfoQuery } from "@/features/status/queries";
|
||||
import { getDeviceToken, setDeviceToken } from "@/lib/api";
|
||||
@@ -35,13 +32,6 @@ import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
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 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 wsState = useConnectionStore((state) => state.wsState);
|
||||
const storedServer = useConnectionStore((state) => state.server);
|
||||
const storedScopes = useConnectionStore((state) => state.scopes);
|
||||
|
||||
const [meta, setMeta] = useState<PairMeta | null>(() => readPairMeta());
|
||||
const [scanOpen, setScanOpen] = useState(false);
|
||||
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. */
|
||||
/** Connected state: the re-pair panel (the manual form) expands in place. */
|
||||
const [repairOpen, setRepairOpen] = useState(false);
|
||||
const [repairManualOpen, setRepairManualOpen] = useState(false);
|
||||
/** `/connect?…&auto=1` (from a scanned `/pair/<CODE>` link): pair with no input. */
|
||||
/** `/connect?…&auto=1` (from a `/pair/<CODE>` link): pair with no input. */
|
||||
const autoParam = useMemo(() => {
|
||||
const raw = search.get("auto");
|
||||
return raw === "1" || raw === "true";
|
||||
@@ -120,7 +102,6 @@ export function ConnectPage() {
|
||||
fetchedAt: info.dataUpdatedAt || null,
|
||||
nameFallback: storedServer?.name || meta?.server?.name,
|
||||
});
|
||||
const scopes = scopesForIdentity(meta, info.data, storedScopes);
|
||||
const defaultDeviceName = t("connect.defaultDeviceName");
|
||||
const osLabel = info.data?.os || info.data?.platform || server.os || "—";
|
||||
const uptimeSeconds =
|
||||
@@ -128,9 +109,9 @@ export function ConnectPage() {
|
||||
const defaultPort = defaultPortFor(info.data?.port ?? server.port);
|
||||
|
||||
/**
|
||||
* One pairing path for the scan/confirm dialog and the manual form:
|
||||
* redeem against the public endpoint, persist token + scopes, then follow
|
||||
* the allow-listed `next`.
|
||||
* One pairing path for the zero-input link and the manual form: redeem
|
||||
* against the public endpoint, persist token + metadata, then follow the
|
||||
* allow-listed `next`.
|
||||
*/
|
||||
const finishPairing = useCallback(
|
||||
async (target: PairTarget, deviceName: string) => {
|
||||
@@ -140,17 +121,15 @@ export function ConnectPage() {
|
||||
deviceName,
|
||||
});
|
||||
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 = {
|
||||
scopes: result.scopes,
|
||||
deviceName,
|
||||
kind: result.kind,
|
||||
server: result.server,
|
||||
pairedAt: Date.now(),
|
||||
};
|
||||
writePairMeta(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 });
|
||||
},
|
||||
[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() {
|
||||
disconnect();
|
||||
clearPairMeta();
|
||||
setMeta(null);
|
||||
setRepairOpen(false);
|
||||
setManualOpen(false);
|
||||
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) {
|
||||
return (
|
||||
<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. */
|
||||
function connectedPanel() {
|
||||
return (
|
||||
@@ -303,24 +229,6 @@ export function ConnectPage() {
|
||||
</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.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")}>
|
||||
<RelativeTime ts={connectedAt || meta?.pairedAt || null} />
|
||||
</KV>
|
||||
@@ -342,9 +250,9 @@ export function ConnectPage() {
|
||||
aria-expanded={repairOpen}
|
||||
aria-controls="cn-repair"
|
||||
data-testid="connect-repair"
|
||||
onClick={toggleRepair}
|
||||
onClick={() => setRepairOpen((open) => !open)}
|
||||
>
|
||||
<Icon name="scan" />
|
||||
<Icon name="refresh" />
|
||||
{t("connect.reconnect")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -360,22 +268,7 @@ export function ConnectPage() {
|
||||
</div>
|
||||
|
||||
<div className="cn-repair" id="cn-repair" hidden={!repairOpen} data-testid="connect-repair-panel">
|
||||
<div className="cn-pair">
|
||||
<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)}
|
||||
{renderManualForm(repairOpen, repairOpen)}
|
||||
</div>
|
||||
|
||||
<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() {
|
||||
return (
|
||||
<section className="card card--quiet cn-card" aria-labelledby="cn-card-title">
|
||||
@@ -436,23 +329,7 @@ export function ConnectPage() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="cn-pair">
|
||||
<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)}
|
||||
{renderManualForm(true, true)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -477,73 +354,6 @@ export function ConnectPage() {
|
||||
</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
|
||||
open={disconnectOpen}
|
||||
onOpenChange={setDisconnectOpen}
|
||||
|
||||
@@ -11,7 +11,6 @@ import { toast } from "@/components/ui/toast";
|
||||
import {
|
||||
clearPairMeta,
|
||||
readPairMeta,
|
||||
scopesForIdentity,
|
||||
} from "@/features/connect/pairing";
|
||||
import { ConnectionCard } from "@/features/status/connection-card";
|
||||
import { deviceKey, DevicesCard } from "@/features/status/devices-card";
|
||||
@@ -84,7 +83,6 @@ export function StatusPage() {
|
||||
const models = useModelsQuery(modelsWorkspaceId);
|
||||
|
||||
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 server = deriveServerIdentity({
|
||||
@@ -242,7 +240,6 @@ export function StatusPage() {
|
||||
<ConnectionCard
|
||||
server={server}
|
||||
deviceName={storedDeviceName || meta?.deviceName || ""}
|
||||
scopes={scopes}
|
||||
connectedAt={connectedAt || meta?.pairedAt || null}
|
||||
loading={info.isPending}
|
||||
error={info.isError ? translatedError(info.error, "status.infoError", t) : null}
|
||||
|
||||
@@ -8,9 +8,6 @@ export const CONNECTION_KEY = "pi2-connection";
|
||||
export const ENDPOINT_KEY = "pi2-endpoint";
|
||||
export const DEVICE_KEY = "pi2-device";
|
||||
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 {
|
||||
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 interface ConnectionStore {
|
||||
@@ -65,14 +42,12 @@ export interface ConnectionStore {
|
||||
deviceName: string;
|
||||
connectedAt: number;
|
||||
token: string | null;
|
||||
/** Device scopes granted by the daemon when this browser was paired. */
|
||||
scopes: string[];
|
||||
server: InfoResponse | null;
|
||||
wsState: WsConnectionState;
|
||||
|
||||
isPaired: () => boolean;
|
||||
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;
|
||||
setServer: (server: InfoResponse | null) => void;
|
||||
setWsState: (state: WsConnectionState) => void;
|
||||
@@ -86,7 +61,6 @@ function initialState() {
|
||||
deviceName: read(DEVICE_KEY) ?? "",
|
||||
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
|
||||
token: getDeviceToken(),
|
||||
scopes: readScopes(),
|
||||
server: null as InfoResponse | null,
|
||||
wsState: "idle" as WsConnectionState,
|
||||
};
|
||||
@@ -99,12 +73,11 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
|
||||
|
||||
refreshFromStorage: () => set(initialState()),
|
||||
|
||||
connect: ({ endpoint, deviceName, token, scopes } = {}) => {
|
||||
connect: ({ endpoint, deviceName, token } = {}) => {
|
||||
const now = Date.now();
|
||||
if (endpoint) write(ENDPOINT_KEY, endpoint);
|
||||
if (deviceName) write(DEVICE_KEY, deviceName);
|
||||
if (token !== undefined) setDeviceToken(token);
|
||||
if (scopes !== undefined) writeScopes(scopes);
|
||||
write(CONNECTED_AT_KEY, String(now));
|
||||
write(CONNECTION_KEY, "paired");
|
||||
set({
|
||||
@@ -113,7 +86,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
|
||||
deviceName: deviceName ?? get().deviceName,
|
||||
connectedAt: now,
|
||||
token: getDeviceToken(),
|
||||
scopes: scopes !== undefined ? readScopes() : get().scopes,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -121,7 +93,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
|
||||
drop(ENDPOINT_KEY);
|
||||
drop(DEVICE_KEY);
|
||||
drop(CONNECTED_AT_KEY);
|
||||
drop(SCOPES_KEY);
|
||||
setDeviceToken(null);
|
||||
write(CONNECTION_KEY, "unpaired");
|
||||
set({
|
||||
@@ -130,7 +101,6 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
|
||||
deviceName: "",
|
||||
connectedAt: 0,
|
||||
token: null,
|
||||
scopes: [...DEFAULT_CONNECTION_SCOPES],
|
||||
server: null,
|
||||
wsState: "idle",
|
||||
});
|
||||
|
||||
@@ -102,7 +102,7 @@
|
||||
}
|
||||
.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 {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
@@ -115,29 +115,6 @@
|
||||
color: var(--faint);
|
||||
}
|
||||
.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 ---------- */
|
||||
.cn-state { gap: var(--space-3); }
|
||||
.cn-state__head {
|
||||
@@ -168,8 +145,6 @@
|
||||
.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-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 {
|
||||
display: flex;
|
||||
@@ -267,111 +242,6 @@
|
||||
.cn .btn .cn-ico svg { width: 15px; height: 15px; display: block; }
|
||||
.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 ---------- */
|
||||
@media (max-width: 899px) {
|
||||
.cn-hero { align-items: center; text-align: center; }
|
||||
@@ -388,12 +258,9 @@
|
||||
.cn-hero__title { font-size: var(--fs-xl); }
|
||||
.cn-features { gap: 6px; }
|
||||
.cn .card--quiet { padding: var(--space-4); }
|
||||
.cn .btn,
|
||||
.cn-scan .btn { min-height: 44px; }
|
||||
.cn .btn { min-height: 44px; }
|
||||
.cn .input { 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__main { flex-direction: column; align-items: stretch; }
|
||||
.cn-actions .btn,
|
||||
@@ -401,8 +268,4 @@
|
||||
.cn-row { grid-template-columns: minmax(0, 1fr); }
|
||||
.cn-form__foot .btn,
|
||||
.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; }
|
||||
}
|
||||
@@ -276,9 +276,8 @@
|
||||
.device-icon svg { width: 16px; height: 16px; }
|
||||
.device-main { min-width: 0; }
|
||||
.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); }
|
||||
.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:hover {
|
||||
color: var(--destructive);
|
||||
@@ -356,10 +355,8 @@
|
||||
overflow-wrap: anywhere;
|
||||
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 */
|
||||
.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 {
|
||||
@@ -399,6 +396,20 @@
|
||||
border: 1px solid var(--border-subtle);
|
||||
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 svg { width: 13px; height: 13px; flex: none; margin-top: 2px; }
|
||||
.pair-expiry { font-size: var(--fs-xs); white-space: nowrap; }
|
||||
|
||||
@@ -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 {
|
||||
return {
|
||||
method: "POST",
|
||||
path: "/api/v1/pair",
|
||||
path: "/api/v1/pair/redeem",
|
||||
handler: () => ({
|
||||
status: reply.status ?? 200,
|
||||
body: reply.body ?? {
|
||||
@@ -44,7 +44,6 @@ function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
|
||||
id: "dev-7c1",
|
||||
name: "My browser",
|
||||
kind: "laptop",
|
||||
scopes: ["read", "steer"],
|
||||
lastSeenAt: 1_700_000_000_000,
|
||||
},
|
||||
},
|
||||
@@ -54,31 +53,35 @@ function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
|
||||
|
||||
interface PairCall {
|
||||
origin: string;
|
||||
path: string;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Every recorded `POST` to the pairing surface (mint or redeem). */
|
||||
function pairCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] {
|
||||
return fetchMock.mock.calls
|
||||
.filter(([input, init]) => {
|
||||
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]) => {
|
||||
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
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 expandManual() {
|
||||
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 redeemCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] {
|
||||
return pairCalls(fetchMock).filter((call) => call.path === "/api/v1/pair/redeem");
|
||||
}
|
||||
|
||||
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.port !== undefined) fireEvent.change(screen.getByTestId("connect-port"), { target: { value: values.port } });
|
||||
if (values.code !== undefined) {
|
||||
@@ -117,37 +120,22 @@ describe("ConnectPage", () => {
|
||||
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()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
const scan = screen.getByTestId("connect-scan");
|
||||
expect(scan).toHaveClass("btn--primary");
|
||||
expect(primaries()).toHaveLength(1);
|
||||
|
||||
// The camera scanner is gone: the form is the only path and it is open.
|
||||
expect(screen.queryByTestId("connect-scan")).toBeNull();
|
||||
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(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
|
||||
expect(screen.getByTestId("connect-scan")).not.toHaveClass("btn--primary");
|
||||
expect(primaries()).toHaveLength(1);
|
||||
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 () => {
|
||||
mockApi([pairRoute()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
expandManual();
|
||||
|
||||
const port = screen.getByTestId("connect-port");
|
||||
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());
|
||||
fireEvent.click(screen.getByTestId("connect-repair"));
|
||||
expandManual();
|
||||
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 () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
expandManual();
|
||||
|
||||
const submit = screen.getByTestId("connect-submit");
|
||||
fireEvent.click(submit);
|
||||
@@ -198,17 +184,41 @@ describe("ConnectPage", () => {
|
||||
it("labels the third field as a pairing code and uppercases input", async () => {
|
||||
mockApi([pairRoute()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
expandManual();
|
||||
|
||||
expect(screen.getByLabelText("Pairing code")).toBe(screen.getByTestId("connect-pair-code"));
|
||||
fillManualForm({ code: "ab-cd12 34" });
|
||||
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 { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
expandManual();
|
||||
|
||||
fillManualForm({ host: "192.168.2.10", port: "4321", code: "abcd1234", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
@@ -216,12 +226,13 @@ describe("ConnectPage", () => {
|
||||
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-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[0]?.origin).toBe("http://192.168.2.10:4321");
|
||||
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"));
|
||||
expect(await screen.findByText("Workspaces destination")).toBeInTheDocument();
|
||||
@@ -239,14 +250,15 @@ describe("ConnectPage", () => {
|
||||
await waitFor(() => expect(localStorage.getItem("pi2-connection")).toBe("paired"));
|
||||
expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test");
|
||||
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[0]?.origin).toBe(origin);
|
||||
expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "Web console" });
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -278,14 +290,13 @@ describe("ConnectPage", () => {
|
||||
const { router } = await renderPage(routes(), "/connect?next=%2Fchat%2F01a15368%3Fworkspace%3Dws-1", {
|
||||
paired: false,
|
||||
});
|
||||
expandManual();
|
||||
|
||||
fillManualForm({ host: "192.168.2.10", port: "4321", code: "ABCD1234", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/chat/01a15368"));
|
||||
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 () => {
|
||||
@@ -296,7 +307,6 @@ describe("ConnectPage", () => {
|
||||
}),
|
||||
]);
|
||||
const { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
expandManual();
|
||||
|
||||
fillManualForm({ host: "192.168.2.10", port: "4321", code: "ZZZZ9999", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
@@ -310,53 +320,13 @@ describe("ConnectPage", () => {
|
||||
expect(screen.getByTestId("connect-submit")).toBeEnabled();
|
||||
});
|
||||
|
||||
it("warns then pairs from a pasted pi2 pair link through the confirmation dialog", 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 () => {
|
||||
it("shows the connected summary with server identity and one primary", async () => {
|
||||
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
||||
await renderPage(routes(), "/connect", {
|
||||
paired: true,
|
||||
storage: {
|
||||
"pi2-device": "Test browser",
|
||||
"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("0.4.2")).toBeInTheDocument();
|
||||
expect(screen.getByText("Test browser")).toBeInTheDocument();
|
||||
expect(screen.getByText("Read")).toBeInTheDocument();
|
||||
expect(screen.getByText("Steer")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Apply")).not.toBeInTheDocument();
|
||||
// Scopes are gone from the console entirely.
|
||||
expect(screen.queryByText("Scopes")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Read")).not.toBeInTheDocument();
|
||||
|
||||
// Back to workspaces is the single primary while the re-pair panel is closed.
|
||||
expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary");
|
||||
@@ -378,7 +348,7 @@ describe("ConnectPage", () => {
|
||||
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 }) }]);
|
||||
await renderPage(routes(), "/connect", {
|
||||
paired: true,
|
||||
@@ -389,19 +359,13 @@ describe("ConnectPage", () => {
|
||||
fireEvent.click(repair);
|
||||
const panel = screen.getByTestId("connect-repair-panel");
|
||||
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(primaries()).toHaveLength(1);
|
||||
|
||||
expandManual();
|
||||
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.
|
||||
// Collapsing the panel returns the primary to "back to workspaces".
|
||||
fireEvent.click(repair);
|
||||
expect(panel).toHaveAttribute("hidden");
|
||||
expect(screen.getByTestId("connect-manual-panel")).toHaveAttribute("hidden");
|
||||
expect(screen.getByTestId("connect-back")).toHaveClass("btn--primary");
|
||||
expect(primaries()).toHaveLength(1);
|
||||
});
|
||||
@@ -421,9 +385,9 @@ describe("ConnectPage", () => {
|
||||
|
||||
await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBeNull());
|
||||
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.getByTestId("connect-scan")).toHaveClass("btn--primary");
|
||||
expect(screen.getByTestId("connect-submit")).toHaveClass("btn--primary");
|
||||
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", () => {
|
||||
expect(parsePairLink("https://192.168.2.10:4321/pair/ABCD1234")).toMatchObject({
|
||||
endpoint: "https://192.168.2.10:4321",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { commandCalls, mockApi, type MockRoute } from "./helpers/api-mock";
|
||||
import { renderPage } from "./helpers/render-page";
|
||||
|
||||
import { drawQr } from "@/features/status/qr";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { StatusPage } from "@/pages/status";
|
||||
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 = {
|
||||
accepted: true,
|
||||
code: "ABCD1234",
|
||||
url: "http://127.0.0.1:4321/pair/ABCD1234",
|
||||
expiresAt: Date.now() + 9 * 60_000,
|
||||
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 = {
|
||||
@@ -107,7 +115,6 @@ const devicesBody = [
|
||||
id: "dev-1",
|
||||
name: "Pixel",
|
||||
kind: "phone",
|
||||
scopes: ["read", "steer"],
|
||||
createdAt: Date.now() - 90_000,
|
||||
lastSeenAt: Date.now() - 60_000,
|
||||
revokedAt: null,
|
||||
@@ -177,6 +184,48 @@ afterEach(() => {
|
||||
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", () => {
|
||||
it("renders the four metric tiles, one count line and no primary button", async () => {
|
||||
mockApi(apiRoutes());
|
||||
@@ -275,12 +324,15 @@ describe("StatusPage", () => {
|
||||
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());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
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(/Pairing code expires in \d+ minutes/)).toBeInTheDocument();
|
||||
|
||||
@@ -293,6 +345,26 @@ describe("StatusPage", () => {
|
||||
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 () => {
|
||||
let attempts = 0;
|
||||
mockApi(
|
||||
|
||||
Reference in new issue
Block a user