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

+105 -18
View File
@@ -14,7 +14,11 @@ import type {
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import {
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
fetchGroupMessageRange,
} from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
@@ -152,6 +156,7 @@ async function walkBackHistory<T extends { msgSeq: number }>(
endSeq: number,
count: number,
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number = (event) => event.msgSeq,
): Promise<T[]> {
if (!(endSeq > 0)) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
@@ -165,15 +170,19 @@ async function walkBackHistory<T extends { msgSeq: number }>(
if (batch.length > 0) {
let minSeq = curEnd;
for (const ev of batch) {
collected.set(ev.msgSeq, ev);
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
const sequence = sequenceOf(ev);
if (!Number.isInteger(sequence) || sequence < start || sequence > curEnd) {
throw new Error(`history response sequence is outside requested range ${start}-${curEnd}`);
}
collected.set(sequence, ev);
if (sequence < minSeq) minSeq = sequence;
}
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
} else {
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
}
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
return all.slice(-want); // newest `want`, oldest→newest
}
@@ -186,6 +195,7 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
startSeq: number,
count: number,
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number = (event) => event.msgSeq,
): Promise<T[]> {
if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
@@ -195,13 +205,13 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
let curStart = startSeq;
while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) {
const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1);
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow);
for (const event of window.messages) collected.set(event.msgSeq, event);
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow, sequenceOf);
for (const event of window.messages) collected.set(sequenceOf(event), event);
if (!window.complete || end === HISTORY_MAX_SEQUENCE) break;
curStart = end + 1;
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
return all.slice(0, want);
}
@@ -222,6 +232,7 @@ async function fetchForwardWindow<T extends { msgSeq: number }>(
endSeq: number,
budget: { remaining: number },
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number,
): Promise<ForwardWindowResult<T>> {
if (budget.remaining <= 0) return { messages: [], complete: false };
@@ -230,17 +241,24 @@ async function fetchForwardWindow<T extends { msgSeq: number }>(
const batch = await fetchWindow(startSeq, endSeq);
if (batch.length === 0) return { messages: [], complete: true };
const messages = [...new Map(batch.map((event) => [event.msgSeq, event])).values()]
.sort((a, b) => a.msgSeq - b.msgSeq);
const messages = [...new Map(batch.map((event) => [sequenceOf(event), event])).values()]
.sort((a, b) => sequenceOf(a) - sequenceOf(b));
for (const message of messages) {
if (!Number.isInteger(message.msgSeq) || message.msgSeq < startSeq || message.msgSeq > endSeq) {
const sequence = sequenceOf(message);
if (!Number.isInteger(sequence) || sequence < startSeq || sequence > endSeq) {
throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`);
}
}
const firstSequence = messages[0]!.msgSeq;
const firstSequence = sequenceOf(messages[0]!);
if (firstSequence === startSeq) return { messages, complete: true };
const prefix = await fetchForwardWindow(startSeq, firstSequence - 1, budget, fetchWindow);
const prefix = await fetchForwardWindow(
startSeq,
firstSequence - 1,
budget,
fetchWindow,
sequenceOf,
);
if (!prefix.complete) return prefix;
return { messages: [...prefix.messages, ...messages], complete: true };
}
@@ -825,9 +843,78 @@ export class MessageApi {
if (!friendUid) return [];
const fetchWindow = (start: number, end: number) =>
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end);
const serverSequence = (message: FriendMessage) => message.ntMsgSeq ?? 0;
return reverseOrder
? walkBackHistory(anchorSeq, count, fetchWindow)
: walkForwardHistory(anchorSeq, count, fetchWindow);
? walkBackHistory(anchorSeq, count, fetchWindow, serverSequence)
: walkForwardHistory(anchorSeq, count, fetchWindow, serverSequence);
}
/**
* Fetch the latest private history page without relying on a locally cached
* sequence. C2C field-5 sequences are sender-local, so only SsoGetRoamMsg's
* timestamp cursor can safely bootstrap an unanchored conversation.
*/
async getC2cLatestHistory(
friendUid: string,
count: number,
selfUin = 0,
beforeTime = Math.floor(Date.now() / 1000) + 1,
): Promise<FriendMessage[]> {
if (!friendUid) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
const collected = new Map<number, FriendMessage>();
let cursor = { time: beforeTime, random: 0 };
const seenCursors = new Set<string>([`${cursor.time}:${cursor.random}`]);
let reachedEnd = false;
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want; i++) {
await throttleHistory();
const page = await fetchC2cRoamMessagePage(
this.ctx,
this.ctx.identity,
selfUin,
friendUid,
cursor.time,
want - collected.size,
cursor.random,
);
for (const message of page.messages) {
const sequence = message.ntMsgSeq ?? 0;
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error(`private roam history returned invalid NT sequence ${String(sequence)}`);
}
collected.set(sequence, message);
}
if (collected.size >= want) break;
if (page.cursor.time === 0 && page.cursor.random === 0) {
reachedEnd = true;
break;
}
const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`;
if (seenCursors.has(nextCursorKey)) {
if (page.messages.length === 0) {
reachedEnd = true;
break;
}
throw new Error(
`private roam history cursor did not advance from ${cursor.time}/${cursor.random}`,
);
}
seenCursors.add(nextCursorKey);
cursor = page.cursor;
}
if (collected.size < want && !reachedEnd) {
throw new Error(
`private roam history request budget exhausted after ${HISTORY_MAX_REQUESTS} pages `
+ `(requested=${want}, collected=${collected.size})`,
);
}
return [...collected.values()]
.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time)
.slice(-want);
}
/**
@@ -848,16 +935,16 @@ export class MessageApi {
}
/**
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
* conversation peer. Returns the matching `friend_message`, or null.
* Fetch a single c2c message by its exact conversation-wide NT sequence —
* `SsoGetC2cMsg` over a 1-wide `[seq, seq]` range, through the same throttle
* gate. Sender-local reply/recall sequences must not be passed here.
*/
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
if (!friendUid || !(seq > 0)) return null;
await throttleHistory();
try {
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
return batch.find((m) => m.msgSeq === seq) ?? null;
return batch.find((m) => m.ntMsgSeq === seq) ?? null;
} catch {
return null;
}
@@ -6,14 +6,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
return { ...actual, fetchGroupMessageRange: vi.fn(), fetchC2cMessageRange: vi.fn() };
return {
...actual,
fetchGroupMessageRange: vi.fn(),
fetchC2cMessageRange: vi.fn(),
fetchC2cRoamMessagePage: vi.fn(),
};
});
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import {
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
fetchGroupMessageRange,
} from '@snowluma/protocol/msg-push';
import { MessageApi } from '../src/bridge/apis/message';
const mockFetch = vi.mocked(fetchGroupMessageRange);
const mockC2cFetch = vi.mocked(fetchC2cMessageRange);
const mockC2cRoamFetch = vi.mocked(fetchC2cRoamMessagePage);
function gm(seq: number): any {
return {
@@ -32,6 +42,7 @@ describe('MessageApi history pagination', () => {
beforeEach(() => {
mockFetch.mockReset();
mockC2cFetch.mockReset();
mockC2cRoamFetch.mockReset();
vi.useFakeTimers();
});
afterEach(() => vi.useRealTimers());
@@ -90,13 +101,110 @@ describe('MessageApi history pagination', () => {
it('uses the same forward semantics for private history', async () => {
mockC2cFetch.mockImplementation(async (_s, _id, _self, _uid, start, end) => {
const out = [];
for (let s = start; s <= end; s++) out.push(gm(s));
for (let s = start; s <= end; s++) {
out.push({ ...gm(s + 10_000), kind: 'friend_message', ntMsgSeq: s });
}
return out;
});
const res = await runHistory(new MessageApi(ctx).getC2cHistory('u_friend', 300, 3, 0, false));
expect(res.map((message) => message.msgSeq)).toEqual([300, 301, 302]);
expect(res.map((message) => message.ntMsgSeq)).toEqual([300, 301, 302]);
});
it('fetches the latest private page by timestamp without inventing a sequence anchor', async () => {
mockC2cRoamFetch.mockResolvedValue({
cursor: { time: 0, random: 0 },
messages: [
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000002 },
{ ...gm(32743), kind: 'friend_message', ntMsgSeq: 63214, time: 1700000001 },
],
} as any);
const result = await runHistory(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1700000100),
);
expect(mockC2cRoamFetch).toHaveBeenCalledWith(
ctx,
ctx.identity,
10001,
'u_friend',
1700000100,
20,
0,
);
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214]);
expect(mockC2cFetch).not.toHaveBeenCalled();
});
it('follows the private roam cursor until the requested count is filled', async () => {
mockC2cRoamFetch
.mockResolvedValueOnce({
cursor: { time: 1700000000, random: 7 },
messages: [
{ ...gm(32744), kind: 'friend_message', ntMsgSeq: 63215, time: 1700000002 },
],
} as any)
.mockResolvedValueOnce({
cursor: { time: 1699999900, random: 8 },
messages: [
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000000 },
{ ...gm(32743), kind: 'friend_message', ntMsgSeq: 63214, time: 1700000001 },
],
} as any);
const result = await runHistory(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 3, 10001, 1700000100),
);
expect(mockC2cRoamFetch).toHaveBeenNthCalledWith(
1, ctx, ctx.identity, 10001, 'u_friend', 1700000100, 3, 0,
);
expect(mockC2cRoamFetch).toHaveBeenNthCalledWith(
2, ctx, ctx.identity, 10001, 'u_friend', 1700000000, 2, 7,
);
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214, 63215]);
});
it('rejects a stalled private roam cursor instead of returning a partial page', async () => {
mockC2cRoamFetch.mockResolvedValue({
cursor: { time: 1700000100, random: 0 },
messages: [
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000000 },
],
} as any);
const assertion = expect(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 2, 10001, 1700000100),
).rejects.toThrow('cursor did not advance');
await vi.runAllTimersAsync();
await assertion;
});
it('rejects a partial private page when the request budget is exhausted', async () => {
let page = 0;
mockC2cRoamFetch.mockImplementation(async () => {
page++;
return {
cursor: { time: 1700000100 - page, random: page },
messages: [
{
...gm(32000 + page),
kind: 'friend_message',
ntMsgSeq: 63000 + page,
time: 1700000100 - page,
},
],
} as any;
});
const assertion = expect(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1700000200),
).rejects.toThrow('request budget exhausted');
await vi.runAllTimersAsync();
await assertion;
expect(mockC2cRoamFetch).toHaveBeenCalledTimes(12);
});
it('stops forward pagination at the unsigned sequence ceiling', async () => {
@@ -780,6 +780,8 @@ describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
expect(event.kind).toBe('friend_recall');
expect(event.userUin).toBe(77777);
expect(event.msgSeq).toBe(4242);
expect(event.clientSeq).toBe(4242);
expect(event.recalledBySelf).toBe(false);
});
it('subType 139 picks toUid as the peer (we recalled our msg sent to friend)', () => {
@@ -791,6 +793,7 @@ describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
expect(event.kind).toBe('friend_recall');
expect(event.userUin).toBe(77777); // resolved from toUid (the friend), not fromUid (us)
expect(event.recalledBySelf).toBe(true);
});
});
+4 -2
View File
@@ -3247,7 +3247,7 @@
{
"name": "get_friend_msg_history",
"aliases": [],
"summary": "获取好友消息历史",
"summary": "获取好友消息历史(无锚点时从服务器获取最新双向记录)",
"returns": "{ messages }:好友消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。",
"returnsSchema": {
"type": "object",
@@ -3294,7 +3294,8 @@
"type": "integer",
"minimum": 0
},
"default": 20
"default": 20,
"desc": "无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存"
},
{
"name": "reverse_order",
@@ -3324,6 +3325,7 @@
"count": {
"type": "integer",
"minimum": 0,
"description": "无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存",
"default": 20
},
"reverse_order": {
+4 -2
View File
@@ -3250,7 +3250,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_friend_msg_history",
"aliases": [],
"summary": "获取好友消息历史",
"summary": "获取好友消息历史(无锚点时从服务器获取最新双向记录)",
"returns": "{ messages }:好友消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。",
"returnsSchema": {
"type": "object",
@@ -3297,7 +3297,8 @@ export const ACTIONS: CatalogAction[] = [
"type": "integer",
"minimum": 0
},
"default": 20
"default": 20,
"desc": "无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存"
},
{
"name": "reverse_order",
@@ -3327,6 +3328,7 @@ export const ACTIONS: CatalogAction[] = [
"count": {
"type": "integer",
"minimum": 0,
"description": "无锚点时从 QQ 服务器获取最新双向历史;服务器或身份解析失败时动作失败,不返回不完整的本地缓存",
"default": 20
},
"reverse_order": {
+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' } }],
+4 -6
View File
@@ -222,11 +222,9 @@ export interface SrcMsg {
troopName?: pb<11, bytes>;
}
// Decoded content of SrcMsg.pbReserve(8). For a c2c (friend) reply the
// canonical replied-to sequence lives here as `friendSequence`, NOT in
// `origSeqs` (which carries the per-sender clientSequence). Lagrange resolves an
// incoming reply as `Sequence = reserve.FriendSequence ?? OrigSeqs[0]`
// (dev/Lagrange.Core/.../SourceMsg.PbPreserve.cs ProtoMember(8)).
// Decoded content of SrcMsg.pbReserve(8). `friendSequence` is a friendship-side
// counter observed in QQNT, not the conversation-wide C2C NT message sequence;
// private reply resolution therefore uses SrcMsg.origSeqs plus direction/time.
export interface SrcMsgPbReserve {
receiverUid?: pb<7, string>;
friendSequence?: pb<8, uint_32>;
@@ -436,4 +434,4 @@ export interface Preserve {
senderUid?: pb<6, string>;
receiverUid?: pb<7, string>;
clientSequence?: pb<8, uint_32>;
}
}
+21 -2
View File
@@ -1,8 +1,9 @@
import type { pb, pb_repeated, uint_32 } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton';
import type { PushMsgBody } from './message';
// trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg — fetch private (c2c)
// message history from the server by sequence range. Reference: Lagrange.Core
// message history from the server by conversation-wide NT sequence range.
// Reference: Lagrange.Core
// Internal/Service/Message/GetC2cMessageService.cs + Packets/Message/Action/
// SsoGetC2cMsg(.Response).cs. The peer is the friend's UID (not uin); the
// response carries the same `PushMsgBody` shape as a live message.
@@ -17,3 +18,21 @@ export interface SsoGetC2cMsgResponse {
friendUid?: pb<4, string>;
messages?: pb_repeated<7, PushMsgBody>;
}
// trpc.msg.register_proxy.RegisterProxy.SsoGetRoamMsg — fetch private
// history before a timestamp cursor. This is QQ's latest-page C2C history
// endpoint; unlike SsoGetC2cMsg it does not require a locally known sequence.
export interface SsoGetRoamMsg {
friendUid?: pb<1, string>;
time?: pb<2, uint_32>;
random?: pb<3, uint_32>;
count?: pb<4, uint_32>;
direction?: pb<5, bool>;
}
export interface SsoGetRoamMsgResponse {
friendUid?: pb<3, string>;
timestamp?: pb<5, uint_32>;
random?: pb<6, uint_32>;
messages?: pb_repeated<7, PushMsgBody>;
}
+4
View File
@@ -52,6 +52,10 @@ export interface ContentHead {
sequence?: pb<5, uint_32>;
timestamp?: pb<6, uint_32>;
field7?: pb<7, uint_64>;
/** Conversation-wide C2C sequence. Unlike field 5, this advances across
* messages sent by either participant and is the sequence accepted by
* SsoGetC2cMsg. It is absent on group messages. */
ntMsgSeq?: pb<11, uint_32>;
newId?: pb<12, uint_64>;
}
+15
View File
@@ -235,7 +235,14 @@ export interface FriendMessage extends QQEvent {
* index can preserve the exact C2C peer instead of re-resolving its UIN. */
senderUid?: string;
senderNick: string;
/** Sender-local sequence exposed as OneBot message_seq and used by replies. */
msgSeq: number;
/** Bidirectional C2C sequence used for history/actions and canonical message ids. */
ntMsgSeq?: number;
/** Sender-local sequence used by private recall requests. */
clientSeq?: number;
/** False only when an older packet omitted ContentHead field 11. */
sequenceAuthoritative?: boolean;
msgId: number;
elements: MessageElement[];
}
@@ -263,6 +270,9 @@ export interface TempMessage extends QQEvent {
groupId: number;
senderNick: string;
msgSeq: number;
ntMsgSeq?: number;
clientSeq?: number;
sequenceAuthoritative?: boolean;
elements: MessageElement[];
}
@@ -314,7 +324,12 @@ export interface GroupAdminEvent extends QQEvent {
export interface FriendRecall extends QQEvent {
kind: 'friend_recall';
userUin: number;
/** Legacy alias retained for converters; this is the sender-local sequence. */
msgSeq: number;
/** Sender-local sequence carried by the recall protocol. */
clientSeq?: number;
/** True for subtype 139, where the logged-in account recalled its own send. */
recalledBySelf?: boolean;
}
export interface GroupRecallEvent extends QQEvent {
@@ -13,7 +13,10 @@ export interface MsgPushHead {
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: number;
readonly timestamp: number;
readonly msgId: number;
}
@@ -68,6 +71,7 @@ export function buildContextFromMessage(
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
@@ -173,6 +173,8 @@ function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
return [ev];
}
@@ -27,6 +27,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
// Stash the approval msgseq from a private group-invite card so a later
// `set_group_add_request` can approve a bot self-invite (issue #125).
for (const el of elements) {
@@ -43,6 +44,9 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: '',
@@ -3,12 +3,16 @@ import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
@@ -1,6 +1,13 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type {
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
} from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { isBlankMessage, isC2cControlPush } from './blank-filter';
@@ -8,6 +15,9 @@ import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
export const SSO_GET_C2C_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg';
export const SSO_GET_ROAM_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetRoamMsg';
const log = createLogger('MsgPush.C2CHistory');
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -15,9 +25,52 @@ interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
export interface C2cRoamPage {
messages: FriendMessage[];
cursor: { time: number; random: number };
}
function requirePacketResponse(result: SendPacketResult, command: string): Uint8Array {
if (!result.success) {
throw new Error(`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
}
function decodeC2cMessages(
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
): FriendMessage[] {
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
}
if (isC2cControlPush(ctx.head)) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') continue;
if (isBlankMessage(ev.elements, ctx.body)) continue;
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence `
+ `(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
return out;
}
/**
* Fetch one [startSeq, endSeq] window of private (c2c) history from the server
* via `SsoGetC2cMsg`, decoding each returned message with the regular friend
* Fetch one [startSeq, endSeq] NT-sequence window of private (c2c) history from
* the server via `SsoGetC2cMsg`, decoding each returned message with the regular friend
* decoder. `friendUid` is the conversation peer's UID. Returns `friend_message`
* events sorted oldest→newest by sequence. One packet per call — the caller
* owns chunking/throttling.
@@ -39,24 +92,76 @@ export async function fetchC2cMessageRange(
});
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
if (!res.success || !res.gotResponse || !res.responseData) return [];
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(res.responseData);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
const messages = decoded?.messages ?? [];
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message' || ev.msgSeq <= 0) continue;
// Drop C2C control/system signals and content-less pushes (the "[空消息]"
// phantom, #102) just as QQ NT does on its roam/history fetch — keep
// history parity with live (parseMsgPush).
if (isC2cControlPush(ctx.head) || isBlankMessage(ev.elements, ctx.body)) continue;
out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
}
/**
* Fetch one timestamp-cursor page of C2C roaming history. QQ uses this endpoint
* for an unanchored latest page; it returns messages from both participants.
*/
export async function fetchC2cRoamMessagePage(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
): Promise<C2cRoamPage> {
if (!friendUid) throw new Error('SsoGetRoamMsg friend uid is required');
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
}
+27 -2
View File
@@ -26,7 +26,13 @@ import { SysMsgDedup } from './sysmsg-dedup';
export { SysMsgDedup } from './sysmsg-dedup';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history';
export {
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
} from './fetch-c2c-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -90,6 +96,21 @@ function describeUndecodedBody(body: PushMsgBody | undefined): string {
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message')
&& ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
}
export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
@@ -111,7 +132,10 @@ export function parseMsgPush(
}
return false;
}
if ((ev as { elements?: unknown[] }).elements?.length !== 0) return true;
if ((ev as { elements?: unknown[] }).elements?.length !== 0) {
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
}
// Empty-element message that's NOT a known control cmd. Drop it when the body
// is genuinely empty (a content-less push we don't yet classify by c2cCmd).
// If instead the body *had* content we just couldn't decode, keep the
@@ -121,6 +145,7 @@ export function parseMsgPush(
log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType,
describeUndecodedBody(ctx.body));
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
}
return false;
@@ -395,22 +395,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
);
}
// Reply / quote. For a c2c (friend) reply the canonical replied-to sequence
// is the srcMsg reserve's `friendSequence`, NOT `origSeqs[0]` — origSeqs
// carries the per-sender clientSequence, which doesn't match how the
// original message is keyed (by its server/private sequence), so resolving
// the reply (and get_msg on the quoted message) would miss. Mirrors
// Lagrange's `Sequence = reserve.FriendSequence ?? OrigSeqs[0]`
// (ForwardEntity.cs). Group replies keep origSeqs[0] (the shared group seq).
// Reply / quote. `origSeqs[0]` is the shared group sequence for groups and
// the quoted sender's local client sequence for C2C. The latter is not the
// conversation-wide NT sequence used by private history/message ids, so the
// OneBot layer resolves it with peer + sender direction + quote time.
if (elem.srcMsg) {
// The reply resolves to srcMsg.origSeqs[0] — for BOTH group (shared group
// seq) and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals
// the quoted message's head.sequence, i.e. the seq its message_id is
// hashed from. reserve.friendSequence is a small friend-relationship
// counter that does NOT match (e.g. 25 vs a head.sequence of 12707), so
// the earlier `friendSequence` override made reply.id != the quoted
// message_id: get_msg(reply_id) missed and a quoted File's content came
// back empty.
// On-target capture (#114 / #124) also proved reserve.friendSequence is a
// small friend-relationship counter, not either usable message sequence.
const src = elem.srcMsg;
const replySeq = src.origSeqs?.[0] ?? 0;
if (replySeq > 0) {
@@ -39,12 +39,13 @@ describe('parseMsgPush — empty message drop (#102)', () => {
it('keeps a friend message that actually has content', () => {
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: { msgType: 166, subType: 0, sequence: 100, timestamp: 1781540572, msgId: 1 },
contentHead: { msgType: 166, subType: 0, sequence: 32743, ntMsgSeq: 63214, timestamp: 1781540572, msgId: 1 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
}), identity);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({
kind: 'friend_message', senderUid: 'u_x', elements: [{ type: 'text', text: 'hi' }],
kind: 'friend_message', senderUid: 'u_x', msgSeq: 32743, ntMsgSeq: 63214, clientSeq: 32743,
elements: [{ type: 'text', text: 'hi' }],
});
});
@@ -5,9 +5,19 @@
import { describe, expect, it } from 'vitest';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type {
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
} from '@snowluma/proto-defs/get-c2c-msg';
import type { IdentityService } from '../../src/identity-service';
import { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from '../../src/msg-push';
import {
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
} from '../../src/msg-push';
const identity = { findFriend: () => undefined } as unknown as IdentityService;
@@ -40,17 +50,17 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
messages: [
{
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 },
contentHead: { msgType: 166, sequence: 9120, ntMsgSeq: 120, timestamp: 1700000120, msgId: 7120 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
},
{
responseHead: { fromUin: 111, forward: { friendName: 'Alice' } },
contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 },
contentHead: { msgType: 166, sequence: 9110, ntMsgSeq: 110, timestamp: 1700000110, msgId: 7110 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
},
{
responseHead: { fromUin: 10001, toUin: 333, forward: { friendName: 'Self' } },
contentHead: { msgType: 166, sequence: 115, timestamp: 1700000115, msgId: 7115 },
contentHead: { msgType: 166, sequence: 9115, ntMsgSeq: 115, timestamp: 1700000115, msgId: 7115 },
body: { richText: { elems: [{ text: { str: 'sent' } }] } },
},
],
@@ -59,12 +69,12 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
const out = await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120);
expect(out.map((m) => m.msgSeq)).toEqual([110, 115, 120]); // sorted ascending
expect(out.map((m) => m.ntMsgSeq)).toEqual([110, 115, 120]); // sorted by server sequence
expect(out.every((m) => m.kind === 'friend_message')).toBe(true);
expect(out.every((m) => m.selfUin === 10001)).toBe(true);
expect(out[0]).toMatchObject({ msgSeq: 110, senderUin: 111, senderNick: 'Alice' });
expect(out[1]).toMatchObject({ msgSeq: 115, senderUin: 10001, peerUin: 333, senderNick: 'Self' });
expect(out[2]).toMatchObject({ msgSeq: 120, senderUin: 222, senderNick: 'Bob' });
expect(out[0]).toMatchObject({ msgSeq: 9110, ntMsgSeq: 110, clientSeq: 9110, senderUin: 111, senderNick: 'Alice' });
expect(out[1]).toMatchObject({ msgSeq: 9115, ntMsgSeq: 115, clientSeq: 9115, senderUin: 10001, peerUin: 333, senderNick: 'Self' });
expect(out[2]).toMatchObject({ msgSeq: 9120, ntMsgSeq: 120, clientSeq: 9120, senderUin: 222, senderNick: 'Bob' });
});
it('drops content-less blank messages, keeps real ones (#102 parity)', async () => {
@@ -73,24 +83,45 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
messages: [
{ // genuinely-blank control push (the invite phantom) → dropped
responseHead: { fromUin: 111, forward: { friendName: 'Alice' } },
contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 },
contentHead: { msgType: 166, sequence: 9110, ntMsgSeq: 110, timestamp: 1700000110, msgId: 7110 },
body: { richText: { elems: [] } },
},
{ // real message → kept
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 },
contentHead: { msgType: 166, sequence: 9120, ntMsgSeq: 120, timestamp: 1700000120, msgId: 7120 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
},
],
});
const out = await fetchC2cMessageRange({ sendRawPacket: async () => okResult(resp) }, identity, 10001, 'u_friend', 100, 120);
expect(out.map((m) => m.msgSeq)).toEqual([120]);
expect(out.map((m) => m.ntMsgSeq)).toEqual([120]);
expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] });
});
it('returns [] on a failed packet, empty uid, or out-of-range request', async () => {
it('rejects a visible message without the canonical NT sequence', async () => {
const resp = protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_friend',
messages: [{
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
contentHead: { msgType: 166, sequence: 9120, timestamp: 1700000120, msgId: 7120 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
}],
});
await expect(fetchC2cMessageRange(
{ sendRawPacket: async () => okResult(resp) },
identity,
10001,
'u_friend',
100,
120,
)).rejects.toThrow('canonical NT sequence');
});
it('surfaces a failed packet, while invalid input is rejected before sending', async () => {
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
expect(await fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120)).toEqual([]);
await expect(fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120))
.rejects.toThrow('SsoGetC2cMsg');
let sent = false;
const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } };
@@ -99,3 +130,56 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
expect(sent).toBe(false);
});
});
describe('fetchC2cRoamMessagePage / SsoGetRoamMsg', () => {
it('encodes the timestamp cursor and orders both sides by canonical NT sequence', async () => {
let captured: { cmd: string; body: Uint8Array } | null = null;
const response = protobuf_encode<SsoGetRoamMsgResponse>({
friendUid: 'u_friend',
timestamp: 1700000000,
random: 77,
messages: [
{
responseHead: { fromUin: 10001, toUin: 222, forward: { friendName: 'Self' } },
contentHead: { msgType: 166, sequence: 32743, ntMsgSeq: 63214, timestamp: 1700000001, msgId: 20 },
body: { richText: { elems: [{ text: { str: 'out' } }] } },
},
{
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
contentHead: { msgType: 166, sequence: 32742, ntMsgSeq: 63213, timestamp: 1700000002, msgId: 10 },
body: { richText: { elems: [{ text: { str: 'in' } }] } },
},
],
});
const sender = {
sendRawPacket: async (cmd: string, body: Uint8Array) => {
captured = { cmd, body };
return okResult(response);
},
};
const page = await fetchC2cRoamMessagePage(
sender, identity, 10001, 'u_friend', 1700000100, 20, 9,
);
expect(captured!.cmd).toBe(SSO_GET_ROAM_MSG_CMD);
const request = protobuf_decode<SsoGetRoamMsg>(captured!.body);
expect(request).toMatchObject({
friendUid: 'u_friend',
time: 1700000100,
random: 9,
count: 20,
direction: true,
});
expect(page.cursor).toEqual({ time: 1700000000, random: 77 });
expect(page.messages.map((message) => ({
sender: message.senderUin,
sequence: message.ntMsgSeq,
messageSequence: message.msgSeq,
clientSequence: message.clientSeq,
}))).toEqual([
{ sender: 222, sequence: 63213, messageSequence: 32742, clientSequence: 32742 },
{ sender: 10001, sequence: 63214, messageSequence: 32743, clientSequence: 32743 },
]);
});
});