From 852870db596b93bb2c11687d320012384a4ff519 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 01:26:31 +0800 Subject: [PATCH 01/18] feat(onebot): report C2C input status as notify/input_status Decode the 0x210/0x115 input-state sys_msg (RE'd from wrapper.linux.node aio_input_state_worker) into a friend_input_status event and map it to a notify/input_status notice, matching NapCat's onInputStatusPush. event_type 1 = typing, 3 = recording voice; status_text synthesised to match the client's own strings. --- packages/core/tests/msg-push-handler.test.ts | 48 +++++++++++++++++++ packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 13 +++++ packages/onebot/src/event-pipeline.ts | 1 + packages/proto-defs/src/notify.ts | 19 ++++++++ packages/protocol/src/events.ts | 16 ++++++- .../src/msg-push/decoders/event-0x210.ts | 31 ++++++++++++ packages/protocol/src/msg-push/enums.ts | 9 ++++ 8 files changed, 138 insertions(+), 1 deletion(-) diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index e706d9c6..4aeac485 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -14,6 +14,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; // inline-extract the kind. import type { GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin, + InputStatusNotify, } from '@snowluma/proto-defs/notify'; import type { PushMsg } from '@snowluma/proto-defs/message'; import type { @@ -254,6 +255,53 @@ 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=139 (self-recall direction)', () => { // 138 = friend recalled their own message sent to bot // (peer in friend_recall event = fromUid) diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 5a0b6cf7..1e15ac83 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -7,6 +7,7 @@ import { } from './to-message'; import { convertFriendAdd, + convertFriendInputStatus, convertFriendPoke, convertFriendRecall, convertGroupAdmin, @@ -78,6 +79,7 @@ const CONVERTERS: ConverterRegistry = { group_essence: convertGroupEssence, group_file_upload: convertGroupFileUpload, friend_add: convertFriendAdd, + friend_input_status: convertFriendInputStatus, 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..cec7659f 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -17,6 +17,7 @@ type GroupEssence = Extract; type GroupFileUpload = Extract; type FriendAdd = Extract; type GroupMsgEmojiLike = Extract; +type FriendInputStatus = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -156,6 +157,18 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO }); } +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..a96a8eb7 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -70,6 +70,7 @@ const NOTICE_KINDS = [ 'group_essence', 'group_file_upload', 'friend_add', + 'friend_input_status', 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index 68903cb2..b32292e6 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -262,3 +262,22 @@ export interface GroupReactNotify { field13?: pb<13, uint_32>; groupReactionData?: pb<44, GroupReactionData>; } + +// 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/src/events.ts b/packages/protocol/src/events.ts index 5b0af057..a06cb16f 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -294,6 +294,19 @@ export interface PttTransResultEvent extends QQEvent { text: string; } +/** + * 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 +325,5 @@ export type QQEventVariant = | GroupFileUploadEvent | FriendAddEvent | GroupMsgEmojiLikeEvent - | PttTransResultEvent; + | PttTransResultEvent + | FriendInputStatusEvent; diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 65a922c0..2bb43324 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -10,6 +10,7 @@ import type { FriendRecall, FriendRequest, GeneralGrayTipInfo, + InputStatusNotify, NewFriend, } from '@snowluma/proto-defs/notify'; import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans'; @@ -23,6 +24,7 @@ import { import type { MsgPushDecoder } from '../registry'; type FriendRecallEvent = Extract; +type FriendInputStatusEvent = Extract; const unknownLog = createLogger('MsgPush.Unknown'); @@ -37,6 +39,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { case Event0x210SubType.FriendRecallSelfNotice: return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx); // 179 + 226 both carry the NewFriend payload — see enum comment. case Event0x210SubType.NewFriendNotice: case Event0x210SubType.NewFriendNoticeAlt: @@ -128,6 +131,34 @@ 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 ? '对方正在讲话...' : '对方正在输入...'; +} + 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/enums.ts b/packages/protocol/src/msg-push/enums.ts index e94c157c..d972def1 100644 --- a/packages/protocol/src/msg-push/enums.ts +++ b/packages/protocol/src/msg-push/enums.ts @@ -67,6 +67,15 @@ export enum Event0x210SubType { */ NewFriendNotice = 179, NewFriendNoticeAlt = 226, + /** + * 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). * From bfde0daab4684c119cc42b65f947f2990f184d5f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 02:05:52 +0800 Subject: [PATCH 02/18] feat(onebot): report group name change as notify/group_name Dispatch the 0x2DC subType-16 push by NotifyMessageBody.field13 (was emoji-react only); field13==12 decodes eventParam as GroupNameChange and emits notify/group_name {group_id, user_id=operator, name_new}, matching NapCat. Emoji-react (field13==35) path unchanged. --- packages/core/tests/msg-push-handler.test.ts | 51 ++++++++++++++++++- packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 13 +++++ packages/onebot/src/event-pipeline.ts | 1 + packages/proto-defs/src/notify.ts | 8 +++ packages/protocol/src/events.ts | 14 ++++- .../src/msg-push/decoders/event-0x2dc.ts | 42 ++++++++++++++- 7 files changed, 128 insertions(+), 3 deletions(-) diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 4aeac485..e3f0e19f 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -14,7 +14,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; // inline-extract the kind. import type { GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin, - InputStatusNotify, + InputStatusNotify, NotifyMessageBody, GroupNameChange, } from '@snowluma/proto-defs/notify'; import type { PushMsg } from '@snowluma/proto-defs/message'; import type { @@ -302,6 +302,55 @@ describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输 }); }); +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/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 1e15ac83..eb8b7e08 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -17,6 +17,7 @@ import { convertGroupMemberLeave, convertGroupMsgEmojiLike, convertGroupMute, + convertGroupNameChange, convertGroupPoke, convertGroupRecall, } from './to-notice'; @@ -80,6 +81,7 @@ const CONVERTERS: ConverterRegistry = { group_file_upload: convertGroupFileUpload, friend_add: convertFriendAdd, friend_input_status: convertFriendInputStatus, + group_name_change: convertGroupNameChange, 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 cec7659f..c878e85b 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -18,6 +18,7 @@ type GroupFileUpload = Extract; type FriendAdd = Extract; type GroupMsgEmojiLike = Extract; type FriendInputStatus = Extract; +type GroupNameChange = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -157,6 +158,18 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO }); } +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. diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index a96a8eb7..f9615b9c 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -71,6 +71,7 @@ const NOTICE_KINDS = [ 'group_file_upload', 'friend_add', 'friend_input_status', + 'group_name_change', 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index b32292e6..408d1947 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -263,6 +263,14 @@ export interface GroupReactNotify { groupReactionData?: pb<44, GroupReactionData>; } +// 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>; +} + // 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` diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index a06cb16f..54b74321 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -294,6 +294,17 @@ export interface PttTransResultEvent extends QQEvent { text: 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 +} + /** * C2C "对方正在输入…" input-status push (Event 0x210 subType 0x115 / 277). * `eventType` 1 = typing, 3 = recording a voice message. Mirrors NapCat's @@ -326,4 +337,5 @@ export type QQEventVariant = | FriendAddEvent | GroupMsgEmojiLikeEvent | PttTransResultEvent - | FriendInputStatusEvent; + | FriendInputStatusEvent + | GroupNameChangeEvent; diff --git a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts index ca0b4dbe..116251e3 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts @@ -4,12 +4,14 @@ import type { GroupEssenceEvent, GroupMsgEmojiLikeEvent, GroupMuteEvent, + GroupNameChangeEvent, GroupPokeEvent, GroupRecallEvent, QQEventVariant, } from '../../events'; import type { GroupMute, + GroupNameChange, GroupReactNotify, NotifyMessageBody, } from '@snowluma/proto-defs/notify'; @@ -28,7 +30,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 +125,44 @@ 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_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_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 == 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 []; From d3d1d2512e27823b1d9e517ce3672e93678674a9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 02:23:17 +0800 Subject: [PATCH 03/18] feat(onebot): report group member card change as notice/group_card Detect a group member's card change from message traffic (sender card vs cached roster card) and emit group_card {group_id, user_id, card_new, card_old}, matching NapCat's parseCardChangedEvent. Fires only on a real change of a known member; first-contact and unchanged cards are suppressed. --- packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 13 ++++ packages/onebot/src/event-pipeline.ts | 1 + packages/protocol/src/events.ts | 16 ++++- packages/protocol/src/packet-pipeline.ts | 31 +++++++++ .../packet-pipeline-stranger-resolve.test.ts | 68 +++++++++++++++++++ 6 files changed, 130 insertions(+), 1 deletion(-) diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index eb8b7e08..110e82ec 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -11,6 +11,7 @@ import { convertFriendPoke, convertFriendRecall, convertGroupAdmin, + convertGroupCardChange, convertGroupEssence, convertGroupFileUpload, convertGroupMemberJoin, @@ -82,6 +83,7 @@ const CONVERTERS: ConverterRegistry = { friend_add: convertFriendAdd, friend_input_status: convertFriendInputStatus, group_name_change: convertGroupNameChange, + 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 c878e85b..a9ed2491 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -19,6 +19,7 @@ type FriendAdd = Extract; type GroupMsgEmojiLike = Extract; type FriendInputStatus = Extract; type GroupNameChange = Extract; +type GroupCardChange = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -158,6 +159,18 @@ 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 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`. diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index f9615b9c..72a08ba3 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -72,6 +72,7 @@ const NOTICE_KINDS = [ 'friend_add', 'friend_input_status', 'group_name_change', + 'group_card_change', 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 54b74321..c2dea380 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -294,6 +294,19 @@ export interface PttTransResultEvent extends QQEvent { text: 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; +} + /** * Group name changed (Event 0x2DC subType 16, field13 == 12). Mirrors NapCat's * OB11GroupNameEvent → `notice/notify` `sub_type:'group_name'`. @@ -338,4 +351,5 @@ export type QQEventVariant = | GroupMsgEmojiLikeEvent | PttTransResultEvent | FriendInputStatusEvent - | GroupNameChangeEvent; + | GroupNameChangeEvent + | GroupCardChangeEvent; 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/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); + }); +}); From 0d4d58605fb7953bd7d5760cf0b915d1ee922922 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 02:53:38 +0800 Subject: [PATCH 04/18] feat(onebot): report group special title grant as notify/title Decode the 0x2DC subType-16 field13==6 push: eventParam carries the member uin (f5) and a gray-tip template (f2) whose last rich token holds the title text. Emit notify/title {group_id, user_id, title}, matching NapCat. Field layout taken from a real on-wire sample, not ported blindly. --- packages/core/tests/msg-push-handler.test.ts | 52 ++++++++++++++++++- packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 13 +++++ packages/onebot/src/event-pipeline.ts | 1 + packages/proto-defs/src/notify.ts | 11 ++++ packages/protocol/src/events.ts | 14 ++++- .../src/msg-push/decoders/event-0x2dc.ts | 42 +++++++++++++++ 7 files changed, 133 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index e3f0e19f..e8e78024 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -14,7 +14,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; // inline-extract the kind. import type { GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin, - InputStatusNotify, NotifyMessageBody, GroupNameChange, + InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange, } from '@snowluma/proto-defs/notify'; import type { PushMsg } from '@snowluma/proto-defs/message'; import type { @@ -302,6 +302,56 @@ describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输 }); }); +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. diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 110e82ec..e5e0089f 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -19,6 +19,7 @@ import { convertGroupMsgEmojiLike, convertGroupMute, convertGroupNameChange, + convertGroupTitleChange, convertGroupPoke, convertGroupRecall, } from './to-notice'; @@ -83,6 +84,7 @@ const CONVERTERS: ConverterRegistry = { friend_add: convertFriendAdd, friend_input_status: convertFriendInputStatus, group_name_change: convertGroupNameChange, + group_title_change: convertGroupTitleChange, group_card_change: convertGroupCardChange, group_msg_emoji_like: convertGroupMsgEmojiLike, // Requests. diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index a9ed2491..a7a39822 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -20,6 +20,7 @@ type GroupMsgEmojiLike = Extract; type GroupNameChange = Extract; type GroupCardChange = Extract; +type GroupTitleChange = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -171,6 +172,18 @@ export function convertGroupCardChange(ctx: ConverterContext, event: GroupCardCh }); } +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`. diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 72a08ba3..25827093 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -72,6 +72,7 @@ const NOTICE_KINDS = [ 'friend_add', 'friend_input_status', 'group_name_change', + 'group_title_change', 'group_card_change', 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index 408d1947..8d96b4c0 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -271,6 +271,17 @@ 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>; +} + // 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` diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index c2dea380..1e58a181 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -307,6 +307,17 @@ export interface GroupCardChangeEvent extends QQEvent { 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'`. @@ -352,4 +363,5 @@ export type QQEventVariant = | PttTransResultEvent | FriendInputStatusEvent | GroupNameChangeEvent - | GroupCardChangeEvent; + | GroupCardChangeEvent + | GroupTitleChangeEvent; diff --git a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts index 116251e3..95e1595c 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts @@ -5,6 +5,7 @@ import type { GroupMsgEmojiLikeEvent, GroupMuteEvent, GroupNameChangeEvent, + GroupTitleChangeEvent, GroupPokeEvent, GroupRecallEvent, QQEventVariant, @@ -12,6 +13,7 @@ import type { import type { GroupMute, GroupNameChange, + GroupSpecialTitleChange, GroupReactNotify, NotifyMessageBody, } from '@snowluma/proto-defs/notify'; @@ -129,12 +131,14 @@ const GROUP_REACT_DISCRIMINATOR = 35; // `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: @@ -143,6 +147,44 @@ function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] { } } +// 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[] { From 447b40a25911fa3ca5cd60b813259f1c0e0e82e8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 03:05:14 +0800 Subject: [PATCH 05/18] feat(onebot): report profile like as notify/profile_like Decode the multiplexed 0x210 subType-39 push: when body.msgContent is a ProfileLikeTip with inner msgType==0/subType==203, emit notify/profile_like {operator_id, operator_nick, times}. times is parsed from detail.txt. Proto shape from NapCat's raw decoder; wiring + decode verified, but the byte-exact wire is pending a real like capture to confirm. --- packages/core/tests/msg-push-handler.test.ts | 41 +++++++++++++++++++ packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 13 ++++++ packages/onebot/src/event-pipeline.ts | 1 + packages/proto-defs/src/notify.ts | 27 ++++++++++++ packages/protocol/src/events.ts | 15 ++++++- .../src/msg-push/decoders/event-0x210.ts | 29 +++++++++++++ packages/protocol/src/msg-push/enums.ts | 8 ++++ 8 files changed, 135 insertions(+), 1 deletion(-) diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index e8e78024..5b1efd09 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -15,6 +15,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; 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 { @@ -302,6 +303,46 @@ describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输 }); }); +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', () => { + const [event] = parseMsgPush( + makeLikePacket({ uin: 1787882683, nick: '東雪蓮', txt: '赞了你3次' }), + makeIdentity(), + ) as FriendProfileLikeEvent[]; + + expect(event.kind).toBe('friend_profile_like'); + expect(event.operatorUin).toBe(1787882683); + expect(event.operatorNick).toBe('東雪蓮'); + expect(event.times).toBe(3); + 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 diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index e5e0089f..3034ca8c 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -8,6 +8,7 @@ import { import { convertFriendAdd, convertFriendInputStatus, + convertFriendProfileLike, convertFriendPoke, convertFriendRecall, convertGroupAdmin, @@ -83,6 +84,7 @@ const CONVERTERS: ConverterRegistry = { group_file_upload: convertGroupFileUpload, friend_add: convertFriendAdd, friend_input_status: convertFriendInputStatus, + friend_profile_like: convertFriendProfileLike, group_name_change: convertGroupNameChange, group_title_change: convertGroupTitleChange, group_card_change: convertGroupCardChange, diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index a7a39822..94d76e6b 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -21,6 +21,7 @@ type FriendInputStatus = Extract; type GroupCardChange = Extract; type GroupTitleChange = Extract; +type FriendProfileLike = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return notice(ctx, event, { @@ -172,6 +173,18 @@ export function convertGroupCardChange(ctx: ConverterContext, event: GroupCardCh }); } +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. diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 25827093..5079c481 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -71,6 +71,7 @@ const NOTICE_KINDS = [ 'group_file_upload', 'friend_add', 'friend_input_status', + 'friend_profile_like', 'group_name_change', 'group_title_change', 'group_card_change', diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index 8d96b4c0..443dac2e 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -282,6 +282,33 @@ export interface GroupSpecialTitleChange { 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. NOTE: proto shape sourced from NapCat's +// raw-bytes decoder (adaptDecoder.ts) — semantics only; pending a real like +// capture to confirm byte-exactly. times 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` diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 1e58a181..a015af0b 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -329,6 +329,18 @@ export interface GroupNameChangeEvent extends QQEvent { 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 @@ -364,4 +376,5 @@ export type QQEventVariant = | FriendInputStatusEvent | GroupNameChangeEvent | GroupCardChangeEvent - | GroupTitleChangeEvent; + | GroupTitleChangeEvent + | FriendProfileLikeEvent; diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 2bb43324..047c41c7 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -12,6 +12,7 @@ import type { GeneralGrayTipInfo, InputStatusNotify, NewFriend, + ProfileLikeTip, } from '@snowluma/proto-defs/notify'; import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans'; import type { MsgPushContext } from '../context'; @@ -25,6 +26,7 @@ import type { MsgPushDecoder } from '../registry'; type FriendRecallEvent = Extract; type FriendInputStatusEvent = Extract; +type FriendProfileLikeEvent = Extract; const unknownLog = createLogger('MsgPush.Unknown'); @@ -40,6 +42,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { 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: @@ -159,6 +162,32 @@ 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`. Proto shape from NapCat's +// raw-bytes decoder — pending a real like capture to validate byte-exactly. +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/enums.ts b/packages/protocol/src/msg-push/enums.ts index d972def1..a408bb44 100644 --- a/packages/protocol/src/msg-push/enums.ts +++ b/packages/protocol/src/msg-push/enums.ts @@ -67,6 +67,14 @@ 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` From eda1c32994228cbdb0dc196ac238aa104bbb901f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 15:10:06 +0800 Subject: [PATCH 06/18] test(onebot): confirm profile_like decode against real captures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validated the 0x210/39 ProfileLikeTip field layout byte-exact against three real captured like pushes (detail.txt='赞了我的资料卡N次', f3=uin, f5=nick). Drop the pending-validation caveat; test now uses the real txt shape. --- packages/core/tests/msg-push-handler.test.ts | 9 +++++---- packages/proto-defs/src/notify.ts | 6 +++--- packages/protocol/src/msg-push/decoders/event-0x210.ts | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 5b1efd09..b3128296 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -322,15 +322,16 @@ describe('parseMsgPush Event0x210 subType=39 (profile like → 名片赞)', () = } 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: 1787882683, nick: '東雪蓮', txt: '赞了你3次' }), + makeLikePacket({ uin: 1206069534, nick: '墨白灵MotricLuck', txt: '赞了我的资料卡2次' }), makeIdentity(), ) as FriendProfileLikeEvent[]; expect(event.kind).toBe('friend_profile_like'); - expect(event.operatorUin).toBe(1787882683); - expect(event.operatorNick).toBe('東雪蓮'); - expect(event.times).toBe(3); + expect(event.operatorUin).toBe(1206069534); + expect(event.operatorNick).toBe('墨白灵MotricLuck'); + expect(event.times).toBe(2); expect(event.time).toBe(1710001111); }); diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index 443dac2e..f106a46b 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -284,9 +284,9 @@ export interface GroupSpecialTitleChange { // 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. NOTE: proto shape sourced from NapCat's -// raw-bytes decoder (adaptDecoder.ts) — semantics only; pending a real like -// capture to confirm byte-exactly. times is parsed from `detail.txt`. +// 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>; diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 047c41c7..acc3ffb5 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -165,8 +165,8 @@ function inputStatusText(eventType: number): string { // 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`. Proto shape from NapCat's -// raw-bytes decoder — pending a real like capture to validate byte-exactly. +// `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, From d9dfe513ee45fa79f94a11e576e36fecf4fb7e27 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 15:25:35 +0800 Subject: [PATCH 07/18] feat(onebot): report forced offline as notice/bot_offline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Register a handler for the StatusService.KickNT push (QQ NT's unified forced-offline notification — kick / login-elsewhere / risk-control), decode KickNTResponse and emit bot_offline {user_id, tag, message}, matching NapCat. Command + field layout (f4=tips_title, f3=tips_content) RE-confirmed against wrapper.linux.node + Lagrange; not yet live-captured. --- packages/core/src/bridge/bridge.ts | 2 + packages/onebot/src/event-converter/index.ts | 2 + .../onebot/src/event-converter/to-notice.ts | 12 ++++++ packages/onebot/src/event-pipeline.ts | 1 + packages/proto-defs/src/notify.ts | 12 ++++++ packages/protocol/package.json | 4 ++ packages/protocol/src/events.ts | 14 ++++++- packages/protocol/src/kick-nt.ts | 33 +++++++++++++++ packages/protocol/tests/kick-nt.test.ts | 41 +++++++++++++++++++ 9 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 packages/protocol/src/kick-nt.ts create mode 100644 packages/protocol/tests/kick-nt.test.ts 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/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 3034ca8c..028c16f9 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -6,6 +6,7 @@ import { convertTempMessage, } from './to-message'; import { + convertBotOffline, convertFriendAdd, convertFriendInputStatus, convertFriendProfileLike, @@ -85,6 +86,7 @@ const CONVERTERS: ConverterRegistry = { 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, diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index 94d76e6b..2770aa57 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -22,6 +22,7 @@ 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, { @@ -173,6 +174,17 @@ export function convertGroupCardChange(ctx: ConverterContext, event: GroupCardCh }); } +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. diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 5079c481..1c278809 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -72,6 +72,7 @@ const NOTICE_KINDS = [ 'friend_add', 'friend_input_status', 'friend_profile_like', + 'bot_offline', 'group_name_change', 'group_title_change', 'group_card_change', diff --git a/packages/proto-defs/src/notify.ts b/packages/proto-defs/src/notify.ts index f106a46b..16d722ba 100644 --- a/packages/proto-defs/src/notify.ts +++ b/packages/proto-defs/src/notify.ts @@ -263,6 +263,18 @@ export interface GroupReactNotify { 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 diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 987ff78e..430f3c59 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -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 a015af0b..dade5237 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -294,6 +294,17 @@ 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 @@ -377,4 +388,5 @@ export type QQEventVariant = | GroupNameChangeEvent | GroupCardChangeEvent | GroupTitleChangeEvent - | FriendProfileLikeEvent; + | 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/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); + }); +}); From fd57eb4b6f4ad4fb59064d71b00549fa499201cb Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 15:48:52 +0800 Subject: [PATCH 08/18] fix(webui): scope message-segment drag to the grip handle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The whole segment row in the debug message builder was `draggable`, so an HTML5 drag started on any pointer gesture inside it — including selecting part of a pasted URL in a segment input, which dragged the card instead of selecting text. Move `draggable` (and onDragStart/onDragEnd) off the row onto the grip handle only; the row keeps onDragOver/onDrop so it stays the drop target. The body is now fully selectable/editable. The grip also moves up beside the segment label, freeing the card's left edge. Nested forward-node builders keep their stopPropagation drag boundary. --- .../src/components/debug/message-builder.tsx | 42 ++++++++++++------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/packages/webui/src/components/debug/message-builder.tsx b/packages/webui/src/components/debug/message-builder.tsx index dc5ee47c..e2c15b2a 100644 --- a/packages/webui/src/components/debug/message-builder.tsx +++ b/packages/webui/src/components/debug/message-builder.tsx @@ -140,27 +140,37 @@ export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }: {segments.map((s, i) => (
{ 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} />
))} From c09c6e0883eeeaf28fda1c27d56f01ba997d116f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 21:20:07 +0800 Subject: [PATCH 09/18] fix(onebot): heal half-open reverse-WS client with a transport heartbeat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A reverse-WS client could end up half-open after the peer restarted: still writable (events kept flowing out) but no longer readable, so inbound action frames silently never arrived and only a full restart recovered it (#208). The OneBot app-level meta heartbeat is a one-way push and cannot detect this. Add an RFC6455 ping/pong keepalive (startHeartbeat) wired into the ws-client adapter. It pings every 30s and declares the link dead only after 2 unanswered pings (~90s of total silence), then terminates the socket so the existing reconnect path runs. Any inbound activity — a pong OR a message — resets the counter, so a connection carrying real traffic is never reaped; the conservative tolerance keeps the false-positive rate near zero (a GC pause or latency spike is absorbed). The stop is per-socket and also held on the instance so close()/reload halt it immediately rather than waiting for the deferred 'close'; a symmetric identity guard on 'open' mirrors the #97 stale-socket guard on 'close'. --- packages/onebot/src/network/utils.ts | 62 +++++ .../onebot/src/network/ws-client-adapter.ts | 40 +++- .../onebot/tests/ws-client-heartbeat.test.ts | 225 ++++++++++++++++++ 3 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 packages/onebot/tests/ws-client-heartbeat.test.ts 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/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(); + } + }); +}); From 1914807770e08c6249ca0f00a50f4d90c15a4862 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 21:20:19 +0800 Subject: [PATCH 10/18] fix(onebot): apply the transport heartbeat to the reverse-WS server too Symmetric with the ws-client fix (#208): the reverse-WS server now pings each attached client and terminates one that goes fully silent for ~90s (2 unanswered pings), reaping a half-open client that would otherwise linger in the connection set. Reuses startHeartbeat with the same conservative, activity-reset tolerance, so a client with live traffic is never dropped. The per-connection stop is kept on the ForwardConn entry and cleared in both close() and the socket 'close' handler; no shared instance state, so the #97 overlap does not apply here. --- .../onebot/src/network/ws-server-adapter.ts | 30 +++- .../onebot/tests/ws-server-heartbeat.test.ts | 148 ++++++++++++++++++ 2 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 packages/onebot/tests/ws-server-heartbeat.test.ts 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/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(); + } + }); +}); From 8fbcbd29ff9f253296658bf48d607f4332684b56 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 21:35:33 +0800 Subject: [PATCH 11/18] feat(onebot): honour a custom per-node time in merged forward (#209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merged-forward nodes always stamped the current time. A custom forward can now set each node's displayed timestamp via the OneBot `data.time` field (unix seconds), matching the field the wire already carries per node. parseForwardNodes reads `data.time` on custom/fake nodes and threads it onto the node payload (the `time?` field already existed for the receive side); buildForwardPushBody uses it for `contentHead.timestamp`, falling back to now when absent. The value is validated to a plausible unix-seconds range — the wire field is uint32, so a millisecond or out-of-range input is rejected (would overflow) and defaults to now rather than corrupting the timestamp. The message_id-reference branch (time from the quoted message) and the c2c-file expireTime (real now) are unchanged. Nested inner nodes honour their own time. --- packages/core/src/bridge/apis/forward.ts | 4 +- packages/core/tests/actions/forward.test.ts | 38 +++++++++++++++++-- .../onebot/src/modules/message-actions.ts | 6 +++ packages/onebot/tests/forward-nested.test.ts | 25 ++++++++++++ 4 files changed, 69 insertions(+), 4 deletions(-) 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/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/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/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 From 4802dfe7aa086b25457334e70938cf7410ff2392 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 22:07:02 +0800 Subject: [PATCH 12/18] perf(webui): virtualize the log viewer row list (#185) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The logs page rendered every filtered row, so a full 2000-line view mounted ~10k DOM nodes and cost ~66ms of layout per commit. Switch to a virtualized list (@tanstack/react-virtual) that mounts only the visible window plus a small overscan — a few dozen nodes regardless of how many lines the view holds. Rows are dynamically measured (measureElement) so wrap mode's variable-height lines need no fixed row-height assumption; the size cache is keyed by row id so the maxLines front-drop doesn't mis-attribute heights across the index shift. The column header moved just outside the scroll viewport so the virtual list is the sole scroll content (no sticky-offset math). Auto-scroll now follows the tail via scrollToIndex with a next-frame re-pin (freshly-appended rows carry the size estimate until measured, which otherwise left wrap-mode tails short), and re-runs on filter/level/wrap/maxLines changes, not just new logs. ScrollArea gained an optional viewportRef so the virtualizer can drive off the real Radix scroll element. The per-row entrance fade is dropped (rows mount/unmount on scroll); divide-y became a per-row border. --- packages/webui/package.json | 1 + .../webui/src/components/pages/logs-page.tsx | 88 +++++++++++++------ .../webui/src/components/ui/scroll-area.tsx | 6 +- pnpm-lock.yaml | 61 ++++++++++++- 4 files changed, 126 insertions(+), 30 deletions(-) diff --git a/packages/webui/package.json b/packages/webui/package.json index 49637a9b..3a53630a 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -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/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/ui/scroll-area.tsx b/packages/webui/src/components/ui/scroll-area.tsx index dd5f714a..d53090bb 100644 --- a/packages/webui/src/components/ui/scroll-area.tsx +++ b/packages/webui/src/components/ui/scroll-area.tsx @@ -4,16 +4,20 @@ import { cn } from '@/lib/utils'; interface ScrollAreaProps extends React.ComponentPropsWithoutRef { viewportClassName?: string; + /** Ref to the scrollable viewport element — needed to drive a virtualizer + * (TanStack Virtual's getScrollElement) off the actual scroll container. */ + viewportRef?: React.Ref; } const ScrollArea = React.forwardRef, ScrollAreaProps>( - ({ className, children, viewportClassName, ...props }, ref) => ( + ({ className, children, viewportClassName, viewportRef, ...props }, ref) => ( div]:!block', viewportClassName)} > {children} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f079dbbd..fd84492e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -379,6 +379,9 @@ importers: '@tanstack/react-router': specifier: ^1.169.2 version: 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@tanstack/react-virtual': + specifier: ^3.14.5 + version: 3.14.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -1720,6 +1723,12 @@ packages: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@tanstack/react-virtual@3.14.5': + resolution: {integrity: sha512-4EKRXh7zBLkbKbFmG3AUVkircuHd+7OdT1pocJSepxtfBd3qnrJgJ5rtPkRYyo9fmyVb2+pI2xPy5oYvMLQy6A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@tanstack/router-core@1.169.2': resolution: {integrity: sha512-5sm0DJF1A7Mz+9gy4Gz/lLovNailK3yot4vYvz9MkBUPw26uLnhQiR8hSCYxucjE0wD6Mdlc5l+Z0/XTlZ7xHw==} engines: {node: '>=20.19'} @@ -1727,6 +1736,9 @@ packages: '@tanstack/store@0.9.3': resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==} + '@tanstack/virtual-core@3.17.3': + resolution: {integrity: sha512-8Np/TFELpI0ySuJoVmjvOrQYXH/8sTX0Biv9szhFhY39xOdAAY+smrMxjxOum/ux3eM8MUJQsEJ0/R0UpvC8dw==} + '@tybys/wasm-util@0.10.3': resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} @@ -4308,6 +4320,12 @@ snapshots: react-dom: 19.2.5(react@19.2.5) use-sync-external-store: 1.6.0(react@19.2.5) + '@tanstack/react-virtual@3.14.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@tanstack/virtual-core': 3.17.3 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + '@tanstack/router-core@1.169.2': dependencies: '@tanstack/history': 1.161.6 @@ -4317,6 +4335,8 @@ snapshots: '@tanstack/store@0.9.3': {} + '@tanstack/virtual-core@3.17.3': {} + '@tybys/wasm-util@0.10.3': dependencies: tslib: 2.8.1 @@ -4476,7 +4496,7 @@ snapshots: magicast: 0.5.3 obug: 2.1.1 tinyrainbow: 3.1.0 - vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) transitivePeerDependencies: - supports-color @@ -4492,7 +4512,7 @@ snapshots: obug: 2.1.1 std-env: 4.1.0 tinyrainbow: 3.1.0 - vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) '@vitest/expect@4.1.4': dependencies: @@ -4511,6 +4531,14 @@ snapshots: optionalDependencies: vite: 8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@vitest/mocker@4.1.4(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': + dependencies: + '@vitest/spy': 4.1.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@vitest/pretty-format@4.1.4': dependencies: tinyrainbow: 3.1.0 @@ -5813,6 +5841,35 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): + dependencies: + '@vitest/expect': 4.1.4 + '@vitest/mocker': 4.1.4(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + '@vitest/pretty-format': 4.1.4 + '@vitest/runner': 4.1.4 + '@vitest/snapshot': 4.1.4 + '@vitest/spy': 4.1.4 + '@vitest/utils': 4.1.4 + es-module-lexer: 2.0.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.1 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.1.1 + tinyglobby: 0.2.16 + tinyrainbow: 3.1.0 + vite: 8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 25.6.0 + '@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4) + '@vitest/coverage-v8': 4.1.4(vitest@4.1.4) + transitivePeerDependencies: + - msw + vp-runtime-helper@1.0.10: dependencies: '@types/fs-extra': 11.0.4 From c49a5a0aa8753d06a7fc81739034a39a833e51b3 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 22:17:16 +0800 Subject: [PATCH 13/18] perf(webui): make debug feed pause truly close the SSE (#185) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The live-activity feed kept its /api/debug/stream EventSource open while paused and merely dropped frames in the handler, so a paused feed still held a backend connection slot and processed every event for nothing. Make `paused` a dependency of the subscription effect: pausing now closes the stream and resuming reopens it. Events during a pause were already discarded, and the row buffer is preserved across toggles, so the only change is that a paused feed stops consuming. Deliberately NOT gated on tab visibility: debug-page keeps this component mounted across tabs on purpose (the comment there notes actions fired from other tabs must still land in the feed), so closing on tab switch would regress that. Only an explicit pause severs the connection. StatusPill gained a `paused` state so a deliberate pause reads as 已暂停 rather than 未连接. --- .../src/components/debug/live-activity.tsx | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) 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} - +
Date: Tue, 7 Jul 2026 22:29:10 +0800 Subject: [PATCH 14/18] perf(webui): share one ref-counted /api/logs/stream across subscribers (#185) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The log viewer and each dashboard "recent alerts" widget opened their own EventSource to /api/logs/stream, so N alert tiles + the viewer meant N+1 identical connections (plus a short-lived-connection churn on navigation). Make openLogStream ref-counted: the first subscriber opens a single shared stream, every frame and status change fans out to all subscribers (each isolated with try/catch and re-checked against the live Set so a mid-frame unsubscribe is skipped), and the last to leave closes it. Late subscribers replay the current status. Hardening: a no-token open no longer caches a dead disposer (it would have blocked every later subscriber from ever connecting); the shared URL bakes in the token, so setToken() tears down and reopens on any token change (re-login would otherwise retry a stale-token URL forever); the connecting window seeds 'reconnecting' so a late joiner's badge isn't wrongly 'closed'. Consumers are unchanged — the dedup is transparent behind api.logs.stream. --- packages/webui/src/lib/api/client.ts | 70 ++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 1219a085..352ad8fb 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -42,6 +42,13 @@ class HttpApiClient implements ApiClient { private currentToken: string | null; private onUnauthorized?: () => void; + // Shared, ref-counted /api/logs/stream: a single EventSource fans out to every + // subscriber (any number of dashboard alert widgets + the log viewer) instead + // of opening one connection each. See openLogStream. + private logSubscribers = new Set(); + private logStreamDispose: (() => void) | null = null; + private lastLogStatus: StreamStatus = 'closed'; + // namespaced surfaces are bound up-front so callers can destructure readonly processes: ApiClient['processes']; readonly config: ApiClient['config']; @@ -268,8 +275,12 @@ class HttpApiClient implements ApiClient { // ---------- token management ---------- private setToken(token: string | null): void { + const changed = this.currentToken !== token; this.currentToken = token; this.tokenStore.save(token); + // The shared log stream URL carries the token — rebuild it on any change so + // a re-login doesn't leave subscribers on a stale-token connection (#185). + if (changed) this.reopenSharedLogStream(); } // ---------- auth ---------- @@ -394,10 +405,63 @@ class HttpApiClient implements ApiClient { } private openLogStream(options: LogsStreamOptions): () => void { - return this.openSseChannel('/api/logs/stream', (parsed) => { + this.logSubscribers.add(options); + if (this.logStreamDispose) { + // A late subscriber joins the already-live shared connection — replay the + // current transport status so its badge isn't stuck at the default. + options.onStatus?.(this.lastLogStatus); + } else { + this.openSharedLogStream(); + } + return () => { + this.logSubscribers.delete(options); + if (this.logSubscribers.size === 0 && this.logStreamDispose) { + this.logStreamDispose(); + this.logStreamDispose = null; + this.lastLogStatus = 'closed'; + } + }; + } + + /** Open the single shared /api/logs/stream connection; every frame and status + * change fans out to all subscribers, each isolated so one throwing handler + * can't drop the frame for the others (and a subscriber unsubscribed mid-frame + * is skipped). A no-token attempt does NOT cache a dead disposer — it reports + * 'closed' and returns so a later subscribe / setToken can open for real, + * avoiding poisoning the shared cache. */ + private openSharedLogStream(): void { + if (!this.currentToken) { + this.lastLogStatus = 'closed'; + for (const sub of [...this.logSubscribers]) { + if (this.logSubscribers.has(sub)) { try { sub.onStatus?.('closed'); } catch { /* isolate */ } } + } + return; + } + this.lastLogStatus = 'reconnecting'; // connecting until onopen fires + this.logStreamDispose = this.openSseChannel('/api/logs/stream', (parsed) => { if ('type' in parsed) return; // control frame, not a log line - options.onLine(parsed); - }, options.onStatus); + for (const sub of [...this.logSubscribers]) { + if (this.logSubscribers.has(sub)) { try { sub.onLine(parsed); } catch { /* isolate a bad subscriber */ } } + } + }, (s) => { + this.lastLogStatus = s; + for (const sub of [...this.logSubscribers]) { + if (this.logSubscribers.has(sub)) { try { sub.onStatus?.(s); } catch { /* isolate */ } } + } + }); + } + + /** Token changed (login / re-login / logout): the shared stream baked the old + * token into its URL, so tear it down and reopen with the new one if anyone is + * still listening. Without this a re-login would leave the feed retrying a + * stale-token URL forever. */ + private reopenSharedLogStream(): void { + if (this.logStreamDispose) { + this.logStreamDispose(); + this.logStreamDispose = null; + } + this.lastLogStatus = 'closed'; + if (this.logSubscribers.size > 0) this.openSharedLogStream(); } // Invoke a (stream) action and relay each `data: \n\n` SSE frame. Uses From fc424ab740d226ca35a91b3ac4e8d99e9d8a5881 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 7 Jul 2026 22:34:07 +0800 Subject: [PATCH 15/18] perf(webui): stop login-waves rAF under reduced-motion; gate deliveries poll on visibility (#185) login-waves ran its requestAnimationFrame loop unconditionally, ignoring reduced-motion. Honour it (OS `prefers-reduced-motion` or the app's `data-reduce-motion`): when reduced, paint a single static frame and never start the loop; otherwise animate. React live to OS preference changes, and repaint the static frame on resize while reduced so the field doesn't blank out. The loop is torn down on unmount as before. deliveries-widget polled /api/notifications/recent every 15s regardless of tab visibility. Skip the poll while `document.hidden`, refresh immediately on becoming visible, and add an in-flight guard so a slow request can't stack overlapping polls. --- packages/webui/src/components/login-waves.tsx | 21 +++++++++++++++++-- .../components/overview/deliveries-widget.tsx | 16 ++++++++++++-- 2 files changed, 33 insertions(+), 4 deletions(-) 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]); From 9914db69e6f23f582cd4da407f7ccf58a254b6c6 Mon Sep 17 00:00:00 2001 From: Airline233 Date: Tue, 7 Jul 2026 22:34:55 +0800 Subject: [PATCH 16/18] feat(webui): add load button to process probe dialog (#189) --- packages/webui/src/components/pages/processes-page.tsx | 6 ++++++ packages/webui/src/components/process-probe-dialog.tsx | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/webui/src/components/pages/processes-page.tsx b/packages/webui/src/components/pages/processes-page.tsx index 8a7d62c5..aca90d94 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) { + void load(probeDialog.pid); + 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 && (