From de3bb4817d3093c3ce7ec17408351bc78b06d9d6 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 24 Jun 2026 21:51:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(webui):=20subscribe=20to=20/api/state/stre?= =?UTF-8?q?am=20=E2=80=94=20push-driven=20dashboard=20state?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 4 of the SSE migration. The dashboard's three live resources now update the moment the backend sees a change instead of within 0-3000ms of the next polling tick. - New api.stateStream({ onEvent, onStatus }) in lib/api/client.ts mirrors the existing openLogStream / openDebugStream EventSource pattern: token in the query string (EventSource can't set headers), single onerror → 'reconnecting' status, source.close() on dispose, JSON.parse with skip- malformed isolation. Browser-native EventSource auto-reconnect covers transport drops with no manual retry timer. - StateStreamEvent union covers the three resource frames plus the two control frames ('ready' on connect, 'dropped' on backpressure). The resource frames carry typed HookProcessInfo[] / QQInfo[] / AccountConnections[] payloads. - AppLayout now subscribes on mount, applies pushed snapshots to the same setProcessList / setQqList / setConnections React state slots the polling tick used to drive. The REST polling tick is RETAINED but slowed to max(pollInterval × 10, 10s) (default 3s → 30s) so it acts as a silent- drop reconcile rather than the primary update path. systemInfo isn't on the SSE feed — it stays on the slow REST loop. Resolves the two reported bugs: 1. new QQ.exe not showing in WebUI until manual refresh → process- discovered now publishes 'processes' through the StateBus → frame arrives within 50ms. 2. injection panel stuck at "waiting for connection" after a successful hook (group messages arriving) → HookSession 'status-changed' now publishes 'processes' → 'online' status frame arrives within 50ms. WebUI typecheck clean. No unit tests in packages/webui (consistent with the existing openLogStream/openDebugStream which also have no client tests). --- packages/webui/src/lib/api/client.ts | 22 +++++++++++++++++ packages/webui/src/lib/api/types.ts | 21 ++++++++++++++++ packages/webui/src/router/app-layout.tsx | 31 +++++++++++++++++++++++- 3 files changed, 73 insertions(+), 1 deletion(-) 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);