feat(onebot): debug subscribe seams for NetworkManager + ApiHandler

Add NetworkManager.subscribeDebug (notified for every emitEvent, before the
adapter check, so the debug stream sees events even with no adapter) and
ApiHandler.setObserver (fires after every handled action with
{action,params,response,ms}, success or failure). Both Set-based, return an
unsubscribe, and swallow subscriber throws so they never break dispatch.
OneBotInstance exposes subscribeDebugEvents / observeActions / invokeAction.
Foundation for the Wave A3 debug stream + action tester.
This commit is contained in:
DrSmoothl committed 2026-06-18 15:17:28 +08:00
1 parent d2e8222886
commit cde5a22ec8
4 files changed
+149 -5

No files matched your search

+37 -3
View File
@@ -81,9 +81,27 @@ export interface ApiActionContext {
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
/** A handled-action record handed to debug observers. */
export interface ActionRecord {
action: string;
params: JsonObject;
response: import('./types').ApiResponse;
ms: number;
}
export type ActionObserver = (rec: ActionRecord) => void;
export class ApiHandler {
private readonly handlers = new Map<string, ActionHandler>();
private readonly log: Logger;
/** Debug-stream taps — notified after every handled action. Attached
* on-demand (ref-counted) by the WebUI debug stream. */
private readonly observers = new Set<ActionObserver>();
/** Observe handled actions (debug). Returns an unsubscribe. */
setObserver(cb: ActionObserver): () => void {
this.observers.add(cb);
return () => { this.observers.delete(cb); };
}
constructor(context: ApiActionContext, uin?: number) {
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
@@ -132,10 +150,10 @@ export class ApiHandler {
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
const startedAt = Date.now();
let response: import('./types').ApiResponse;
try {
const response = await handler(params);
response = await handler(params);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
return response;
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so
@@ -145,7 +163,23 @@ export class ApiHandler {
error instanceof Error ? error.message : String(error),
error instanceof Error ? (error.stack ?? '') : '');
const message = error instanceof Error ? error.message : 'internal error';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
response = failedResponse(RETCODE.INTERNAL_ERROR, message);
}
this.notifyObservers(action, params, response, Date.now() - startedAt);
return response;
}
private notifyObservers(
action: string,
params: JsonObject,
response: import('./types').ApiResponse,
ms: number,
): void {
if (!this.observers.size) return;
for (const cb of this.observers) {
try { cb({ action, params, response, ms }); } catch (err) {
this.log.warn('action observer error: %s', err instanceof Error ? err.message : String(err));
}
}
}
+16 -2
View File
@@ -2,7 +2,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
import path from 'path';
import { ApiHandler } from './api-handler';
import { ApiHandler, type ActionObserver } from './api-handler';
import type { ConverterContext } from './event-converter';
import { registerEventPipeline } from './event-pipeline';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
@@ -24,7 +24,7 @@ import {
type NetworkAdapterContext,
} from './network';
import { ReactionStore } from './reaction-store';
import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
const moduleLog = createLogger('Event');
@@ -59,6 +59,20 @@ export class OneBotInstance {
return this.networkManager.describeStatuses();
}
// ── Debug taps (WebUI debug stream / tester) ──
/** Tap every emitted OneBot event for this account. Returns an unsubscribe. */
subscribeDebugEvents(cb: (event: JsonObject) => void): () => void {
return this.networkManager.subscribeDebug(cb);
}
/** Observe every handled action for this account. Returns an unsubscribe. */
observeActions(cb: ActionObserver): () => void {
return this.apiHandler.setObserver(cb);
}
/** Invoke an OneBot action against this account (debug tester). */
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
return this.apiHandler.handle(action, params);
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.bridge = bridge;
@@ -9,6 +9,14 @@ type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
/** Debug-stream taps — notified for every emitted event regardless of adapter
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
subscribeDebug(cb: (event: JsonObject) => void): () => void {
this.debugSubscribers.add(cb);
return () => { this.debugSubscribers.delete(cb); };
}
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
const existing = this.adapters.get(adapter.name);
@@ -75,6 +83,14 @@ export class OneBotNetworkManager {
}
async emitEvent(event: JsonObject): Promise<void> {
// Notify debug taps first — before the adapter check — so the debug stream
// sees every event even when no adapter is connected. Never let a tap throw
// into the dispatch path.
if (this.debugSubscribers.size) {
for (const cb of this.debugSubscribers) {
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
}
}
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];