From 898898a5076e208ec8dec7b554ed67d5b8f03c93 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 14:51:48 +0800 Subject: [PATCH] feat(msg-push): handle three friend-related events we used to drop on the floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Close three coverage gaps surfaced by the cross-Lagrange-family audit (Lagrange V2 / LagrangeGo / acidify / lagrange-python): - **0x210 subType 179 + 226 (NewFriend)** — mutual-accept friend notice. 179 fires when bot sent a request and the other side accepted; 226 fires for the opposite direction. Both decode through the same wire shape. LagrangeGo handles the pair via a `case 226: case 179:` fallthrough in `client/listener.go:248`. We surface them as `kind: 'friend_add'`, which the existing converter routes straight to OneBot `notice.friend_add` — bot frameworks that wait for "auto-add a friend after they accept" were previously stuck because nothing arrived. - **0x210 subType 139 (self-recall)** — bot recalled its own message sent to a friend. Same `FriendRecall` wire shape as 138 but the peer is on `toUid` instead of `fromUid` — acidify's `parseFriendRecall:380` splits exactly this way. Without 139, self-recalls disappeared and downstream `notice.friend_recall` handlers thought the bot had never recalled anything. - **PkgType 85 (bot self-joined a group)** — fires on the bot's session once `set_group_add_request` is approved or an invite is accepted, ported from lagrange-python's `server_push/msg.py:108`. PkgType 33 (GroupMemberIncreaseNotice) only fires for *other* members joining, so without 85 the bot never received its own `notice.group_increase` until the first message arrived. We decode `SelfJoinInGroup` and emit `kind: 'group_member_join'` with `userUin = selfUin`; the existing converter picks `sub_type: 'approve' | 'invite'` from the operator/user equality so consumers see the standard OneBot shape. While wiring 139, also fix a *pre-existing* prod bug spotted via proton call-site analysis on the resulting bundle: `event-0x210.ts` imported `FriendRecall` from both `proto/proton/notify` (as `FriendRecallNotify`) *and* `events` (as the event interface). Proton's import-resolver registers `importedTypeSources` keyed on the *imported* name (last-write-wins), so the events.ts import shadowed the proto one — `protobuf_decode(...)` lost its codec, fell through to the runtime fallback throw, and was silently swallowed by `MsgPushRegistry.decode`'s catch. Verified by the substituted codec list in `dist/index.mjs`: pre-fix it had `FriendRequest` / `GeneralGrayTipInfo` but no `FriendRecall`; post-fix `FriendRecall` / `NewFriend` / `SelfJoinInGroup` are all emitted as expected. Side-step the collision by importing the proto types unaliased and re-deriving the colliding event type via `Extract`. New proto interfaces in `proto/proton/notify.ts`: - `NewFriend` + `NewFriendInfo` (uid/time/message/nickName fields, fields 1-9; ported from `LagrangeGo/.../notify.proto:25 NewFriend`) - `SelfJoinInGroup` (groupUin / operatorUid + a few placeholder fields; ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`) Regression coverage in `tests/msg-push-handler.test.ts`: - subType 179/226 both produce identical friend_add events - falls back to `routingHead.fromUin` when the new friend's uid isn't in the local cache (matches LagrangeGo's "emit-then-resolve" pattern) - subType 138 keeps fromUid as the peer (other recalled their own msg to us); subType 139 picks toUid (we recalled ours sent to them) - PkgType 85 emits group_member_join with userUin == selfUin, operator resolved through identity when known core: 635/635 tests pass (+7), typecheck clean. Production bundle now contains substituted codecs for FriendRecall, NewFriend, SelfJoinInGroup (cross-checked via `grep protobuf_decode_X` on `dist/index.mjs`). --- .../bridge/msg-push/decoders/event-0x210.ts | 66 +++++- .../msg-push/decoders/group-member-change.ts | 46 ++++- packages/core/src/bridge/msg-push/enums.ts | 32 +++ packages/core/src/bridge/msg-push/index.ts | 3 +- .../core/src/bridge/proto/proton/notify.ts | 39 ++++ packages/core/tests/msg-push-handler.test.ts | 190 +++++++++++++++++- 6 files changed, 361 insertions(+), 15 deletions(-) diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index fadc5dd5..eafe1fb1 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -1,15 +1,29 @@ // Handles Event0x210 wrapper (528). Internal switch on subType dispatches -// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290). +// to FriendRequest (35) / FriendRecall (138, 139) / NewFriend +// (179, 226) / FriendPoke (290). import { protobuf_decode } from '@snowluma/proton'; +// Proto types imported unaliased — proton's import-resolver registers +// `importedTypeSources` keyed on the *imported* name. If we also did +// `import type { FriendRecall } from '../../events'` it would shadow +// the proto-side mapping (last-write-wins), point the resolver at the +// event-side file which has no `pb<>` schema, and the codec would +// never get generated — `protobuf_decode(...)` then +// falls through to the runtime fallback and throws (silently caught +// by `MsgPushRegistry.decode`). The event-side colliding names are +// re-derived from `QQEventVariant` below via `Extract` instead. import type { - FriendRequest as FriendRequestNotify, - FriendRecall as FriendRecallNotify, + FriendRequest, + FriendRecall, GeneralGrayTipInfo, + NewFriend, } from '../../proto/proton/notify'; import type { - FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant, + FriendRequestEvent, FriendPokeEvent, + FriendAddEvent, QQEventVariant, } from '../../events'; + +type FriendRecallEvent = Extract; import type { MsgPushDecoder } from '../registry'; import type { MsgPushContext } from '../context'; import { Event0x210SubType } from '../enums'; @@ -23,8 +37,17 @@ const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x210: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x210SubType) { case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx); - case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); + // 138 (other-recalled) and 139 (self-recalled) share the same + // FriendRecall wire shape; the helper picks the right uid side + // based on the subType. + case Event0x210SubType.FriendRecallNotice: + case Event0x210SubType.FriendRecallSelfNotice: + return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + // 179 + 226 both carry the NewFriend payload — see enum comment. + case Event0x210SubType.NewFriendNotice: + case Event0x210SubType.NewFriendNoticeAlt: + return decodeNewFriend(ctx); case Event0x210SubType.GroupAppStatePush: // QQ-client-internal troop shortcut bar / discussion app state // push — no OneBot-level event. See enum comment for the @@ -36,7 +59,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { }; function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { - const request = protobuf_decode(ctx.content); + const request = protobuf_decode(ctx.content); if (!request?.info) return []; const sourceUid = request.info.newSource || request.info.sourceUid || ''; const ev: FriendRequestEvent = { @@ -52,18 +75,43 @@ function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { } function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] { - const recall = protobuf_decode(ctx.content); + const recall = protobuf_decode(ctx.content); if (!recall?.info) return []; - const ev: FriendRecall = { + // 138 = friend recalled their own message sent to bot (peer = fromUid). + // 139 = bot recalled own message sent to friend (peer = toUid). Same + // ambiguity acidify handles in `parseFriendRecall:380`. Without this + // split, self-recall events surface `userUin` as the bot itself which + // confuses downstream OneBot consumers that key off `user_id`. + const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice; + const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? ''; + const ev: FriendRecallEvent = { kind: 'friend_recall', time: recall.info.time ?? ctx.head.timestamp, selfUin: ctx.selfUin, - userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin), + userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin), msgSeq: recall.info.clientSequence ?? 0, }; return [ev]; } +function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] { + const nf = protobuf_decode(ctx.content); + if (!nf?.info) return []; + const newFriendUid = nf.info.uid ?? ''; + const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin); + if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot + const ev: FriendAddEvent = { + kind: 'friend_add', + // proto field is `fixed32 Time` — already uint32 seconds epoch. + // Fall back to head.timestamp if the field is missing (some + // captures have it as 0). + time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp, + selfUin: ctx.selfUin, + userUin: newFriendUin, + }; + return [ev]; +} + function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { const grayTip = protobuf_decode(ctx.content); if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return []; diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts index 53386dfc..4d371620 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts +++ b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts @@ -1,9 +1,21 @@ -// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34). -// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs -// voluntary leave (dt != 0 && dt != 130 means kicked). +// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34) + +// GroupSelfJoinedNotice (85, bot-self admittance). +// +// 33/34 share GroupChangeSchema; the decreaseType field distinguishes +// kick vs voluntary leave (dt != 0 && dt != 130 means kicked). +// +// 85 carries a different wire shape (`SelfJoinInGroup`) — without it +// the bot has no signal that its own `set_group_add_request` was +// approved (33 fires only for *other* members joining). We surface +// 85 as a regular GroupMemberJoin with `userUin = selfUin` so the +// existing OneBot converter naturally produces +// `notice.group_increase` with `sub_type: 'approve' | 'invite'` +// (the converter compares operator == user to pick the sub_type; +// for self-join the operator is the admin/inviter, so 'invite' is +// emitted — matching go-cqhttp / NapCat semantics). import { protobuf_decode } from '@snowluma/proton'; -import type { GroupChange } from '../../proto/proton/notify'; +import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify'; import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeOperatorUid, resolveUidToUin } from '../helpers'; @@ -47,3 +59,29 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { }; return [ev]; }; + +export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => { + const joined = protobuf_decode(ctx.content); + if (!joined) return []; + // groupUin is uint_64 on the wire (bigint). Real group IDs fit in + // uint32 (≤ 10 digits in practice), so Number() conversion is safe + // — saturate to 0 on the unlikely overflow rather than letting + // BigInt propagate downstream where consumers expect a number. + const groupUinBig = joined.groupUin ?? 0n; + const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0; + const operatorUid = joined.operatorUid ?? ''; + // We're the one joining — surface the bot's own identity as userUin + // so the existing converter's `notice.group_increase` shape works + // unchanged. + const ev: GroupMemberJoin = { + kind: 'group_member_join', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId, + userUin: ctx.selfUin, + userUid: ctx.identity.selfUid ?? '', + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0), + operatorUid, + }; + return [ev]; +}; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts index 12ba3f08..19a98eb1 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -13,6 +13,17 @@ export enum PkgType { PrivateFileMessage = 529, GroupRequestInvitationNotice = 525, GroupRequestJoinNotice = 84, + /** + * Self-join admittance — fires on the bot's session right after an + * admin approves its `set_group_add_request` or an invite-accept + * goes through. Ported from `lagrange-python`'s + * `server_push/msg.py:108 case 85`. Maps to OneBot11 + * `notice.group_increase` with the bot itself as `user_id` — + * existing 33 (GroupMemberIncreaseNotice) doesn't fire for the + * bot's own join, so without this case the bot never knows it + * just entered a group until the first message arrives. + */ + GroupSelfJoinedNotice = 85, GroupInviteNotice = 87, GroupAdminChangedNotice = 44, GroupMemberIncreaseNotice = 33, @@ -29,8 +40,29 @@ export enum Event0x2DCSubType { export enum Event0x210SubType { FriendRequestNotice = 35, + /** + * Outgoing friend-message recall — bot recalled its own message that + * was sent to a friend. Same `FriendRecall` wire shape as 138; the + * difference is direction (138 = friend recalled their own message + * sent to bot, 139 = bot recalled own message sent to friend). + * Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor` + * registered for both 138 and 139) + acidify (`138, 139 -> + * parseFriendRecall`). The decoder uses the subType to figure out + * which UID side ends up as `userUin` on the emitted event. + */ + FriendRecallSelfNotice = 139, FriendRecallNotice = 138, FriendPokeNotice = 290, + /** + * Mutual-accept friend notice — 179 fires when bot sent a friend + * request and the other side accepted; 226 fires for the opposite + * direction. Both decode through the same `NewFriend` wire shape + * (LagrangeGo registers them via a `case 226: case 179:` fallthrough + * in `client/listener.go:248-258`). Maps to OneBot11 + * `notice.friend_add`. + */ + NewFriendNotice = 179, + NewFriendNoticeAlt = 226, /** * Group-app state push (troop shortcut bar / discussion app). * diff --git a/packages/core/src/bridge/msg-push/index.ts b/packages/core/src/bridge/msg-push/index.ts index 536c4c6f..71766e90 100644 --- a/packages/core/src/bridge/msg-push/index.ts +++ b/packages/core/src/bridge/msg-push/index.ts @@ -9,7 +9,7 @@ import { buildContext } from './context'; import { MsgPushRegistry } from './registry'; import { PkgType } from './enums'; import { - decodeGroupMemberJoin, decodeGroupMemberLeave, + decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined, } from './decoders/group-member-change'; import { decodeGroupAdmin } from './decoders/group-admin'; import { @@ -26,6 +26,7 @@ export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; const registry = new MsgPushRegistry(); registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin); registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave); +registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined); registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin); registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest); registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation); diff --git a/packages/core/src/bridge/proto/proton/notify.ts b/packages/core/src/bridge/proto/proton/notify.ts index 2640dcca..4a916290 100644 --- a/packages/core/src/bridge/proto/proton/notify.ts +++ b/packages/core/src/bridge/proto/proton/notify.ts @@ -122,6 +122,45 @@ export interface FriendRecall { reserved?: pb<5, bytes>; } +// ── NewFriend (0x210 subType 179 + 226) ─────────────────────────── +// +// Mutual-accept friend notice. Fires when: +// - bot sent a friend request and the other side accepted (179), or +// - the other side sent a request and bot accepted it (226). +// Both subTypes share this wire shape; field semantics follow +// `LagrangeDev/LagrangeGo` client/packets/pb/message/notify.proto. + +export interface NewFriendInfo { + uid?: pb<1, string>; + field2?: pb<2, uint_32>; + time?: pb<3, uint_32>; // fixed32 on wire; uint_32 decoded value is the unix epoch + message?: pb<4, string>; + nickName?: pb<5, string>; + field6?: pb<6, uint_32>; + field7?: pb<7, uint_32>; + toUid?: pb<9, string>; +} + +export interface NewFriend { + field1?: pb<1, uint_32>; + info?: pb<2, NewFriendInfo>; +} + +// ── SelfJoinInGroup (PkgType 85) ────────────────────────────────── +// +// Fired when the bot itself was admitted into a group — typically the +// completion of an admin-approved join request or an accepted invite. +// Ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`. + +export interface SelfJoinInGroup { + groupUin?: pb<1, uint_64>; + field2?: pb<2, uint_32>; + operatorUid?: pb<3, string>; + field4?: pb<4, uint_32>; + field6?: pb<6, uint_32>; + field7?: pb<7, string>; +} + export interface GroupMuteState { targetUid?: pb<1, string>; duration?: pb<2, uint_32>; diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 2df80459..c40ca4c8 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -1,10 +1,30 @@ import { describe, expect, it } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push'; import { IdentityService } from '../src/bridge/identity-service'; import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info'; import { PushMsgSchema } from '../src/bridge/proto/message'; import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify'; -import type { GroupMemberJoin } from '../src/bridge/events'; +// Proton's call-site analyzer keys off the literal type identifier +// printed in `protobuf_encode` — it walks imports by *original* +// name (not alias). If both `import { X } from 'proto/notify'` and +// `import { X as Y } from 'events'` appear, the analyzer's import +// resolver picks up the second one and the proton-side definition +// loses, so call sites referencing `X` go un-replaced. Side-step by +// re-aliasing the event-side type's *source* (not just the local +// name) — we don't need to import it directly since assertions can +// inline-extract the kind. +import type { + NewFriend, FriendRecall, SelfJoinInGroup, +} from '../src/bridge/proto/proton/notify'; +import type { + GroupMemberJoin, FriendAddEvent, QQEventVariant, +} from '../src/bridge/events'; + +// Local alias for the event-side recall type — derived via Extract so +// we avoid an `import { FriendRecall as X }` that collides with the +// proton import above. +type FriendRecallEvent = Extract; import type { PacketInfo } from '../src/protocol/types'; import { protoEncode } from '../src/protobuf/decode'; import { subscribeLogs } from '../src/utils/logger'; @@ -161,3 +181,171 @@ describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { } }); }); + +// ── P1 coverage extension: subTypes confirmed by LagrangeGo / acidify +// that we were previously dropping into the "unknown" fallback. ── + +function makeEvent0x210PacketAny(subType: number, content: Uint8Array): PacketInfo { + const body = protoEncode({ + message: { + responseHead: { fromUin: 22222, type: 0, sigMap: 0 }, + contentHead: { msgType: 528, subType, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any, PushMsgSchema); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, + retCode: 0, fromClient: false, body, + }; +} + +describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', () => { + // 179 fires when bot sent a request and other side accepted; 226 + // when bot accepted other side's request. Both share the + // `NewFriend` wire shape (LagrangeGo registers both via + // case-fallthrough in `client/listener.go:248`). We surface them + // identically as `kind: 'friend_add'`. + + function makeNewFriendPacket(subType: 179 | 226, friendUid: string, time = 1710000000): PacketInfo { + const content = protobuf_encode({ + field1: 0, + info: { uid: friendUid, time, message: 'hello', nickName: 'Alice' }, + }); + return makeEvent0x210PacketAny(subType, content); + } + + it('emits friend_add for subType 179', () => { + const member = makeGroupMember(99999, 'u_new_friend'); + const [event] = parseMsgPush( + makeNewFriendPacket(179, member.uid), + makeIdentity([member]), + ) as FriendAddEvent[]; + + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(99999); + expect(event.time).toBe(1710000000); + }); + + it('emits friend_add for subType 226 (same wire shape, different surface)', () => { + const member = makeGroupMember(88888, 'u_other_friend'); + const [event] = parseMsgPush( + makeNewFriendPacket(226, member.uid), + makeIdentity([member]), + ) as FriendAddEvent[]; + + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(88888); + }); + + it('falls back to the packet routingHead.fromUin when the uid is not in the local cache', () => { + // No member registered for `u_unknown_uid`, but the packet itself + // carries the new friend's uin on `fromUin` (22222 in + // makeEvent0x210PacketAny). That's the wire-level convention + // (LagrangeGo emits unconditionally then calls `ResolveUin` post + // hoc, see `client/listener.go:259`). Without the fallback the + // event would either drop or surface `user_id: 0`, both of which + // confuse OneBot consumers. + const [event] = parseMsgPush( + makeNewFriendPacket(179, 'u_unknown_uid'), + makeIdentity(), + ) as FriendAddEvent[]; + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(22222); // the packet's fromUin + }); +}); + +describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => { + // 138 = friend recalled their own message sent to bot + // (peer in friend_recall event = fromUid) + // 139 = bot recalled own message sent to friend + // (peer in friend_recall event = toUid) + // Same wire shape; the subType is the direction discriminator. + // Acidify makes the same split in `parseFriendRecall:380`. Without + // 139, self-recalls used to fall through and disappear. + + function makeFriendRecallPacket(subType: 138 | 139, fromUid: string, toUid: string): PacketInfo { + const content = protobuf_encode({ + info: { + fromUid, toUid, clientSequence: 4242, newId: 0n, + time: 1710000000, random: 0, pkgNum: 1, pkgIndex: 0, divSeq: 1, + }, + }); + return makeEvent0x210PacketAny(subType, content); + } + + it('subType 138 keeps fromUid as the resolved peer (other recalled their own msg to us)', () => { + const friend = makeGroupMember(77777, 'u_friend'); + const [event] = parseMsgPush( + makeFriendRecallPacket(138, friend.uid, 'u_self'), + makeIdentity([friend]), + ) as FriendRecallEvent[]; + + expect(event.kind).toBe('friend_recall'); + expect(event.userUin).toBe(77777); + expect(event.msgSeq).toBe(4242); + }); + + it('subType 139 picks toUid as the peer (we recalled our msg sent to friend)', () => { + const friend = makeGroupMember(77777, 'u_friend'); + const [event] = parseMsgPush( + makeFriendRecallPacket(139, 'u_self', friend.uid), + makeIdentity([friend]), + ) as FriendRecallEvent[]; + + expect(event.kind).toBe('friend_recall'); + expect(event.userUin).toBe(77777); // resolved from toUid (the friend), not fromUid (us) + }); +}); + +describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => { + // PkgType 33 (GroupMemberIncreaseNotice) fires for *other* members + // joining; the bot's own join after `set_group_add_request` approval + // / invite-accept arrives at 85 instead. We surface it as + // `group_member_join` with `userUin = selfUin` so the OneBot + // converter naturally produces `notice.group_increase`. + function makeSelfJoinPacket(groupId: number, operatorUid = ''): PacketInfo { + const content = protobuf_encode({ + groupUin: BigInt(groupId), + field2: 1, + operatorUid, + field4: 0, + field6: 48, + field7: '', + }); + const body = protoEncode({ + message: { + responseHead: { fromUin: groupId, type: 0, sigMap: 0 }, + contentHead: { msgType: 85, subType: 0, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any, PushMsgSchema); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, + retCode: 0, fromClient: false, body, + }; + } + + it('emits group_member_join with userUin == selfUin', () => { + const [event] = parseMsgPush( + makeSelfJoinPacket(GROUP_ID), + makeIdentity(), + ) as GroupMemberJoin[]; + + expect(event.kind).toBe('group_member_join'); + expect(event.groupId).toBe(GROUP_ID); + expect(event.userUin).toBe(Number(SELF_UIN)); + }); + + it('resolves operator uid through identity when present', () => { + const admin = makeGroupMember(11111, 'u_admin'); + const [event] = parseMsgPush( + makeSelfJoinPacket(GROUP_ID, admin.uid), + makeIdentity([admin]), + ) as GroupMemberJoin[]; + + expect(event.operatorUin).toBe(admin.uin); + expect(event.operatorUid).toBe(admin.uid); + }); +});