Merge branch 'SnowLuma:main' into main

This commit is contained in:
Ventiの酒 authored and GitHub committed 2026-05-06 16:26:12 +08:00
commit 758d21cc79
9 files changed
+419 -122

No files matched your search

+1 -1
View File
@@ -143,7 +143,7 @@ jobs:
## 使用说明 ## 使用说明
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。 - Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。 - Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:8080。 - 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。 - Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
EOF EOF
+306 -102
View File
@@ -6,10 +6,17 @@ import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjec
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client'; import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
const log = createLogger('Hook'); const log = createLogger('Hook');
const CONNECT_RETRY_COUNT = 30; const DEFAULT_WATCHER_INTERVAL_MS = 1500;
const CONNECT_RETRY_INTERVAL_MS = 1000; const MIN_WATCHER_INTERVAL_MS = 250;
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected'; export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
export interface HookProcessInfo extends HookProcessBaseInfo { export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean; injected: boolean;
@@ -25,96 +32,141 @@ interface HookProcessState extends HookProcessInfo {
client: QqHookClient | null; client: QqHookClient | null;
sender: HookPacketClient | null; sender: HookPacketClient | null;
injectResult: HookInjectResult | null; injectResult: HookInjectResult | null;
connectTask: Promise<void> | null;
bound: boolean; bound: boolean;
} }
export interface HookManagerOptions {
/** Background pipe-watcher polling interval. Lower = faster reconnect but
* more frequent named-pipe directory listings. Defaults to 1500 ms. */
watcherIntervalMs?: number;
}
/**
* Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes.
*
* Lifecycle: load -> inject DLL only (returns fast) -> background watcher
* detects the named pipe coming up and connects -> on QQ login the bridge is
* notified. The watcher also handles reconnect after a pipe drop and detects
* hooks that survived a previous SnowLuma restart.
*
* Concurrency: every per-PID mutation (load / unload / refresh / connect /
* close-handler / watcher reconcile) goes through a per-PID promise chain so
* users can spam buttons without races.
*/
export class HookManager { export class HookManager {
private readonly states = new Map<number, HookProcessState>(); private readonly states = new Map<number, HookProcessState>();
private readonly loadTasks = new Map<number, Promise<HookProcessInfo>>(); private readonly opsByPid = new Map<number, Promise<unknown>>();
private readonly unloadTasks = new Map<number, Promise<HookProcessInfo>>(); private readonly watcherIntervalMs: number;
private watcherTimer: NodeJS.Timeout | null = null;
private watcherTicking = false;
private disposed = false;
constructor( constructor(
private readonly ntqq: NtqqHandler, private readonly ntqq: NtqqHandler,
private readonly bridgeManager: BridgeManager, private readonly bridgeManager: BridgeManager,
) {} options: HookManagerOptions = {},
) {
async listProcesses(): Promise<HookProcessInfo[]> { this.watcherIntervalMs = Math.max(
const processes = await listHookProcesses(); MIN_WATCHER_INTERVAL_MS,
for (const proc of processes) { options.watcherIntervalMs ?? DEFAULT_WATCHER_INTERVAL_MS,
const state = this.ensureState(proc.pid); );
state.name = proc.name; // Boot the watcher on the next tick so callers can attach listeners first.
state.path = proc.path; this.scheduleWatcher(0);
} }
const seen = new Set(processes.map(proc => proc.pid)); async listProcesses(): Promise<HookProcessInfo[]> {
const processes = listHookProcesses();
const seen = new Set<number>();
for (const proc of processes) {
seen.add(proc.pid);
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
const result: HookProcessInfo[] = []; const result: HookProcessInfo[] = [];
for (const proc of processes) { for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid))); result.push(this.toPublicInfo(this.ensureState(proc.pid)));
} }
for (const state of this.states.values()) { for (const state of this.states.values()) {
if (!seen.has(state.pid) && state.injected) { if (!seen.has(state.pid) && (state.injected || state.client)) {
result.push(this.toPublicInfo(state)); result.push(this.toPublicInfo(state));
} }
} }
return result.sort((a, b) => a.pid - b.pid); return result.sort((a, b) => a.pid - b.pid);
} }
async loadProcess(pid: number): Promise<HookProcessInfo> { loadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) { if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
throw new Error('invalid pid'); return this.serialize(pid, () => this.loadProcessInternal(pid));
}
const runningTask = this.loadTasks.get(pid);
if (runningTask) return runningTask;
const task = this.loadProcessInternal(pid);
this.loadTasks.set(pid, task);
try {
return await task;
} finally {
this.loadTasks.delete(pid);
}
} }
async unloadProcess(pid: number): Promise<HookProcessInfo> { unloadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) { if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
throw new Error('invalid pid'); return this.serialize(pid, () => this.unloadProcessInternal(pid));
} }
const runningTask = this.unloadTasks.get(pid);
if (runningTask) return runningTask;
const task = this.unloadProcessInternal(pid); /**
this.unloadTasks.set(pid, task); * Re-probe the named pipe for `pid`, reconnect if it became available,
try { * or tear down a stale connection if it disappeared. Safe to call at any
return await task; * time; serialised against load/unload/watcher actions on the same PID.
} finally { */
this.unloadTasks.delete(pid); refreshProcess(pid: number): Promise<HookProcessInfo> {
} if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
return this.serialize(pid, () => this.refreshProcessInternal(pid));
} }
dispose(): void { dispose(): void {
this.disposed = true;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
}
for (const state of this.states.values()) { for (const state of this.states.values()) {
state.client?.close(); this.tearDownClient(state);
state.client = null;
state.connected = false;
state.loggedIn = false;
state.status = state.injected ? 'disconnected' : 'available'; state.status = state.injected ? 'disconnected' : 'available';
} }
} }
// ───────────────────────── per-PID serialization ─────────────────────────
/**
* Serialise an operation against a per-PID promise chain. Guarantees that
* load / unload / refresh / watcher-driven connects for the same PID never
* interleave even if the user mashes buttons.
*/
private async serialize<T>(pid: number, op: () => Promise<T>): Promise<T> {
const previous = this.opsByPid.get(pid) ?? Promise.resolve();
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
const chained = previous.then(() => completion);
this.opsByPid.set(pid, chained);
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
// Drop the chain entry once nothing else is waiting on it.
if (this.opsByPid.get(pid) === chained) this.opsByPid.delete(pid);
}
}
// ──────────────────────────── load / unload ──────────────────────────────
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> { private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid); const state = this.ensureState(pid);
state.status = 'loading';
state.error = ''; state.error = '';
state.status = 'loading';
try { try {
if (!state.injected) { if (!state.injected) {
// Fast path: if QQ.exe still hosts a hook DLL from a previous SnowLuma // Fast path: a previous SnowLuma run may have left the hook DLL
// run, the control pipe is already listed. Skip re-injection on a hit. // resident in QQ.exe. If the control pipe is already listed we skip
if (await QqHookClient.probePipe(pid)) { // re-injection and let the watcher reconnect instead.
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
state.injected = true; state.injected = true;
state.method = 'reconnect'; state.method = 'reconnect';
log.info('SnowLuma reconnected to existing hook in PID=%d', pid); log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
} else { } else {
state.injectResult = injectHookProcess(pid); state.injectResult = injectHookProcess(pid);
state.injected = true; state.injected = true;
@@ -122,14 +174,18 @@ export class HookManager {
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method); log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
} }
} }
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded'; state.status = state.connected
this.startClient(state); ? (state.loggedIn ? 'online' : 'loaded')
: 'connecting';
} catch (error) { } catch (error) {
state.status = 'error'; state.status = 'error';
state.error = error instanceof Error ? error.message : String(error); state.error = error instanceof Error ? error.message : String(error);
log.error('load failed: PID=%d err=%s', pid, state.error); log.error('load failed: PID=%d err=%s', pid, state.error);
} }
// Wake the watcher so it can pick up the freshly-injected pipe asap
// instead of waiting up to one full interval.
this.scheduleWatcher(0);
return this.toPublicInfo(state); return this.toPublicInfo(state);
} }
@@ -138,14 +194,9 @@ export class HookManager {
state.error = ''; state.error = '';
try { try {
state.client?.close(); const wasLoggedIn = state.loggedIn;
state.client = null; this.tearDownClient(state);
state.sender = null; if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
state.connectTask = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
this.bridgeManager.onPidDisconnected(pid);
const handle = state.injectResult?.handle; const handle = state.injectResult?.handle;
if (state.injected && handle) { if (state.injected && handle) {
@@ -167,6 +218,44 @@ export class HookManager {
return this.toPublicInfo(state); return this.toPublicInfo(state);
} }
private async refreshProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
try {
const livePipes = await QqHookClient.listLivePipes();
const pipeUp = livePipes.has(pid);
if (pipeUp) {
// A live pipe means a SnowLuma DLL is resident — even if we did not
// inject it ourselves (e.g. left over from a prior run).
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
}
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.connected) {
await this.attemptConnect(state);
} else {
state.status = state.loggedIn ? 'online' : 'loaded';
}
} else {
// Pipe is gone; if we still hold a client, drop it and surface the
// appropriate disconnected/available state to the UI.
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
state.status = state.injected ? 'disconnected' : 'available';
}
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
state.status = state.injected ? 'disconnected' : 'error';
log.warn('refresh failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private ensureState(pid: number): HookProcessState { private ensureState(pid: number): HookProcessState {
let state = this.states.get(pid); let state = this.states.get(pid);
if (!state) { if (!state) {
@@ -184,7 +273,6 @@ export class HookManager {
client: null, client: null,
sender: null, sender: null,
injectResult: null, injectResult: null,
connectTask: null,
bound: false, bound: false,
}; };
this.states.set(pid, state); this.states.set(pid, state);
@@ -192,20 +280,139 @@ export class HookManager {
return state; return state;
} }
private startClient(state: HookProcessState): void { // ───────────────────────────── pipe watcher ──────────────────────────────
private scheduleWatcher(delayMs: number): void {
if (this.disposed) return;
if (this.watcherTimer) {
clearTimeout(this.watcherTimer);
this.watcherTimer = null;
}
this.watcherTimer = setTimeout(() => {
this.watcherTimer = null;
void this.tickWatcher();
}, Math.max(0, delayMs));
}
private async tickWatcher(): Promise<void> {
if (this.disposed) return;
if (this.watcherTicking) {
this.scheduleWatcher(this.watcherIntervalMs);
return;
}
this.watcherTicking = true;
try {
const livePipes = await QqHookClient.listLivePipes();
const processes = listHookProcesses();
// Refresh metadata + ensure a state entry exists for each known PID.
for (const proc of processes) {
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
// Auto-detect hooks that survived a SnowLuma restart.
for (const pid of livePipes) {
const state = this.ensureState(pid);
if (!state.injected) {
state.injected = true;
state.method = state.method || 'reconnect';
if (state.status === 'available') state.status = 'connecting';
log.info('Detected pre-existing SnowLuma pipe in PID=%d', pid);
}
}
const runningSet = new Set(processes.map(p => p.pid));
const tasks: Promise<unknown>[] = [];
for (const state of [...this.states.values()]) {
const alivePipe = livePipes.has(state.pid);
const aliveProc = runningSet.has(state.pid);
// Reap stale state entries that have nothing left to do.
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
this.states.delete(state.pid);
continue;
}
// Pipe vanished but we still hold a client → schedule a teardown.
if (state.connected && !alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileLostPipe(state.pid))
.catch(err => log.warn('watcher teardown failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected & pipe up but not connected → schedule a connect.
if (state.injected && !state.connected && alivePipe) {
tasks.push(this.serialize(state.pid, async () => this.reconcileConnect(state.pid))
.catch(err => log.warn('watcher connect failed: PID=%d err=%s', state.pid, this.errMsg(err))));
continue;
}
// Injected but pipe still pending → keep status visible to the UI.
if (state.injected && !state.connected && !alivePipe) {
if (state.status !== 'error' && state.status !== 'disconnected' && state.status !== 'loading') {
state.status = 'connecting';
}
}
}
await Promise.all(tasks);
} finally {
this.watcherTicking = false;
this.scheduleWatcher(this.watcherIntervalMs);
}
}
/** Re-check pipe and connect under the per-PID lock. */
private async reconcileConnect(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.injected || state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
const live = await QqHookClient.listLivePipes();
if (!live.has(pid)) return;
await this.attemptConnect(state);
}
/** Tear down a client whose pipe disappeared. */
private async reconcileLostPipe(pid: number): Promise<void> {
const state = this.states.get(pid);
if (!state || !state.connected) return;
const live = await QqHookClient.listLivePipes();
if (live.has(pid)) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
state.status = state.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available';
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
}
// ───────────────────────────── client plumbing ───────────────────────────
private async attemptConnect(state: HookProcessState): Promise<void> {
if (state.connected) return;
if (state.client?.isClosed) this.tearDownClient(state);
if (!state.client) { if (!state.client) {
state.client = new QqHookClient(state.pid); state.client = new QqHookClient(state.pid);
state.sender = new HookPacketClient(state.client); state.sender = new HookPacketClient(state.client);
state.bound = false;
} }
if (!state.bound) { if (!state.bound) {
this.bindClient(state, state.client); this.bindClient(state, state.client);
state.bound = true; state.bound = true;
} }
if (!state.connectTask) {
state.connectTask = this.connectClient(state).finally(() => { const client = state.client;
state.connectTask = null; try {
}); await client.connectAll({ recv: true });
void state.connectTask; state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(state, loginState);
log.info('pipe connected: PID=%d', state.pid);
} catch (error) {
state.error = this.errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient(state);
state.status = state.injected ? 'connecting' : 'available';
} }
} }
@@ -213,46 +420,43 @@ export class HookManager {
client.on('packet', packet => this.handlePacket(state, packet)); client.on('packet', packet => this.handlePacket(state, packet));
client.on('loginState', loginState => this.handleLoginState(state, loginState)); client.on('loginState', loginState => this.handleLoginState(state, loginState));
client.on('error', error => { client.on('error', error => {
state.error = error instanceof Error ? error.message : String(error); const msg = this.errMsg(error);
if (!state.connected) state.status = 'error'; state.error = msg;
log.warn('pipe error: PID=%d err=%s', state.pid, state.error); log.warn('pipe error: PID=%d err=%s', state.pid, msg);
}); });
client.on('close', () => { client.on('close', () => {
state.connected = false; if (this.disposed) return;
if (state.loggedIn) { // Only the client that is currently registered should drive a reconcile;
state.loggedIn = false; // listeners may fire for an already-replaced client.
if (state.client !== client) return;
void this.serialize(state.pid, async () => {
if (state.client !== client) return;
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (!state.injected) {
state.status = 'available';
} else if (wasLoggedIn) {
state.status = 'disconnected'; state.status = 'disconnected';
this.bridgeManager.onPidDisconnected(state.pid); this.bridgeManager.onPidDisconnected(state.pid);
} else {
state.status = 'connecting';
} }
}).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err)));
}); });
} }
private async connectClient(state: HookProcessState): Promise<void> { /** Detach + close the current client and reset its associated fields. */
private tearDownClient(state: HookProcessState): void {
const client = state.client; const client = state.client;
if (!client) return; if (client) {
client.removeAllListeners();
for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) { try { client.close(); } catch { /* ignore */ }
try {
await client.connectAll({ recv: true });
state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) {
this.handleLoginState(state, loginState);
}
log.info('pipe connected: PID=%d', state.pid);
return;
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
if (attempt >= CONNECT_RETRY_COUNT) {
state.status = 'error';
log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error);
return;
}
await delay(CONNECT_RETRY_INTERVAL_MS);
}
} }
state.client = null;
state.sender = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
} }
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void { private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
@@ -290,13 +494,13 @@ export class HookManager {
method: state.method, method: state.method,
}; };
} }
private errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
} }
function isRealUin(uin: string): boolean { function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false; if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5; return /^\d+$/.test(uin) && uin.length >= 5;
} }
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
+27 -7
View File
@@ -253,6 +253,10 @@ export class QqHookClient extends EventEmitter {
return this.loginState.loggedIn; return this.loginState.loggedIn;
} }
get isClosed(): boolean {
return this.closed;
}
get currentUin(): string { get currentUin(): string {
return this.loginState.uin; return this.loginState.uin;
} }
@@ -289,20 +293,36 @@ export class QqHookClient extends EventEmitter {
* opening the pipe, so probing cannot disturb the first real client connect. * opening the pipe, so probing cannot disturb the first real client connect.
*/ */
static async probePipe(pid: number): Promise<boolean> { static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
return live.has(pid);
}
/**
* Enumerate every PID currently hosting a SnowLuma `mojo.<pid>.control` pipe
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
const result = new Set<number>();
try { try {
const pipeFileName = process.platform === 'win32'
? `mojo.${pid}.control`
: `mojo.${pid}.control.sock`;
if (process.platform === 'win32') { if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\'); const names = await fs.readdir('\\\\.\\pipe\\');
return names.some(name => name.toLowerCase() === pipeFileName.toLowerCase()); for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
} }
} else {
const names = await fs.readdir(linuxRuntimeDir()); const names = await fs.readdir(linuxRuntimeDir());
return names.includes(pipeFileName); for (const name of names) {
} catch { const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
return false; if (m) result.add(Number(m[1]));
} }
} }
} catch {
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
async connect(): Promise<QqHookHello> { async connect(): Promise<QqHookHello> {
if (this.closed) { if (this.closed) {
+14
View File
@@ -456,6 +456,20 @@ export async function initWebUI(
} }
}); });
app.post('/api/processes/:pid/refresh', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.refreshProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.get('/api/config/:uin', (c) => { app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin'); const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
Binary file not shown.
Binary file not shown.
+35 -3
View File
@@ -39,7 +39,11 @@ function AppInner() {
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null); const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null); const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState(''); const [processActionStatus, setProcessActionStatus] = useState('');
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
// collapse spam-clicks instead of firing a second concurrent request.
const inflightProcessOps = useRef(new Set<number>());
const [selectedUin, setSelectedUin] = useState<string | null>(null); const [selectedUin, setSelectedUin] = useState<string | null>(null);
const [config, setConfig] = useState<OneBotConfig | null>(null); const [config, setConfig] = useState<OneBotConfig | null>(null);
@@ -224,39 +228,65 @@ function AppInner() {
}, [fetchApi]); }, [fetchApi]);
const handleLoadProcess = useCallback(async (pid: number) => { const handleLoadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessLoadingPid(pid); setProcessLoadingPid(pid);
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`); setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try { try {
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' }); const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '加载失败'); if (!res.ok) throw new Error(data.message || data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma`); setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
await refreshProcesses(); await refreshProcesses();
} catch (e) { } catch (e) {
setProcessActionStatus(`加载失败:${(e as Error).message}`); setProcessActionStatus(`加载失败:${(e as Error).message}`);
} finally { } finally {
inflightProcessOps.current.delete(pid);
setProcessLoadingPid(null); setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000); setTimeout(() => setProcessActionStatus(''), 4000);
} }
}, [fetchApi, refreshProcesses]); }, [fetchApi, refreshProcesses]);
const handleUnloadProcess = useCallback(async (pid: number) => { const handleUnloadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessUnloadingPid(pid); setProcessUnloadingPid(pid);
setProcessActionStatus(`正在从进程 ${pid} 卸载…`); setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try { try {
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' }); const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '卸载失败'); if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
setProcessActionStatus(`已从进程 ${pid} 卸载`); setProcessActionStatus(`已从进程 ${pid} 卸载`);
await refreshProcesses(); await refreshProcesses();
} catch (e) { } catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`); setProcessActionStatus(`卸载失败:${(e as Error).message}`);
} finally { } finally {
inflightProcessOps.current.delete(pid);
setProcessUnloadingPid(null); setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000); setTimeout(() => setProcessActionStatus(''), 4000);
} }
}, [fetchApi, refreshProcesses]); }, [fetchApi, refreshProcesses]);
const handleRefreshProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessRefreshingPid(pid);
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
try {
const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessRefreshingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleSaveConfig = useCallback(async () => { const handleSaveConfig = useCallback(async () => {
if (!selectedUin || !config) return; if (!selectedUin || !config) return;
setSaveStatus('保存中...'); setSaveStatus('保存中...');
@@ -321,12 +351,14 @@ function AppInner() {
processList={processList} processList={processList}
processLoadingPid={processLoadingPid} processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid} processUnloadingPid={processUnloadingPid}
processRefreshingPid={processRefreshingPid}
processActionStatus={processActionStatus} processActionStatus={processActionStatus}
systemInfo={systemInfo} systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses} onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem} onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess} onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess} onUnloadProcess={handleUnloadProcess}
onRefreshProcess={handleRefreshProcess}
/> />
)} )}
{active === 'config' && ( {active === 'config' && (
@@ -31,17 +31,20 @@ interface OverviewPageProps {
processList: HookProcessInfo[]; processList: HookProcessInfo[];
processLoadingPid: number | null; processLoadingPid: number | null;
processUnloadingPid: number | null; processUnloadingPid: number | null;
processRefreshingPid: number | null;
processActionStatus: string; processActionStatus: string;
systemInfo: SystemInfo | null; systemInfo: SystemInfo | null;
onRefreshProcesses: () => void; onRefreshProcesses: () => void;
onRefreshSystem: () => void; onRefreshSystem: () => void;
onLoadProcess: (pid: number) => Promise<void> | void; onLoadProcess: (pid: number) => Promise<void> | void;
onUnloadProcess: (pid: number) => Promise<void> | void; onUnloadProcess: (pid: number) => Promise<void> | void;
onRefreshProcess: (pid: number) => Promise<void> | void;
} }
const processStatusLabel: Record<HookProcessInfo['status'], string> = { const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载', available: '可加载',
loading: '加载中', loading: '加载中',
connecting: '等待连接',
loaded: '等待登录', loaded: '等待登录',
online: '已在线', online: '已在线',
error: '错误', error: '错误',
@@ -50,8 +53,9 @@ const processStatusLabel: Record<HookProcessInfo['status'], string> = {
function processBadgeVariant(status: HookProcessInfo['status']) { function processBadgeVariant(status: HookProcessInfo['status']) {
if (status === 'online') return 'success' as const; if (status === 'online') return 'success' as const;
if (status === 'error' || status === 'disconnected') return 'destructive' as const; if (status === 'error') return 'destructive' as const;
if (status === 'loading' || status === 'loaded') return 'default' as const; if (status === 'disconnected') return 'destructive' as const;
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
return 'secondary' as const; return 'secondary' as const;
} }
@@ -99,12 +103,14 @@ export function OverviewPage({
processList, processList,
processLoadingPid, processLoadingPid,
processUnloadingPid, processUnloadingPid,
processRefreshingPid,
processActionStatus, processActionStatus,
systemInfo, systemInfo,
onRefreshProcesses, onRefreshProcesses,
onRefreshSystem, onRefreshSystem,
onLoadProcess, onLoadProcess,
onUnloadProcess, onUnloadProcess,
onRefreshProcess,
}: OverviewPageProps) { }: OverviewPageProps) {
const [confirm, setConfirm] = useState< const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string } | { kind: 'load' | 'unload'; pid: number; name: string }
@@ -278,10 +284,13 @@ export function OverviewPage({
{processList.map((proc, idx) => { {processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading'; const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid; const unloading = processUnloadingPid === proc.pid;
const busy = loading || unloading; const refreshing = processRefreshingPid === proc.pid;
const busy = loading || unloading || refreshing;
const isOnline = proc.status === 'online'; const isOnline = proc.status === 'online';
const canUnload = const canUnload = proc.injected;
proc.injected || proc.status === 'loaded' || isOnline || proc.status === 'disconnected'; // Refresh is meaningful whenever a hook may exist (so the user
// can re-check the pipe and trigger a reconnect on demand).
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
return ( return (
<motion.div <motion.div
key={proc.pid} key={proc.pid}
@@ -328,6 +337,24 @@ export function OverviewPage({
</div> </div>
)} )}
</div> </div>
<div className="flex shrink-0 items-center gap-1.5">
{showRefresh && (
<Button
size="icon"
variant="ghost"
disabled={busy}
aria-label={`刷新进程 ${proc.pid} 管道状态`}
title="刷新管道状态 / 重连"
onClick={() => onRefreshProcess(proc.pid)}
className="size-8 text-muted-foreground hover:text-foreground"
>
{refreshing ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<RefreshCw className="size-3.5" />
)}
</Button>
)}
<Button <Button
size="sm" size="sm"
variant={canUnload ? 'outline' : 'default'} variant={canUnload ? 'outline' : 'default'}
@@ -340,14 +367,14 @@ export function OverviewPage({
}) })
} }
className={cn( className={cn(
'shrink-0',
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive' canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
)} )}
> >
{busy && <Loader2 className="size-3.5 animate-spin" />} {(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
{!busy && canUnload && <Unplug className="size-3.5" />} {!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'} {canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
</Button> </Button>
</div>
</motion.div> </motion.div>
); );
})} })}
+1 -1
View File
@@ -14,7 +14,7 @@ export interface HookProcessInfo {
connected: boolean; connected: boolean;
loggedIn: boolean; loggedIn: boolean;
uin: string; uin: string;
status: 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected'; status: 'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
error: string; error: string;
method: string; method: string;
} }