feat(webui): subscribe to /api/state/stream — push-driven dashboard state

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).
This commit is contained in:
DrSmoothl committed 2026-06-24 21:51:35 +08:00
1 parent a7522deb82
commit de3bb4817d
3 files changed
+73 -1

No files matched your search

+22
View File
@@ -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 {
+21
View File
@@ -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<LoginResult>;
@@ -98,6 +112,13 @@ export interface ApiClient {
/** Live OneBot adapter health per account. */
connections(): Promise<AccountConnections[]>;
/** 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<HookProcessInfo[]>;
+30 -1
View File
@@ -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);