diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index ccfa2e6d..72f15d35 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -10,7 +10,7 @@ import type { } from '@snowluma/proto-defs/oidb-actions/base'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events'; -import { fetchGroupMessageRange } from '@snowluma/protocol/msg-push'; +import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; // `Bridge` is imported as a type only so we can narrow `ctx` back to @@ -26,6 +26,7 @@ import type { Bridge, SendMessageReceipt } from '../bridge'; const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; type GroupMessage = Extract; +type FriendMessage = Extract; // ── Group-history fetch guards (the server frequency-limits / kicks abusive // pulls, so keep each request small, bound the loop, and space the sends). ── @@ -50,6 +51,47 @@ function throttleHistory(): Promise { return run; } +/** + * Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide + * windows ending at `endSeq`, throttled, walking strictly backward (handling a + * server-side short cap via the oldest sequence actually returned), dedup by + * sequence, until `count` (capped) is gathered or the floor is reached. Returns + * the newest `want` items oldest→newest. + */ +async function walkBackHistory( + endSeq: number, + count: number, + fetchWindow: (startSeq: number, endSeq: number) => Promise, +): Promise { + if (!(endSeq > 0)) return []; + const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + + const collected = new Map(); // dedup by sequence + let curEnd = endSeq; + for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) { + const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1); + await throttleHistory(); + let batch: T[]; + try { + batch = await fetchWindow(start, curEnd); + } catch { + break; // network/decode error — return whatever we have so far + } + if (batch.length > 0) { + let minSeq = curEnd; + for (const ev of batch) { + collected.set(ev.msgSeq, ev); + if (ev.msgSeq < minSeq) minSeq = ev.msgSeq; + } + 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); + return all.slice(-want); // newest `want`, oldest→newest +} + export class MessageApi { constructor(private readonly ctx: BridgeContext) { } @@ -363,37 +405,22 @@ export class MessageApi { * kicked). Returns decoded `group_message` events oldest→newest. */ async getGroupHistory(groupUin: number, endSeq: number, count: number, selfUin = 0): Promise { - if (!(groupUin > 0) || !(endSeq > 0)) return []; - const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + if (!(groupUin > 0)) return []; + return walkBackHistory(endSeq, count, (start, end) => + fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end)); + } - const collected = new Map(); // dedup by sequence - let curEnd = endSeq; - for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) { - const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1); - await throttleHistory(); - let batch: GroupMessage[]; - try { - batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, curEnd); - } catch { - break; // network/decode error — return whatever we have so far - } - if (batch.length > 0) { - let minSeq = curEnd; - for (const ev of batch) { - collected.set(ev.msgSeq, ev); - if (ev.msgSeq < minSeq) minSeq = ev.msgSeq; - } - // Continue strictly below the OLDEST sequence the server actually - // returned — covers the case where the server caps a window short. - curEnd = minSeq - 1; - } else { - // Empty window (a gap of recalled/absent seqs) — skip past it. - curEnd = start - 1; - } - } - - const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq); - return all.slice(-want); // newest `want`, oldest→newest + /** + * Fetch real private (c2c) history from the server (`SsoGetC2cMsg`), ending + * at and including `endSeq`. Same rate-limit + data-volume guards as the + * group variant (they share the throttle gate). `friendUid` is the + * conversation peer's UID. Returns decoded `friend_message` events + * oldest→newest. + */ + async getC2cHistory(friendUid: string, endSeq: number, count: number, selfUin = 0): Promise { + if (!friendUid) return []; + return walkBackHistory(endSeq, count, (start, end) => + fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end)); } } diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index 92f5d371..61541b4c 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -26,7 +26,7 @@ import { deleteMessage, forwardSingleMessage, getForwardMessage, - getFriendMsgHistory, + getFriendHistory, getGroupHistory, sendGroupForwardMessage, sendGroupMessage, @@ -77,7 +77,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId), handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason), getGroupMsgHistory: (groupId, messageId, count) => getGroupHistory(ref, groupId, messageId, count), - getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count), + getFriendMsgHistory: (userId, messageId, count) => getFriendHistory(ref, userId, messageId, count), handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge), getDownloadRKeys: () => getDownloadRKeys(bridge), sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta), diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index ec06ac81..b41ae29e 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -65,7 +65,7 @@ export async function getFriendMsgHistory( } // Deps the server-backed history fetch needs from the instance context. -interface GroupHistoryRef { +interface HistoryRef { bridge: BridgeInterface; messageStore: MessageStore; converterCtx: ConverterContext; @@ -82,7 +82,7 @@ interface GroupHistoryRef { * fetch is unavailable or empty. */ export async function getGroupHistory( - ref: GroupHistoryRef, + ref: HistoryRef, groupId: number, messageId: number | undefined, count: number | undefined, @@ -110,8 +110,8 @@ export async function getGroupHistory( for (const ev of events) { const json = await convertEvent(ref.converterCtx, ev); if (!json || json.message_type !== 'group') continue; - persistGroupHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing - out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path) + persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing + out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path) } if (out.length > 0) return out; } catch (err) { @@ -122,12 +122,77 @@ export async function getGroupHistory( return getGroupMsgHistory(ref.messageStore, groupId, messageId, count); } -function persistGroupHistoryEvent(store: MessageStore, event: JsonObject): void { +/** + * 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. Falls back to the + * local store on unknown anchor / no uid / empty / error. + */ +export async function getFriendHistory( + ref: HistoryRef, + userId: number, + messageId: number | undefined, + count: number | undefined, +): Promise { + if (!Number.isInteger(userId) || userId <= 0) return []; + const want = normalizeHistoryCount(count); + + let anchorSeq = 0; + if (Number.isInteger(messageId) && messageId !== 0) { + const meta = ref.messageStore.findMeta(messageId as number); + // A c2c conversation seq is shared across both directions, but self-sent + // messages are keyed under our own uin — so accept any private anchor by + // sequence rather than requiring targetId === userId. + if (!meta || meta.isGroup || meta.sequence <= 0) { + return getFriendMsgHistory(ref.messageStore, userId, messageId, count); + } + anchorSeq = meta.sequence; + } else { + // Latest observed *inbound* message from this friend (self-sent messages + // are keyed under our own uin, not the recipient, so the store can't give + // "latest sent to this friend"). The c2c sequence is shared across both + // directions, so the fetch window around this anchor still includes recent + // self-sent messages — only ones strictly newer than the last inbound are + // missed on the unparameterized first page (a paged client catches up). + const latest = ref.messageStore.listSessionEvents(false, userId, 1); + anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0; + } + + 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); + const out: JsonObject[] = []; + for (const ev of events) { + const json = await convertEvent(ref.converterCtx, ev); + if (!json || json.message_type !== 'private') continue; + persistHistoryEvent(ref.messageStore, json); + out.push(sanitizeMessageEventForApi(json)); + } + if (out.length > 0) return out; + } + } catch (err) { + log.warn('friend history server fetch failed (%s); using local store', err instanceof Error ? err.message : String(err)); + } + } + + return getFriendMsgHistory(ref.messageStore, userId, messageId, count); +} + +// Persist a converted history event so reply / get_msg / future listing resolve +// it — keyed exactly like the live pipeline (group → group_id, private → the +// sender uin carried in user_id). +function persistHistoryEvent(store: MessageStore, event: JsonObject): void { const messageId = toHistInt(event.message_id); - const sessionId = toHistInt(event.group_id); + if (messageId === 0) return; + const isGroup = event.message_type === 'group'; + const sessionId = isGroup ? toHistInt(event.group_id) : toHistInt(event.user_id); const sequence = toHistInt(event.message_seq); - if (messageId === 0 || sessionId === 0) return; - store.storeEvent(messageId, true, sessionId, sequence, GROUP_MESSAGE_EVENT, event); + const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; + if (sessionId === 0) return; + store.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event); } function toHistInt(value: unknown): number { diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 31560d77..9576f6d1 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -35,6 +35,10 @@ "types": "./src/get-group-msg.ts", "default": "./src/get-group-msg.ts" }, + "./get-c2c-msg": { + "types": "./src/get-c2c-msg.ts", + "default": "./src/get-c2c-msg.ts" + }, "./notify": { "types": "./src/notify.ts", "default": "./src/notify.ts" diff --git a/packages/proto-defs/src/get-c2c-msg.ts b/packages/proto-defs/src/get-c2c-msg.ts new file mode 100644 index 00000000..b27508db --- /dev/null +++ b/packages/proto-defs/src/get-c2c-msg.ts @@ -0,0 +1,19 @@ +import type { pb, pb_repeated, uint_32 } 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 +// 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. + +export interface SsoGetC2cMsg { + friendUid?: pb<2, string>; + startSequence?: pb<3, uint_32>; + endSequence?: pb<4, uint_32>; +} + +export interface SsoGetC2cMsgResponse { + friendUid?: pb<4, string>; + messages?: pb_repeated<7, PushMsgBody>; +} diff --git a/packages/proto-defs/src/index.ts b/packages/proto-defs/src/index.ts index 0f92fba6..890bc78a 100644 --- a/packages/proto-defs/src/index.ts +++ b/packages/proto-defs/src/index.ts @@ -26,6 +26,7 @@ export type * from './element.js'; export type * from './longmsg.js'; export type * from './message.js'; export type * from './get-group-msg.js'; +export type * from './get-c2c-msg.js'; export type * from './notify.js'; export type * from './oidb.js'; export type * from './oidb-action.js'; diff --git a/packages/protocol/src/msg-push/fetch-c2c-history.ts b/packages/protocol/src/msg-push/fetch-c2c-history.ts new file mode 100644 index 00000000..9b08986c --- /dev/null +++ b/packages/protocol/src/msg-push/fetch-c2c-history.ts @@ -0,0 +1,56 @@ +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 { QQEventVariant } from '../events'; +import type { IdentityService } from '../identity-service'; +import { buildContextFromMessage } from './context'; +import { decodeFriendMessage } from './decoders/friend-message'; + +export const SSO_GET_C2C_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg'; + +type FriendMessage = Extract; + +interface RawSender { + sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; +} + +/** + * Fetch one [startSeq, endSeq] 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. + */ +export async function fetchC2cMessageRange( + sender: RawSender, + identity: IdentityService, + selfUin: number, + friendUid: string, + startSeq: number, + endSeq: number, +): Promise { + if (!friendUid || !(endSeq > 0) || startSeq > endSeq) return []; + + const req = protobuf_encode({ + friendUid, + startSequence: startSeq, + endSequence: endSeq, + }); + + const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req); + if (!res.success || !res.gotResponse || !res.responseData) return []; + + const decoded = protobuf_decode(res.responseData); + 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) out.push(ev); + } + } + out.sort((a, b) => a.msgSeq - b.msgSeq); + return out; +} diff --git a/packages/protocol/src/msg-push/index.ts b/packages/protocol/src/msg-push/index.ts index d9132170..711a16a9 100644 --- a/packages/protocol/src/msg-push/index.ts +++ b/packages/protocol/src/msg-push/index.ts @@ -19,6 +19,7 @@ import { PkgType } from './enums'; import { MsgPushRegistry } from './registry'; export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history'; +export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history'; export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; diff --git a/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts b/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts new file mode 100644 index 00000000..8c438b06 --- /dev/null +++ b/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts @@ -0,0 +1,74 @@ +// Round-trips the SsoGetC2cMsg request/response protos (proton codegen + field +// tags) and the fetched private-history decode path (each returned PushMsgBody +// re-uses the regular friend decoder). + +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 { IdentityService } from '../../src/identity-service'; +import { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from '../../src/msg-push'; + +const identity = { findFriend: () => undefined } as unknown as IdentityService; + +function okResult(data: Uint8Array): SendPacketResult { + return { success: true, gotResponse: true, responseData: data } as SendPacketResult; +} + +describe('fetchC2cMessageRange / SsoGetC2cMsg', () => { + it('sends the right command and request field tags', async () => { + let captured: { cmd: string; body: Uint8Array } | null = null; + const sender = { + sendRawPacket: async (cmd: string, body: Uint8Array) => { + captured = { cmd, body }; + return okResult(protobuf_encode({ friendUid: 'u_friend', messages: [] })); + }, + }; + + await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120); + + expect(captured!.cmd).toBe(SSO_GET_C2C_MSG_CMD); + const req = protobuf_decode(captured!.body); + expect(req.friendUid).toBe('u_friend'); + expect(req.startSequence).toBe(100); + expect(req.endSequence).toBe(120); + }); + + it('decodes returned friend messages (seq/sender/self uin), oldest→newest', async () => { + const resp = protobuf_encode({ + friendUid: 'u_friend', + messages: [ + { + responseHead: { fromUin: 222, forward: { friendName: 'Bob' } }, + contentHead: { msgType: 166, sequence: 120, timestamp: 1700000120, msgId: 7120 }, + body: { richText: { elems: [] } }, + }, + { + responseHead: { fromUin: 111, forward: { friendName: 'Alice' } }, + contentHead: { msgType: 166, sequence: 110, timestamp: 1700000110, msgId: 7110 }, + body: { richText: { elems: [] } }, + }, + ], + }); + const sender = { sendRawPacket: async () => okResult(resp) }; + + const out = await fetchC2cMessageRange(sender, identity, 10001, 'u_friend', 100, 120); + + expect(out.map((m) => m.msgSeq)).toEqual([110, 120]); // sorted ascending + 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: 120, senderUin: 222, senderNick: 'Bob' }); + }); + + it('returns [] on a failed packet, empty uid, or out-of-range request', async () => { + const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) }; + expect(await fetchC2cMessageRange(failSender, identity, 10001, 'u_x', 100, 120)).toEqual([]); + + let sent = false; + const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } }; + expect(await fetchC2cMessageRange(guardSender, identity, 10001, '', 100, 120)).toEqual([]); // empty uid + expect(await fetchC2cMessageRange(guardSender, identity, 10001, 'u_x', 200, 100)).toEqual([]); // start > end + expect(sent).toBe(false); + }); +});