diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 72f15d35..c0203393 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -422,5 +422,38 @@ export class MessageApi { return walkBackHistory(endSeq, count, (start, end) => fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end)); } + + /** + * Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a + * 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to + * back-fill a replied-to message the local store never saw. Returns the + * matching `group_message`, or null if absent / on error. + */ + async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise { + if (!(groupUin > 0) || !(seq > 0)) return null; + await throttleHistory(); + try { + const batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq); + return batch.find((m) => m.msgSeq === seq) ?? null; + } catch { + return null; + } + } + + /** + * Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a + * 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the + * conversation peer. Returns the matching `friend_message`, or null. + */ + async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise { + if (!friendUid || !(seq > 0)) return null; + await throttleHistory(); + try { + const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq); + return batch.find((m) => m.msgSeq === seq) ?? null; + } catch { + return null; + } + } } diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 53fce4e9..c339c50a 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -4,6 +4,7 @@ import type { QQEventVariant } from '@snowluma/protocol/events'; import { convertEvent } from './event-converter'; import type { OneBotInstanceContext } from './instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; +import { backfillReplyTarget } from './modules/message-actions'; import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter'; const moduleLog = createLogger('Event'); @@ -94,6 +95,13 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]); return; } + // If this message quotes one we don't have, fetch + persist it first (gated + + // throttled) so a consumer's get_msg on the quote resolves. No-op for the + // common case (no reply, or the quoted message is already stored). Never let a + // back-fill failure block delivery of the live message. + try { + await backfillReplyTarget(ctx, event); + } catch { /* best-effort — dispatch the live event regardless */ } ctx.dispatchEvent(converted); log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]); } diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index b41ae29e..1a43854b 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1,6 +1,6 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; +import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events'; import type { MessageSendResult } from '../api-handler'; import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter'; import { segmentsToRawMessage } from '../helper/cq'; @@ -181,6 +181,61 @@ export async function getFriendHistory( return getFriendMsgHistory(ref.messageStore, userId, messageId, count); } +/** + * Back-fill the message a freshly-received reply points to, when the local store + * doesn't have the full event (e.g. a message from before SnowLuma was running, + * or one it never observed). Fetches just the quoted message from the server — + * group via `SsoGetGroupMsg`, c2c via `SsoGetC2cMsg`, both through the shared + * history throttle gate — and persists it under the SAME id the reply resolves + * to, so a subsequent `get_msg` (or quote lookup) hits. + * + * No-op when: the event isn't a group/friend message, has no reply, the target + * is already stored, the uid can't be resolved, the fetch returns nothing, or + * it errors. Meant to be awaited before dispatch so the consumer's get_msg — + * which an approval bot fires right after seeing the reply — sees the message. + */ +export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant): Promise { + let isGroup: boolean; + let session: number; + if (event.kind === 'group_message') { isGroup = true; session = event.groupId; } + else if (event.kind === 'friend_message') { isGroup = false; session = event.senderUin; } + else return; + if (!Number.isInteger(session) || session <= 0) return; + + const reply = event.elements.find( + (e: MessageElement) => e.type === 'reply' && Number.isInteger(e.replySeq) && (e.replySeq ?? 0) > 0, + ); + const replySeq = reply?.replySeq ?? 0; + if (replySeq <= 0) return; + + 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 + + try { + let fetched: GroupMessage | FriendMessage | 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 (!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)); + } +} + // Persist a converted history event so reply / get_msg / future listing resolve // it — keyed exactly like the live pipeline (group → group_id, private → the // sender uin carried in user_id). diff --git a/packages/onebot/tests/backfill-reply-target.test.ts b/packages/onebot/tests/backfill-reply-target.test.ts new file mode 100644 index 00000000..ff8346fa --- /dev/null +++ b/packages/onebot/tests/backfill-reply-target.test.ts @@ -0,0 +1,161 @@ +// When an incoming message quotes one SnowLuma's store doesn't have, the +// receive pipeline fetches just that message from the server (group → +// getGroupMessageBySeq, c2c → getC2cMessageBySeq, both rate-limited) and +// persists it under the SAME id the reply resolves to, so a consumer's get_msg +// on the quote hits. These tests cover the gating + keying of that back-fill. + +import { describe, expect, it, vi } from 'vitest'; +import { backfillReplyTarget } from '../src/modules/message-actions'; +import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/message-id'; + +const SELF = 10001; + +const converterCtx = { + selfId: SELF, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: null, + mediaSegmentSink: null, +} as any; + +function fakeStore(has = false) { + return { + findEvent: vi.fn(() => (has ? ({ message_id: 1 } as any) : null)), + storeEvent: vi.fn(), + }; +} + +function groupEvent(replySeq: number | null) { + const elements: any[] = replySeq != null ? [{ type: 'reply', replySeq }] : []; + elements.push({ type: 'text', text: '同意' }); + return { + kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, + senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2, elements, + } as any; +} + +function fetchedGroupMessage(msgSeq: number) { + return { + kind: 'group_message', time: 1700000000, selfUin: SELF, groupId: 700, senderUin: 800, + senderNick: 'orig', senderCard: '', senderRole: 'member', msgSeq, msgId: 1, + elements: [{ type: 'text', text: 'quoted' }], + } as any; +} + +function fetchedFriendMessage(msgSeq: number, senderUin: number) { + return { + kind: 'friend_message', time: 1700000000, selfUin: SELF, senderUin, + senderNick: 'orig', msgSeq, msgId: 1, elements: [{ type: 'text', text: 'quoted' }], + } as any; +} + +describe('backfillReplyTarget', () => { + it('group: fetches the quoted message and stores it under the resolved reply id', async () => { + const store = fakeStore(false); + const getGroupMessageBySeq = vi.fn(async () => fetchedGroupMessage(123)); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() }, + } as any; + + await backfillReplyTarget(ref, groupEvent(123)); + + expect(getGroupMessageBySeq).toHaveBeenCalledWith(700, 123, SELF); + const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT); + expect(store.storeEvent).toHaveBeenCalledWith( + targetId, true, 700, 123, GROUP_MESSAGE_EVENT, + expect.objectContaining({ message_id: targetId, message_type: 'group' }), + ); + }); + + it('c2c: resolves the friend uid, fetches, and stores under the peer session', async () => { + const store = fakeStore(false); + const getC2cMessageBySeq = vi.fn(async () => fetchedFriendMessage(456, 448671521)); + const resolveUserUid = vi.fn(async () => 'u_friend'); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getC2cMessageBySeq } }, resolveUserUid }, + } as any; + const event = { + kind: 'friend_message', time: 1, selfUin: SELF, senderUin: 448671521, + senderNick: '', msgSeq: 999, msgId: 2, + elements: [{ type: 'reply', replySeq: 456 }, { type: 'text', text: '同意' }], + } as any; + + await backfillReplyTarget(ref, event); + + expect(resolveUserUid).toHaveBeenCalledWith(448671521); + expect(getC2cMessageBySeq).toHaveBeenCalledWith('u_friend', 456, SELF); + const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_MESSAGE_EVENT); + expect(store.storeEvent).toHaveBeenCalledWith( + targetId, false, 448671521, 456, PRIVATE_MESSAGE_EVENT, + expect.objectContaining({ message_id: targetId, message_type: 'private' }), + ); + }); + + it('c2c: a bot self-sent quoted message is keyed under the peer (not self)', async () => { + // The fetched message was sent by us (senderUin = self) — it converts with + // user_id=self, but must still be findable under hash(seq, peer, private), + // which is what the incoming reply resolves to. + const store = fakeStore(false); + const getC2cMessageBySeq = vi.fn(async () => fetchedFriendMessage(456, SELF)); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getC2cMessageBySeq } }, resolveUserUid: vi.fn(async () => 'u_friend') }, + } as any; + const event = { + kind: 'friend_message', time: 1, selfUin: SELF, senderUin: 448671521, + senderNick: '', msgSeq: 999, msgId: 2, + elements: [{ type: 'reply', replySeq: 456 }], + } as any; + + await backfillReplyTarget(ref, event); + + const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_MESSAGE_EVENT); + expect(store.storeEvent).toHaveBeenCalledWith( + targetId, false, 448671521, 456, PRIVATE_MESSAGE_EVENT, expect.objectContaining({ message_id: targetId }), + ); + }); + + it('no-op when the quoted message is already stored (no fetch)', async () => { + const store = fakeStore(true); // findEvent hits + const getGroupMessageBySeq = vi.fn(); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() }, + } as any; + + await backfillReplyTarget(ref, groupEvent(123)); + + expect(getGroupMessageBySeq).not.toHaveBeenCalled(); + expect(store.storeEvent).not.toHaveBeenCalled(); + }); + + it('no-op when the message has no reply element', async () => { + const store = fakeStore(false); + const getGroupMessageBySeq = vi.fn(); + const ref = { + selfId: SELF, converterCtx, messageStore: store, + bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() }, + } as any; + + await backfillReplyTarget(ref, groupEvent(null)); + + expect(getGroupMessageBySeq).not.toHaveBeenCalled(); + expect(store.storeEvent).not.toHaveBeenCalled(); + }); + + it('does not store when the server has nothing at that sequence', 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; + + await backfillReplyTarget(ref, groupEvent(123)); + + expect(getGroupMessageBySeq).toHaveBeenCalledOnce(); + expect(store.storeEvent).not.toHaveBeenCalled(); + }); +});