feat(onebot): back-fill a quoted message from the server when not stored

When an incoming reply quotes a message SnowLuma's store doesn't have (e.g. one
from before it was running, or never observed), the receive pipeline now fetches
just that message from the server and persists it before dispatch — so a
consumer's get_msg on the quote resolves instead of returning "message not
found". Works for both group and private (c2c).

- core: MessageApi.getGroupMessageBySeq / getC2cMessageBySeq — fetch a single
  message over a 1-wide [seq,seq] range, through the shared history throttle
  gate (same rate-limit as the bulk history APIs — no flood / kick risk).
- onebot: backfillReplyTarget — on a group/friend reply whose target isn't in
  the store, fetch (group SsoGetGroupMsg / c2c SsoGetC2cMsg, uid resolved for
  c2c) and persist under the EXACT id the reply resolves to, so get_msg hits
  regardless of who sent the quoted message (a bot self-sent c2c message
  converts with user_id=self but is keyed under the peer session). Awaited
  before dispatch so the consumer sees it; best-effort — a back-fill failure
  never blocks delivery of the live message.
- tests: gating (already-stored / no-reply / nothing-on-server) + keying
  (group, c2c, c2c self-sent under peer session).

Only fires on a store miss, so the common path (no reply, or quote already
stored) stays zero-cost.
This commit is contained in:
DrSmoothl committed 2026-06-15 13:53:04 +08:00
1 parent cf8e62d2ac
commit 28633f3c62
4 files changed
+258 -1

No files matched your search

+8
View File
@@ -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)`]);
}
+56 -1
View File
@@ -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<void> {
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).