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

@@ -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' } }],