From 11e7584d1c977f16e90e8136c369b23a022dffce Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 15:25:28 +0800 Subject: [PATCH 1/6] fix(onebot): approve bot self-invite via private card msgseq (#125) When the bot is invited to a group via a private-chat "qun.invite" ark card, set_group_add_request failed: handleGroupAddRequest re-derived the approval tuple from fetchGroupRequests (0x10c8_2), but for a self-invite the only sequence the server accepts at 0x10c8_1 is the msgseq embedded in the card's mqqapi://group/invite_join jumpUrl, applied with eventType=2 / filtered=false. The MSF invite push (PkgType 87) never carries that msgseq, so approval returned 120161001 'handle async message fail'. - friend-message decoder: parse the private invite card's jumpUrl and stash groupUin -> msgseq on the per-instance IdentityService. - ContactsApi.getGroupInviteCardSequence(groupId) exposes it. - handleGroupAddRequest: for an invite flag, if a card msgseq is cached, approve with setAddRequest(groupId, msgseq, 2, approve, reason, false); otherwise fall back to the existing fetchGroupRequests path. Validated on-target (Docker): private invite card -> set_group_add_request approve -> 0x10c8_1 ok -> bot joined the group (get_group_member_info shows role=member, fresh join_time); no 120161001. --- packages/core/src/bridge/apis/contacts.ts | 7 ++++ .../onebot/src/modules/request-actions.ts | 12 +++++++ packages/protocol/src/identity-service.ts | 15 +++++++++ .../src/msg-push/decoders/friend-message.ts | 32 ++++++++++++++++++- 4 files changed, 65 insertions(+), 1 deletion(-) diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 379abc46..24a9618b 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -232,6 +232,13 @@ export class ContactsApi { return requests; } + /** The approval msgseq captured from a private "qun.invite" card for this + * group, or undefined if none was seen. `set_group_add_request` uses it to + * approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */ + getGroupInviteCardSequence(groupId: number): number | undefined { + return this.ctx.identity.getGroupInviteCardSequence(groupId); + } + async fetchDownloadRKeys(): Promise { const resp = await FetchDownloadRkeys.invoke(this.ctx); diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index 29954e2b..573179a1 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -15,6 +15,18 @@ export async function handleGroupAddRequest( if (!groupId) throw new Error('invalid group_id in flag'); if (!targetUid) throw new Error('invalid request target in flag'); + // Bot self-invited via a private "qun.invite" card: the only sequence the + // server accepts at 0x10c8_1 is that card's jumpUrl msgseq, with eventType=2 + // / filtered=false. The fetchGroupRequests tuple below fails this case with + // 120161001 ("handle async message fail"). See issue #125. + if (requestType === 'invite') { + const cardSequence = bridge.apis.contacts.getGroupInviteCardSequence(groupId); + if (cardSequence) { + await bridge.apis.groupAdmin.setAddRequest(groupId, cardSequence, 2, approve, reason, false); + return; + } + } + const requests = await bridge.apis.contacts.fetchGroupRequests(); const matching = requests.find((r) => { if (r.groupId !== groupId) return false; diff --git a/packages/protocol/src/identity-service.ts b/packages/protocol/src/identity-service.ts index d2e566e2..7e7ee814 100644 --- a/packages/protocol/src/identity-service.ts +++ b/packages/protocol/src/identity-service.ts @@ -105,6 +105,10 @@ export class IdentityService { private readonly userProfiles_ = new Map(); private friends_: FriendInfo[] = []; private readonly groups_ = new Map(); + // groupUin → approval msgseq from a private "qun.invite" card's jumpUrl. + // The 0x10c8 approval for a bot self-invite needs THIS sequence (with + // eventType=2); the MSF invite push never carries it. See issue #125. + private readonly groupInviteCardSeqs_ = new Map(); // ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ─── private readonly uinByUid = new Map(); @@ -381,6 +385,17 @@ export class IdentityService { }))); } + /** Remember the approval msgseq carried by a private "qun.invite" card's + * jumpUrl, keyed by group. `set_group_add_request` reads it back to approve + * a bot self-invite via 0x10c8 (eventType=2). See issue #125. */ + rememberGroupInviteCardSequence(groupUin: number, sequence: number): void { + if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence); + } + + getGroupInviteCardSequence(groupUin: number): number | undefined { + return this.groupInviteCardSeqs_.get(groupUin); + } + rememberGroupRequests(requests: GroupRequestInfo[]): void { for (const request of requests) { this.rememberUidUin(request.targetUid, request.targetUin); diff --git a/packages/protocol/src/msg-push/decoders/friend-message.ts b/packages/protocol/src/msg-push/decoders/friend-message.ts index d0bedd21..858b4e4e 100644 --- a/packages/protocol/src/msg-push/decoders/friend-message.ts +++ b/packages/protocol/src/msg-push/decoders/friend-message.ts @@ -2,7 +2,37 @@ import type { FriendMessage } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeRichBody } from '../rich-body-decoder'; +/** + * A private "qun.invite" ark card (someone DMs the bot a group-invite card) + * carries the only sequence the server accepts when the bot later approves the + * invite via 0x10c8 — the `msgseq` embedded in its `mqqapi://group/invite_join` + * jumpUrl, applied with eventType=2 / filtered=false. The MSF invite push + * (PkgType 87) never carries it. Parse it out so `set_group_add_request` can + * use it. See issue #125. + */ +function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null { + if (!jsonText.includes('group/invite_join')) return null; + const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/); + if (!m) return null; + const query = m[0].split('?')[1] ?? ''; + const params = new URLSearchParams(query); + const groupUin = Number(params.get('groupcode') ?? 0); + const sequence = Number(params.get('msgseq') ?? 0); + if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) return null; + if (groupUin <= 0 || sequence <= 0) return null; + return { groupUin, sequence }; +} + export const decodeFriendMessage: MsgPushDecoder = (ctx) => { + const elements = decodeRichBody(ctx.body, false); + // Stash the approval msgseq from a private group-invite card so a later + // `set_group_add_request` can approve a bot self-invite (issue #125). + for (const el of elements) { + if (el.type === 'json' && typeof el.text === 'string') { + const card = parseGroupInviteCard(el.text); + if (card) ctx.identity.rememberGroupInviteCardSequence(card.groupUin, card.sequence); + } + } const ev: FriendMessage = { kind: 'friend_message', time: ctx.head.timestamp, @@ -10,7 +40,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => { senderUin: ctx.fromUin, msgSeq: ctx.head.sequence, msgId: ctx.head.msgId & 0x7FFFFFFF, - elements: decodeRichBody(ctx.body, false), + elements, senderNick: '', }; if (ctx.responseHead?.forward?.friendName) { From 839de51519b221ce654fa1570318dea51b8ee057 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 16:07:36 +0800 Subject: [PATCH 2/6] fix(protocol): c2c reply uses origSeqs[0], not friendSequence (#114, #124) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A private (c2c) reply resolved to srcMsg.reserve.friendSequence, but a received message's message_id is hashed from its head.sequence. On-target capture showed origSeqs[0] == head.sequence (e.g. 12709) while friendSequence is a small friend-relationship counter (e.g. 25) — so reply.id != the quoted message_id. Downstream get_msg(reply_id) then missed: - #114: reported reply id didn't match the quoted message's real id. - #124: replying to a File message returned empty quoted content (AstrBot relies on get_msg(reply_id) to learn the quote was a file; text replies appeared fine because they read the inline follow-up text instead). Drop the c2c friendSequence override (reverting cf8e62d's premise, which was backwards) so both group and c2c replies use origSeqs[0]. Validated on-target (Docker): file message id == reply.id, and get_msg(reply_id) -> retcode 0, message [{type:file}]. --- .../src/msg-push/rich-body-decoder.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 600cfcd9..d0bc4b3d 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -9,7 +9,6 @@ import type { NotOnlineImage, QFaceExtra, QSmallFaceExtra, - SrcMsgPbReserve, } from '@snowluma/proto-defs/element'; import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message'; import { decompressData, makeImageUrl } from './helpers'; @@ -22,7 +21,7 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): const elements: MessageElement[] = []; if (body?.richText) { const rt = body.richText; - if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[], isGroup)); + if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[])); extractRichtextExtras(rt, elements, isGroup); } if (body?.msgContent && body.msgContent.length > 0) { @@ -31,7 +30,7 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): return elements; } -function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement[] { +function convertElements(elems: ElemDecoded[]): MessageElement[] { const result: MessageElement[] = []; let skipNext = false; @@ -46,11 +45,15 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement // Lagrange's `Sequence = reserve.FriendSequence ?? OrigSeqs[0]` // (ForwardEntity.cs). Group replies keep origSeqs[0] (the shared group seq). if (elem.srcMsg) { - let replySeq = elem.srcMsg.origSeqs?.[0] ?? 0; - if (!isGroup && elem.srcMsg.pbReserve && elem.srcMsg.pbReserve.length > 0) { - const reserve = protobuf_decode(elem.srcMsg.pbReserve); - if (reserve.friendSequence) replySeq = reserve.friendSequence; - } + // The reply resolves to srcMsg.origSeqs[0] — for BOTH group (shared group + // seq) and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals + // the quoted message's head.sequence, i.e. the seq its message_id is + // hashed from. reserve.friendSequence is a small friend-relationship + // counter that does NOT match (e.g. 25 vs a head.sequence of 12707), so + // the earlier `friendSequence` override made reply.id != the quoted + // message_id: get_msg(reply_id) missed and a quoted File's content came + // back empty. + const replySeq = elem.srcMsg.origSeqs?.[0] ?? 0; if (replySeq > 0) result.push({ type: 'reply', replySeq }); } From 45aae92af5d1541ed19885a36e72571d3aad3baa Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 20:37:19 +0800 Subject: [PATCH 3/6] =?UTF-8?q?fix(protocol):=20group=20reply+at=20?= =?UTF-8?q?=E2=80=94=20emit=20replied-sender=20mention=20after=20srcMsg=20?= =?UTF-8?q?(#129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a group message combined a reply with a user @ , the @ showed but never notified (no blue link, no ping). On-target capture showed SnowLuma sent [srcMsg, @target(mention), text] — the @ lands directly in the reply's mention slot right after srcMsg, which the QQ NT group server does not honor. Mirror Lagrange's ForwardEntity.PackElement: when a reply and an @ coexist in a group message, emit the replied sender as a trailing mention element right after srcMsg, so the user's @ is no longer the first post-srcMsg element and is honored. Gated to the reply+@ case so plain replies are unchanged. Validated on-target (Docker, group send): baseline reply+at -> @ not delivered; fixed -> @ delivered (blue link + notification). --- packages/protocol/src/element-builder.ts | 28 +++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index d251084a..43be2636 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -105,6 +105,20 @@ function makeReplyElem(element: MessageElement): ProtoElem { return { srcMsg }; } +// The replied sender, encoded as a mention element placed right after srcMsg. +// QQ NT's group reply wire shape expects this; without it a following +// user-supplied @ is silently not honored by the server (issue #129). +async function makeReplyMentionElem(ctx: SendContext, uin: number): Promise { + if (ctx.groupId === undefined || uin <= 0) return null; + const member = ctx.bridge.identity.findGroupMember(ctx.groupId, uin); + let uid = member?.uid ?? ''; + if (!uid) uid = await ctx.bridge.identity.resolveUid(uin, ctx.groupId).catch(() => ''); + if (!uid) return null; + const name = member?.card?.trim() || member?.nickname?.trim() || String(uin); + const extra = protobuf_encode({ type: 2, uin, field5: 0, uid }); + return { text: { str: `@${name} `, pbReserve: extra } }; +} + function makeDeflatedPayload(content: string): Uint8Array { const deflated = deflateSync(Buffer.from(content, 'utf8')); const payload = new Uint8Array(deflated.length + 1); @@ -378,6 +392,12 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise */ export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise { const result: ProtoElem[] = []; + // A user-supplied @ that lands immediately after a reply's srcMsg isn't + // honored by the QQ NT group server (the @ shows but never notifies, #129). + // When a reply and an @ coexist, emit the replied sender as a trailing + // mention right after srcMsg (mirrors Lagrange ForwardEntity.PackElement), + // which restores the wire shape the server expects. + const hasUserAt = elements.some((e) => e.type === 'at'); for (const elem of elements) { switch (elem.type) { @@ -398,7 +418,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'reply': - if (elem.replySeq) result.push(makeReplyElem(elem)); + if (elem.replySeq) { + result.push(makeReplyElem(elem)); + if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) { + const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin); + if (replyMention) result.push(replyMention); + } + } break; case 'json': From 4593ba334056b152ce2e8a569816fe858b32f4c7 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 20:53:10 +0800 Subject: [PATCH 4/6] fix(protocol): strip reply auto-mention on receive; align send to uin=0 (#127) A QQ NT reply carries the replied sender as a structural auto-mention (MentionExtra.type=2, uin=0) right after srcMsg, plus a blank separator text. SnowLuma reported both as a real [CQ:at] + empty/space segment, so downstreams saw a phantom @ (#127). A real user @ carries a non-zero MentionExtra.uin, so it is preserved. - receive (rich-body-decoder): after a reply, drop a type=2/uin=0 mention and the blank text that follows it; keep non-zero-uin mentions. - send (element-builder, #129 follow-up): the reply auto-mention added for reply+@ now uses uin=0 (real uid stays in `uid`) to match QQ's native wire shape, so the bot's own replies are stripped the same way by receivers and don't surface a phantom @ either. Validated on-target (Docker, group): reply w/o @ -> [reply, text] (no phantom @/empty); reply w/ @ -> [reply, at(real), text]; bot reply+@ still delivers the @ (uin=0). --- packages/protocol/src/element-builder.ts | 6 +++++- .../src/msg-push/rich-body-decoder.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index 43be2636..a8f5265d 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -115,7 +115,11 @@ async function makeReplyMentionElem(ctx: SendContext, uin: number): Promise ''); if (!uid) return null; const name = member?.card?.trim() || member?.nickname?.trim() || String(uin); - const extra = protobuf_encode({ type: 2, uin, field5: 0, uid }); + // uin=0 matches QQ NT's native reply auto-mention (the real uid lives in + // `uid`). It does not itself notify — the user's own @ does — and the receive + // side strips a type=2/uin=0 mention as structural (#127), so the bot's own + // replies don't surface a spurious @ either. + const extra = protobuf_encode({ type: 2, uin: 0, field5: 0, uid }); return { text: { str: `@${name} `, pbReserve: extra } }; } diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index d0bc4b3d..cf5a5c3b 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -33,6 +33,13 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): function convertElements(elems: ElemDecoded[]): MessageElement[] { const result: MessageElement[] = []; let skipNext = false; + // [#127] A QQ NT reply carries the replied sender as a structural auto-mention + // (MentionExtra.type=2, uin=0) right after srcMsg, followed by a blank + // separator text. Both are part of the reply wire shape, not user content — + // drop them so they aren't reported as a spurious @ + empty segment. A real + // user @ carries a non-zero MentionExtra.uin, so it's preserved. + let sawReply = false; + let dropNextBlankText = false; for (const elem of elems) { if (skipNext) { skipNext = false; continue; } @@ -55,6 +62,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // back empty. const replySeq = elem.srcMsg.origSeqs?.[0] ?? 0; if (replySeq > 0) result.push({ type: 'reply', replySeq }); + sawReply = true; } // Text (with possible @ detection) @@ -67,6 +75,17 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11; const hasMention = mention && (mention.type === 1 || mention.type === 2); + // [#127] drop the reply's structural auto-mention (type=2, uin=0) and the + // blank separator text right after it; keep real @s (non-zero uin). + if (sawReply && mention && mention.type === 2 && (mention.uin ?? 0) === 0) { + dropNextBlankText = true; + continue; + } + if (dropNextBlankText) { + dropNextBlankText = false; + if (!hasMention && (t.str ?? '').trim() === '') continue; + } + if (hasAttr6 || hasMention) { const me: MessageElement = { type: 'at', text: t.str ?? '' }; if (hasAttr6) { From e160837f8b26102ba1b2222d61c4ebd878465234 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 21:25:05 +0800 Subject: [PATCH 5/6] feat(onebot): tiered reply backfill + quoted-file recovery for get_msg (#128) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Harvests the sound ideas from PR #128 while KEEPING origSeqs[0] as the c2c reply sequence (on-target capture in #114/#124 proved origSeqs[0] == the quoted message's head.sequence; pbReserve.friendSequence is a small unrelated counter that makes reply.id miss). The PR's friendSequence override is intentionally NOT taken. - rich-body-decoder: enrich the reply element with replySenderUin/replyTime and the quoted message's own decoded elements (SrcMsg.elems, field 5); recover a c2c quoted FILE from sourceMsg (field 9 -> RichText.notOnlineFile) when elems carried none, so a quoted file survives into get_msg (#124). - backfillReplyTarget: tiered fallback — Tier 0 local store, Tier 1 server fetch (correct seq = origSeqs[0]), Tier 2 reconstruct from the embedded quoted elements (no round-trip), Tier 3 minimal '[引用消息]' placeholder so get_msg never returns 'message not found'. - to-segment: per-element try/catch (logged, not silent) so one bad element doesn't drop the whole message. - actions/message: log get_msg misses. - tests: fix request-actions getGroupInviteCardSequence mock (gap from #125); cover backfill Tier 2 (reconstruct) + Tier 3 (placeholder); flip the stale c2c reply test to assert origSeqs[0] (was asserting the disproven friendSequence). Validated on-target (Docker): get_msg on group reply, private text reply, and a private quoted FILE all return correct content (file with name/size/id); full onebot + protocol suites green. --- packages/onebot/src/actions/message.ts | 8 +- .../onebot/src/event-converter/to-segment.ts | 18 ++- .../onebot/src/modules/message-actions.ts | 103 +++++++++++++++--- .../tests/backfill-reply-target.test.ts | 32 +++++- packages/onebot/tests/request-actions.test.ts | 2 + packages/protocol/src/events.ts | 1 + .../src/msg-push/rich-body-decoder.ts | 38 ++++++- .../tests/msg-push/rich-body-decoder.test.ts | 21 ++-- 8 files changed, 189 insertions(+), 34 deletions(-) diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index 40e229c6..6f816794 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -1,8 +1,11 @@ +import { createLogger } from '@snowluma/common/logger'; import type { JsonObject, JsonValue } from '../types'; import type { ApiHandler, ApiActionContext } from '../api-handler'; import { defineAction, groupAction, registerActions, f } from '../action-kit'; import { RETCODE, failedResponse, okResponse } from '../types'; +const log = createLogger('OneBot'); + /** * Re-sign image URLs in a stored message event at read time. `get_msg` * returns a copy persisted when the message first arrived, and image rkeys @@ -89,7 +92,10 @@ export const actions = [ params: { message_id: f.messageId() }, run: async (p, ctx) => { const data = ctx.getMessage(p.message_id); - if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + if (!data) { + log.warn('[get_msg] miss message_id=%d', p.message_id); + return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + } const result: JsonObject = { ...data }; delete result.post_type; delete result.self_id; diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index edf7d0ab..db5bc33d 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -7,6 +7,9 @@ import type { MessageIdResolver, } from './index'; import { resolveReplyId } from './utils'; +import { createLogger } from '@snowluma/common/logger'; + +const log = createLogger('OneBot'); export async function elementsToJson( elements: MessageElement[], @@ -19,10 +22,17 @@ export async function elementsToJson( ): Promise { const result: JsonArray = []; for (const element of elements) { - result.push(await elementToSegment( - element, isGroup, sessionId, - imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, - )); + // One malformed element shouldn't drop the whole message — skip it (with a + // breadcrumb) and keep converting the rest. + try { + result.push(await elementToSegment( + element, isGroup, sessionId, + imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, + )); + } catch (err) { + log.warn('segment convert skipped type=%s (%s)', element.type, + err instanceof Error ? err.message : String(err)); + } } return result; } diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 1a43854b..3505dbce 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -210,30 +210,103 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; const targetId = hashMessageIdInt32(replySeq, session, eventName); - if (ref.messageStore.findEvent(targetId)) return; // already have the full event + if (ref.messageStore.findEvent(targetId)) return; // Tier 0: already have the full event + // Tier 1: fetch the quoted message from the server, keyed under the exact id + // the reply resolves to (replySeq is origSeqs[0] == the quoted message's own + // head.sequence, so this matches how it was/would be stored). A c2c message + // the bot itself sent converts with user_id=self but is still keyed under the + // reply's session (the peer), so get_msg(targetId) hits. try { - let fetched: GroupMessage | FriendMessage | null; + let fetched: GroupMessage | FriendMessage | null = null; if (isGroup) { fetched = await ref.bridge.apis.message.getGroupMessageBySeq(session, replySeq, ref.selfId); } else { const friendUid = await ref.bridge.resolveUserUid(session); - if (!friendUid) return; - fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId); + if (friendUid) { + fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId); + } + } + if (fetched) { + const json = await convertEvent(ref.converterCtx, fetched); + if (json) { + json.message_id = targetId; + ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json); + return; + } } - if (!fetched) return; - - const json = await convertEvent(ref.converterCtx, fetched); - if (!json) return; - // Key under the exact id the reply resolves to (and the reply's session) so - // get_msg(targetId) hits regardless of who sent the quoted message: a c2c - // message the bot itself sent converts with user_id=self and would - // otherwise key under a different session than the reply's peer. - json.message_id = targetId; - ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json); } catch (err) { - log.warn('reply-target backfill failed (%s)', err instanceof Error ? err.message : String(err)); + log.warn('reply-target backfill tier-1 failed (%s)', err instanceof Error ? err.message : String(err)); } + + // Tier 2: reconstruct from the quoted message's own elements, which the push + // embeds in SrcMsg.elems — no server round-trip. Covers messages the server + // won't return (expired, self-c2c, file-only) but whose content rode along. + const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session); + if (reply?.replyElements?.length) { + try { + const segments = await elementsToOneBotSegments( + reply.replyElements, isGroup, session, + ref.converterCtx.imageUrlResolver, ref.converterCtx.mediaUrlResolver, + ref.converterCtx.messageIdResolver, ref.converterCtx.mediaSegmentSink, + ) as JsonArray; + const fallback = buildBackfillEvent(targetId, replySeq, quotedSender, + reply.replyTime ?? 0, segments, ref.selfId, isGroup, session); + ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback); + return; + } catch (err) { + log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(err)); + } + } + + // Tier 3: minimal `[引用消息]` placeholder so get_msg(reply_id) never returns + // "message not found" — an approval bot that fires get_msg right after seeing + // the reply gets a well-formed (if sparse) event instead of an error. + const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender, + reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }], + ref.selfId, isGroup, session); + ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder); +} + +// Build a stored-message event for a backfilled reply target (Tier 2/3). +function buildBackfillEvent( + messageId: number, + msgSeq: number, + senderUin: number, + timestamp: number, + segments: JsonArray, + selfId: number, + isGroup: boolean, + sessionId: number, +): JsonObject { + const common = { + time: timestamp || Math.floor(Date.now() / 1000), + self_id: selfId, + post_type: 'message' as const, + message_id: messageId, + message_seq: msgSeq, + message: segments, + raw_message: segmentsToRawMessage(segments), + font: 0, + }; + if (isGroup) { + return { + ...common, + message_type: 'group', + sub_type: 'normal', + group_id: sessionId, + user_id: senderUin, + sender: { user_id: senderUin, nickname: '', card: '', role: 'member', sex: 'unknown', age: 0 }, + anonymous: null, + }; + } + return { + ...common, + message_type: 'private', + sub_type: 'friend', + user_id: senderUin, + sender: { user_id: senderUin, nickname: '', sex: 'unknown', age: 0 }, + }; } // Persist a converted history event so reply / get_msg / future listing resolve diff --git a/packages/onebot/tests/backfill-reply-target.test.ts b/packages/onebot/tests/backfill-reply-target.test.ts index ff8346fa..2c1436d6 100644 --- a/packages/onebot/tests/backfill-reply-target.test.ts +++ b/packages/onebot/tests/backfill-reply-target.test.ts @@ -145,7 +145,30 @@ describe('backfillReplyTarget', () => { expect(store.storeEvent).not.toHaveBeenCalled(); }); - it('does not store when the server has nothing at that sequence', async () => { + it('reconstructs from replyElements when the server has nothing (tier 2)', async () => { + const store = fakeStore(false); + const getGroupMessageBySeq = vi.fn(async () => null); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() }, + } as any; + const event = { + kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, + senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2, + elements: [{ type: 'reply', replySeq: 123, replySenderUin: 800, replyElements: [{ type: 'text', text: 'quoted' }] }], + } as any; + + await backfillReplyTarget(ref, event); + + const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT); + expect(store.storeEvent).toHaveBeenCalledOnce(); + expect(store.storeEvent).toHaveBeenCalledWith( + targetId, true, 700, 123, GROUP_MESSAGE_EVENT, + expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }), + ); + }); + + it('stores a [引用消息] placeholder when server fetch and replyElements both miss (tier 3)', async () => { const store = fakeStore(false); const getGroupMessageBySeq = vi.fn(async () => null); const ref = { @@ -156,6 +179,11 @@ describe('backfillReplyTarget', () => { await backfillReplyTarget(ref, groupEvent(123)); expect(getGroupMessageBySeq).toHaveBeenCalledOnce(); - expect(store.storeEvent).not.toHaveBeenCalled(); + const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT); + expect(store.storeEvent).toHaveBeenCalledOnce(); + expect(store.storeEvent).toHaveBeenCalledWith( + targetId, true, 700, 123, GROUP_MESSAGE_EVENT, + expect.objectContaining({ message_id: targetId, message_type: 'group' }), + ); }); }); diff --git a/packages/onebot/tests/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts index e636503c..682dcb1e 100644 --- a/packages/onebot/tests/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -8,6 +8,7 @@ const APIS_ROUTING: Record = { fetchFriendList: 'contacts', fetchGroupList: 'contacts', fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', + getGroupInviteCardSequence: 'contacts', }; function fakeBridge(overrides: Record = {}): BridgeInterface { @@ -72,6 +73,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { fetchGroupRequests: vi.fn(async () => [ fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }), ]), + getGroupInviteCardSequence: vi.fn(() => null), apis: { groupAdmin: { setAddRequest } } as any, }); diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 8edc06ba..34ed625c 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -14,6 +14,7 @@ export interface MessageElement { replySenderUin?: number; // For reply: original sender's UIN replyTime?: number; // For reply: original message timestamp replyRandom?: number; // For reply: original message random/msgId + replyElements?: MessageElement[]; // Decoded elements of the quoted message (SrcMsg.elems) — lets a backfill reconstruct it for get_msg without a server round-trip url?: string; thumbUrl?: string; subType?: number; diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index cf5a5c3b..b93d5133 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -10,7 +10,7 @@ import type { QFaceExtra, QSmallFaceExtra, } from '@snowluma/proto-defs/element'; -import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message'; +import type { FileExtra, MessageBody, PushMsgBody as PushMsgBodyFull, RichText } from '@snowluma/proto-defs/message'; import { decompressData, makeImageUrl } from './helpers'; type ElemDecoded = Elem; @@ -60,8 +60,40 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // the earlier `friendSequence` override made reply.id != the quoted // message_id: get_msg(reply_id) missed and a quoted File's content came // back empty. - const replySeq = elem.srcMsg.origSeqs?.[0] ?? 0; - if (replySeq > 0) result.push({ type: 'reply', replySeq }); + const src = elem.srcMsg; + const replySeq = src.origSeqs?.[0] ?? 0; + if (replySeq > 0) { + const reply: MessageElement = { type: 'reply', replySeq }; + if (src.senderUin) reply.replySenderUin = Number(src.senderUin); + if (src.time) reply.replyTime = src.time; + // Decode the quoted message's own elements (SrcMsg.elems, field 5) so a + // backfill can reconstruct it locally if it isn't in the store / server. + if (src.elemsRaw?.length) { + const decoded: ElemDecoded[] = []; + for (const raw of src.elemsRaw) { + try { decoded.push(protobuf_decode(raw)); } catch { /* skip corrupt elem */ } + } + if (decoded.length) reply.replyElements = convertElements(decoded); + } + // A C2C quoted FILE lives in RichText.notOnlineFile (message level), not + // in elems[] — recover it from sourceMsg (field 9) when elems carried no + // file, so a quoted file's content survives into get_msg (#124). + if (src.sourceMsg?.length && !reply.replyElements?.some((e) => e.type === 'file')) { + try { + const pmsg = protobuf_decode(src.sourceMsg); + const nof = pmsg?.body?.richText?.notOnlineFile; + if (nof?.fileName) { + (reply.replyElements ??= []).push({ + type: 'file', + fileName: nof.fileName, + fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0, + fileId: nof.fileUuid ?? '', + }); + } + } catch { /* sourceMsg decode is best-effort */ } + } + result.push(reply); + } sawReply = true; } diff --git a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts index c8053270..d304aa2d 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -165,13 +165,15 @@ describe('decodeRichBody / market face', () => { }); }); -// Reply identity for c2c: a friend's reply carries the per-sender -// clientSequence in srcMsg.origSeqs[0], but the *canonical* replied-to sequence -// (the one the original message is keyed by) is srcMsg.pbReserve.friendSequence. -// Reading origSeqs[0] made get_msg on the quoted message miss ("无法解析申请信息"). -describe('decodeRichBody / reply uses friendSequence for c2c', () => { - const CLIENT_SEQ = 23188; // origSeqs[0] — per-sender clientSequence - const FRIEND_SEQ = 888; // pbReserve.friendSequence — canonical replied-to seq +// Reply identity for c2c: the replied-to sequence is srcMsg.origSeqs[0] for BOTH +// group and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals the +// quoted message's head.sequence — i.e. the seq its message_id is hashed from — +// while pbReserve.friendSequence is a small friend-relationship counter that does +// NOT match (e.g. 25 vs a head.sequence of 12707). Reading friendSequence made +// reply.id != the quoted message_id, so get_msg(reply_id) missed. +describe('decodeRichBody / reply uses origSeqs[0] for c2c', () => { + const CLIENT_SEQ = 23188; // origSeqs[0] — the quoted message's head.sequence + const FRIEND_SEQ = 888; // pbReserve.friendSequence — a small unrelated counter, ignored function replyBody(): MessageBody { return { @@ -188,8 +190,9 @@ describe('decodeRichBody / reply uses friendSequence for c2c', () => { }; } - it('c2c: replySeq = friendSequence, not origSeqs[0]', () => { - expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: FRIEND_SEQ }); + it('c2c: replySeq = origSeqs[0], not friendSequence (#114/#124)', () => { + expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: CLIENT_SEQ }); + expect(FRIEND_SEQ).not.toBe(CLIENT_SEQ); // guard: the two must differ for this to mean anything }); it('group: replySeq = origSeqs[0] (friendSequence ignored)', () => { From 1bd126562fb1c29875e3849170b0ff3260e4591b Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 22 Jun 2026 21:31:06 +0800 Subject: [PATCH 6/6] chore(release): v1.10.2 --- package.json | 2 +- packages/bridge/package.json | 2 +- packages/common/package.json | 2 +- packages/core/package.json | 2 +- packages/mcp/package.json | 2 +- packages/onebot/package.json | 2 +- packages/proto-defs/package.json | 2 +- packages/protocol/package.json | 2 +- packages/proton/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 510d1a1b..a8ccb879 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.10.1", + "version": "1.10.2", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 32518c49..ca24d120 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/common/package.json b/packages/common/package.json index d50055a7..0902bf69 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index 3d07a2c3..bf1b4717 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.10.1", + "version": "1.10.2", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 406bcb60..2140c5f4 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.10.1", + "version": "1.10.2", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 3c55c2fe..9aca50bc 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 142af27e..e7a30535 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 9fb17add..b0d3c280 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/proton/package.json b/packages/proton/package.json index 4767c7c8..911ba1e3 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 241c9226..74c9cedb 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 1148ec4c..df046765 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.10.1", + "version": "1.10.2", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index a04bb3c2..7e74ca62 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.10.1", + "version": "1.10.2", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index e653d3ba..4336ac5b 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.10.1", + "version": "1.10.2", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 533c9928..7bebfefc 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.10.1", + "version": "1.10.2", "type": "module", "scripts": { "dev": "vite",