fix(onebot): resolve private reply targets consistently

Refs #618
This commit is contained in:
DrSmoothl committed 2026-11-02 08:47:26 +08:00
1 parent a1688a33b0
commit 4a10f38743
17 files changed
+1221 -608

No files matched your search

@@ -15,6 +15,7 @@ import type {
} from './index';
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
import { resolveReplyId } from './utils';
import type { PrivateQuoteSource } from '../private-quote';
// ─────────────────────────────────────────────────────────────────────────
// 消息元素 codec 表(onebot 侧)—— 把「同一种元素」的两个 onebot 方向并到一处:
@@ -42,6 +43,7 @@ export interface ToSegmentContext {
mediaUrlResolver?: MediaUrlResolver | null;
messageIdResolver?: MessageIdResolver | null;
mediaSegmentSink?: MediaSegmentSink | null;
currentMessage?: PrivateQuoteSource;
}
// The image segment is the one intentional triangular mapping: an image with
@@ -295,17 +297,20 @@ export const ELEMENT_CODECS = {
const eventName = ctx.isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(sentBySelf, false);
const id = await resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
ctx.messageIdResolver,
eventName,
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
element.replyElements,
);
const id =
element.replyMessageId ??
(await resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
ctx.messageIdResolver,
eventName,
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
element.replyElements,
ctx.currentMessage,
));
return { type: 'reply', data: { id: String(id) } };
},
async fromSegment(data, options) {
@@ -1,5 +1,6 @@
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import type { PrivateQuoteSource } from '../private-quote';
import { convertFriendMessage, convertGroupMessage, convertTempMessage } from './to-message';
import {
convertBotOffline,
@@ -40,6 +41,7 @@ export type MessageIdResolver = (
eventName: string,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
) => number | Promise<number>;
export type MediaSegmentSink = (
@@ -53,7 +53,16 @@ async function convertPrivateMessage(
messageIdSequence,
eventName,
);
const segments = await toSegments(ctx, event.elements, false, sessionId);
const segments = await elementsToOneBotSegments(ctx, event.elements, false, sessionId, {
currentMessage: {
id: messageId,
sequence: hasCanonicalNtSequence ? ntSequence : 0,
clientSequence:
event.kind === 'friend_message' ? (event.clientSeq ?? event.msgSeq) : event.msgSeq,
timestamp: event.time,
sentBySelf: isSelf,
},
});
const sender: JsonObject = {
user_id: event.senderUin,
nickname: event.senderNick,
@@ -5,6 +5,7 @@ import { getElementCodec } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
import type { ConverterContext } from './index';
import { attachMessageMedia } from '../message-media';
import type { PrivateQuoteSource } from '../private-quote';
const log = createLogger('OneBot');
@@ -13,9 +14,15 @@ export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
options: { includeReplyContent?: boolean } = {},
options: { includeReplyContent?: boolean; currentMessage?: PrivateQuoteSource } = {},
): Promise<JsonArray> {
const segmentCtx: ToSegmentContext = { ...ctx, isGroup, sessionId, mediaSegmentSink: null };
const segmentCtx: ToSegmentContext = {
...ctx,
isGroup,
sessionId,
mediaSegmentSink: null,
currentMessage: options.currentMessage,
};
const result: JsonArray = [];
for (const element of elements) {
@@ -34,6 +41,21 @@ export async function elementsToOneBotSegments(
continue;
}
if (
element.type === 'reply' &&
(segment.data as JsonObject).id === '0' &&
!options.includeReplyContent
) {
log.warn(
'quote target unresolved: group=%s session=%d seq=%d time=%s; omitting reply id',
isGroup,
sessionId,
element.replySeq,
element.replyTime,
);
continue;
}
// Forward quotes often refer to messages outside the local account's
// history. Carry their inline content so consumers can resend the node.
if (
+6 -1
View File
@@ -1,6 +1,7 @@
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { MessageIdResolver } from './index';
import type { MessageElement } from '@snowluma/protocol/events';
import type { PrivateQuoteSource } from '../private-quote';
export function isSameActor(
leftUin: number,
@@ -43,6 +44,7 @@ export async function resolveReplyId(
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
): Promise<number> {
const seq = Math.trunc(sequence);
@@ -58,11 +60,14 @@ export async function resolveReplyId(
eventName,
timestamp,
replyElements,
excludedMessage,
);
if (Number.isInteger(resolved) && resolved !== 0) {
if (Number.isInteger(resolved)) {
return resolved;
}
throw new Error('reply resolver returned an invalid message id');
}
return seq;
+29 -27
View File
@@ -176,10 +176,38 @@ async function convertAndDispatch(
state: EventTraceState,
messageIdOverride?: number,
): Promise<void> {
let preparedEvent = event;
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
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 {
preparedEvent = await backfillReplyTarget(ctx, event);
} catch (error) {
// Best-effort — dispatch the live event regardless, but keep the failure
// attributable so a repeated store/server miss is diagnosable.
log.warn(
'reply backfill failed kind=%s: %s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
log.trace(() => [
'event_branch kind=%s reason=reply_backfill_failed error=%s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
}
let converted;
try {
converted = await convertEvent(ctx.converterCtx, event);
converted = await convertEvent(ctx.converterCtx, preparedEvent);
} catch (error) {
traceEventTerminal(log, event.kind, state, 'failed', 'converter_threw', error);
throw error;
@@ -200,32 +228,6 @@ async function convertAndDispatch(
renderParamsVerbose(converted),
]);
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
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 (error) {
// Best-effort — dispatch the live event regardless, but keep the failure
// attributable so a repeated store/server miss is diagnosable.
log.warn(
'reply backfill failed kind=%s: %s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
log.trace(() => [
'event_branch kind=%s reason=reply_backfill_failed error=%s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
}
// Backfill can await several network/media operations. Re-check immediately
// before dispatch so a recall that arrived during that gap wins the race.
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
+3 -46
View File
@@ -18,15 +18,9 @@ import type { GlobalSettings } from './global-config';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
} from './message-id';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, privateMessageEventName } from './message-id';
import { MessageStore } from './message-store';
import { createMessageIdResolver } from './message-id-resolver';
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
import {
buildStatusText,
@@ -159,44 +153,7 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: async (
isGroup,
sessionId,
sequence,
eventName,
timestamp,
replyElements,
) => {
const resolvedEventName =
eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (
!isGroup &&
timestamp !== undefined &&
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
) {
const storedId = await this.messageStore.resolvePrivateReplyMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
replyElements,
);
if (storedId !== null) {
return storedId;
}
}
return hashMessageIdInt32(
sequence,
sessionId,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
? PRIVATE_NT_MESSAGE_EVENT
: resolvedEventName,
);
},
messageIdResolver: createMessageIdResolver(this.messageStore),
mediaSegmentSink: async (mediaType, element, data, isGroup, sessionId) =>
await mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
@@ -0,0 +1,54 @@
import type { MessageIdResolver } from './event-converter';
import type { MessageStore } from './message-store';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
} from './message-id';
export function createMessageIdResolver(
store: Pick<MessageStore, 'resolvePrivateReplyMessageId'>,
): MessageIdResolver {
return async (
isGroup,
sessionId,
sequence,
eventName,
timestamp,
replyElements,
excludedMessage,
) => {
const resolvedEventName =
eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (
!isGroup &&
timestamp !== undefined &&
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
) {
const storedId = await store.resolvePrivateReplyMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
replyElements,
excludedMessage,
);
// Quote sequences are not canonical message-id inputs. A miss must
// remain unresolved so the live pipeline can fetch and verify history.
return storedId ?? 0;
}
return hashMessageIdInt32(
sequence,
sessionId,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
? PRIVATE_NT_MESSAGE_EVENT
: resolvedEventName,
);
};
}
+88 -276
View File
@@ -1,8 +1,14 @@
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
import { SqliteDatabase, type SqliteRow, type SqliteStatement } from '@snowluma/sqlite';
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, MessageMeta } from './types';
import type { MessageElement } from '@snowluma/protocol/events';
import { cqUnescape } from './helper/cq';
import {
cachedQuotePreview,
isUsableQuoteTime,
PRIVATE_QUOTE_MAX_DRIFT_SECONDS,
selectPrivateQuote,
type PrivateQuoteSource,
} from './private-quote';
import { openSqliteDb } from './sqlite-open';
import {
mergeMessageMedia,
@@ -49,9 +55,8 @@ export class MessageStore {
private stmtFindLatestPersistedAuthoritativeSequence!: SqliteStatement;
private stmtListIncomingC2CSessions!: SqliteStatement;
private stmtFindPrivateRecall!: SqliteStatement;
private stmtFindPrivateMessageAtTime!: SqliteStatement;
private stmtFindPrivateMessageBySequence!: SqliteStatement;
private stmtFindPrivateOutgoingNearTime!: SqliteStatement;
private stmtFindPrivateReplyBySequence!: SqliteStatement;
private stmtFindPrivateReplyByTime!: SqliteStatement;
private stmtFindPrivateRecallTombstone!: SqliteStatement;
private stmtUpsertPrivateRecallTombstone!: SqliteStatement;
private stmtDeleteMessage!: SqliteStatement;
@@ -205,27 +210,22 @@ export class MessageStore {
LIMIT 1`,
);
this.stmtFindPrivateMessageAtTime = this.db.prepare(
`SELECT message_hash, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?`,
this.stmtFindPrivateReplyBySequence = this.db.prepare(
`SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND client_sequence = ? AND timestamp BETWEEN ? AND ?
UNION
SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND sequence = ? AND sequence_authoritative = 1 AND timestamp BETWEEN ? AND ?`,
);
this.stmtFindPrivateMessageBySequence = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND sequence = ?
AND private_direction = ? AND sequence_authoritative = 1
LIMIT 1`,
);
this.stmtFindPrivateOutgoingNearTime = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND timestamp BETWEEN ? AND ?
ORDER BY ABS(timestamp - ?) ASC, sequence DESC
LIMIT 2`,
this.stmtFindPrivateReplyByTime = this.db.prepare(
`SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND timestamp BETWEEN ? AND ?`,
);
this.stmtFindPrivateRecallTombstone = this.db.prepare(
@@ -618,217 +618,66 @@ export class MessageStore {
});
}
/**
* Resolve a private quote to a stored OneBot id. Prefer the quoted
* sender-local sequence, then the conversation sequence. For a
* self-sent target, also match the send receipt by time because QQ's
* quote sequence is often neither of those stored values, and the
* quote time can drift a few seconds from the send receipt.
*/
/** Resolve quotes independently of recall lookup: a reused sequence is not an identity. */
async resolvePrivateReplyMessageId(
sessionId: number,
replySequence: number,
sentBySelf: boolean,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
const byClientSequence = await this.findPrivateMessageId(
sessionId,
replySequence,
sentBySelf,
timestamp,
);
if (byClientSequence !== null) {
return byClientSequence;
}
const byConversationSequence = await this.findPrivateMessageIdBySequence(
sessionId,
replySequence,
sentBySelf,
);
if (byConversationSequence !== null) {
return byConversationSequence;
}
}
if (!sentBySelf) {
return null;
}
const byExactTime = await this.findPrivateMessageIdAtTime(
sessionId,
true,
const hasTime = isUsableQuoteTime(timestamp);
const lower = hasTime ? timestamp - PRIVATE_QUOTE_MAX_DRIFT_SECONDS : 0;
const upper = hasTime
? timestamp + PRIVATE_QUOTE_MAX_DRIFT_SECONDS
: Number.MAX_SAFE_INTEGER;
const key = {
sequence: replySequence,
sentBySelf,
timestamp,
replyElements,
);
if (byExactTime !== null) {
return byExactTime;
}
const byNearbyTime = await this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
if (byNearbyTime !== null) {
return byNearbyTime;
}
return null;
});
}
async findPrivateMessageIdAtTime(
sessionId: number,
sentBySelf: boolean,
timestamp?: number,
replyElements?: readonly MessageElement[],
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!isUsablePrivateQuoteTime(timestamp)) {
return null;
}
const rows = (await this.stmtFindPrivateMessageAtTime.all(
sessionId,
sentBySelf ? 1 : 0,
timestamp,
)) as { message_hash: number; data: string | null }[];
if (rows.length === 0) {
return null;
}
let matches = rows;
if (rows.length > 1) {
const text =
replyElements?.length && replyElements.every((e) => e.type === 'text')
? replyElements.map((e) => e.text ?? '').join('')
: null;
const candidates = text
? rows
.map((row) => ({ row, preview: cachedQuoteText(row.data) }))
.filter(
({ preview }) => preview === null || preview.text.startsWith(text),
)
elements: replyElements,
exclude: excludedMessage,
};
const rows =
Number.isSafeInteger(replySequence) && replySequence > 0
? ((await this.stmtFindPrivateReplyBySequence.all(
sessionId,
sentBySelf ? 1 : 0,
replySequence,
lower,
upper,
sessionId,
sentBySelf ? 1 : 0,
replySequence,
lower,
upper,
)) as PrivateReplyRow[])
: [];
matches =
candidates.length === 1 &&
candidates[0]!.preview?.plain &&
candidates[0]!.preview.text === text
? [candidates[0]!.row]
: [];
let selected = selectPrivateQuote(rows.map(privateReplyCandidate), key);
if (matches.length !== 1) {
log.debug(
'private quote time is ambiguous: peer=%d time=%d candidates=%d contentMatches=%d',
sessionId,
timestamp,
rows.length,
matches.length,
);
return null;
}
}
const row = matches[0]!;
if (!isValidMessageId(row.message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(row.message_hash)}`,
);
}
return row.message_hash;
});
}
async findPrivateMessageIdBySequence(
sessionId: number,
sequence: number,
sentBySelf: boolean,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
return null;
}
const row = (await this.stmtFindPrivateMessageBySequence.get(
sessionId,
sequence,
sentBySelf ? 1 : 0,
)) as { message_hash: number } | undefined;
if (!row) {
return null;
}
if (!isValidMessageId(row.message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(row.message_hash)}`,
);
}
return row.message_hash;
});
}
async findUniquePrivateOutgoingNearTime(
sessionId: number,
timestamp?: number,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!isUsablePrivateQuoteTime(timestamp)) {
return null;
}
for (const windowSeconds of PRIVATE_REPLY_TIME_WINDOWS_SECONDS) {
const rows = (await this.stmtFindPrivateOutgoingNearTime.all(
if (!selected.candidate && selected.reason !== 'ambiguous' && sentBySelf && hasTime) {
const nearby = (await this.stmtFindPrivateReplyByTime.all(
sessionId,
1,
timestamp - windowSeconds,
timestamp + windowSeconds,
timestamp,
)) as Array<{ message_hash: number }>;
if (rows.length !== 1) {
continue;
}
if (!isValidMessageId(rows[0].message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(rows[0].message_hash)}`,
);
}
return rows[0].message_hash;
lower,
upper,
)) as PrivateReplyRow[];
selected = selectPrivateQuote(nearby.map(privateReplyCandidate), key);
}
return null;
log.trace(
'private quote lookup: peer=%d seq=%d outgoing=%s time=%s result=%s messageId=%s',
sessionId,
replySequence,
sentBySelf,
timestamp,
selected.reason,
selected.candidate?.id ?? 'unknown',
);
return selected.candidate?.id ?? null;
});
}
@@ -1148,64 +997,27 @@ function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
return -1;
}
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
/** Unknown, truncated, and media previews remain possible competing matches. */
function cachedQuoteText(data: string | null): { text: string; plain: boolean } | null {
if (!data) {
return null;
}
const event = JSON.parse(data) as JsonObject;
if (typeof event.message === 'string') {
return event.message.includes('[CQ:')
? null
: { text: cqUnescape(event.message), plain: true };
}
if (!Array.isArray(event.message) || event.message.length === 0) {
return null;
}
const segments = event.message as JsonObject[];
const labels: Record<string, string> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
};
const parts: string[] = [];
let plain = true;
for (const segment of segments) {
const body = segment?.data as JsonObject | undefined;
if (segment?.type === 'text' && typeof body?.text === 'string') {
parts.push(body.text);
} else if (typeof segment?.type === 'string' && labels[segment.type]) {
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
plain = false;
} else {
return null;
}
}
return { text: parts.join(''), plain };
interface PrivateReplyRow extends SqliteRow {
message_hash: number;
sequence: number;
sequence_authoritative: number;
client_sequence: number;
timestamp: number;
data: string | null;
}
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
return (
timestamp !== undefined &&
Number.isSafeInteger(timestamp) &&
timestamp > 0 &&
timestamp < Number.MAX_SAFE_INTEGER
);
function privateReplyCandidate(row: PrivateReplyRow) {
if (!isValidMessageId(row.message_hash)) {
throw new Error(`private quote matched invalid message id ${String(row.message_hash)}`);
}
return {
id: row.message_hash,
sequence: row.sequence_authoritative === 1 ? row.sequence : 0,
clientSequence: row.client_sequence,
timestamp: row.timestamp,
preview: cachedQuotePreview(row.data),
};
}
function validatePrivateRecallKey(
+259 -181
View File
@@ -15,6 +15,7 @@ import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/v
import { guessFileNameFromUrl } from '@snowluma/protocol/highway/utils';
import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { applyMessageIdResolver } from '../event-converter/utils';
import { segmentsToRawMessage } from '../helper/cq';
import { persistHistoryEvent, toHistoryInt } from '../history-persistence';
import type { OneBotInstanceContext } from '../instance-context';
@@ -28,6 +29,12 @@ import {
import type { MessageStore } from '../message-store';
import { sameSelfSentMessage } from '../self-sent-event';
import { replyPreviewElements } from '../reply-preview';
import {
isUsableQuoteTime,
messageQuotePreview,
PRIVATE_QUOTE_MAX_DRIFT_SECONDS,
selectPrivateQuote,
} from '../private-quote';
import {
hasAuthoritativeSequence,
type JsonArray,
@@ -424,225 +431,296 @@ export async function getFriendHistory(
return out;
}
/**
* 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 the quoted message from the server —
* group via `SsoGetGroupMsg`, C2C via timestamp roaming, 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. Private replies carry
* the quoted sender's local sequence, so they are matched through a timestamp
* roam page rather than incorrectly used as an NT-sequence range anchor.
*
* 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.peerUin ?? event.senderUin;
} else {
return;
/** Resolve and prepare quotes before conversion, without changing the protocol event. */
export async function backfillReplyTarget(
ref: HistoryRef,
event: QQEventVariant,
): Promise<QQEventVariant> {
if (event.kind !== 'group_message' && event.kind !== 'friend_message') {
return event;
}
const session =
event.kind === 'group_message' ? event.groupId : (event.peerUin ?? event.senderUin);
if (!Number.isInteger(session) || session <= 0) {
return;
return event;
}
const reply = event.elements.find(
(e: MessageElement) =>
e.type === 'reply' && Number.isInteger(e.replySeq) && (e.replySeq ?? 0) > 0,
);
const replySeq = reply?.replySeq ?? 0;
const elements: MessageElement[] = [];
let changed = false;
if (replySeq <= 0) {
return;
for (const element of event.elements) {
if (
element.type !== 'reply' ||
!Number.isSafeInteger(element.replySeq) ||
element.replySeq <= 0
) {
elements.push(element);
continue;
}
const messageId =
event.kind === 'group_message'
? await backfillGroupReply(ref, session, element)
: await backfillPrivateReply(ref, session, event, element);
elements.push({ ...element, replyMessageId: messageId });
changed = true;
}
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(quotedSender === ref.selfId, false);
const resolvedId = await ref.converterCtx.messageIdResolver?.(
isGroup,
return changed ? { ...event, elements } : event;
}
async function backfillPrivateReply(
ref: HistoryRef,
session: number,
event: FriendMessage,
reply: MessageElementOf<'reply'>,
): Promise<number> {
const sender = reply.replySenderUin ?? session;
const sentBySelf = sender === ref.selfId;
const hasNtSequence = (event.ntMsgSeq ?? 0) > 0 && event.sequenceAuthoritative !== false;
const currentId = await applyMessageIdResolver(
ref.converterCtx.messageIdResolver,
false,
session,
replySeq,
eventName,
reply?.replyTime && reply.replyTime > 0 ? reply.replyTime : Number.MAX_SAFE_INTEGER,
hasNtSequence ? event.ntMsgSeq! : event.msgSeq,
privateMessageEventName(event.senderUin === ref.selfId, hasNtSequence),
);
const exclude = {
id: currentId,
sequence: hasNtSequence ? event.ntMsgSeq! : 0,
clientSequence: event.clientSeq ?? event.msgSeq,
timestamp: event.time,
sentBySelf: event.senderUin === ref.selfId,
};
const storedId = await ref.messageStore.resolvePrivateReplyMessageId(
session,
reply.replySeq,
sentBySelf,
reply.replyTime,
reply.replyElements,
exclude,
);
if (storedId !== null && (await ref.messageStore.findEvent(storedId))) {
return storedId;
}
let history: FriendMessage[] = [];
try {
const uid = await ref.bridge.resolveUserUid(session);
if (uid) {
const time = isUsableQuoteTime(reply.replyTime) ? reply.replyTime : event.time;
history = await ref.bridge.apis.message.getC2cLatestHistory(
uid,
20,
ref.selfId,
Math.min(0xffff_ffff, Math.max(1, time + 1)),
);
}
} catch (error) {
log.warn(
'private quote history failed: peer=%d seq=%d error=%s',
session,
reply.replySeq,
error instanceof Error ? error.message : String(error),
);
}
const selection = selectPrivateQuote(
history
.filter(
(candidate) =>
candidate.senderUin === sender &&
candidate.selfUin === ref.selfId &&
(candidate.peerUin ??
(candidate.senderUin === ref.selfId ? session : candidate.senderUin)) ===
session,
)
.map((source) => ({
source: { ...source, peerUin: session },
sequence: source.sequenceAuthoritative !== false ? (source.ntMsgSeq ?? 0) : 0,
clientSequence: source.clientSeq ?? source.msgSeq,
timestamp: source.time,
preview: messageQuotePreview(source.elements),
})),
{
sequence: reply.replySeq,
sentBySelf,
timestamp: reply.replyTime,
elements: reply.replyElements,
exclude,
},
);
const fetched = selection.candidate?.source;
const knownMeta = storedId !== null ? await ref.messageStore.findMeta(storedId) : null;
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (!json) {
throw new Error('private quote history could not be converted');
}
// Preserve an existing legacy id only when the fetched message confirms
// the same stored identity, rather than assigning a quote-sequence hash.
if (
storedId !== null &&
knownMeta &&
Math.abs(knownMeta.timestamp - fetched.time) <= PRIVATE_QUOTE_MAX_DRIFT_SECONDS &&
(knownMeta.sequenceAuthoritative !== false &&
knownMeta.sequence > 0 &&
fetched.sequenceAuthoritative !== false &&
(fetched.ntMsgSeq ?? 0) > 0
? knownMeta.sequence === fetched.ntMsgSeq
: knownMeta.clientSequence > 0 &&
knownMeta.clientSequence === (fetched.clientSeq ?? fetched.msgSeq))
) {
json.message_id = storedId;
}
const persisted = await persistHistoryEvent(ref.messageStore, json, session, fetched);
const id = persisted ? toHistoryInt(json.message_id) : 0;
log.trace(
'private quote history resolved: peer=%d seq=%d result=%s messageId=%d',
session,
reply.replySeq,
persisted ? selection.reason : 'recalled',
id,
);
return id;
}
// Embedded text may fill the body of a verified existing identity. It cannot
// create a new private-message identity or overwrite an unrelated record.
if (storedId !== null && knownMeta && reply.replyElements?.length) {
const segments = await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements.filter((element) => element.type !== 'reply'),
false,
session,
);
const json = buildBackfillEvent(
storedId,
knownMeta.clientSequence || knownMeta.sequence,
sender,
knownMeta.timestamp,
segments,
ref.selfId,
false,
session,
);
const persisted = await ref.messageStore.storeHistoryEvent(
storedId,
false,
session,
knownMeta.sequence,
knownMeta.eventName,
json,
{ sequenceAuthoritative: knownMeta.sequenceAuthoritative, meta: knownMeta },
);
return persisted ? storedId : 0;
}
log.trace(
'private quote unresolved: peer=%d seq=%d time=%s result=%s knownId=%s',
session,
reply.replySeq,
reply.replyTime,
selection.reason,
storedId ?? 'unknown',
);
return storedId ?? 0;
}
async function backfillGroupReply(
ref: HistoryRef,
session: number,
reply: MessageElementOf<'reply'>,
): Promise<number> {
const resolvedId = await ref.converterCtx.messageIdResolver?.(
true,
session,
reply.replySeq,
GROUP_MESSAGE_EVENT,
reply.replyTime && reply.replyTime > 0 ? reply.replyTime : Number.MAX_SAFE_INTEGER,
reply.replyElements,
);
const targetId =
Number.isInteger(resolvedId) && resolvedId !== 0
? (resolvedId as number)
: hashMessageIdInt32(replySeq, session, eventName);
: hashMessageIdInt32(reply.replySeq, session, GROUP_MESSAGE_EVENT);
if (await ref.messageStore.findEvent(targetId)) {
return;
} // Tier 0: already have the full event
return targetId;
}
let fetched: GroupMessage | null = null;
// Tier 1: fetch the quoted message from the server, keyed under the exact id
// the reply resolves to. Groups can query `replySeq` directly. C2C replies
// carry a sender-local client sequence, while SsoGetC2cMsg ranges use the
// conversation-wide NT sequence; use the quote time as a roam cursor and
// match both direction and client sequence instead.
try {
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) {
const quoteTime =
reply?.replyTime && reply.replyTime > 0 ? reply.replyTime : event.time;
const beforeTime = Math.min(0xffff_ffff, Math.max(1, quoteTime + 1));
const candidates = await ref.bridge.apis.message.getC2cLatestHistory(
friendUid,
20,
ref.selfId,
beforeTime,
);
const quotedSentBySelf = quotedSender === ref.selfId;
fetched =
[...candidates]
.reverse()
.find(
(candidate) =>
(candidate.clientSeq ?? candidate.msgSeq) === replySeq &&
(candidate.senderUin === ref.selfId) === quotedSentBySelf &&
(!reply?.replyTime || candidate.time <= reply.replyTime),
) ?? null;
}
}
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (json) {
json.message_id = targetId;
if (fetched.kind === 'group_message') {
await ref.messageStore.storeEvent(
targetId,
true,
session,
replySeq,
eventName,
json,
);
} else {
const serverSequence = fetched.ntMsgSeq ?? 0;
const sequenceAuthoritative =
fetched.sequenceAuthoritative !== false && serverSequence > 0;
await ref.messageStore.storeMeta(targetId, {
isGroup: false,
targetId: session,
sequence: serverSequence,
sequenceAuthoritative,
eventName,
clientSequence: fetched.clientSeq ?? fetched.msgSeq,
privateDirection:
fetched.senderUin === ref.selfId ? 'outgoing' : 'incoming',
random: fetched.msgId,
timestamp: fetched.time,
});
await ref.messageStore.storeEvent(
targetId,
false,
session,
serverSequence,
eventName,
json,
{ sequenceAuthoritative },
);
}
return;
}
}
} catch (err) {
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(
session,
reply.replySeq,
ref.selfId,
);
} catch (error) {
log.warn(
'reply-target backfill tier-1 failed (%s)',
err instanceof Error ? err.message : String(err),
error instanceof Error ? error.message : String(error),
);
}
// 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.
if (reply?.replyElements?.length) {
try {
const segments = (await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements,
isGroup,
session,
)) as JsonArray;
const fallback = buildBackfillEvent(
targetId,
replySeq,
quotedSender,
reply.replyTime ?? 0,
segments,
ref.selfId,
isGroup,
session,
);
// Inline quote metadata proves what was displayed, but not that replySeq
// still names a server-backed roam message. Keep it queryable via
// get_msg without letting it become a history/recall/reply anchor.
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (json) {
json.message_id = targetId;
await ref.messageStore.storeEvent(
targetId,
isGroup,
true,
session,
replySeq,
eventName,
fallback,
{ sequenceAuthoritative: false },
);
return;
} catch (err) {
log.warn(
'reply-target backfill tier-2 failed (%s)',
err instanceof Error ? err.message : String(err),
reply.replySeq,
GROUP_MESSAGE_EVENT,
json,
);
return targetId;
}
}
// 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(
let segments: JsonArray = [{ type: 'text', data: { text: '[引用消息]' } }];
if (reply.replyElements?.length) {
segments = await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements,
true,
session,
);
}
const fallback = buildBackfillEvent(
targetId,
replySeq,
quotedSender,
reply?.replyTime ?? 0,
[{ type: 'text', data: { text: '[引用消息]' } }],
reply.replySeq,
reply.replySenderUin ?? 0,
reply.replyTime ?? 0,
segments,
ref.selfId,
isGroup,
true,
session,
);
await ref.messageStore.storeEvent(
targetId,
isGroup,
true,
session,
replySeq,
eventName,
placeholder,
reply.replySeq,
GROUP_MESSAGE_EVENT,
fallback,
{ sequenceAuthoritative: false },
);
return targetId;
}
// Build a stored-message event for a backfilled reply target (Tier 2/3).
+194
View File
@@ -0,0 +1,194 @@
import type { MessageElement } from '@snowluma/protocol/events';
import type { JsonObject } from './types';
import { cqUnescape } from './helper/cq';
// Send receipts and quoted timestamps can differ; never search outside the
// existing bounded drift window when resolving a quoted message.
export const PRIVATE_QUOTE_MAX_DRIFT_SECONDS = 30;
const TIME_WINDOWS = [0, 5, PRIVATE_QUOTE_MAX_DRIFT_SECONDS] as const;
interface QuotePreview {
text: string;
plain: boolean;
}
export interface PrivateQuoteCandidate {
id?: number;
sequence: number;
clientSequence: number;
timestamp: number;
preview: QuotePreview | null;
}
/** Identity of the containing message, which can never be its own quote target. */
export interface PrivateQuoteSource {
id: number;
sequence: number;
clientSequence: number;
timestamp: number;
sentBySelf: boolean;
}
export interface PrivateQuoteKey {
sequence: number;
sentBySelf: boolean;
timestamp?: number;
elements?: readonly MessageElement[];
exclude?: PrivateQuoteSource;
}
export function isUsableQuoteTime(timestamp: number | undefined): timestamp is number {
return (
timestamp !== undefined &&
Number.isSafeInteger(timestamp) &&
timestamp > 0 &&
timestamp < Number.MAX_SAFE_INTEGER
);
}
/** Sequence namespaces may overlap. Only a unique, consistent candidate wins. */
export function selectPrivateQuote<T extends PrivateQuoteCandidate>(
candidates: readonly T[],
quote: PrivateQuoteKey,
): { candidate: T | null; reason: 'sequence' | 'time' | 'ambiguous' | 'missing' } {
const time = isUsableQuoteTime(quote.timestamp) ? quote.timestamp : null;
const text =
quote.elements?.length && quote.elements.every((element) => element.type === 'text')
? quote.elements.map((element) => element.text ?? '').join('')
: '';
const nearby = candidates.filter((candidate) => {
const source = quote.exclude;
if (
source &&
(candidate.id === source.id ||
(source.sentBySelf === quote.sentBySelf &&
((source.sequence > 0 && candidate.sequence === source.sequence) ||
(source.clientSequence > 0 &&
candidate.clientSequence === source.clientSequence &&
candidate.timestamp === source.timestamp))))
) {
return false;
}
return (
time === null || Math.abs(candidate.timestamp - time) <= PRIVATE_QUOTE_MAX_DRIFT_SECONDS
);
});
// QQ can truncate the quote. Unknown and prefix-only previews remain
// competing candidates; only contradictory known content is excluded.
const compatible = nearby.filter(
(candidate) => !text || !candidate.preview || candidate.preview.text.startsWith(text),
);
const bySequence = compatible.filter(
(candidate) =>
quote.sequence > 0 &&
(candidate.clientSequence === quote.sequence || candidate.sequence === quote.sequence),
);
if (bySequence.length > 0) {
return {
candidate: bySequence.length === 1 ? bySequence[0]! : null,
reason: bySequence.length === 1 ? 'sequence' : 'ambiguous',
};
}
if (quote.sentBySelf && time !== null) {
for (const window of TIME_WINDOWS) {
const matches = compatible.filter(
(candidate) => Math.abs(candidate.timestamp - time) <= window,
);
if (matches.length > 0) {
const match = matches.length === 1 ? matches[0]! : null;
const windowCount = nearby.filter(
(candidate) => Math.abs(candidate.timestamp - time) <= window,
).length;
// A missing body cannot confirm quoted text. When content is the
// only discriminator, a truncated/media preview cannot prove it.
const confirmed =
match &&
(!text ||
(match.preview &&
(windowCount === 1 ||
(match.preview.plain && match.preview.text === text))));
return {
candidate: confirmed ? match : null,
reason: confirmed ? 'time' : 'ambiguous',
};
}
}
}
return { candidate: null, reason: 'missing' };
}
const labels: Readonly<Record<string, string>> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
};
export function cachedQuotePreview(data: string | null): QuotePreview | null {
if (!data) {
return null;
}
const event = JSON.parse(data) as JsonObject;
if (typeof event.message === 'string') {
return event.message.includes('[CQ:')
? null
: { text: cqUnescape(event.message), plain: true };
}
if (!Array.isArray(event.message) || event.message.length === 0) {
return null;
}
const parts: string[] = [];
let plain = true;
for (const segment of event.message as JsonObject[]) {
const body = segment?.data as JsonObject | undefined;
if (segment?.type === 'text' && typeof body?.text === 'string') {
parts.push(body.text);
} else if (typeof segment?.type === 'string' && Object.hasOwn(labels, segment.type)) {
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
plain = false;
} else {
return null;
}
}
return { text: parts.join(''), plain };
}
export function messageQuotePreview(elements: readonly MessageElement[]): QuotePreview | null {
const parts: string[] = [];
let plain = true;
for (const element of elements) {
if (element.type === 'text') {
parts.push(element.text ?? '');
} else if (Object.hasOwn(labels, element.type)) {
parts.push(
'summary' in element && typeof element.summary === 'string'
? element.summary
: labels[element.type]!,
);
plain = false;
} else {
return null;
}
}
return parts.length > 0 ? { text: parts.join(''), plain } : null;
}