fix(onebot): correct private message history (#256)

Use the C2C roam cursor and canonical NT sequence for bidirectional history. Persist direction-aware recall tombstones so recalled messages cannot reappear.
This commit is contained in:
DrSmoothl committed 2026-07-20 22:25:13 +08:00
1 parent 88216ce644
commit 4aa2cd1693
37 files changed
+1853 -242

No files matched your search

+2 -2
View File
@@ -339,7 +339,7 @@ export const actions = [
defineAction({
name: 'get_friend_msg_history',
summary: '获取好友消息历史',
summary: '获取好友消息历史(无锚点时从服务器获取最新双向记录)',
readOnly: true,
returns: '{ messages }:好友消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。',
returnsSchema: {
@@ -353,7 +353,7 @@ export const actions = [
user_id: f.userId(),
// Signed int32 hash, frequently negative — see get_group_msg_history.
message_id: f.int().default(0).role('message_id'),
count: f.int({ min: 0 }).default(20),
count: f.int({ min: 0 }).default(20).describe('无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存'),
reverse_order: f.bool().default(true).describe('仅在 message_id 非 0 时生效;true 返回锚点及更旧消息,false 返回锚点及更新消息'),
},
run: async (p, ctx) => {
@@ -13,6 +13,7 @@ import type {
MessageIdResolver,
MediaSegmentSink,
} from './index';
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
import { resolveReplyId } from './utils';
// ─────────────────────────────────────────────────────────────────────────
@@ -36,6 +37,7 @@ const log = createLogger('MsgParser');
export interface ToSegmentContext {
isGroup: boolean;
sessionId: number;
selfId: number;
imageUrlResolver?: ImageUrlResolver | null;
mediaUrlResolver?: MediaUrlResolver | null;
messageIdResolver?: MessageIdResolver | null;
@@ -182,7 +184,22 @@ export const ELEMENT_CODECS = {
reply: {
async toSegment(element, ctx) {
const id = resolveReplyId(ctx.isGroup, ctx.sessionId, element.replySeq ?? 0, ctx.messageIdResolver);
const sentBySelf = !ctx.isGroup
&& ctx.selfId > 0
&& element.replySenderUin === ctx.selfId;
const eventName = ctx.isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(sentBySelf, false);
const id = resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
ctx.messageIdResolver,
eventName,
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
);
return { type: 'reply', data: { id: String(id) } };
},
async fromSegment(data, options) {
+9 -2
View File
@@ -33,7 +33,13 @@ import { elementsToJson } from './to-segment';
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
export type MessageIdResolver = (
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
timestamp?: number,
) => number;
export type MediaSegmentSink = (
mediaType: 'image' | 'record' | 'video',
@@ -120,9 +126,10 @@ export async function elementsToOneBotSegments(
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
selfId = 0,
) {
return elementsToJson(
elements, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, selfId,
);
}
@@ -1,6 +1,10 @@
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { segmentsToRawMessage } from '../helper/cq';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
privateMessageEventName,
} from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { elementsToJson } from './to-segment';
@@ -16,6 +20,7 @@ function toSegments(ctx: ConverterContext, elements: MessageElement[], isGroup:
return elementsToJson(
elements, isGroup, sessionId,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
ctx.selfId,
);
}
@@ -34,8 +39,18 @@ async function convertPrivateMessage(
const sessionId = event.kind === 'friend_message' && event.peerUin && event.peerUin > 0
? event.peerUin
: event.senderUin;
// ContentHead field 5 (`msgSeq`) is sender-local in C2C and can collide in
// both directions. Friend history/pushes expose field 11 (`ntMsgSeq`), which
// is conversation-wide and therefore the canonical OneBot id input.
const ntSequence = event.kind === 'friend_message' ? (event.ntMsgSeq ?? 0) : 0;
const hasCanonicalNtSequence = ntSequence > 0
&& event.sequenceAuthoritative !== false;
const messageIdSequence = hasCanonicalNtSequence ? ntSequence : event.msgSeq;
const eventName = event.kind === 'friend_message'
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
: PRIVATE_MESSAGE_EVENT;
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, sessionId, event.msgSeq, PRIVATE_MESSAGE_EVENT,
ctx.messageIdResolver, false, sessionId, messageIdSequence, eventName,
);
const segments = await toSegments(ctx, event.elements, false, sessionId);
const sender: JsonObject = {
@@ -1,5 +1,5 @@
import type { QQEventVariant } from '@snowluma/protocol/events';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { applyMessageIdResolver, isSameActor } from './utils';
@@ -80,7 +80,12 @@ export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): Jso
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
ctx.messageIdResolver,
false,
event.userUin,
event.msgSeq,
privateMessageEventName(event.recalledBySelf === true, false),
event.time,
);
return notice(ctx, event, {
notice_type: 'friend_recall',
@@ -19,6 +19,7 @@ export async function elementsToJson(
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
selfId = 0,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
@@ -27,7 +28,7 @@ export async function elementsToJson(
try {
result.push(await elementToSegment(
element, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink, selfId,
));
} catch (err) {
log.warn('segment convert skipped type=%s (%s)', element.type,
@@ -45,6 +46,7 @@ async function elementToSegment(
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
selfId = 0,
): Promise<JsonObject> {
// S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。
const codec = getElementCodec(element.type);
@@ -56,6 +58,7 @@ async function elementToSegment(
mediaUrlResolver,
messageIdResolver,
mediaSegmentSink,
selfId,
});
}
log.warn('segment convert fallback type=%s reason=no receive-side codec', element.type);
+5 -3
View File
@@ -22,9 +22,10 @@ export function applyMessageIdResolver(
sessionId: number,
sequence: number,
eventName: string,
timestamp?: number,
): number {
if (resolver) {
const resolved = resolver(isGroup, sessionId, sequence, eventName);
const resolved = resolver(isGroup, sessionId, sequence, eventName, timestamp);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
const seq = Math.trunc(sequence);
@@ -36,13 +37,14 @@ export function resolveReplyId(
sessionId: number,
sequence: number,
resolver?: MessageIdResolver | null,
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
timestamp?: number,
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const resolved = resolver(isGroup, sessionId, seq, eventName);
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
+119 -14
View File
@@ -3,9 +3,15 @@ import { renderParamsVerbose } from '@snowluma/common/log-summary';
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 {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
} from './message-id';
import { backfillReplyTarget } from './modules/message-actions';
import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
import type { MessageMeta } from './types';
const moduleLog = createLogger('Event');
@@ -61,13 +67,33 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline
);
disposers.push(
ctx.bridge.events.on('friend_message', (event) => track(event.kind, async () => {
cachePrivateMessageMeta(ctx, event.peerUin ?? event.senderUin, event.msgSeq, event.time, event.msgId);
cachePrivateMessageMeta(
ctx,
event.peerUin ?? event.senderUin,
event.msgSeq,
event.ntMsgSeq ?? 0,
event.clientSeq ?? event.msgSeq,
event.time,
event.msgId,
event.sequenceAuthoritative !== false,
event.senderUin === ctx.selfId ? 'outgoing' : 'incoming',
);
await convertAndDispatch(ctx, log, event);
})),
);
disposers.push(
ctx.bridge.events.on('temp_message', (event) => track(event.kind, async () => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
cachePrivateMessageMeta(
ctx,
event.senderUin,
event.msgSeq,
event.ntMsgSeq ?? 0,
event.clientSeq ?? 0,
event.time,
0,
event.sequenceAuthoritative !== false,
undefined,
);
// Record this group temp session so a later reply is limited to sessions
// the peer opened.
ctx.tempSessions.record(event.senderUin, event.groupId);
@@ -80,7 +106,26 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline
if (event.kind === 'group_msg_emoji_like') {
cacheReaction(ctx, event);
}
await convertAndDispatch(ctx, log, event);
let messageIdOverride: number | undefined;
if (event.kind === 'friend_recall') {
const clientSequence = event.clientSeq ?? event.msgSeq;
const recalled = ctx.messageStore.recordPrivateRecall(
event.userUin,
clientSequence,
event.recalledBySelf === true,
event.time,
);
if (recalled !== null) {
messageIdOverride = recalled;
} else {
log.debug(
'friend recall cache miss peer=%d clientSeq=%d',
event.userUin,
clientSequence,
);
}
}
await convertAndDispatch(ctx, log, event, messageIdOverride);
})),
);
}
@@ -143,19 +188,31 @@ const NOTICE_KINDS = [
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
async function convertAndDispatch(
ctx: OneBotInstanceContext,
log: Logger,
event: QQEventVariant,
messageIdOverride?: number,
): Promise<void> {
// Inbound choke point — the receive-side mirror of the outbound api-handler.
// Correlate the whole receive chain (decode → convert, incl. any rkey-fetch
// packets the conversion triggers, → dispatch) under one [req#N]. Only pay
// the AsyncLocalStorage wrap + id when trace is actually live.
if (getLogLevel() !== 'trace') {
await runConvertAndDispatch(ctx, log, event);
await runConvertAndDispatch(ctx, log, event, messageIdOverride);
return;
}
await runWithRequestId(nextRequestId(), () => runConvertAndDispatch(ctx, log, event));
await runWithRequestId(nextRequestId(), () => (
runConvertAndDispatch(ctx, log, event, messageIdOverride)
));
}
async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
async function runConvertAndDispatch(
ctx: OneBotInstanceContext,
log: Logger,
event: QQEventVariant,
messageIdOverride?: number,
): Promise<void> {
// Raw inbound event, memory-only (trace). Lazy → the deep render runs only
// when trace is live.
log.trace(() => [`recv ${event.kind} ⇐ %s`, renderParamsVerbose(event)]);
@@ -165,6 +222,10 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]);
return;
}
if (messageIdOverride !== undefined && event.kind === 'friend_recall') {
converted.message_id = messageIdOverride;
}
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) 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
@@ -180,6 +241,9 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
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' && isFriendMessageRecalled(ctx, log, event)) return;
ctx.dispatchEvent(converted, 'bridge');
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
}
@@ -201,23 +265,64 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEven
function cachePrivateMessageMeta(
ctx: OneBotInstanceContext,
sessionId: number,
msgSeq: number,
messageSequence: number,
serverSequence: number,
clientSequence: number,
timestamp: number,
random: number,
sequenceAuthoritative: boolean,
privateDirection: MessageMeta['privateDirection'],
): void {
const messageId = hashMessageIdInt32(msgSeq, sessionId, PRIVATE_MESSAGE_EVENT);
const isFriendMessage = privateDirection !== undefined;
const hasNtSequence = isFriendMessage
&& sequenceAuthoritative
&& serverSequence > 0;
const eventName = isFriendMessage
? privateMessageEventName(privateDirection === 'outgoing', hasNtSequence)
: PRIVATE_MESSAGE_EVENT;
const messageId = hashMessageIdInt32(
hasNtSequence ? serverSequence : messageSequence,
sessionId,
eventName,
);
ctx.cacheMessageMeta(messageId, {
isGroup: false,
targetId: sessionId,
sequence: msgSeq,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
sequence: serverSequence,
sequenceAuthoritative: sequenceAuthoritative && serverSequence > 0,
eventName,
clientSequence,
privateDirection,
random,
timestamp,
});
}
function isFriendMessageRecalled(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
): boolean {
const peerUin = event.peerUin ?? event.senderUin;
const clientSequence = event.clientSeq ?? event.msgSeq;
const sentBySelf = event.senderUin === ctx.selfId;
const recalled = ctx.messageStore.isPrivateMessageRecalled(
peerUin,
clientSequence,
sentBySelf,
event.time,
);
if (recalled) {
log.debug(
'friend message suppressed by recall tombstone peer=%d clientSeq=%d self=%s',
peerUin,
clientSequence,
String(sentBySelf),
);
}
return recalled;
}
function cacheReaction(
ctx: OneBotInstanceContext,
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
+29 -4
View File
@@ -12,7 +12,13 @@ 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, hashMessageIdInt32 } from './message-id';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
} from './message-id';
import { MessageStore } from './message-store';
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
@@ -127,8 +133,23 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp) => {
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 = this.messageStore.findPrivateMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
);
if (storedId !== null) return storedId;
}
return hashMessageIdInt32(sequence, sessionId, resolvedEventName);
},
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
@@ -495,7 +516,11 @@ export class OneBotInstance {
? (toInt(event.target_id) || toInt(event.user_id))
: toInt(event.user_id);
const sequence = toInt(event.message_seq);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: event.sub_type === 'friend'
? privateMessageEventName(event.post_type === 'message_sent', false)
: PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) return;
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
+9
View File
@@ -2,6 +2,15 @@ import { createHash } from 'node:crypto';
export const GROUP_MESSAGE_EVENT = 'group_message';
export const PRIVATE_MESSAGE_EVENT = 'private_message';
/** Legacy/fallback namespace for private messages sent by the current account. */
export const PRIVATE_SENT_MESSAGE_EVENT = 'private_message_sent';
/** Namespace for private messages keyed by QQ's conversation-wide NT sequence. */
export const PRIVATE_NT_MESSAGE_EVENT = 'private_message_nt';
export function privateMessageEventName(sentBySelf: boolean, hasNtSequence: boolean): string {
if (hasNtSequence) return PRIVATE_NT_MESSAGE_EVENT;
return sentBySelf ? PRIVATE_SENT_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
}
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
+335 -10
View File
@@ -28,6 +28,10 @@ export class MessageStore {
private readonly stmtListEventsLatest: StatementSync;
private readonly stmtFindLatestAuthoritativeSequence: StatementSync;
private readonly stmtListIncomingC2CSessions: StatementSync;
private readonly stmtFindPrivateRecall: StatementSync;
private readonly stmtFindPrivateRecallTombstone: StatementSync;
private readonly stmtUpsertPrivateRecallTombstone: StatementSync;
private readonly stmtDeleteMessage: StatementSync;
constructor(dbPath: string) {
// Replace .json extension with .db if present
@@ -39,22 +43,29 @@ export class MessageStore {
// Database instance — `close()` finalizes them automatically.
this.stmtStoreEvent = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name,
sequence = CASE WHEN excluded.is_group = 1 THEN excluded.sequence ELSE messages.sequence END,
sequence_authoritative = CASE WHEN excluded.is_group = 1 THEN excluded.sequence_authoritative ELSE messages.sequence_authoritative END,
event_name = CASE
WHEN excluded.is_group = 1 THEN excluded.event_name
ELSE messages.event_name
END,
private_direction = CASE
WHEN excluded.private_direction >= 0 THEN excluded.private_direction
ELSE messages.private_direction
END,
timestamp = excluded.timestamp,
data = excluded.data`,
);
this.stmtStoreMeta = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
@@ -62,6 +73,7 @@ export class MessageStore {
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name,
client_sequence = excluded.client_sequence,
private_direction = excluded.private_direction,
random = excluded.random,
timestamp = excluded.timestamp`,
);
@@ -71,7 +83,7 @@ export class MessageStore {
);
this.stmtFindMeta = this.db.prepare(
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
);
this.stmtResolveReplyGroup = this.db.prepare(
@@ -82,9 +94,13 @@ export class MessageStore {
);
this.stmtResolveReplyPrivate = this.db.prepare(
`SELECT sequence
`SELECT CASE
WHEN client_sequence > 0 THEN client_sequence
ELSE sequence
END AS sequence
FROM messages
WHERE is_group = 0 AND message_hash = ? AND sequence_authoritative = 1
WHERE is_group = 0 AND message_hash = ?
AND (client_sequence > 0 OR sequence_authoritative = 1)
LIMIT 1`,
);
@@ -134,6 +150,33 @@ export class MessageStore {
GROUP BY session_id
ORDER BY session_id ASC`,
);
this.stmtFindPrivateRecall = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND client_sequence = ?
AND private_direction = ? AND timestamp <= ?
ORDER BY timestamp DESC, sequence DESC
LIMIT 1`,
);
this.stmtFindPrivateRecallTombstone = this.db.prepare(
`SELECT recalled_at
FROM private_recall_tombstones
WHERE session_id = ? AND client_sequence = ? AND private_direction = ?`,
);
this.stmtUpsertPrivateRecallTombstone = this.db.prepare(
`INSERT INTO private_recall_tombstones
(session_id, client_sequence, private_direction, recalled_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(session_id, client_sequence, private_direction) DO UPDATE SET
recalled_at = MAX(private_recall_tombstones.recalled_at, excluded.recalled_at)`,
);
this.stmtDeleteMessage = this.db.prepare(
'DELETE FROM messages WHERE message_hash = ?',
);
}
close(): void {
@@ -152,6 +195,30 @@ export class MessageStore {
if (!isValidMessageId(messageId)) return;
const json = JSON.stringify(event);
const timestamp = toInt(event.time);
const privateDirection = eventPrivateDirection(isGroup, event);
if (privateDirection >= 0) {
const existing = this.stmtFindMeta.get(messageId) as { client_sequence: number } | undefined;
const eventClientSequence = toInt(event.message_seq);
const clientSequence = existing?.client_sequence && existing.client_sequence > 0
? existing.client_sequence
: eventClientSequence;
if (clientSequence > 0 && this.isPrivateMessageRecalled(
sessionId,
clientSequence,
privateDirection === 1,
timestamp,
)) {
this.stmtDeleteMessage.run(messageId);
log.debug(
'suppressed recalled private event: peer=%d clientSeq=%d self=%s messageId=%d',
sessionId,
clientSequence,
String(privateDirection === 1),
messageId,
);
return;
}
}
this.stmtStoreEvent.run(
messageId,
@@ -160,6 +227,7 @@ export class MessageStore {
sequence,
options.sequenceAuthoritative === false ? 0 : 1,
eventName,
privateDirection,
timestamp,
json,
);
@@ -167,6 +235,26 @@ export class MessageStore {
storeMeta(messageId: number, meta: MessageMeta): void {
if (!isValidMessageId(messageId)) return;
const privateDirection = encodePrivateDirection(meta.privateDirection);
if (!meta.isGroup
&& privateDirection >= 0
&& meta.clientSequence > 0
&& this.isPrivateMessageRecalled(
meta.targetId,
meta.clientSequence,
privateDirection === 1,
meta.timestamp,
)) {
this.stmtDeleteMessage.run(messageId);
log.debug(
'suppressed recalled private meta: peer=%d clientSeq=%d self=%s messageId=%d',
meta.targetId,
meta.clientSequence,
String(privateDirection === 1),
messageId,
);
return;
}
this.stmtStoreMeta.run(
messageId,
meta.isGroup ? 1 : 0,
@@ -175,6 +263,7 @@ export class MessageStore {
meta.sequenceAuthoritative === false ? 0 : 1,
meta.eventName,
meta.clientSequence,
privateDirection,
meta.random,
meta.timestamp
);
@@ -202,6 +291,7 @@ export class MessageStore {
sequence_authoritative: number;
event_name: string;
client_sequence: number;
private_direction: number;
random: number;
timestamp: number;
} | undefined;
@@ -215,6 +305,11 @@ export class MessageStore {
sequenceAuthoritative: row.sequence_authoritative === 1,
eventName: row.event_name,
clientSequence: row.client_sequence,
...(row.private_direction === 0
? { privateDirection: 'incoming' as const }
: row.private_direction === 1
? { privateDirection: 'outgoing' as const }
: {}),
random: row.random,
timestamp: row.timestamp,
};
@@ -229,6 +324,8 @@ export class MessageStore {
// - When receiving: session_id is the sender's UIN
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
// So for private messages, we only match by message_hash and is_group flag.
// Replies use ContentHead field 5 (sender-local client sequence), while
// `sequence` stores field 11 for bidirectional history pagination.
const row = isGroup
? this.stmtResolveReplyGroup.get(sessionId, messageId) as { sequence: number } | undefined
: this.stmtResolveReplyPrivate.get(messageId) as { sequence: number } | undefined;
@@ -239,6 +336,39 @@ export class MessageStore {
return row.sequence;
}
/**
* Resolve a sender-local C2C sequence to the stored OneBot id. Direction and
* timestamp are part of the key because QQ can reuse the same client sequence
* in the opposite direction and after a client restart.
*/
findPrivateMessageId(
sessionId: number,
clientSequence: number,
sentBySelf: boolean,
atOrBefore?: number,
): number | null {
const upperTimestamp = atOrBefore === undefined
? Number.MAX_SAFE_INTEGER
: atOrBefore;
validatePrivateRecallKey(
sessionId,
clientSequence,
upperTimestamp,
'message lookup time',
);
const row = this.stmtFindPrivateRecall.get(
sessionId,
clientSequence,
sentBySelf ? 1 : 0,
upperTimestamp,
) 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;
}
listSessionEvents(
isGroup: boolean,
sessionId: number,
@@ -285,6 +415,78 @@ export class MessageStore {
return row.sequence;
}
/**
* Resolve a private recall's sender-local client sequence to the OneBot
* message id and remove the cached row. The protocol recall notice does not
* carry the bidirectional NT sequence, so this lookup must happen before the
* notice is converted.
*/
recordPrivateRecall(
sessionId: number,
clientSequence: number,
recalledBySelf: boolean,
recalledAt: number,
): number | null {
validatePrivateRecallKey(sessionId, clientSequence, recalledAt);
const direction = recalledBySelf ? 1 : 0;
this.db.exec('BEGIN IMMEDIATE');
try {
this.stmtUpsertPrivateRecallTombstone.run(
sessionId,
clientSequence,
direction,
recalledAt,
);
const row = this.stmtFindPrivateRecall.get(
sessionId,
clientSequence,
direction,
recalledAt,
) as { message_hash: number } | undefined;
if (!row) {
this.db.exec('COMMIT');
return null;
}
if (!isValidMessageId(row.message_hash)) {
throw new Error(`private recall matched invalid message id ${String(row.message_hash)}`);
}
const deleted = this.stmtDeleteMessage.run(row.message_hash);
if (Number(deleted.changes) !== 1) {
throw new Error(
`private recall cache deletion lost row message=${row.message_hash} peer=${sessionId} clientSeq=${clientSequence}`,
);
}
this.db.exec('COMMIT');
log.debug(
'private recall removed cached message: peer=%d clientSeq=%d self=%s messageId=%d',
sessionId,
clientSequence,
String(recalledBySelf),
row.message_hash,
);
return row.message_hash;
} catch (error) {
this.db.exec('ROLLBACK');
throw error;
}
}
isPrivateMessageRecalled(
sessionId: number,
clientSequence: number,
sentBySelf: boolean,
messageTime: number,
): boolean {
validatePrivateRecallKey(sessionId, clientSequence, messageTime, 'message time');
const row = this.stmtFindPrivateRecallTombstone.get(
sessionId,
clientSequence,
sentBySelf ? 1 : 0,
) as { recalled_at: number } | undefined;
return row !== undefined && row.recalled_at >= messageTime;
}
/**
* Build read-report targets from current groups plus genuine incoming C2C
* sessions. `is_group = 0` alone is insufficient: group temp sessions use
@@ -325,14 +527,103 @@ export class MessageStore {
sequence_authoritative INTEGER NOT NULL DEFAULT 1,
event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0,
private_direction INTEGER NOT NULL DEFAULT -1,
random INTEGER NOT NULL DEFAULT 0,
timestamp INTEGER NOT NULL DEFAULT 0,
data TEXT
)
`);
this.migrateSequenceAuthority();
this.migratePrivateDirection();
this.migratePrivateNtSequences();
this.db.exec(`
CREATE TABLE IF NOT EXISTS private_recall_tombstones (
session_id INTEGER NOT NULL,
client_sequence INTEGER NOT NULL,
private_direction INTEGER NOT NULL CHECK(private_direction IN (0, 1)),
recalled_at INTEGER NOT NULL,
PRIMARY KEY (session_id, client_sequence, private_direction)
)
`);
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)');
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)');
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)');
}
private migratePrivateDirection(): void {
const columns = this.db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
if (columns.some((column) => column.name === 'private_direction')) return;
this.db.exec('BEGIN IMMEDIATE');
try {
this.db.exec(
'ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1',
);
this.db.exec(`
UPDATE messages
SET private_direction = CASE json_extract(data, '$.post_type')
WHEN 'message' THEN 0
WHEN 'message_sent' THEN 1
ELSE -1
END
WHERE is_group = 0
AND data IS NOT NULL
AND json_valid(data)
AND json_extract(data, '$.message_type') = 'private'
AND json_extract(data, '$.sub_type') = 'friend'
`);
this.db.exec('COMMIT');
} catch (error) {
this.db.exec('ROLLBACK');
throw error;
}
}
private migratePrivateNtSequences(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS message_store_migrations (
name TEXT PRIMARY KEY,
applied_at INTEGER NOT NULL
)
`);
const migration = 'private-nt-sequence-v1';
this.db.exec('BEGIN IMMEDIATE');
try {
const applied = this.db.prepare(
'SELECT 1 AS applied FROM message_store_migrations WHERE name = ?',
).get(migration) as { applied: number } | undefined;
if (applied) {
this.db.exec('COMMIT');
return;
}
// Pre-fix observed/fetched private rows did not retain client_sequence;
// their `sequence` came from ContentHead field 5 and is sender-local.
// Action-sent rows do retain client_sequence and their send receipt
// carries QQ's private server sequence, so those remain usable.
const result = this.db.prepare(`
UPDATE messages
SET sequence_authoritative = 0
WHERE is_group = 0
AND sequence_authoritative = 1
AND client_sequence = 0
`).run();
this.db.prepare(
'INSERT INTO message_store_migrations (name, applied_at) VALUES (?, ?)',
).run(migration, Math.floor(Date.now() / 1000));
this.db.exec('COMMIT');
if (Number(result.changes) > 0) {
log.info(
'message-store schema migrated: legacy private sequences invalidated=%d',
Number(result.changes),
);
}
} catch (error) {
this.db.exec('ROLLBACK');
throw error;
}
}
private migrateSequenceAuthority(): void {
@@ -423,6 +714,40 @@ function isValidMessageId(messageId: number): boolean {
return Number.isInteger(messageId) && messageId !== 0;
}
function encodePrivateDirection(direction: MessageMeta['privateDirection']): number {
if (direction === 'incoming') return 0;
if (direction === 'outgoing') return 1;
return -1;
}
function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
if (isGroup
|| event.message_type !== 'private'
|| event.sub_type !== 'friend') {
return -1;
}
if (event.post_type === 'message') return 0;
if (event.post_type === 'message_sent') return 1;
return -1;
}
function validatePrivateRecallKey(
sessionId: number,
clientSequence: number,
timestamp: number,
timestampLabel = 'recall time',
): void {
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
throw new Error(`invalid private recall peer ${String(sessionId)}`);
}
if (!Number.isSafeInteger(clientSequence) || clientSequence <= 0) {
throw new Error(`invalid private recall client sequence ${String(clientSequence)}`);
}
if (!Number.isSafeInteger(timestamp) || timestamp < 0) {
throw new Error(`invalid private recall ${timestampLabel} ${String(timestamp)}`);
}
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
+211 -84
View File
@@ -6,7 +6,11 @@ import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { segmentsToRawMessage } from '../helper/cq';
import type { OneBotInstanceContext } from '../instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import {
GROUP_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
} from '../message-id';
import { MessageElementValidationError, parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store';
import { sameSelfSentMessage } from '../self-sent-event';
@@ -219,11 +223,12 @@ export async function getGroupHistory(
/**
* Private (c2c) history — the same server-fetch + persist pattern as
* {@link getGroupHistory}, but via `SsoGetC2cMsg` (peer = the friend's UID,
* resolved from the uin). The anchor is the message_id's sequence (any side of
* the conversation) or the latest observed inbound message. Direction applies
* only to an explicit anchor; an unanchored request keeps latest-page behavior.
* Falls back to the local store on unknown anchor / no uid / empty / error.
* {@link getGroupHistory}. Explicit anchors use `SsoGetC2cMsg`; unanchored
* latest-page requests use `SsoGetRoamMsg`, because C2C field-5 sequences are
* sender-local and cannot safely bootstrap a conversation. Falls back to the
* local store only when an explicit message id cannot supply a safe server
* anchor. Server and UID failures are surfaced instead of returning a partial
* local conversation as a successful response.
*/
export async function getFriendHistory(
ref: HistoryRef,
@@ -253,77 +258,81 @@ export async function getFriendHistory(
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
}
anchorSeq = meta.sequence;
} else {
// Current rows are keyed by conversation peer, so the latest local anchor
// covers both incoming and self-sent messages. Legacy sender-keyed rows are
// repaired when they are fetched through an explicit anchor.
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(false, userId) ?? 0;
}
log.debug(
'friend history anchor selected: user=%d source=%s anchorSeq=%d',
'friend history source selected: user=%d source=%s anchorSeq=%d',
userId,
hasAnchor ? 'message_id' : 'latest_authoritative',
hasAnchor ? 'message_id' : 'roam',
anchorSeq,
);
if (anchorSeq > 0) {
try {
const friendUid = await ref.bridge.resolveUserUid(userId);
if (friendUid) {
const events = await ref.bridge.apis.message.getC2cHistory(
friendUid,
anchorSeq,
want,
ref.selfId,
effectiveReverseOrder,
);
const out: JsonObject[] = [];
for (const ev of events) {
// The action itself identifies the conversation even when an older
// QQ response omits ResponseHead.toUin on a self-sent row.
if (!ev.peerUin || ev.peerUin <= 0) ev.peerUin = userId;
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'private') continue;
// Private history is scoped by the requested peer, while user_id is
// the sender and therefore equals selfId for outgoing messages.
// Preserve the peer explicitly so later local pagination can keep
// both sides of the conversation together.
if (json.post_type === 'message_sent' && toHistInt(json.target_id) === 0) {
json.target_id = userId;
}
persistHistoryEvent(ref.messageStore, json, userId);
out.push(sanitizeMessageEventForApi(json));
}
if (out.length > 0) return out;
log.debug(
'friend history server fetch returned no usable messages: user=%d anchorSeq=%d count=%d; using local store',
userId,
anchorSeq,
want,
);
}
} catch (err) {
log.warn(
'friend history server fetch failed: user=%d anchorSeq=%d count=%d reverseOrder=%s error=%s; using local store',
userId,
anchorSeq,
want,
String(effectiveReverseOrder),
err instanceof Error ? err.message : String(err),
);
}
const friendUid = await ref.bridge.resolveUserUid(userId);
if (!friendUid) {
throw new Error(`friend history cannot resolve uid for user ${userId}`);
}
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
const events = hasAnchor
? await ref.bridge.apis.message.getC2cHistory(
friendUid,
anchorSeq,
want,
ref.selfId,
effectiveReverseOrder,
)
: await ref.bridge.apis.message.getC2cLatestHistory(friendUid, want, ref.selfId);
const out: JsonObject[] = [];
for (const ev of events) {
// The action itself identifies the conversation even when an older
// QQ response omits ResponseHead.toUin on a self-sent row.
if (!ev.peerUin || ev.peerUin <= 0) ev.peerUin = userId;
const clientSequence = ev.clientSeq ?? ev.msgSeq;
const sentBySelf = ev.senderUin === ref.selfId;
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'private') continue;
// Conversion can await media resolution, so consult the tombstone only
// after it settles. From this check through persistence/return there is no
// async gap in which a recall could race past us.
if (ref.messageStore.isPrivateMessageRecalled(
userId,
clientSequence,
sentBySelf,
ev.time,
)) {
log.debug(
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
userId,
clientSequence,
String(sentBySelf),
);
continue;
}
// Private history is scoped by the requested peer, while user_id is
// the sender and therefore equals selfId for outgoing messages.
if (json.post_type === 'message_sent' && toHistInt(json.target_id) === 0) {
json.target_id = userId;
}
persistHistoryEvent(ref.messageStore, json, userId, ev);
out.push(sanitizeMessageEventForApi(json));
}
log.debug(
'friend history server fetch complete: user=%d source=%s anchorSeq=%d requested=%d returned=%d',
userId,
hasAnchor ? 'message_id' : 'roam',
anchorSeq,
want,
out.length,
);
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 just the quoted message from the server —
* group via `SsoGetGroupMsg`, c2c via `SsoGetC2cMsg`, both through the shared
* 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.
* 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
@@ -347,15 +356,29 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const replySeq = reply?.replySeq ?? 0;
if (replySeq <= 0) return;
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const targetId = hashMessageIdInt32(replySeq, session, eventName);
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(quotedSender === ref.selfId, false);
const resolvedId = ref.converterCtx.messageIdResolver?.(
isGroup,
session,
replySeq,
eventName,
reply?.replyTime && reply.replyTime > 0
? reply.replyTime
: Number.MAX_SAFE_INTEGER,
);
const targetId = Number.isInteger(resolvedId) && resolvedId !== 0
? resolvedId as number
: hashMessageIdInt32(replySeq, session, eventName);
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.
// 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) {
@@ -363,14 +386,57 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
} else {
const friendUid = await ref.bridge.resolveUserUid(session);
if (friendUid) {
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
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;
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
if (fetched.kind === 'group_message') {
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
} else {
const serverSequence = fetched.ntMsgSeq ?? 0;
const sequenceAuthoritative = fetched.sequenceAuthoritative !== false
&& serverSequence > 0;
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,
});
ref.messageStore.storeEvent(
targetId,
false,
session,
serverSequence,
eventName,
json,
{ sequenceAuthoritative },
);
}
return;
}
}
@@ -381,13 +447,13 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
// 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,
ref.selfId,
) as JsonArray;
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session);
@@ -437,10 +503,11 @@ function buildBackfillEvent(
isGroup: boolean,
sessionId: number,
): JsonObject {
const sentBySelf = senderUin === selfId;
const common = {
time: timestamp || Math.floor(Date.now() / 1000),
self_id: selfId,
post_type: 'message' as const,
post_type: sentBySelf ? 'message_sent' as const : 'message' as const,
message_id: messageId,
message_seq: msgSeq,
message: segments,
@@ -458,29 +525,66 @@ function buildBackfillEvent(
anonymous: null,
};
}
return {
const privateEvent: JsonObject = {
...common,
message_type: 'private',
sub_type: 'friend',
user_id: senderUin,
sender: { user_id: senderUin, nickname: '', sex: 'unknown', age: 0 },
};
if (sentBySelf) privateEvent.target_id = sessionId;
return privateEvent;
}
// Persist a converted history event so reply / get_msg / future listing resolve
// it. Private history callers provide the conversation peer because `user_id`
// identifies the sender and equals the bot account on outgoing messages.
function persistHistoryEvent(store: MessageStore, event: JsonObject, privatePeerId?: number): void {
function persistHistoryEvent(
store: MessageStore,
event: JsonObject,
privatePeerId?: number,
source?: FriendMessage,
): void {
const messageId = toHistInt(event.message_id);
if (messageId === 0) return;
const isGroup = event.message_type === 'group';
const sessionId = isGroup
? toHistInt(event.group_id)
: (privatePeerId && privatePeerId > 0 ? privatePeerId : toHistInt(event.user_id));
const sequence = toHistInt(event.message_seq);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const messageSequence = toHistInt(event.message_seq);
const sequence = source?.ntMsgSeq ?? messageSequence;
const sequenceAuthoritative = source?.sequenceAuthoritative !== false && sequence > 0;
const isOutgoingPrivate = !isGroup && source?.senderUin === source?.selfUin;
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: source
? privateMessageEventName(isOutgoingPrivate, sequenceAuthoritative)
: privateMessageEventName(event.post_type === 'message_sent', false);
if (sessionId === 0) return;
store.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
if (!isGroup && source) {
store.storeMeta(messageId, {
isGroup: false,
targetId: sessionId,
sequence,
sequenceAuthoritative,
eventName,
clientSequence: source.clientSeq ?? source.msgSeq,
privateDirection: source.senderUin === source.selfUin
? 'outgoing'
: 'incoming',
random: source.msgId,
timestamp: source.time,
});
}
store.storeEvent(
messageId,
isGroup,
sessionId,
sequence,
eventName,
event,
{ sequenceAuthoritative },
);
}
function toHistInt(value: unknown): number {
@@ -563,8 +667,10 @@ async function finalizeSend(
elements: MessageElement[],
reportEcho = false,
): Promise<MessageSendResult> {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const sequenceAuthoritative = Number.isInteger(receipt.sequence) && receipt.sequence > 0;
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(true, sequenceAuthoritative);
const opaqueMessageId = receipt.messageId ?? 0;
// Ordinary sends use QQ's real sequence so receive/send paths derive the same
// OneBot id. OIDB-only sends (notably group files) have no QQ sequence: keep
@@ -574,7 +680,11 @@ async function finalizeSend(
? hashMessageIdInt32(receipt.sequence, targetId, eventName)
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
? opaqueMessageId
: hashMessageIdInt32(0, targetId, eventName);
: hashMessageIdInt32(
isGroup ? 0 : receipt.clientSequence,
targetId,
eventName,
);
ref.cacheMessageMeta(messageId, {
isGroup,
targetId,
@@ -582,6 +692,7 @@ async function finalizeSend(
sequenceAuthoritative,
eventName,
clientSequence: receipt.clientSequence,
...(isGroup ? {} : { privateDirection: 'outgoing' as const }),
random: receipt.random,
timestamp: receipt.timestamp,
});
@@ -590,7 +701,9 @@ async function finalizeSend(
sessionId: targetId,
messageId,
sequence: receipt.sequence,
messageSequence: isGroup ? receipt.sequence : receipt.clientSequence,
sequenceAuthoritative,
eventName,
timestamp: receipt.timestamp,
elements,
});
@@ -605,8 +718,12 @@ async function cacheSelfSentMessage(
isGroup: boolean;
sessionId: number; // groupId or peer userId
messageId: number;
/** QQ server/NT sequence used for protocol operations and history ordering. */
sequence: number;
/** Public OneBot message_seq (sender-local client sequence for C2C). */
messageSequence: number;
sequenceAuthoritative: boolean;
eventName: string;
timestamp: number;
elements: MessageElement[];
},
@@ -616,7 +733,9 @@ async function cacheSelfSentMessage(
sessionId,
messageId,
sequence,
messageSequence,
sequenceAuthoritative,
eventName,
timestamp,
elements,
} = options;
@@ -636,9 +755,17 @@ async function cacheSelfSentMessage(
// resolver is async and bound to the receive pipeline; skipping it
// means /get_msg returns the segment with the original `file` path
// and an empty `url`, which is what Lagrange does too.
const segments = await elementsToOneBotSegments(elements, isGroup, sessionId) as JsonArray;
const segments = await elementsToOneBotSegments(
elements,
isGroup,
sessionId,
undefined,
undefined,
undefined,
undefined,
ref.selfId,
) as JsonArray;
const raw = segmentsToRawMessage(segments);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const selfId = ref.selfId;
const event: JsonObject = {
@@ -648,7 +775,7 @@ async function cacheSelfSentMessage(
message_type: isGroup ? 'group' : 'private',
sub_type: isGroup ? 'normal' : 'friend',
message_id: messageId,
message_seq: sequence,
message_seq: messageSequence,
user_id: selfId, // sender = self
message: segments,
raw_message: raw,
+2
View File
@@ -126,6 +126,8 @@ export interface MessageMeta {
sequenceAuthoritative: boolean;
eventName: string;
clientSequence: number;
/** Sender direction for friend messages; absent for groups/temp/legacy rows. */
privateDirection?: 'incoming' | 'outgoing';
random: number;
timestamp: number;
}
@@ -1,12 +1,17 @@
// 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
// getGroupMessageBySeq, c2c → timestamp roam lookup, 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';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
} from '../src/message-id';
const SELF = 10001;
@@ -21,6 +26,7 @@ const converterCtx = {
function fakeStore(has = false) {
return {
findEvent: vi.fn(() => (has ? ({ message_id: 1 } as any) : null)),
storeMeta: vi.fn(),
storeEvent: vi.fn(),
};
}
@@ -45,7 +51,9 @@ function fetchedGroupMessage(msgSeq: number) {
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' }],
peerUin: senderUin === SELF ? 448671521 : senderUin,
senderNick: 'orig', msgSeq, ntMsgSeq: msgSeq + 1000, clientSeq: msgSeq,
sequenceAuthoritative: true, msgId: 1, elements: [{ type: 'text', text: 'quoted' }],
} as any;
}
@@ -70,14 +78,14 @@ describe('backfillReplyTarget', () => {
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 getC2cLatestHistory = 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 },
bridge: { apis: { message: { getC2cLatestHistory } }, resolveUserUid },
} as any;
const event = {
kind: 'friend_message', time: 1, selfUin: SELF, senderUin: 448671521,
kind: 'friend_message', time: 1700000100, selfUin: SELF, senderUin: 448671521,
senderNick: '', msgSeq: 999, msgId: 2,
elements: [{ type: 'reply', replySeq: 456 }, { type: 'text', text: '同意' }],
} as any;
@@ -85,11 +93,18 @@ describe('backfillReplyTarget', () => {
await backfillReplyTarget(ref, event);
expect(resolveUserUid).toHaveBeenCalledWith(448671521);
expect(getC2cMessageBySeq).toHaveBeenCalledWith('u_friend', 456, SELF);
expect(getC2cLatestHistory).toHaveBeenCalledWith('u_friend', 20, SELF, 1700000101);
const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_MESSAGE_EVENT);
expect(store.storeMeta).toHaveBeenCalledWith(targetId, expect.objectContaining({
sequence: 1456,
clientSequence: 456,
privateDirection: 'incoming',
sequenceAuthoritative: true,
}));
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, false, 448671521, 456, PRIVATE_MESSAGE_EVENT,
targetId, false, 448671521, 1456, PRIVATE_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'private' }),
{ sequenceAuthoritative: true },
);
});
@@ -98,35 +113,37 @@ describe('backfillReplyTarget', () => {
// 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 getC2cLatestHistory = vi.fn(async () => [fetchedFriendMessage(456, SELF)]);
const ref = {
selfId: SELF, converterCtx, messageStore: store,
bridge: { apis: { message: { getC2cMessageBySeq } }, resolveUserUid: vi.fn(async () => 'u_friend') },
bridge: { apis: { message: { getC2cLatestHistory } }, resolveUserUid: vi.fn(async () => 'u_friend') },
} as any;
const event = {
kind: 'friend_message', time: 1, selfUin: SELF, senderUin: 448671521,
kind: 'friend_message', time: 1700000100, selfUin: SELF, senderUin: 448671521,
senderNick: '', msgSeq: 999, msgId: 2,
elements: [{ type: 'reply', replySeq: 456 }],
elements: [{ type: 'reply', replySeq: 456, replySenderUin: SELF }],
} as any;
await backfillReplyTarget(ref, event);
const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_MESSAGE_EVENT);
const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_SENT_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, false, 448671521, 456, PRIVATE_MESSAGE_EVENT, expect.objectContaining({ message_id: targetId }),
targetId, false, 448671521, 1456, PRIVATE_SENT_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId }),
{ sequenceAuthoritative: true },
);
});
it('c2c: a self-sent reply echo backfills under the conversation peer', async () => {
const peerUin = 448671521;
const store = fakeStore(false);
const getC2cMessageBySeq = vi.fn(async () => fetchedFriendMessage(456, peerUin));
const getC2cLatestHistory = vi.fn(async () => [fetchedFriendMessage(456, peerUin)]);
const ref = {
selfId: SELF, converterCtx, messageStore: store,
bridge: { apis: { message: { getC2cMessageBySeq } }, resolveUserUid: vi.fn(async () => 'u_friend') },
bridge: { apis: { message: { getC2cLatestHistory } }, resolveUserUid: vi.fn(async () => 'u_friend') },
} as any;
const event = {
kind: 'friend_message', time: 1, selfUin: SELF, senderUin: SELF, peerUin,
kind: 'friend_message', time: 1700000100, selfUin: SELF, senderUin: SELF, peerUin,
senderNick: '', msgSeq: 999, msgId: 2,
elements: [{ type: 'reply', replySeq: 456 }],
} as any;
@@ -135,8 +152,9 @@ describe('backfillReplyTarget', () => {
const targetId = hashMessageIdInt32(456, peerUin, PRIVATE_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, false, peerUin, 456, PRIVATE_MESSAGE_EVENT,
targetId, false, peerUin, 1456, PRIVATE_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'private' }),
{ sequenceAuthoritative: true },
);
});
@@ -17,6 +17,7 @@ import type {
QQEventVariant,
TempMessage,
} from '@snowluma/protocol/events';
import { PRIVATE_SENT_MESSAGE_EVENT } from '../src/message-id';
const SELF_ID = 10001;
const PEER_UIN = 22222;
@@ -355,6 +356,7 @@ describe('convertEvent — message elements (13 segment types)', () => {
const segments = await elementsToOneBotSegments(
[element], false, PEER_UIN,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
ctx.selfId,
);
return segments[0] as unknown as Segment;
}
@@ -436,6 +438,28 @@ describe('convertEvent — message elements (13 segment types)', () => {
expect(seg).toEqual({ type: 'reply', data: { id: '9999' } });
});
it('reply: self-sent private targets use the outgoing lookup namespace', async () => {
const calls: unknown[][] = [];
const seg = await segment(
{ type: 'reply', replySeq: 5, replySenderUin: SELF_ID, replyTime: 1234 },
{
messageIdResolver: (...args) => {
calls.push(args);
return 9999;
},
},
);
expect(seg).toEqual({ type: 'reply', data: { id: '9999' } });
expect(calls[0]).toEqual([
false,
PEER_UIN,
5,
PRIVATE_SENT_MESSAGE_EVENT,
1234,
]);
});
it('reply: replySeq=0 -> id "0", no resolver call', async () => {
let resolverCalls = 0;
const seg = await segment(
+58 -1
View File
@@ -46,6 +46,9 @@ function makeFriendMessage(): FriendMessage {
senderUin: PEER_UIN,
senderNick: 'peer',
msgSeq: 11,
ntMsgSeq: 11,
clientSeq: 1011,
sequenceAuthoritative: true,
msgId: 555,
elements: [{ type: 'text', text: 'hi' }],
};
@@ -76,6 +79,7 @@ function makeTempMessage(): TempMessage {
groupId: GROUP_ID,
senderNick: 'peer',
msgSeq: 33,
ntMsgSeq: 33,
elements: [{ type: 'text', text: 'temp' }],
};
}
@@ -113,7 +117,7 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
uin: SELF_UIN,
selfId: SELF_ID,
bridge: fakeBridge as never,
messageStore: {} as never,
messageStore: { isPrivateMessageRecalled: () => false } as never,
mediaStore: {} as never,
reactionStore: {
recordAdd: () => {},
@@ -146,6 +150,7 @@ describe('registerEventPipeline', () => {
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
expect(metaCalls[0].meta.sequence).toBe(11);
expect(metaCalls[0].meta.sequenceAuthoritative).toBe(true);
expect(metaCalls[0].meta.clientSequence).toBe(1011);
expect(metaCalls[0].meta.random).toBe(555);
expect(dispatchCalls).toHaveLength(1);
@@ -208,6 +213,32 @@ describe('registerEventPipeline', () => {
expect(dispatchCalls[0].notice_type).toBe('group_increase');
});
it('removes a recalled private message and reports its original OneBot id', async () => {
const recordPrivateRecall = vi.fn(() => -7654321);
const { ctx, bus, dispatchCalls } = makeContext({
messageStore: { recordPrivateRecall } as never,
});
registerEventPipeline(ctx);
await bus.emit({
kind: 'friend_recall',
time: 1700000001,
selfUin: SELF_ID,
userUin: PEER_UIN,
msgSeq: 1011,
clientSeq: 1011,
recalledBySelf: false,
} as QQEventVariant);
expect(recordPrivateRecall).toHaveBeenCalledWith(PEER_UIN, 1011, false, 1700000001);
expect(dispatchCalls).toHaveLength(1);
expect(dispatchCalls[0]).toMatchObject({
notice_type: 'friend_recall',
user_id: PEER_UIN,
message_id: -7654321,
});
});
it('returns a lifecycle handle that fully unsubscribes', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
const pipeline = registerEventPipeline(ctx);
@@ -305,6 +336,32 @@ describe('registerEventPipeline', () => {
))).toBe(true);
});
it('suppresses a friend message recalled while reply backfill is in flight', async () => {
let markBackfillStarted!: () => void;
const backfillStarted = new Promise<void>((resolve) => { markBackfillStarted = resolve; });
let releaseBackfill!: () => void;
const backfillGate = new Promise<void>((resolve) => { releaseBackfill = resolve; });
vi.mocked(backfillReplyTarget).mockImplementationOnce(async () => {
markBackfillStarted();
await backfillGate;
});
const isPrivateMessageRecalled = vi.fn()
.mockReturnValueOnce(false)
.mockReturnValueOnce(true);
const { ctx, bus, dispatchCalls } = makeContext({
messageStore: { isPrivateMessageRecalled } as never,
});
registerEventPipeline(ctx);
const emitting = bus.emit(makeFriendMessage());
await backfillStarted;
releaseBackfill();
await emitting;
expect(isPrivateMessageRecalled).toHaveBeenCalledTimes(2);
expect(dispatchCalls).toHaveLength(0);
});
it('dispatches a separate event for every kind in parallel', async () => {
const { ctx, bus, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
+149 -3
View File
@@ -1,5 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
hashMessageIdInt32,
} from '../src/message-id';
import { MessageStore } from '../src/message-store';
import { getFriendHistory, getFriendMsgHistory, getGroupHistory } from '../src/modules/message-actions';
@@ -32,12 +37,15 @@ function groupMessage(sequence: number) {
};
}
function friendMessage(sequence: number, senderUin: number) {
function friendMessage(sequence: number, senderUin: number, clientSequence = sequence) {
return {
kind: 'friend_message' as const,
senderUin,
senderNick: senderUin === SELF_ID ? 'self' : 'friend',
msgSeq: sequence,
msgSeq: clientSequence,
ntMsgSeq: sequence,
clientSeq: clientSequence,
sequenceAuthoritative: true,
msgId: sequence,
time: sequence,
selfUin: SELF_ID,
@@ -116,6 +124,144 @@ describe('history direction plumbing', () => {
expect(cached.map((message) => message.message_seq)).toEqual([700, 701]);
});
it('uses C2C roaming for an unanchored latest page and ignores a stale local sequence', async () => {
const fetchRangeHistory = vi.fn(async () => [friendMessage(99999, FRIEND_ID)]);
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
]);
messageStore.storeMeta(-222222222, {
isGroup: false,
targetId: FRIEND_ID,
sequence: 99999,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: 1,
});
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: {
message: {
getC2cHistory: fetchRangeHistory,
getC2cLatestHistory: fetchLatestHistory,
},
},
},
messageStore,
converterCtx,
} as any;
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
expect(fetchLatestHistory).toHaveBeenCalledWith('u_friend', 20, SELF_ID);
expect(fetchRangeHistory).not.toHaveBeenCalled();
expect(messages.map((message) => ({
sender: message.user_id,
sequence: message.message_seq,
}))).toEqual([
{ sender: FRIEND_ID, sequence: 32742 },
{ sender: SELF_ID, sequence: 32743 },
]);
expect(messageStore.findMeta(Number(messages[0]!.message_id))).toMatchObject({
sequence: 63213,
clientSequence: 32742,
sequenceAuthoritative: true,
});
});
it('uses the conversation-wide NT sequence when both directions share a client sequence', async () => {
const sharedClientSequence = 32742;
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, sharedClientSequence),
friendMessage(63214, SELF_ID, sharedClientSequence),
]);
const productionConverterCtx = {
...converterCtx,
messageIdResolver: (
_isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
) => hashMessageIdInt32(sequence, sessionId, eventName),
};
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
},
messageStore,
converterCtx: productionConverterCtx,
} as any;
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
const ids = messages.map((message) => Number(message.message_id));
expect(messages.map((message) => message.message_seq)).toEqual([
sharedClientSequence,
sharedClientSequence,
]);
expect(ids).toEqual([
hashMessageIdInt32(63213, FRIEND_ID, PRIVATE_NT_MESSAGE_EVENT),
hashMessageIdInt32(63214, FRIEND_ID, PRIVATE_NT_MESSAGE_EVENT),
]);
expect(new Set(ids).size).toBe(2);
expect(ids.map((id) => messageStore.findEvent(id)?.message_id)).toEqual(ids);
});
it('does not return or re-cache a private message covered by a recall tombstone', async () => {
messageStore.recordPrivateRecall(FRIEND_ID, 32742, false, 1700000010);
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
]);
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
},
messageStore,
converterCtx,
} as any;
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
expect(messageStore.listSessionEvents(false, FRIEND_ID, 20))
.toHaveLength(1);
});
it('surfaces an unanchored server failure instead of returning incomplete local history', async () => {
messageStore.storeEvent(1, false, FRIEND_ID, 12, PRIVATE_MESSAGE_EVENT, {
time: 12,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 1,
message_seq: 12,
user_id: FRIEND_ID,
});
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: {
message: { getC2cLatestHistory: vi.fn(async () => { throw new Error('roam unavailable'); }) },
},
},
messageStore,
converterCtx,
} as any;
await expect(getFriendHistory(ref, FRIEND_ID, undefined, 20))
.rejects.toThrow('roam unavailable');
});
it('keeps latest-page group requests backward-compatible without an anchor', async () => {
const fetchHistory = vi.fn(async (...args: unknown[]) =>
args[4] === true ? [groupMessage(899), groupMessage(900)] : [groupMessage(900), groupMessage(901)]);
+268 -2
View File
@@ -82,6 +82,23 @@ describe('MessageStore', () => {
expect(resolvedWithDifferentSession).toBe(sequence);
});
it('uses the sender-local sequence for private replies, not the NT history sequence', () => {
const messageId = -123456789;
store.storeMeta(messageId, {
isGroup: false,
targetId: 111111,
sequence: 63214,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 32743,
privateDirection: 'incoming',
random: 88,
timestamp: 1700000000,
});
expect(store.resolveReplySequence(false, 111111, messageId)).toBe(32743);
});
it('returns null for non-existent message', () => {
const resolved = store.resolveReplySequence(true, 123456, 999999);
expect(resolved).toBeNull();
@@ -192,6 +209,32 @@ describe('MessageStore', () => {
const retrieved = store.findMeta(999999);
expect(retrieved).toBeNull();
});
it('does not promote a non-authoritative sequence when event data arrives later', () => {
const messageId = 54322;
store.storeMeta(messageId, {
isGroup: false,
targetId: 123456,
sequence: 0,
sequenceAuthoritative: false,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 88,
random: 12,
timestamp: 1700000000,
});
store.storeEvent(messageId, false, 123456, 88, PRIVATE_MESSAGE_EVENT, {
time: 1700000000,
post_type: 'message',
message_type: 'private',
message_id: messageId,
message_seq: 88,
});
expect(store.findMeta(messageId)).toMatchObject({
sequenceAuthoritative: false,
clientSequence: 88,
});
});
});
describe('listSessionEvents', () => {
@@ -260,6 +303,7 @@ describe('MessageStore', () => {
const legacy = new DatabaseSync(testDbPath);
legacy.exec(`
DROP TABLE messages;
DROP TABLE message_store_migrations;
CREATE TABLE messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
@@ -363,6 +407,11 @@ describe('MessageStore', () => {
message: [{ type: 'text', data: { text: 'quoted private content' } }],
sender: { user_id: 555, nickname: '', sex: 'unknown', age: 0 },
}));
legacy.prepare(`
INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (9, 0, 555, 850, ?, 4455, 99, 1700000550, NULL)
`).run(PRIVATE_MESSAGE_EVENT);
legacy.close();
store = new MessageStore(testDbPath);
@@ -373,9 +422,226 @@ describe('MessageStore', () => {
expect(store.findMeta(3)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(4)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(5)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findLatestAuthoritativeSequence(false, 555)).toBe(800);
expect(store.findMeta(6)).toMatchObject({ sequenceAuthoritative: true });
// Pre-fix observed/fetched private rows contain sender-local field-5
// sequences and may not become anchors. A send receipt with a retained
// client sequence is already authoritative and remains usable.
expect(store.findLatestAuthoritativeSequence(false, 555)).toBe(850);
expect(store.findMeta(6)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(7)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(9)).toMatchObject({ sequenceAuthoritative: true });
store.storeMeta(8, {
isGroup: false,
targetId: 555,
sequence: 900,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 1240,
random: 88,
timestamp: 1700000600,
});
expect(store.findLatestAuthoritativeSequence(false, 555)).toBe(900);
});
});
describe('private recall invalidation', () => {
it('removes the recalled cached event by peer and client sequence', () => {
const messageId = -123456789;
const peerId = 555;
store.storeMeta(messageId, {
isGroup: false,
targetId: peerId,
sequence: 63214,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 32743,
random: 88,
timestamp: 1700000600,
});
store.storeEvent(messageId, false, peerId, 63214, PRIVATE_MESSAGE_EVENT, {
time: 1700000600,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: 63214,
user_id: peerId,
message: [{ type: 'text', data: { text: '77' } }],
});
const selfMessageId = -22334455;
store.storeMeta(selfMessageId, {
isGroup: false,
targetId: peerId,
sequence: 73214,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 32743,
random: 99,
timestamp: 1700000601,
});
store.storeEvent(selfMessageId, false, peerId, 73214, PRIVATE_MESSAGE_EVENT, {
time: 1700000601,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: selfMessageId,
message_seq: 32743,
user_id: 10001,
target_id: peerId,
message: [{ type: 'text', data: { text: 'self' } }],
});
expect(store.recordPrivateRecall(peerId, 32743, false, 1700000700)).toBe(messageId);
expect(store.findEvent(messageId)).toBeNull();
expect(store.findMeta(messageId)).toBeNull();
expect(store.findEvent(selfMessageId)).not.toBeNull();
expect(store.recordPrivateRecall(peerId, 32743, false, 1700000700)).toBeNull();
expect(store.recordPrivateRecall(peerId, 32743, true, 1700000700)).toBe(selfMessageId);
});
it('prevents a recalled message from being stored after a meta-only race', () => {
const messageId = -123456789;
const peerId = 555;
store.storeMeta(messageId, {
isGroup: false,
targetId: peerId,
sequence: 63214,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 32743,
privateDirection: 'incoming',
random: 88,
timestamp: 1700000600,
});
expect(store.recordPrivateRecall(peerId, 32743, false, 1700000700)).toBe(messageId);
store.storeEvent(messageId, false, peerId, 63214, PRIVATE_MESSAGE_EVENT, {
time: 1700000600,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: 32743,
user_id: peerId,
});
expect(store.findEvent(messageId)).toBeNull();
expect(store.findMeta(messageId)).toBeNull();
});
it('prevents an outgoing self-sent event from reviving after its meta is recalled', () => {
const messageId = -22334455;
const peerId = 555;
store.storeMeta(messageId, {
isGroup: false,
targetId: peerId,
sequence: 73214,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 32743,
privateDirection: 'outgoing',
random: 99,
timestamp: 1700000600,
});
expect(store.recordPrivateRecall(peerId, 32743, true, 1700000700)).toBe(messageId);
store.storeEvent(messageId, false, peerId, 73214, PRIVATE_MESSAGE_EVENT, {
time: 1700000600,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: 32743,
user_id: 10001,
target_id: peerId,
});
expect(store.findEvent(messageId)).toBeNull();
expect(store.findMeta(messageId)).toBeNull();
});
it('does not delete a later message that reused the recalled client sequence', () => {
const peerId = 555;
const clientSequence = 32743;
const oldMessageId = -123456789;
const futureMessageId = -22334455;
const storePrivate = (messageId: number, ntSequence: number, timestamp: number) => {
store.storeMeta(messageId, {
isGroup: false,
targetId: peerId,
sequence: ntSequence,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence,
privateDirection: 'incoming',
random: ntSequence,
timestamp,
});
store.storeEvent(messageId, false, peerId, ntSequence, PRIVATE_MESSAGE_EVENT, {
time: timestamp,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: clientSequence,
user_id: peerId,
});
};
storePrivate(oldMessageId, 63214, 600);
storePrivate(futureMessageId, 73214, 800);
expect(store.findPrivateMessageId(peerId, clientSequence, false, 700)).toBe(oldMessageId);
expect(store.recordPrivateRecall(peerId, clientSequence, false, 700)).toBe(oldMessageId);
expect(store.findEvent(oldMessageId)).toBeNull();
expect(store.findEvent(futureMessageId)).not.toBeNull();
expect(store.findPrivateMessageId(peerId, clientSequence, false)).toBe(futureMessageId);
});
it('keeps the opposite direction when sender-local sequences collide', () => {
const peerId = 555;
store.recordPrivateRecall(peerId, 32743, false, 1700000700);
store.storeEvent(-22334455, false, peerId, 73214, PRIVATE_MESSAGE_EVENT, {
time: 1700000601,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: -22334455,
message_seq: 32743,
user_id: 10001,
target_id: peerId,
});
expect(store.findEvent(-22334455)).not.toBeNull();
});
it('rejects invalid recall identifiers instead of treating them as cache misses', () => {
expect(() => store.recordPrivateRecall(0, 32743, false, 1700000700))
.toThrow('invalid private recall peer');
expect(() => store.recordPrivateRecall(555, 0, false, 1700000700))
.toThrow('invalid private recall client sequence');
});
});
it('lets a real group event replace an older non-authoritative placeholder', () => {
const groupId = 123456;
store.storeEvent(123, true, groupId, 99, GROUP_MESSAGE_EVENT, {
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 123,
message_seq: 99,
}, { sequenceAuthoritative: false });
store.storeEvent(123, true, groupId, 100, GROUP_MESSAGE_EVENT, {
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 123,
message_seq: 100,
});
expect(store.findMeta(123)).toMatchObject({
sequence: 100,
sequenceAuthoritative: true,
});
});
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
import { OneBotInstance } from '../src/instance';
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
import { hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import { hashMessageIdInt32, PRIVATE_NT_MESSAGE_EVENT } from '../src/message-id';
import { TempSessionStore } from '../src/temp-session-store';
import type { JsonObject, OneBotConfig } from '../src/types';
@@ -102,7 +102,7 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject {
message_type: 'private',
sub_type: 'friend',
message_id: 987654,
message_seq: RECEIPT.sequence,
message_seq: RECEIPT.clientSequence,
user_id: SELF_ID,
target_id: PEER_ID,
message: [{ type: 'text', data: { text: 'hello' } }],
@@ -130,7 +130,7 @@ describe('OneBot self-sent events', () => {
self_id: SELF_ID,
user_id: SELF_ID,
target_id: PEER_ID,
message_seq: RECEIPT.sequence,
message_seq: RECEIPT.clientSequence,
}), 'send');
});
@@ -163,7 +163,7 @@ describe('OneBot self-sent events', () => {
it('keeps an earlier QQ echo and does not report the later action event', async () => {
const { ctx, dispatchEvent, events } = makeContext();
const messageId = hashMessageIdInt32(RECEIPT.sequence, PEER_ID, PRIVATE_MESSAGE_EVENT);
const messageId = hashMessageIdInt32(RECEIPT.sequence, PEER_ID, PRIVATE_NT_MESSAGE_EVENT);
const qqEcho: JsonObject = {
time: RECEIPT.timestamp,
self_id: SELF_ID,
@@ -171,7 +171,7 @@ describe('OneBot self-sent events', () => {
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: RECEIPT.sequence,
message_seq: RECEIPT.clientSequence,
user_id: SELF_ID,
target_id: PEER_ID,
message: [{ type: 'text', data: { text: 'hello' } }],