diff --git a/package.json b/package.json index a9e5238c..38cb82ba 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.11.4", + "version": "1.12.0", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index dcf524fb..10c0f48b 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/common/package.json b/packages/common/package.json index 237f5dfb..66196198 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index 031623e7..3e8b79c3 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.11.4", + "version": "1.12.0", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index 698729b8..af071639 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -163,7 +163,9 @@ async function buildForwardPushBody( subType: 4, msgId: random, sequence: seq, - timestamp: now, + // Honour a custom per-node display time (#209); default to now. `now` + // still drives the c2c-file expireTime above, which must stay real. + timestamp: node.time && node.time > 0 ? node.time : now, c2cCmd: 0, }, body: { diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index aeca9979..f9d99eb1 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -4,6 +4,7 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push'; +import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt'; import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline'; import { buildApiHub, type ApiHub } from './apis'; import { @@ -65,6 +66,7 @@ export class Bridge implements BridgeInterface { }, }); this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_)); + this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT); } dispose(): void { diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 999d0c40..0eec208c 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -14,13 +14,26 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => []), })); -import { gzipSync } from 'zlib'; -import { protobuf_encode } from '@snowluma/proton'; -import type { SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import { gunzipSync, gzipSync } from 'zlib'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg'; import type { PushMsgBody } from '@snowluma/proto-defs/message'; import { ForwardApi } from '../../src/bridge/apis/forward'; import { mockBridge } from './_helpers'; +/** Decode the SsoSendLongMsg packet body back into the per-node contentHead + * timestamps of the MultiMsg action — how #209's custom time is verified on + * the wire. */ +function sentNodeTimestamps(body: Uint8Array): number[] { + const req = protobuf_decode(body); + const payload = req.info?.payload; + if (!payload) return []; + const longMsg = protobuf_decode(gunzipSync(Buffer.from(payload))); + const main = longMsg.action?.find((a) => a?.actionCommand === 'MultiMsg'); + const bodies = Array.isArray(main?.actionData?.msgBody) ? main!.actionData!.msgBody : []; + return bodies.map((b) => Number(b.contentHead?.timestamp ?? 0)); +} + function uploadResponseWithResId(resId: string) { const encoded = protobuf_encode({ result: { resId } }); return { @@ -65,6 +78,25 @@ describe('actions/forward', () => { expect((body as Uint8Array).length).toBeGreaterThan(0); }); + it('honours a custom per-node time on the wire, and defaults to now when absent (#209)', async () => { + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-time')) as any, + }); + + const customTime = 1600000000; // 2020-09-13, clearly not "now" + await new ForwardApi(bridge as any).upload([ + { userUin: 10001, nickname: 'alice', elements: [], time: customTime }, + { userUin: 10002, nickname: 'bob', elements: [] }, // no time → fallback + ]); + + const [, body] = bridge.sendRawPacket.mock.calls[0]!; + const [tsAlice, tsBob] = sentNodeTimestamps(body as Uint8Array); + + expect(tsAlice).toBe(customTime); + // Bob falls back to the current time (seconds). + expect(Math.abs(tsBob - Math.floor(Date.now() / 1000))).toBeLessThan(5); + }); + it('uploadForwardNodes throws when sendRawPacket reports failure', async () => { const bridge = mockBridge({ sendRawPacket: vi.fn(async () => ({ diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index e706d9c6..b3128296 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -14,6 +14,8 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; // inline-extract the kind. import type { GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin, + InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange, + ProfileLikeTip, } from '@snowluma/proto-defs/notify'; import type { PushMsg } from '@snowluma/proto-defs/message'; import type { @@ -254,6 +256,193 @@ describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', ( }); }); +describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输入)', () => { + // RE'd from wrapper.linux.node aio_input_state_worker.cc: 0x210/0x115 sys_msg, + // body = InputStatusNotify {fromUid, toUid, notifyItem{eventType@f4}}. + type FriendInputStatusEvent = Extract; + + function makeInputStatusPacket(fromUid: string, eventType: number): PacketInfo { + const content = protobuf_encode({ + fromUid, + toUid: 'u_self', + notifyItem: { eventType }, + }); + return makeEvent0x210PacketAny(277, content); + } + + it('emits friend_input_status (typing) for eventType 1', () => { + const member = makeGroupMember(77777, 'u_typer'); + const [event] = parseMsgPush( + makeInputStatusPacket(member.uid, 1), + makeIdentity([member]), + ) as FriendInputStatusEvent[]; + + expect(event.kind).toBe('friend_input_status'); + expect(event.userUin).toBe(77777); + expect(event.eventType).toBe(1); + expect(event.statusText).toBe('对方正在输入...'); + }); + + it('surfaces eventType 3 as the voice-recording status text', () => { + const member = makeGroupMember(77777, 'u_typer'); + const [event] = parseMsgPush( + makeInputStatusPacket(member.uid, 3), + makeIdentity([member]), + ) as FriendInputStatusEvent[]; + + expect(event.eventType).toBe(3); + expect(event.statusText).toBe('对方正在讲话...'); + }); + + it('drops a body with no fromUid (nothing to key user_id on)', () => { + const events = parseMsgPush( + makeEvent0x210PacketAny(277, protobuf_encode({ notifyItem: { eventType: 1 } })), + makeIdentity(), + ); + expect(events).toEqual([]); + }); +}); + +describe('parseMsgPush Event0x210 subType=39 (profile like → 名片赞)', () => { + // 0x210/39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a + // like only when inner msgType==0 && subType==203. Proto shape from NapCat's + // raw-bytes decoder (pending a real like capture to validate byte-exactly). + type FriendProfileLikeEvent = Extract; + + function makeLikePacket(opts: { msgType?: number; subType?: number; uin?: number; nick?: string; txt?: string; time?: number }): PacketInfo { + const content = protobuf_encode({ + msgType: opts.msgType ?? 0, + subType: opts.subType ?? 203, + content: { msg: { + time: opts.time ?? 1710001111, + detail: { txt: opts.txt ?? '', uin: BigInt(opts.uin ?? 0), nickname: opts.nick ?? '' }, + } }, + }); + return makeEvent0x210PacketAny(39, content); + } + + it('emits friend_profile_like with liker uin, nick and parsed count', () => { + // txt shape taken from a real capture: "赞了我的资料卡N次". + const [event] = parseMsgPush( + makeLikePacket({ uin: 1206069534, nick: '墨白灵MotricLuck', txt: '赞了我的资料卡2次' }), + makeIdentity(), + ) as FriendProfileLikeEvent[]; + + expect(event.kind).toBe('friend_profile_like'); + expect(event.operatorUin).toBe(1206069534); + expect(event.operatorNick).toBe('墨白灵MotricLuck'); + expect(event.times).toBe(2); + expect(event.time).toBe(1710001111); + }); + + it('ignores a non-like 39 variant (inner subType != 203)', () => { + const events = parseMsgPush( + makeLikePacket({ subType: 999, uin: 1787882683 }), + makeIdentity(), + ); + expect(events).toEqual([]); + }); +}); + +describe('parseMsgPush Event0x2DC subType=16 field13=6 (group special title)', () => { + // Built from a REAL on-wire capture: eventParam f2 = the gray-tip template + // "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔", f5 = member uin. The title + // is the last <{…}> token's text. + type GroupTitleChangeEvent = Extract; + + const TIP = '恭喜<{"cmd":5,"data":"3433035623","text":"星屿"}>获得群主授予的' + + '<{"cmd":1,"data":"https://qun.qq.com/x?medal=302&uin=3433035623","text":"摸鱼冠军",' + + '"url":"https://qun.qq.com/x?medal=302&uin=3433035623"}>头衔'; + + function makeTitlePacket(memberUin: number, tip: string): PacketInfo { + const notify = protobuf_encode({ + groupUin: GROUP_ID, + field13: 6, + eventParam: protobuf_encode({ tipText: tip, memberUin }), + }); + const content = new Uint8Array(7 + notify.length); + content.set(notify, 7); + const body = protobuf_encode({ + message: { + responseHead: { fromUin: 0, type: 0, sigMap: 0 }, + contentHead: { msgType: 732, subType: 16, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + }); + return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body }; + } + + it('emits group_title_change with the granted title + member', () => { + const [event] = parseMsgPush( + makeTitlePacket(22222, TIP), + makeIdentity([makeGroupMember(22222, 'u_member')]), + ) as GroupTitleChangeEvent[]; + + expect(event.kind).toBe('group_title_change'); + expect(event.groupId).toBe(GROUP_ID); + expect(event.userUin).toBe(22222); + expect(event.title).toBe('摸鱼冠军'); // last <{…}> token's text + }); + + it('drops a title tip with no parseable title token', () => { + const events = parseMsgPush( + makeTitlePacket(22222, '恭喜获得头衔'), + makeIdentity(), + ); + expect(events).toEqual([]); + }); +}); + +describe('parseMsgPush Event0x2DC subType=16 field13=12 (group name change)', () => { + // RE cross-ref: Lagrange Event0x2DCSubType16Field13.GroupNameChangeNotice = 12, + // EventParam(f5) → GroupNameChange{f2=name}, operator = NotifyMessageBody.f21. + // The 0x2DC subType16 body carries a 7-byte prefix (groupUin+byte+len) before + // the NotifyMessageBody proto — the decoder strips it via subarray(7). + type GroupNameChangeEvent = Extract; + + function makeGroupNamePacket(groupUin: number, operatorUid: string, name: string): PacketInfo { + const notify = protobuf_encode({ + groupUin, + field13: 12, + operatorUid, + eventParam: protobuf_encode({ name }), + }); + const content = new Uint8Array(7 + notify.length); // 7-byte prefix + proto + content.set(notify, 7); + const body = protobuf_encode({ + message: { + responseHead: { fromUin: 0, type: 0, sigMap: 0 }, + contentHead: { msgType: 732, subType: 16, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + }); + return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body }; + } + + it('emits group_name_change with the new name + operator', () => { + const member = makeGroupMember(54321, 'u_operator'); + const [event] = parseMsgPush( + makeGroupNamePacket(GROUP_ID, member.uid, '新的群名'), + makeIdentity([member]), + ) as GroupNameChangeEvent[]; + + expect(event.kind).toBe('group_name_change'); + expect(event.groupId).toBe(GROUP_ID); + expect(event.name).toBe('新的群名'); + expect(event.operatorUin).toBe(54321); + }); + + it('drops a name-change body with an empty name', () => { + const events = parseMsgPush( + makeGroupNamePacket(GROUP_ID, 'u_operator', ''), + makeIdentity(), + ); + expect(events).toEqual([]); + }); +}); + describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => { // 138 = friend recalled their own message sent to bot // (peer in friend_recall event = fromUid) diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 15480e19..f394027a 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.11.4", + "version": "1.12.0", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 9240b4b6..d1f49fe8 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 5a0b6cf7..028c16f9 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -6,16 +6,22 @@ import { convertTempMessage, } from './to-message'; import { + convertBotOffline, convertFriendAdd, + convertFriendInputStatus, + convertFriendProfileLike, convertFriendPoke, convertFriendRecall, convertGroupAdmin, + convertGroupCardChange, convertGroupEssence, convertGroupFileUpload, convertGroupMemberJoin, convertGroupMemberLeave, convertGroupMsgEmojiLike, convertGroupMute, + convertGroupNameChange, + convertGroupTitleChange, convertGroupPoke, convertGroupRecall, } from './to-notice'; @@ -78,6 +84,12 @@ const CONVERTERS: ConverterRegistry = { group_essence: convertGroupEssence, group_file_upload: convertGroupFileUpload, friend_add: convertFriendAdd, + friend_input_status: convertFriendInputStatus, + friend_profile_like: convertFriendProfileLike, + bot_offline: convertBotOffline, + group_name_change: convertGroupNameChange, + group_title_change: convertGroupTitleChange, + group_card_change: convertGroupCardChange, group_msg_emoji_like: convertGroupMsgEmojiLike, // Requests. friend_request: convertFriendRequest, diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index 05b8b762..2770aa57 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -17,6 +17,12 @@ type GroupEssence = Extract; type GroupFileUpload = Extract; type FriendAdd = Extract; type GroupMsgEmojiLike = Extract; +type FriendInputStatus = Extract; +type GroupNameChange = Extract; +type GroupCardChange = Extract; +type GroupTitleChange = Extract; +type FriendProfileLike = Extract; +type BotOffline = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -156,6 +162,77 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO }); } +export function convertGroupCardChange(ctx: ConverterContext, event: GroupCardChange): JsonObject { + // Mirrors NapCat's OB11GroupCardEvent: notice_type group_card with the new and + // old group cards. + return notice(ctx, event, { + notice_type: 'group_card', + group_id: event.groupId, + user_id: event.userUin, + card_new: event.cardNew, + card_old: event.cardOld, + }); +} + +export function convertBotOffline(ctx: ConverterContext, event: BotOffline): JsonObject { + // Mirrors NapCat's OB11BotOfflineEvent: notice_type bot_offline with the bot's + // own uin plus the tag/message describing why it went offline. + return notice(ctx, event, { + notice_type: 'bot_offline', + user_id: event.selfUin, + tag: event.tag, + message: event.message, + }); +} + +export function convertFriendProfileLike(ctx: ConverterContext, event: FriendProfileLike): JsonObject { + // Mirrors NapCat's OB11ProfileLikeEvent: notify/profile_like with the liker's + // uin, nickname and like count. + return notice(ctx, event, { + notice_type: 'notify', + sub_type: 'profile_like', + operator_id: event.operatorUin, + operator_nick: event.operatorNick, + times: event.times, + }); +} + +export function convertGroupTitleChange(ctx: ConverterContext, event: GroupTitleChange): JsonObject { + // Mirrors NapCat's OB11GroupTitleEvent: notify/title with the recipient's uin + // and the granted title text. + return notice(ctx, event, { + notice_type: 'notify', + sub_type: 'title', + group_id: event.groupId, + user_id: event.userUin, + title: event.title, + }); +} + +export function convertGroupNameChange(ctx: ConverterContext, event: GroupNameChange): JsonObject { + // Mirrors NapCat's OB11GroupNameEvent: notify/group_name with the operator's + // uin as user_id and the new name in `name_new`. + return notice(ctx, event, { + notice_type: 'notify', + sub_type: 'group_name', + group_id: event.groupId, + user_id: event.operatorUin, + name_new: event.name, + }); +} + +export function convertFriendInputStatus(ctx: ConverterContext, event: FriendInputStatus): JsonObject { + // Mirrors NapCat's OB11InputStatusEvent: notify/input_status with the peer's + // uin, the raw event_type (1 = typing, 3 = recording voice) and status_text. + return notice(ctx, event, { + notice_type: 'notify', + sub_type: 'input_status', + user_id: event.userUin, + event_type: event.eventType, + status_text: event.statusText, + }); +} + export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject { const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index c339c50a..1c278809 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -70,6 +70,12 @@ const NOTICE_KINDS = [ 'group_essence', 'group_file_upload', 'friend_add', + 'friend_input_status', + 'friend_profile_like', + 'bot_offline', + 'group_name_change', + 'group_title_change', + 'group_card_change', 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 3e91130c..1b4d5122 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1240,6 +1240,12 @@ async function parseForwardNodes( } const node: ForwardNodePayload = { userUin, nickname, elements }; + // Honour an explicit per-node display time (OneBot `data.time`, unix + // seconds) so a custom forward can set/back-date each node's timestamp + // (#209). The wire field is uint32, so reject a millisecond value or any + // out-of-range input (it would overflow/throw) and fall back to now. + const nodeTime = toPositiveInt(nodeData.time); + if (nodeTime > 0 && nodeTime < 0xffffffff) node.time = nodeTime; if (innerForward) node.innerForward = innerForward; nodes.push(node); } diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index 64458964..d4e3d13b 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -49,6 +49,68 @@ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): vo socket.close(code, reason); } +/** RFC6455 transport-level keepalive for a reverse-WS connection. + * + * The OneBot app-level `meta_event` heartbeat is a one-way outbound push, so it + * cannot detect a connection that is writable but no longer readable — a + * half-open link left behind when the peer restarts behind a proxy/NAT. In that + * state events keep flowing out while inbound action frames silently never + * arrive, and only a full restart recovers it (issue #208). + * + * This pings every `intervalMs` and counts consecutive silent intervals. ANY + * inbound activity — a pong OR a message — resets the counter, so a connection + * carrying real traffic is never reaped. Death is declared once `maxMissed` + * pings have gone unanswered, i.e. after roughly `(maxMissed + 1) * intervalMs` + * of total silence (the counter is checked at the top of each tick, so the + * tick that observes the threshold is one interval past the last ping). The + * tolerance plus a conservative interval keeps the false-positive rate near + * zero: a single GC pause, event-loop stall, or transient latency spike is + * absorbed (Node fires an overdue interval once, not N catch-up times), and + * death is declared only on genuine sustained silence. + * + * Returns an idempotent stop function; the timer is `unref`'d so it never keeps + * the process alive. */ +export function startHeartbeat( + socket: WebSocket, + opts: { intervalMs: number; maxMissed: number }, + onDead: () => void, +): () => void { + let missed = 0; + let stopped = false; + const onActivity = (): void => { missed = 0; }; + socket.on('pong', onActivity); + socket.on('message', onActivity); + + const timer = setInterval(() => { + if (missed >= opts.maxMissed) { + // `maxMissed` consecutive intervals with zero inbound traffic — the read + // direction is dead. Stop first so onDead()'s terminate→close→reconnect + // can't re-enter this tick. + stop(); + onDead(); + return; + } + missed += 1; + try { + socket.ping(); + } catch { + // Ping on an already-dead socket — treat as dead immediately. + stop(); + onDead(); + } + }, opts.intervalMs); + timer.unref?.(); + + function stop(): void { + if (stopped) return; + stopped = true; + clearInterval(timer); + socket.off?.('pong', onActivity); + socket.off?.('message', onActivity); + } + return stop; +} + export function normalizePath(pathValue: string | undefined): string { const path = (pathValue ?? '/').trim() || '/'; if (path === '/') return '/'; diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index 59682996..910e1495 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -8,10 +8,17 @@ import { } from '../event-filter'; import type { JsonObject, WsClientNetwork, WsRole } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils'; +import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils'; const moduleLog = createLogger('OneBot.WS-Client'); const DEFAULT_RECONNECT_INTERVAL_MS = 5000; +// Transport-level keepalive: ping every 30s, declare the link dead only after 2 +// consecutive pings go unanswered — ~90s of total silence (see startHeartbeat +// for the +1-interval timing). Conservative on purpose so transient jitter/GC +// never reaps a healthy connection. See issue #208. +const HEARTBEAT_INTERVAL_MS = 30_000; +const HEARTBEAT_MAX_MISSED = 2; +const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000; export class WsClientAdapter extends IOneBotNetworkAdapter { private socket: WebSocket | null = null; @@ -20,6 +27,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private role: WsRole; private explicitlyClosed = false; + // 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 + // closure in connect() still owns the #97 stale-socket case; this is idempotent + // with it (both call the same stop). + private heartbeatStop: (() => void) | null = null; constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx, moduleLog); @@ -41,6 +53,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { this.isEnabled = false; this.connected = false; this.cancelReconnect(); + this.heartbeatStop?.(); + this.heartbeatStop = null; if (this.socket) { safeClose(this.socket); this.socket = null; @@ -90,11 +104,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { const socket = new WebSocket(this.config.url, { headers }); this.socket = socket; + // Per-socket so a hot-reload overlap (old close firing after the new socket + // is assigned, see #97) can only ever stop its own keepalive. + let stopHeartbeat: (() => void) | null = null; socket.on('open', () => { + // Symmetric with the 'close' guard (#97): if this socket was already + // replaced, a late 'open' must not flip `connected` or install a stale + // heartbeat onto the current connection's slot. + if (this.socket !== socket) return; this.connected = true; this.log.info('[%s] connected %s', this.name, this.config.url); this.sendBootstrapMetaEvents(socket); + // Only meaningful once OPEN — ping() no-ops before the handshake completes. + stopHeartbeat = startHeartbeat( + socket, + { intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED }, + () => { + if (this.explicitlyClosed || !this.isEnabled) return; + this.log.warn('[%s] no inbound response for ~%ds, reconnecting half-open connection %s', this.name, HEARTBEAT_DEAD_AFTER_S, this.config.url); + // terminate → 'close' → scheduleReconnect, reusing the normal path. + socket.terminate(); + }, + ); + this.heartbeatStop = stopHeartbeat; }); socket.on('message', (raw: Buffer) => { @@ -104,6 +137,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { }); socket.on('close', () => { + stopHeartbeat?.(); + // Drop the instance handle only if it still points at THIS socket's stop + // (a newer socket may already own it after a hot-reload overlap). + if (this.heartbeatStop === stopHeartbeat) this.heartbeatStop = null; + stopHeartbeat = null; // Ignore close events from a socket that is no longer the current // connection. A hot reload (signature change) calls close() then open() // back-to-back; the old socket's `'close'` event fires AFTER the new diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index b2f2056f..088d03a0 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -9,14 +9,22 @@ import { } from '../event-filter'; import type { JsonObject, WsRole, WsServerNetwork } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils'; +import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils'; const moduleLog = createLogger('OneBot.WS-Server'); +// Transport keepalive for each attached client, symmetric with the ws-client +// adapter: ping every 30s, reap a client only after 2 consecutive pings go +// unanswered — ~90s of total silence (see startHeartbeat for the +1-interval +// timing). Any inbound frame resets the counter — see issue #208. +const HEARTBEAT_INTERVAL_MS = 30_000; +const HEARTBEAT_MAX_MISSED = 2; +const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000; interface ForwardConn { socket: WebSocket; role: WsRole; options: EventReportOptions; + stopHeartbeat: () => void; } export class WsServerAdapter extends IOneBotNetworkAdapter { @@ -50,7 +58,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.isEnabled = false; this.listening = false; - for (const ws of [...this.connections.keys()]) safeClose(ws); + for (const conn of this.connections.values()) { + conn.stopHeartbeat(); + safeClose(conn.socket); + } this.connections.clear(); this.wss?.close(); this.wss = null; @@ -115,7 +126,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { } const role = this.config.role ?? classifyForwardRole(request); - const conn: ForwardConn = { socket, role, options: this.options }; + const stopHeartbeat = startHeartbeat( + socket, + { intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED }, + () => { + this.log.warn('[%s] client silent for ~%ds, terminating half-open connection', this.name, HEARTBEAT_DEAD_AFTER_S); + socket.terminate(); // → 'close' → connections.delete; the client reconnects on its own + }, + ); + const conn: ForwardConn = { socket, role, options: this.options, stopHeartbeat }; this.connections.set(socket, conn); socket.on('message', (raw: Buffer) => { @@ -123,7 +142,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); }); }); - socket.on('close', () => this.connections.delete(socket)); + socket.on('close', () => { + stopHeartbeat(); + this.connections.delete(socket); + }); socket.on('error', (err: Error) => { this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err)); }); diff --git a/packages/onebot/tests/forward-nested.test.ts b/packages/onebot/tests/forward-nested.test.ts index fa285ed7..21623b3b 100644 --- a/packages/onebot/tests/forward-nested.test.ts +++ b/packages/onebot/tests/forward-nested.test.ts @@ -97,6 +97,31 @@ describe('forward — nested {type:"node"} content', () => { expect(sendGroupMessage).toHaveBeenCalledOnce(); }); + it('threads an explicit data.time onto the node payload, leaving absent ones for the default (#209)', async () => { + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID'); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, + })); + + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any); + const ctx = makeCtx(bridge); + + const messages = [ + { type: 'node', data: { user_id: 111, nickname: 'a', time: 1600000000, content: [{ type: 'text', data: { text: 'hi' } }] } }, + { type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'yo' } }] } }, + { type: 'node', data: { user_id: 333, nickname: 'c', time: 1700000000000, content: [{ type: 'text', data: { text: 'ms' } }] } }, // ms → out of uint32 range + { type: 'node', data: { user_id: 444, nickname: 'd', time: -5, content: [{ type: 'text', data: { text: 'neg' } }] } }, + ]; + + await sendGroupForwardMessage(ctx, 12345, messages as any); + + const [nodes] = uploadForwardNodes.mock.calls[0]!; + expect((nodes as any[])[0].time).toBe(1600000000); // explicit seconds carried through + expect((nodes as any[])[1].time).toBeUndefined(); // absent → default to now + expect((nodes as any[])[2].time).toBeUndefined(); // millisecond input rejected (uint32 overflow guard) + expect((nodes as any[])[3].time).toBeUndefined(); // negative rejected → default to now + }); + it('private: nested forward threads userId into uploadForwardNodes', async () => { // Same shape but routed via sendPrivateForwardMessage. The c2c path // passes `userId` instead of `groupId` so the upload pipeline can diff --git a/packages/onebot/tests/ws-client-heartbeat.test.ts b/packages/onebot/tests/ws-client-heartbeat.test.ts new file mode 100644 index 00000000..2930d08e --- /dev/null +++ b/packages/onebot/tests/ws-client-heartbeat.test.ts @@ -0,0 +1,225 @@ +// Issue #208: after a reverse-WS reconnect the link could end up half-open — +// writable (events keep flowing out) but not readable (inbound action frames +// never arrive), a state only a full restart recovered. The fix adds a +// transport-level ping/pong keepalive that reconnects a genuinely silent link. +// +// These tests pin BOTH sides of the contract: it must reconnect a dead link, +// and — the harder half — it must NOT reap a healthy one. The false-positive +// guards are the point: death is declared only after `maxMissed` consecutive +// intervals with zero inbound traffic (pong OR message), so pong round-trips +// and live message flow both keep a connection alive indefinitely. +// +// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout), +// mirroring ws-client-stale-close.test.ts. Timers are faked and driven. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { FakeWebSocket, instances } = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { EventEmitter } = require('node:events') as typeof import('node:events'); + const instances: FakeWebSocket[] = []; + + class FakeWebSocket extends EventEmitter { + public readyState = 1; // 1 = OPEN, 2 = CLOSING, 3 = CLOSED + public pings = 0; + public terminated = false; + public readonly url: string; + + constructor(url: string, _opts: unknown) { + super(); + this.url = url; + instances.push(this); + } + + send(_payload: string, cb?: (err?: Error | null) => void): void { cb?.(null); } + ping(): void { this.pings += 1; } + terminate(): void { + if (this.readyState === 3) return; + this.terminated = true; + this.readyState = 3; + this.emit('close'); // real terminate → destroy → deferred 'close'; sync here + } + close(code = 1000, reason = 'normal'): void { + void code; void reason; + if (this.readyState >= 2) return; + this.readyState = 2; // do NOT auto-emit 'close' (matches the real deferral) + } + + simulateOpen(): void { this.emit('open'); } + simulatePong(): void { this.emit('pong', Buffer.alloc(0)); } + simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); } + simulateClose(): void { this.readyState = 3; this.emit('close'); } + } + + return { FakeWebSocket, instances }; +}); + +vi.mock('@snowluma/websocket', () => ({ WebSocket: FakeWebSocket })); + +import { WsClientAdapter } from '../src/network/ws-client-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { WsClientNetwork } from '../src/types'; + +// Must match the adapter's module constants. +const INTERVAL = 30_000; +const MAX_MISSED = 2; + +function ctx(): NetworkAdapterContext { + return { + uin: '10001', + api: { processStreamRequest: async () => {} } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), + }; +} + +function cfg(over: Partial = {}): WsClientNetwork { + return { + enabled: true, + url: 'ws://127.0.0.1:8080/', + role: 'Universal', + reconnectIntervalMs: 1000, + ...over, + } as WsClientNetwork; +} + +describe('WsClientAdapter — transport heartbeat (issue #208)', () => { + beforeEach(() => { instances.length = 0; }); + + it('reconnects a silent (half-open) connection, but only after maxMissed intervals', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // maxMissed silent intervals are TOLERATED — the counter absorbs transient + // jitter/GC without reaping. Still alive here. + vi.advanceTimersByTime(INTERVAL * MAX_MISSED); + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + + // The next silent interval crosses the threshold: terminate → 'close' → + // scheduleReconnect (no new socket until the reconnect interval elapses). + vi.advanceTimersByTime(INTERVAL); + expect(a.terminated).toBe(true); + expect(instances).toHaveLength(1); + + vi.advanceTimersByTime(1000); + expect(instances).toHaveLength(2); // reconnect spun up a fresh socket + expect(instances[1]).not.toBe(a); + } finally { + vi.useRealTimers(); + } + }); + + it('never reaps a healthy connection whose pong lags a full interval', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // Each cycle lets TWO intervals pass with no pong (missed climbs 0→1→2) + // before a pong arrives, so a non-zero `missed` is carried across a check + // boundary. A broken 1-strike (`missed >= 1`) impl reaps on the 2nd tick; + // the real 2-strike tolerance survives (the fatal `>= 2` check never sees + // 2 because the pong resets first). + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 1 + vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 2 (still alive) + a.simulatePong(); // pong resets missed → 0 + } + + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + expect(a.pings).toBeGreaterThan(0); // it WAS actively probing + } finally { + vi.useRealTimers(); + } + }); + + it('treats inbound message traffic as liveness (no pong needed)', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + + // No pongs at all, but a message arrives every interval. A busy link is + // provably alive, so it must never be reaped. + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); + a.simulateMessage(); + } + + expect(a.terminated).toBe(false); + expect(instances).toHaveLength(1); + } finally { + vi.useRealTimers(); + } + }); + + it('close() proactively stops the heartbeat — no lingering pings on the socket', () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + vi.advanceTimersByTime(INTERVAL); // one real tick → a.pings === 1 + + // close() must halt the keepalive immediately, NOT wait for the deferred + // 'close' event (a real ws defers it). No further pings, no reap. + adapter.close(); + const pingsAtClose = a.pings; + vi.advanceTimersByTime(INTERVAL * 5); + expect(a.pings).toBe(pingsAtClose); + expect(a.terminated).toBe(false); + expect(adapter.describeStatus().status).toBe('disabled'); + } finally { + vi.useRealTimers(); + } + }); + + it('a hot-reload does not let the old socket heartbeat reap the new one (#97 + #208)', async () => { + vi.useFakeTimers(); + try { + const adapter = new WsClientAdapter('ws', cfg(), ctx()); + adapter.open(); + const a = instances[0]; + a.simulateOpen(); + vi.advanceTimersByTime(INTERVAL); // a's heartbeat has ticked once + + // Hot reload (URL change) → base class close() then open(); close() stops + // a's heartbeat proactively before b is created. + await adapter.reload(cfg({ url: 'ws://127.0.0.1:8081/' })); + expect(instances).toHaveLength(2); + const b = instances[1]; + b.simulateOpen(); + + const aPingsAfterReload = a.pings; + // Advance well past a's would-be death window. a's heartbeat was stopped by + // the reload, so it never pings/terminates; b keeps its own healthy loop. + for (let i = 0; i < 6; i++) { + vi.advanceTimersByTime(INTERVAL); + b.simulatePong(); + } + // Stale socket's delayed close finally lands — must not disturb b. + a.simulateClose(); + vi.advanceTimersByTime(INTERVAL); + b.simulatePong(); // b stays healthy through the stale event + + expect(a.pings).toBe(aPingsAfterReload); // a's timer never fired again + expect(a.terminated).toBe(false); + expect(b.terminated).toBe(false); + expect(instances).toHaveLength(2); // no stray reconnect socket + expect(adapter.describeStatus().status).toBe('ok'); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/packages/onebot/tests/ws-server-heartbeat.test.ts b/packages/onebot/tests/ws-server-heartbeat.test.ts new file mode 100644 index 00000000..9dba27cf --- /dev/null +++ b/packages/onebot/tests/ws-server-heartbeat.test.ts @@ -0,0 +1,148 @@ +// Issue #208 (server side): symmetric transport keepalive for the reverse-WS +// SERVER. Each attached client is pinged; a client that goes fully silent for +// maxMissed consecutive intervals is terminated (and drops out of the +// connection set) so a half-open client can't wedge forever. A healthy or +// actively-messaging client must never be reaped — the same false-positive +// guard as the client adapter. +// +// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout), +// mirroring network-bootstrap-meta.test.ts. Timers are faked and driven. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { FakeWebSocket, FakeWebSocketServer, servers } = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { EventEmitter } = require('node:events') as typeof import('node:events'); + const servers: FakeWebSocketServer[] = []; + + class FakeWebSocket extends EventEmitter { + public readyState = 1; // OPEN + public pings = 0; + public terminated = false; + send(_payload: string, cb?: (err?: Error | null) => void): void { cb?.(null); } + ping(): void { this.pings += 1; } + terminate(): void { + if (this.readyState === 3) return; + this.terminated = true; + this.readyState = 3; + this.emit('close'); + } + close(): void { if (this.readyState < 2) this.readyState = 2; } + simulatePong(): void { this.emit('pong', Buffer.alloc(0)); } + simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); } + } + + class FakeWebSocketServer extends EventEmitter { + public closed = false; + constructor(_opts: unknown) { super(); servers.push(this); } + close(): void { this.closed = true; } + simulateConnection(socket: FakeWebSocket, request: unknown): void { + this.emit('connection', socket, request); + } + } + + return { FakeWebSocket, FakeWebSocketServer, servers }; +}); + +vi.mock('@snowluma/websocket', () => ({ + WebSocket: FakeWebSocket, + WebSocketServer: FakeWebSocketServer, +})); + +import { WsServerAdapter } from '../src/network/ws-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { WsServerNetwork } from '../src/types'; + +const INTERVAL = 30_000; +const MAX_MISSED = 2; + +function ctx(): NetworkAdapterContext { + return { + uin: '10001', + api: { processStreamRequest: async () => {} } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), + }; +} + +function cfg(over: Partial = {}): WsServerNetwork { + return { enabled: true, host: '0.0.0.0', port: 8080, path: '/', role: 'Universal', ...over } as WsServerNetwork; +} + +const REQUEST = { url: '/', headers: {} } as unknown; + +function connect(): { adapter: WsServerAdapter; socket: InstanceType } { + const adapter = new WsServerAdapter('ws', cfg(), ctx()); + adapter.open(); + const server = servers[servers.length - 1]; + server.emit('listening'); // adapter marks itself listening → status 'ok' + const socket = new FakeWebSocket(); + server.simulateConnection(socket, REQUEST); + return { adapter, socket }; +} + +describe('WsServerAdapter — transport heartbeat (issue #208)', () => { + beforeEach(() => { servers.length = 0; }); + + it('reaps a silent client only after maxMissed intervals, then drops it', () => { + vi.useFakeTimers(); + try { + const { adapter, socket } = connect(); + expect(adapter.describeStatus().detail).toBe('1 个客户端'); + + vi.advanceTimersByTime(INTERVAL * MAX_MISSED); // tolerated + expect(socket.terminated).toBe(false); + + vi.advanceTimersByTime(INTERVAL); // threshold crossed + expect(socket.terminated).toBe(true); + expect(adapter.describeStatus().detail).toBe('0 个客户端'); + } finally { + vi.useRealTimers(); + } + }); + + it('never reaps a client that keeps ponging', () => { + vi.useFakeTimers(); + try { + const { adapter, socket } = connect(); + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); + socket.simulatePong(); + } + expect(socket.terminated).toBe(false); + expect(adapter.describeStatus().detail).toBe('1 个客户端'); + expect(socket.pings).toBeGreaterThan(0); + } finally { + vi.useRealTimers(); + } + }); + + it('treats inbound messages as liveness', () => { + vi.useFakeTimers(); + try { + const { adapter, socket } = connect(); + for (let i = 0; i < 10; i++) { + vi.advanceTimersByTime(INTERVAL); + socket.simulateMessage(); + } + expect(socket.terminated).toBe(false); + expect(adapter.describeStatus().detail).toBe('1 个客户端'); + } finally { + vi.useRealTimers(); + } + }); + + it('stops all client heartbeats on adapter close — no lingering pings', () => { + vi.useFakeTimers(); + try { + const { adapter, socket } = connect(); + adapter.close(); + const pingsAtClose = socket.pings; + vi.advanceTimersByTime(INTERVAL * 5); + expect(socket.pings).toBe(pingsAtClose); + expect(socket.terminated).toBe(false); // closed cleanly, not reaped + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index ff0e7254..7de9613a 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index 68903cb2..16d722ba 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -262,3 +262,80 @@ export interface GroupReactNotify { field13?: pb<13, uint_32>; groupReactionData?: pb<44, GroupReactionData>; } + +// Forced-offline ("被迫下线") push — SSO cmd +// `trpc.qq_new_tech.status_svc.StatusService.KickNT`. QQ NT's unified offline +// notification (kick / login-elsewhere / risk-control-triggered offline all +// arrive here; the reason is in the strings). Field layout RE'd from +// wrapper.linux.node (log fmt "tips_title:{} tips_content:{}") + Lagrange's +// ServiceKickNTResponse: f4 = tips_title (short title), f3 = tips_content (desc). +export interface KickNTResponse { + uin?: pb<1, uint_32>; + tips?: pb<3, string>; // tips_content — the longer description + title?: pb<4, string>; // tips_title — the short title +} + +// Group-name change (Event 0x2DC subType 16, NotifyMessageBody.field13 == 12). +// Rides in `NotifyMessageBody.eventParam` (field 5). Field layout matches +// Lagrange's `GroupNameChange` (RE'd from wrapper.linux.node): only the new +// name at field 2. The operator uid is `NotifyMessageBody.operatorUid` (f21). +export interface GroupNameChange { + name?: pb<2, string>; +} + +// Group special-title granted (Event 0x2DC subType 16, NotifyMessageBody.field13 +// == 6). Rides in `NotifyMessageBody.eventParam` (field 5). Field layout captured +// on-wire: f2 = the gray-tip template text ("恭喜<{…}>获得群主授予的<{…"text":TITLE…}>头衔"), +// f5 = the member uin who received the title. The title text itself is embedded in +// the last `<{…}>` rich token of f2 (the kernel parses that template into a clean +// string; on the raw wire we parse it ourselves). +export interface GroupSpecialTitleChange { + tipText?: pb<2, string>; + memberUin?: pb<5, uint_32>; +} + +// Profile-like ("名片赞") notify — Event 0x210 subType 39, whose body.msgContent +// decodes as this ProfileLikeTip. subType 39 is multiplexed; only inner +// msgType==0 && subType==203 is a like. Field numbers CONFIRMED byte-exact against +// real on-wire captures (detail.txt = "赞了我的资料卡N次", f3=liker uin, f5=nick); +// the like count is parsed from `detail.txt`. +export interface ProfileLikeDetail { + txt?: pb<1, string>; + uin?: pb<3, uint_64>; + nickname?: pb<5, string>; +} + +export interface ProfileLikeMsg { + times?: pb<1, int_32>; + time?: pb<2, int_32>; + detail?: pb<3, ProfileLikeDetail>; +} + +export interface ProfileLikeSubTip { + msg?: pb<14, ProfileLikeMsg>; +} + +export interface ProfileLikeTip { + msgType?: pb<1, int_32>; + subType?: pb<2, int_32>; + content?: pb<203, ProfileLikeSubTip>; +} + +// C2C input-status notify — the "对方正在输入…" push. Delivered as a system +// message (msgType 0x210 / subMsgType 0x115) whose `MsgBody.msgContent` carries +// this body. Field layout RE'd from `wrapper.linux.node` +// `aio_input_state_worker.cc::ProcessInputStateNotifySysMsg` (reads f1=fromUid, +// f2=toUid, f3=notifyItem; the item's f4 is the event type). +export interface InputStatusNotifyItem { + field2?: pb<2, uint_32>; + field3?: pb<3, uint_64>; + eventType?: pb<4, uint_32>; // 1 = 正在输入 (typing), 3 = 正在讲话 (recording voice) + field5?: pb<5, uint_32>; + statusText?: pb<6, string>; +} + +export interface InputStatusNotify { + fromUid?: pb<1, string>; + toUid?: pb<2, string>; + notifyItem?: pb<3, InputStatusNotifyItem>; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 987ff78e..3411423b 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", @@ -28,6 +28,10 @@ "types": "./src/packet-pipeline.ts", "default": "./src/packet-pipeline.ts" }, + "./kick-nt": { + "types": "./src/kick-nt.ts", + "default": "./src/kick-nt.ts" + }, "./element-builder": { "types": "./src/element-builder.ts", "default": "./src/element-builder.ts" diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 5b0af057..dade5237 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -294,6 +294,77 @@ export interface PttTransResultEvent extends QQEvent { text: string; } +/** + * The bot account was forced offline (kicked / logged in elsewhere / risk-control) + * — SSO push `StatusService.KickNT`. Mirrors NapCat's OB11BotOfflineEvent → + * `notice_type:'bot_offline'`. `tag` = short title, `message` = description. + */ +export interface BotOfflineEvent extends QQEvent { + kind: 'bot_offline'; + tag: string; + message: string; +} + +/** + * A group member's card (群名片) changed — detected from message traffic when + * the sender's live card differs from the cached one (same mechanism as NapCat's + * `parseCardChangedEvent`). Maps to OB11 `notice_type:'group_card'`. + */ +export interface GroupCardChangeEvent extends QQEvent { + kind: 'group_card_change'; + groupId: number; + userUin: number; + cardNew: string; + cardOld: string; +} + +/** + * A group member was granted a special title (群头衔) — Event 0x2DC subType 16, + * field13 == 6. Maps to OB11 `notice/notify` `sub_type:'title'`. + */ +export interface GroupTitleChangeEvent extends QQEvent { + kind: 'group_title_change'; + groupId: number; + userUin: number; // the member who received the title + title: string; +} + +/** + * Group name changed (Event 0x2DC subType 16, field13 == 12). Mirrors NapCat's + * OB11GroupNameEvent → `notice/notify` `sub_type:'group_name'`. + */ +export interface GroupNameChangeEvent extends QQEvent { + kind: 'group_name_change'; + groupId: number; + operatorUin: number; // who renamed the group + name: string; // the new group name +} + +/** + * Someone liked the bot's profile card ("名片赞") — Event 0x210 subType 39, + * inner ProfileLikeTip msgType 0 / subType 203. Mirrors NapCat's + * OB11ProfileLikeEvent → `notice/notify` `sub_type:'profile_like'`. + */ +export interface FriendProfileLikeEvent extends QQEvent { + kind: 'friend_profile_like'; + operatorUin: number; // who liked + operatorNick: string; + times: number; // like count from this event +} + +/** + * C2C "对方正在输入…" input-status push (Event 0x210 subType 0x115 / 277). + * `eventType` 1 = typing, 3 = recording a voice message. Mirrors NapCat's + * `onInputStatusPush` → OB11 `notice/notify` `sub_type:'input_status'`. + */ +export interface FriendInputStatusEvent extends QQEvent { + kind: 'friend_input_status'; + userUin: number; // the peer whose input status changed (the typer) + userUid: string; + eventType: number; // 1 = 正在输入, 3 = 正在讲话(录音) + statusText: string; +} + export type QQEventVariant = | FriendMessage | GroupMessage @@ -312,4 +383,10 @@ export type QQEventVariant = | GroupFileUploadEvent | FriendAddEvent | GroupMsgEmojiLikeEvent - | PttTransResultEvent; + | PttTransResultEvent + | FriendInputStatusEvent + | GroupNameChangeEvent + | GroupCardChangeEvent + | GroupTitleChangeEvent + | FriendProfileLikeEvent + | BotOfflineEvent; diff --git a/packages/protocol/src/kick-nt.ts b/packages/protocol/src/kick-nt.ts new file mode 100644 index 00000000..c5f4483b --- /dev/null +++ b/packages/protocol/src/kick-nt.ts @@ -0,0 +1,33 @@ +// Forced-offline push. QQ NT tells a client it was kicked / logged in elsewhere / +// dropped for risk-control via the SSO command +// `trpc.qq_new_tech.status_svc.StatusService.KickNT`, whose body is a +// `KickNTResponse`. We surface it as a `bot_offline` event (NapCat parity). +// +// The push arrives on the same StatusService channel SnowLuma already receives +// (e.g. StatusService.SsoHeartBeat), so it just needs its own cmd handler. +// Command + field layout RE-confirmed against wrapper.linux.node + Lagrange's +// KickNTService/ServiceKickNTResponse. + +import { protobuf_decode } from '@snowluma/proton'; +import type { KickNTResponse } from '@snowluma/proto-defs/notify'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { IdentityService } from './identity-service'; +import type { QQEventVariant } from './events'; + +export const KICK_NT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.KickNT'; + +type BotOfflineEvent = Extract; + +export function parseKickNT(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] { + const resp = protobuf_decode(pkt.body); + if (!resp) return []; + const ev: BotOfflineEvent = { + kind: 'bot_offline', + // KickNT carries no timestamp — stamp with receive time. + time: Math.floor(Date.now() / 1000), + selfUin: Number(pkt.uin) || Number(identity.uin) || 0, + tag: resp.title ?? '', // tips_title — the short title + message: resp.tips ?? '', // tips_content — the description / reason + }; + return [ev]; +} diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 65a922c0..acc3ffb5 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -10,7 +10,9 @@ import type { FriendRecall, FriendRequest, GeneralGrayTipInfo, + InputStatusNotify, NewFriend, + ProfileLikeTip, } from '@snowluma/proto-defs/notify'; import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans'; import type { MsgPushContext } from '../context'; @@ -23,6 +25,8 @@ import { import type { MsgPushDecoder } from '../registry'; type FriendRecallEvent = Extract; +type FriendInputStatusEvent = Extract; +type FriendProfileLikeEvent = Extract; const unknownLog = createLogger('MsgPush.Unknown'); @@ -37,6 +41,8 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { case Event0x210SubType.FriendRecallSelfNotice: return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx); + case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx); // 179 + 226 both carry the NewFriend payload — see enum comment. case Event0x210SubType.NewFriendNotice: case Event0x210SubType.NewFriendNoticeAlt: @@ -128,6 +134,60 @@ function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] { return [ev]; } +// C2C "对方正在输入…" input-status push. Body (`InputStatusNotify`) rides in +// `body.msgContent` (= ctx.content). Layout + event-type semantics RE'd from +// `aio_input_state_worker.cc::ProcessInputStateNotifySysMsg`: the notify item's +// field 4 is the event type (1 = typing, 3 = recording voice). The client +// synthesises the status text from that type, so we do the same for OneBot +// parity (NapCat's `onInputStatusPush` → `notice/notify` `input_status`). +function decodeInputStatus(ctx: MsgPushContext): QQEventVariant[] { + const notify = protobuf_decode(ctx.content); + const fromUid = notify?.fromUid ?? ''; + if (!fromUid) return []; + const eventType = notify.notifyItem?.eventType ?? 1; + const ev: FriendInputStatusEvent = { + kind: 'friend_input_status', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + userUin: resolveUidToUin(ctx.identity, 0, fromUid, ctx.fromUin), + userUid: fromUid, + eventType, + statusText: inputStatusText(eventType), + }; + return [ev]; +} + +// The client's own strings (wrapper.linux.node @0xB8FFE0 / @0xB90000). +function inputStatusText(eventType: number): string { + return eventType === 3 ? '对方正在讲话...' : '对方正在输入...'; +} + +// subType 39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a +// profile-like ("名片赞") only when inner msgType==0 && subType==203. Other 39 +// variants (multi-device sync etc.) decode to a non-matching tip → dropped. +// `times` is the like count parsed out of `detail.txt` ("赞了我的资料卡N次"). +// Field layout confirmed byte-exact against real on-wire captures. +function decodeProfileLike(ctx: MsgPushContext): QQEventVariant[] { + const tip = protobuf_decode(ctx.content); + // msgType 0 is the proto default → omitted on the wire → decodes as undefined, + // so treat missing as 0 (matches NapCat's `msgType !== 0` check). + if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) return []; + const msg = tip.content?.msg; + const detail = msg?.detail; + const operatorUin = Number(detail?.uin ?? 0n); + if (!operatorUin) return []; + const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0; + const ev: FriendProfileLikeEvent = { + kind: 'friend_profile_like', + time: msg?.time || ctx.head.timestamp, + selfUin: ctx.selfUin, + operatorUin, + operatorNick: detail?.nickname ?? '', + times, + }; + return [ev]; +} + function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { const grayTip = protobuf_decode(ctx.content); if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return []; diff --git a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts index ca0b4dbe..95e1595c 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts @@ -4,12 +4,16 @@ import type { GroupEssenceEvent, GroupMsgEmojiLikeEvent, GroupMuteEvent, + GroupNameChangeEvent, + GroupTitleChangeEvent, GroupPokeEvent, GroupRecallEvent, QQEventVariant, } from '../../events'; import type { GroupMute, + GroupNameChange, + GroupSpecialTitleChange, GroupReactNotify, NotifyMessageBody, } from '@snowluma/proto-defs/notify'; @@ -28,7 +32,7 @@ const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x2DCSubType) { case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx); - case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx); + case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeSubType16(ctx); case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx); case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx); case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx); @@ -123,6 +127,84 @@ const GROUP_REACT_PREFIX_BYTES = 7; // for other notify variants, only 35 means "emoji react". Anything // else falls through to MsgPush.Unknown for protocol-drift visibility. const GROUP_REACT_DISCRIMINATOR = 35; +// Event 0x2DC subType 16 multiplexes several group notices, discriminated by +// `NotifyMessageBody.field13`. RE cross-ref (Lagrange Event0x2DCSubType16Field13, +// itself RE'd from wrapper.linux.node): 6=special title, 12=name change, 23=todo, +// 35=emoji reaction. We peek field13 off the shared NotifyMessageBody, then branch. +const SUBTYPE16_SPECIAL_TITLE = 6; +const SUBTYPE16_GROUP_NAME_CHANGE = 12; + +function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] { + if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return []; + const field13 = protobuf_decode(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))?.field13 ?? 0; + switch (field13) { + case SUBTYPE16_SPECIAL_TITLE: return decodeGroupTitle(ctx); + case SUBTYPE16_GROUP_NAME_CHANGE: return decodeGroupName(ctx); + case GROUP_REACT_DISCRIMINATOR: return decodeGroupMsgEmojiLike(ctx); + default: + unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13); + return []; + } +} + +// field13 == 6: a member was granted a special title. eventParam carries the +// member uin (f5) + a gray-tip template string (f2); the title text is the last +// `<{"…","text":TITLE,…}>` rich token in that string (on-wire captured shape — +// the kernel resolves the template to a clean string, we parse it here). +function decodeGroupTitle(ctx: MsgPushContext): QQEventVariant[] { + const notify = protobuf_decode(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES)); + const param = notify?.eventParam + ? protobuf_decode(notify.eventParam) + : undefined; + const userUin = param?.memberUin ?? 0; + const title = extractTitleFromTip(param?.tipText ?? ''); + if (!userUin || !title) return []; + const ev: GroupTitleChangeEvent = { + kind: 'group_title_change', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId: notify?.groupUin ?? 0, + userUin, + title, + }; + return [ev]; +} + +// The tip text is "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔" — the title is +// the `text` of the LAST `<{…}>` rich token (the one just before "头衔"). Tokens +// are flat JSON with no `<`/`>` inside, so a non-greedy scan is safe. +function extractTitleFromTip(text: string): string { + const tokens = text.match(/<\{[^<>]*\}>/g); + if (!tokens || tokens.length === 0) return ''; + const last = tokens[tokens.length - 1]; + try { + const parsed = JSON.parse(last.slice(1, -1)) as { text?: string }; + return parsed.text ?? ''; + } catch { + return ''; + } +} + +// field13 == 12: group renamed. New name is nested in `eventParam` as a +// `GroupNameChange` (field 2); operator is `NotifyMessageBody.operatorUid`. +function decodeGroupName(ctx: MsgPushContext): QQEventVariant[] { + const notify = protobuf_decode(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES)); + const name = notify?.eventParam ? (protobuf_decode(notify.eventParam)?.name ?? '') : ''; + if (!name) return []; + const groupId = notify?.groupUin ?? 0; + const ev: GroupNameChangeEvent = { + kind: 'group_name_change', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId, + // Operator is a group member → resolves from the roster. Fall back to 0 + // (not ctx.fromUin, which on a 0x2DC push is the group id) so an + // unresolved operator never surfaces the group id as user_id. + operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? '', 0), + name, + }; + return [ev]; +} function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] { if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return []; diff --git a/packages/protocol/src/msg-push/enums.ts b/packages/protocol/src/msg-push/enums.ts index e94c157c..a408bb44 100644 --- a/packages/protocol/src/msg-push/enums.ts +++ b/packages/protocol/src/msg-push/enums.ts @@ -67,6 +67,23 @@ export enum Event0x210SubType { */ NewFriendNotice = 179, NewFriendNoticeAlt = 226, + /** + * Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of + * its variants is the profile-like ("名片赞") push: body.msgContent decodes as + * `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203. + * NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants + * (multi-device sync etc.) fall through. + */ + ProfileLikeNotice = 39, + /** + * C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277). + * RE-confirmed against `wrapper.linux.node` + * `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly + * `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload + * (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's + * `onInputStatusPush`. + */ + InputStatusNotice = 277, /** * Group-app state push (troop shortcut bar / discussion app). * diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index 4ef9098a..6f27b5d1 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -104,7 +104,12 @@ export class IncomingPacketPipeline { err instanceof Error ? (err.stack ?? err.message) : String(err)); }); } else { + // Snapshot the sender's cached group card BEFORE dispatch — the + // side-effects inside finishDispatch self-heal (overwrite) it, so we + // must read it first to detect a real change and surface group_card. + const cardBefore = this.groupCardBefore(event); this.finishDispatch(event); + this.emitGroupCardChange(event, cardBefore); } } } catch (e) { @@ -119,6 +124,32 @@ export class IncomingPacketPipeline { void this.deps.events.emit(event); } + /** The sender's cached group card just before this event is dispatched (its + * side-effects will overwrite the cache). Only meaningful for group_message. */ + private groupCardBefore(event: QQEventVariant): string | undefined { + if (event.kind !== 'group_message') return undefined; + return this.deps.identity.findGroupMember(event.groupId, event.senderUin)?.card; + } + + /** Surface a `group_card_change` when a KNOWN member's card actually changed — + * mirrors NapCat's `parseCardChangedEvent`. Requires a non-empty prior card + * (`cardBefore`) that differs from a non-empty new one, so a cold/unknown + * cache never fabricates a change on first contact. */ + private emitGroupCardChange(event: QQEventVariant, cardBefore: string | undefined): void { + if (event.kind !== 'group_message') return; + const cardNew = event.senderCard ?? ''; + if (!cardBefore || !cardNew || cardBefore === cardNew) return; + this.finishDispatch({ + kind: 'group_card_change', + time: event.time, + selfUin: event.selfUin, + groupId: event.groupId, + userUin: event.senderUin, + cardNew, + cardOld: cardBefore, + }); + } + /** * Common dispatch tail shared by the sync path and the two async enrichment * paths: run side effects, log the event, then emit it. `alreadyRefreshed` is diff --git a/packages/protocol/tests/kick-nt.test.ts b/packages/protocol/tests/kick-nt.test.ts new file mode 100644 index 00000000..5501e203 --- /dev/null +++ b/packages/protocol/tests/kick-nt.test.ts @@ -0,0 +1,41 @@ +// StatusService.KickNT (forced-offline push) → bot_offline event. +// Command + field layout RE-confirmed against wrapper.linux.node + Lagrange's +// KickNTService/ServiceKickNTResponse (f4 = tips_title, f3 = tips_content). + +import { describe, expect, it } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import { parseKickNT, KICK_NT_CMD } from '@snowluma/protocol/kick-nt'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { KickNTResponse } from '@snowluma/proto-defs/notify'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { QQEventVariant } from '@snowluma/protocol/events'; + +type BotOfflineEvent = Extract; + +describe('parseKickNT (StatusService.KickNT → bot_offline)', () => { + const identity = IdentityService.memory('3433035623'); + + function pkt(resp: KickNTResponse, uin = '3433035623'): PacketInfo { + return { + pid: 1, uin, serviceCmd: KICK_NT_CMD, seqId: 1, retCode: 0, + fromClient: false, body: protobuf_encode(resp), + }; + } + + it('emits bot_offline with tag=title (f4) and message=tips (f3)', () => { + const [ev] = parseKickNT( + pkt({ uin: 3433035623, title: '你已离线', tips: '你的账号在其他设备登录' }), + identity, + ) as BotOfflineEvent[]; + + expect(ev.kind).toBe('bot_offline'); + expect(ev.selfUin).toBe(3433035623); + expect(ev.tag).toBe('你已离线'); + expect(ev.message).toBe('你的账号在其他设备登录'); + }); + + it('falls back to the identity uin when the packet uin is missing', () => { + const [ev] = parseKickNT(pkt({ title: 't', tips: 'm' }, ''), identity) as BotOfflineEvent[]; + expect(ev.selfUin).toBe(3433035623); + }); +}); diff --git a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts index c117feab..db799d0c 100644 --- a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts +++ b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts @@ -13,6 +13,7 @@ import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; import type { QQEventVariant } from '@snowluma/protocol/events'; +import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; import type { PacketInfo } from '@snowluma/common/protocol-types'; function makePipeline(opts: { @@ -346,3 +347,70 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => { expect(identity.findGroupMember(9999, 222)).toBeNull(); }); }); + +describe('IncomingPacketPipeline / group_card_change from message traffic', () => { + const GROUP = 123456789; + + function member(card: string): GroupMemberInfo { + return { + uin: 22222, uid: 'u_member', nickname: 'nick', card, role: 'member', + level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0, + }; + } + + function setup(cachedCard: string) { + const identity = IdentityService.memory('10001'); + identity.rememberGroups([{ + groupId: GROUP, groupName: 'g', remark: '', memberCount: 1, memberMax: 500, + members: new Map([[22222, member(cachedCard)]]), + } as QQGroupInfo]); + const events = new BridgeEventBus(); + const pipeline = new IncomingPacketPipeline({ + identity, events, + refreshMemberCache: vi.fn(async () => false), + resolveStrangerProfile: vi.fn(async () => null), + resolveGroupJoinRequest: vi.fn(async () => null), + }); + const captured: QQEventVariant[] = []; + events.onAny((e) => captured.push(e as QQEventVariant)); + return { pipeline, captured }; + } + + function groupMsg(card: string): QQEventVariant { + return { + kind: 'group_message', time: 1700000000, selfUin: 10001, groupId: GROUP, + senderUin: 22222, senderNick: 'nick', senderCard: card, senderRole: 'member', + msgSeq: 1, msgId: 1, elements: [], + } as QQEventVariant; + } + + const pkt = (): PacketInfo => ({ + pid: 1, uin: '10001', serviceCmd: 'test.cmd', seqId: 1, retCode: 0, + fromClient: false, body: new Uint8Array(), + }); + + it('emits group_card_change when a known member card changes', () => { + const { pipeline, captured } = setup('OldCard'); + pipeline.registerCmd('test.cmd', () => [groupMsg('NewCard')]); + pipeline.process(pkt()); + const ev = captured.find((e) => e.kind === 'group_card_change'); + expect(ev).toBeTruthy(); + expect((ev as Extract).cardOld).toBe('OldCard'); + expect((ev as Extract).cardNew).toBe('NewCard'); + expect((ev as Extract).userUin).toBe(22222); + }); + + it('does NOT emit when the card is unchanged', () => { + const { pipeline, captured } = setup('SameCard'); + pipeline.registerCmd('test.cmd', () => [groupMsg('SameCard')]); + pipeline.process(pkt()); + expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false); + }); + + it('does NOT fabricate a change on first contact (no cached card)', () => { + const { pipeline, captured } = setup(''); + pipeline.registerCmd('test.cmd', () => [groupMsg('SomeCard')]); + pipeline.process(pkt()); + expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false); + }); +}); diff --git a/packages/proton/package.json b/packages/proton/package.json index d3f0c1f7..bc773523 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 65446917..964669a4 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index fe6f581f..900901d2 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.11.4", + "version": "1.12.0", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index d244402b..191f6a8f 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.11.4", + "version": "1.12.0", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index f14dbc1e..0f4301ca 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.11.4", + "version": "1.12.0", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 49637a9b..7430ce2a 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.11.4", + "version": "1.12.0", "type": "module", "scripts": { "dev": "vite", @@ -20,6 +20,7 @@ "@radix-ui/react-slot": "^1.1.3", "@radix-ui/react-tooltip": "^1.1.9", "@tanstack/react-router": "^1.169.2", + "@tanstack/react-virtual": "^3.14.5", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "gridstack": "^12.6.0", diff --git a/packages/webui/src/components/debug/live-activity.tsx b/packages/webui/src/components/debug/live-activity.tsx index 4ab93647..632dc3f4 100644 --- a/packages/webui/src/components/debug/live-activity.tsx +++ b/packages/webui/src/components/debug/live-activity.tsx @@ -25,12 +25,15 @@ function IconBtn({ onClick, title, children }: { onClick: () => void; title: str ); } -function StatusPill({ status }: { status: 'open' | 'reconnecting' | 'closed' }) { - const map = { - open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' }, - reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' }, - closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' }, - }[status]; +function StatusPill({ status, paused }: { status: 'open' | 'reconnecting' | 'closed'; paused?: boolean }) { + // A deliberate pause reads as "已暂停", distinct from an unwanted disconnect. + const map = paused + ? { dot: 'bg-muted-foreground/50', label: '已暂停', glow: '' } + : { + open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' }, + reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' }, + closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' }, + }[status]; return (
@@ -94,14 +97,18 @@ export function LiveActivity() { const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed'); const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all'); const [query, setQuery] = useState(''); - const pausedRef = useRef(paused); - useEffect(() => { pausedRef.current = paused; }, [paused]); const idRef = useRef(0); + // Pausing truly drops the EventSource instead of connecting-and-discarding: + // `paused` is an effect dependency, so it closes the stream on pause and + // reopens it on resume. (The always-on-across-tabs behaviour is intentional — + // debug-page keeps this mounted so actions fired from other tabs still land in + // the feed — so only an explicit pause severs the connection.) useEffect(() => { + if (paused) return; const off = api.debug.stream( (m) => { - if (m.kind === 'ready' || pausedRef.current) return; + if (m.kind === 'ready') return; setRows((prev) => { // Precompute the search haystack once at enqueue, so filtering never // re-stringifies every row on each keystroke. @@ -112,7 +119,7 @@ export function LiveActivity() { (s) => setStatus(s), ); return off; - }, [api]); + }, [paused, api]); const visible = useMemo(() => { const q = query.trim().toLowerCase(); @@ -149,7 +156,7 @@ export function LiveActivity() {

实时活动

{visible.length} - +
(
{ e.stopPropagation(); setDragFrom(i); }} onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.stopPropagation(); if (dragFrom !== null) move(dragFrom, i); setDragFrom(null); }} - onDragEnd={() => setDragFrom(null)} - className="flex items-start gap-2 rounded-xl border border-border/50 bg-card/60 p-2" + className="rounded-xl border border-border/50 bg-card/60 p-2" > - -
-
- {LABELS[s.k]} -
- - - -
+ {/* Drag is scoped to the grip handle only — making the whole row + draggable hijacked text selection inside the segment inputs (you + couldn't select part of a pasted URL without dragging the card). + The row stays the drop target; its body is fully selectable. */} +
+ + { e.stopPropagation(); setDragFrom(i); }} + onDragEnd={() => setDragFrom(null)} + title="拖动此处排序" aria-label="拖动排序" + className="flex shrink-0 cursor-grab rounded-md p-0.5 text-muted-foreground/50 transition-colors hover:bg-muted hover:text-foreground active:cursor-grabbing" + > + + + {LABELS[s.k]} + +
+ + +
- patch(i, n)} uin={uin} groupId={groupId} depth={depth} />
+ patch(i, n)} uin={uin} groupId={groupId} depth={depth} />
))} diff --git a/packages/webui/src/components/login-waves.tsx b/packages/webui/src/components/login-waves.tsx index f6e9506f..233ed2ac 100644 --- a/packages/webui/src/components/login-waves.tsx +++ b/packages/webui/src/components/login-waves.tsx @@ -89,6 +89,10 @@ export function LoginWaves() { let lines: Pt[][] = []; let paths: SVGPathElement[] = []; let raf = 0; + // Honour reduced-motion (the OS setting or the app's own data-reduce-motion + // toggle): draw a single static frame instead of running the rAF loop. #185. + const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)'); + const reduced = () => prefersReduced.matches || document.documentElement.dataset.reduceMotion === '1'; const setSize = () => { bounding = host.getBoundingClientRect(); @@ -143,7 +147,7 @@ export function LoginWaves() { const t = e.touches[0]; if (t) updateMouse(t.clientX, t.clientY); }; - const onResize = () => { setSize(); setLines(); }; + const onResize = () => { setSize(); setLines(); if (reduced()) { movePoints(0); drawLines(); } }; const movePoints = (time: number) => { lines.forEach((points) => { @@ -213,10 +217,23 @@ export function LoginWaves() { window.addEventListener('resize', onResize); window.addEventListener('mousemove', onMouseMove); window.addEventListener('touchmove', onTouchMove, { passive: true }); - raf = requestAnimationFrame(tick); + // Animate only when motion is allowed; otherwise paint one static frame. + // React live to changes of the OS reduced-motion preference. + const applyMotion = () => { + if (reduced()) { + if (raf) { cancelAnimationFrame(raf); raf = 0; } + movePoints(0); + drawLines(); + } else if (!raf) { + raf = requestAnimationFrame(tick); + } + }; + prefersReduced.addEventListener('change', applyMotion); + applyMotion(); return () => { cancelAnimationFrame(raf); + prefersReduced.removeEventListener('change', applyMotion); window.removeEventListener('resize', onResize); window.removeEventListener('mousemove', onMouseMove); window.removeEventListener('touchmove', onTouchMove); diff --git a/packages/webui/src/components/overview/deliveries-widget.tsx b/packages/webui/src/components/overview/deliveries-widget.tsx index 89a252ed..5d5ace7c 100644 --- a/packages/webui/src/components/overview/deliveries-widget.tsx +++ b/packages/webui/src/components/overview/deliveries-widget.tsx @@ -18,7 +18,12 @@ export function DeliveriesWidget() { useEffect(() => { let active = true; - const pull = () => + let inFlight = false; + const pull = () => { + // Skip while the tab is backgrounded, or if a request is still in flight + // (a slow endpoint must not stack overlapping polls). #185. + if (inFlight || document.hidden) return; + inFlight = true; api.notifications .recent(50) .then((r) => { @@ -26,12 +31,19 @@ export function DeliveriesWidget() { }) .catch(() => { if (active) setRecords((prev) => prev ?? []); - }); + }) + .finally(() => { inFlight = false; }); + }; void pull(); const id = window.setInterval(() => void pull(), POLL_MS); + // The interval keeps firing but no-ops while hidden, so refresh immediately + // when the tab becomes visible again to shed any staleness. + const onVisible = () => { if (!document.hidden) pull(); }; + document.addEventListener('visibilitychange', onVisible); return () => { active = false; window.clearInterval(id); + document.removeEventListener('visibilitychange', onVisible); }; }, [api]); diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index f3e91a62..ccdb1c84 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useVirtualizer } from '@tanstack/react-virtual'; import { motion, AnimatePresence } from 'motion/react'; import { ArrowDownToLine, Download, Filter, Highlighter, Inbox, Pause, Plus, RefreshCw, Search, SearchX, SlidersHorizontal, Trash2, WrapText, X } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -91,7 +92,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool export function LogsPage() { const api = useApi(); - const { formatClock, appearance } = useTheme(); + const { formatClock } = useTheme(); const { pages, setPages } = useLayout(); const prefs = pages.logs; @@ -104,7 +105,7 @@ export function LogsPage() { const [showOptions, setShowOptions] = useState(false); const [newKeyword, setNewKeyword] = useState(''); const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id); - const endRef = useRef(null); + const scrollRef = useRef(null); // maxLines is read through a ref so changing it doesn't re-subscribe the SSE. const maxLines = prefs.maxLines; @@ -179,11 +180,6 @@ export function LogsPage() { }; }, [api]); - useEffect(() => { - if (!prefs.autoScroll) return; - endRef.current?.scrollIntoView({ block: 'end' }); - }, [logs, prefs.autoScroll]); - const filtered = useMemo(() => { const f = filter.trim().toLowerCase(); const capped = logs.slice(-maxLines); @@ -199,6 +195,40 @@ export function LogsPage() { }); }, [logs, filter, enabled, maxLines]); + // Virtualize the log rows: only the visible window (+overscan) is mounted, so + // the DOM stays at a few dozen nodes regardless of how many lines the view + // holds. Rows are dynamically measured (measureElement) so wrap mode's + // variable-height lines are handled without a fixed row-height assumption. + const rowVirtualizer = useVirtualizer({ + count: filtered.length, + getScrollElement: () => scrollRef.current, + estimateSize: () => 28, + overscan: 12, + // Key the size cache by row id, not index: the list is front-dropped at the + // maxLines cap, so every surviving row's index shifts down each flush. Keying + // by id keeps each measured height with its content (and matches the React + // key), avoiding a one-frame height mis-attribution on off-screen rows. + getItemKey: (index) => filtered[index]?.id ?? index, + }); + + // Toggling wrap changes every row's height — force a clean re-measure so the + // cached sizes don't leave gaps/overlaps. + useEffect(() => { rowVirtualizer.measure(); }, [prefs.wrap, rowVirtualizer]); + + // Follow the tail while auto-scroll is on. Re-run on anything that changes the + // visible set or row heights (new logs, filter/level/maxLines → filtered.length, + // wrap → heights), not just new logs. Freshly-appended rows still carry the + // estimate on this pass, so a second pin on the next frame (after ResizeObserver + // measures them) reaches the true bottom in wrap mode. + useEffect(() => { + if (!prefs.autoScroll || filtered.length === 0) return; + const last = filtered.length - 1; + rowVirtualizer.scrollToIndex(last, { align: 'end' }); + const raf = requestAnimationFrame(() => rowVirtualizer.scrollToIndex(last, { align: 'end' })); + return () => cancelAnimationFrame(raf); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [logs, filtered.length, prefs.autoScroll, prefs.wrap]); + // Any hand edit to the bundled prefs drops the active preset to 'custom'. const toggleLevel = (lv: LogLevel) => { const next = new Set(enabled); @@ -497,17 +527,18 @@ export function LogsPage() { {/* ── Log stream ──────────────────────────────────────────── */}
- + {/* Column header lives OUTSIDE the scroll viewport so the virtualizer's + scroll element contains only the rows (no sticky-offset math). */} + {filtered.length > 0 && ( +
+ 时间 + 级别 + 模块 + 消息 +
+ )} +
- {filtered.length > 0 && ( -
- 时间 - 级别 - 模块 - 消息 -
- )} - {filtered.length === 0 ? (
{logs.length === 0 ? ( @@ -524,17 +555,21 @@ export function LogsPage() { )}
) : ( -
- {filtered.map((log) => { +
+ {rowVirtualizer.getVirtualItems().map((vRow) => { + const log = filtered[vRow.index]; + if (!log) return null; // guard a transient count/measurement skew const hl = matchHighlight(log.message, prefs.highlightRules); return ( -
{formatClock(log.time)} @@ -553,12 +588,11 @@ export function LogsPage() { )} {log.message} - +
); })}
)} -
diff --git a/packages/webui/src/components/pages/processes-page.tsx b/packages/webui/src/components/pages/processes-page.tsx index 8a7d62c5..4c4a483a 100644 --- a/packages/webui/src/components/pages/processes-page.tsx +++ b/packages/webui/src/components/pages/processes-page.tsx @@ -263,6 +263,12 @@ export function ProcessesPage() { processName={probeDialog.name} open={!!probeDialog} onOpenChange={(open) => !open && setProbeDialog(null)} + onLoad={() => { + if (probeDialog) { + setConfirm({ kind: 'load', pid: probeDialog.pid, name: probeDialog.name }); + setProbeDialog(null); + } + }} /> )}
diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx index 768347da..31bd1e38 100644 --- a/packages/webui/src/components/process-probe-dialog.tsx +++ b/packages/webui/src/components/process-probe-dialog.tsx @@ -25,13 +25,14 @@ interface ProcessProbeDialogProps { processName: string; open: boolean; onOpenChange: (open: boolean) => void; + onLoad?: () => void; } function qqAvatarUrl(uin: string) { return `/avatar/${encodeURIComponent(uin)}`; } -export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: ProcessProbeDialogProps) { +export function ProcessProbeDialog({ pid, processName, open, onOpenChange, onLoad }: ProcessProbeDialogProps) { const api = useApi(); const [loading, setLoading] = useState(false); const [info, setInfo] = useState(null); @@ -127,6 +128,11 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro + {!loading && info?.loggedIn && onLoad && ( + + )} {!loading && (