feat(web): React 19 + Vite + Tailwind v4 + shadcn foundation

- design tokens ported verbatim from the product design, data-theme light/dark
- app shell: topbar, sidebar/rail/tabbar responsive nav, lang + theme menus
- ui primitives (button/card/badge/dot/chip/tabs/dialog/sheet/toast/kv/seg/progress)
- api client, reconnecting ws client, zustand stores, route guard to /connect
- full zh/en dictionaries (key parity test), 32 vitest specs, dist committed
This commit is contained in:
yuez committed 2026-10-21 11:33:36 +08:00
1 parent 4e98ef8658
commit 5b55e622ea
63 files changed
+8466

No files matched your search

+316
View File
@@ -0,0 +1,316 @@
import type {
ContextUsage,
Entry,
ErrorBody,
ModelRef,
SessionState,
TaskItem,
TodoItem,
UsageTotals,
WorkspaceInfo,
} from "./protocol";
/** Storage key shared with the prototype and the pairing flow. */
export const TOKEN_STORAGE_KEY = "pi2-device-token";
export function getDeviceToken(): string | null {
try {
return localStorage.getItem(TOKEN_STORAGE_KEY);
} catch {
return null;
}
}
export function setDeviceToken(token: string | null): void {
try {
if (token) localStorage.setItem(TOKEN_STORAGE_KEY, token.toLowerCase().startsWith("bearer ") ? token : `Bearer ${token}`);
else localStorage.removeItem(TOKEN_STORAGE_KEY);
} catch {
/* private mode */
}
}
/** Bearer header value; accepts a token with or without the `Bearer ` prefix. */
function authHeader(): Record<string, string> {
const raw = getDeviceToken()?.replace(/^Bearer\s+/i, "").trim();
return raw ? { Authorization: `Bearer ${raw}` } : {};
}
export class ApiError extends Error {
readonly code: string;
readonly status: number;
readonly retryable: boolean;
readonly details?: Record<string, unknown>;
constructor(input: { code: string; message: string; status: number; retryable?: boolean; details?: Record<string, unknown> }) {
super(input.message);
this.name = "ApiError";
this.code = input.code;
this.status = input.status;
this.retryable = input.retryable ?? false;
this.details = input.details;
}
}
/**
* Stable error code → i18n key. The daemon's `message` is English/debug only;
* the browser translates the code (docs/protocol.md §3).
*/
export const ERROR_I18N_KEYS: Record<string, string> = {
E_BAD_REQUEST: "errors.badRequest",
E_UNAUTHORIZED: "errors.unauthorized",
E_FORBIDDEN: "errors.forbidden",
E_NOT_FOUND: "errors.notFound",
E_METHOD_NOT_ALLOWED: "errors.methodNotAllowed",
E_PROTOCOL_VERSION: "errors.protocolVersion",
E_PAYLOAD_TOO_LARGE: "errors.payloadTooLarge",
E_RATE_LIMITED: "errors.rateLimited",
E_INSTANCE_STARTING: "errors.instanceStarting",
E_INSTANCE_UNMANAGED: "errors.instanceUnmanaged",
E_INSTANCE_UNAVAILABLE: "errors.instanceUnavailable",
E_LEASE: "errors.lease",
E_EXTERNAL_SESSION: "errors.externalSession",
E_SESSION_NOT_FOUND: "errors.sessionNotFound",
E_ATTENTION_RESOLVED: "errors.attentionResolved",
E_UNSUPPORTED: "errors.unsupported",
E_INTERNAL: "errors.internal",
E_NETWORK: "errors.network",
E_TIMEOUT: "errors.timeout",
E_UNKNOWN: "errors.unknown",
};
export function errorI18nKey(code: string | undefined): string {
return (code && ERROR_I18N_KEYS[code]) || "errors.unknown";
}
function statusCode(status: number): string {
switch (status) {
case 400:
return "E_BAD_REQUEST";
case 401:
return "E_UNAUTHORIZED";
case 403:
return "E_FORBIDDEN";
case 404:
return "E_NOT_FOUND";
case 405:
return "E_METHOD_NOT_ALLOWED";
case 409:
return "E_LEASE";
case 413:
return "E_PAYLOAD_TOO_LARGE";
case 429:
return "E_RATE_LIMITED";
case 426:
return "E_PROTOCOL_VERSION";
case 501:
return "E_UNSUPPORTED";
default:
return status >= 500 ? "E_INTERNAL" : "E_UNKNOWN";
}
}
interface RequestOptions {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
body?: unknown;
signal?: AbortSignal;
headers?: Record<string, string>;
/** Absolute URL for pairing (before a device token exists). */
baseUrl?: string;
timeoutMs?: number;
}
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { method = "GET", body, signal, headers = {}, baseUrl = "", timeoutMs = 20_000 } = options;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(new DOMException("Request timed out", "TimeoutError")), timeoutMs);
const onAbort = () => controller.abort(signal?.reason);
signal?.addEventListener("abort", onAbort, { once: true });
try {
const response = await fetch(`${baseUrl}${path}`, {
method,
credentials: "same-origin",
headers: {
Accept: "application/json",
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
...authHeader(),
...headers,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
if (response.status === 204) return undefined as T;
const contentType = response.headers.get("content-type") ?? "";
const payload: unknown = contentType.includes("application/json") ? await response.json() : await response.text();
if (!response.ok) {
const errorBody = extractErrorBody(payload);
throw 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,
});
}
return payload as T;
} catch (error) {
if (error instanceof ApiError) throw error;
if (error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError")) {
throw new ApiError({ code: "E_TIMEOUT", message: "Request aborted", status: 0, retryable: true });
}
throw new ApiError({
code: "E_NETWORK",
message: error instanceof Error ? error.message : String(error),
status: 0,
retryable: true,
});
} finally {
clearTimeout(timeout);
signal?.removeEventListener("abort", onAbort);
}
}
function extractErrorBody(payload: unknown): (ErrorBody & { error?: ErrorBody }) | undefined {
if (!payload || typeof payload !== "object") return undefined;
const record = payload as Record<string, unknown>;
const nested = record.error;
if (nested && typeof nested === "object") {
const err = nested as Record<string, unknown>;
return {
code: String(err.code ?? "E_UNKNOWN"),
message: String(err.message ?? ""),
retryable: Boolean(err.retryable),
details: err.details as Record<string, unknown> | undefined,
};
}
if (typeof record.code === "string") {
return {
code: record.code,
message: String(record.message ?? ""),
retryable: Boolean(record.retryable),
details: record.details as Record<string, unknown> | undefined,
};
}
return undefined;
}
/* ------------------------------------------------------------------ */
/* Wire responses */
/* ------------------------------------------------------------------ */
export interface InfoResponse {
v?: number;
daemonId?: string;
machineId?: string;
platform?: string;
capabilities?: string[];
limits?: Record<string, number>;
/** Optional identity fields the status page shows when the daemon provides them. */
name?: string;
hostname?: string;
version?: string;
pluginVersion?: string;
host?: string;
port?: number;
status?: "online" | "degraded" | "offline";
}
export interface ServerLike {
name: string;
hostname: string;
host: string;
port: number;
version: string;
pluginVersion: string;
status: "online" | "degraded" | "offline";
}
export interface HealthResponse {
ok?: boolean;
checkedAt?: number;
items: { name: string; ok: boolean; detail?: string }[];
}
export interface DeviceInfo {
deviceId: string;
name: string;
kind: "phone" | "laptop" | "tablet";
scopes: string[];
lastActiveAt: number | null;
}
export interface ModelInfo {
provider: string;
models: { id: string; contextWindow: number; reasoning: boolean }[];
}
export interface ResourcesResponse {
instances: { workspaceId: string; instanceId: string; nvimPid: number | null; rssBytes: number | null; sessions: number; hasUI: boolean }[];
totalRssBytes: number;
physicalMemoryBytes: number;
warn: boolean;
reason?: string;
}
export interface DiagnosticsResponse {
connections?: unknown[];
instances?: unknown[];
[key: string]: unknown;
}
export interface PairRequest {
code?: string;
token?: string;
deviceName?: string;
}
export interface PairResponse {
token?: string;
deviceId?: string;
scopes?: string[];
server?: Partial<InfoResponse>;
[key: string]: unknown;
}
export type { ContextUsage, Entry, ModelRef, SessionState, TaskItem, TodoItem, UsageTotals, WorkspaceInfo };
/* ------------------------------------------------------------------ */
/* Endpoints (docs/protocol.md §3.1/§3.2) */
/* ------------------------------------------------------------------ */
export const api = {
info: (signal?: AbortSignal) => request<InfoResponse>("/api/v1/info", { signal }),
health: (signal?: AbortSignal) => request<HealthResponse>("/api/v1/health", { signal }),
workspaces: (signal?: AbortSignal) => request<WorkspaceInfo[]>("/api/v1/workspaces", { signal }),
sessions: (workspaceId: string, signal?: AbortSignal) =>
request<SessionState[]>(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/sessions`, { signal }),
entries: (sessionId: string, options: { before?: number; limit?: number; signal?: AbortSignal } = {}) => {
const params = new URLSearchParams();
if (options.before !== undefined) params.set("before", String(options.before));
if (options.limit !== undefined) params.set("limit", String(options.limit));
const query = params.size ? `?${params.toString()}` : "";
return request<Entry[]>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries${query}`, { signal: options.signal });
},
attention: (workspaceId: string, signal?: AbortSignal) =>
request<unknown[]>(`/api/v1/attention?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
devices: (signal?: AbortSignal) => request<DeviceInfo[]>("/api/v1/devices", { signal }),
revokeDevice: (deviceId: string, signal?: AbortSignal) =>
request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }),
models: (workspaceId: string, signal?: AbortSignal) =>
request<ModelInfo[]>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
resources: (signal?: AbortSignal) => request<ResourcesResponse>("/api/v1/resources", { signal }),
diagnostics: (signal?: AbortSignal) => request<DiagnosticsResponse>("/api/v1/diagnostics", { signal }),
command: (body: { method: string; params?: Record<string, unknown>; sessionId?: string; clientRequestId?: string }, signal?: AbortSignal) =>
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 }),
pairRedeem: (body: PairRequest, baseUrl?: string, signal?: AbortSignal) =>
request<PairResponse>("/api/v1/pair/redeem", { method: "POST", body, baseUrl, signal }),
};
export { request as apiRequest };
+98
View File
@@ -0,0 +1,98 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "@/locales/en.json";
import zh from "@/locales/zh.json";
export const LANGUAGES = ["zh", "en"] as const;
export type Language = (typeof LANGUAGES)[number];
export const LANGUAGE_STORAGE_KEY = "pi2-lang";
const SHORT: Record<Language, string> = { zh: "中", en: "EN" };
export function isLanguage(value: unknown): value is Language {
return typeof value === "string" && (LANGUAGES as readonly string[]).includes(value);
}
/** `pi2-lang` wins; otherwise follow the browser (zh* → zh, anything else → en). */
export function detectLanguage(): Language {
try {
const saved = localStorage.getItem(LANGUAGE_STORAGE_KEY);
if (isLanguage(saved)) return saved;
} catch {
/* private mode */
}
const nav = String(navigator.language || "zh").toLowerCase();
return nav.startsWith("zh") ? "zh" : "en";
}
export function localeFor(language: Language): string {
return language === "zh" ? "zh-CN" : "en-US";
}
void i18n.use(initReactI18next).init({
resources: {
zh: { translation: zh },
en: { translation: en },
},
lng: detectLanguage(),
fallbackLng: "zh",
supportedLngs: [...LANGUAGES],
load: "currentOnly",
// The design catalog is flat and uses dotted keys, so disable i18next's separators.
keySeparator: false,
nsSeparator: false,
// The design catalog interpolates with single braces: "{n} minutes ago".
interpolation: { prefix: "{", suffix: "}", escapeValue: false },
returnNull: false,
returnEmptyString: false,
});
if (typeof document !== "undefined") {
document.documentElement.lang = localeFor(i18n.language as Language);
}
/** Switch language and persist it to `pi2-lang` (the design's storage key). */
export async function setLanguage(language: Language): Promise<void> {
if (!isLanguage(language)) return;
await i18n.changeLanguage(language);
try {
localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
} catch {
/* private mode */
}
if (typeof document !== "undefined") {
document.documentElement.lang = localeFor(language);
}
}
export function currentLanguage(): Language {
return isLanguage(i18n.language) ? i18n.language : "zh";
}
/** Localized language name, e.g. Chinese UI → 中文 / 英文; English UI → Chinese / English. */
export function languageLabel(language: Language): string {
return i18n.t(`language.${language}`);
}
export function languageShort(language: Language): string {
return SHORT[language];
}
/**
* Port of the prototype's `I18N.plural`: pick `key.one` / `key.other` through
* `Intl.PluralRules`, falling back to the base key when the suffix is absent.
*/
export function plural(key: string, n: number, params?: Record<string, unknown>): string {
let category = n === 1 ? "one" : "other";
try {
category = new Intl.PluralRules(localeFor(currentLanguage())).select(n);
} catch {
/* fall back to one/other */
}
const suffixed = `${key}.${category}`;
const values = { ...params, n };
return i18n.exists(suffixed) ? i18n.t(suffixed, values) : i18n.t(key, values);
}
export default i18n;
+306
View File
@@ -0,0 +1,306 @@
// synced from pi2d/src/protocol/types.ts — do not edit by hand; re-copy when the wire types change.
/**
* pi2 wire protocol — shared types.
*
* Three surfaces, one vocabulary:
* browser <-> daemon (HTTP + WS)
* plugin <-> daemon (JSONL over unix socket)
* daemon <-> plugin (same JSONL envelope, reversed direction)
*
* The plugin is the single source of truth for session state; the daemon only
* routes, the browser only renders.
*/
export const PROTOCOL_VERSION = 1;
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted";
export type ClientKind = "nvim" | "web" | "cli" | "daemon" | "system";
export interface ClientRef {
clientId: string;
kind: ClientKind;
}
export interface ModelRef {
provider: string;
id: string;
}
export interface UsageTotals {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
}
export interface ContextUsage {
tokens: number;
window: number;
percent: number;
}
export interface ToolOutput {
text?: string;
details?: unknown;
isError?: boolean;
}
export type Block =
| { type: "text"; text: string }
| { type: "thinking"; text: string; redacted?: boolean }
| {
type: "tool";
toolCallId: string;
name: string;
args?: unknown;
output?: ToolOutput;
state: "pending" | "running" | "done" | "error";
durationMs?: number;
}
| { type: "error"; text: string };
export type EntryRole = "user" | "assistant" | "system" | "notice";
export interface Entry {
id: string;
role: EntryRole;
ts: number;
blocks: Block[];
done: boolean;
messageId?: string;
images?: { mimeType: string; data: string }[];
}
export interface TodoItem {
content: string;
status: "pending" | "in_progress" | "completed";
activeForm?: string;
}
export interface QueueItem {
id: string;
text: string;
steer: boolean;
}
export interface TaskItem {
id: string;
command: string;
status: "running" | "completed" | "failed" | "stopped";
startTime: number;
durationMs?: number;
exitCode?: number | null;
outputFile?: string;
}
export type BatchItemStatus = "queued" | "spawning" | "running" | "ok" | "failed" | "cancelled";
export interface BatchItem {
ref: string;
name?: string;
status: BatchItemStatus;
error?: string;
}
export interface BatchItemCounts {
total: number;
done: number;
ok: number;
failed: number;
cancelled: number;
running: number;
}
export interface Batch {
batchId: string;
status: "running" | "completed" | "partial" | "failed" | "cancelled";
items: BatchItem[];
summary?: BatchItemCounts;
}
export interface Subagent {
id: string;
name?: string;
status: "active" | "completed" | "failed" | "interrupted" | "dormant";
model?: string;
thinking?: ThinkingLevel;
task?: string;
createdAt?: number;
lastActiveAt?: number;
live?: boolean;
children?: Subagent[];
}
export interface AttentionOption {
id: string;
label: string;
}
export interface AttentionItem {
requestId: string;
method: string;
title?: string;
message?: string;
options?: AttentionOption[];
/** Free-form payload; `diff` requests carry `{files:[{path,before,after}]}`. */
payload?: unknown;
timeoutSec?: number;
createdAt: number;
receivedAt: number;
}
export interface SessionFlags {
attention: boolean;
done: boolean;
error: boolean;
}
export interface SessionState {
sessionId: string;
workspaceId: string;
cwd: string;
name: string | null;
status: SessionStatus;
flags: SessionFlags;
model: ModelRef | null;
thinking: ThinkingLevel | null;
usage: UsageTotals;
contextUsage: ContextUsage | null;
queue: QueueItem[];
todos: TodoItem[];
tasks: TaskItem[];
batches: Batch[];
subagents: Subagent[];
attention: AttentionItem[];
entries: Entry[];
}
/* ------------------------------------------------------------------ */
/* Events */
/* ------------------------------------------------------------------ */
/**
* Pi native events are relayed verbatim (`message_start`, `message_update`,
* `tool_execution_*`, `queue_update`, `agent_*`, `turn_*`, `compaction_*`,
* `session_info_changed`, `thinking_level_changed`, `entry_appended`).
*
* Derived events are prefixed `pi2:` and are computed by the plugin only.
*/
export type SessionEventType =
| "agent_start"
| "agent_end"
| "agent_settled"
| "turn_start"
| "turn_end"
| "message_start"
| "message_update"
| "message_end"
| "tool_execution_start"
| "tool_execution_update"
| "tool_execution_end"
| "queue_update"
| "session_info_changed"
| "thinking_level_changed"
| "entry_appended"
| "compaction_start"
| "compaction_end"
| "pi2:session"
| "pi2:todo"
| "pi2:batch"
| "pi2:task"
| "pi2:subagents"
| "pi2:attention_request"
| "pi2:attention_resolved"
| "pi2:process_exit"
| "pi2:error";
export interface SessionEvent {
type: SessionEventType | string;
ts: number;
[key: string]: unknown;
}
/* ------------------------------------------------------------------ */
/* Envelopes */
/* ------------------------------------------------------------------ */
export interface InstanceState {
workspaceId: string;
instanceId: string;
status: "starting" | "ready" | "degraded" | "stopping" | "stopped" | "unmanaged";
nvimPid: number | null;
pluginVersion: string | null;
hasUI: boolean;
attachedClients: number;
listenAddr: string | null;
startedAt: number | null;
reason?: string;
}
export interface WorkspaceInfo {
workspaceId: string;
cwd: string;
name: string;
alias?: string | null;
pinned?: boolean;
hidden?: boolean;
trusted: boolean;
exists: boolean;
/** Number of session files discovered on disk (header scan). */
sessionCount: number;
/** Number of live sessions reported by the instance, if any. */
liveCount: number;
lastActiveAt: number | null;
instance: InstanceState | null;
}
export type DaemonCommandMethod =
| "instance.ensure"
| "instance.shutdown"
| "workspace.add"
| "workspace.update"
| "workspace.remove"
| "workspace.refresh"
| "pair.create"
| "pair.redeem"
| "device.revoke"
| "session.create"
| "session.open"
| "session.close"
| "session.resume"
| "session.rename"
| "session.fork"
| "session.compact"
| "session.setModel"
| "session.setThinking"
| "session.hibernate"
| "prompt.send"
| "prompt.abort"
| "queue.remove"
| "queue.setSteer"
| "attention.respond"
| "subagent.dispatch"
| "subagent.stop"
| "subagent.steer"
| "subagent.read"
| "task.stop"
| "system.doctor"
| "system.shutdown";
export interface CommandRequest {
method: DaemonCommandMethod | string;
params?: Record<string, unknown>;
sessionId?: string;
clientRequestId?: string;
}
export interface ErrorBody {
code: string;
message: string;
retryable: boolean;
details?: Record<string, unknown>;
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Route guard helpers. `next` is restricted to the three navigation pages
* (plus the /workspace and /chat detail routes) — everything else falls back
* to /workspaces, matching `App.safeNext` in the prototype.
*/
export const NEXT_FALLBACK = "/workspaces";
export const CONNECT_PATH = "/connect";
const EXACT = new Set(["/workspaces", "/status", "/chat"]);
const PREFIXES = ["/chat/", "/workspace/"];
/** Validate and normalize a post-connect return path. */
export function safeNext(path: string | null | undefined, fallback = NEXT_FALLBACK): string {
const fb = isAllowed(fallback) ? fallback : NEXT_FALLBACK;
if (!path) return fb;
let url: URL;
try {
url = new URL(String(path), "http://pi2.local");
} catch {
return fb;
}
if (!isAllowed(url.pathname)) return fb;
return `${url.pathname}${url.search}`;
}
export function isAllowed(pathname: string): boolean {
const normalized = pathname.replace(/\/+$/, "") || "/";
if (EXACT.has(normalized)) return true;
return PREFIXES.some((prefix) => normalized.startsWith(prefix));
}
export function connectHref(next: string): string {
return `${CONNECT_PATH}?next=${encodeURIComponent(safeNext(next))}`;
}
+7
View File
@@ -0,0 +1,7 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/** Merge conditional class names, letting later Tailwind utilities win. */
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
+423
View File
@@ -0,0 +1,423 @@
/**
* Reconnecting WebSocket client for the pi2 daemon.
*
* 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
*
* 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.
*/
export type WsConnectionState = "idle" | "connecting" | "authenticating" | "open" | "reconnecting" | "closed";
export interface WsFrame {
v?: number;
type: string;
id?: string;
workspaceId?: string;
sessionId?: string;
epoch?: string;
seq?: number;
ts?: number;
payload?: Record<string, unknown>;
[key: string]: unknown;
}
export interface WsSnapshotMessage {
sessionId: string;
epoch?: string;
seq: number;
payload: unknown;
}
export interface WsEventMessage {
sessionId: string;
epoch?: string;
seq: number;
payload: unknown;
ts?: number;
}
export interface WsHandlers {
onState?: (state: WsConnectionState) => void;
onHelloAck?: () => void;
onSnapshot?: (snapshot: WsSnapshotMessage) => void;
onEvent?: (event: WsEventMessage) => void;
onResyncRequired?: (frame: WsFrame) => void;
onError?: (error: Error, frame?: WsFrame) => void;
}
/** Minimal surface the client needs; lets tests inject a fake socket. */
export interface WebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
onopen: ((event: unknown) => void) | null;
onmessage: ((event: { data: unknown }) => void) | null;
onclose: ((event: { code?: number; reason?: string }) => void) | null;
onerror: ((event: unknown) => void) | null;
}
export type SocketFactory = (url: string) => WebSocketLike;
export interface PiWsOptions {
url: string;
token?: string | null;
socketFactory?: SocketFactory;
initialBackoffMs?: number;
maxBackoffMs?: number;
backoffMultiplier?: number;
authTimeoutMs?: number;
/** 0 disables the keep-alive ping. */
heartbeatMs?: number;
handlers?: WsHandlers;
}
const AUTH_FRAME_TYPE = "auth";
function defaultFactory(url: string): WebSocketLike {
return new WebSocket(url) as unknown as WebSocketLike;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object";
}
export class PiWsClient {
private readonly url: string;
private readonly socketFactory: SocketFactory;
private readonly initialBackoffMs: number;
private readonly maxBackoffMs: number;
private readonly backoffMultiplier: number;
private readonly authTimeoutMs: number;
private readonly heartbeatMs: number;
private handlers: WsHandlers;
private socket: WebSocketLike | null = null;
private state: WsConnectionState = "idle";
private token: string | null;
private attempt = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private authTimer: ReturnType<typeof setTimeout> | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private manuallyClosed = false;
private readonly subscriptions = new Set<string>();
private readonly lastSeq = new Map<string, number>();
private readonly epochs = new Map<string, string>();
constructor(options: PiWsOptions) {
this.url = options.url;
this.token = options.token ?? null;
this.socketFactory = options.socketFactory ?? defaultFactory;
this.initialBackoffMs = options.initialBackoffMs ?? 200;
this.maxBackoffMs = options.maxBackoffMs ?? 5_000;
this.backoffMultiplier = options.backoffMultiplier ?? 2;
this.authTimeoutMs = options.authTimeoutMs ?? 8_000;
this.heartbeatMs = options.heartbeatMs ?? 25_000;
this.handlers = options.handlers ?? {};
}
getState(): WsConnectionState {
return this.state;
}
getLastSeq(sessionId: string): number | undefined {
return this.lastSeq.get(sessionId);
}
getEpoch(sessionId: string): string | undefined {
return this.epochs.get(sessionId);
}
setHandlers(handlers: WsHandlers): void {
this.handlers = { ...this.handlers, ...handlers };
}
setToken(token: string | null): void {
this.token = token;
}
connect(): void {
if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return;
this.manuallyClosed = false;
this.openSocket();
}
/**
* Stop reconnecting and close the socket. A later `connect()` starts over
* (used by the connection store when the user re-pairs).
*/
close(): void {
this.manuallyClosed = true;
this.clearReconnectTimer();
this.clearAuthTimer();
this.stopHeartbeat();
const socket = this.socket;
this.socket = null;
if (socket) {
socket.onopen = null;
socket.onmessage = null;
socket.onclose = null;
socket.onerror = null;
try {
socket.close(1000, "client closed");
} catch {
/* already closed */
}
}
this.setState("closed");
}
/** Subscribe to one or more sessions; queued until the socket is authenticated. */
subscribe(sessionIds: string | string[]): void {
const ids = Array.isArray(sessionIds) ? sessionIds : [sessionIds];
for (const id of ids) if (id) this.subscriptions.add(id);
if (this.state === "open") this.sendSubscribe(ids.filter(Boolean));
}
unsubscribe(sessionIds: string | string[]): void {
const ids = Array.isArray(sessionIds) ? sessionIds : [sessionIds];
for (const id of ids) {
this.subscriptions.delete(id);
this.lastSeq.delete(id);
this.epochs.delete(id);
}
if (this.state === "open" && ids.length) {
this.send({ v: 1, type: "unsubscribe", payload: { sessionIds: ids } });
}
}
getSubscriptions(): string[] {
return [...this.subscriptions];
}
private setState(next: WsConnectionState): void {
if (this.state === next) return;
this.state = next;
this.handlers.onState?.(next);
}
private openSocket(): void {
this.clearReconnectTimer();
this.setState(this.attempt > 0 ? "reconnecting" : "connecting");
let socket: WebSocketLike;
try {
socket = this.socketFactory(this.url);
} catch (error) {
this.handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
this.scheduleReconnect();
return;
}
this.socket = socket;
socket.onopen = () => {
if (this.socket !== socket) return;
this.setState("authenticating");
this.send({ v: 1, type: AUTH_FRAME_TYPE, payload: { token: this.token ?? undefined } });
this.authTimer = setTimeout(() => {
if (this.state !== "authenticating" || this.socket !== socket) return;
this.handlers.onError?.(new Error("WebSocket auth timed out"));
this.dropSocket(socket);
this.scheduleReconnect();
}, this.authTimeoutMs);
};
socket.onmessage = (event) => {
if (this.socket !== socket) return;
this.handleMessage(event.data);
};
socket.onerror = () => {
this.handlers.onError?.(new Error("WebSocket transport error"));
};
socket.onclose = (event) => {
if (this.socket !== socket) return;
this.socket = null;
this.clearAuthTimer();
this.stopHeartbeat();
if (this.manuallyClosed) {
this.setState("closed");
return;
}
this.handlers.onError?.(new Error(`WebSocket closed (${event.code ?? 1006})`));
this.scheduleReconnect();
};
}
private dropSocket(socket: WebSocketLike): void {
if (this.socket === socket) this.socket = null;
socket.onopen = null;
socket.onmessage = null;
socket.onclose = null;
socket.onerror = null;
try {
socket.close(4000, "client reset");
} catch {
/* already closed */
}
}
private scheduleReconnect(): void {
this.clearReconnectTimer();
this.setState("reconnecting");
const delay = Math.min(this.initialBackoffMs * this.backoffMultiplier ** this.attempt, this.maxBackoffMs);
this.attempt += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.openSocket();
}, delay);
}
private clearReconnectTimer(): void {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
private clearAuthTimer(): void {
if (this.authTimer) {
clearTimeout(this.authTimer);
this.authTimer = null;
}
}
private startHeartbeat(): void {
this.stopHeartbeat();
if (this.heartbeatMs <= 0) return;
this.heartbeatTimer = setInterval(() => {
if (this.state === "open") this.send({ v: 1, type: "ping" });
}, this.heartbeatMs);
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
private send(frame: WsFrame): boolean {
if (!this.socket) return false;
try {
this.socket.send(JSON.stringify(frame));
return true;
} catch (error) {
this.handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
return false;
}
}
private sendSubscribe(sessionIds: string[]): void {
if (!sessionIds.length) return;
const sinceSeq: Record<string, number> = {};
for (const id of sessionIds) {
const seq = this.lastSeq.get(id);
if (seq !== undefined) sinceSeq[id] = seq;
}
this.send({
v: 1,
type: "subscribe",
payload: {
sessionIds,
...(Object.keys(sinceSeq).length ? { sinceSeq } : {}),
},
});
}
private flushSubscriptions(): void {
if (this.subscriptions.size) this.sendSubscribe([...this.subscriptions]);
}
private handleMessage(raw: unknown): void {
let frame: WsFrame;
try {
const parsed: unknown = typeof raw === "string" ? JSON.parse(raw) : raw;
if (!isRecord(parsed) || typeof parsed.type !== "string") return;
frame = parsed as WsFrame;
} catch {
return;
}
switch (frame.type) {
case "hello_ack": {
this.clearAuthTimer();
this.attempt = 0;
this.setState("open");
this.startHeartbeat();
this.handlers.onHelloAck?.();
this.flushSubscriptions();
break;
}
case "snapshot": {
const sessionId = String(frame.sessionId ?? "");
if (!sessionId) return;
const seq = Number(frame.seq ?? 0);
if (frame.epoch) this.epochs.set(sessionId, String(frame.epoch));
this.lastSeq.set(sessionId, seq);
this.handlers.onSnapshot?.({
sessionId,
epoch: frame.epoch ? String(frame.epoch) : undefined,
seq,
payload: frame.payload,
});
break;
}
case "event": {
const sessionId = String(frame.sessionId ?? "");
if (!sessionId) return;
const seq = Number(frame.seq ?? 0);
const previous = this.lastSeq.get(sessionId);
if (previous !== undefined && Number.isFinite(seq) && seq <= previous) return;
if (Number.isFinite(seq)) this.lastSeq.set(sessionId, seq);
if (frame.epoch) this.epochs.set(sessionId, String(frame.epoch));
this.handlers.onEvent?.({
sessionId,
epoch: frame.epoch ? String(frame.epoch) : undefined,
seq,
payload: frame.payload,
ts: typeof frame.ts === "number" ? frame.ts : undefined,
});
break;
}
case "resync_required": {
const sessionId = String(frame.sessionId ?? "");
if (sessionId) {
this.lastSeq.delete(sessionId);
this.epochs.delete(sessionId);
}
this.handlers.onResyncRequired?.(frame);
break;
}
case "error": {
const payload = isRecord(frame.payload) ? frame.payload : {};
const code = String(payload.code ?? "E_UNKNOWN");
const message = String(payload.message ?? code);
this.handlers.onError?.(Object.assign(new Error(message), { code, frame }), frame);
if (code === "E_UNAUTHORIZED" || code === "E_PROTOCOL_VERSION") {
this.manuallyClosed = true;
this.clearReconnectTimer();
this.close();
}
break;
}
case "pong":
case "presence":
case "dropped":
break;
default:
break;
}
}
}
/** Build the default WS URL for the current origin (vite.config proxies /ws to the daemon). */
export function defaultWsUrl(path = "/ws"): string {
if (typeof window === "undefined") return path;
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${window.location.host}${path}`;
}