fix(core): verify conversation read updates
Replace message-header sequence forwarding with a server-guided read flow for group and private conversations. Batch read reports conservatively, validate per-conversation results and cursor advancement, and fail with actionable errors when the server does not apply an update. Add regression coverage for mixed batches, pagination, already-current sessions, malformed responses, and private sequence-domain mismatches.
This commit is contained in:
@@ -4,9 +4,12 @@ import type {
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
C2CReadedReportResponseItem,
|
||||
C2CRecallRequest,
|
||||
GroupReadedReportResponseItem,
|
||||
GroupRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
@@ -14,6 +17,7 @@ import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, 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';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid } from './shared';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
@@ -27,9 +31,89 @@ import { resolveSelfUid } from './shared';
|
||||
import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
const READ_REPORT_CMD = 'trpc.msg.msg_svc.MsgService.SsoReadedReport';
|
||||
const READ_REPORT_BATCH_SIZE = 100;
|
||||
|
||||
const log = createLogger('Bridge.Message');
|
||||
|
||||
function decodeReadReportResponse(result: SendPacketResult, label: string): SsoReadedReportResp {
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || `${label} transport failed`);
|
||||
}
|
||||
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
|
||||
throw new Error(`${label} response is empty`);
|
||||
}
|
||||
|
||||
let response: SsoReadedReportResp;
|
||||
try {
|
||||
response = protobuf_decode<SsoReadedReportResp>(result.responseData);
|
||||
} catch (error) {
|
||||
throw new Error(`${label} response decode failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const resultCode = response.resultCode ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(response.errorMessage || `${label} failed with result code ${resultCode}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
interface C2CReadTarget {
|
||||
userId: number;
|
||||
uid: string;
|
||||
}
|
||||
|
||||
interface ReadResponseItem {
|
||||
resultCode?: number;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
function uniqueSessionIds(ids: readonly number[], label: string): number[] {
|
||||
const result: number[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const id of ids) {
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
throw new Error(`invalid ${label} read target ${String(id)}`);
|
||||
}
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
result.push(id);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function requireReadResponseItem<T extends ReadResponseItem>(
|
||||
items: readonly T[] | undefined,
|
||||
index: number,
|
||||
matches: (item: T) => boolean,
|
||||
label: string,
|
||||
): T {
|
||||
const item = items?.find(matches) ?? items?.[index];
|
||||
if (!item) throw new Error(`${label} response item is missing`);
|
||||
|
||||
const resultCode = item.resultCode ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(item.errorMessage || `${label} failed with result code ${resultCode}`);
|
||||
}
|
||||
if (!matches(item)) throw new Error(`${label} response identity does not match the request`);
|
||||
return item;
|
||||
}
|
||||
|
||||
function readUnsignedSequence(value: bigint | null | undefined, label: string): bigint {
|
||||
// Proton represents an omitted protobuf scalar as null; protobuf semantics
|
||||
// define that as the numeric default (zero), not a decode failure.
|
||||
if (value == null) return 0n;
|
||||
if (typeof value !== 'bigint' || value < 0n) throw new Error(`${label} is invalid`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requirePositiveSequence(value: bigint | null | undefined, label: string): bigint {
|
||||
const sequence = readUnsignedSequence(value, label);
|
||||
if (sequence === 0n) throw new Error(`${label} is missing`);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
@@ -454,48 +538,190 @@ export class MessageApi {
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
|
||||
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
|
||||
* NT client's own "scrolled to bottom" behaviour so subsequent
|
||||
* sync packets don't replay messages we've already processed.
|
||||
*/
|
||||
async markGroupRead(groupId: number, sequence: number): Promise<void> {
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
}
|
||||
/** Mark the entire group conversation read, matching QQ NT's setMsgRead(peer). */
|
||||
async markGroupRead(groupId: number): Promise<void> {
|
||||
await this.markAllRead([groupId], []);
|
||||
}
|
||||
|
||||
/** Mark the entire private conversation read, matching QQ NT's setMsgRead(peer). */
|
||||
async markPrivateRead(userId: number): Promise<void> {
|
||||
await this.markAllRead([], [userId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a c2c read-report. Same wire-cmd as the group variant but
|
||||
* keyed by friend uid (resolved from uin via IdentityService).
|
||||
* `lastReadTime` defaults to "now" — matches the QQ NT client
|
||||
* which also uses wall-clock seconds rather than the read-message
|
||||
* timestamp.
|
||||
* Mark every supplied conversation read through SsoReadedReport.
|
||||
*
|
||||
* Message-head sequences are not valid C2C read sequences. The first packet
|
||||
* therefore reports zero for every conversation and reads the server's
|
||||
* current read/latest pair from the response without moving the marker
|
||||
* backwards. A second packet advances only conversations that are behind.
|
||||
* QQ NT caps each packet at 100 C2C plus 100 group entries and waits for the
|
||||
* response before sending the next page; mirror that strictly here.
|
||||
*/
|
||||
async markPrivateRead(userId: number, sequence: number): Promise<void> {
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
async markAllRead(groupIds: readonly number[], privateUserIds: readonly number[]): Promise<void> {
|
||||
const groups = uniqueSessionIds(groupIds, 'group');
|
||||
const privateUsers = uniqueSessionIds(privateUserIds, 'private');
|
||||
const c2cTargets: C2CReadTarget[] = [];
|
||||
|
||||
// Keep UID resolution sequential. A cache miss may itself use the network,
|
||||
// so Promise.all here would reintroduce the burst this method is designed
|
||||
// to avoid.
|
||||
for (const userId of privateUsers) {
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
if (!uid) throw new Error(`failed to resolve uid for private read target ${userId}`);
|
||||
c2cTargets.push({ userId, uid });
|
||||
}
|
||||
|
||||
const totalBatches = Math.max(
|
||||
Math.ceil(groups.length / READ_REPORT_BATCH_SIZE),
|
||||
Math.ceil(c2cTargets.length / READ_REPORT_BATCH_SIZE),
|
||||
);
|
||||
if (totalBatches === 0) return;
|
||||
|
||||
log.debug(
|
||||
'mark-read start: groups=%d c2c=%d batches=%d',
|
||||
groups.length,
|
||||
c2cTargets.length,
|
||||
totalBatches,
|
||||
);
|
||||
|
||||
for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
|
||||
const start = batchIndex * READ_REPORT_BATCH_SIZE;
|
||||
await this.markReadBatch(
|
||||
groups.slice(start, start + READ_REPORT_BATCH_SIZE),
|
||||
c2cTargets.slice(start, start + READ_REPORT_BATCH_SIZE),
|
||||
batchIndex + 1,
|
||||
totalBatches,
|
||||
);
|
||||
}
|
||||
|
||||
log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length);
|
||||
}
|
||||
|
||||
private async sendReadReport(request: SsoReadedReportReq, label: string): Promise<SsoReadedReportResp> {
|
||||
log.debug(
|
||||
'%s send: groups=%d c2c=%d',
|
||||
label,
|
||||
request.groupList?.length ?? 0,
|
||||
request.c2cList?.length ?? 0,
|
||||
);
|
||||
const payload = protobuf_encode<SsoReadedReportReq>(request);
|
||||
const result = await this.ctx.sendRawPacket(READ_REPORT_CMD, payload);
|
||||
const response = decodeReadReportResponse(result, label);
|
||||
log.debug(
|
||||
'%s response: groups=%d c2c=%d',
|
||||
label,
|
||||
response.groupList?.length ?? 0,
|
||||
response.c2cList?.length ?? 0,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
private groupReadResponse(
|
||||
response: SsoReadedReportResp,
|
||||
groupId: number,
|
||||
index: number,
|
||||
label: string,
|
||||
): GroupReadedReportResponseItem {
|
||||
const groupUin = BigInt(groupId);
|
||||
return requireReadResponseItem(
|
||||
response.groupList,
|
||||
index,
|
||||
item => item.groupUin === groupUin,
|
||||
`${label} group ${groupId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private c2cReadResponse(
|
||||
response: SsoReadedReportResp,
|
||||
target: C2CReadTarget,
|
||||
index: number,
|
||||
label: string,
|
||||
): C2CReadedReportResponseItem {
|
||||
return requireReadResponseItem(
|
||||
response.c2cList,
|
||||
index,
|
||||
item => item.uid === target.uid,
|
||||
`${label} private user ${target.userId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async markReadBatch(
|
||||
groupIds: readonly number[],
|
||||
c2cTargets: readonly C2CReadTarget[],
|
||||
batchIndex: number,
|
||||
totalBatches: number,
|
||||
): Promise<void> {
|
||||
const batchLabel = `mark-read batch ${batchIndex}/${totalBatches}`;
|
||||
const probe = await this.sendReadReport({
|
||||
groupList: groupIds.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })),
|
||||
c2cList: c2cTargets.map(target => ({ uid: target.uid, lastReadTime: 0n, lastReadSeq: 0n })),
|
||||
}, `${batchLabel} probe`);
|
||||
|
||||
const groupList: NonNullable<SsoReadedReportReq['groupList']> = [];
|
||||
for (let i = 0; i < groupIds.length; i++) {
|
||||
const groupId = groupIds[i]!;
|
||||
const item = this.groupReadResponse(probe, groupId, i, `${batchLabel} probe`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} read sequence`);
|
||||
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} group ${groupId} latest sequence`);
|
||||
if (latestSeq < readSeq) {
|
||||
throw new Error(`${batchLabel} group ${groupId} latest sequence ${latestSeq} is before read sequence ${readSeq}`);
|
||||
}
|
||||
if (latestSeq > readSeq) groupList.push({ groupUin: BigInt(groupId), lastReadSeq: latestSeq });
|
||||
}
|
||||
|
||||
const c2cList: NonNullable<SsoReadedReportReq['c2cList']> = [];
|
||||
const c2cConfirmTargets: C2CReadTarget[] = [];
|
||||
for (let i = 0; i < c2cTargets.length; i++) {
|
||||
const target = c2cTargets[i]!;
|
||||
const item = this.c2cReadResponse(probe, target, i, `${batchLabel} probe`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} private user ${target.userId} read sequence`);
|
||||
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} private user ${target.userId} latest sequence`);
|
||||
if (latestSeq < readSeq) {
|
||||
throw new Error(
|
||||
`${batchLabel} private user ${target.userId} latest sequence ${latestSeq} is before read sequence ${readSeq}`,
|
||||
);
|
||||
}
|
||||
if (latestSeq > readSeq) {
|
||||
const lastMsgTime = requirePositiveSequence(
|
||||
item.lastMsgTime,
|
||||
`${batchLabel} private user ${target.userId} last message time`,
|
||||
);
|
||||
c2cList.push({ uid: target.uid, lastReadTime: lastMsgTime, lastReadSeq: latestSeq });
|
||||
c2cConfirmTargets.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
if (groupList.length === 0 && c2cList.length === 0) {
|
||||
log.debug('%s already current', batchLabel);
|
||||
return;
|
||||
}
|
||||
|
||||
const confirm = await this.sendReadReport({ groupList, c2cList }, `${batchLabel} confirm`);
|
||||
for (let i = 0; i < groupList.length; i++) {
|
||||
const requested = groupList[i]!;
|
||||
const groupId = Number(requested.groupUin);
|
||||
const item = this.groupReadResponse(confirm, groupId, i, `${batchLabel} confirm`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} confirmed read sequence`);
|
||||
if (readSeq < (requested.lastReadSeq ?? 0n)) {
|
||||
throw new Error(
|
||||
`${batchLabel} group ${groupId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < c2cList.length; i++) {
|
||||
const requested = c2cList[i]!;
|
||||
const target = c2cConfirmTargets[i]!;
|
||||
const item = this.c2cReadResponse(confirm, target, i, `${batchLabel} confirm`);
|
||||
const readSeq = readUnsignedSequence(
|
||||
item.readSeq,
|
||||
`${batchLabel} private user ${target.userId} confirmed read sequence`,
|
||||
);
|
||||
if (readSeq < (requested.lastReadSeq ?? 0n)) {
|
||||
throw new Error(
|
||||
`${batchLabel} private user ${target.userId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,4 +784,3 @@ export class MessageApi {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface MockMessageApi {
|
||||
recallPrivate: ReturnType<typeof vi.fn>;
|
||||
markGroupRead: ReturnType<typeof vi.fn>;
|
||||
markPrivateRead: ReturnType<typeof vi.fn>;
|
||||
markAllRead: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
export function mockMessageApi(): MockMessageApi {
|
||||
@@ -38,6 +39,7 @@ export function mockMessageApi(): MockMessageApi {
|
||||
recallPrivate: vi.fn(async () => undefined),
|
||||
markGroupRead: vi.fn(async () => undefined),
|
||||
markPrivateRead: vi.fn(async () => undefined),
|
||||
markAllRead: vi.fn(async () => undefined),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,11 @@
|
||||
// and #6 commit 6 absorbed setEssence into InteractionApi.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
SsoReadedReportReq,
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
@@ -16,6 +21,16 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
import { MessageApi } from '../../src/bridge/apis/message';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function readReportResult(response: SsoReadedReportResp) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SsoReadedReportResp>(response)),
|
||||
};
|
||||
}
|
||||
|
||||
describe('apis/message — recall + markRead', () => {
|
||||
beforeEach(() => {
|
||||
// No global mock state to reset — sendRawPacket is per-bridge.
|
||||
@@ -51,16 +66,151 @@ describe('apis/message — recall + markRead', () => {
|
||||
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
|
||||
});
|
||||
|
||||
it('markGroupRead and markPrivateRead both hit SsoReadedReport', async () => {
|
||||
const bridge = mockBridge();
|
||||
const api = new MessageApi(bridge as any);
|
||||
await api.markGroupRead(12345, 50);
|
||||
await api.markPrivateRead(10001, 60);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
const cmds = bridge.sendRawPacket.mock.calls.map((c: any) => c[0]);
|
||||
expect(cmds).toEqual([
|
||||
it('probes and confirms group plus private reads in the same packets', async () => {
|
||||
const sendRawPacket = vi.fn()
|
||||
.mockResolvedValueOnce(readReportResult({
|
||||
groupList: [{ groupUin: 1081372778n, readSeq: 66569n, latestSeq: 66629n }],
|
||||
c2cList: [{
|
||||
uid: 'resolved-uid',
|
||||
readSeq: 160n,
|
||||
latestSeq: 171n,
|
||||
lastMsgTime: 1783952859n,
|
||||
}],
|
||||
}))
|
||||
.mockResolvedValueOnce(readReportResult({
|
||||
groupList: [{ groupUin: 1081372778n, readSeq: 66629n, latestSeq: 66629n }],
|
||||
c2cList: [{
|
||||
uid: 'resolved-uid',
|
||||
readSeq: 171n,
|
||||
latestSeq: 171n,
|
||||
lastMsgTime: 1783952859n,
|
||||
}],
|
||||
}));
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new MessageApi(bridge as any).markAllRead([1081372778], [10001]);
|
||||
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
expect(sendRawPacket.mock.calls.map((call: any) => call[0])).toEqual([
|
||||
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
|
||||
'trpc.msg.msg_svc.MsgService.SsoReadedReport',
|
||||
]);
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
|
||||
|
||||
const probeBytes = sendRawPacket.mock.calls[0]![1];
|
||||
expect(Buffer.from(probeBytes).toString('hex')).toBe(
|
||||
'0a0608eae0d18304120e120c7265736f6c7665642d756964',
|
||||
);
|
||||
const probe = protobuf_decode<SsoReadedReportReq>(probeBytes);
|
||||
expect(probe).toEqual({
|
||||
groupList: [{ groupUin: 1081372778n, lastReadSeq: null }],
|
||||
c2cList: [{ uid: 'resolved-uid', lastReadTime: null, lastReadSeq: null }],
|
||||
});
|
||||
|
||||
const confirm = protobuf_decode<SsoReadedReportReq>(sendRawPacket.mock.calls[1]![1]);
|
||||
expect(confirm).toEqual({
|
||||
groupList: [{ groupUin: 1081372778n, lastReadSeq: 66629n }],
|
||||
c2cList: [{
|
||||
uid: 'resolved-uid',
|
||||
lastReadTime: 1783952859n,
|
||||
lastReadSeq: 171n,
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it('does not send a confirm packet when every read marker is current', async () => {
|
||||
const sendRawPacket = vi.fn(async () => readReportResult({
|
||||
groupList: [{ groupUin: 12345n, readSeq: 50n, latestSeq: 50n }],
|
||||
}));
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new MessageApi(bridge as any).markGroupRead(12345);
|
||||
|
||||
expect(sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('markGroupRead rejects a transport success with no business response', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new MessageApi(bridge as any).markGroupRead(12345))
|
||||
.rejects.toThrow(/response is empty/);
|
||||
});
|
||||
|
||||
it('markGroupRead surfaces the per-group business error', async () => {
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => readReportResult({
|
||||
groupList: [{ resultCode: 100000010, errorMessage: 'send group msg failed, ret:2' }],
|
||||
})),
|
||||
});
|
||||
await expect(new MessageApi(bridge as any).markGroupRead(1))
|
||||
.rejects.toThrow(/send group msg failed, ret:2/);
|
||||
});
|
||||
|
||||
it('rejects a top-level success when the private read marker did not advance', async () => {
|
||||
const sendRawPacket = vi.fn()
|
||||
.mockResolvedValueOnce(readReportResult({
|
||||
c2cList: [{
|
||||
uid: 'resolved-uid',
|
||||
readSeq: 160n,
|
||||
latestSeq: 171n,
|
||||
lastMsgTime: 1783952859n,
|
||||
}],
|
||||
}))
|
||||
.mockResolvedValueOnce(readReportResult({
|
||||
c2cList: [{
|
||||
uid: 'resolved-uid',
|
||||
readSeq: 160n,
|
||||
latestSeq: 171n,
|
||||
lastMsgTime: 1783952859n,
|
||||
}],
|
||||
}));
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await expect(new MessageApi(bridge as any).markPrivateRead(10001))
|
||||
.rejects.toThrow(/confirmed sequence 160 before requested 171/);
|
||||
});
|
||||
|
||||
it('caps mixed read reports at 100 + 100 and confirms each page before probing the next', async () => {
|
||||
const sendRawPacket = vi.fn(async (_cmd: string, body: Uint8Array) => {
|
||||
const request = protobuf_decode<SsoReadedReportReq>(body);
|
||||
return readReportResult({
|
||||
groupList: request.groupList?.map(item => {
|
||||
const requested = item.lastReadSeq ?? 0n;
|
||||
return {
|
||||
groupUin: item.groupUin,
|
||||
readSeq: requested,
|
||||
latestSeq: requested === 0n ? 1n : requested,
|
||||
};
|
||||
}),
|
||||
c2cList: request.c2cList?.map(item => {
|
||||
const requested = item.lastReadSeq ?? 0n;
|
||||
return {
|
||||
uid: item.uid,
|
||||
readSeq: requested,
|
||||
latestSeq: requested === 0n ? 1n : requested,
|
||||
lastMsgTime: 1700000000n,
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
const resolveUserUid = vi.fn(async (userId: number) => `uid-${userId}`);
|
||||
const bridge = mockBridge({ sendRawPacket, resolveUserUid });
|
||||
const groups = Array.from({ length: 101 }, (_, i) => 1000 + i);
|
||||
const users = Array.from({ length: 101 }, (_, i) => 2000 + i);
|
||||
|
||||
await new MessageApi(bridge as any).markAllRead(groups, users);
|
||||
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(4);
|
||||
const requests = sendRawPacket.mock.calls.map((call: any) =>
|
||||
protobuf_decode<SsoReadedReportReq>(call[1]));
|
||||
expect(requests.map(request => [request.groupList?.length, request.c2cList?.length])).toEqual([
|
||||
[100, 100],
|
||||
[100, 100],
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
]);
|
||||
expect(requests[0]!.groupList![0]!.lastReadSeq).toBeNull();
|
||||
expect(requests[1]!.groupList![0]!.lastReadSeq).toBe(1n);
|
||||
expect(requests[2]!.groupList![0]!.lastReadSeq).toBeNull();
|
||||
expect(requests[3]!.groupList![0]!.lastReadSeq).toBe(1n);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -370,7 +370,7 @@ export const actions = [
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||
}
|
||||
|
||||
await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence);
|
||||
await ctx.bridge.apis.message.markGroupRead(meta.targetId);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
@@ -392,7 +392,7 @@ export const actions = [
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
|
||||
}
|
||||
|
||||
await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence);
|
||||
await ctx.bridge.apis.message.markPrivateRead(meta.targetId);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
@@ -413,9 +413,9 @@ export const actions = [
|
||||
}
|
||||
|
||||
if (meta.isGroup) {
|
||||
await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence);
|
||||
await ctx.bridge.apis.message.markGroupRead(meta.targetId);
|
||||
} else {
|
||||
await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence);
|
||||
await ctx.bridge.apis.message.markPrivateRead(meta.targetId);
|
||||
}
|
||||
return okResponse();
|
||||
},
|
||||
|
||||
@@ -289,6 +289,34 @@ describe('extended-actions / history accepts negative message_id', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / mark conversation read', () => {
|
||||
it('uses a group message only to identify the conversation', async () => {
|
||||
const markGroupRead = vi.fn(async () => undefined);
|
||||
const bridge = fakeBridge({ apis: { message: { markGroupRead } } });
|
||||
const ctx = fakeCtx(bridge, {
|
||||
getMessageMeta: () => fakeMeta({ targetId: 12345, sequence: 42708 }),
|
||||
});
|
||||
|
||||
const res = await makeHandler(ctx).handle('mark_group_msg_as_read', { message_id: 1 });
|
||||
|
||||
expect(markGroupRead).toHaveBeenCalledWith(12345);
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
});
|
||||
|
||||
it('routes a private message to the C2C read implementation without forwarding its header sequence', async () => {
|
||||
const markPrivateRead = vi.fn(async () => undefined);
|
||||
const bridge = fakeBridge({ apis: { message: { markPrivateRead } } });
|
||||
const ctx = fakeCtx(bridge, {
|
||||
getMessageMeta: () => fakeMeta({ isGroup: false, targetId: 1787882683, sequence: 42708 }),
|
||||
});
|
||||
|
||||
const res = await makeHandler(ctx).handle('mark_private_msg_as_read', { message_id: 1 });
|
||||
|
||||
expect(markPrivateRead).toHaveBeenCalledWith(1787882683);
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: nc_get_packet_status / nc_get_rkey ───
|
||||
|
||||
describe('extended-actions / nc_get_packet_status', () => {
|
||||
|
||||
Reference in New Issue
Block a user