Files
pi2d/web/src/features/status/queries.ts
T
yuez 3e35fb7ef3 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.
2026-10-27 10:44:54 +08:00

213 lines
7.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useQueries, useQuery } from "@tanstack/react-query";
import {
api,
apiRequest,
type HealthResponse,
type InfoResponse,
type ModelInfo,
type ResourcesResponse,
} from "@/lib/api";
import type { SessionState, TaskItem, WorkspaceInfo } from "@/lib/protocol";
/**
* `GET /api/v1/devices` answers a **bare array** (`auth.listDevices()`); older
* builds wrapped it as `{devices:[…]}`. `id` is the daemon's device id, while
* `deviceId` is what pairing responses call it.
*/
export interface DeviceEntry {
id?: string;
deviceId?: string;
name: string;
kind: string;
/** `lastSeenAt` is the daemon field; `lastActiveAt` came from older builds. */
lastActiveAt?: number | null;
lastSeenAt?: number | null;
createdAt?: number | null;
revokedAt?: number | null;
}
export interface DevicesResponse {
devices: DeviceEntry[];
}
export interface ModelsResponse {
providers: ModelInfo[];
}
/** Accept the daemon's bare device array and the legacy `{devices:[…]}` envelope. */
export function normalizeDevices(payload: unknown): DeviceEntry[] {
if (Array.isArray(payload)) return payload as DeviceEntry[];
const record = payload as { devices?: unknown } | null | undefined;
return Array.isArray(record?.devices) ? (record.devices as DeviceEntry[]) : [];
}
export async function fetchDevices(signal?: AbortSignal): Promise<DevicesResponse> {
return { devices: normalizeDevices(await apiRequest<unknown>("/api/v1/devices", { signal })) };
}
export async function fetchModels(workspaceId: string, signal?: AbortSignal): Promise<ModelsResponse> {
return apiRequest<ModelsResponse>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal });
}
/**
* `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;
code?: string;
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. */
export const PAIR_CODE_TTL_SEC = 600;
export async function createPairCode(signal?: AbortSignal): Promise<PairCodeResponse> {
return apiRequest<PairCodeResponse>("/api/v1/pair", {
method: "POST",
body: { ttlSec: PAIR_CODE_TTL_SEC },
signal,
});
}
/** A background task plus the session it belongs to (the card shows both). */
export interface StatusTask extends TaskItem {
sessionId: string;
}
/** `/sessions` relays a `workspace.query` ack: `{sessions}`, `{result:{sessions}}` or a bare array. */
export function normalizeSessions(payload: unknown, workspaceId: string): SessionState[] {
if (Array.isArray(payload)) return (payload as SessionState[]).map((row) => ({ ...row, workspaceId }));
const record = payload as { sessions?: unknown; result?: { sessions?: unknown } } | null | undefined;
const rows = record?.sessions ?? record?.result?.sessions;
if (!Array.isArray(rows)) return [];
return (rows as SessionState[]).map((row) => ({ ...row, workspaceId: row.workspaceId || workspaceId }));
}
/** Every `sessions[].task` of a `/sessions` payload, tagged with its session id. */
export function sessionTasks(sessions: SessionState[]): StatusTask[] {
return sessions.flatMap((session) =>
(Array.isArray(session.tasks) ? session.tasks : []).map((task) => ({
...task,
sessionId: session.sessionId || "",
})),
);
}
/** Merge task lists, keeping the first entry per task id (live state wins). */
export function mergeTasks(...lists: StatusTask[][]): StatusTask[] {
const byId = new Map<string, StatusTask>();
for (const list of lists) {
for (const task of list) {
const key = task.id || `${task.sessionId}:${task.command}`;
if (!byId.has(key)) byId.set(key, task);
}
}
return [...byId.values()];
}
export function useInfoQuery(enabled = true) {
return useQuery<InfoResponse>({
queryKey: ["info"],
queryFn: ({ signal }) => api.info(signal),
enabled,
staleTime: 30_000,
});
}
export function useHealthQuery() {
return useQuery<HealthResponse>({
queryKey: ["health"],
queryFn: ({ signal }) => api.health(signal),
staleTime: 10_000,
});
}
export function useResourcesQuery() {
return useQuery<ResourcesResponse>({
queryKey: ["resources"],
queryFn: ({ signal }) => api.resources(signal),
// Resource pressure is the only live figure: poll every 3s while the tab is visible.
refetchInterval: 3_000,
refetchIntervalInBackground: false,
staleTime: 2_000,
});
}
/** `GET /api/v1/workspaces` answers an array; the envelope shape is only a fallback. */
export function normalizeWorkspaces(payload: unknown): WorkspaceInfo[] {
if (Array.isArray(payload)) return payload as WorkspaceInfo[];
const record = payload as { workspaces?: unknown } | null | undefined;
return Array.isArray(record?.workspaces) ? (record.workspaces as WorkspaceInfo[]) : [];
}
export function useWorkspacesQuery() {
return useQuery<WorkspaceInfo[]>({
queryKey: ["workspaces"],
queryFn: async ({ signal }) => normalizeWorkspaces(await apiRequest<unknown>("/api/v1/workspaces", { signal })),
staleTime: 10_000,
});
}
export function useDevicesQuery() {
return useQuery<DevicesResponse>({
queryKey: ["devices"],
queryFn: ({ signal }) => fetchDevices(signal),
staleTime: 10_000,
});
}
/**
* A fresh pairing code for the connection card. A code is single-use and short
* lived, so each mount mints its own (`gcTime: 0` drops it when the card goes
* away) and `refetch()` is the retry button.
*/
export function usePairCodeQuery(enabled = true) {
return useQuery<PairCodeResponse>({
queryKey: ["pair-code"],
queryFn: ({ signal }) => createPairCode(signal),
enabled,
staleTime: Number.POSITIVE_INFINITY,
gcTime: 0,
retry: false,
});
}
/**
* Sessions (and therefore background tasks) of every registered workspace, so
* the tasks card works after a hard reload instead of only from the chat store.
*/
export function useWorkspaceSessionsQueries(workspaceIds: string[], enabled = true) {
return useQueries({
queries: workspaceIds.map((workspaceId) => ({
queryKey: ["status-sessions", workspaceId],
queryFn: async ({ signal }: { signal: AbortSignal }) =>
normalizeSessions(
await apiRequest<unknown>(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/sessions`, {
signal,
}),
workspaceId,
),
enabled,
staleTime: 10_000,
retry: false,
})),
});
}
export function useModelsQuery(workspaceId: string | null | undefined) {
return useQuery<ModelsResponse>({
queryKey: ["models", workspaceId ?? ""],
queryFn: ({ signal }) => fetchModels(workspaceId ?? "", signal),
enabled: Boolean(workspaceId),
staleTime: 60_000,
});
}