diff --git a/packages/core/src/webui/connection-diff-loop.ts b/packages/core/src/webui/connection-diff-loop.ts new file mode 100644 index 00000000..cb911ea4 --- /dev/null +++ b/packages/core/src/webui/connection-diff-loop.ts @@ -0,0 +1,70 @@ +/** + * Connection-status diff loop. OneBot adapters don't have an internal + * event-emitter for connection state (listening / connected / client-count + * changes), so this loop polls `getConnectionStatuses()` and publishes + * `connections` to the StateBus when the JSON-serialised snapshot changes + * vs the previous tick. + * + * Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only + * fires the StateBus when state actually moves — so the SSE handler only + * pushes a fresh `connections` frame when the user would actually see + * something update. + */ + +import type { StateBus } from './state-bus'; + +export interface ConnectionDiffLoopOptions { + bus: StateBus; + /** Read the current adapter-status snapshot for every live UIN. */ + getSnapshot: () => unknown; + /** Poll cadence in milliseconds; default 500. */ + intervalMs?: number; +} + +export interface ConnectionDiffLoopHandle { + /** Stop the loop. Subsequent snapshot mutations produce nothing. */ + dispose(): void; +} + +export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle { + const intervalMs = opts.intervalMs ?? 500; + let lastSerialized = ''; + let haveBaseline = false; + let disposed = false; + + const tick = (): void => { + if (disposed) return; + let snap: unknown; + try { + snap = opts.getSnapshot(); + } catch { + // Snapshot read failed (e.g. mid-shutdown). Skip this tick; the + // next one will retry. Don't reset the baseline so we don't + // spuriously republish when the snapshot starts working again. + return; + } + const serialized = JSON.stringify(snap); + if (!haveBaseline) { + // First successful observation. The SSE handler's sendAllInitial + // already shipped a `connections` frame to every connected client + // on connect, so the baseline is what they already have — emitting + // it again would be a duplicate. Just store it. + lastSerialized = serialized; + haveBaseline = true; + return; + } + if (serialized === lastSerialized) return; + lastSerialized = serialized; + opts.bus.publish('connections'); + }; + + const timer = setInterval(tick, intervalMs); + + return { + dispose(): void { + if (disposed) return; + disposed = true; + clearInterval(timer); + }, + }; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index b92fc764..df79acef 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -23,6 +23,7 @@ import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-do import { createFramePusher } from './debug-stream'; import { bindStateStream } from './state-stream'; import type { StateBus, StateResource } from './state-bus'; +import { startConnectionDiffLoop } from './connection-diff-loop'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -324,6 +325,18 @@ export async function initWebUI( const trustProxyMode = parseTrustProxy(listener.trustProxy); const getClientIp = makeClientIpResolver(trustProxyMode); + // Connection-status diff loop: OneBot adapters don't emit events for + // listening/connected/client-count changes, so we poll the snapshot at + // 500ms and publish 'connections' to the StateBus when it actually + // moves. One loop per server lifetime, lives until process exit. + if (listener.stateBus) { + startConnectionDiffLoop({ + bus: listener.stateBus, + getSnapshot: () => oneBotManager.getConnectionStatuses(), + intervalMs: 500, + }); + } + // Actual bound port (set just before serve; findAvailablePort may bump it). // Read by GET /api/system/settings so the panel shows what's really live. let boundPort = desiredPort; diff --git a/packages/core/tests/webui-connection-diff-loop.test.ts b/packages/core/tests/webui-connection-diff-loop.test.ts new file mode 100644 index 00000000..7a56614d --- /dev/null +++ b/packages/core/tests/webui-connection-diff-loop.test.ts @@ -0,0 +1,111 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { StateBus } from '../src/webui/state-bus'; +import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop'; + +describe('startConnectionDiffLoop', () => { + beforeEach(() => { vi.useFakeTimers(); }); + afterEach(() => { vi.useRealTimers(); }); + + it('does NOT publish when the snapshot is stable tick after tick', () => { + const bus = new StateBus(); + const seen: string[] = []; + bus.subscribe((r) => seen.push(r)); + const handle = startConnectionDiffLoop({ + bus, + getSnapshot: () => [{ uin: '12345', nickname: 'me', adapters: [] }], + intervalMs: 500, + }); + + vi.advanceTimersByTime(2_000); // 4 ticks + expect(seen).toEqual([]); + handle.dispose(); + }); + + it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => { + const bus = new StateBus(); + const seen: string[] = []; + bus.subscribe((r) => seen.push(r)); + let snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'listening' }] }]; + const handle = startConnectionDiffLoop({ + bus, + getSnapshot: () => snap, + intervalMs: 500, + }); + vi.advanceTimersByTime(500); // first observation — baseline, no publish + expect(seen).toEqual([]); + snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'connected' }] }]; + vi.advanceTimersByTime(500); + expect(seen).toEqual(['connections']); + // Next tick: stable again → no extra publish. + vi.advanceTimersByTime(500); + expect(seen).toEqual(['connections']); + handle.dispose(); + }); + + it('publishes once per CHANGE, not once per tick the snapshot differs from initial', () => { + const bus = new StateBus(); + const seen: string[] = []; + bus.subscribe((r) => seen.push(r)); + const versions = [ + [{ uin: '1', nickname: 'a', adapters: [] }], // baseline (no publish on first observation) + [{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }], + [{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }], + [{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'connected' }] }], + ]; + let i = 0; + const handle = startConnectionDiffLoop({ + bus, + getSnapshot: () => versions[Math.min(i, versions.length - 1)] ?? [], + intervalMs: 500, + }); + + vi.advanceTimersByTime(500); // i=0 baseline + i = 1; vi.advanceTimersByTime(500); // change #1 + i = 2; vi.advanceTimersByTime(500); // stable vs i=1 + i = 3; vi.advanceTimersByTime(500); // change #2 + + expect(seen).toEqual(['connections', 'connections']); + handle.dispose(); + }); + + it('dispose() stops further ticks, no publish even after a change', () => { + const bus = new StateBus(); + const seen: string[] = []; + bus.subscribe((r) => seen.push(r)); + let snap: object[] = []; + const handle = startConnectionDiffLoop({ + bus, + getSnapshot: () => snap, + intervalMs: 500, + }); + handle.dispose(); + snap = [{ uin: '1', nickname: 'a', adapters: [] }]; + vi.advanceTimersByTime(5_000); + expect(seen).toEqual([]); + }); + + it('survives a throwing snapshot() — keeps trying on the next tick', () => { + const bus = new StateBus(); + const seen: string[] = []; + bus.subscribe((r) => seen.push(r)); + let mode: 'throw' | 'stable' | 'changed' = 'throw'; + const handle = startConnectionDiffLoop({ + bus, + getSnapshot: () => { + if (mode === 'throw') throw new Error('getConnectionStatuses failed'); + if (mode === 'stable') return [{ uin: '1', adapters: [] }]; + return [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }]; + }, + intervalMs: 500, + }); + vi.advanceTimersByTime(500); // throws — skipped, no publish + expect(seen).toEqual([]); + mode = 'stable'; + vi.advanceTimersByTime(500); // first SUCCESSFUL read — baseline, no publish + expect(seen).toEqual([]); + mode = 'changed'; + vi.advanceTimersByTime(500); // real change → publish + expect(seen).toEqual(['connections']); + handle.dispose(); + }); +});