diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 8c7c5965..e2d919c4 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -10,6 +10,8 @@ import { type LoginResult, type LogsStreamOptions, type ProcessActionResult, + type StateStreamEvent, + type StateStreamOptions, type TokenStore, } from './types'; import { localStorageTokenStore } from './token-store'; @@ -344,6 +346,26 @@ class HttpApiClient implements ApiClient { return this.getJson<{ list: AccountConnections[] }>('/api/connections').then((d) => d.list ?? []); } + stateStream(options: StateStreamOptions): () => void { + if (!this.currentToken) { options.onStatus?.('closed'); return () => {}; } + const url = `/api/state/stream?token=${encodeURIComponent(this.currentToken)}`; + const source = new EventSource(url); + // EventSource auto-reconnects on transport drop: `onerror` fires once + // when the connection is lost and the browser is about to retry, so + // a single 'reconnecting' status is sufficient — no manual reconnect + // timer needed. + source.onopen = () => options.onStatus?.('open'); + source.onerror = () => options.onStatus?.('reconnecting'); + source.onmessage = (event) => { + try { + options.onEvent(JSON.parse(event.data) as StateStreamEvent); + } catch { + /* malformed frame — skip; the next one will arrive normally */ + } + }; + return () => { source.close(); options.onStatus?.('closed'); }; + } + // ---------- SSE ---------- private openLogStream(options: LogsStreamOptions): () => void { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index aa7d22fb..51dd22ae 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -73,6 +73,20 @@ export interface LogsStreamOptions { onStatus?: (status: StreamStatus) => void; } +/** A single frame from /api/state/stream — either a control frame or a + * fresh snapshot for one of the three live dashboard resources. */ +export type StateStreamEvent = + | { kind: 'ready' } + | { kind: 'dropped'; count: number } + | { resource: 'processes'; data: HookProcessInfo[] } + | { resource: 'qq-list'; data: QQInfo[] } + | { resource: 'connections'; data: AccountConnections[] }; + +export interface StateStreamOptions { + onEvent: (event: StateStreamEvent) => void; + onStatus?: (status: StreamStatus) => void; +} + export interface ApiClient { // ---- auth ---- login(password: string): Promise; @@ -98,6 +112,13 @@ export interface ApiClient { /** Live OneBot adapter health per account. */ connections(): Promise; + /** Subscribe to the unified SSE feed pushing fresh snapshots whenever + * processes / qq-list / connections change. Initial frames on connect + * give the current snapshot for all three resources. Returns a disposer. + * REST endpoints above remain for the pre-SSE first paint and the slow + * reconcile fallback if the SSE drops. */ + stateStream(options: StateStreamOptions): () => void; + // ---- hook processes ---- processes: { list(): Promise; diff --git a/packages/webui/src/router/app-layout.tsx b/packages/webui/src/router/app-layout.tsx index f90cdba2..777b451b 100644 --- a/packages/webui/src/router/app-layout.tsx +++ b/packages/webui/src/router/app-layout.tsx @@ -104,15 +104,44 @@ export function AppLayout() { onAfterOp: refreshProcesses, }); + // Primary live-state path: subscribe to /api/state/stream and apply + // pushed snapshots directly. Initial frames on connect prime + // processes/qqList/connections without a polling tick. systemInfo isn't + // covered by the SSE feed (it changes on a daily cadence — kernel/ + // distro details) so it stays REST-driven below. + useEffect(() => { + const dispose = api.stateStream({ + onEvent: (event) => { + if ('resource' in event) { + if (event.resource === 'processes') setProcessList(event.data); + else if (event.resource === 'qq-list') setQqList(event.data); + else if (event.resource === 'connections') setConnections(event.data); + } + // 'ready' / 'dropped' control frames intentionally ignored — a + // 'dropped' just means the SSE skipped some intermediate frames + // under backpressure; the NEXT delivered frame is a full snapshot + // so the UI auto-recovers. + }, + }); + return () => { dispose(); }; + }, [api]); + + // Fallback reconcile loop: even with the SSE primary, fire a single + // REST tick every `pollInterval` × 10 (so the default 3s → 30s) just to + // recover from a silent SSE drop (proxy rewrites text/event-stream, + // browser tab thrashing, etc.). systemInfo refreshes here too. useEffect(() => { if (pollInterval <= 0) return; let cancelled = false; + const reconcileMs = Math.max(pollInterval * 10, 10_000); const tick = async () => { if (cancelled) return; await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem(), refreshConnections()]); }; + // Initial tick so the four lists exist before the SSE handshake + // completes (avoids a flash of empty state in the chrome). tick(); - const interval = setInterval(tick, pollInterval); + const interval = setInterval(tick, reconcileMs); return () => { cancelled = true; clearInterval(interval);