fix(web): make the web console work end-to-end

- Pair through the public POST /api/v1/pair and persist the device scopes;
  keep the allow-listed next deep link. Rename the manual field to pairing code.
- Authenticate the WebSocket with the raw device token (strip Bearer) and
  recover from a 401 by clearing the connection once.
- Fix chat payloads: setModel/setThinking, attention/diff responses, subagent
  dispatch items, queue ids/mode, task output and WS resume since.
- Render exactly one assistant message per turn: one-to-one snapshot/history
  merge plus a stale-delta guard after message_end (fixes PONGONG).
- Fix dialogs (content above the overlay), unknown-session deep links
  (error + retry, no silent fallback), device list/revoke, status identity and
  live pairing code, reconnect banner and Playwright selectors.
This commit is contained in:
yuez committed 2026-10-21 20:42:19 +08:00
1 parent 5572ac0d84
commit 0ef019f58d
57 files changed
+3549 -684

No files matched your search

+44 -3
View File
@@ -118,10 +118,43 @@ interface RequestOptions {
/** Absolute URL for pairing (before a device token exists). */
baseUrl?: string;
timeoutMs?: number;
/**
* A 401 on this request must not clear the connection. Pairing requests use
* `baseUrl` and may legitimately answer 401 for a wrong code while another
* device token is already stored.
*/
skipAuthReset?: boolean;
}
export type UnauthorizedHandler = (error: ApiError) => void;
const unauthorizedHandlers = new Set<UnauthorizedHandler>();
/**
* Subscribe to authenticated-request 401s (`E_UNAUTHORIZED`) so the shell can
* clear a stale device token and bounce the user back to `/connect`.
*/
export function onUnauthorized(handler: UnauthorizedHandler): () => void {
unauthorizedHandlers.add(handler);
return () => {
unauthorizedHandlers.delete(handler);
};
}
function notifyUnauthorized(error: ApiError): void {
for (const handler of [...unauthorizedHandlers]) {
try {
handler(error);
} catch {
/* a listener must never break the request path */
}
}
}
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { method = "GET", body, signal, headers = {}, baseUrl = "", timeoutMs = 20_000 } = options;
const { method = "GET", body, signal, headers = {}, baseUrl = "", timeoutMs = 20_000, skipAuthReset } = options;
// Only same-origin API calls authenticate as the stored device token.
const resetsAuthOn401 = skipAuthReset ? false : baseUrl === "";
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(new DOMException("Request timed out", "TimeoutError")), timeoutMs);
const onAbort = () => controller.abort(signal?.reason);
@@ -148,13 +181,17 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
if (!response.ok) {
const errorBody = extractErrorBody(payload);
throw new ApiError({
const error = new ApiError({
code: errorBody?.code ?? statusCode(response.status),
message: errorBody?.message ?? (response.statusText || `HTTP ${response.status}`),
status: response.status,
retryable: errorBody?.retryable ?? response.status >= 500,
details: errorBody?.details,
});
if (resetsAuthOn401 && (response.status === 401 || error.code === "E_UNAUTHORIZED")) {
notifyUnauthorized(error);
}
throw error;
}
return payload as T;
@@ -217,6 +254,9 @@ export interface InfoResponse {
pluginVersion?: string;
host?: string;
port?: number;
/** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */
os?: string;
uptimeMs?: number;
status?: "online" | "degraded" | "offline";
}
@@ -309,8 +349,9 @@ export const api = {
request<{ accepted: boolean; disposition?: string }>("/api/v1/cmd", { method: "POST", body, signal }),
pairCreate: (baseUrl?: string, signal?: AbortSignal) =>
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/redeem", { method: "POST", body, baseUrl, signal }),
request<PairResponse>("/api/v1/pair", { method: "POST", body, baseUrl, signal, skipAuthReset: true }),
};
export { request as apiRequest };
+142 -8
View File
@@ -247,23 +247,157 @@ export function projectEntries(rawEntries: unknown[]): ProjectedEntry[] {
return out;
}
/** Live snapshot entries win over the same id from a historical page. */
/** Normalized plain text of an entry (the identity fallback below). */
function entryText(entry: Entry): string {
const parts: string[] = [];
for (const block of entry.blocks) {
if (block.type === "text" || block.type === "error" || block.type === "thinking") parts.push(block.text);
}
return parts.join("\n").replace(/\s+/g, " ").trim();
}
/**
* Exact identity: role, second-bucketed timestamp and normalized text.
*
* Kept for callers that want a cheap map key, but *not* used as the only
* cross-source identity: the two sources derive `ts` from different clocks
* (snapshot entries carry the plugin's event timestamp, projected pi entries
* carry the message timestamp), so the same message can land in adjacent
* buckets or seconds apart (see `matchIndex`).
*/
export function entrySignature(entry: Entry): string | null {
const text = entryText(entry);
if (!text) return null;
return `${entry.role}|${Math.round(entry.ts / 1_000)}|${text}`;
}
/**
* Timestamp distance as a ranking tie-break well below one tier step, so a
* looser identity tier never outranks a tighter one.
*/
function skewScore(a: Entry, b: Entry): number {
return Math.min(Math.abs(a.ts - b.ts), 60_000) / 120_000;
}
/**
* Identity index over one side of a merge: exact id, exact `(role, ts, text)`
* signature and `(role, text)`. Built once per merge so a re-render stays cheap.
*/
interface PoolIndex {
items: Entry[];
byId: Map<string, number[]>;
bySignature: Map<string, number[]>;
byText: Map<string, number[]>;
}
function indexPool(items: Entry[]): PoolIndex {
const index: PoolIndex = { items, byId: new Map(), bySignature: new Map(), byText: new Map() };
const add = (bucket: Map<string, number[]>, key: string, at: number) => {
const list = bucket.get(key);
if (list) list.push(at);
else bucket.set(key, [at]);
};
items.forEach((entry, at) => {
add(index.byId, entry.id, at);
const signature = entrySignature(entry);
if (signature !== null) add(index.bySignature, signature, at);
const text = entryText(entry);
if (text) add(index.byText, `${entry.role}|${text}`, at);
});
return index;
}
/**
* Index of the entry in `index` that is the same message as `candidate`, or -1.
*
* The snapshot tail (synthetic `m<N>` ids, plugin event clock) and the REST
* pages (pi's raw ids, message clock) describe the same transcript under
* different ids *and* slightly different timestamps, so identity falls back to
* `(role, normalized text)` with the closest timestamp winning. `isTaken` keeps
* the pairing one-to-one, so two genuinely repeated messages never collapse
* into one.
*/
function matchIndex(index: PoolIndex, candidate: Entry, isTaken: (at: number) => boolean): number {
const signature = entrySignature(candidate);
const text = entryText(candidate);
// Collect every identity tier a pool entry reaches; the tightest one wins.
const tiers = new Map<number, number>();
const offer = (at: number, tier: number) => {
const current = tiers.get(at);
if (current === undefined || tier < current) tiers.set(at, tier);
};
for (const at of index.byId.get(candidate.id) ?? []) offer(at, 0);
if (signature !== null) {
for (const at of index.bySignature.get(signature) ?? []) offer(at, 1);
}
if (text) {
for (const at of index.byText.get(`${candidate.role}|${text}`) ?? []) offer(at, 2);
}
let best = -1;
let bestScore = Number.POSITIVE_INFINITY;
for (const [at, tier] of tiers) {
if (isTaken(at)) continue;
const entry = index.items[at];
if (!entry || entry.role !== candidate.role) continue;
const score = tier + skewScore(entry, candidate);
if (score < bestScore) {
bestScore = score;
best = at;
}
}
return best;
}
/**
* Live entries win over the same message from a historical page: by id first,
* then by `(role, text)` when the ids differ (the snapshot carries synthetic
* `m<N>` ids while the pages carry pi's raw entry ids). The historical position
* is kept so the transcript never re-orders, and each message renders once.
*/
export function mergeEntries(history: Entry[], live: Entry[]): Entry[] {
if (!history.length) return live;
if (!live.length) return history;
const liveById = new Map(live.map((entry) => [entry.id, entry]));
const merged: Entry[] = history.map((entry) => liveById.get(entry.id) ?? entry);
const historical = new Set(history.map((entry) => entry.id));
// Match from the live side so a live entry always claims its closest page
// counterpart, even when the page holds several identical texts.
const historyIndex = indexPool(history);
const claimed = new Set<number>();
const replaces = new Map<number, Entry>();
for (const entry of live) {
if (!historical.has(entry.id)) merged.push(entry);
const match = matchIndex(historyIndex, entry, (at) => claimed.has(at));
if (match < 0) continue;
claimed.add(match);
replaces.set(match, entry);
}
const merged: Entry[] = history.map((entry, index) => replaces.get(index) ?? entry);
const rendered = new Set<Entry>(replaces.values());
for (const entry of live) {
if (!rendered.has(entry)) merged.push(entry);
}
return merged;
}
/** Prepend an older page while never duplicating an id already rendered. */
/**
* Prepend an older page while never duplicating an entry already rendered —
* by id, then by `(role, text)` — and keeping the page's own order.
*/
export function prependUnique(existing: Entry[], older: Entry[]): Entry[] {
const seen = new Set(existing.map((entry) => entry.id));
const fresh = older.filter((entry) => !seen.has(entry.id));
if (!older.length) return existing;
// Each already-rendered entry absorbs at most one match from the page.
const existingIndex = indexPool(existing);
const claimed = new Set<number>();
const fresh: Entry[] = [];
for (const entry of older) {
const match = matchIndex(existingIndex, entry, (at) => claimed.has(at));
if (match >= 0) {
claimed.add(match);
continue;
}
fresh.push(entry);
}
return fresh.length ? [...fresh, ...existing] : existing;
}
+41 -13
View File
@@ -3,8 +3,8 @@
*
* Frame flow (docs/protocol.md §1/§3.3):
* connect → socket open → auth frame → hello_ack → open (subscriptions flush)
* snapshot replaces the render cache and establishes `seq`
* event increments `seq`; reconnect resubscribes with `sinceSeq` for a lossless resume
* snapshot replaces the render cache and establishes `(epoch, seq)`
* event increments `seq`; reconnect resubscribes with `since` for a lossless resume
*
* The frame envelope is shared with the daemon (`v`, `type`, `id`, `payload`).
* The auth frame is the first frame on every socket, before any subscribe.
@@ -77,6 +77,26 @@ export interface PiWsOptions {
const AUTH_FRAME_TYPE = "auth";
/** `Authorization: Bearer <token>` prefix, the shape `setDeviceToken()` stores. */
const BEARER_PREFIX = /^bearer(?:\s+|$)/i;
/**
* Unwrap an `Authorization: Bearer` style token for the WS auth frame.
*
* `setDeviceToken()` persists the token as `Bearer <token>` (the HTTP client
* strips the prefix in `authHeader()`), but the daemon hashes the auth-frame
* string verbatim in `verifyToken()` and does not understand the prefix. Sending
* it unchanged makes every authenticated socket fail with `E_UNAUTHORIZED`.
*
* @param token Token as stored (`abc` or `Bearer abc`).
* @returns The bare token, or `undefined` when there is nothing to send.
*/
export function normalizeDeviceToken(token: string | null | undefined): string | undefined {
if (typeof token !== "string") return undefined;
const stripped = token.trim().replace(BEARER_PREFIX, "").trim();
return stripped.length ? stripped : undefined;
}
function defaultFactory(url: string): WebSocketLike {
return new WebSocket(url) as unknown as WebSocketLike;
}
@@ -216,7 +236,9 @@ export class PiWsClient {
socket.onopen = () => {
if (this.socket !== socket) return;
this.setState("authenticating");
this.send({ v: 1, type: AUTH_FRAME_TYPE, token: this.token ?? undefined });
// Normalized on every socket (not cached) so a re-partnered token is
// picked up by the next reconnect too.
this.send({ v: 1, type: AUTH_FRAME_TYPE, token: normalizeDeviceToken(this.token) });
this.authTimer = setTimeout(() => {
if (this.state !== "authenticating" || this.socket !== socket) return;
this.handlers.onError?.(new Error("WebSocket auth timed out"));
@@ -314,19 +336,25 @@ export class PiWsClient {
private sendSubscribe(sessionIds: string[]): void {
if (!sessionIds.length) return;
const sinceSeq: Record<string, number> = {};
// The daemon accepts one `since` cursor per frame (protocol §3.3), so a
// resumable session gets its own subscribe frame; the rest are batched.
const fresh: string[] = [];
for (const id of sessionIds) {
const seq = this.lastSeq.get(id);
if (seq !== undefined) sinceSeq[id] = seq;
const epoch = this.epochs.get(id);
if (seq === undefined || epoch === undefined) {
fresh.push(id);
continue;
}
this.send({
v: 1,
type: "subscribe",
payload: { sessionIds: [id], since: { sessionId: id, epoch, seq } },
});
}
if (fresh.length) {
this.send({ v: 1, type: "subscribe", payload: { sessionIds: fresh } });
}
this.send({
v: 1,
type: "subscribe",
payload: {
sessionIds,
...(Object.keys(sinceSeq).length ? { sinceSeq } : {}),
},
});
}
private flushSubscriptions(): void {