Merge pull request #6 from venti1112/main

fix: correct ineffective quote replies, use Get-CimInstance for GPU detection with wmic fallback, and show uninstall failure notification
This commit is contained in:
MliKiowa authored and GitHub committed 2026-05-07 09:32:51 +08:00
commit 3f4b389e6d
11 files changed
+482 -40

No files matched your search

+2 -9
View File
@@ -475,17 +475,10 @@ function elementsToText(elements: MessageElement[]): string {
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message': {
const c = elementsToText(event.elements);
const s = event.senderCard || event.senderNick || String(event.senderUin);
eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c);
break;
}
case 'group_message':
case 'friend_message':
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
break;
case 'temp_message':
eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements));
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
@@ -54,11 +54,21 @@ function makeMentionElem(element: MessageElement): ProtoElem {
}
function makeReplyElem(element: MessageElement): ProtoElem {
return {
srcMsg: {
origSeqs: [element.replySeq! & 0xFFFFFFFF],
} as any,
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
}
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
function makeJsonElem(element: MessageElement): ProtoElem {
+4
View File
@@ -13,6 +13,10 @@ export interface MessageElement {
fileName?: string;
fileSize?: number;
replySeq?: number;
replyMessageId?: number; // For reply: original message ID (for logging)
replySenderUin?: number; // For reply: original sender's UIN
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
url?: string;
subType?: number;
duration?: number;
+15 -2
View File
@@ -204,11 +204,24 @@ export class HookManager {
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
}
// Clear injection state first
state.injected = false;
state.injectResult = null;
state.method = '';
state.uin = '0';
state.status = 'available';
// Verify unload succeeded by checking if pipe still exists
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
// Pipe still exists - unload failed, but let watcher handle reconnection
state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
state.status = 'connecting'; // Let watcher pick it up and reconnect
log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid);
} else {
// Successfully unloaded
state.status = 'available';
state.error = '';
}
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
@@ -311,7 +324,7 @@ export class HookManager {
state.name = proc.name || state.name;
state.path = proc.path || state.path;
}
// Auto-detect hooks that survived a SnowLuma restart.
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
for (const pid of livePipes) {
const state = this.ensureState(pid);
if (!state.injected) {
+100 -5
View File
@@ -1,5 +1,5 @@
import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload } from '../bridge/events';
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import { elementsToOneBotSegments } from './event-converter';
@@ -7,6 +7,9 @@ import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
export interface InstanceRef {
uin: string;
@@ -412,6 +415,68 @@ async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, mess
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
}
// --- Send message logging ---
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
const type = isGroup ? '群聊' : '私聊';
const parts: string[] = [];
// Check for reply element
const replyElem = elements.find(e => e.type === 'reply');
if (replyElem && replyElem.replyMessageId) {
parts.push(`[回复:${replyElem.replyMessageId}]`);
}
// Build message content preview
for (const elem of elements) {
if (elem.type === 'reply') continue; // Already handled
switch (elem.type) {
case 'text':
if (elem.text) {
const preview = elem.text.length > 50 ? elem.text.substring(0, 50) + '...' : elem.text;
parts.push(preview);
}
break;
case 'image':
parts.push('[图片]');
break;
case 'face':
parts.push('[表情]');
break;
case 'at':
if (elem.text) parts.push(elem.text.trim());
break;
case 'record':
parts.push('[语音]');
break;
case 'video':
parts.push('[视频]');
break;
case 'json':
parts.push('[JSON消息]');
break;
case 'xml':
parts.push('[XML消息]');
break;
case 'markdown':
parts.push('[Markdown]');
break;
case 'forward':
parts.push('[转发消息]');
break;
case 'poke':
parts.push('[戳一戳]');
break;
default:
break;
}
}
const content = parts.join(' ').trim() || '[空消息]';
log.info(`${type} ${targetId} | 发送:${content}`);
}
// --- Send message ---
async function handleSendPrivate(
@@ -421,8 +486,20 @@ async function handleSendPrivate(
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId, // For received messages, targetId is the sender
time: meta.timestamp,
random: meta.random,
};
}
return null;
},
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
@@ -430,6 +507,9 @@ async function handleSendPrivate(
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
// Log sent message
logSentMessage(false, userId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: false,
@@ -451,8 +531,20 @@ async function handleSendGroup(
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
senderUin: typeof event.user_id === 'number' ? event.user_id : parseInt(String(event.user_id || '0'), 10),
time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10),
random: 0, // Group messages might not have random field in event
};
}
return null;
},
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
@@ -460,6 +552,9 @@ async function handleSendGroup(
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
// Log sent message
logSentMessage(true, groupId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: true,
+55
View File
@@ -12,6 +12,9 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { HttpTransport } from './http-transport';
import { HttpPostTransport } from './http-post-transport';
import { WsTransport } from './ws-transport';
import { createLogger } from '../utils/logger';
const log = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
@@ -153,10 +156,62 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
this.wsTransport.publishEvent(event);
this.httpPostTransport.publishEvent(event);
}
private logReceivedMessage(event: JsonObject): void {
if (event.post_type !== 'message') return;
const messageId = toInt(event.message_id);
const isGroup = event.message_type === 'group';
// Build message preview
const parts: string[] = [];
const message = event.message;
if (Array.isArray(message)) {
for (const seg of message) {
if (seg.type === 'text' && seg.data?.text) {
const text = String(seg.data.text);
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
parts.push(preview);
} else if (seg.type === 'image') {
parts.push('[图片]');
} else if (seg.type === 'face') {
parts.push('[表情]');
} else if (seg.type === 'at') {
parts.push(`@${seg.data?.qq || ''}`);
} else if (seg.type === 'reply') {
parts.push(`[回复:${seg.data?.id || ''}]`);
} else if (seg.type === 'record') {
parts.push('[语音]');
} else if (seg.type === 'video') {
parts.push('[视频]');
} else {
parts.push(`[${seg.type}]`);
}
}
}
const content = parts.join(' ').trim() || '[空消息]';
const idStr = `ID:${messageId}`;
if (isGroup) {
const groupId = toInt(event.group_id);
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.card || sender?.nickname || String(userId);
log.success(`群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
} else {
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.nickname || String(userId);
log.success(`私聊 ${nickname}(${userId}): ${idStr} ${content}`);
}
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message') return;
+18 -1
View File
@@ -7,6 +7,7 @@ import type { JsonValue, JsonObject } from './types';
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
musicSignUrl?: string;
}
@@ -102,7 +103,23 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
return { type: 'reply', replySeq: resolved };
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
}
return element;
}
}
+24 -8
View File
@@ -120,15 +120,31 @@ export class MessageStore {
}
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
const row = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = ? AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
return null;
}
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
// For private messages, we cannot rely on session_id matching because:
// - When receiving: session_id is the sender's UIN
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
// So for private messages, we only match by message_hash and is_group flag.
const row = isGroup
? this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(sessionId, messageId) as { sequence: number } | undefined
: this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 0 AND message_hash = ?
LIMIT 1`
).get(messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
return null;
}
return row.sequence;
}
+30 -10
View File
@@ -276,28 +276,48 @@ export async function initWebUI(
if (cachedGpu && now - gpuFetchedAt < 60_000) return cachedGpu;
const platform = os.platform();
const result: { name: string; vendor: string }[] = [];
const unique = new Set<string>();
const pushGpu = (name: string, vendor = '') => {
const normalizedName = name.trim();
const normalizedVendor = vendor.trim();
if (!normalizedName) return;
if (normalizedName.toLowerCase() === 'name') return;
const key = `${normalizedName.toLowerCase()}|${normalizedVendor.toLowerCase()}`;
if (unique.has(key)) return;
unique.add(key);
result.push({ name: normalizedName, vendor: normalizedVendor });
};
try {
if (platform === 'win32') {
const { stdout } = await execAsync('wmic path win32_VideoController get Name /value', {
timeout: 4000,
windowsHide: true,
});
for (const line of stdout.split(/\r?\n/)) {
const m = line.match(/^Name=(.+)$/);
if (m && m[1].trim()) result.push({ name: m[1].trim(), vendor: '' });
// Prefer CIM on modern Windows; WMIC is deprecated and may not exist.
const commands = [
'powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name"',
'wmic path win32_VideoController get Name /value',
];
for (const command of commands) {
try {
const { stdout } = await execAsync(command, { timeout: 5000, windowsHide: true });
for (const line of stdout.split(/\r?\n/)) {
const value = line.includes('=') ? line.split('=').slice(1).join('=') : line;
pushGpu(value);
}
if (result.length > 0) break;
} catch {
// Try next fallback command.
}
}
} else if (platform === 'linux') {
try {
const { stdout } = await execAsync('lspci -mm | grep -Ei "vga|3d|display"', { timeout: 4000 });
for (const line of stdout.split(/\r?\n/)) {
const parts = line.match(/"([^"]+)"\s+"([^"]+)"\s+"([^"]+)"/);
if (parts) result.push({ vendor: parts[2], name: parts[3] });
if (parts) pushGpu(parts[3], parts[2]);
}
} catch {
try {
const { stdout } = await execAsync('nvidia-smi --query-gpu=name --format=csv,noheader', { timeout: 4000 });
for (const line of stdout.split(/\r?\n/)) {
if (line.trim()) result.push({ name: line.trim(), vendor: 'NVIDIA' });
pushGpu(line, 'NVIDIA');
}
} catch {
/* ignore */
@@ -309,7 +329,7 @@ export async function initWebUI(
const json = JSON.parse(stdout);
const list = json.SPDisplaysDataType ?? [];
for (const item of list) {
if (item._name) result.push({ name: item._name, vendor: item.spdisplays_vendor ?? '' });
if (item._name) pushGpu(item._name, item.spdisplays_vendor ?? '');
}
} catch {
/* ignore */
+190
View File
@@ -0,0 +1,190 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { MessageStore } from '../src/onebot/message-store';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
import fs from 'fs';
import path from 'path';
describe('MessageStore', () => {
const testDbPath = path.join('data', 'test', 'messages-test.db');
let store: MessageStore;
beforeEach(() => {
// Clean up any existing test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore if file doesn't exist
}
store = new MessageStore(testDbPath);
});
afterEach(() => {
store.close();
// Clean up test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore cleanup errors
}
});
describe('resolveReplySequence', () => {
it('resolves group message reply sequence', () => {
const groupId = 123456;
const sequence = 100;
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
// Store a group message
store.storeMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Resolve the reply sequence
const resolved = store.resolveReplySequence(true, groupId, messageId);
expect(resolved).toBe(sequence);
});
it('resolves private message reply sequence without session_id matching', () => {
// Simulate receiving a private message from user 111111
const senderUin = 111111;
const sequence = 200;
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
// Store the received message (session_id is sender's UIN)
store.storeMeta(messageId, {
isGroup: false,
targetId: senderUin,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// When replying to this message, we send to the sender (who becomes the recipient)
// The key fix: resolveReplySequence should work even when sessionId doesn't match
const resolved = store.resolveReplySequence(false, senderUin, messageId);
expect(resolved).toBe(sequence);
// More importantly: it should also work when we pass a different sessionId
// (which was the bug - we were passing recipient UIN instead of sender UIN)
const differentUin = 999999;
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
expect(resolvedWithDifferentSession).toBe(sequence);
});
it('returns null for non-existent message', () => {
const resolved = store.resolveReplySequence(true, 123456, 999999);
expect(resolved).toBeNull();
});
it('returns null for invalid messageId', () => {
const resolved = store.resolveReplySequence(true, 123456, 0);
expect(resolved).toBeNull();
});
it('returns null for invalid sessionId', () => {
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
const resolved = store.resolveReplySequence(true, 0, messageId);
expect(resolved).toBeNull();
});
it('distinguishes between group and private messages', () => {
const sessionId = 123456;
const sequence = 300;
// Store a group message
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
store.storeMeta(groupMessageId, {
isGroup: true,
targetId: sessionId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Store a private message with same sequence but different hash
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
store.storeMeta(privateMessageId, {
isGroup: false,
targetId: sessionId,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Should resolve correctly based on isGroup flag
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
expect(groupResolved).toBe(sequence);
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
expect(privateResolved).toBe(sequence);
// Should not cross-resolve
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
expect(wrongGroupResolve).toBeNull();
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
expect(wrongPrivateResolve).toBeNull();
});
});
describe('storeEvent and findEvent', () => {
it('stores and retrieves event data', () => {
const messageId = 12345;
const event = {
post_type: 'message',
message_type: 'group',
message_id: messageId,
group_id: 123456,
message: 'test message',
time: Date.now(),
};
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
const retrieved = store.findEvent(messageId);
expect(retrieved).toEqual(event);
});
it('returns null for non-existent event', () => {
const retrieved = store.findEvent(999999);
expect(retrieved).toBeNull();
});
});
describe('storeMeta and findMeta', () => {
it('stores and retrieves message meta', () => {
const messageId = 54321;
const meta = {
isGroup: true,
targetId: 123456,
sequence: 100,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 1,
random: 12345,
timestamp: Date.now(),
};
store.storeMeta(messageId, meta);
const retrieved = store.findMeta(messageId);
expect(retrieved).toEqual(meta);
});
it('returns null for non-existent meta', () => {
const retrieved = store.findMeta(999999);
expect(retrieved).toBeNull();
});
});
});
+30 -1
View File
@@ -8,6 +8,7 @@ import { ConfigPage } from '@/components/pages/config-page';
import { LogsPage } from '@/components/pages/logs-page';
import { SettingsPage } from '@/components/pages/settings-page';
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
@@ -41,6 +42,7 @@ function AppInner() {
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
// 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>());
@@ -256,7 +258,15 @@ function AppInner() {
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
setProcessActionStatus(`已从进程 ${pid} 卸载`);
// Check if unload actually failed (pipe still exists)
if (data.process?.status === 'connecting' && data.process?.error) {
setUnloadFailedAlert({ pid, error: data.process.error });
setProcessActionStatus(`进程 ${pid} 卸载失败`);
} else {
setProcessActionStatus(`已从进程 ${pid} 卸载`);
}
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
@@ -376,6 +386,25 @@ function AppInner() {
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
</MainLayout>
)}
<ConfirmDialog
open={!!unloadFailedAlert}
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
title="卸载失败"
description={
unloadFailedAlert ? (
<>
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
<p className="mt-2 text-sm text-muted-foreground">
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
</p>
</>
) : null
}
confirmText="知道了"
onConfirm={() => setUnloadFailedAlert(null)}
/>
</TooltipProvider>
);
}