refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

+15 -45
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger'; import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary'; import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketSender } from '@snowluma/common/packet-sender';
@@ -7,12 +8,11 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import { import {
injectHookProcess, injectHookProcess,
listHookProcesses, listHookProcesses,
resolveHookNativePath,
unloadHookProcess, unloadHookProcess,
type HookProcessBaseInfo, type HookProcessBaseInfo,
} from './injector'; } from './injector';
import { PipeWatcher } from './pipe-watcher'; import { PipeWatcher } from './pipe-watcher';
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator'; import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client'; import { QqHookClient } from './qq-hook-client';
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account'; import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
import type { HookProcessAccount, HookProcessInfo } from './types'; import type { HookProcessAccount, HookProcessInfo } from './types';
@@ -55,7 +55,7 @@ export type HookManagerDeps = {
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */ /** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number; watcherIntervalMs?: number;
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */ /** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => HookProcessBaseInfo[]; listProcesses?: () => Promise<HookProcessBaseInfo[]>;
/** Local account detection used to label each process with the account QQ is /** Local account detection used to label each process with the account QQ is
* signed in as. Receives the pids to label so each one is resolved against * signed in as. Receives the pids to label so each one is resolved against
* the HOME it actually runs under (a container can give every QQ instance * the HOME it actually runs under (a container can give every QQ instance
@@ -104,13 +104,7 @@ export class HookManager {
private readonly makeClient: HookSessionDeps['makeClient']; private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher; private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean; private readonly ownsPipeWatcher: boolean;
/** Watcher/API process enumeration — isolated + timeout-bounded by default private readonly enumerator: ProcessEnumerator;
* so a blocked native /proc walk can't freeze the loop (issue #158).
* Resolves to `null` (UNKNOWN) on timeout/failure. */
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
/** The owned enumerator (worker lifecycle), or null when a custom lister was
* injected (tests) — nothing to tear down in that case. */
private readonly enumerator: ProcessEnumerator | null;
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>; private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
private readonly accountReprobeIntervalMs: number; private readonly accountReprobeIntervalMs: number;
private readonly autoLoadOnDiscovery: boolean; private readonly autoLoadOnDiscovery: boolean;
@@ -149,37 +143,17 @@ export class HookManager {
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS; deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false; this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
// A custom lister (tests) is used directly — no worker, no isolation, just this.enumerator = createProcessEnumerator({
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path listProcesses: deps.listProcesses ?? listHookProcesses,
// wraps the native enumerator in a worker with a timeout. log: this.log,
if (deps.listProcesses) { });
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
return null;
}
};
} else {
this.enumerator = createNativeProcessEnumerator({
addonPath: resolveHookNativePath('node'),
fallbackSync: listHookProcesses,
processName: defaultProcessName(),
log: this.log,
});
this.enumerate = () => this.enumerator!.enumerate();
}
if (deps.pipeWatcher) { if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher; this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false; this.ownsPipeWatcher = false;
} else { } else {
this.pipeWatcher = new PipeWatcher({ this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerate, listProcesses: this.enumerator.enumerate,
listLivePipes: (processes) => listLivePipes: (processes) =>
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)), QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs, intervalMs: deps.watcherIntervalMs,
@@ -196,7 +170,7 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> { async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise; await this.startPromise;
const processes = await this.enumerate(); const processes = await this.enumerator.enumerate();
// A failed enumeration preserves the last known process set. // A failed enumeration preserves the last known process set.
const sessions = const sessions =
processes === null processes === null
@@ -257,7 +231,7 @@ export class HookManager {
this.sessions.clear(); this.sessions.clear();
this.accounts.clear(); this.accounts.clear();
this.autoLoadAttempts.clear(); this.autoLoadAttempts.clear();
this.enumerator?.dispose(); this.enumerator.dispose();
if (this.ownsPipeWatcher) { if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose(); this.pipeWatcher.dispose();
@@ -315,7 +289,7 @@ export class HookManager {
this.lastAccountProbeFailure = ''; this.lastAccountProbeFailure = '';
} catch (error) { } catch (error) {
const message = errMsg(error); const message = errorMessage(error);
if (this.lastAccountProbeFailure !== message) { if (this.lastAccountProbeFailure !== message) {
this.lastAccountProbeFailure = message; this.lastAccountProbeFailure = message;
@@ -573,10 +547,10 @@ export class HookManager {
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d', 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
session.pid, session.pid,
attempt, attempt,
errMsg(err), errorMessage(err),
Date.now() - startedAt, Date.now() - startedAt,
); );
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err)); this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errorMessage(err));
} }
}); });
} }
@@ -644,7 +618,7 @@ export class HookManager {
try { try {
this.onSessionsChangedRaw(); this.onSessionsChangedRaw();
} catch (err) { } catch (err) {
this.log.warn('onSessionsChanged threw: %s', errMsg(err)); this.log.warn('onSessionsChanged threw: %s', errorMessage(err));
} }
} }
@@ -659,10 +633,6 @@ function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq'; return process.platform === 'win32' ? 'QQ.exe' : 'qq';
} }
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
function isTransientLibcMappingError(error: string): boolean { function isTransientLibcMappingError(error: string): boolean {
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error); return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
} }
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
@@ -57,10 +58,6 @@ function isProcessGoneError(error: unknown): boolean {
return code === 'ENOENT' || code === 'ESRCH'; return code === 'ENOENT' || code === 'ESRCH';
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string { function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
const explicit = configuredDirectory( const explicit = configuredDirectory(
env.SNOWLUMA_HOOK_RUNTIME_DIR, env.SNOWLUMA_HOOK_RUNTIME_DIR,
+30 -37
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { import {
createLogger, createLogger,
runWithoutRequestContext, runWithoutRequestContext,
@@ -205,7 +206,9 @@ export class HookSession extends EventEmitter {
} }
await this.reconcilePipeUp(); await this.reconcilePipeUp();
}).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err))); }).catch((err) =>
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
} }
onPipeDown(): void { onPipeDown(): void {
@@ -219,7 +222,9 @@ export class HookSession extends EventEmitter {
} }
this.reconcilePipeDown(); this.reconcilePipeDown();
}).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err))); }).catch((err) =>
this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
} }
/** Called by the manager when the watcher reports the QQ.exe process is /** Called by the manager when the watcher reports the QQ.exe process is
@@ -267,7 +272,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [ this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', 'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid, this.pid,
errMsg(error), errorMessage(error),
renderParamsVerbose(this.toInfo()), renderParamsVerbose(this.toInfo()),
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
@@ -275,7 +280,7 @@ export class HookSession extends EventEmitter {
} }
}); });
}).catch((err) => }).catch((err) =>
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)), this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errorMessage(err)),
); );
} }
@@ -347,7 +352,7 @@ export class HookSession extends EventEmitter {
this.pid, this.pid,
operation, operation,
`${operation}_threw`, `${operation}_threw`,
errMsg(error), errorMessage(error),
renderParamsVerbose(this.toInfo()), renderParamsVerbose(this.toInfo()),
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
@@ -357,20 +362,12 @@ export class HookSession extends EventEmitter {
} }
private serialize<T>(op: () => Promise<T>): Promise<T> { private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain; const result = this.opChain.then(op);
let release!: () => void; this.opChain = result.then(
const completion = new Promise<void>((resolve) => { () => undefined,
release = resolve; () => undefined,
}); );
this.opChain = previous.then(() => completion); return result;
return (async () => {
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
}
})();
} }
// ─────────────── internal transitions ─────────────── // ─────────────── internal transitions ───────────────
@@ -411,7 +408,7 @@ export class HookSession extends EventEmitter {
this.applyStatus(); this.applyStatus();
} catch (error) { } catch (error) {
this._error = errMsg(error); this._error = errorMessage(error);
this.setStatus('error', this._error); this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error); this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
// The module can already be listening even when this call returns // The module can already be listening even when this call returns
@@ -467,7 +464,7 @@ export class HookSession extends EventEmitter {
this.setStatus('available', ''); this.setStatus('available', '');
} }
} catch (error) { } catch (error) {
this._error = errMsg(error); this._error = errorMessage(error);
this.setStatus('error', this._error); this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error); this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
} }
@@ -489,7 +486,7 @@ export class HookSession extends EventEmitter {
this.reconcilePipeDown(); this.reconcilePipeDown();
} }
} catch (error) { } catch (error) {
this._error = errMsg(error); this._error = errorMessage(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error); this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error); this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
} }
@@ -581,7 +578,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [ this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', 'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid, this.pid,
errMsg(error), errorMessage(error),
renderParamsVerbose(this.toInfo()), renderParamsVerbose(this.toInfo()),
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
@@ -650,7 +647,7 @@ export class HookSession extends EventEmitter {
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
} catch (error) { } catch (error) {
this._error = errMsg(error); this._error = errorMessage(error);
// Drop the client so the next attempt builds a fresh socket pair. // Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available'). // A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient(); this.tearDownClient();
@@ -670,7 +667,7 @@ export class HookSession extends EventEmitter {
client.on('packet', (packet) => this.handlePacket(packet)); client.on('packet', (packet) => this.handlePacket(packet));
client.on('loginState', (state) => this.handleLoginState(state)); client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => { client.on('error', (error) => {
const msg = errMsg(error); const msg = errorMessage(error);
this._error = msg; this._error = msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg); this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
}); });
@@ -696,7 +693,7 @@ export class HookSession extends EventEmitter {
this.reconcilePipeDown(); this.reconcilePipeDown();
}).catch((err) => }).catch((err) =>
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)), this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errorMessage(err)),
); );
}); });
} }
@@ -788,7 +785,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [ this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', 'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid, this.pid,
errMsg(error), errorMessage(error),
renderParamsVerbose(this.toInfo()), renderParamsVerbose(this.toInfo()),
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
@@ -813,7 +810,7 @@ export class HookSession extends EventEmitter {
() => void this.detectLoginOnce(), () => void this.detectLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS, LOGIN_RECONCILE_INTERVAL_MS,
); );
this.loginReconcileTimer.unref?.(); this.loginReconcileTimer.unref();
} }
private stopLoginReconcile(): void { private stopLoginReconcile(): void {
@@ -849,7 +846,7 @@ export class HookSession extends EventEmitter {
try { try {
uin = await this.detectLoginUin(this.pid); uin = await this.detectLoginUin(this.pid);
} catch (error) { } catch (error) {
const message = errMsg(error); const message = errorMessage(error);
if (this.lastDetectFailure !== message) { if (this.lastDetectFailure !== message) {
this.lastDetectFailure = message; this.lastDetectFailure = message;
@@ -924,7 +921,7 @@ export class HookSession extends EventEmitter {
this.pid, this.pid,
uin, uin,
attempt, attempt,
errMsg(error), errorMessage(error),
); );
this.nextLoginIdentityObservationAt = this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
@@ -936,7 +933,7 @@ export class HookSession extends EventEmitter {
this.pid, this.pid,
uin, uin,
attempt, attempt,
errMsg(error), errorMessage(error),
); );
} }
} }
@@ -1077,9 +1074,9 @@ export class HookSession extends EventEmitter {
silentForMs, silentForMs,
); );
}, RECEIVE_STALE_CONFIRM_MS); }, RECEIVE_STALE_CONFIRM_MS);
this.receiveWatchTimer.unref?.(); this.receiveWatchTimer.unref();
}, RECEIVE_STALE_AFTER_MS); }, RECEIVE_STALE_AFTER_MS);
this.receiveWatchTimer.unref?.(); this.receiveWatchTimer.unref();
} }
private shouldWatchReceive(): boolean { private shouldWatchReceive(): boolean {
@@ -1134,7 +1131,3 @@ export class HookSession extends EventEmitter {
this._receiveHealthy = true; this._receiveHealthy = true;
} }
} }
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+14 -44
View File
@@ -1,11 +1,8 @@
import { existsSync } from 'fs'; import { errorMessage } from '@snowluma/common/errors';
import path from 'path'; import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
import { fileURLToPath } from 'url';
import { listSnowlumaPipePidsSync } from './qq-hook-client'; import { listSnowlumaPipePidsSync } from './qq-hook-client';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle { export interface ManualMapHandle {
base: bigint; base: bigint;
entry: bigint; entry: bigint;
@@ -15,7 +12,7 @@ export interface ManualMapHandle {
interface NativeHookAddon { interface NativeHookAddon {
getRuntimeIntegrity?(): unknown; getRuntimeIntegrity?(): unknown;
getAllMainProcess(): number[]; getAllMainProcessAsync(): Promise<number[]>;
probeDbLock?(dbPath: string): { pid: number; name: string }[]; probeDbLock?(dbPath: string): { pid: number; name: string }[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>; loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void; unloadModuleManual(pid: number, handle: ManualMapHandle): void;
@@ -43,14 +40,6 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
type HookBinaryExt = 'node' | 'dll' | 'so'; type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') {
return `snowluma-win32-x64.${ext}`;
}
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' { function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so'; return process.platform === 'win32' ? 'dll' : 'so';
} }
@@ -59,33 +48,8 @@ function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq'; return process.platform === 'win32' ? 'QQ.exe' : 'qq';
} }
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: HookBinaryExt): string | null { export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext); return resolveRuntimeNativePath(`snowluma-${process.platform}-${process.arch}.${ext}`);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) {
return fullPath;
}
}
return null;
} }
export function getNativeHookAddon(): NativeHookAddon | null { export function getNativeHookAddon(): NativeHookAddon | null {
@@ -105,7 +69,7 @@ export function getNativeHookAddon(): NativeHookAddon | null {
nativeLoadError = null; nativeLoadError = null;
return nativeAddon; return nativeAddon;
} catch (error) { } catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error); nativeLoadError = errorMessage(error);
return null; return null;
} }
} }
@@ -114,7 +78,7 @@ export function getNativeHookLoadError(): string | null {
return nativeLoadError; return nativeLoadError;
} }
export function listHookProcesses(): HookProcessBaseInfo[] { export async function listHookProcesses(): Promise<HookProcessBaseInfo[]> {
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model // macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener // means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock` // socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
@@ -130,10 +94,16 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
const addon = getNativeHookAddon(); const addon = getNativeHookAddon();
if (!addon) { if (!addon) {
return []; throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
} }
return [...new Set(addon.getAllMainProcess())] if (typeof addon.getAllMainProcessAsync !== 'function') {
throw new Error(
'Hook native addon lacks getAllMainProcessAsync; update the native artifacts',
);
}
return [...new Set(await addon.getAllMainProcessAsync())]
.filter((pid) => Number.isInteger(pid) && pid > 0) .filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b) .sort((a, b) => a - b)
.map((pid) => ({ pid, name: defaultProcessName(), path: '' })); .map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
+3 -6
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger'; import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import type { HookProcessBaseInfo } from './injector'; import type { HookProcessBaseInfo } from './injector';
@@ -163,7 +164,7 @@ export class PipeWatcher extends EventEmitter {
try { try {
processes = await this.listProcesses(); processes = await this.listProcesses();
} catch (error) { } catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error)); this.log.warn('listProcesses failed: %s', errorMessage(error));
processes = null; processes = null;
} }
@@ -183,7 +184,7 @@ export class PipeWatcher extends EventEmitter {
try { try {
livePipes = await this.listLivePipes(processes); livePipes = await this.listLivePipes(processes);
} catch (error) { } catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error)); this.log.warn('listLivePipes failed: %s', errorMessage(error));
livePipes = null; livePipes = null;
} }
@@ -257,7 +258,3 @@ export class PipeWatcher extends EventEmitter {
} }
} }
} }
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+43 -257
View File
@@ -1,291 +1,77 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger'; import { createLogger, type Logger } from '@snowluma/common/logger';
import { Worker } from 'worker_threads';
import type { HookProcessBaseInfo } from './injector'; import type { HookProcessBaseInfo } from './injector';
/**
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
* enumeration.
*
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
* calling the synchronous native enumerator, which walks `/proc` and reads each
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
* silent hot-update and the process table churns. A blocked synchronous native
* call freezes the whole Node event loop: OneBot stops responding, the watcher
* stops ticking, reconnect logic never runs. The process stays "alive" so the
* supervisor never restarts it — the bot just goes silent.
*
* The only way to put a real timeout on a synchronous native call is to run it
* off the main thread. We run it in a worker; the main thread races the result
* against a deadline. On timeout the main loop keeps going (it returns the
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
* prior state" — crucially NOT "all processes gone"). The blocked worker is
* abandoned (a fresh one is spawned next time); it exits on its own once the
* native call finally returns.
*
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
* exactly today's behaviour, no worse.
*/
export interface ProcessEnumerator { export interface ProcessEnumerator {
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed /** null means unknown: keep the previous process set. */
* out / failed and the caller should keep its prior state. */
enumerate(): Promise<HookProcessBaseInfo[] | null>; enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void; dispose(): void;
} }
export interface NativeEnumeratorDeps { interface ProcessEnumeratorDeps {
/** Resolved path to the hook `.node` addon, or null when there is none listProcesses: () => Promise<HookProcessBaseInfo[]>;
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
timeoutMs?: number; timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger; log?: Logger;
} }
const DEFAULT_TIMEOUT_MS = 4000; export function createProcessEnumerator(deps: ProcessEnumeratorDeps): ProcessEnumerator {
const DEFAULT_MAX_ORPHANS = 4;
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
// `process.dlopen` is a global and needs no module system). Loads the addon
// handed in via workerData, then answers each 'enumerate' with the raw pid list
// from the blocking native call. All the cheap post-processing stays on main.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
let addon = null;
try {
const mod = { exports: {} };
process.dlopen(mod, workerData.addonPath);
addon = mod.exports;
} catch (e) {
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
}
if (addon) {
parentPort.on('message', (msg) => {
if (!msg || msg.type !== 'enumerate') return;
try {
const pids = addon.getAllMainProcess();
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
} catch (e) {
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
}
});
parentPort.postMessage({ type: 'ready' });
}
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator'); const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS; const timeoutMs = deps.timeoutMs ?? 4000;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() {
/* nothing to tear down */
},
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false; let disposed = false;
let pending: {
const spawnWorker = (): void => { promise: Promise<HookProcessBaseInfo[] | null>;
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } }); settle: (result: HookProcessBaseInfo[] | null) => void;
worker = w; } | null = null;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') {
return;
}
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn(
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
msg.error ?? '',
);
isolationBroken = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) {
return;
}
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) {
teardownWorker();
}
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) {
return;
}
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => {
orphans = Math.max(0, orphans - 1);
});
void w.terminate().catch(() => {
/* already gone */
});
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
}
};
return { return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> { enumerate() {
if (disposed || isolationBroken) { if (disposed) {
return syncFallback(); return Promise.resolve(null);
} }
if (!worker) { if (pending) {
if (orphans >= maxOrphans) { return pending.promise;
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
} }
const w = worker; let resolve!: (result: HookProcessBaseInfo[] | null) => void;
const promise = new Promise<HookProcessBaseInfo[] | null>((done) => {
if (!w) { resolve = done;
return syncFallback();
}
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
}); });
try { const settle = (result: HookProcessBaseInfo[] | null) => {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) {
clearTimeout(timer); clearTimeout(timer);
} resolve(result);
};
if (outcome === 'timeout') { const timer = setTimeout(() => {
pending.delete(id);
log.warn( log.warn(
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set', 'process enumeration timed out after %dms; keeping prior process set',
timeoutMs, timeoutMs,
); );
teardownWorker(); settle(null);
return null; }, timeoutMs);
} pending = { promise, settle };
if (outcome === null) { // A timeout ends the wait, not the native call. Keep its slot until it
// Native call threw inside the worker — treat as a transient failure, // finishes so subsequent polls cannot accumulate blocked native work.
// keep prior state rather than nuking every session. void Promise.resolve()
return null; .then(() => (disposed ? null : deps.listProcesses()))
} .then(
(processes) => {
return mapPids(outcome, deps.processName); pending = null;
settle(disposed ? null : processes);
},
(error) => {
pending = null;
log.warn('process enumeration failed: %s', errorMessage(error));
settle(null);
},
);
return promise;
}, },
dispose() { dispose() {
disposed = true; disposed = true;
pending?.settle(null);
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
const w = worker;
worker = null;
if (w) {
void w.terminate().catch(() => {
/* ignore */
});
}
}, },
}; };
} }
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
@@ -37,7 +37,7 @@ function makeManager(
let pids = opts.processes ?? []; let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []); let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({ const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live), listLivePipes: async () => new Set(live),
intervalMs: 60_000, intervalMs: 60_000,
}); });
@@ -72,7 +72,7 @@ function makeManager(
unload: vi.fn(), unload: vi.fn(),
}, },
makeClient: clientFactory, makeClient: clientFactory,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []), detectAccounts: opts.detectAccounts ?? (async () => []),
accountReprobeIntervalMs: opts.accountReprobeIntervalMs, accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
onSessionsChanged, onSessionsChanged,
@@ -162,7 +162,7 @@ describe('HookManager.onSessionsChanged', () => {
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => { it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242]; const pids = [4242];
const pipeWatcher = new PipeWatcher({ const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(), listLivePipes: async () => new Set(),
intervalMs: 60_000, intervalMs: 60_000,
}); });
@@ -193,7 +193,7 @@ describe('HookManager.onSessionsChanged', () => {
return c; return c;
}), }),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [], detectAccounts: async () => [],
// onSessionsChanged deliberately omitted // onSessionsChanged deliberately omitted
}); });
+2 -2
View File
@@ -43,7 +43,7 @@ function makeManager(opts: {
); );
const unload = vi.fn(); const unload = vi.fn();
const pipeWatcher = new PipeWatcher({ const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live), listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually intervalMs: 60_000, // disable internal timer; tests drive ticks manually
}); });
@@ -77,7 +77,7 @@ function makeManager(opts: {
makeClient, makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery, autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged, onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// Detection reads QQ's own data directories; tests stay off the host. // Detection reads QQ's own data directories; tests stay off the host.
detectAccounts: opts.detectAccounts ?? (async () => []), detectAccounts: opts.detectAccounts ?? (async () => []),
}); });
@@ -43,7 +43,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
const clients: FakeClient[] = []; const clients: FakeClient[] = [];
const pipeWatcher = new PipeWatcher({ const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet), listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only intervalMs: 60_000, // manual ticks only
}); });
@@ -70,7 +70,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
return c as unknown as QqHookClient; return c as unknown as QqHookClient;
}, },
autoLoadOnDiscovery: true, autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
detectAccounts: async () => [], detectAccounts: async () => [],
}); });
@@ -15,7 +15,7 @@
// - at most one client is alive at any point // - at most one client is alive at any point
// - every prior client's EventEmitter listener count drops to 0 after teardown // - every prior client's EventEmitter listener count drops to 0 after teardown
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, onTestFinished, vi } from 'vitest';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session'; import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector'; import type { ManualMapHandle } from '../src/injector';
@@ -57,6 +57,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
let pipeLive = true; let pipeLive = true;
const clients: FakeClient[] = []; const clients: FakeClient[] = [];
const session = new HookSession(61, { const session = new HookSession(61, {
detectLoginUin: async () => null,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(() => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
@@ -71,6 +72,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
}, },
pipeWatcher: { isPipeLive: () => pipeLive }, pipeWatcher: { isPipeLive: () => pipeLive },
}); });
onTestFinished(() => session.dispose());
await session.load(); await session.load();
session.onPipeUp(); session.onPipeUp();
@@ -99,6 +101,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
let pipeLive = true; let pipeLive = true;
const clients: FakeClient[] = []; const clients: FakeClient[] = [];
const session = new HookSession(61, { const session = new HookSession(61, {
detectLoginUin: async () => null,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(() => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
@@ -113,6 +116,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
}, },
pipeWatcher: { isPipeLive: () => pipeLive }, pipeWatcher: { isPipeLive: () => pipeLive },
}); });
onTestFinished(() => session.dispose());
await session.load(); await session.load();
session.onPipeUp(); session.onPipeUp();
+38 -27
View File
@@ -20,7 +20,9 @@ vi.mock('../src/qq-hook-client', () => ({
listSnowlumaPipePidsSync: listPidsMock, listSnowlumaPipePidsSync: listPidsMock,
})); }));
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url))); const NATIVE_PATH_DIR = path.dirname(
fileURLToPath(new URL('../../common/src/native-path.ts', import.meta.url)),
);
const ORIGINAL_PLATFORM = process.platform; const ORIGINAL_PLATFORM = process.platform;
const ORIGINAL_ARCH = process.arch; const ORIGINAL_ARCH = process.arch;
@@ -41,17 +43,15 @@ function restorePlatform(): void {
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true }); Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
} }
function nativeSearchDirs(cwd = process.cwd()): string[] { function nativeSearchDirs(): string[] {
return [ return [
path.resolve(INJECTOR_DIR, 'native'), path.resolve(NATIVE_PATH_DIR, 'native'),
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'), path.resolve(NATIVE_PATH_DIR, '..', '..', 'runtime', 'native'),
path.resolve(cwd, 'dist', 'native'),
path.resolve(cwd, 'packages', 'runtime', 'native'),
]; ];
} }
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string { function nativeCandidate(fileName: string, dirIndex: number): string {
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName); return path.join(nativeSearchDirs()[dirIndex]!, fileName);
} }
function allowExisting(paths: readonly string[]): void { function allowExisting(paths: readonly string[]): void {
@@ -61,13 +61,13 @@ function allowExisting(paths: readonly string[]): void {
function fakeAddon( function fakeAddon(
overrides: { overrides: {
getAllMainProcess?: number[]; getAllMainProcessAsync?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown; loadModuleManual?: (pid: number, dylibPath: string) => unknown;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
} = {}, } = {},
) { ) {
return { return {
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []), getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
}; };
@@ -110,8 +110,6 @@ describe('resolveHookNativePath', () => {
expect(probed).toEqual([ expect(probed).toEqual([
nativeCandidate('snowluma-linux-x64.node', 0), nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.node', 1), nativeCandidate('snowluma-linux-x64.node', 1),
nativeCandidate('snowluma-linux-x64.node', 2),
nativeCandidate('snowluma-linux-x64.node', 3),
]); ]);
}); });
@@ -132,7 +130,7 @@ describe('resolveHookNativePath', () => {
it('skips missing earlier directories for the injectable .so', async () => { it('skips missing earlier directories for the injectable .so', async () => {
setPlatform('linux', 'arm64'); setPlatform('linux', 'arm64');
const winner = nativeCandidate('snowluma-linux-arm64.so', 2); const winner = nativeCandidate('snowluma-linux-arm64.so', 1);
allowExisting([winner]); allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector(); const { resolveHookNativePath } = await loadInjector();
@@ -141,7 +139,7 @@ describe('resolveHookNativePath', () => {
it('resolves snowluma-win32-x64.dll on win32 x64', async () => { it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64'); setPlatform('win32', 'x64');
const winner = nativeCandidate('snowluma-win32-x64.dll', 3); const winner = nativeCandidate('snowluma-win32-x64.dll', 1);
allowExisting([winner]); allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector(); const { resolveHookNativePath } = await loadInjector();
@@ -157,7 +155,7 @@ describe('resolveHookNativePath', () => {
expect(resolveHookNativePath('node')).toBe(winner); expect(resolveHookNativePath('node')).toBe(winner);
}); });
it('re-reads process.cwd() for the dist/native fallback', async () => { it('does not load an unrelated native addon from the working directory', async () => {
setPlatform('darwin', 'arm64'); setPlatform('darwin', 'arm64');
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd'); vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
const winner = path.join( const winner = path.join(
@@ -169,7 +167,7 @@ describe('resolveHookNativePath', () => {
allowExisting([winner]); allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector(); const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner); expect(resolveHookNativePath('node')).toBeNull();
}); });
}); });
@@ -248,14 +246,25 @@ describe('getNativeHookAddon / getNativeHookLoadError', () => {
}); });
describe('listHookProcesses', () => { describe('listHookProcesses', () => {
it('rejects an obsolete addon without calling its synchronous enumerator', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
const getAllMainProcess = vi.fn(() => [9]);
installDlopen({ getAllMainProcess });
const { listHookProcesses } = await loadInjector();
await expect(listHookProcesses()).rejects.toThrow('getAllMainProcessAsync');
expect(getAllMainProcess).not.toHaveBeenCalled();
});
it('on darwin maps sorted pipe pids without opening the native addon', async () => { it('on darwin maps sorted pipe pids without opening the native addon', async () => {
setPlatform('darwin', 'arm64'); setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set([42, 7, 15])); listPidsMock.mockReturnValue(new Set([42, 7, 15]));
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] })); const dlopen = installDlopen(fakeAddon({ getAllMainProcessAsync: [99] }));
const { listHookProcesses } = await loadInjector(); const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([ expect(await listHookProcesses()).toEqual([
{ pid: 7, name: 'qq', path: '' }, { pid: 7, name: 'qq', path: '' },
{ pid: 15, name: 'qq', path: '' }, { pid: 15, name: 'qq', path: '' },
{ pid: 42, name: 'qq', path: '' }, { pid: 42, name: 'qq', path: '' },
@@ -269,14 +278,16 @@ describe('listHookProcesses', () => {
listPidsMock.mockReturnValue(new Set()); listPidsMock.mockReturnValue(new Set());
const { listHookProcesses } = await loadInjector(); const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]); expect(await listHookProcesses()).toEqual([]);
}); });
it('on non-darwin returns [] when the addon cannot be loaded', async () => { it('reports a missing addon instead of an empty process set', async () => {
setPlatform('linux', 'x64'); setPlatform('linux', 'x64');
const { listHookProcesses } = await loadInjector(); const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]); await expect(listHookProcesses()).rejects.toThrow(
'No hook native addon found for linux-x64',
);
}); });
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => { it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
@@ -285,12 +296,12 @@ describe('listHookProcesses', () => {
allowExisting([nodePath]); allowExisting([nodePath]);
installDlopen( installDlopen(
fakeAddon({ fakeAddon({
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2], getAllMainProcessAsync: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
}), }),
); );
const { listHookProcesses } = await loadInjector(); const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([ expect(await listHookProcesses()).toEqual([
{ pid: 2, name: 'qq', path: '' }, { pid: 2, name: 'qq', path: '' },
{ pid: 8, name: 'qq', path: '' }, { pid: 8, name: 'qq', path: '' },
]); ]);
@@ -299,10 +310,10 @@ describe('listHookProcesses', () => {
it('on win32 names processes QQ.exe', async () => { it('on win32 names processes QQ.exe', async () => {
setPlatform('win32', 'x64'); setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]); allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
installDlopen(fakeAddon({ getAllMainProcess: [9] })); installDlopen(fakeAddon({ getAllMainProcessAsync: [9] }));
const { listHookProcesses } = await loadInjector(); const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]); expect(await listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
}); });
}); });
@@ -345,8 +356,8 @@ describe('injectHookProcess', () => {
it('accepts a synchronous loadModuleManual return value', async () => { it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64'); setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2); const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 1);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3); const soPath = nativeCandidate('snowluma-darwin-arm64.so', 1);
allowExisting([nodePath, soPath]); allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE }); const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon); installDlopen(addon);
+108 -45
View File
@@ -1,57 +1,120 @@
import { describe, it, expect, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createNativeProcessEnumerator } from '../src/process-enumerator'; import { createProcessEnumerator } from '../src/process-enumerator';
import type { HookProcessBaseInfo } from '../src/injector'; import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' }); const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
describe('createNativeProcessEnumerator', () => { function deferred() {
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => { let resolve!: (processes: HookProcessBaseInfo[]) => void;
it('returns the sync lister result', async () => { let reject!: (error: Error) => void;
const en = createNativeProcessEnumerator({ const promise = new Promise<HookProcessBaseInfo[]>((done, fail) => {
addonPath: null, resolve = done;
fallbackSync: () => [QQ(10), QQ(20)], reject = fail;
processName: 'qq', });
}); return { promise, resolve, reject };
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]); }
en.dispose();
});
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => { beforeEach(() => vi.useFakeTimers());
const en = createNativeProcessEnumerator({ afterEach(() => vi.useRealTimers());
addonPath: null,
fallbackSync: () => { describe('process enumeration', () => {
throw new Error('boom'); it('shares one native request between concurrent callers', async () => {
}, const request = deferred();
processName: 'qq', const listProcesses = vi.fn(() => request.promise);
}); const enumerator = createProcessEnumerator({ listProcesses });
expect(await en.enumerate()).toBeNull(); const first = enumerator.enumerate();
en.dispose(); expect(enumerator.enumerate()).toBe(first);
}); request.resolve([QQ(1), QQ(2)]);
expect(await first).toEqual([QQ(1), QQ(2)]);
expect(listProcesses).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
enumerator.dispose();
}); });
describe('worker isolation that cannot load the addon → permanent fallback', () => { it('keeps timed-out native work in flight until it actually finishes', async () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => { const request = deferred();
const fallback = vi.fn(() => [QQ(7)]); const listProcesses = vi.fn(() => request.promise).mockResolvedValueOnce([QQ(1)]);
const en = createNativeProcessEnumerator({ const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
// A path that exists nowhere → process.dlopen throws in the worker → expect(await enumerator.enumerate()).toEqual([QQ(1)]);
// the worker posts 'fatal' → isolation is abandoned for good. const stalled = enumerator.enumerate();
addonPath: '/nonexistent/snowluma-test.node', await vi.advanceTimersByTimeAsync(100);
fallbackSync: fallback, expect(await stalled).toBeNull();
processName: 'qq',
timeoutMs: 200, for (let i = 0; i < 10; i++) {
expect(await enumerator.enumerate()).toBeNull();
}
expect(listProcesses).toHaveBeenCalledTimes(2);
request.resolve([QQ(2)]);
await vi.advanceTimersByTimeAsync(0);
listProcesses.mockResolvedValueOnce([QQ(3)]);
expect(await enumerator.enumerate()).toEqual([QQ(3)]);
expect(await stalled).toBeNull();
enumerator.dispose();
});
it.each(['throw', 'reject'] as const)(
'keeps a %s unknown and allows a fresh request',
async (kind) => {
const listProcesses = vi.fn<() => Promise<HookProcessBaseInfo[]>>(() => {
if (kind === 'throw') {
throw new Error('process table unavailable');
}
return Promise.reject(new Error('process table unavailable'));
}); });
const enumerator = createProcessEnumerator({ listProcesses });
expect(await enumerator.enumerate()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
listProcesses.mockResolvedValueOnce([]);
expect(await enumerator.enumerate()).toEqual([]);
enumerator.dispose();
},
);
// First call spawns the worker; the fatal message drains it to UNKNOWN. it('handles a rejection after timeout and recovers on the next poll', async () => {
const first = await en.enumerate(); const request = deferred();
expect(first).toBeNull(); const listProcesses = vi.fn(() => request.promise);
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
const pending = enumerator.enumerate();
await vi.advanceTimersByTimeAsync(100);
expect(await pending).toBeNull();
request.reject(new Error('late failure'));
await vi.advanceTimersByTimeAsync(0);
listProcesses.mockResolvedValueOnce([QQ(4)]);
expect(await enumerator.enumerate()).toEqual([QQ(4)]);
enumerator.dispose();
});
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't it('settles disposal immediately without accepting late native results', async () => {
// already, then subsequent calls take the synchronous fallback. const request = deferred();
await new Promise((r) => setTimeout(r, 50)); const listProcesses = vi.fn(() => request.promise);
const second = await en.enumerate(); const enumerator = createProcessEnumerator({ listProcesses });
expect(second).toEqual([QQ(7)]); const pending = enumerator.enumerate();
expect(fallback).toHaveBeenCalled(); await Promise.resolve();
en.dispose(); enumerator.dispose();
}); enumerator.dispose();
expect(await pending).toBeNull();
expect(vi.getTimerCount()).toBe(0);
request.resolve([QQ(1)]);
expect(await enumerator.enumerate()).toBeNull();
expect(listProcesses).toHaveBeenCalledTimes(1);
});
it('never calls the lister after disposal', async () => {
const listProcesses = vi.fn(async () => [QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses });
enumerator.dispose();
expect(await enumerator.enumerate()).toBeNull();
expect(listProcesses).not.toHaveBeenCalled();
});
it('does not start queued native work when disposed in the same tick', async () => {
const listProcesses = vi.fn(async () => [QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses });
const pending = enumerator.enumerate();
enumerator.dispose();
expect(await pending).toBeNull();
expect(listProcesses).not.toHaveBeenCalled();
}); });
}); });
+8
View File
@@ -12,6 +12,14 @@
"types": "./src/version.ts", "types": "./src/version.ts",
"default": "./src/version.ts" "default": "./src/version.ts"
}, },
"./native-path": {
"types": "./src/native-path.ts",
"default": "./src/native-path.ts"
},
"./errors": {
"types": "./src/errors.ts",
"default": "./src/errors.ts"
},
".": { ".": {
"types": "./src/index.ts", "types": "./src/index.ts",
"default": "./src/index.ts" "default": "./src/index.ts"
+3
View File
@@ -0,0 +1,3 @@
export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+2 -19
View File
@@ -1,26 +1,9 @@
const HEX_CHARS = '0123456789abcdef';
const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string { export function toHex(data: Uint8Array | Buffer): string {
let h = ''; return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('hex');
for (const b of data) {
h += HEX_CHARS[b >> 4];
h += HEX_CHARS[b & 0xf];
}
return h;
} }
export function toHexUpper(data: Uint8Array | Buffer): string { export function toHexUpper(data: Uint8Array | Buffer): string {
let h = ''; return toHex(data).toUpperCase();
for (const b of data) {
h += HEX_CHARS_UPPER[b >> 4];
h += HEX_CHARS_UPPER[b & 0xf];
}
return h;
} }
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string { export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from './errors';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { sanitizeLogLine } from './log-sanitize'; import { sanitizeLogLine } from './log-sanitize';
@@ -1237,7 +1238,3 @@ export async function _resetFileTransportForTesting(): Promise<void> {
function isMissing(error: unknown): boolean { function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT'; return error instanceof Error && 'code' in error && error.code === 'ENOENT';
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+21
View File
@@ -0,0 +1,21 @@
import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
export function resolveRuntimeNativePath(fileName: string): string | null {
// Bundled releases and workspace sources each own their native inputs.
for (const directory of [
path.join(moduleDir, 'native'),
path.resolve(moduleDir, '..', '..', 'runtime', 'native'),
]) {
const candidate = path.join(directory, fileName);
if (existsSync(candidate)) {
return candidate;
}
}
return null;
}
+6
View File
@@ -2,6 +2,12 @@ import { describe, expect, it } from 'vitest';
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex'; import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
describe('hex', () => { describe('hex', () => {
it('encodes only the selected byte view', () => {
const bytes = Uint8Array.of(0xff, 0x01, 0xab, 0xff);
expect(toHex(bytes.subarray(1, 3))).toBe('01ab');
expect(toHexUpper(Buffer.from(bytes).subarray(1, 3))).toBe('01AB');
});
it('toHex / toHexUpper render bytes as zero-padded hex', () => { it('toHex / toHexUpper render bytes as zero-padded hex', () => {
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]); const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
expect(toHex(b)).toBe('000fa0ff'); expect(toHex(b)).toBe('000fa0ff');
+1 -1
View File
@@ -318,7 +318,7 @@ export class ExtrasApi {
), ),
); );
}, receiptTimeoutMs); }, receiptTimeoutMs);
timeout.unref?.(); timeout.unref();
}), }),
])); ]));
@@ -17,3 +17,12 @@ export interface BridgeInterface extends BridgeContext {
* QQ has not emitted its cache notification since SnowLuma attached. */ * QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null; getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
} }
export interface BridgeSessionListener {
started?(uin: string, bridge: BridgeInterface): void;
closed?(uin: string, bridge: BridgeInterface, pid: number): void;
}
export interface BridgeSessionSource {
subscribeSessions(listener: BridgeSessionListener): () => void;
}
+47 -70
View File
@@ -4,31 +4,28 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin'; import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service'; import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge'; import { Bridge } from './bridge';
import type { BridgeSessionListener, BridgeSessionSource } from './bridge-interface';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge, pid: number) => void;
interface QQSession {
bridge: Bridge;
}
const log = createLogger('Bridge'); const log = createLogger('Bridge');
const packetLog = createLogger('Bridge.Packet'); const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime'); const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager { export class BridgeManager implements BridgeSessionSource {
private sessions_ = new Map<string, QQSession>(); private readonly bridges = new Map<string, Bridge>();
private pidToUin_ = new Map<number, string>(); private readonly pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Promise<void>>(); private readonly closingSessions_ = new Map<string, Promise<void>>();
private readonly closeErrors_: unknown[] = []; private readonly closeErrors_: unknown[] = [];
private readonly sessionSubscriptions = new Set<{ listener: BridgeSessionListener }>();
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */ /** Hook callbacks remain synchronous; shutdown awaits every detached account. */
async dispose(): Promise<void> { async dispose(): Promise<void> {
for (const [uin, session] of this.sessions_) { this.sessionSubscriptions.clear();
this.closeSession(uin, session.bridge);
for (const [uin, session] of this.bridges) {
this.closeSession(uin, session);
} }
this.sessions_.clear(); this.bridges.clear();
this.pidToUin_.clear(); this.pidToUin_.clear();
await Promise.allSettled(this.closingSessions_.values()); await Promise.allSettled(this.closingSessions_.values());
@@ -58,33 +55,21 @@ export class BridgeManager {
); );
} }
private readonly sessionStartedListeners_ = new Set<SessionStartedCallback>(); /** Listener changes take effect on the next event. Close observers run before
private readonly sessionClosedListeners_ = new Set<SessionClosedCallback>(); * Bridge disposal, so the final process and account identity remain readable. */
subscribeSessions(listener: BridgeSessionListener): () => void {
/** Each subscription has an independent, idempotent unsubscribe handle. */ const subscription = { listener };
addSessionStartedListener(cb: SessionStartedCallback): () => void { this.sessionSubscriptions.add(subscription);
const listener: SessionStartedCallback = (...args) => cb(...args);
this.sessionStartedListeners_.add(listener);
return () => { return () => {
this.sessionStartedListeners_.delete(listener); this.sessionSubscriptions.delete(subscription);
};
}
/** The close edge includes the final PID and bridge before disposal. */
addSessionClosedListener(cb: SessionClosedCallback): () => void {
const listener: SessionClosedCallback = (...args) => cb(...args);
this.sessionClosedListeners_.add(listener);
return () => {
this.sessionClosedListeners_.delete(listener);
}; };
} }
private fireSessionStarted(uin: string, bridge: Bridge): void { private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of [...this.sessionStartedListeners_]) { for (const { listener } of [...this.sessionSubscriptions]) {
try { try {
cb(uin, bridge); listener.started?.(uin, bridge);
} catch (err) { } catch (err) {
log.warn( log.warn(
'session-started listener threw: %s', 'session-started listener threw: %s',
@@ -95,9 +80,9 @@ export class BridgeManager {
} }
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void { private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const cb of [...this.sessionClosedListeners_]) { for (const { listener } of [...this.sessionSubscriptions]) {
try { try {
cb(uin, bridge, pid); listener.closed?.(uin, bridge, pid);
} catch (err) { } catch (err) {
log.warn( log.warn(
'session-closed listener threw: %s', 'session-closed listener threw: %s',
@@ -120,7 +105,7 @@ export class BridgeManager {
try { try {
const closed = this.detachPidFromSession(pid, uin); const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null; const activePid = this.bridges.get(uin)?.activePid ?? null;
if (closed) { if (closed) {
runtimeLog.trace( runtimeLog.trace(
@@ -160,15 +145,15 @@ export class BridgeManager {
throw new Error(message); throw new Error(message);
} }
const session = this.sessions_.get(uin); const session = this.bridges.get(uin);
if (!session || !session.bridge.hasPid(pid)) { if (!session || !session.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`; const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message); log.error(message);
throw new Error(message); throw new Error(message);
} }
session.bridge.setPidReceiveHealthy(pid, healthy); session.setPidReceiveHealthy(pid, healthy);
} }
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
@@ -196,14 +181,14 @@ export class BridgeManager {
uin, uin,
previousUin, previousUin,
); );
const previousSession = this.sessions_.get(previousUin); const previousSession = this.bridges.get(previousUin);
runtimeLog.trace( runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j', 'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid, pid,
uin, uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed', previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin, previousUin,
previousSession?.bridge.activePid ?? null, previousSession?.activePid ?? null,
); );
} }
@@ -214,7 +199,7 @@ export class BridgeManager {
uin, uin,
); );
log.debug('session started: UIN=%s', uin); log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge); this.fireSessionStarted(uin, session);
} }
runtimeLog.trace( runtimeLog.trace(
@@ -223,7 +208,7 @@ export class BridgeManager {
uin, uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound', previousUin && previousUin !== uin ? 'rebound' : 'bound',
created, created,
session.bridge.activePid, session.activePid,
Date.now() - startedAt, Date.now() - startedAt,
); );
} catch (error) { } catch (error) {
@@ -284,13 +269,13 @@ export class BridgeManager {
// Notify session started on first real packet // Notify session started on first real packet
if (created) { if (created) {
log.debug('session started: UIN=%s', uin); log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge); this.fireSessionStarted(uin, session);
} }
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and // Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment. // dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true; handedToPipeline = true;
completion = session.bridge.onPacket(pkt); completion = session.onPacket(pkt);
} catch (error) { } catch (error) {
this.tracePacketFailure( this.tracePacketFailure(
pkt, pkt,
@@ -336,7 +321,7 @@ export class BridgeManager {
uin: string, uin: string,
packetClient: PacketSender, packetClient: PacketSender,
source: 'login' | 'packet', source: 'login' | 'packet',
): { session: QQSession; created: boolean } { ): { session: Bridge; created: boolean } {
const previousUin = this.pidToUin_.get(pid); const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) { if (previousUin && previousUin !== uin) {
@@ -351,7 +336,7 @@ export class BridgeManager {
} }
const result = this.ensureSession(uin); const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient); result.session.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin); this.pidToUin_.set(pid, uin);
return result; return result;
} }
@@ -363,7 +348,7 @@ export class BridgeManager {
return null; return null;
} }
const session = this.sessions_.get(uin); const session = this.bridges.get(uin);
if (!session) { if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -371,7 +356,7 @@ export class BridgeManager {
throw new Error(message); throw new Error(message);
} }
const packetClient = session.bridge.packetClientForPid(pid); const packetClient = session.packetClientForPid(pid);
if (packetClient) { if (packetClient) {
return packetClient; return packetClient;
@@ -391,7 +376,7 @@ export class BridgeManager {
throw new Error(message); throw new Error(message);
} }
const session = this.sessions_.get(uin); const session = this.bridges.get(uin);
if (!session) { if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -399,7 +384,7 @@ export class BridgeManager {
throw new Error(message); throw new Error(message);
} }
if (!session.bridge.hasPid(pid)) { if (!session.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`; const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message); log.error(message);
throw new Error(message); throw new Error(message);
@@ -408,22 +393,22 @@ export class BridgeManager {
// Validation is complete. Mutate both sides only after the ownership // Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence. // invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid); this.pidToUin_.delete(pid);
session.bridge.detachPid(pid); session.detachPid(pid);
if (!session.bridge.empty) { if (!session.empty) {
return false; return false;
} }
this.sessions_.delete(uin); this.bridges.delete(uin);
log.debug('session closed: UIN=%s', uin); log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity. // Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge, pid); this.fireSessionClosed(uin, session, pid);
this.closeSession(uin, session.bridge); this.closeSession(uin, session);
return true; return true;
} }
private ensureSession(uin: string): { session: QQSession; created: boolean } { private ensureSession(uin: string): { session: Bridge; created: boolean } {
let session = this.sessions_.get(uin); const session = this.bridges.get(uin);
if (session) { if (session) {
return { session, created: false }; return { session, created: false };
@@ -432,20 +417,12 @@ export class BridgeManager {
const bridge = new Bridge( const bridge = new Bridge(
IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)), IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)),
); );
session = { bridge }; this.bridges.set(uin, bridge);
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to return { session: bridge, created: true };
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
} }
getSession(uin: string): QQSession | null { getBridge(uin: string): Bridge | null {
return this.sessions_.get(uin) ?? null; return this.bridges.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
} }
} }
+2 -4
View File
@@ -77,12 +77,13 @@ async function main() {
const bridgeManager = new BridgeManager(); const bridgeManager = new BridgeManager();
bindSystemFaceCatalog(bridgeManager); bindSystemFaceCatalog(bridgeManager);
const oneBotManager = new OneBotManager(); const oneBotManager = new OneBotManager();
oneBotManager.bind(bridgeManager);
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
// WebUI state-push wiring: HookManager + BridgeManager edges publish // WebUI state-push wiring: HookManager + BridgeManager edges publish
// `processes` / `qq-list` / `connections` invalidations into a bus the // `processes` / `qq-list` / `connections` invalidations into a bus the
// /api/state/stream SSE handler subscribes to (no REST polling required). // /api/state/stream SSE handler subscribes to (no REST polling required).
const stateWiring = createStateWiring(); const stateWiring = createStateWiring(bridgeManager);
const hookManager = new HookManager({ const hookManager = new HookManager({
bridgeManager, bridgeManager,
autoLoadOnDiscovery, autoLoadOnDiscovery,
@@ -93,9 +94,6 @@ async function main() {
log.info('hook auto-load enabled: every discovered QQ process will be injected'); log.info('hook auto-load enabled: every discovered QQ process will be injected');
} }
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER // Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes. // OneBotManager so the nickname fallback is already populated when it observes.
// Lifecycle events identify their PID; an older process with the same UIN // Lifecycle events identify their PID; an older process with the same UIN
+1 -1
View File
@@ -337,7 +337,7 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
tick(); tick();
const timer = setInterval(tick, options.intervalMs ?? 500); const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref?.(); timer.unref();
return { return {
stop() { stop() {
stopped = true; stopped = true;
+27 -18
View File
@@ -9,10 +9,11 @@
// SMTP send, the clock) are injected so the class is fully unit-testable; the // SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom. // real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env'; import { positiveIntEnv } from '@snowluma/common/env';
import { errorMessage } from '@snowluma/common/errors';
import type { HookProcessInfo } from '@snowluma/bridge/types'; import type { HookProcessInfo } from '@snowluma/bridge/types';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config'; import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager'; import type { BridgeSessionSource } from '../bridge/bridge-interface';
import { import {
isEmailChannel, isEmailChannel,
loadNotificationsConfig, loadNotificationsConfig,
@@ -93,10 +94,6 @@ interface AccountNotificationContext {
pid: number | null; pid: number | null;
} }
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/** /**
* Pure: the channels a UIN should be notified through — globally enabled AND * Pure: the channels a UIN should be notified through — globally enabled AND
* opted into by the UIN — preserving config order. Exported for unit tests. * opted into by the UIN — preserving config order. Exported for unit tests.
@@ -118,6 +115,7 @@ export class NotificationManager {
private readonly deliveries = new Map<string, Promise<void>>(); private readonly deliveries = new Map<string, Promise<void>>();
private readonly historyLimit: number; private readonly historyLimit: number;
private disposed = false; private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
constructor(deps: NotificationManagerDeps) { constructor(deps: NotificationManagerDeps) {
this.deps = deps; this.deps = deps;
@@ -126,13 +124,17 @@ export class NotificationManager {
/** Subscribe to the global session online/offline edges. Register AFTER /** Subscribe to the global session online/offline edges. Register AFTER
* OneBotManager so the nickname fallback is already populated. */ * OneBotManager so the nickname fallback is already populated. */
bind(bridgeManager: BridgeManager): void { bind(bridgeManager: BridgeSessionSource): void {
bridgeManager.addSessionStartedListener((uin, bridge) => if (this.disposed) {
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid), return;
); }
bridgeManager.addSessionClosedListener((uin, bridge, pid) =>
this.handleOffline(uin, bridge.identity.nickname, pid), this.unsubscribeSessions?.();
); this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
closed: (uin, bridge, pid) => this.handleOffline(uin, bridge.identity.nickname, pid),
});
} }
handleOnline(uin: string, nickname?: string, pid: number | null = null): void { handleOnline(uin: string, nickname?: string, pid: number | null = null): void {
@@ -158,7 +160,7 @@ export class NotificationManager {
try { try {
debounceSeconds = this.deps.loadConfig().debounceSeconds; debounceSeconds = this.deps.loadConfig().debounceSeconds;
} catch (err) { } catch (err) {
log.warn('offline(%s) skipped — config load failed: %s', uin, errMsg(err)); log.warn('offline(%s) skipped — config load failed: %s', uin, errorMessage(err));
return; return;
} }
@@ -234,7 +236,12 @@ export class NotificationManager {
const cfg = this.deps.loadConfig(); const cfg = this.deps.loadConfig();
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin)); channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
} catch (err) { } catch (err) {
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err)); log.warn(
'notify(%s, %s) skipped — config load failed: %s',
uin,
event,
errorMessage(err),
);
return; return;
} }
@@ -247,7 +254,7 @@ export class NotificationManager {
try { try {
facts = await this.deps.resolveProcess?.(uin, account.pid); facts = await this.deps.resolveProcess?.(uin, account.pid);
} catch (err) { } catch (err) {
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errMsg(err)); log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errorMessage(err));
} }
const vars: Record<string, string> = { const vars: Record<string, string> = {
@@ -318,7 +325,7 @@ export class NotificationManager {
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers); return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) { } catch (err) {
return { ok: false, error: errMsg(err) }; return { ok: false, error: errorMessage(err) };
} }
} }
@@ -332,7 +339,7 @@ export class NotificationManager {
try { try {
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId); channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
} catch (err) { } catch (err) {
return { ok: false, found: false, error: errMsg(err) }; return { ok: false, found: false, error: errorMessage(err) };
} }
if (!channel) { if (!channel) {
@@ -371,6 +378,8 @@ export class NotificationManager {
} }
this.disposed = true; this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const timer of this.timers.values()) { for (const timer of this.timers.values()) {
clearTimeout(timer); clearTimeout(timer);
@@ -399,7 +408,7 @@ export function createDefaultPost(
error: res.ok ? undefined : `HTTP ${res.status}`, error: res.ok ? undefined : `HTTP ${res.status}`,
}; };
} catch (err) { } catch (err) {
return { ok: false, error: errMsg(err) }; return { ok: false, error: errorMessage(err) };
} }
}; };
} }
+12 -10
View File
@@ -6,7 +6,7 @@ import {
type SysFaceCatalogStorage, type SysFaceCatalogStorage,
} from '@snowluma/protocol/sys-face-store'; } from '@snowluma/protocol/sys-face-store';
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage'; import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
import type { BridgeManager } from './bridge/manager'; import type { BridgeSessionSource } from './bridge/bridge-interface';
const log = createLogger('SysFace'); const log = createLogger('SysFace');
@@ -19,7 +19,7 @@ export interface SystemFaceCatalogBindingOptions {
/** Attach the shared system-face catalog to Bridge login edges. The first /** Attach the shared system-face catalog to Bridge login edges. The first
* account restores + refreshes it; later accounts reuse the same result. */ * account restores + refreshes it; later accounts reuse the same result. */
export function bindSystemFaceCatalog( export function bindSystemFaceCatalog(
manager: BridgeManager, manager: BridgeSessionSource,
options: SystemFaceCatalogBindingOptions = {}, options: SystemFaceCatalogBindingOptions = {},
): void { ): void {
const store = options.store ?? sysFaceStore; const store = options.store ?? sysFaceStore;
@@ -30,13 +30,15 @@ export function bindSystemFaceCatalog(
); );
store.configureStorage(storage); store.configureStorage(storage);
manager.addSessionStartedListener((uin, bridge) => { manager.subscribeSessions({
void store.prewarm(bridge).catch((error) => { started: (uin, bridge) => {
log.error( void store.prewarm(bridge).catch((error) => {
'system face catalog login prewarm failed: uin=%s error=%s', log.error(
uin, 'system face catalog login prewarm failed: uin=%s error=%s',
error instanceof Error ? (error.stack ?? error.message) : String(error), uin,
); error instanceof Error ? (error.stack ?? error.message) : String(error),
}); );
});
},
}); });
} }
@@ -40,8 +40,7 @@ export interface ConnectionDiffLoopHandle {
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle { export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
const intervalMs = opts.intervalMs ?? 500; const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = ''; let lastSerialized: string | undefined | null = null;
let haveBaseline = false;
let disposed = false; let disposed = false;
// One-shot diagnostic latch: a projector that starts throwing only after // One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no // a shape regression would otherwise wedge the baseline silently — no
@@ -112,13 +111,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
const serialized = JSON.stringify(comparable); const serialized = JSON.stringify(comparable);
if (!haveBaseline) { if (lastSerialized === null) {
// First successful observation. The SSE handler's sendAllInitial // First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client // already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting // on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it. // it again would be a duplicate. Just store it.
lastSerialized = serialized; lastSerialized = serialized;
haveBaseline = true;
return; return;
} }
@@ -144,7 +142,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
// lifetime by design, but tests / a future hot-reload scenario must be // lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the // able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts. // tokenJanitor pattern in server.ts.
timer.unref?.(); timer.unref();
return { return {
dispose(): void { dispose(): void {
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
@@ -434,10 +435,6 @@ function invoke(options: RestoreBackupOptions, operation: RestoreOperation): voi
options.beforeOperation?.(operation); options.beforeOperation?.(operation);
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function isMissingPathError(error: unknown): boolean { function isMissingPathError(error: unknown): boolean {
return ( return (
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT' typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
+1 -1
View File
@@ -853,7 +853,7 @@ export async function initWebUI(
// Periodic janitor — keeps sessionTokens / loginAttempts from growing // Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do. // unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.(); tokenJanitor.unref();
// ─── Login ─────────────────────────────────────────────────────────────── // ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => { app.post('/api/login', async (c) => {
+65 -101
View File
@@ -1,21 +1,9 @@
/** import { errorMessage } from '@snowluma/common/errors';
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes import { createLogger } from '@snowluma/common/logger';
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
* connection with one frame per resource.
*
* Decoupled from the HTTP layer so the route handler in server.ts can drop
* its responsibility down to "open a ReadableStream, hand its enqueue to
* bindStateStream, abort tears it down". Pure logic = unit-testable with
* fake timers; no Response/controller mocking needed.
*
* Per-resource debounce, not global: an 'qq-list' churn during a slow
* 'processes' burst must not delay the qq-list frame, and a 'connections'
* diff loop running at 500ms must not coalesce 10 unrelated processes
* events into one. Each resource is its own timer.
*/
import type { StateBus, StateResource } from './state-bus'; import type { StateBus, StateResource } from './state-bus';
const log = createLogger('WebUI.StateStream');
export interface StateStreamFrame { export interface StateStreamFrame {
resource: StateResource; resource: StateResource;
data: unknown; data: unknown;
@@ -45,112 +33,88 @@ const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connec
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle { export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50; const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false; let disposed = false;
const flush = async (resource: StateResource): Promise<void> => { function resourceStream(resource: StateResource) {
if (disposed) { let timer: ReturnType<typeof setTimeout> | null = null;
return; let task: Promise<void> | null = null;
let pending = false;
function clearTimer() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
} }
inFlight.add(resource); function flush(): Promise<void> {
if (disposed) {
try { return Promise.resolve();
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
} }
if (task) {
return task;
}
clearTimer();
task = Promise.resolve()
.then(async () => {
if (disposed) {
return;
}
const data = await opts.snapshot(resource);
if (!disposed) {
opts.send({ resource, data });
}
})
.catch((error) => {
log.warn('state stream %s failed: %s', resource, errorMessage(error));
})
.finally(() => {
task = null;
if (pending) {
pending = false;
schedule();
}
});
return task;
}
function schedule(): void {
if (disposed) { if (disposed) {
return; return;
} }
try { if (task) {
opts.send({ resource, data }); pending = true;
} catch { return;
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
} }
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one clearTimer();
// follow-up flush. Re-uses the debounce so a sustained publish timer = setTimeout(() => void flush(), debounceMs);
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
} }
return { flush, schedule, clearTimer };
}
const streams = {
processes: resourceStream('processes'),
'qq-list': resourceStream('qq-list'),
connections: resourceStream('connections'),
}; };
const unsubscribe = opts.bus.subscribe((resource) => streams[resource].schedule());
const schedule = (resource: StateResource): void => {
if (disposed) {
return;
}
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) {
clearTimeout(existing);
}
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
return { return {
async sendAllInitial(): Promise<void> { async sendAllInitial(): Promise<void> {
if (disposed) { await Promise.all(ALL_RESOURCES.map((resource) => streams[resource].flush()));
return;
}
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
}, },
dispose(): void { dispose(): void {
if (disposed) {
return;
}
disposed = true; disposed = true;
unsubscribe(); unsubscribe();
ALL_RESOURCES.forEach((resource) => streams[resource].clearTimer());
for (const t of timers.values()) {
clearTimeout(t);
}
timers.clear();
pending.clear();
}, },
}; };
} }
+10 -24
View File
@@ -1,45 +1,31 @@
import { StateBus } from './state-bus'; import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager'; import type { BridgeSessionSource } from '../bridge/bridge-interface';
export interface StateWiring { export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus; readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */ onSessionsChanged(): void;
onSessionsChanged: () => void;
/** Replace the bridge subscription for account and connection invalidations. */
bindBridgeManager(bm: BridgeManager): void;
/** Unsubscribe and stop publishing. */
dispose(): void; dispose(): void;
} }
export function createStateWiring(): StateWiring { export function createStateWiring(bridgeManager: BridgeSessionSource): StateWiring {
const bus = new StateBus(); const bus = new StateBus();
let subscriptions: (() => void)[] | null = [];
const publishAccount = (): void => { const publishAccountChange = (): void => {
// Publish the account list before its adapters are enumerated.
bus.publish('qq-list'); bus.publish('qq-list');
bus.publish('connections'); bus.publish('connections');
}; };
const unsubscribe = bridgeManager.subscribeSessions({
started: publishAccountChange,
closed: publishAccountChange,
});
return { return {
bus, bus,
onSessionsChanged: () => bus.publish('processes'), onSessionsChanged: () => bus.publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
if (!subscriptions) {
return;
}
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions = [
bm.addSessionStartedListener(publishAccount),
bm.addSessionClosedListener(publishAccount),
];
},
dispose(): void { dispose(): void {
subscriptions?.forEach((unsubscribe) => unsubscribe());
subscriptions = null;
bus.dispose(); bus.dispose();
unsubscribe();
}, },
}; };
} }
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport'; import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport';
@@ -377,10 +378,6 @@ function validateAccountStorageCategory(value: string): AccountStorageCategory {
throw new StorageManagementInputError(`unsupported account storage category: ${value}`); throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string { function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath); const absolute = path.resolve(filePath);
return message.split(absolute).join(label).split(filePath).join(label); return message.split(absolute).join(label).split(filePath).join(label);
+3 -6
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem // WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish // (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
// helpers: validate a pasted pair (save path) and resolve the on-disk pair // helpers: validate a pasted pair (save path) and resolve the on-disk pair
@@ -25,10 +26,6 @@ export interface RequiredTlsContext {
key: Buffer; key: Buffer;
} }
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */ /** Parse-validate a cert/key pair (used by the save endpoint before writing). */
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation { export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
if (!cert || !cert.toString().trim()) { if (!cert || !cert.toString().trim()) {
@@ -43,7 +40,7 @@ export function validateTlsPair(cert: string | Buffer, key: string | Buffer): Tl
tls.createSecureContext({ cert, key }); tls.createSecureContext({ cert, key });
return { ok: true }; return { ok: true };
} catch (e) { } catch (e) {
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` }; return { ok: false, reason: `invalid cert/key: ${errorMessage(e)}` };
} }
} }
@@ -63,7 +60,7 @@ export function resolveTlsContext(configDir: string): TlsResolution {
cert = fs.readFileSync(certPath); cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath); key = fs.readFileSync(keyPath);
} catch (e) { } catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` }; return { ok: false, reason: `failed to read cert/key: ${errorMessage(e)}` };
} }
const valid = validateTlsPair(cert, key); const valid = validateTlsPair(cert, key);
@@ -138,7 +138,7 @@ describe('BridgeManager PID ownership', () => {
try { try {
manager.onHookLogin(101, '10001', makeSender().client); manager.onHookLogin(101, '10001', makeSender().client);
manager.getSession('10001')!.bridge.detachPid(101); manager.getBridge('10001')!.detachPid(101);
expect(() => manager.onPidDisconnected(101)).toThrowError( expect(() => manager.onPidDisconnected(101)).toThrowError(
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID', 'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
); );
@@ -239,7 +239,7 @@ describe('BridgeManager PID ownership', () => {
}), }),
]), ]),
); );
expect(manager.getSession('0')).toBeNull(); expect(manager.getBridge('0')).toBeNull();
} finally { } finally {
unsubscribe(); unsubscribe();
} }
@@ -295,20 +295,20 @@ describe('BridgeManager PID ownership', () => {
const first = makeSender(); const first = makeSender();
const second = makeSender(); const second = makeSender();
const lifecycle: string[] = []; const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', first.client); manager.onHookLogin(101, '10001', first.client);
const oldBridge = manager.getSession('10001')!.bridge; const oldBridge = manager.getBridge('10001')!;
const dispose = vi.spyOn(oldBridge, 'dispose'); const dispose = vi.spyOn(oldBridge, 'dispose');
manager.onHookLogin(101, '20002', second.client); manager.onHookLogin(101, '20002', second.client);
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']); expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getBridge('10001')).toBeNull();
expect(oldBridge.hasPid(101)).toBe(false); expect(oldBridge.hasPid(101)).toBe(false);
expect(dispose).toHaveBeenCalledOnce(); expect(dispose).toHaveBeenCalledOnce();
expect(manager.getSession('20002')!.bridge.hasPid(101)).toBe(true); expect(manager.getBridge('20002')!.hasPid(101)).toBe(true);
}); });
it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => { it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => {
@@ -316,11 +316,11 @@ describe('BridgeManager PID ownership', () => {
const first = makeSender(); const first = makeSender();
const second = makeSender(); const second = makeSender();
const closed = vi.fn(); const closed = vi.fn();
manager.addSessionClosedListener(closed); manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', first.client); manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '10001', second.client); manager.onHookLogin(202, '10001', second.client);
const bridge = manager.getSession('10001')!.bridge; const bridge = manager.getBridge('10001')!;
expect(bridge.activePid).toBe(202); expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1])); await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
@@ -329,7 +329,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(202); manager.onPidDisconnected(202);
expect(manager.getSession('10001')!.bridge).toBe(bridge); expect(manager.getBridge('10001')!).toBe(bridge);
expect(bridge.activePid).toBe(101); expect(bridge.activePid).toBe(101);
expect(closed).not.toHaveBeenCalled(); expect(closed).not.toHaveBeenCalled();
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2])); await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
@@ -337,7 +337,7 @@ describe('BridgeManager PID ownership', () => {
expect(testSends(second.sendPacket)).toHaveLength(1); expect(testSends(second.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(101); manager.onPidDisconnected(101);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getBridge('10001')).toBeNull();
expect(closed).toHaveBeenCalledOnce(); expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', bridge, 101); expect(closed).toHaveBeenCalledWith('10001', bridge, 101);
await expect( await expect(
@@ -363,7 +363,7 @@ describe('BridgeManager PID ownership', () => {
manager.onHookLogin(202, '10001', second.client); manager.onHookLogin(202, '10001', second.client);
manager.onPacket(packet(202, '10001')); manager.onPacket(packet(202, '10001'));
manager.onPidDisconnected(202); manager.onPidDisconnected(202);
const bridge = manager.getSession('10001')!.bridge; const bridge = manager.getBridge('10001')!;
manager.onPidDisconnected(101); manager.onPidDisconnected(101);
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff])); await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
@@ -393,7 +393,7 @@ describe('BridgeManager PID ownership', () => {
const manager = new BridgeManager(); const manager = new BridgeManager();
manager.onHookLogin(101, '10001', makeSender().client); manager.onHookLogin(101, '10001', makeSender().client);
manager.onHookLogin(202, '10001', makeSender().client); manager.onHookLogin(202, '10001', makeSender().client);
const bridge = manager.getSession('10001')!.bridge; const bridge = manager.getBridge('10001')!;
expect(bridge.receiveHealthy).toBe(true); expect(bridge.receiveHealthy).toBe(true);
@@ -414,13 +414,13 @@ describe('BridgeManager PID ownership', () => {
const third = makeSender(); const third = makeSender();
const reboundFirst = makeSender(); const reboundFirst = makeSender();
const started = vi.fn(); const started = vi.fn();
manager.addSessionStartedListener(started); manager.subscribeSessions({ started: started });
manager.onHookLogin(101, '10001', first.client); manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '10001', second.client); manager.onHookLogin(202, '10001', second.client);
manager.onHookLogin(303, '10001', third.client); manager.onHookLogin(303, '10001', third.client);
manager.onHookLogin(101, '10001', reboundFirst.client); manager.onHookLogin(101, '10001', reboundFirst.client);
const bridge = manager.getSession('10001')!.bridge; const bridge = manager.getBridge('10001')!;
expect(started).toHaveBeenCalledOnce(); expect(started).toHaveBeenCalledOnce();
expect(bridge.activePid).toBe(101); expect(bridge.activePid).toBe(101);
@@ -442,15 +442,15 @@ describe('BridgeManager PID ownership', () => {
const manager = new BridgeManager(); const manager = new BridgeManager();
const sender = makeSender(); const sender = makeSender();
const lifecycle: string[] = []; const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', sender.client); manager.onHookLogin(101, '10001', sender.client);
manager.onPacket(packet(101, '20002')); manager.onPacket(packet(101, '20002'));
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']); expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getBridge('10001')).toBeNull();
const replacement = manager.getSession('20002')!.bridge; const replacement = manager.getBridge('20002')!;
expect(replacement.hasPid(101)).toBe(true); expect(replacement.hasPid(101)).toBe(true);
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1])); await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
expect(testSends(sender.sendPacket)).toHaveLength(1); expect(testSends(sender.sendPacket)).toHaveLength(1);
@@ -462,24 +462,24 @@ describe('BridgeManager PID ownership', () => {
const moving = makeSender(); const moving = makeSender();
const rebound = makeSender(); const rebound = makeSender();
const lifecycle: string[] = []; const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', fallback.client); manager.onHookLogin(101, '10001', fallback.client);
manager.onHookLogin(202, '10001', moving.client); manager.onHookLogin(202, '10001', moving.client);
const oldBridge = manager.getSession('10001')!.bridge; const oldBridge = manager.getBridge('10001')!;
expect(oldBridge.activePid).toBe(202); expect(oldBridge.activePid).toBe(202);
manager.onHookLogin(202, '20002', rebound.client); manager.onHookLogin(202, '20002', rebound.client);
expect(lifecycle).toEqual(['started:10001', 'started:20002']); expect(lifecycle).toEqual(['started:10001', 'started:20002']);
expect(manager.getSession('10001')!.bridge).toBe(oldBridge); expect(manager.getBridge('10001')!).toBe(oldBridge);
expect(oldBridge.hasPid(202)).toBe(false); expect(oldBridge.hasPid(202)).toBe(false);
expect(oldBridge.activePid).toBe(101); expect(oldBridge.activePid).toBe(101);
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1])); await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
expect(testSends(fallback.sendPacket)).toHaveLength(1); expect(testSends(fallback.sendPacket)).toHaveLength(1);
const newBridge = manager.getSession('20002')!.bridge; const newBridge = manager.getBridge('20002')!;
expect(newBridge.activePid).toBe(202); expect(newBridge.activePid).toBe(202);
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2])); await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
expect(testSends(rebound.sendPacket)).toHaveLength(1); expect(testSends(rebound.sendPacket)).toHaveLength(1);
@@ -502,20 +502,20 @@ describe('BridgeManager PID ownership', () => {
const reboundFirst = makeSender(); const reboundFirst = makeSender();
const started = vi.fn(); const started = vi.fn();
const closed = vi.fn(); const closed = vi.fn();
manager.addSessionStartedListener(started); manager.subscribeSessions({ started: started });
manager.addSessionClosedListener(closed); manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', first.client); manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '20002', second.client); manager.onHookLogin(202, '20002', second.client);
const targetBridge = manager.getSession('20002')!.bridge; const targetBridge = manager.getBridge('20002')!;
manager.onHookLogin(101, '20002', reboundFirst.client); manager.onHookLogin(101, '20002', reboundFirst.client);
expect(started).toHaveBeenCalledTimes(2); expect(started).toHaveBeenCalledTimes(2);
expect(closed).toHaveBeenCalledOnce(); expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101); expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getBridge('10001')).toBeNull();
expect(manager.getSession('20002')!.bridge).toBe(targetBridge); expect(manager.getBridge('20002')!).toBe(targetBridge);
expect(targetBridge.activePid).toBe(101); expect(targetBridge.activePid).toBe(101);
manager.onPidDisconnected(101); manager.onPidDisconnected(101);
@@ -533,8 +533,8 @@ describe('BridgeManager PID ownership', () => {
const sender = makeSender(); const sender = makeSender();
const started = vi.fn(); const started = vi.fn();
const closed = vi.fn(); const closed = vi.fn();
manager.addSessionStartedListener(started); manager.subscribeSessions({ started: started });
manager.addSessionClosedListener(closed); manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', sender.client); manager.onHookLogin(101, '10001', sender.client);
manager.onHookLogin(101, '10001', sender.client); manager.onHookLogin(101, '10001', sender.client);
@@ -563,7 +563,7 @@ describe('BridgeManager PID ownership', () => {
manager.onHookLogin(101, '10001', sender.client); manager.onHookLogin(101, '10001', sender.client);
// Remove the connection without updating the manager's ownership index. // Remove the connection without updating the manager's ownership index.
manager.getSession('10001')!.bridge.detachPid(101); manager.getBridge('10001')!.detachPid(101);
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError( expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session', 'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
@@ -0,0 +1,80 @@
import { IdentityService } from '@snowluma/protocol/identity-service';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BridgeManager } from '../src/bridge/manager';
describe('BridgeManager subscriptions', () => {
let manager: BridgeManager;
const sender = { sendPacket: vi.fn() } as never;
beforeEach(() => {
vi.spyOn(IdentityService, 'openForUin').mockImplementation((uin) =>
IdentityService.memory(uin),
);
manager = new BridgeManager();
});
afterEach(async () => {
await manager.dispose();
vi.restoreAllMocks();
});
it('unsubscribes both session edges without removing another observer', () => {
const started = vi.fn();
const closed = vi.fn();
const peer = { started: vi.fn(), closed: vi.fn() };
const unsubscribe = manager.subscribeSessions({ started, closed });
manager.subscribeSessions(peer);
manager.onHookLogin(101, '10001', sender);
unsubscribe();
manager.onPidDisconnected(101);
manager.onHookLogin(202, '20002', sender);
expect(started).toHaveBeenCalledOnce();
expect(closed).not.toHaveBeenCalled();
expect(peer.started).toHaveBeenCalledTimes(2);
expect(peer.closed).toHaveBeenCalledOnce();
});
it('keeps subscription handles independent when an observer is reused', () => {
const listener = { started: vi.fn() };
const unsubscribeFirst = manager.subscribeSessions(listener);
const unsubscribeSecond = manager.subscribeSessions(listener);
unsubscribeFirst();
unsubscribeFirst();
manager.onHookLogin(101, '10001', sender);
expect(listener.started).toHaveBeenCalledOnce();
unsubscribeSecond();
manager.onHookLogin(202, '20002', sender);
expect(listener.started).toHaveBeenCalledOnce();
});
it('applies listener changes to the next event while preserving dispatch order', () => {
const seen: string[] = [];
let unsubscribeSecond: () => void;
manager.subscribeSessions({
started: () => {
seen.push('first');
unsubscribeSecond();
manager.subscribeSessions({ started: () => seen.push('later') });
},
});
unsubscribeSecond = manager.subscribeSessions({ started: () => seen.push('second') });
manager.onHookLogin(101, '10001', sender);
expect(seen).toEqual(['first', 'second']);
seen.length = 0;
manager.onHookLogin(202, '20002', sender);
expect(seen).toEqual(['first', 'later']);
});
it('releases its observers when disposed', async () => {
const started = vi.fn();
manager.subscribeSessions({ started });
await manager.dispose();
manager.onHookLogin(101, '10001', sender);
expect(started).not.toHaveBeenCalled();
});
});
@@ -6,10 +6,10 @@ describe('BridgeManager session subscriptions', () => {
const manager = new BridgeManager(); const manager = new BridgeManager();
const started = vi.fn(); const started = vi.fn();
const closed = vi.fn(); const closed = vi.fn();
const offStarted = manager.addSessionStartedListener(started); const offStarted = manager.subscribeSessions({ started });
manager.addSessionStartedListener(started); manager.subscribeSessions({ started });
const offClosed = manager.addSessionClosedListener(closed); const offClosed = manager.subscribeSessions({ closed });
manager.addSessionClosedListener(closed); manager.subscribeSessions({ closed });
offStarted(); offStarted();
offStarted(); offStarted();
offClosed(); offClosed();
@@ -25,8 +25,8 @@ describe('BridgeManager session subscriptions', () => {
it('keeps the current fan-out stable when a listener unsubscribes a peer', async () => { it('keeps the current fan-out stable when a listener unsubscribes a peer', async () => {
const manager = new BridgeManager(); const manager = new BridgeManager();
const peer = vi.fn(); const peer = vi.fn();
manager.addSessionStartedListener(() => offPeer()); manager.subscribeSessions({ started: () => offPeer() });
const offPeer = manager.addSessionStartedListener(peer); const offPeer = manager.subscribeSessions({ started: peer });
manager.onHookLogin(4002, '12345', {} as never); manager.onHookLogin(4002, '12345', {} as never);
manager.onHookLogin(4003, '23456', {} as never); manager.onHookLogin(4003, '23456', {} as never);
@@ -63,6 +63,28 @@ describe('notification lifecycle PID', () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('detaches from session events when disposed and cannot be rebound afterward', () => {
const online = vi.spyOn(notifications, 'handleOnline');
const offline = vi.spyOn(notifications, 'handleOffline');
notifications.dispose();
notifications.bind(bridges);
bridges.onHookLogin(1001, '12345', sender);
bridges.onPidDisconnected(1001);
expect(online).not.toHaveBeenCalled();
expect(offline).not.toHaveBeenCalled();
});
it('replaces its existing binding instead of delivering each event twice', () => {
const online = vi.spyOn(notifications, 'handleOnline');
notifications.bind(bridges);
bridges.onHookLogin(1001, '12345', sender);
expect(online).toHaveBeenCalledOnce();
});
it('retains the final detached PID through debounce and uses the new PID on recovery', async () => { it('retains the final detached PID through debounce and uses the new PID on recovery', async () => {
bridges.onHookLogin(1001, '12345', sender); bridges.onHookLogin(1001, '12345', sender);
bridges.onHookLogin(2002, '12345', sender); bridges.onHookLogin(2002, '12345', sender);
@@ -71,7 +93,7 @@ describe('notification lifecycle PID', () => {
expect(posts).toEqual([]); expect(posts).toEqual([]);
bridges.onPidDisconnected(2002); bridges.onPidDisconnected(2002);
expect(bridges.getSession('12345')).toBeNull(); expect(bridges.getBridge('12345')).toBeNull();
await vi.advanceTimersByTimeAsync(30_000); await vi.advanceTimersByTimeAsync(30_000);
expect(resolveProcess).toHaveBeenNthCalledWith(1, '12345', 2002); expect(resolveProcess).toHaveBeenNthCalledWith(1, '12345', 2002);
@@ -7,6 +7,20 @@ import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
const previousLogLevel = getLogLevel(); const previousLogLevel = getLogLevel();
describe('startConnectionDiffLoop', () => { describe('startConnectionDiffLoop', () => {
it('treats an undefined snapshot as an established baseline', () => {
vi.useFakeTimers();
const bus = new StateBus();
const publish = vi.spyOn(bus, 'publish');
let snapshot: unknown = undefined;
const handle = startConnectionDiffLoop({ bus, getSnapshot: () => snapshot });
vi.advanceTimersByTime(1000);
expect(publish).not.toHaveBeenCalled();
snapshot = null;
vi.advanceTimersByTime(500);
expect(publish).toHaveBeenCalledOnce();
handle.dispose();
});
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers(); vi.useFakeTimers();
}); });
@@ -19,6 +19,50 @@ describe('bindStateStream', () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('joins concurrent initial snapshots for the same resource', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let resolve!: (data: unknown) => void;
const slow = new Promise((done) => {
resolve = done;
});
const snapshot = vi.fn((resource: StateResource) =>
resource === 'processes' ? slow : resource,
);
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
const first = handle.sendAllInitial();
const second = handle.sendAllInitial();
await vi.advanceTimersByTimeAsync(0);
expect(snapshot).toHaveBeenCalledTimes(3);
resolve('processes');
await Promise.all([first, second]);
expect(sent).toHaveLength(3);
handle.dispose();
});
it('absorbs a scheduled publish into an initial snapshot without starting another request', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let resolve!: (data: unknown) => void;
const slow = new Promise((done) => {
resolve = done;
});
const snapshot = vi.fn((resource: StateResource) =>
resource === 'processes' ? slow : resource,
);
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
bus.publish('processes');
const initial = handle.sendAllInitial();
await vi.advanceTimersByTimeAsync(100);
expect(snapshot).toHaveBeenCalledTimes(3);
resolve('fresh');
await initial;
expect(sent.filter((frame) => frame.resource === 'processes')).toEqual([
{ resource: 'processes', data: 'fresh' },
]);
handle.dispose();
});
it('sendAllInitial emits one frame per resource with the snapshot data', async () => { it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
const bus = new StateBus(); const bus = new StateBus();
const sent: CapturedFrame[] = []; const sent: CapturedFrame[] = [];
+25 -20
View File
@@ -4,15 +4,15 @@ import { createStateWiring } from '../src/webui/state-wiring';
import { BridgeManager } from '../src/bridge/manager'; import { BridgeManager } from '../src/bridge/manager';
describe('createStateWiring', () => { describe('createStateWiring', () => {
it('replaces its bridge subscription without retaining the old manager', async () => { it('keeps a replacement wiring independent of its disposed predecessor', async () => {
const wiring = createStateWiring();
const old = new BridgeManager(); const old = new BridgeManager();
const current = new BridgeManager(); const current = new BridgeManager();
const listener = vi.fn(); const listener = vi.fn();
const previousWiring = createStateWiring(old);
previousWiring.bus.subscribe(listener);
previousWiring.dispose();
const wiring = createStateWiring(current);
wiring.bus.subscribe(listener); wiring.bus.subscribe(listener);
wiring.bindBridgeManager(old);
wiring.bindBridgeManager(current);
wiring.bindBridgeManager(current);
old.onHookLogin(4100, '12345', {} as never); old.onHookLogin(4100, '12345', {} as never);
expect(listener).not.toHaveBeenCalled(); expect(listener).not.toHaveBeenCalled();
@@ -24,15 +24,13 @@ describe('createStateWiring', () => {
await current.dispose(); await current.dispose();
}); });
it('unsubscribes on disposal and does not bind again', async () => { it('unsubscribes on disposal before another account starts', async () => {
const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
const subscribe = vi.spyOn(bm, 'addSessionStartedListener'); const subscribe = vi.spyOn(bm, 'subscribeSessions');
const wiring = createStateWiring(bm);
const publish = vi.spyOn(wiring.bus, 'publish'); const publish = vi.spyOn(wiring.bus, 'publish');
wiring.bindBridgeManager(bm);
wiring.dispose(); wiring.dispose();
wiring.dispose(); wiring.dispose();
wiring.bindBridgeManager(bm);
bm.onHookLogin(4300, '34567', {} as never); bm.onHookLogin(4300, '34567', {} as never);
expect(publish).not.toHaveBeenCalled(); expect(publish).not.toHaveBeenCalled();
@@ -40,8 +38,19 @@ describe('createStateWiring', () => {
await bm.dispose(); await bm.dispose();
}); });
it('releases its session subscription when disposed', () => {
const unsubscribe = vi.fn();
const source = { subscribeSessions: vi.fn(() => unsubscribe) };
const wiring = createStateWiring(source);
wiring.dispose();
expect(source.subscribeSessions).toHaveBeenCalledOnce();
expect(unsubscribe).toHaveBeenCalledOnce();
});
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => { it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
const wiring = createStateWiring(); const wiring = createStateWiring(new BridgeManager());
expect(wiring.bus).toBeInstanceOf(StateBus); expect(wiring.bus).toBeInstanceOf(StateBus);
const sub = vi.fn(); const sub = vi.fn();
wiring.bus.subscribe(sub); wiring.bus.subscribe(sub);
@@ -50,9 +59,8 @@ describe('createStateWiring', () => {
}); });
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => { it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
wiring.bindBridgeManager(bm); const wiring = createStateWiring(bm);
const seen: string[] = []; const seen: string[] = [];
wiring.bus.subscribe((r) => seen.push(r)); wiring.bus.subscribe((r) => seen.push(r));
@@ -63,9 +71,8 @@ describe('createStateWiring', () => {
}); });
it('publishes "qq-list" + "connections" on session-closed', () => { it('publishes "qq-list" + "connections" on session-closed', () => {
const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
wiring.bindBridgeManager(bm); const wiring = createStateWiring(bm);
bm.onHookLogin(4242, '12345', {} as never); bm.onHookLogin(4242, '12345', {} as never);
const sub = vi.fn(); const sub = vi.fn();
wiring.bus.subscribe(sub); wiring.bus.subscribe(sub);
@@ -80,9 +87,8 @@ describe('createStateWiring', () => {
}); });
it('dispose() latches so later Hook/Bridge edges publish nothing', () => { it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
wiring.bindBridgeManager(bm); const wiring = createStateWiring(bm);
const sub = vi.fn(); const sub = vi.fn();
wiring.bus.subscribe(sub); wiring.bus.subscribe(sub);
@@ -98,15 +104,14 @@ describe('createStateWiring', () => {
}); });
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => { it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
wiring.bindBridgeManager(bm); const wiring = createStateWiring(bm);
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws. // A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
const peer = vi.fn(() => { const peer = vi.fn(() => {
throw new Error('peer down'); throw new Error('peer down');
}); });
bm.addSessionStartedListener(peer); bm.subscribeSessions({ started: peer });
const sub = vi.fn(); const sub = vi.fn();
wiring.bus.subscribe(sub); wiring.bus.subscribe(sub);
+1
View File
@@ -2,6 +2,7 @@
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist",
"allowImportingTsExtensions": true,
// Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway. // Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway.
"types": ["node", "vitest/globals"], "types": ["node", "vitest/globals"],
"paths": { "paths": {
+3 -9
View File
@@ -53,8 +53,7 @@ function lite(a: CatalogAction) {
const DOCS_TOOLS: Tool[] = [ const DOCS_TOOLS: Tool[] = [
{ {
name: 'list_actions', name: 'list_actions',
description: description: '列出 OneBot action,支持按分类过滤。返回名称、摘要、别名及执行类型。',
'列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。',
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { properties: {
@@ -66,8 +65,7 @@ const DOCS_TOOLS: Tool[] = [
}, },
{ {
name: 'get_action', name: 'get_action',
description: description: '获取 action 文档、参数 JSON Schema、约束和返回类型。',
'获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { name: { type: 'string', description: 'action 名(接受别名)' } }, properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
@@ -78,7 +76,7 @@ const DOCS_TOOLS: Tool[] = [
}, },
{ {
name: 'search_actions', name: 'search_actions',
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。', description: '按名称、摘要或别名搜索 action。',
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { query: { type: 'string', description: '关键字' } }, properties: { query: { type: 'string', description: '关键字' } },
@@ -291,10 +289,6 @@ async function execute(
return asError('execution.input_file 仅可用于 upload_file_stream。'); return asError('execution.input_file 仅可用于 upload_file_stream。');
} }
if (inputFile && !cat.stream) {
return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`);
}
try { try {
const result = cat.stream const result = cat.stream
? await ctx.client.callStream(action, params, { ? await ctx.client.callStream(action, params, {
+3 -17
View File
@@ -1,3 +1,4 @@
import { fromHex, toHex } from '@snowluma/common/hex';
import { mapWithConcurrency } from '@snowluma/common/concurrency'; import { mapWithConcurrency } from '@snowluma/common/concurrency';
import { positiveIntEnv } from '@snowluma/common/env'; import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
@@ -3275,7 +3276,7 @@ export const actions = [
); );
} }
const body = hexToBytes(p.data); const body = fromHex(p.data);
const result = await ctx.bridge.sendRawPacket(p.cmd, body); const result = await ctx.bridge.sendRawPacket(p.cmd, body);
if (!result.success) { if (!result.success) {
@@ -3286,7 +3287,7 @@ export const actions = [
return okResponse(null); return okResponse(null);
} }
const respHex = result.responseData ? bytesToHex(result.responseData) : ''; const respHex = result.responseData ? toHex(result.responseData) : '';
return okResponse(respHex); return okResponse(respHex);
}, },
}), }),
@@ -3577,21 +3578,6 @@ async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
return ctx.bridge.apis.contacts.fetchGroupRequests(true); return ctx.bridge.apis.contacts.fetchGroupRequests(true);
} }
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(buf: Buffer | Uint8Array): string {
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
return arr.toString('hex');
}
function parseDownloadHeaders(headers: unknown): Record<string, string> { function parseDownloadHeaders(headers: unknown): Record<string, string> {
const result: Record<string, string> = {}; const result: Record<string, string> = {};
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
// Stream API file actions (#163) — NapCat-compatible chunked file transfer. // Stream API file actions (#163) — NapCat-compatible chunked file transfer.
// //
// upload_file_stream: a client (possibly on another machine) pushes a file to // upload_file_stream: a client (possibly on another machine) pushes a file to
@@ -531,7 +532,3 @@ export const __test = {
MAX_CONCURRENT_STREAMS, MAX_CONCURRENT_STREAMS,
MAX_CHUNKS, MAX_CHUNKS,
}; };
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+1 -1
View File
@@ -287,7 +287,7 @@ export class GroupRequestPoller {
this.timer = null; this.timer = null;
this.scheduledTask = this.runScheduledPoll(); this.scheduledTask = this.runScheduledPoll();
}, this.intervalMs); }, this.intervalMs);
this.timer.unref?.(); this.timer.unref();
} }
} }
} }
+1 -1
View File
@@ -534,7 +534,7 @@ function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
signal.removeEventListener('abort', onAbort); signal.removeEventListener('abort', onAbort);
resolve(); resolve();
}, ms); }, ms);
timer.unref?.(); timer.unref();
const onAbort = () => { const onAbort = () => {
clearTimeout(timer); clearTimeout(timer);
+23 -57
View File
@@ -8,9 +8,6 @@ const log = createLogger('OneBot');
interface CachedRKey { interface CachedRKey {
value: string; value: string;
type: number;
createTime: number;
ttlSeconds: number;
expiresAt: number; expiresAt: number;
} }
@@ -61,72 +58,50 @@ export class RKeyCache {
); );
} }
async resolveImageUrl( resolveImageUrl(
bridge: BridgeInterface, bridge: BridgeInterface,
element: MessageElement, element: MessageElement,
isGroup: boolean, isGroup: boolean,
): Promise<string> { ): Promise<string> {
const url = element.imageUrl ?? ''; const url = element.imageUrl ?? '';
// Forwarded images retain their upload scene, encoded by appid in the URL.
if (!urlNeedsRKey(url)) { const type =
return url;
}
// The rkey scene must follow the IMAGE's own upload context, not the
// message currently carrying it. A c2c image forwarded into a group
// keeps its original c2c fileid/appid (1406); signing it with the
// group rkey just because the forward node looks like a group message
// yields `invalid rkey` on download. So derive the scene from the
// appid baked into the URL, and only fall back to `isGroup` when the
// URL carries no recognised appid (legacy gchat / unknown shapes).
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
// 1407 → group).
const primaryType =
imageRKeyTypeFromUrl(url) ?? imageRKeyTypeFromUrl(url) ??
(isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE); (isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
const rkey = await this.findRKeyForType(bridge, primaryType); return this.resolveUrl(bridge, url, type);
if (!rkey) {
return url;
}
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
} }
async resolveMediaUrl( resolveMediaUrl(
bridge: BridgeInterface, bridge: BridgeInterface,
element: MessageElement, element: MessageElement,
isGroup: boolean, isGroup: boolean,
): Promise<string> { ): Promise<string> {
const url = element.url ?? ''; let type: number;
if (!url || !urlNeedsRKey(url)) { if (element.type === 'video') {
type = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (element.type === 'record') {
type = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
type = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
return this.resolveUrl(bridge, element.url ?? '', type);
}
private async resolveUrl(bridge: BridgeInterface, url: string, type: number): Promise<string> {
if (!urlNeedsRKey(url)) {
return url; return url;
} }
const mediaType = element.type; const rkey = await this.findRKeyForType(bridge, type);
let primaryType: number;
if (mediaType === 'video') {
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (mediaType === 'record') {
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
const rkey = await this.findRKeyForType(bridge, primaryType);
if (!rkey) { if (!rkey) {
return url; return url;
} }
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey='; const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey); return url + separator + encodeURIComponent(stripRKeyPrefix(rkey));
} }
private updateCache(rkeys: DownloadRKeyInfo[]): void { private updateCache(rkeys: DownloadRKeyInfo[]): void {
@@ -141,9 +116,6 @@ export class RKeyCache {
const ttl = rk.ttlSeconds || 3600; const ttl = rk.ttlSeconds || 3600;
this.cache.set(rk.type, { this.cache.set(rk.type, {
value: rk.rkey, value: rk.rkey,
type: rk.type,
createTime: rk.createTime,
ttlSeconds: rk.ttlSeconds,
expiresAt: baseTime + ttl, expiresAt: baseTime + ttl,
}); });
} }
@@ -224,10 +196,6 @@ export class RKeyCache {
const inflight = this.refreshInflight; const inflight = this.refreshInflight;
if (!inflight) {
return;
}
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<void>((resolve) => { const timeout = new Promise<void>((resolve) => {
timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS);
@@ -236,9 +204,7 @@ export class RKeyCache {
try { try {
await Promise.race([inflight, timeout]); await Promise.race([inflight, timeout]);
} finally { } finally {
if (timer) { clearTimeout(timer);
clearTimeout(timer);
}
} }
} }
@@ -295,7 +261,7 @@ export class RKeyCache {
} }
private setFallbackRkey(type: number, value: string, expiresAt: number): void { private setFallbackRkey(type: number, value: string, expiresAt: number): void {
this.cache.set(type, { value, type, createTime: 0, ttlSeconds: 0, expiresAt }); this.cache.set(type, { value, expiresAt });
} }
} }
+1 -1
View File
@@ -855,7 +855,7 @@ export class OneBotInstance {
this.heartbeatTimer = setInterval(() => { this.heartbeatTimer = setInterval(() => {
this.dispatchEvent(this.makeHeartbeatEvent()); this.dispatchEvent(this.makeHeartbeatEvent());
}, OneBotInstance.HEARTBEAT_INTERVAL); }, OneBotInstance.HEARTBEAT_INTERVAL);
this.heartbeatTimer.unref?.(); this.heartbeatTimer.unref();
} }
private makeHeartbeatEvent(): JsonObject { private makeHeartbeatEvent(): JsonObject {
+53 -63
View File
@@ -1,6 +1,5 @@
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger'; import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { BridgeInterface, BridgeSessionSource } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig, OneBotConfigValidationError } from './config'; import { loadOneBotConfig, OneBotConfigValidationError } from './config';
import { loadGlobalSettings } from './global-config'; import { loadGlobalSettings } from './global-config';
import { OneBotInstance } from './instance'; import { OneBotInstance } from './instance';
@@ -134,10 +133,7 @@ export class OneBotManager {
instances?: Set<OneBotInstance>; instances?: Set<OneBotInstance>;
}> = []; }> = [];
private readonly pendingStarts = new Map< private readonly pendingStarts = new Map<string, { bridge: BridgeInterface }>();
string,
{ bridge: BridgeInterface; cancelled: boolean }
>();
private readonly databaseMigrations = new Map< private readonly databaseMigrations = new Map<
string, string,
@@ -145,8 +141,6 @@ export class OneBotManager {
bridge: BridgeInterface; bridge: BridgeInterface;
task: DatabaseMigrationTask; task: DatabaseMigrationTask;
state: AccountDatabaseMigration; state: AccountDatabaseMigration;
ready: boolean;
cancelled: boolean;
rowsPerSecond: number | null; rowsPerSecond: number | null;
retryTimer: NodeJS.Timeout | null; retryTimer: NodeJS.Timeout | null;
} }
@@ -157,6 +151,7 @@ export class OneBotManager {
private disposePromise: Promise<void> | null = null; private disposePromise: Promise<void> | null = null;
private disposed = false; private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
private readonly sessionReleaseDeadlineMs: number; private readonly sessionReleaseDeadlineMs: number;
constructor(options: OneBotManagerOptions = {}) { constructor(options: OneBotManagerOptions = {}) {
@@ -187,13 +182,17 @@ export class OneBotManager {
new OneBotInstance(uin, bridge, config, globalSettings)); new OneBotInstance(uin, bridge, config, globalSettings));
} }
bind(bridgeManager: BridgeManager): void { bind(bridgeManager: BridgeSessionSource): void {
bridgeManager.addSessionStartedListener((uin, bridge) => { if (this.disposed) {
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge)); return;
}); }
bridgeManager.addSessionClosedListener((uin) => { this.unsubscribeSessions?.();
this.onSessionClosed(uin); this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) => {
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
},
closed: (uin) => this.onSessionClosed(uin),
}); });
} }
@@ -208,22 +207,16 @@ export class OneBotManager {
/** Live OneBot adapter status for active accounts plus failed retiring /** Live OneBot adapter status for active accounts plus failed retiring
* generations. A zombie that still owns a port must remain observable. */ * generations. A zombie that still owns a port must remain observable. */
getConnectionStatuses(): AccountConnections[] { getConnectionStatuses(): AccountConnections[] {
const visible = [...this.instances.values()]; const visible = new Set([...this.instances.values(), ...this.retiringInstances]);
const connections = [...visible].map((instance) => {
for (const instance of this.retiringInstances) { const migration = this.databaseMigrations.get(instance.uin);
if (!visible.includes(instance)) { return {
visible.push(instance); uin: instance.uin,
} nickname: instance.nickname,
} adapters: instance.getConnectionStatuses(),
...(migration ? { databaseMigration: migration.state } : {}),
const connections = visible.map((instance) => ({ };
uin: instance.uin, });
nickname: instance.nickname,
adapters: instance.getConnectionStatuses(),
...(this.databaseMigrations.get(instance.uin)?.state
? { databaseMigration: this.databaseMigrations.get(instance.uin)?.state }
: {}),
}));
const activeUins = new Set(this.instances.keys()); const activeUins = new Set(this.instances.keys());
@@ -288,10 +281,13 @@ export class OneBotManager {
} }
this.disposed = true; this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const migration of this.databaseMigrations.values()) { const migrations = [...this.databaseMigrations.values()];
migration.cancelled = true; this.databaseMigrations.clear();
for (const migration of migrations) {
if (migration.retryTimer) { if (migration.retryTimer) {
clearTimeout(migration.retryTimer); clearTimeout(migration.retryTimer);
} }
@@ -299,8 +295,6 @@ export class OneBotManager {
migration.task.cancel(); migration.task.cancel();
} }
this.databaseMigrations.clear();
for (const instance of this.instances.values()) { for (const instance of this.instances.values()) {
this.retiringInstances.add(instance); this.retiringInstances.add(instance);
} }
@@ -389,7 +383,7 @@ export class OneBotManager {
const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin); const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin);
if (retiring.length > 0) { if (retiring.length > 0) {
const pending = { bridge, cancelled: false }; const pending = { bridge };
this.pendingStarts.set(uin, pending); this.pendingStarts.set(uin, pending);
this.trackLifecycle( this.trackLifecycle(
`session handoff UIN=${uin}`, `session handoff UIN=${uin}`,
@@ -410,16 +404,21 @@ export class OneBotManager {
bridge, bridge,
task: this.createDatabaseMigrationTask(uin), task: this.createDatabaseMigrationTask(uin),
state: preparingMigrationState(), state: preparingMigrationState(),
ready: false,
cancelled: false,
rowsPerSecond: null as number | null, rowsPerSecond: null as number | null,
retryTimer: null as NodeJS.Timeout | null, retryTimer: null as NodeJS.Timeout | null,
}; };
this.databaseMigrations.set(uin, migration); this.databaseMigrations.set(uin, migration);
const startTask = (): void => { const startTask = (): void => {
const task = migration.task;
const isCurrent = () =>
this.databaseMigrations.get(uin) === migration &&
migration.task === task &&
migration.state.phase !== 'failed' &&
migration.state.phase !== 'complete';
const handleFailure = (error: unknown, stage = 'database migration'): void => { const handleFailure = (error: unknown, stage = 'database migration'): void => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) { if (!isCurrent()) {
return; return;
} }
@@ -429,7 +428,6 @@ export class OneBotManager {
migration.state = { migration.state = {
...migration.state, ...migration.state,
phase: 'failed', phase: 'failed',
usable: migration.ready,
estimatedRemainingSeconds: null, estimatedRemainingSeconds: null,
error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`, error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`,
}; };
@@ -441,7 +439,7 @@ export class OneBotManager {
error instanceof Error ? (error.stack ?? error.message) : String(error), error instanceof Error ? (error.stack ?? error.message) : String(error),
); );
migration.task.cancel(); task.cancel();
if (!retryable || migration.retryTimer) { if (!retryable || migration.retryTimer) {
return; return;
@@ -450,23 +448,23 @@ export class OneBotManager {
migration.retryTimer = setTimeout(() => { migration.retryTimer = setTimeout(() => {
migration.retryTimer = null; migration.retryTimer = null;
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) { if (this.databaseMigrations.get(uin) !== migration) {
return; return;
} }
migration.task = this.createDatabaseMigrationTask(uin); migration.task = this.createDatabaseMigrationTask(uin);
migration.state = migration.ready migration.state = migration.state.usable
? { ...migration.state, phase: 'migrating', usable: true, error: undefined } ? { ...migration.state, phase: 'migrating', usable: true, error: undefined }
: preparingMigrationState(); : preparingMigrationState();
startTask(); startTask();
}, 5_000); }, 5_000);
migration.retryTimer.unref?.(); migration.retryTimer.unref();
}; };
try { try {
migration.task.start({ task.start({
onReady: () => { onReady: () => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) { if (!isCurrent()) {
return; return;
} }
@@ -477,7 +475,6 @@ export class OneBotManager {
return; return;
} }
migration.ready = true;
migration.state = { migration.state = {
...migration.state, ...migration.state,
phase: 'migrating', phase: 'migrating',
@@ -486,14 +483,14 @@ export class OneBotManager {
}; };
try { try {
migration.task.beginMigration(); task.beginMigration();
} catch (error) { } catch (error) {
handleFailure(error); handleFailure(error);
} }
}, },
onProgress: (status, elapsedMs) => { onProgress: (status, elapsedMs) => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) { if (!isCurrent()) {
return; return;
} }
@@ -511,7 +508,7 @@ export class OneBotManager {
migration.state = migrationPublicState(status, migration.rowsPerSecond); migration.state = migrationPublicState(status, migration.rowsPerSecond);
if (status.phase === 'complete') { if (status.phase === 'complete') {
migration.task.cancel(); task.cancel();
} }
}, },
@@ -628,26 +625,19 @@ export class OneBotManager {
const migration = this.databaseMigrations.get(uin); const migration = this.databaseMigrations.get(uin);
if (migration) { if (migration) {
migration.cancelled = true; this.databaseMigrations.delete(uin);
if (migration.retryTimer) { if (migration.retryTimer) {
clearTimeout(migration.retryTimer); clearTimeout(migration.retryTimer);
} }
migration.task.cancel(); migration.task.cancel();
this.databaseMigrations.delete(uin);
} }
const instance = this.instances.get(uin); const instance = this.instances.get(uin);
if (!instance) { if (!instance) {
const pending = this.pendingStarts.get(uin); this.pendingStarts.delete(uin);
if (pending) {
pending.cancelled = true;
this.pendingStarts.delete(uin);
}
return; return;
} }
@@ -678,13 +668,13 @@ export class OneBotManager {
private async releaseRetiringInstance( private async releaseRetiringInstance(
uin: string, uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean }, pending: { bridge: BridgeInterface },
instance: OneBotInstance, instance: OneBotInstance,
): Promise<void> { ): Promise<void> {
let timer: NodeJS.Timeout | undefined; let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => { const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs); timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
timer.unref?.(); timer.unref();
}); });
// Map rejection here so a dispose() that fails after the deadline still // Map rejection here so a dispose() that fails after the deadline still
@@ -704,7 +694,7 @@ export class OneBotManager {
); );
try { try {
instance.forceRelease?.(); instance.forceRelease();
} catch (error) { } catch (error) {
log.error( log.error(
'forced session release failed: UIN=%s: %s', 'forced session release failed: UIN=%s: %s',
@@ -734,7 +724,7 @@ export class OneBotManager {
private async finishRetiringBeforeStart( private async finishRetiringBeforeStart(
uin: string, uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean }, pending: { bridge: BridgeInterface },
retiring: OneBotInstance[], retiring: OneBotInstance[],
): Promise<void> { ): Promise<void> {
for (const instance of retiring) { for (const instance of retiring) {
@@ -748,7 +738,7 @@ export class OneBotManager {
this.pendingStarts.delete(uin); this.pendingStarts.delete(uin);
if (pending.cancelled || this.disposed) { if (this.disposed) {
return; return;
} }
@@ -37,7 +37,7 @@ export function waitPttTransText(key: string, timeoutMs: number): Promise<string
reject(new Error('语音转文字超时(未收到结果推送)')); reject(new Error('语音转文字超时(未收到结果推送)'));
}, timeoutMs); }, timeoutMs);
timer.unref?.(); timer.unref();
pending.set(key, { resolve, reject, timer }); pending.set(key, { resolve, reject, timer });
}); });
} }
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger'; import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler'; import type { ApiHandler } from '../api-handler';
import { import {
@@ -220,7 +221,3 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
this.onConfigReplaced(next); this.onConfigReplaced(next);
} }
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+18 -33
View File
@@ -1,4 +1,5 @@
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import { errorMessage } from '@snowluma/common/errors';
import { assertValidOneBotConfig } from '../config'; import { assertValidOneBotConfig } from '../config';
import { buildDispatchPayload } from '../event-filter'; import { buildDispatchPayload } from '../event-filter';
import type { import type {
@@ -67,11 +68,9 @@ export class OneBotNetworkManager {
private readonly adapters = new Map<string, ManagedAdapter>(); private readonly adapters = new Map<string, ManagedAdapter>();
private readonly factory: NetworkAdapterFactory | null; private readonly factory: NetworkAdapterFactory | null;
private operationTail: Promise<void> = Promise.resolve(); private operationTail: Promise<void> = Promise.resolve();
private acceptingReconciles = true; private accepting = true;
private acceptingEvents = true;
private readonly inFlightEmits = new Set<Promise<void>>(); private readonly inFlightEmits = new Set<Promise<void>>();
private shutdownPromise: Promise<NetworkShutdownResult> | null = null; private shutdownPromise: Promise<NetworkShutdownResult> | null = null;
private shutdownResult: NetworkShutdownResult | null = null;
/** Debug-stream taps — notified for every emitted event regardless of adapter /** Debug-stream taps — notified for every emitted event regardless of adapter
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */ * state. Attached on-demand (ref-counted) by the WebUI debug stream. */
@@ -92,7 +91,7 @@ export class OneBotNetworkManager {
/** Test/embedding seam for pre-built adapters. Production topology changes /** Test/embedding seam for pre-built adapters. Production topology changes
* go through reconcile(), which refuses duplicate names. */ * go through reconcile(), which refuses duplicate names. */
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void { register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
if (!this.acceptingReconciles) { if (!this.accepting) {
throw new Error('network manager is shutting down'); throw new Error('network manager is shutting down');
} }
@@ -163,17 +162,16 @@ export class OneBotNetworkManager {
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> { reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
const desired = this.compileDesiredPlan(config); const desired = this.compileDesiredPlan(config);
if (!this.acceptingReconciles) { if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down')); return Promise.reject(new Error('network manager is shutting down'));
} }
return this.enqueue(() => this.reconcileNow(desired)); return this.enqueue(() => this.reconcileNow(desired));
} }
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and /** Open registered adapters in order and report each failure. */
* reports each failure instead of hiding it in a detached Promise. */
openAll(): Promise<NetworkReconcileResult> { openAll(): Promise<NetworkReconcileResult> {
if (!this.acceptingReconciles) { if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down')); return Promise.reject(new Error('network manager is shutting down'));
} }
@@ -195,7 +193,7 @@ export class OneBotNetworkManager {
} }
closeOne(name: string): Promise<void> { closeOne(name: string): Promise<void> {
if (!this.acceptingReconciles) { if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down')); return Promise.reject(new Error('network manager is shutting down'));
} }
@@ -214,16 +212,11 @@ export class OneBotNetworkManager {
/** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish /** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish
* first; calls made after shutdown is requested fail immediately. */ * first; calls made after shutdown is requested fail immediately. */
shutdown(): Promise<NetworkShutdownResult> { shutdown(): Promise<NetworkShutdownResult> {
if (this.shutdownResult?.closed) {
return Promise.resolve(this.shutdownResult);
}
if (this.shutdownPromise) { if (this.shutdownPromise) {
return this.shutdownPromise; return this.shutdownPromise;
} }
this.acceptingReconciles = false; this.accepting = false;
this.acceptingEvents = false;
const attempt = this.enqueue(async () => { const attempt = this.enqueue(async () => {
const errors: NetworkApplyError[] = []; const errors: NetworkApplyError[] = [];
const dispatches = await Promise.allSettled([...this.inFlightEmits]); const dispatches = await Promise.allSettled([...this.inFlightEmits]);
@@ -232,7 +225,7 @@ export class OneBotNetworkManager {
if (dispatch.status === 'rejected') { if (dispatch.status === 'rejected') {
log.error( log.error(
'in-flight event dispatch failed during shutdown: %s', 'in-flight event dispatch failed during shutdown: %s',
errMessage(dispatch.reason), errorMessage(dispatch.reason),
); );
} }
} }
@@ -255,8 +248,9 @@ export class OneBotNetworkManager {
this.shutdownPromise = attempt; this.shutdownPromise = attempt;
void attempt.then( void attempt.then(
(result) => { (result) => {
this.shutdownResult = result.closed ? result : null; if (!result.closed) {
this.shutdownPromise = null; this.shutdownPromise = null;
}
}, },
() => { () => {
this.shutdownPromise = null; this.shutdownPromise = null;
@@ -265,27 +259,22 @@ export class OneBotNetworkManager {
return attempt; return attempt;
} }
closeAll(): Promise<NetworkShutdownResult> {
return this.shutdown();
}
/** Best-effort immediate release. Does not wait for the operation queue, /** Best-effort immediate release. Does not wait for the operation queue,
* in-flight dispatches, or peer close handshakes. */ * in-flight dispatches, or peer close handshakes. */
forceRelease(): void { forceRelease(): void {
this.acceptingReconciles = false; this.accepting = false;
this.acceptingEvents = false;
for (const { adapter } of this.adapters.values()) { for (const { adapter } of this.adapters.values()) {
try { try {
adapter.forceClose(); adapter.forceClose();
} catch (error) { } catch (error) {
log.error('forced adapter release failed: %s', errMessage(error)); log.error('forced adapter release failed: %s', errorMessage(error));
} }
} }
} }
emitEvent(event: JsonObject): Promise<void> { emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) { if (!this.accepting) {
return Promise.reject( return Promise.reject(
new Error('network manager is shutting down; event dispatch rejected'), new Error('network manager is shutting down; event dispatch rejected'),
); );
@@ -313,7 +302,7 @@ export class OneBotNetworkManager {
try { try {
cb(event); cb(event);
} catch (error) { } catch (error) {
log.warn('debug subscriber error: %s', errMessage(error)); log.warn('debug subscriber error: %s', errorMessage(error));
} }
} }
} }
@@ -337,7 +326,7 @@ export class OneBotNetworkManager {
Promise.resolve() Promise.resolve()
.then(() => adapter.onEvent(event, payload)) .then(() => adapter.onEvent(event, payload))
.catch((error) => { .catch((error) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error)); log.warn('adapter [%s] onEvent error: %s', adapter.name, errorMessage(error));
log.trace(() => [ log.trace(() => [
'report_target_failed target=%s error=%s', 'report_target_failed target=%s error=%s',
adapter.name, adapter.name,
@@ -549,7 +538,7 @@ export class OneBotNetworkManager {
name, name,
kind, kind,
phase, phase,
message: errMessage(error), message: errorMessage(error),
at: Date.now(), at: Date.now(),
...(restored === undefined ? {} : { restored }), ...(restored === undefined ? {} : { restored }),
}; };
@@ -575,7 +564,3 @@ export class OneBotNetworkManager {
return result; return result;
} }
} }
function errMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+4 -8
View File
@@ -46,11 +46,7 @@ export function rawDataToString(
return Buffer.from(new Uint8Array(raw)).toString('utf8'); return Buffer.from(new Uint8Array(raw)).toString('utf8');
} }
if (ArrayBuffer.isView(raw)) { return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
} }
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void { export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
@@ -156,7 +152,7 @@ export function startHeartbeat(
onDead(); onDead();
} }
}, opts.intervalMs); }, opts.intervalMs);
timer.unref?.(); timer.unref();
function stop(): void { function stop(): void {
if (stopped) { if (stopped) {
@@ -165,8 +161,8 @@ export function startHeartbeat(
stopped = true; stopped = true;
clearInterval(timer); clearInterval(timer);
socket.off?.('pong', onActivity); socket.off('pong', onActivity);
socket.off?.('message', onActivity); socket.off('message', onActivity);
} }
return stop; return stop;
@@ -26,8 +26,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private reconnectTimer: NodeJS.Timeout | null = null; private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions; private options: EventReportOptions;
private role: WsRole; private role: WsRole;
private explicitlyClosed = false;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>(); private readonly inFlightActions = new Set<Promise<void>>();
// Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it // Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it
// immediately instead of waiting for the deferred 'close' event. The per-socket // immediately instead of waiting for the deferred 'close' event. The per-socket
@@ -42,37 +40,23 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
} }
open(): void { open(): void {
if (this.isEnabled) { if (this.isEnabled || !this.willEnable(this.config)) {
return; return;
} }
if (this.config.enabled === false) {
return;
}
if (!this.config.url) {
return;
}
this.explicitlyClosed = false;
this.isEnabled = true; this.isEnabled = true;
try { try {
this.connect(); this.connect();
this.acceptingActions = true;
this.clearApplyFailure(); this.clearApplyFailure();
} catch (error) { } catch (error) {
this.isEnabled = false; this.isEnabled = false;
this.explicitlyClosed = true;
this.acceptingActions = false;
this.recordTransportFailure(error); this.recordTransportFailure(error);
throw error; throw error;
} }
} }
override forceClose(): void { override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false; this.isEnabled = false;
this.connected = false; this.connected = false;
this.cancelReconnect(); this.cancelReconnect();
@@ -91,8 +75,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
} }
async close(): Promise<void> { async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false; this.isEnabled = false;
this.connected = false; this.connected = false;
this.cancelReconnect(); this.cancelReconnect();
@@ -156,7 +138,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
} }
private connect(): void { private connect(): void {
if (this.explicitlyClosed) { if (!this.isEnabled) {
return; return;
} }
@@ -200,7 +182,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
socket, socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED }, { intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => { () => {
if (this.explicitlyClosed || !this.isEnabled) { if (!this.isEnabled) {
return; return;
} }
@@ -265,7 +247,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
this.socket = null; this.socket = null;
this.connected = false; this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) { if (!this.isEnabled) {
return; return;
} }
@@ -287,7 +269,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
return; return;
} }
if (this.explicitlyClosed) { if (!this.isEnabled) {
return; return;
} }
@@ -298,13 +280,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
const timer = setTimeout(() => { const timer = setTimeout(() => {
this.reconnectTimer = null; this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) { if (!this.isEnabled) {
return; return;
} }
this.connect(); this.connect();
}, interval); }, interval);
timer.unref?.(); timer.unref();
this.reconnectTimer = timer; this.reconnectTimer = timer;
} }
@@ -338,7 +320,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
} }
private trackInboundAction(start: () => Promise<void>): void { private trackInboundAction(start: () => Promise<void>): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) { if (!this.isEnabled || this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name); this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
return; return;
} }
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import fs from 'node:fs'; import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
@@ -254,10 +255,6 @@ function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT'; return error instanceof Error && 'code' in error && error.code === 'ENOENT';
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function assertManagedDirectory(directory: string, stat: fs.Stats): void { function assertManagedDirectory(directory: string, stat: fs.Stats): void {
if (stat.isSymbolicLink()) { if (stat.isSymbolicLink()) {
throw new Error(`managed stream directory must not be a symbolic link: ${directory}`); throw new Error(`managed stream directory must not be a symbolic link: ${directory}`);
@@ -199,6 +199,44 @@ describe('RKeyCache.resolveImageUrl', () => {
}); });
}); });
describe('RKeyCache.resolveMediaUrl', () => {
it.each([
['video', false, 12],
['video', true, 22],
['record', false, 14],
['record', true, 24],
['file', false, 10],
['file', true, 20],
] as const)('signs %s media (group=%s) with rkey type %s', async (type, isGroup, expected) => {
const { bridge } = makeBridge(async () =>
[10, 20, 12, 22, 14, 24].map((type) => ({
rkey: `?rkey=key/${type}`,
type,
ttlSeconds: 3600,
createTime: nowSec(),
})),
);
const cache = new RKeyCache();
const url = 'https://multimedia.nt.qq.com.cn/download?fileid=MEDIA';
expect(await cache.resolveMediaUrl(bridge as never, { type, url }, isGroup)).toBe(
`${url}&rkey=key%2F${expected}`,
);
});
it('preserves signed, unrelated, and absent URLs without fetching', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
for (const url of ['', 'https://example.com/video', `${NT_IMAGE_URL}&rkey=existing`]) {
expect(await cache.resolveMediaUrl(bridge as never, { type: 'video', url }, true)).toBe(
url,
);
}
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
});
});
describe('RKeyCache remote fallback (#156)', () => { describe('RKeyCache remote fallback (#156)', () => {
const SERVER = 'https://rkey.example/r'; const SERVER = 'https://rkey.example/r';
@@ -76,6 +76,70 @@ describe('database migration estimates', () => {
}); });
describe('OneBotManager database preparation', () => { describe('OneBotManager database preparation', () => {
it('releases its session subscription before shutdown and cannot bind after disposal', async () => {
const first = vi.fn();
const second = vi.fn();
const source = {
subscribeSessions: vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second),
};
const manager = new OneBotManager();
manager.bind(source);
manager.bind(source);
expect(first).toHaveBeenCalledOnce();
expect(second).not.toHaveBeenCalled();
const disposed = manager.dispose();
expect(second).toHaveBeenCalledOnce();
await disposed;
await manager.dispose();
manager.bind(source);
expect(second).toHaveBeenCalledOnce();
expect(source.subscribeSessions).toHaveBeenCalledTimes(2);
});
it.each(['logout', 'dispose'] as const)(
'invalidates migration callbacks before cancelling the task on %s',
async (reason) => {
vi.useFakeTimers();
let callbacks!: DatabaseMigrationCallbacks;
const cancel = vi.fn(() => {
callbacks.onFailed(new Error('cancelled task'));
callbacks.onProgress({ phase: 'complete', processed: 1, total: 1 }, 100);
});
const createTask = vi.fn(() => ({
start: (next: DatabaseMigrationCallbacks) => {
callbacks = next;
},
beginMigration: vi.fn(),
cancel,
}));
const manager = new OneBotManager({ createDatabaseMigrationTask: createTask });
const lifecycle = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
try {
lifecycle.onSessionStarted('10001', fakeBridge() as never);
if (reason === 'logout') {
lifecycle.onSessionClosed('10001');
} else {
await manager.dispose();
}
expect(manager.getConnectionStatuses()).toEqual([]);
expect(cancel).toHaveBeenCalledOnce();
vi.advanceTimersByTime(10_000);
expect(createTask).toHaveBeenCalledOnce();
} finally {
await manager.dispose();
vi.useRealTimers();
}
},
);
it('detaches migration and network startup from the login operation', () => { it('detaches migration and network startup from the login operation', () => {
let callbacks!: DatabaseMigrationCallbacks; let callbacks!: DatabaseMigrationCallbacks;
const observedRequestIds: Array<number | undefined> = []; const observedRequestIds: Array<number | undefined> = [];
@@ -104,11 +168,11 @@ describe('OneBotManager database preparation', () => {
}); });
let startListener!: (uin: string, bridge: never) => void; let startListener!: (uin: string, bridge: never) => void;
manager.bind({ manager.bind({
addSessionStartedListener: (listener) => { subscribeSessions: (listener) => {
startListener = listener; startListener = listener.started!;
return vi.fn();
}, },
addSessionClosedListener: vi.fn(), });
} as never);
const bridge = fakeBridge(new Promise(() => undefined)); const bridge = fakeBridge(new Promise(() => undefined));
runWithRequestId(5201, () => startListener('10001', bridge as never)); runWithRequestId(5201, () => startListener('10001', bridge as never));
@@ -449,10 +513,20 @@ describe('OneBotManager database preparation', () => {
usable: false, usable: false,
error: '数据库迁移失败:private detail;将自动重试', error: '数据库迁移失败:private detail;将自动重试',
}); });
const failed = manager.getConnectionStatuses()[0].databaseMigration;
callbacks[0].onProgress({ phase: 'complete', processed: 10, total: 10 }, 100);
callbacks[0].onFailed(new Error('duplicate failure'));
expect(manager.getConnectionStatuses()[0].databaseMigration).toBe(failed);
expect(tasks[0].cancel).toHaveBeenCalledOnce();
vi.advanceTimersByTime(5_000); vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2); expect(tasks).toHaveLength(2);
expect(tasks[1].start).toHaveBeenCalledOnce(); expect(tasks[1].start).toHaveBeenCalledOnce();
const preparing = manager.getConnectionStatuses()[0].databaseMigration;
callbacks[0].onProgress({ phase: 'complete', processed: 10, total: 10 }, 100);
callbacks[0].onFailed(new Error('obsolete task failure'));
expect(manager.getConnectionStatuses()[0].databaseMigration).toBe(preparing);
expect(tasks[1].cancel).not.toHaveBeenCalled();
internals.onSessionClosed('10001'); internals.onSessionClosed('10001');
callbacks[1].onFailed(new Error('late failure')); callbacks[1].onFailed(new Error('late failure'));
@@ -240,7 +240,7 @@ describe('OneBotNetworkManager', () => {
expect(mgr.hasActiveAdapters()).toBe(true); expect(mgr.hasActiveAdapters()).toBe(true);
}); });
it('closeAll clears every adapter', async () => { it('shutdown clears every adapter', async () => {
const mgr = new OneBotNetworkManager(); const mgr = new OneBotNetworkManager();
const a = makeAdapter('a'); const a = makeAdapter('a');
const b = makeAdapter('b'); const b = makeAdapter('b');
@@ -248,7 +248,7 @@ describe('OneBotNetworkManager', () => {
mgr.register(b); mgr.register(b);
await mgr.openAll(); await mgr.openAll();
await mgr.closeAll(); await mgr.shutdown();
expect(mgr.list()).toHaveLength(0); expect(mgr.list()).toHaveLength(0);
expect(a.closes).toBe(1); expect(a.closes).toBe(1);
expect(b.closes).toBe(1); expect(b.closes).toBe(1);
@@ -262,11 +262,11 @@ describe('OneBotNetworkManager', () => {
expect(mgr.hasActiveAdapters()).toBe(false); expect(mgr.hasActiveAdapters()).toBe(false);
await mgr.openAll(); await mgr.openAll();
expect(mgr.hasActiveAdapters()).toBe(true); expect(mgr.hasActiveAdapters()).toBe(true);
await mgr.closeAll(); await mgr.shutdown();
expect(mgr.hasActiveAdapters()).toBe(false); expect(mgr.hasActiveAdapters()).toBe(false);
}); });
it('rejects compatibility registration after shutdown', async () => { it('rejects new registration after shutdown', async () => {
const mgr = new OneBotNetworkManager(); const mgr = new OneBotNetworkManager();
await mgr.shutdown(); await mgr.shutdown();
@@ -288,6 +288,7 @@ describe('OneBotNetworkManager', () => {
const emitting = mgr.emitEvent(SAMPLE_EVENT); const emitting = mgr.emitEvent(SAMPLE_EVENT);
const closing = mgr.shutdown(); const closing = mgr.shutdown();
expect(mgr.shutdown()).toBe(closing);
await expect(mgr.emitEvent(SAMPLE_EVENT)).rejects.toThrow(/shutting down/); await expect(mgr.emitEvent(SAMPLE_EVENT)).rejects.toThrow(/shutting down/);
await Promise.resolve(); await Promise.resolve();
await Promise.resolve(); await Promise.resolve();
@@ -296,6 +297,7 @@ describe('OneBotNetworkManager', () => {
release(); release();
await emitting; await emitting;
await closing; await closing;
expect(mgr.shutdown()).toBe(closing);
expect(adapter.closes).toBe(1); expect(adapter.closes).toBe(1);
}); });
}); });
+28 -68
View File
@@ -1,12 +1,12 @@
import { errorMessage } from '@snowluma/common/errors';
import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
import crypto from 'crypto'; import crypto from 'crypto';
import fs from 'fs'; import fs from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const log = createLogger('Highway.Audio'); const log = createLogger('Highway.Audio');
export interface FFmpegVideoInfo { export interface FFmpegVideoInfo {
@@ -42,46 +42,10 @@ interface FFmpegNativeAddon {
let cachedAddon: FFmpegNativeAddon | null = null; let cachedAddon: FFmpegNativeAddon | null = null;
let cachedLoadError: string | null = null; let cachedLoadError: string | null = null;
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function addonFileName(): string { function addonFileName(): string {
return `ffmpegAddon.${process.platform}.${process.arch}.node`; return `ffmpegAddon.${process.platform}.${process.arch}.node`;
} }
function addonSearchDirs(): string[] {
// Mirrors the hook injector's resolution strategy so the addon is found
// regardless of whether we're running from:
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
// the dist root.
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
// __dirname is `packages/core/src/bridge/highway` — four levels deep
// under `packages/`. Note: the hook injector lives at
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
return [
path.resolve(__dirname, 'native', 'ffmpeg'),
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
];
}
function resolveAddonPath(): string | null {
const fileName = addonFileName();
for (const dir of addonSearchDirs()) {
const full = path.join(dir, fileName);
if (fs.existsSync(full)) {
return full;
}
}
return null;
}
/** /**
* Load the ffmpegAddon once and return a cached instance. * Load the ffmpegAddon once and return a cached instance.
* Throws on first-use failure; subsequent calls replay the same error message * Throws on first-use failure; subsequent calls replay the same error message
@@ -96,7 +60,7 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
throw new Error(cachedLoadError); throw new Error(cachedLoadError);
} }
const addonPath = resolveAddonPath(); const addonPath = resolveRuntimeNativePath(path.join('ffmpeg', addonFileName()));
if (!addonPath) { if (!addonPath) {
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`; cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
@@ -121,19 +85,14 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
* a ready-to-upload silk file. * a ready-to-upload silk file.
*/ */
export function isSilkFile(filePath: string): boolean { export function isSilkFile(filePath: string): boolean {
try { const fd = fs.openSync(filePath, 'r');
const fd = fs.openSync(filePath, 'r');
try { try {
const buf = Buffer.alloc(10); const buf = Buffer.alloc(10);
fs.readSync(fd, buf, 0, 10, 0); fs.readSync(fd, buf, 0, 10, 0);
const header = buf.toString(); return buf.toString().includes('#!SILK');
return header.includes('#!SILK') || header.includes('\x02#!SILK'); } finally {
} finally { fs.closeSync(fd);
fs.closeSync(fd);
}
} catch {
return false;
} }
} }
@@ -153,33 +112,34 @@ export interface EncodeSilkResult {
*/ */
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> { export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
const addon = getFFmpegAddon(); const addon = getFFmpegAddon();
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
// Already silk — trust the file, just measure duration via the addon.
if (isSilkFile(inputFile)) { if (isSilkFile(inputFile)) {
let duration = 1;
try {
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
} catch {
// getDuration on a silk file occasionally fails on certain encodings;
// the upload path only needs a rough, non-zero value, so fall back
// to the size-based heuristic used by NapCat's audio.ts.
const stat = fs.statSync(inputFile);
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
}
return { path: inputFile, duration, converted: false }; return { path: inputFile, duration, converted: false };
} }
fs.mkdirSync(tempDir, { recursive: true }); fs.mkdirSync(tempDir, { recursive: true });
const outPath = path.join(tempDir, crypto.randomUUID()); const outPath = path.join(tempDir, crypto.randomUUID());
await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) { try {
throw new Error('convertToNTSilkTct produced no output file'); await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) {
throw new Error('convertToNTSilkTct produced no output file');
}
} catch (error) {
try {
await fs.promises.rm(outPath, { force: true });
} catch (cleanupError) {
throw new AggregateError(
[error, cleanupError],
`SILK conversion failed: ${errorMessage(error)}; temporary file cleanup failed: ${errorMessage(cleanupError)}`,
);
}
throw error;
} }
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
return { path: outPath, duration, converted: true }; return { path: outPath, duration, converted: true };
} }
+2 -5
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger'; import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
import type { import type {
EncodableMediaMsgInfo, EncodableMediaMsgInfo,
@@ -136,10 +137,6 @@ function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
.join(';')}]`; .join(';')}]`;
} }
function mediaErrorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
// ─────────────── main entrypoint ─────────────── // ─────────────── main entrypoint ───────────────
/** /**
@@ -191,7 +188,7 @@ export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespB
label, label,
failureReason, failureReason,
params.uploads.length, params.uploads.length,
mediaErrorText(error), errorMessage(error),
Date.now() - startedAt, Date.now() - startedAt,
]); ]);
throw error; throw error;
+1 -1
View File
@@ -1766,7 +1766,7 @@ export class IdentityService {
this.recordPersistenceFailure('retry', error), this.recordPersistenceFailure('retry', error),
); );
}, delay); }, delay);
this.retryTimer_.unref?.(); this.retryTimer_.unref();
} }
private flushPendingWrites(scheduleRetry = true): Promise<void> { private flushPendingWrites(scheduleRetry = true): Promise<void> {
@@ -0,0 +1,86 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/common/native-path', () => ({
resolveRuntimeNativePath: () => '/test/ffmpeg.node',
}));
const addon = {
getDuration: vi.fn<(file: string) => Promise<number>>(),
convertToNTSilkTct: vi.fn<(input: string, output: string) => Promise<void>>(),
};
let root: string;
beforeEach(() => {
vi.resetModules();
addon.getDuration.mockReset().mockResolvedValue(2.5);
addon.convertToNTSilkTct.mockReset().mockImplementation(async (_input, output) => {
await fs.promises.writeFile(output, '\x02#!SILK_V3payload');
});
vi.spyOn(process, 'dlopen').mockImplementation((module) => {
(module as { exports: object }).exports = addon;
});
root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-encode-silk-'));
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(root, { recursive: true, force: true });
});
describe('SILK encoding', () => {
it('rejects unreadable files instead of treating them as a different audio format', async () => {
const { isSilkFile } = await import('../../src/highway/ffmpeg-addon');
expect(() => isSilkFile(path.join(root, 'missing'))).toThrow(/ENOENT/);
});
it('keeps native duration failures visible instead of guessing from SILK file size', async () => {
const input = path.join(root, 'invalid.silk');
fs.writeFileSync(input, '#!SILK_V3truncated');
const failure = new Error('truncated SILK packet');
addon.getDuration.mockRejectedValue(failure);
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).rejects.toBe(failure);
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
expect(fs.readdirSync(root)).toEqual(['invalid.silk']);
});
it('reuses a valid SILK input without creating a temporary file', async () => {
const input = path.join(root, 'voice.silk');
fs.writeFileSync(input, '\x02#!SILK_V3payload');
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).resolves.toEqual({
path: input,
duration: 3,
converted: false,
});
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
});
it('returns the converted file for caller-owned cleanup', async () => {
const input = path.join(root, 'voice.wav');
fs.writeFileSync(input, 'RIFF');
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
const result = await encodeSilk(input, root);
expect(result.converted).toBe(true);
expect(result.duration).toBe(3);
expect(fs.readFileSync(result.path, 'utf8')).toBe('\x02#!SILK_V3payload');
expect(addon.convertToNTSilkTct).toHaveBeenCalledWith(input, result.path);
});
it('removes partial output when native conversion fails, preserving the source and error', async () => {
const input = path.join(root, 'voice.wav');
fs.writeFileSync(input, 'RIFF');
const failure = new Error('conversion interrupted');
addon.convertToNTSilkTct.mockImplementation(async (_input, output) => {
await fs.promises.writeFile(output, 'partial');
throw failure;
});
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).rejects.toBe(failure);
expect(fs.readdirSync(root)).toEqual(['voice.wav']);
expect(fs.readFileSync(input, 'utf8')).toBe('RIFF');
});
});
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon'; import { convertAudioBytes, encodeSilk } from '@snowluma/protocol/highway/ffmpeg-addon';
interface NativeAudioAddon { interface NativeAudioAddon {
convertToNTSilkTct(inputFile: string, outputFile: string): Promise<void>; convertToNTSilkTct(inputFile: string, outputFile: string): Promise<void>;
@@ -111,9 +111,20 @@ describeBundledAddon('bundled native ffmpeg addon', () => {
); );
await expect(addon.getDuration(recordPath)).rejects.toThrow(/Invalid data/); await expect(addon.getDuration(recordPath)).rejects.toThrow(/Invalid data/);
await expect(encodeSilk(recordPath, tmpDir)).rejects.toThrow(/Invalid data/);
}); });
}); });
it('encodes a WAV with the runtime addon when started from the protocol package', async () => {
const wavPath = path.join(tmpDir, 'runtime-input.wav');
writeFileSync(wavPath, makeMonoWav());
const result = await encodeSilk(wavPath, tmpDir);
expect(result.converted).toBe(true);
expect(result.duration).toBe(1);
expect(readFileSync(result.path).subarray(1, 10).toString('ascii')).toBe('#!SILK_V3');
expect(await loadBundledAddon().getDuration(result.path)).toBeCloseTo(1, 6);
});
it('converts a mono QQ-style SILK record to a decodable MP3 through the public transcode seam', async () => { it('converts a mono QQ-style SILK record to a decodable MP3 through the public transcode seam', async () => {
const addon = loadBundledAddon(); const addon = loadBundledAddon();
const wavPath = path.join(tmpDir, 'mono-input.wav'); const wavPath = path.join(tmpDir, 'mono-input.wav');
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -5
View File
@@ -64,11 +64,7 @@ export function rawToString(value: unknown): string {
return value; return value;
} }
if (value instanceof ArrayBuffer) { if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value); return new TextDecoder().decode(value);
} }
+15 -9
View File
@@ -12,12 +12,19 @@ export function createRequestAbortState(
externalSignal?: AbortSignal, externalSignal?: AbortSignal,
): RequestAbortState { ): RequestAbortState {
const controller = new AbortController(); const controller = new AbortController();
let timedOut = false; let abortedBy: 'timeout' | 'external' | null = null;
let externallyAborted = false;
const abort = (source: 'timeout' | 'external', reason?: unknown): void => {
if (abortedBy !== null) {
return;
}
abortedBy = source;
controller.abort(reason);
};
const onExternalAbort = (): void => { const onExternalAbort = (): void => {
externallyAborted = true; abort('external', externalSignal?.reason);
controller.abort(externalSignal?.reason);
}; };
if (externalSignal?.aborted) { if (externalSignal?.aborted) {
@@ -29,8 +36,7 @@ export function createRequestAbortState(
const timer = const timer =
timeoutMs > 0 timeoutMs > 0
? setTimeout(() => { ? setTimeout(() => {
timedOut = true; abort('timeout');
controller.abort();
}, timeoutMs) }, timeoutMs)
: null; : null;
@@ -44,10 +50,10 @@ export function createRequestAbortState(
externalSignal?.removeEventListener('abort', onExternalAbort); externalSignal?.removeEventListener('abort', onExternalAbort);
}, },
isTimedOut() { isTimedOut() {
return timedOut; return abortedBy === 'timeout';
}, },
isExternallyAborted() { isExternallyAborted() {
return externallyAborted || externalSignal?.aborted === true; return abortedBy === 'external';
}, },
}; };
} }
@@ -63,7 +69,7 @@ export function isAbortError(error: unknown): boolean {
typeof error === 'object' && typeof error === 'object' &&
error !== null && error !== null &&
'name' in error && 'name' in error &&
(error as { name?: unknown }).name === 'AbortError' error.name === 'AbortError'
); );
} }
+41
View File
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createRequestAbortState } from '../src/internal/abort';
afterEach(() => vi.useRealTimers());
describe('request cancellation', () => {
it('keeps caller cancellation as the cause when the timeout expires later', () => {
vi.useFakeTimers();
const caller = new AbortController();
const request = createRequestAbortState(100, caller.signal);
caller.abort('caller canceled');
vi.advanceTimersByTime(100);
expect(request.signal.reason).toBe('caller canceled');
expect(request.isExternallyAborted()).toBe(true);
expect(request.isTimedOut()).toBe(false);
request.cleanup();
});
it('keeps the timeout as the cause when the caller cancels later', () => {
vi.useFakeTimers();
const caller = new AbortController();
const request = createRequestAbortState(100, caller.signal);
vi.advanceTimersByTime(100);
caller.abort();
expect(request.isTimedOut()).toBe(true);
expect(request.isExternallyAborted()).toBe(false);
request.cleanup();
});
it('stops observing timeouts and caller cancellation after cleanup', () => {
vi.useFakeTimers();
const caller = new AbortController();
const request = createRequestAbortState(100, caller.signal);
request.cleanup();
caller.abort();
vi.advanceTimersByTime(100);
expect(request.signal.aborted).toBe(false);
expect(request.isTimedOut()).toBe(false);
expect(request.isExternallyAborted()).toBe(false);
});
});
@@ -1,10 +1,3 @@
// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json):
// rkey fallback servers + the music-card signing URL. Same UX as the other
// settings panels — debounced auto-save, no explicit save button. Unlike the
// channel editor these are typed inline, so the server's normalized result is
// NOT written back onto the inputs while editing (that would erase a half-typed
// URL); the store reconciles on the next load. Invalid entries are flagged
// client-side and simply dropped by the server on save.
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { AlertTriangle, KeyRound, Music, Plus, RefreshCw, Trash2 } from 'lucide-react'; import { AlertTriangle, KeyRound, Music, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { SkeletonSwap } from '@/components/interior/skeleton-swap';
@@ -33,20 +26,17 @@ export function GlobalConfigPanel() {
const { runAction } = useActionFeedback(); const { runAction } = useActionFeedback();
const [config, setConfig] = useState<GlobalSettings | null>(null); const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const { msg, flash } = useFlashMessage(); const { msg, flash } = useFlashMessage();
const saveTimer = useRef<number | null>(null); const saveTimer = useRef<number | null>(null);
const saveGen = useRef(0); const saveGen = useRef(0);
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
setLoadFailed(false);
try { try {
setConfig(await api.globalConfig.get()); setConfig(await api.globalConfig.get());
} catch (error) { } catch (error) {
console.error('load global config failed', error); console.error('load global config failed', error);
setLoadFailed(true);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -65,9 +55,7 @@ export function GlobalConfigPanel() {
[], [],
); );
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the // Keep partially typed URLs in the draft until the next load.
* inputs from the server's normalized response (it would wipe a half-typed
* URL); a generation guard just confirms the latest save. */
const commit = ( const commit = (
next: GlobalSettings, next: GlobalSettings,
feedback: false | { title: string; successTitle: string } = { feedback: false | { title: string; successTitle: string } = {
@@ -83,6 +71,7 @@ export function GlobalConfigPanel() {
} }
saveTimer.current = window.setTimeout(() => { saveTimer.current = window.setTimeout(() => {
saveTimer.current = null;
const dropped = const dropped =
next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) || next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) ||
(next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim())); (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
@@ -92,7 +81,6 @@ export function GlobalConfigPanel() {
: runAction( : runAction(
{ {
title: feedback.title, title: feedback.title,
detail: '正在同步 config/snowluma.json',
successTitle: feedback.successTitle, successTitle: feedback.successTitle,
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步', successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
errorTitle: '全局配置更新失败', errorTitle: '全局配置更新失败',
@@ -105,8 +93,6 @@ export function GlobalConfigPanel() {
return; return;
} }
// The server drops invalid (non-http) entries; say so rather than a
// bare "已保存" next to a still-visible rejected value.
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存'); flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
}) })
.catch((error) => { .catch((error) => {
@@ -130,7 +116,7 @@ export function GlobalConfigPanel() {
label="全局配置" label="全局配置"
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''} className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
> >
{!loading && (loadFailed || !config) ? ( {!loading ? (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground"> <div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} /> <AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">加载全局配置失败</p> <p className="text-sm">加载全局配置失败</p>
@@ -162,13 +148,8 @@ export function GlobalConfigPanel() {
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground"> <div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
<KeyRound className="mt-0.5 size-3.5 shrink-0" /> <KeyRound className="mt-0.5 size-3.5 shrink-0" />
<p> <p>
图片 / 文件下载链接需要服务器签发的{' '} 内核无法获取 <code className="font-mono">rkey</code>{' '}
<code className="font-mono">rkey</code>。SnowLuma 默认走内核获取; 时,依次请求下列服务器。留空关闭,建议使用自建服务。
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
<strong className="font-medium text-foreground/80">
默认留空=关闭
</strong>
,不配置就不会联系任何第三方。 建议填你自建的端点。
</p> </p>
</div> </div>
@@ -186,7 +167,7 @@ export function GlobalConfigPanel() {
{servers.length === 0 ? ( {servers.length === 0 ? (
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground"> <p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
未配置回退服务器(rkey 回退已关闭) 回退服务器未启用
</p> </p>
) : ( ) : (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
@@ -235,7 +216,7 @@ export function GlobalConfigPanel() {
<code className="font-mono"> <code className="font-mono">
{'{ group_rkey, private_rkey, expired_time }'} {'{ group_rkey, private_rkey, expired_time }'}
</code> </code>
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。 ,仅支持 HTTP(S)。
</p> </p>
</div> </div>
)} )}
@@ -268,9 +249,6 @@ export function GlobalConfigPanel() {
)} )}
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })} onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
/> />
<p className="text-xs leading-relaxed text-muted-foreground">
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
</p>
</div> </div>
</div> </div>
@@ -1,7 +1,3 @@
// Settings → 通知 tab. Mirrors the node-config UX: the first screen is
// info-only cards (name / url / template + an inline enable toggle); creating
// and editing always go through a dialog. All changes auto-save (debounced),
// like the per-account config page — no explicit save button.
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { motion } from 'motion/react'; import { motion } from 'motion/react';
import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates'; import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
@@ -61,6 +57,7 @@ export function NotificationsPanel() {
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
setMsg(null);
try { try {
setConfig(await api.notifications.getConfig()); setConfig(await api.notifications.getConfig());
@@ -102,6 +99,7 @@ export function NotificationsPanel() {
} }
saveTimer.current = window.setTimeout(() => { saveTimer.current = window.setTimeout(() => {
saveTimer.current = null;
void runAction( void runAction(
{ {
title: copy.title, title: copy.title,
@@ -123,6 +121,10 @@ export function NotificationsPanel() {
flash('ok', '已保存'); flash('ok', '已保存');
}) })
.catch((error) => { .catch((error) => {
if (saveGen.current !== gen) {
return;
}
console.error('save notifications config failed', error); console.error('save notifications config failed', error);
flash('err', '保存失败,请检查服务器日志'); flash('err', '保存失败,请检查服务器日志');
}); });
@@ -1,35 +1,11 @@
import { createContext, useContext, type ReactNode } from 'react'; import { createContext, useContext, type ReactNode } from 'react';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types'; import type { UpdateInfo } from '@/types';
import type { AppResourceData, AppResources } from '@/lib/app-resources';
import type { HookProcessOps } from '@/hooks/use-hook-process-ops'; import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
export interface ResourceLoadState { export interface AppStateValue extends AppResourceData {
ready: boolean;
error: string | null;
}
export interface AppResourceState {
qqList: ResourceLoadState;
processList: ResourceLoadState;
systemInfo: ResourceLoadState;
connections: ResourceLoadState;
updateInfo: ResourceLoadState;
}
/**
* Live mutable state owned by AppLayout and shared with the child route
* components rendered inside its `<Outlet />`. Pages used to receive these
* via prop drilling — now they pull from context so adding a new page does
* not touch AppLayout.
*/
export interface AppStateValue {
qqList: QQInfo[];
processList: HookProcessInfo[];
systemInfo: SystemInfo | null;
connections: AccountConnections[];
/** Advisory update-availability info; null until the first check resolves. */
updateInfo: UpdateInfo | null;
/** Distinguishes an empty result from an unresolved or failed initial read. */ /** Distinguishes an empty result from an unresolved or failed initial read. */
resources: AppResourceState; resources: AppResources;
selectedUin: string | null; selectedUin: string | null;
setSelectedUin: (uin: string | null) => void; setSelectedUin: (uin: string | null) => void;
processOps: HookProcessOps; processOps: HookProcessOps;
@@ -1,13 +1,9 @@
import { createContext, useContext, type ReactNode } from 'react'; import { createContext, useContext, type ReactNode } from 'react';
/** /** Session state shared by the authentication boundary and routed pages. */
* Auth-level state surfaced into the router subtree. `AuthBoundary` mints
* this and `AppLayout` consumes it — used to drive the status badge and to
* complete logout after page-local state has been cleared.
*/
export interface SessionValue { export interface SessionValue {
status: string; status: string;
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */ /** Ends the session and unmounts its page state. */
onLogoutComplete: () => void; onLogoutComplete: () => void;
/** Replays the first-run wizard without changing persisted account state. */ /** Replays the first-run wizard without changing persisted account state. */
restartOnboarding: () => void; restartOnboarding: () => void;
+4 -88
View File
@@ -228,7 +228,6 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
export const FONT_CUSTOM_ID = 'custom'; export const FONT_CUSTOM_ID = 'custom';
const LS_CACHE = 'snowluma_ui_appearance'; const LS_CACHE = 'snowluma_ui_appearance';
const LS_MIGRATED = 'snowluma_ui_migrated';
const TOKEN_KEY = 'snowluma_token'; const TOKEN_KEY = 'snowluma_token';
// ─── Colour helpers (custom hex accent → readable foreground) ────────────── // ─── Colour helpers (custom hex accent → readable foreground) ──────────────
@@ -1012,61 +1011,6 @@ async function persistAppearance(appearance: UiAppearance): Promise<void> {
} }
} }
// ─── Migration of the pre-server-config localStorage theme ─────────────────
function readLegacyOverlay(): Partial<UiAppearance> | null {
try {
const out: Partial<UiAppearance> = {};
const mode = localStorage.getItem('snowluma_theme');
if (mode === 'light' || mode === 'dark' || mode === 'system') {
out.mode = mode;
}
const accent = localStorage.getItem('snowluma_accent');
if (accent && ACCENTS.some((a) => a.id === accent)) {
out.accentMode = 'preset';
out.accentPreset = accent;
}
const radius = Number(localStorage.getItem('snowluma_radius'));
if (Number.isFinite(radius) && radius > 0 && radius <= 2) {
out.radius = radius;
}
const density = localStorage.getItem('snowluma_density');
if (density === 'cozy' || density === 'compact') {
out.density = density;
}
const poll = Number(localStorage.getItem('snowluma_poll_interval'));
if (Number.isFinite(poll) && poll >= 0 && poll <= 60_000) {
out.pollInterval = poll;
}
return Object.keys(out).length > 0 ? out : null;
} catch {
return null;
}
}
function isPristine(a: UiAppearance): boolean {
const d = DEFAULT_APPEARANCE;
return (
a.mode === d.mode &&
a.accentMode === d.accentMode &&
a.accentPreset === d.accentPreset &&
a.radius === d.radius &&
a.density === d.density &&
a.pollInterval === d.pollInterval &&
a.background.type === 'none'
);
}
// ─── Light/dark reveal (View Transitions API) ────────────────────────────── // ─── Light/dark reveal (View Transitions API) ──────────────────────────────
// Where the user last clicked, so the theme reveal emanates from there. // Where the user last clicked, so the theme reveal emanates from there.
let lastPointer: { x: number; y: number } | null = null; let lastPointer: { x: number; y: number } | null = null;
@@ -1149,7 +1093,7 @@ interface ThemeContextValue {
/** Re-fetch appearance from the server (e.g. after login, so the authed /** Re-fetch appearance from the server (e.g. after login, so the authed
* `customCss` loads). */ * `customCss` loads). */
reloadAppearance: () => Promise<void>; reloadAppearance: () => Promise<void>;
// ── back-compat conveniences ── // Common appearance controls.
mode: ThemeMode; mode: ThemeMode;
setMode: (m: ThemeMode) => void; setMode: (m: ThemeMode) => void;
pollInterval: number; pollInterval: number;
@@ -1190,7 +1134,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
return () => mq.removeEventListener('change', handler); return () => mq.removeEventListener('change', handler);
}, []); }, []);
// Initial server load (+ one-time legacy migration). Runs once. // Load the server appearance, retaining the cache if it is unavailable.
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
@@ -1201,34 +1145,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
return; return;
} }
let next = server ?? readCache(); const next = server ?? readCache();
let migrated = true;
try {
migrated = Boolean(localStorage.getItem(LS_MIGRATED));
} catch {
/* storage unavailable: skip migration */
}
if (!migrated) {
try {
localStorage.setItem(LS_MIGRATED, '1');
} catch {
/* ignore */
}
const legacy = readLegacyOverlay();
// Only migrate when the server has never been customized, so we don't
// clobber a look already set from another device.
if (legacy && server && isPristine(server)) {
next = { ...server, ...legacy, background: server.background };
void persistAppearance(next).catch((error) => {
console.error('appearance migration save failed', error);
});
}
}
setAppearanceState(next); setAppearanceState(next);
writeCache(next); writeCache(next);
@@ -1256,8 +1173,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
applyBackgroundLayer(appearance); applyBackgroundLayer(appearance);
}, [appearance]); }, [appearance]);
// Flush a pending debounced save on unmount (defensive — the provider lives // Cancel a pending save when the provider unmounts.
// at the app root and normally never unmounts).
useEffect( useEffect(
() => () => { () => () => {
if (saveTimer.current) { if (saveTimer.current) {
@@ -0,0 +1,45 @@
import { useEffect, useMemo, useSyncExternalStore } from 'react';
import { useApi } from '@/lib/api';
import { createAppResources } from '@/lib/app-resources';
import { startPolling } from '@/lib/polling';
export function useAppResources(pollInterval: number) {
const api = useApi();
const store = useMemo(() => createAppResources(api), [api]);
const resources = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
useEffect(() => {
const dispose = api.stateStream({ onEvent: store.onEvent });
return () => {
dispose();
store.invalidate();
};
}, [api, store]);
// Reconcile SSE resources periodically; system metrics keep the faster cadence.
useEffect(
() =>
startPolling(
store.reconcile,
pollInterval > 0 ? Math.max(pollInterval * 10, 10_000) : 0,
),
[pollInterval, store],
);
useEffect(() => startPolling(store.refreshSystem, pollInterval), [pollInterval, store]);
useEffect(() => startPolling(store.refreshUpdate, 6 * 60 * 60 * 1000, false), [store]);
return {
qqList: resources.qqList.data,
processList: resources.processList.data,
systemInfo: resources.systemInfo.data,
connections: resources.connections.data,
updateInfo: resources.updateInfo.data,
resources,
refreshQqList: store.refreshQqList,
refreshProcesses: store.refreshProcesses,
refreshSystem: store.refreshSystem,
refreshConnections: store.refreshConnections,
refreshUpdate: store.refreshUpdate,
};
}
+18 -222
View File
@@ -1,237 +1,33 @@
// Debug contacts data layer — lazy-loads friend / group / member lists for the import { useEffect, useMemo, useSyncExternalStore } from 'react';
// debug console's pickers via the read-only OneBot actions, with a shared
// module-level cache persisted to localStorage (version-stamped) and a short
// TTL. Every loader degrades gracefully: on error the hook returns the error so
// the Picker can fall back to raw input. One cache is shared across every
// picker instance (tester form, message builder, etc.).
import { useCallback, useEffect, useRef, useState } from 'react';
import { useApi } from '@/lib/api'; import { useApi } from '@/lib/api';
import type { PickerOption } from '@/components/ui/picker'; import { createContactList, type ContactKind } from '@/lib/debug-contacts';
const CACHE_VERSION = 1; // bump to invalidate all persisted entries export { userAvatar, groupAvatar } from '@/lib/debug-contacts';
const TTL_MS = 5 * 60_000;
const LS_KEY = `snowluma.debug.contacts.v${CACHE_VERSION}`;
export function userAvatar(uin: string | number): string { function useContactList(kind: ContactKind, uin: string, groupId = '') {
return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
}
export function groupAvatar(gid: string | number): string {
return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
}
interface Entry {
at: number;
items: PickerOption[];
}
// Avatars are derivable from the id + the list kind (encoded in the cache-key
// prefix), so they're stripped before persisting (a big member list × long
// avatar URLs would otherwise blow the ~5MB localStorage quota and silently
// kill persistence for ALL entries) and regenerated on hydrate.
function avatarFor(key: string, value: string): string | undefined {
if (key.startsWith('groups:')) {
return groupAvatar(value);
}
if (key.startsWith('friends:') || key.startsWith('members:')) {
return userAvatar(value);
}
return undefined;
}
// ── shared cache (module-level, hydrated from localStorage once) ──
const mem = new Map<string, Entry>();
let hydrated = false;
function hydrate(): void {
if (hydrated) {
return;
}
hydrated = true;
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) {
const obj = JSON.parse(raw) as Record<string, Entry>;
for (const [k, v] of Object.entries(obj)) {
if (v && Array.isArray(v.items)) {
mem.set(k, {
at: v.at,
items: v.items.map((it) => ({
...it,
avatar: it.avatar ?? avatarFor(k, it.value),
})),
});
}
}
}
} catch {
/* corrupt / unavailable — start empty */
}
}
function persist(): void {
try {
const obj: Record<string, Entry> = {};
// Strip the derivable avatar to keep the serialized blob small.
for (const [k, v] of mem) {
obj[k] = {
at: v.at,
items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })),
};
}
localStorage.setItem(LS_KEY, JSON.stringify(obj));
} catch {
/* quota / unavailable — memory cache still works */
}
}
type ParseRow = (row: Record<string, unknown>) => PickerOption | null;
interface ListState {
items: PickerOption[];
loading: boolean;
error: string | null;
refresh: () => void;
}
function useContactList(
cacheKey: string | null,
action: string,
uin: string,
params: Record<string, unknown>,
parse: ParseRow,
): ListState {
const api = useApi(); const api = useApi();
hydrate(); const store = useMemo(
const [items, setItems] = useState<PickerOption[]>( () => createContactList(api.debug.invoke, kind, uin, groupId),
() => (cacheKey && mem.get(cacheKey)?.items) || [], [api, kind, uin, groupId],
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const reqId = useRef(0);
const load = useCallback(
async (force: boolean) => {
if (!cacheKey || !uin) {
return;
}
const cached = mem.get(cacheKey);
if (!force && cached && Date.now() - cached.at < TTL_MS) {
setItems(cached.items);
return;
}
const myId = ++reqId.current;
setLoading(true);
setError(null);
try {
const res = await api.debug.invoke(uin, action, params);
if (myId !== reqId.current) {
return;
} // superseded
if (res.status !== 'ok') {
throw new Error(res.message || res.wording || '加载失败');
}
const arr = Array.isArray(res.data) ? (res.data as Record<string, unknown>[]) : [];
const mapped = arr.map(parse).filter((x): x is PickerOption => x !== null);
mem.set(cacheKey, { at: Date.now(), items: mapped });
persist();
setItems(mapped);
} catch (e) {
if (myId !== reqId.current) {
return;
}
setError(e instanceof Error ? e.message : '加载失败');
// keep any stale items visible as a fallback
} finally {
if (myId === reqId.current) {
setLoading(false);
}
}
// params + parse are stable per call-site (their identity is captured by
// cacheKey, which already varies on uin/group), so excluding them is
// deliberate — including the fresh object/closure would reload every render.
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[api, cacheKey, uin, action],
); );
const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
useEffect(() => { useEffect(() => {
if (!cacheKey || !uin) { void store.refresh(false);
setItems([]); return store.invalidate;
return; }, [store]);
}
const cached = mem.get(cacheKey); return { ...state, refresh: () => void store.refresh() };
// Clear stale items when switching to an uncached key — otherwise the picker
// would show the previous account/group's contacts as valid until the fetch
// returns (a member-selection hazard).
setItems(cached ? cached.items : []);
void load(false);
}, [cacheKey, uin, load]);
return { items, loading, error, refresh: () => void load(true) };
} }
export function useFriends(uin: string): ListState { export function useFriends(uin: string) {
return useContactList(uin ? `friends:${uin}` : null, 'get_friend_list', uin, {}, (r) => { return useContactList('friends', uin);
const id = r.user_id;
if (id == null) {
return null;
}
const v = String(id);
const nick = (r.remark as string) || (r.nickname as string) || v;
return { value: v, label: nick, sub: v, avatar: userAvatar(v) };
});
} }
export function useGroups(uin: string): ListState { export function useGroups(uin: string) {
return useContactList(uin ? `groups:${uin}` : null, 'get_group_list', uin, {}, (r) => { return useContactList('groups', uin);
const id = r.group_id;
if (id == null) {
return null;
}
const v = String(id);
return { value: v, label: (r.group_name as string) || v, sub: v, avatar: groupAvatar(v) };
});
} }
export function useGroupMembers(uin: string, groupId: string): ListState { export function useGroupMembers(uin: string, groupId: string) {
const gid = groupId.trim(); return useContactList('members', uin, groupId.trim());
return useContactList(
uin && gid ? `members:${uin}:${gid}` : null,
'get_group_member_list',
uin,
{ group_id: gid },
(r) => {
const id = r.user_id;
if (id == null) {
return null;
}
const v = String(id);
const name = (r.card as string) || (r.nickname as string) || v;
return { value: v, label: name, sub: v, avatar: userAvatar(v) };
},
);
} }
+25 -32
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
export type FlashKind = 'ok' | 'err'; export type FlashKind = 'ok' | 'err';
export interface FlashMessage { export interface FlashMessage {
@@ -6,45 +6,38 @@ export interface FlashMessage {
text: string; text: string;
} }
/** /** `flash` expires automatically; `setMsg` replaces it with a persistent message. */
* Transient status-banner state for a settings panel.
*
* - `flash(kind, text)` shows a message that auto-clears after `durationMs`,
* cancelling any prior auto-clear timer first.
* - `setMsg` sets/clears the message directly (a persistent one that stays
* until the next action — e.g. a load-failure banner).
* - The pending timer is cleared on unmount.
*
* Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` +
* unmount cleanup, which had drifted (one panel omitted the ref, the
* prior-timer cancel, and the unmount cleanup entirely — leaking a timer that
* could fire a stale `setMsg` after unmount).
*/
export function useFlashMessage(durationMs = 2400): { export function useFlashMessage(durationMs = 2400): {
msg: FlashMessage | null; msg: FlashMessage | null;
flash: (kind: FlashKind, text: string) => void; flash: (kind: FlashKind, text: string) => void;
setMsg: (msg: FlashMessage | null) => void; setMsg: (msg: FlashMessage | null) => void;
} { } {
const [msg, setMsg] = useState<FlashMessage | null>(null); const [msg, setMessage] = useState<FlashMessage | null>(null);
const timer = useRef<number | null>(null); const timer = useRef<number | null>(null);
useEffect( const cancelTimer = useCallback(() => {
() => () => { if (timer.current !== null) {
if (timer.current) {
clearTimeout(timer.current);
}
},
[],
);
const flash = (kind: FlashKind, text: string) => {
setMsg({ kind, text });
if (timer.current) {
clearTimeout(timer.current); clearTimeout(timer.current);
} }
timer.current = window.setTimeout(() => setMsg(null), durationMs); timer.current = null;
}; }, []);
useEffect(() => cancelTimer, [cancelTimer]);
const setMsg = useCallback(
(next: FlashMessage | null) => {
cancelTimer();
setMessage(next);
},
[cancelTimer],
);
const flash = useCallback(
(kind: FlashKind, text: string) => {
setMsg({ kind, text });
timer.current = window.setTimeout(() => {
timer.current = null;
setMessage(null);
}, durationMs);
},
[durationMs, setMsg],
);
return { msg, flash, setMsg }; return { msg, flash, setMsg };
} }
@@ -3,12 +3,7 @@ import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import type { OneBotConfig, QQInfo } from '@/types'; import type { OneBotConfig, QQInfo } from '@/types';
import { useApi } from '@/lib/api'; import { useApi } from '@/lib/api';
/** /** Account-scoped editing, persistence, and unsaved-change confirmation. */
* Per-UIN OneBotInstance configuration editor. Owns the full lifecycle:
* selection, load, in-memory edit (with dirty tracking), save (with refetch),
* and a "switch UIN while dirty" guard that surfaces a pending switch the
* view can confirm or cancel.
*/
export interface UseOneBotInstanceConfig { export interface UseOneBotInstanceConfig {
selectedUin: string | null; selectedUin: string | null;
/** Loaded config for the current UIN. Null while loading or before a selection. */ /** Loaded config for the current UIN. Null while loading or before a selection. */
@@ -19,11 +14,7 @@ export interface UseOneBotInstanceConfig {
setConfig: (next: OneBotConfig) => void; setConfig: (next: OneBotConfig) => void;
/** True if the in-memory config diverges from the last server-confirmed snapshot. */ /** True if the in-memory config diverges from the last server-confirmed snapshot. */
dirty: boolean; dirty: boolean;
/** /** Dirty edits require confirmation before switching accounts. */
* Request a UIN switch. If currently dirty, the switch is parked as
* `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it
* applies immediately.
*/
requestSwitchUin: (uin: string) => void; requestSwitchUin: (uin: string) => void;
/** Non-null while a switch is parked waiting for confirmation. */ /** Non-null while a switch is parked waiting for confirmation. */
pendingSwitchUin: string | null; pendingSwitchUin: string | null;
@@ -40,6 +31,14 @@ export interface UseOneBotInstanceConfig {
saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error'; saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error';
} }
type ConfigState =
| { status: 'idle'; uin: null }
| { status: 'loading'; uin: string }
| { status: 'error'; uin: string; error: string }
| { status: 'ready'; uin: string; config: OneBotConfig; savedSnapshot: string };
type SaveFeedback = { text: string; tone: UseOneBotInstanceConfig['saveStatusTone'] };
const IDLE_FEEDBACK: SaveFeedback = { text: '', tone: 'idle' };
const CLEAR_SAVE_STATUS_MS = 3000; const CLEAR_SAVE_STATUS_MS = 3000;
export interface UseOneBotInstanceConfigOptions { export interface UseOneBotInstanceConfigOptions {
@@ -56,19 +55,11 @@ export function useOneBotInstanceConfig(
const api = useApi(); const api = useApi();
const { runAction } = useActionFeedback(); const { runAction } = useActionFeedback();
const { onSelectedUinChange } = options; const { onSelectedUinChange } = options;
// Start the first config request in the same render that receives the account // Load the first account without waiting for selection to propagate upward.
// list; publishing the selection upward remains an effect, but no longer adds
// an otherwise unnecessary render before the network request can begin.
const selectedUin = options.selectedUin ?? accounts[0]?.uin ?? null; const selectedUin = options.selectedUin ?? accounts[0]?.uin ?? null;
const [config, setConfigState] = useState<OneBotConfig | null>(null); const [state, setState] = useState<ConfigState>({ status: 'idle', uin: null });
const [loadedUin, setLoadedUin] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [reloadGeneration, setReloadGeneration] = useState(0); const [reloadGeneration, setReloadGeneration] = useState(0);
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null); const [saveFeedback, setSaveFeedback] = useState<SaveFeedback>(IDLE_FEEDBACK);
const [saveStatus, setSaveStatus] = useState('');
const [saveStatusTone, setSaveStatusTone] =
useState<UseOneBotInstanceConfig['saveStatusTone']>('idle');
const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null); const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null);
const clearTimerRef = useRef<number | null>(null); const clearTimerRef = useRef<number | null>(null);
const editRevisionRef = useRef(0); const editRevisionRef = useRef(0);
@@ -93,23 +84,15 @@ export function useOneBotInstanceConfig(
clearTimerRef.current = null; clearTimerRef.current = null;
} }
setSaveStatus(''); setSaveFeedback(IDLE_FEEDBACK);
setSaveStatusTone('idle'); setPendingSwitchUin(null);
if (!selectedUin) { if (!selectedUin) {
setLoading(false); setState({ status: 'idle', uin: null });
setLoadError(null);
setConfigState(null);
setLoadedUin(null);
setSavedSnapshot(null);
return; return;
} }
setLoading(true); setState({ status: 'loading', uin: selectedUin });
setLoadError(null);
setConfigState(null);
setLoadedUin(null);
setSavedSnapshot(null);
let cancelled = false; let cancelled = false;
(async () => { (async () => {
@@ -121,24 +104,28 @@ export function useOneBotInstanceConfig(
} }
editRevisionRef.current += 1; editRevisionRef.current += 1;
setConfigState(loaded); setState({
setLoadedUin(selectedUin); status: 'ready',
setSavedSnapshot(JSON.stringify(loaded)); uin: selectedUin,
config: loaded,
savedSnapshot: JSON.stringify(loaded),
});
} catch (e) { } catch (e) {
console.error('load-config', e); console.error('load-config', e);
if (!cancelled) { if (!cancelled) {
setLoadError(e instanceof Error ? e.message : '加载账号配置失败'); setState({
} status: 'error',
} finally { uin: selectedUin,
if (!cancelled) { error: e instanceof Error ? e.message : '加载账号配置失败',
setLoading(false); });
} }
} }
})(); })();
return () => { return () => {
cancelled = true; cancelled = true;
saveGenerationRef.current += 1;
}; };
}, [selectedUin, api, reloadGeneration]); }, [selectedUin, api, reloadGeneration]);
@@ -151,9 +138,11 @@ export function useOneBotInstanceConfig(
[], [],
); );
const currentConfig = loadedUin === selectedUin ? config : null; const current = state.uin === selectedUin ? state : null;
const currentLoading = const currentConfig = current?.status === 'ready' ? current.config : null;
selectedUin !== null && (loading || (loadError === null && currentConfig === null)); const savedSnapshot = current?.status === 'ready' ? current.savedSnapshot : null;
const loading = selectedUin !== null && (!current || current.status === 'loading');
const loadError = current?.status === 'error' ? current.error : null;
const dirty = useMemo(() => { const dirty = useMemo(() => {
if (currentConfig == null || savedSnapshot == null) { if (currentConfig == null || savedSnapshot == null) {
@@ -163,10 +152,17 @@ export function useOneBotInstanceConfig(
return JSON.stringify(currentConfig) !== savedSnapshot; return JSON.stringify(currentConfig) !== savedSnapshot;
}, [currentConfig, savedSnapshot]); }, [currentConfig, savedSnapshot]);
const setConfig = useCallback((next: OneBotConfig) => { const setConfig = useCallback(
editRevisionRef.current += 1; (next: OneBotConfig) => {
setConfigState(next); editRevisionRef.current += 1;
}, []); setState((previous) =>
previous.status === 'ready' && previous.uin === selectedUin
? { ...previous, config: next }
: previous,
);
},
[selectedUin],
);
const reload = useCallback(() => setReloadGeneration((generation) => generation + 1), []); const reload = useCallback(() => setReloadGeneration((generation) => generation + 1), []);
const requestSwitchUin = useCallback( const requestSwitchUin = useCallback(
@@ -207,8 +203,7 @@ export function useOneBotInstanceConfig(
return; return;
} }
setSaveStatus(''); setSaveFeedback(IDLE_FEEDBACK);
setSaveStatusTone('idle');
}, CLEAR_SAVE_STATUS_MS); }, CLEAR_SAVE_STATUS_MS);
}, []); }, []);
@@ -223,8 +218,7 @@ export function useOneBotInstanceConfig(
const uin = selectedUin; const uin = selectedUin;
const editRevision = editRevisionRef.current; const editRevision = editRevisionRef.current;
const generation = ++saveGenerationRef.current; const generation = ++saveGenerationRef.current;
setSaveStatus('保存中...'); setSaveFeedback({ text: '保存中…', tone: 'saving' });
setSaveStatusTone('saving');
try { try {
const result = await runAction( const result = await runAction(
@@ -259,39 +253,49 @@ export function useOneBotInstanceConfig(
} }
if (!result.saved) { if (!result.saved) {
setSaveStatus(`保存失败:${result.message || '服务器未确认配置已保存'}`); setSaveFeedback({
setSaveStatusTone('error'); text: `保存失败:${result.message || '服务器未确认配置已保存'}`,
tone: 'error',
});
return; return;
} }
setSavedSnapshot(JSON.stringify(result.config)); const unchanged = editRevisionRef.current === editRevision;
setState((previous) =>
previous.status === 'ready' && previous.uin === uin
? {
...previous,
config: unchanged ? result.config : previous.config,
savedSnapshot: JSON.stringify(result.config),
}
: previous,
);
if (editRevisionRef.current === editRevision) { if (!unchanged) {
setConfigState(result.config); setSaveFeedback({ text: '上一版本已保存,当前修改待保存', tone: 'warning' });
} else {
setSaveStatus('上一版本已保存,当前修改仍待保存');
setSaveStatusTone('warning');
return; return;
} }
if (!result.online) { if (!result.online) {
setSaveStatus('保存成功;当前离线,将在下次连接时应用'); setSaveFeedback({ text: '已保存,下次连接时应用', tone: 'warning' });
setSaveStatusTone('warning');
} else if (result.applied) { } else if (result.applied) {
setSaveStatus('保存成功,热重载完成'); setSaveFeedback({ text: '已保存并应用', tone: 'success' });
setSaveStatusTone('success');
} else { } else {
const first = result.errors[0]?.message; const first = result.errors[0]?.message;
setSaveStatus(`保存成功,但热重载失败${first ? `:${first}` : ''}`); setSaveFeedback({
setSaveStatusTone('warning'); text: `已保存,但热重载失败${first ? `:${first}` : ''}`,
tone: 'warning',
});
} }
} catch (e) { } catch (e) {
if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) { if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) {
return; return;
} }
setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`); setSaveFeedback({
setSaveStatusTone('error'); text: `保存失败:${e instanceof Error ? e.message : '未知错误'}`,
tone: 'error',
});
} finally { } finally {
if (selectedUinRef.current === uin && saveGenerationRef.current === generation) { if (selectedUinRef.current === uin && saveGenerationRef.current === generation) {
scheduleStatusClear(uin, generation); scheduleStatusClear(uin, generation);
@@ -304,7 +308,7 @@ export function useOneBotInstanceConfig(
return { return {
selectedUin, selectedUin,
config: currentConfig, config: currentConfig,
loading: currentLoading, loading,
loadError, loadError,
reload, reload,
setConfig, setConfig,
@@ -314,7 +318,7 @@ export function useOneBotInstanceConfig(
confirmSwitch, confirmSwitch,
cancelSwitch, cancelSwitch,
save, save,
saveStatus, saveStatus: saveFeedback.text,
saveStatusTone, saveStatusTone: saveFeedback.tone,
}; };
} }
+156
View File
@@ -0,0 +1,156 @@
import type { ApiClient, StateStreamEvent } from '@/lib/api/types';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
export interface AppResourceData {
qqList: QQInfo[];
processList: HookProcessInfo[];
systemInfo: SystemInfo | null;
connections: AccountConnections[];
updateInfo: UpdateInfo | null;
}
export type AppResources = {
[K in keyof AppResourceData]: {
data: AppResourceData[K];
ready: boolean;
error: string | null;
};
};
type ResourceKey = keyof AppResourceData;
const LOAD_ERRORS: Record<ResourceKey, string> = {
qqList: '加载账号列表失败',
processList: '加载进程列表失败',
systemInfo: '加载系统信息失败',
connections: '加载连接状态失败',
updateInfo: '检查更新失败',
};
export function createAppResources(api: ApiClient) {
let snapshot: AppResources = {
qqList: { data: [], ready: false, error: null },
processList: { data: [], ready: false, error: null },
systemInfo: { data: null, ready: false, error: null },
connections: { data: [], ready: false, error: null },
updateInfo: { data: null, ready: false, error: null },
};
const revisions: Record<ResourceKey, number> = {
qqList: 0,
processList: 0,
systemInfo: 0,
connections: 0,
updateInfo: 0,
};
const listeners = new Set<() => void>();
function settle<K extends ResourceKey>(
key: K,
data: AppResourceData[K],
error: string | null = null,
) {
snapshot = { ...snapshot, [key]: { data, ready: true, error } };
listeners.forEach((listener) => listener());
}
async function refresh<K extends ResourceKey>(
key: K,
load: () => Promise<AppResourceData[K]>,
throwOnError = false,
): Promise<AppResourceData[K] | null> {
const revision = ++revisions[key];
try {
const data = await load();
if (revisions[key] !== revision) {
return null;
}
settle(key, data);
return data;
} catch (error) {
if (revisions[key] !== revision) {
return null;
}
const message =
error instanceof Error && error.message ? error.message : LOAD_ERRORS[key];
settle(key, snapshot[key].data, message);
if (throwOnError) {
throw error;
}
return null;
}
}
function publish<K extends ResourceKey>(key: K, data: AppResourceData[K]) {
// A pushed snapshot supersedes any pending REST response for this resource.
revisions[key] += 1;
settle(key, data);
}
const refreshQqList = async () => {
await refresh('qqList', () => api.qqList());
};
const refreshProcesses = async () => {
await refresh('processList', () => api.processes.list());
};
const refreshSystem = async () => {
await refresh('systemInfo', () => api.system());
};
const refreshConnections = async () => {
await refresh('connections', () => api.connections());
};
const refreshUpdate = (force = false) =>
refresh('updateInfo', () => api.update.check(force), force);
const reconcile = async () => {
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
};
return {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
invalidate: () => {
for (const key of Object.keys(revisions) as ResourceKey[]) {
revisions[key] += 1;
}
},
onEvent: (event: StateStreamEvent) => {
if ('resource' in event) {
switch (event.resource) {
case 'qq-list':
publish('qqList', event.data);
break;
case 'processes':
publish('processList', event.data);
break;
case 'connections':
publish('connections', event.data);
break;
}
} else if (event.kind === 'dropped') {
void reconcile();
}
},
reconcile,
refreshQqList,
refreshProcesses,
refreshSystem,
refreshConnections,
refreshUpdate,
};
}
+218
View File
@@ -0,0 +1,218 @@
import type { ApiClient } from '@/lib/api/types';
import type { PickerOption } from '@/components/ui/picker';
const TTL_MS = 5 * 60_000;
const LS_KEY = 'snowluma.debug.contacts.v1';
export function userAvatar(uin: string | number): string {
return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
}
export function groupAvatar(gid: string | number): string {
return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
}
interface Entry {
at: number;
items: PickerOption[];
}
// Rebuild avatar URLs rather than storing them for every member.
function avatarFor(key: string, value: string): string | undefined {
if (key.startsWith('groups:')) {
return groupAvatar(value);
}
if (key.startsWith('friends:') || key.startsWith('members:')) {
return userAvatar(value);
}
return undefined;
}
const mem = new Map<string, Entry>();
let hydrated = false;
function hydrate(): void {
if (hydrated) {
return;
}
hydrated = true;
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) {
const obj = JSON.parse(raw) as Record<string, Entry>;
for (const [k, v] of Object.entries(obj)) {
if (v && Array.isArray(v.items)) {
mem.set(k, {
at: v.at,
items: v.items.map((it) => ({
...it,
avatar: avatarFor(k, it.value),
})),
});
}
}
}
} catch {
/* corrupt / unavailable — start empty */
}
}
function persist(): void {
try {
const obj: Record<string, Entry> = {};
// Strip the derivable avatar to keep the serialized blob small.
for (const [k, v] of mem) {
obj[k] = {
at: v.at,
items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })),
};
}
localStorage.setItem(LS_KEY, JSON.stringify(obj));
} catch {
/* quota / unavailable — memory cache still works */
}
}
export type ContactKind = 'friends' | 'groups' | 'members';
export interface ContactListState {
items: PickerOption[];
loading: boolean;
error: string | null;
}
const ACTIONS: Record<ContactKind, string> = {
friends: 'get_friend_list',
groups: 'get_group_list',
members: 'get_group_member_list',
};
function parseContact(kind: ContactKind, row: unknown): PickerOption | null {
if (!row || typeof row !== 'object' || Array.isArray(row)) {
throw new Error('联系人列表格式无效');
}
const fields = row as Record<string, unknown>;
const id = kind === 'groups' ? fields.group_id : fields.user_id;
if (id == null) {
return null;
}
if (typeof id !== 'string' && typeof id !== 'number') {
throw new Error('联系人 ID 格式无效');
}
const value = String(id);
const names =
kind === 'groups'
? [fields.group_name]
: kind === 'friends'
? [fields.remark, fields.nickname]
: [fields.card, fields.nickname];
const label =
names.find((name): name is string => typeof name === 'string' && name !== '') ?? value;
return {
value,
label,
sub: value,
avatar: kind === 'groups' ? groupAvatar(value) : userAvatar(value),
};
}
export function createContactList(
invoke: ApiClient['debug']['invoke'],
kind: ContactKind,
uin: string,
groupId = '',
) {
hydrate();
const key =
uin && (kind !== 'members' || groupId)
? `${kind}:${uin}${kind === 'members' ? `:${groupId}` : ''}`
: null;
const cached = key ? mem.get(key) : undefined;
let state: ContactListState = { items: cached?.items ?? [], loading: false, error: null };
let revision = 0;
const listeners = new Set<() => void>();
function publish(next: ContactListState) {
state = next;
listeners.forEach((listener) => listener());
}
async function refresh(force = true): Promise<void> {
const request = ++revision;
if (!key) {
return;
}
const hit = mem.get(key);
if (!force && hit && Date.now() - hit.at < TTL_MS) {
publish({ items: hit.items, loading: false, error: null });
return;
}
publish({ ...state, loading: true, error: null });
try {
const result = await invoke(
uin,
ACTIONS[kind],
kind === 'members' ? { group_id: groupId } : {},
);
if (request !== revision) {
return;
}
if (result.status !== 'ok') {
throw new Error(result.message || result.wording || '加载失败');
}
if (!Array.isArray(result.data)) {
throw new Error('联系人列表格式无效');
}
const items = result.data
.map((row) => parseContact(kind, row))
.filter((item) => item !== null);
mem.set(key, { at: Date.now(), items });
persist();
publish({ items, loading: false, error: null });
} catch (error) {
if (request === revision) {
publish({
...state,
loading: false,
error: error instanceof Error ? error.message : '加载失败',
});
}
}
}
return {
getSnapshot: () => state,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
refresh,
invalidate: () => {
revision += 1;
},
};
}
+45
View File
@@ -0,0 +1,45 @@
/** Run immediately, then at the requested cadence without overlapping requests. */
export function startPolling(
refresh: () => Promise<unknown>,
intervalMs: number,
pauseWhenHidden = true,
): () => void {
let running = false;
const tick = async () => {
if (running || (pauseWhenHidden && document.hidden)) {
return;
}
running = true;
try {
await refresh();
} finally {
running = false;
}
};
void tick();
const interval = intervalMs > 0 ? setInterval(tick, intervalMs) : null;
const onVisible = () => {
if (!document.hidden) {
void tick();
}
};
if (pauseWhenHidden) {
document.addEventListener('visibilitychange', onVisible);
}
return () => {
if (interval !== null) {
clearInterval(interval);
}
if (pauseWhenHidden) {
document.removeEventListener('visibilitychange', onVisible);
}
};
}
+7 -390
View File
@@ -8,43 +8,12 @@ import { NAV_ITEMS } from '@/components/layout/sidebar';
import { ConfirmDialog } from '@/components/confirm-dialog'; import { ConfirmDialog } from '@/components/confirm-dialog';
import { LowIntegrityWarning } from '@/components/low-integrity-warning'; import { LowIntegrityWarning } from '@/components/low-integrity-warning';
import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { SkeletonSwap } from '@/components/interior/skeleton-swap';
import { AppStateProvider, type AppResourceState } from '@/contexts/AppStateContext'; import { AppStateProvider } from '@/contexts/AppStateContext';
import { useAppResources } from '@/hooks/use-app-resources';
import { KioskProvider } from '@/contexts/KioskContext'; import { KioskProvider } from '@/contexts/KioskContext';
import { LayoutProvider, useLayout } from '@/contexts/LayoutContext'; import { LayoutProvider, useLayout } from '@/contexts/LayoutContext';
import { useSession } from '@/contexts/SessionContext'; import { useSession } from '@/contexts/SessionContext';
import type { AppPath } from '@/router'; import type { AppPath } from '@/router';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
function createInitialResources(): AppResourceState {
return {
qqList: { ready: false, error: null },
processList: { ready: false, error: null },
systemInfo: { ready: false, error: null },
connections: { ready: false, error: null },
updateInfo: { ready: false, error: null },
};
}
type AppResourceKey = keyof AppResourceState;
function createResourceCounters(): Record<AppResourceKey, number> {
return {
qqList: 0,
processList: 0,
systemInfo: 0,
connections: 0,
updateInfo: 0,
};
}
interface ResourceRequestTicket {
generation: number;
streamRevision: number;
}
function errorMessage(error: unknown, fallback: string): string {
return error instanceof Error && error.message ? error.message : fallback;
}
/** /**
* Redirects to the operator's configured landing page once (after the layout * Redirects to the operator's configured landing page once (after the layout
@@ -79,12 +48,6 @@ function DefaultRouteRedirect() {
return null; return null;
} }
/**
* The layout route. Owns the live state shared across the four pages
* (polling lists, processOps, selectedUin) and renders `<Outlet />` inside
* the chrome. The unload-failed alert sits here so it survives navigation
* away from the overview page.
*/
export function AppLayout() { export function AppLayout() {
const api = useApi(); const api = useApi();
const { pollInterval, reloadAppearance } = useTheme(); const { pollInterval, reloadAppearance } = useTheme();
@@ -96,171 +59,9 @@ export function AppLayout() {
void reloadAppearance(); void reloadAppearance();
}, [reloadAppearance]); }, [reloadAppearance]);
const [qqList, setQqList] = useState<QQInfo[]>([]); const data = useAppResources(pollInterval);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]); const { connections, refreshProcesses, systemInfo } = data;
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [connections, setConnections] = useState<AccountConnections[]>([]);
const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
const [resources, setResources] = useState<AppResourceState>(createInitialResources);
const [selectedUin, setSelectedUin] = useState<string | null>(null); const [selectedUin, setSelectedUin] = useState<string | null>(null);
const requestGenerationRef = useRef(createResourceCounters());
const streamRevisionRef = useRef(createResourceCounters());
const settleResource = useCallback((resource: AppResourceKey, error: string | null) => {
setResources((current) => ({
...current,
[resource]: { ready: true, error },
}));
}, []);
const beginResourceRequest = useCallback(
(resource: AppResourceKey): ResourceRequestTicket => ({
generation: ++requestGenerationRef.current[resource],
streamRevision: streamRevisionRef.current[resource],
}),
[],
);
const isCurrentResourceRequest = useCallback(
(resource: AppResourceKey, ticket: ResourceRequestTicket): boolean =>
requestGenerationRef.current[resource] === ticket.generation &&
streamRevisionRef.current[resource] === ticket.streamRevision,
[],
);
const settleStreamResource = useCallback(
(resource: AppResourceKey) => {
streamRevisionRef.current[resource] += 1;
settleResource(resource, null);
},
[settleResource],
);
const refreshQqList = useCallback(async () => {
const ticket = beginResourceRequest('qqList');
try {
const next = await api.qqList();
if (!isCurrentResourceRequest('qqList', ticket)) {
return;
}
setQqList(next);
settleResource('qqList', null);
} catch (e) {
if (!isCurrentResourceRequest('qqList', ticket)) {
console.warn('ignored stale qq-list request failure', e);
return;
}
console.error('qq-list', e);
settleResource('qqList', errorMessage(e, '加载账号列表失败'));
}
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
const refreshProcesses = useCallback(async () => {
const ticket = beginResourceRequest('processList');
try {
const next = await api.processes.list();
if (!isCurrentResourceRequest('processList', ticket)) {
return;
}
setProcessList(next);
settleResource('processList', null);
} catch (e) {
if (!isCurrentResourceRequest('processList', ticket)) {
console.warn('ignored stale process-list request failure', e);
return;
}
console.error('processes', e);
settleResource('processList', errorMessage(e, '加载进程列表失败'));
}
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
const refreshSystem = useCallback(async () => {
const ticket = beginResourceRequest('systemInfo');
try {
const next = await api.system();
if (!isCurrentResourceRequest('systemInfo', ticket)) {
return;
}
setSystemInfo(next);
settleResource('systemInfo', null);
} catch (e) {
if (!isCurrentResourceRequest('systemInfo', ticket)) {
console.warn('ignored stale system-info request failure', e);
return;
}
console.error('system', e);
settleResource('systemInfo', errorMessage(e, '加载系统信息失败'));
}
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
const refreshConnections = useCallback(async () => {
const ticket = beginResourceRequest('connections');
try {
const next = await api.connections();
if (!isCurrentResourceRequest('connections', ticket)) {
return;
}
setConnections(next);
settleResource('connections', null);
} catch (e) {
if (!isCurrentResourceRequest('connections', ticket)) {
console.warn('ignored stale connections request failure', e);
return;
}
console.error('connections', e);
settleResource('connections', errorMessage(e, '加载连接状态失败'));
}
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
const refreshUpdate = useCallback(
async (force = false) => {
const ticket = beginResourceRequest('updateInfo');
try {
const next = await api.update.check(force);
if (!isCurrentResourceRequest('updateInfo', ticket)) {
return null;
}
setUpdateInfo(next);
settleResource('updateInfo', null);
return next;
} catch (e) {
if (!isCurrentResourceRequest('updateInfo', ticket)) {
console.warn('ignored stale update-check request failure', e);
return null;
}
console.error('update-check', e);
settleResource('updateInfo', errorMessage(e, '检查更新失败'));
if (force) {
throw e;
}
return null;
}
},
[api, beginResourceRequest, isCurrentResourceRequest, settleResource],
);
const { const {
ops: processOps, ops: processOps,
unloadFailedAlert, unloadFailedAlert,
@@ -269,182 +70,8 @@ export function AppLayout() {
onAfterOp: refreshProcesses, 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.
//
// On `{kind:'dropped'}` (backpressure made the server skip some frames),
// a per-resource SSE auto-recovery is NOT guaranteed: the next delivered
// frame is whatever resource next changes, not necessarily the one whose
// update we lost. So on dropped, kick a one-shot REST reconcile to
// recover immediately instead of waiting up to 30s for the fallback.
useEffect(() => {
const dispose = api.stateStream({
onEvent: (event) => {
if ('resource' in event) {
if (event.resource === 'processes') {
setProcessList(event.data);
settleStreamResource('processList');
} else if (event.resource === 'qq-list') {
setQqList(event.data);
settleStreamResource('qqList');
} else if (event.resource === 'connections') {
setConnections(event.data);
settleStreamResource('connections');
}
return;
}
if ('kind' in event && event.kind === 'dropped') {
// Fire-and-forget; each refresh has its own try/catch.
void refreshQqList();
void refreshProcesses();
void refreshConnections();
}
},
});
return () => {
dispose();
};
}, [api, refreshQqList, refreshProcesses, refreshConnections, settleStreamResource]);
// Slow reconcile fallback for the SSE-covered resources. SSE drops can
// be silent (proxy rewrites text/event-stream, tab thrashing). One REST
// tick per (pollInterval × 10, min 10s) recovers from those without
// hammering the server.
useEffect(() => {
let cancelled = false;
let running = false;
const reconcileMs = Math.max(pollInterval * 10, 10_000);
const tick = async () => {
// Skip while the tab is hidden — SSE already carries live updates, and a
// backgrounded tab has no UI to refresh. Re-tick on becoming visible.
// `running` drops a tick while the previous refresh is still in flight,
// so a slow backend can't stack overlapping requests.
if (cancelled || document.hidden || running) {
return;
}
running = true;
try {
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
} finally {
running = false;
}
};
// Initial tick primes the lists before the SSE handshake completes
// (avoids a flash of empty state in the chrome).
tick();
const interval = pollInterval > 0 ? setInterval(tick, reconcileMs) : null;
const onVisible = () => {
if (!document.hidden) {
void tick();
}
};
document.addEventListener('visibilitychange', onVisible);
return () => {
cancelled = true;
if (interval !== null) {
clearInterval(interval);
}
document.removeEventListener('visibilitychange', onVisible);
};
}, [pollInterval, refreshQqList, refreshProcesses, refreshConnections]);
// systemInfo has its OWN fast cadence — it carries live values (uptime,
// cpu loadAvg, memory.usagePercent, runtime.heapUsed) that the overview
// widget visibly animates. It isn't on the SSE feed, so a 30s reconcile
// would visibly lag the dashboard. Keep the user's configured
// pollInterval (default 3s) here.
useEffect(() => {
let cancelled = false;
let running = false;
const tick = async () => {
if (cancelled || document.hidden || running) {
return;
}
running = true;
try {
await refreshSystem();
} finally {
running = false;
}
};
tick();
const interval = pollInterval > 0 ? setInterval(tick, pollInterval) : null;
const onVisible = () => {
if (!document.hidden) {
void tick();
}
};
document.addEventListener('visibilitychange', onVisible);
return () => {
cancelled = true;
if (interval !== null) {
clearInterval(interval);
}
document.removeEventListener('visibilitychange', onVisible);
};
}, [pollInterval, refreshSystem]);
// Update check runs on its own slow cadence (6h), independent of the fast
// list-polling above — GitHub's API is rate-limited, the result rarely
// changes, and the server caches it anyway, so this is cheap.
useEffect(() => {
let running = false;
const tick = async () => {
if (running) {
return;
}
running = true;
try {
await refreshUpdate();
} finally {
running = false;
}
};
tick();
const id = setInterval(tick, 6 * 60 * 60 * 1000);
return () => clearInterval(id);
}, [refreshUpdate]);
const handleLogout = useCallback(async () => { const handleLogout = useCallback(async () => {
for (const resource of Object.keys(requestGenerationRef.current) as AppResourceKey[]) {
requestGenerationRef.current[resource] += 1;
streamRevisionRef.current[resource] += 1;
}
await api.logout(); await api.logout();
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setConnections([]);
setUpdateInfo(null);
setResources(createInitialResources());
setSelectedUin(null);
session.onLogoutComplete(); session.onLogoutComplete();
}, [api, session]); }, [api, session]);
@@ -486,7 +113,7 @@ export function AppLayout() {
className="border-b border-warning/25 bg-warning/10 px-4 py-2.5 text-sm text-warning-foreground sm:px-6 lg:px-8" className="border-b border-warning/25 bg-warning/10 px-4 py-2.5 text-sm text-warning-foreground sm:px-6 lg:px-8"
> >
<span className="font-medium">账号数据库状态:</span> <span className="font-medium">账号数据库状态:</span>
{parts.join(';')}。请查看概览详情。 {parts.join(';')}
</div> </div>
); );
}, [connections]); }, [connections]);
@@ -494,20 +121,10 @@ export function AppLayout() {
return ( return (
<AppStateProvider <AppStateProvider
value={{ value={{
qqList, ...data,
processList,
systemInfo,
connections,
updateInfo,
resources,
selectedUin, selectedUin,
setSelectedUin, setSelectedUin,
processOps, processOps,
refreshQqList,
refreshProcesses,
refreshSystem,
refreshConnections,
refreshUpdate,
onLogout: handleLogout, onLogout: handleLogout,
}} }}
> >
@@ -541,7 +158,7 @@ export function AppLayout() {
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p> <p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p> <p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
<p className="mt-2 text-sm text-muted-foreground"> <p className="mt-2 text-sm text-muted-foreground">
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。 如需彻底卸载,请重启 QQ。
</p> </p>
</> </>
) : null ) : null
+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
import { createAppResources } from '../src/lib/app-resources';
import type { QQInfo } from '../src/types';
function setup() {
const api = createApiClient({ tokenStore: { load: () => null, save: () => undefined } });
vi.spyOn(api, 'qqList').mockResolvedValue([]);
vi.spyOn(api.processes, 'list').mockResolvedValue([]);
vi.spyOn(api, 'connections').mockResolvedValue([]);
return { api, store: createAppResources(api) };
}
const accounts: QQInfo[] = [{ uin: '12345', nickname: '当前账号' }];
describe('app resources', () => {
it('publishes data and load status together, distinguishing an empty result from an initial load', async () => {
const { store } = setup();
const initial = store.getSnapshot();
expect(initial.qqList).toEqual({ data: [], ready: false, error: null });
const listener = vi.fn(() => {
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
});
const unsubscribe = store.subscribe(listener);
await store.refreshQqList();
expect(listener).toHaveBeenCalledOnce();
expect(initial.qqList.ready).toBe(false);
unsubscribe();
await store.refreshQqList();
expect(listener).toHaveBeenCalledOnce();
});
it('keeps the latest request when an older request completes later', async () => {
const { api, store } = setup();
const old = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(old.promise).mockResolvedValueOnce(accounts);
const first = store.refreshQqList();
await store.refreshQqList();
old.resolve([]);
await first;
expect(store.getSnapshot().qqList.data).toEqual(accounts);
});
it.each(['success', 'failure'])(
'keeps a pushed snapshot after a stale REST %s',
async (outcome) => {
const { api, store } = setup();
const request = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
const pending = store.refreshQqList();
store.onEvent({ resource: 'qq-list', data: accounts });
const snapshot = store.getSnapshot();
if (outcome === 'success') {
request.resolve([]);
} else {
request.reject(new Error('过期请求失败'));
}
await pending;
expect(store.getSnapshot()).toBe(snapshot);
expect(snapshot.qqList).toEqual({ data: accounts, ready: true, error: null });
},
);
it('does not invalidate a different resource when receiving a push', async () => {
const { api, store } = setup();
vi.mocked(api.qqList).mockResolvedValueOnce(accounts);
const pending = store.refreshQqList();
store.onEvent({ resource: 'connections', data: [] });
await pending;
expect(store.getSnapshot().qqList.data).toEqual(accounts);
expect(store.getSnapshot().connections.ready).toBe(true);
});
it('retains the last data on failure and clears the error on recovery', async () => {
const { api, store } = setup();
store.onEvent({ resource: 'qq-list', data: accounts });
vi.mocked(api.qqList).mockRejectedValueOnce(new Error('连接中断'));
await store.refreshQqList();
expect(store.getSnapshot().qqList).toEqual({
data: accounts,
ready: true,
error: '连接中断',
});
await store.refreshQqList();
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
});
it('invalidates pending work on cleanup and allows a new subscription cycle', async () => {
const { api, store } = setup();
const request = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
const pending = store.refreshQqList();
const initial = store.getSnapshot();
store.invalidate();
request.resolve(accounts);
await pending;
expect(store.getSnapshot()).toBe(initial);
await store.refreshQqList();
expect(store.getSnapshot().qqList.ready).toBe(true);
});
it('reconciles all stream resources when frames are dropped', async () => {
const { api, store } = setup();
store.onEvent({ kind: 'ready' });
expect(api.qqList).not.toHaveBeenCalled();
store.onEvent({ kind: 'dropped', count: 3 });
await vi.waitFor(() => expect(store.getSnapshot().connections.ready).toBe(true));
expect(api.qqList).toHaveBeenCalledOnce();
expect(api.processes.list).toHaveBeenCalledOnce();
expect(api.connections).toHaveBeenCalledOnce();
});
it('reports background update failures but rejects an explicit forced check', async () => {
const { api, store } = setup();
vi.spyOn(api.update, 'check').mockRejectedValue(new Error('检查失败'));
await expect(store.refreshUpdate()).resolves.toBeNull();
expect(store.getSnapshot().updateInfo.error).toBe('检查失败');
await expect(store.refreshUpdate(true)).rejects.toThrow('检查失败');
expect(api.update.check).toHaveBeenLastCalledWith(true);
});
});
+119
View File
@@ -0,0 +1,119 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createContactList } from '../src/lib/debug-contacts';
import type { DebugInvokeResult } from '../src/types';
function deferred() {
let resolve!: (result: DebugInvokeResult) => void;
const promise = new Promise<DebugInvokeResult>((done) => {
resolve = done;
});
return { promise, resolve };
}
const success = (nickname: string): DebugInvokeResult => ({
status: 'ok',
data: [{ user_id: 123, nickname }],
});
beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: vi.fn() });
});
afterEach(() => vi.unstubAllGlobals());
describe('debug contact lists', () => {
it('keeps account state separate and ignores a response after leaving its list', async () => {
const previous = deferred();
const invoke = vi
.fn()
.mockReturnValueOnce(previous.promise)
.mockResolvedValue(success('current'));
const oldList = createContactList(invoke, 'friends', 'old-account');
const pending = oldList.refresh();
oldList.invalidate();
const current = createContactList(invoke, 'friends', 'new-account');
await current.refresh();
previous.resolve(success('stale'));
await pending;
expect(current.getSnapshot().items[0].label).toBe('current');
expect(oldList.getSnapshot().items).toEqual([]);
expect(createContactList(invoke, 'friends', 'old-account').getSnapshot().items).toEqual([]);
});
it('supersedes an in-flight refresh when using a fresh cached list', async () => {
const pending = deferred();
const invoke = vi
.fn()
.mockResolvedValueOnce(success('cached'))
.mockReturnValueOnce(pending.promise);
const list = createContactList(invoke, 'friends', 'cache-account');
await list.refresh();
const refresh = list.refresh();
await list.refresh(false);
expect(list.getSnapshot().loading).toBe(false);
pending.resolve(success('superseded'));
await refresh;
expect(list.getSnapshot().items[0].label).toBe('cached');
});
it('ignores an earlier refresh that completes after its replacement', async () => {
const first = deferred();
const invoke = vi
.fn()
.mockReturnValueOnce(first.promise)
.mockResolvedValueOnce(success('latest'));
const list = createContactList(invoke, 'friends', 'race-account');
const pending = list.refresh();
await list.refresh();
first.resolve(success('old'));
await pending;
expect(list.getSnapshot().items[0].label).toBe('latest');
});
it('keeps group-member caches scoped to the account and group', async () => {
const invoke = vi.fn().mockResolvedValue(success('member'));
const first = createContactList(invoke, 'members', 'member-account', '111');
await first.refresh();
expect(invoke).toHaveBeenCalledWith('member-account', 'get_group_member_list', {
group_id: '111',
});
expect(
createContactList(invoke, 'members', 'member-account', '111').getSnapshot().items,
).toHaveLength(1);
expect(
createContactList(invoke, 'members', 'member-account', '222').getSnapshot().items,
).toEqual([]);
expect(
createContactList(invoke, 'members', 'other-account', '111').getSnapshot().items,
).toEqual([]);
});
it('reports malformed successful responses instead of caching an empty list', async () => {
const invoke = vi
.fn()
.mockResolvedValueOnce(success('retained'))
.mockResolvedValueOnce({ status: 'ok', data: {} });
const list = createContactList(invoke, 'friends', 'invalid-account');
await list.refresh();
await list.refresh();
expect(list.getSnapshot()).toMatchObject({ loading: false, error: '联系人列表格式无效' });
expect(list.getSnapshot().items[0].label).toBe('retained');
await list.refresh(false);
expect(list.getSnapshot().error).toBeNull();
expect(invoke).toHaveBeenCalledTimes(2);
});
it('does not request contacts without an account or group selection', async () => {
const invoke = vi.fn();
const lists = [
createContactList(invoke, 'friends', ''),
createContactList(invoke, 'members', 'account'),
];
for (const list of lists) {
await list.refresh();
expect(list.getSnapshot()).toEqual({ items: [], loading: false, error: null });
}
expect(invoke).not.toHaveBeenCalled();
});
});
+67
View File
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { startPolling } from '../src/lib/polling';
let page: EventTarget & { hidden: boolean };
beforeEach(() => {
vi.useFakeTimers();
page = Object.assign(new EventTarget(), { hidden: false });
vi.stubGlobal('document', page);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe('resource polling', () => {
it('starts immediately and skips ticks while a request is pending', async () => {
const pending = Promise.withResolvers<void>();
const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined);
const stop = startPolling(refresh, 1000);
expect(refresh).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(3000);
expect(refresh).toHaveBeenCalledOnce();
pending.resolve();
await vi.advanceTimersByTimeAsync(1000);
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
it('pauses in the background and refreshes when the page becomes visible', async () => {
page.hidden = true;
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 1000);
await vi.advanceTimersByTimeAsync(2000);
expect(refresh).not.toHaveBeenCalled();
page.hidden = false;
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledOnce();
stop();
await vi.advanceTimersByTimeAsync(2000);
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledOnce();
});
it('keeps initial and visibility refreshes when periodic polling is disabled', async () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 0);
await vi.advanceTimersByTimeAsync(60_000);
expect(refresh).toHaveBeenCalledOnce();
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
it('keeps the update-check cadence independent of page visibility', async () => {
page.hidden = true;
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 6000, false);
await vi.advanceTimersByTimeAsync(6000);
expect(refresh).toHaveBeenCalledTimes(2);
page.hidden = false;
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
});