415 lines
15 KiB
TypeScript
415 lines
15 KiB
TypeScript
"use client";
|
||
// One live channel per tab (PEP-225): a single WebSocket to /api/ws carries every scope the page
|
||
// watches — page changes, the attention counter, the boot id, agent steps, the terminal. Scopes
|
||
// are reference-counted; after a drop the client reconnects with a growing pause and subscribes
|
||
// again with the last version it saw (`since`), so missed changes arrive at once. If the
|
||
// WebSocket never opens (a proxy cuts it), the fallback is the SSE of /api/live and of the
|
||
// terminal, and the WebSocket is tried again every minute. No data is polled on a timer: the
|
||
// only timer is the connection check (ping every 15 s).
|
||
import { useEffect, useRef, useSyncExternalStore } from "react";
|
||
import { m } from "@peppa/shared/i18n";
|
||
|
||
/** Shown through t.text by the terminal. */
|
||
const NO_LINK = m("Нет связи с Peppa FACTORY");
|
||
|
||
export interface LiveTaskRow {
|
||
id: number;
|
||
status: string;
|
||
title: string;
|
||
column: "backlog" | "in_progress" | "review" | "done";
|
||
other?: boolean;
|
||
}
|
||
export type LiveEvent =
|
||
/** `messages` — new messages of a `chat:` scope, ready for this viewer (PEP-228, lib/chat-live-types.ts). */
|
||
| { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
|
||
| { type: "step"; scope: string; step: { id: number } & Record<string, unknown> }
|
||
| { type: "data"; scope: string; v: string; data: unknown }
|
||
| { type: "frame"; scope: string; cols: number; rows: number; data: string }
|
||
| { type: "out"; scope: string; data: string }
|
||
| { type: "end"; scope: string }
|
||
/** The subscription was refused (no access, unknown scope). */
|
||
| { type: "error"; scope: string; status: number; error: string };
|
||
export type LiveHandler = (e: LiveEvent) => void;
|
||
export type LiveMode = "connecting" | "live" | "reconnecting" | "offline";
|
||
|
||
const PING_MS = 15_000;
|
||
const PONG_WAIT_MS = 10_000;
|
||
const BACKOFF_MAX_MS = 30_000;
|
||
const WS_RETRY_FROM_SSE_MS = 60_000;
|
||
/** WebSocket attempts that never opened before the SSE fallback. */
|
||
const WS_FAILS_TO_SSE = 3;
|
||
|
||
interface Sub {
|
||
handlers: Set<LiveHandler>;
|
||
/** Handlers that want the scope only while the tab is visible. */
|
||
heavy: number;
|
||
v?: string;
|
||
lastStep?: number;
|
||
active: boolean;
|
||
}
|
||
|
||
class LiveClient {
|
||
private subs = new Map<string, Sub>();
|
||
private ws: WebSocket | null = null;
|
||
private transport: "ws" | "sse" = "ws";
|
||
private everOpened = false;
|
||
private failsBeforeOpen = 0;
|
||
private attempt = 0;
|
||
private retry: ReturnType<typeof setTimeout> | null = null;
|
||
private pinger: ReturnType<typeof setInterval> | null = null;
|
||
private pongTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private es: EventSource | null = null;
|
||
private esScopes = "";
|
||
private esTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private terms = new Map<string, EventSource>();
|
||
private wsProbe: ReturnType<typeof setTimeout> | null = null;
|
||
private acks = new Map<number, (error: string | null) => void>();
|
||
private nextAck = 1;
|
||
private modeListeners = new Set<() => void>();
|
||
mode: LiveMode = "connecting";
|
||
/** Boot id the server greeted the tab with. */
|
||
boot: string | null = null;
|
||
|
||
constructor() {
|
||
document.addEventListener("visibilitychange", () => this.onVisibility());
|
||
window.addEventListener("online", () => this.reconnectNow());
|
||
}
|
||
|
||
private setMode(m: LiveMode) {
|
||
if (this.mode === m) return;
|
||
this.mode = m;
|
||
for (const fn of this.modeListeners) fn();
|
||
}
|
||
|
||
onMode(fn: () => void): () => void {
|
||
this.modeListeners.add(fn);
|
||
return () => this.modeListeners.delete(fn);
|
||
}
|
||
|
||
/** Watches `scope`; `heavy` scopes are dropped while the tab is hidden. */
|
||
subscribe(scope: string, handler: LiveHandler, opts: { heavy?: boolean } = {}): () => void {
|
||
let sub = this.subs.get(scope);
|
||
if (!sub) this.subs.set(scope, (sub = { handlers: new Set(), heavy: 0, active: false }));
|
||
sub.handlers.add(handler);
|
||
if (opts.heavy) sub.heavy++;
|
||
this.ensure();
|
||
this.activate(scope);
|
||
return () => {
|
||
const s = this.subs.get(scope);
|
||
if (!s) return;
|
||
s.handlers.delete(handler);
|
||
if (opts.heavy) s.heavy--;
|
||
if (!s.handlers.size) {
|
||
this.deactivate(scope);
|
||
this.subs.delete(scope);
|
||
this.syncSse();
|
||
}
|
||
};
|
||
}
|
||
|
||
/** Keyboard input / paste of a terminal; resolves to an error text or null. */
|
||
input(scope: string, body: { keys?: string; paste?: string }): Promise<string | null> {
|
||
if (this.transport === "ws" && this.ws?.readyState === WebSocket.OPEN) {
|
||
const id = this.nextAck++;
|
||
return new Promise((resolve) => {
|
||
this.acks.set(id, resolve);
|
||
this.ws!.send(JSON.stringify({ t: "in", scope, id, ...body }));
|
||
});
|
||
}
|
||
const runner = scope.slice("terminal:".length);
|
||
return fetch(`/api/runners/${runner}/terminal`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
|
||
.then(async (r) => (r.ok ? null : (((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? `HTTP ${r.status}`)))
|
||
.catch(() => NO_LINK);
|
||
}
|
||
|
||
private wanted(sub: Sub): boolean {
|
||
return sub.handlers.size > 0 && !(document.visibilityState === "hidden" && sub.heavy > 0 && sub.heavy === sub.handlers.size);
|
||
}
|
||
|
||
private activate(scope: string) {
|
||
const sub = this.subs.get(scope);
|
||
if (!sub || sub.active || !this.wanted(sub)) return;
|
||
sub.active = true;
|
||
if (this.transport === "ws") {
|
||
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "sub", scope, since: scope.startsWith("steps:") ? sub.lastStep : sub.v }));
|
||
} else this.syncSse();
|
||
}
|
||
|
||
private deactivate(scope: string) {
|
||
const sub = this.subs.get(scope);
|
||
if (!sub?.active) return;
|
||
sub.active = false;
|
||
if (this.transport === "ws") {
|
||
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "unsub", scope }));
|
||
} else {
|
||
this.terms.get(scope)?.close();
|
||
this.terms.delete(scope);
|
||
this.syncSse();
|
||
}
|
||
}
|
||
|
||
private onVisibility() {
|
||
for (const [scope, sub] of this.subs) {
|
||
if (this.wanted(sub)) this.activate(scope);
|
||
else this.deactivate(scope);
|
||
}
|
||
if (document.visibilityState === "visible" && this.mode !== "live") this.reconnectNow();
|
||
}
|
||
|
||
private dispatch(e: LiveEvent) {
|
||
const sub = this.subs.get(e.scope);
|
||
if (!sub) return;
|
||
if ("v" in e && e.v) sub.v = e.v;
|
||
if (e.type === "step") sub.lastStep = Math.max(sub.lastStep ?? 0, Number(e.step.id) || 0);
|
||
for (const fn of [...sub.handlers]) {
|
||
try {
|
||
fn(e);
|
||
} catch (err) {
|
||
console.error("live:", err);
|
||
}
|
||
}
|
||
}
|
||
|
||
private ensure() {
|
||
if (this.ws || this.es || this.retry || this.transport === "sse") return;
|
||
this.connectWs();
|
||
}
|
||
|
||
private reconnectNow() {
|
||
if (this.transport === "sse" || this.ws) return;
|
||
if (this.retry) clearTimeout(this.retry);
|
||
this.retry = null;
|
||
this.connectWs();
|
||
}
|
||
|
||
private connectWs() {
|
||
if (typeof WebSocket === "undefined") return this.toSse();
|
||
let opened = false;
|
||
let ws: WebSocket;
|
||
try {
|
||
ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/ws`);
|
||
} catch {
|
||
return this.toSse();
|
||
}
|
||
this.ws = ws;
|
||
if (this.transport === "ws") this.setMode(this.everOpened ? "reconnecting" : "connecting");
|
||
ws.onopen = () => {
|
||
opened = true;
|
||
this.everOpened = true;
|
||
this.failsBeforeOpen = 0;
|
||
this.attempt = 0;
|
||
if (this.transport === "sse") this.leaveSse();
|
||
this.setMode("live");
|
||
for (const sub of this.subs.values()) sub.active = false;
|
||
for (const scope of this.subs.keys()) this.activate(scope);
|
||
this.startPing();
|
||
};
|
||
ws.onmessage = (msg) => {
|
||
let m: { t: string; scope?: string; type?: string; status?: number; error?: string; id?: number; boot?: string; v?: string };
|
||
try {
|
||
m = JSON.parse(String(msg.data));
|
||
} catch {
|
||
return;
|
||
}
|
||
if (m.t === "pong") {
|
||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||
this.pongTimer = null;
|
||
} else if (m.t === "hello") this.boot = m.boot ?? null;
|
||
else if (m.t === "ev") this.dispatch(m as unknown as LiveEvent);
|
||
else if (m.t === "ok" && m.scope && m.v) {
|
||
const sub = this.subs.get(m.scope);
|
||
if (sub && !sub.v) sub.v = m.v;
|
||
} else if (m.t === "err" && m.scope) {
|
||
const sub = this.subs.get(m.scope);
|
||
if (sub) sub.active = false;
|
||
this.dispatch({ type: "error", scope: m.scope, status: m.status ?? 500, error: m.error ?? "" });
|
||
} else if (m.t === "ack" && typeof m.id === "number") {
|
||
this.acks.get(m.id)?.(m.error ?? null);
|
||
this.acks.delete(m.id);
|
||
}
|
||
};
|
||
ws.onclose = () => {
|
||
if (this.ws !== ws) return;
|
||
this.ws = null;
|
||
this.stopPing();
|
||
for (const [id, done] of this.acks) {
|
||
done(NO_LINK);
|
||
this.acks.delete(id);
|
||
}
|
||
for (const sub of this.subs.values()) sub.active = false;
|
||
if (this.transport === "sse") return; // a failed probe from the fallback
|
||
if (!opened && !this.everOpened && ++this.failsBeforeOpen >= WS_FAILS_TO_SSE) return this.toSse();
|
||
this.scheduleReconnect();
|
||
};
|
||
}
|
||
|
||
private scheduleReconnect() {
|
||
if (!this.subs.size) return; // nothing to watch: reconnect on the next subscribe
|
||
this.setMode(this.attempt > 2 ? "offline" : "reconnecting");
|
||
const pause = Math.min(BACKOFF_MAX_MS, 1000 * 2 ** this.attempt++) * (0.75 + Math.random() * 0.5);
|
||
this.retry = setTimeout(() => {
|
||
this.retry = null;
|
||
this.connectWs();
|
||
}, pause);
|
||
}
|
||
|
||
/** Connection check — the one timer of the channel. */
|
||
private startPing() {
|
||
this.stopPing();
|
||
this.pinger = setInterval(() => {
|
||
const ws = this.ws;
|
||
if (ws?.readyState !== WebSocket.OPEN || this.pongTimer) return;
|
||
ws.send(JSON.stringify({ t: "ping" }));
|
||
this.pongTimer = setTimeout(() => {
|
||
this.pongTimer = null;
|
||
ws.close();
|
||
}, PONG_WAIT_MS);
|
||
}, PING_MS);
|
||
}
|
||
|
||
private stopPing() {
|
||
if (this.pinger) clearInterval(this.pinger);
|
||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||
this.pinger = this.pongTimer = null;
|
||
}
|
||
|
||
// ---- SSE fallback ----
|
||
|
||
private toSse() {
|
||
this.transport = "sse";
|
||
this.ws = null;
|
||
for (const sub of this.subs.values()) sub.active = false;
|
||
for (const scope of this.subs.keys()) this.activate(scope);
|
||
this.syncSse();
|
||
// Try the WebSocket again now and then (the proxy may let it through later).
|
||
const probe = () => {
|
||
this.wsProbe = null;
|
||
if (this.transport !== "sse") return;
|
||
if (!this.ws) this.connectWs();
|
||
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
|
||
};
|
||
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
|
||
}
|
||
|
||
private leaveSse() {
|
||
this.transport = "ws";
|
||
this.es?.close();
|
||
this.es = null;
|
||
this.esScopes = "";
|
||
for (const es of this.terms.values()) es.close();
|
||
this.terms.clear();
|
||
if (this.wsProbe) clearTimeout(this.wsProbe);
|
||
this.wsProbe = null;
|
||
}
|
||
|
||
/** One EventSource for every hub scope (reopened when the set changes), one per terminal. */
|
||
private syncSse() {
|
||
if (this.transport !== "sse") return;
|
||
if (this.esTimer) return;
|
||
this.esTimer = setTimeout(() => {
|
||
this.esTimer = null;
|
||
if (this.transport !== "sse") return;
|
||
const active = [...this.subs].filter(([, s]) => s.active);
|
||
for (const [scope] of active.filter(([s]) => s.startsWith("terminal:"))) if (!this.terms.has(scope)) this.openTerminalSse(scope);
|
||
const hub = active.filter(([s]) => !s.startsWith("terminal:")).map(([s]) => s).sort();
|
||
const key = hub.join(",");
|
||
if (key === this.esScopes && this.es) return;
|
||
this.es?.close();
|
||
this.es = null;
|
||
this.esScopes = key;
|
||
if (!hub.length) return;
|
||
if (typeof EventSource === "undefined") return this.setMode("offline");
|
||
const q = new URLSearchParams({ scope: key });
|
||
for (const s of hub) {
|
||
const sub = this.subs.get(s)!;
|
||
const since = s.startsWith("steps:") ? sub.lastStep : sub.v;
|
||
if (since) q.set(`since.${s}`, String(since));
|
||
}
|
||
const es = new EventSource(`/api/live?${q}`);
|
||
this.es = es;
|
||
let fails = 0;
|
||
es.addEventListener("ready", () => {
|
||
fails = 0;
|
||
this.setMode("live");
|
||
});
|
||
for (const type of ["change", "step", "data"]) es.addEventListener(type, (e) => this.dispatch(JSON.parse((e as MessageEvent<string>).data) as LiveEvent));
|
||
es.onerror = () => {
|
||
// EventSource reconnects by itself (retry: 3000); after a few failures say so.
|
||
this.setMode(++fails >= 3 ? "offline" : "reconnecting");
|
||
};
|
||
}, 50);
|
||
}
|
||
|
||
private openTerminalSse(scope: string) {
|
||
const es = new EventSource(`/api/runners/${scope.slice("terminal:".length)}/terminal`);
|
||
this.terms.set(scope, es);
|
||
for (const type of ["frame", "out"]) es.addEventListener(type, (e) => this.dispatch({ type, scope, ...JSON.parse((e as MessageEvent<string>).data) } as LiveEvent));
|
||
es.addEventListener("end", () => {
|
||
es.close();
|
||
this.terms.delete(scope);
|
||
this.dispatch({ type: "end", scope });
|
||
});
|
||
es.onerror = () => {
|
||
if (es.readyState === EventSource.CLOSED) this.dispatch({ type: "error", scope, status: 404, error: "" });
|
||
};
|
||
}
|
||
}
|
||
|
||
const g = globalThis as { __peppaLive?: LiveClient };
|
||
/** The tab's channel (created on first use in the browser). */
|
||
export function liveClient(): LiveClient {
|
||
return (g.__peppaLive ??= new LiveClient());
|
||
}
|
||
|
||
/** Calls `handler` with every event of `scope` (null — nothing). The latest handler is used without resubscribing. */
|
||
export function useLive(scope: string | null, handler: LiveHandler, opts: { heavy?: boolean } = {}): void {
|
||
const ref = useRef(handler);
|
||
ref.current = handler;
|
||
const heavy = !!opts.heavy;
|
||
useEffect(() => {
|
||
if (!scope) return;
|
||
return liveClient().subscribe(scope, (e) => ref.current(e), { heavy });
|
||
}, [scope, heavy]);
|
||
}
|
||
|
||
/** The connection state for the indicator. */
|
||
export function useLiveMode(): LiveMode {
|
||
return useSyncExternalStore(
|
||
(fn) => liveClient().onMode(fn),
|
||
() => liveClient().mode,
|
||
() => "connecting",
|
||
);
|
||
}
|
||
|
||
// ---- Islands (PEP-225): parts of a page that apply an event in place ----
|
||
|
||
/** Applies a `change` in place; returns the parts it fully applied (they need no server re-render). */
|
||
export type Island = (e: Extract<LiveEvent, { type: "change" }>) => string[];
|
||
const islands = new Set<Island>();
|
||
|
||
/** Registers an island for the page's `change` events (LiveRefresh asks them before re-rendering). */
|
||
export function useLiveIsland(island: Island): void {
|
||
const ref = useRef(island);
|
||
ref.current = island;
|
||
useEffect(() => {
|
||
const fn: Island = (e) => ref.current(e);
|
||
islands.add(fn);
|
||
return () => {
|
||
islands.delete(fn);
|
||
};
|
||
}, []);
|
||
}
|
||
|
||
/** Parts of `e` the page's islands applied. */
|
||
export function applyIslands(e: Extract<LiveEvent, { type: "change" }>): Set<string> {
|
||
const done = new Set<string>();
|
||
for (const fn of islands) {
|
||
try {
|
||
for (const p of fn(e)) done.add(p);
|
||
} catch (err) {
|
||
console.error("live island:", err);
|
||
}
|
||
}
|
||
return done;
|
||
}
|