diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index 50274258..250aab5d 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,7 +1,7 @@ import type { Bridge } from '@snowluma/core/bridge'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; -import type { ApiActionContext, MessageSendResult } from './api-handler'; +import type { ApiActionContext } from './api-handler'; import type { ConverterContext } from './event-converter'; import type { MediaStore } from './media-store'; import type { MessageStore } from './message-store'; @@ -59,12 +59,6 @@ export interface OneBotInstanceContext { export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { const { bridge, messageStore, mediaStore, reactionStore } = ref; - const reportSelfSent = async (result: Promise) => { - const settled = await result; - if (settled.echoEvent) ref.dispatchEvent(settled.echoEvent, 'send'); - return settled; - }; - return { bridge, @@ -77,10 +71,16 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { ), canSendImage: () => true, canSendRecord: () => true, - sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => + sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage( + ref, + userId, + message, + autoEscape, + tempGroupId, tempGroupId === undefined - ? reportSelfSent(sendPrivateMessage(ref, userId, message, autoEscape)) - : sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId), + ? (event) => ref.dispatchEvent(event, 'send') + : undefined, + ), sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape), deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta), getFriendList: () => getFriendList(bridge), diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 02c31e72..58cd6261 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -848,6 +848,8 @@ export async function sendPrivateMessage( autoEscape: boolean, /** When set, reply into this group's temp session instead of friend c2c. */ tempGroupId?: number, + /** Reports each actual friend message as soon as its authoritative receipt arrives. */ + onSelfSent?: (event: JsonObject) => void, ): Promise { // A temp-session reply is only allowed into a session the peer opened. const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId); @@ -943,8 +945,9 @@ export async function sendPrivateMessage( // here — video/ARK/ptt already go through commonElem so the // element-builder handles them inline. // Two sub-paths: - // a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile() - // b) has file_id from a prior upload_private_file → sendC2cFile() only + // a) has url/path but no file_id → uploadPrivate() without publishing, + // followed by sendC2cFile() so the Action retains the send receipt + // b) has file_id from a prior upload_private_file → sendC2cFile() directly let allFileElements = elements.filter(e => e.type === 'file'); let nonFileElements = elements.filter(e => e.type !== 'file'); let fileTargetUid: string | null = null; @@ -983,11 +986,29 @@ export async function sendPrivateMessage( ? ref.bridge.apis.message.sendGroupTempMessage(userId, tempGroupId, elems) : ref.bridge.apis.message.sendPrivate(userId, elems); - let lastReceipt: Awaited> | undefined; + type PrivateReceipt = Awaited>; + let lastResult: MessageSendResult | undefined; + const finalizeBatch = async ( + receipt: PrivateReceipt, + batchElements: MessageElement[], + ): Promise => { + const result = await finalizeSend( + ref, + false, + userId, + receipt, + batchElements, + tempGroupId === undefined && onSelfSent !== undefined, + ); + lastResult = result; + if (result.echoEvent) onSelfSent?.(result.echoEvent); + }; + if (nonFileElements.length > 0) { try { - lastReceipt = await sendText(nonFileElements); + const receipt = await sendText(nonFileElements); logSentMessage(false, userId, nonFileElements); + await finalizeBatch(receipt, nonFileElements); } catch (err) { // A temp-session reply can't fall back to the c2c file path (friend-only) // — surface the original error rather than mis-routing. @@ -1003,8 +1024,9 @@ export async function sendPrivateMessage( nonFileElements = remaining; if (fileEls.length > 0) await ensureFileTargetUid(); if (nonFileElements.length > 0) { - lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); + const receipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); logSentMessage(false, userId, nonFileElements); + await finalizeBatch(receipt, nonFileElements); } } } @@ -1015,21 +1037,43 @@ export async function sendPrivateMessage( const userUid = await ensureFileTargetUid(); for (const fileEl of allFileElements) { if (fileEl.url && !fileEl.fileId) { - // uploadPrivate() already calls sendC2cFile() internally — do NOT call it again. const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file'; - await ref.bridge.apis.groupFile.uploadPrivate(userId, fileEl.url, name, true); - logSentMessage(false, userId, [fileEl]); - if (!lastReceipt) { - lastReceipt = { messageId: 0, sequence: 0, clientSequence: 0, random: 0, timestamp: Math.floor(Date.now() / 1000) }; + // Upload and publish are separate here so the Action keeps the real + // PbSendMsg receipt. Letting uploadPrivate publish internally discards + // that receipt, which makes a reliable message_sent event impossible + // and can turn a failed chat post into an apparently successful send. + const uploaded = await ref.bridge.apis.groupFile.uploadPrivate( + userId, + fileEl.url, + name, + true, + false, + ); + if (!uploaded.fileId) { + throw new Error('private file upload returned no file_id'); } + const cached = ref.bridge.recallUploadedFile(uploaded.fileId); + if (!cached || cached.scope !== 'private' || cached.userId !== userId) { + throw new Error(`private file upload metadata missing for file_id ${uploaded.fileId}`); + } + const receipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { + fileId: uploaded.fileId, + fileName: cached.fileName, + fileSize: cached.fileSize, + fileMd5: cached.fileMd5, + fileHash: uploaded.fileHash ?? cached.fileHash, + }); + logSentMessage(false, userId, [fileEl]); + await finalizeBatch(receipt, [fileEl]); } else if (fileEl.fileId) { const cached = ref.bridge.recallUploadedFile(fileEl.fileId); const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0)); const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; const fileHash = fileEl.fileHash ?? cached?.fileHash; - lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash }); + const receipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash }); logSentMessage(false, userId, [fileEl]); + await finalizeBatch(receipt, [fileEl]); } else { throw new MessageElementValidationError( 'MISSING_FIELD', @@ -1039,13 +1083,8 @@ export async function sendPrivateMessage( } } } - if (!lastReceipt) throw new Error('message is empty'); - - // Dedicated C2C file sends may split one Action into several QQ messages. - // A single synthetic event would misrepresent that wire behaviour, so only - // report the one-batch friend path handled by sendPrivate(). - const reportEcho = tempGroupId === undefined && allFileElements.length === 0; - return finalizeSend(ref, false, userId, lastReceipt, elements, reportEcho); + if (!lastResult) throw new Error('message is empty'); + return { messageId: lastResult.messageId }; } export async function sendGroupMessage( diff --git a/packages/onebot/tests/self-sent-events.test.ts b/packages/onebot/tests/self-sent-events.test.ts index 1c849104..dad56e37 100644 --- a/packages/onebot/tests/self-sent-events.test.ts +++ b/packages/onebot/tests/self-sent-events.test.ts @@ -15,23 +15,51 @@ const RECEIPT = { random: 123456, timestamp: 1_700_000_000, }; +type Receipt = typeof RECEIPT; -function makeContext(receipt = RECEIPT): { +function makeContext(receiptOrReceipts: Receipt | Receipt[] = RECEIPT): { ctx: OneBotInstanceContext; dispatchEvent: ReturnType void>>; events: Map; } { + const receipts = Array.isArray(receiptOrReceipts) ? receiptOrReceipts : [receiptOrReceipts]; + let receiptIndex = 0; + const nextReceipt = () => { + const receipt = receipts[receiptIndex++]; + if (!receipt) throw new Error('unexpected extra private send'); + return receipt; + }; const events = new Map(); const dispatchEvent = vi.fn<(event: JsonObject) => void>(); const bridge = { identity: { nickname: 'SnowLuma' }, apis: { message: { - sendPrivate: vi.fn(async () => receipt), - sendGroupTempMessage: vi.fn(async () => receipt), + sendPrivate: vi.fn(async () => nextReceipt()), + sendGroupTempMessage: vi.fn(async () => nextReceipt()), + sendC2cFile: vi.fn(async () => nextReceipt()), + }, + groupFile: { + uploadPrivate: vi.fn(async () => ({ + fileId: 'uploaded-file-uuid', + fileHash: 'uploaded-file-hash', + })), }, }, resolveUserUid: vi.fn(async () => 'u_peer'), + recallUploadedFile: vi.fn((fileId: string) => fileId === 'uploaded-file-uuid' + ? { + fileId, + scope: 'private', + userId: PEER_ID, + fileName: 'inline.txt', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'uploaded-file-hash', + rememberedAt: Date.now(), + } + : undefined), } as unknown as BridgeInterface; const ctx = { @@ -134,6 +162,149 @@ describe('OneBot self-sent events', () => { }), 'send'); }); + it('reports a private file sent through an action', async () => { + const { ctx, dispatchEvent } = makeContext(); + const api = buildApiContext(ctx); + + const result = await api.sendPrivateMessage(PEER_ID, [{ + type: 'file', + data: { + file_id: 'file-uuid', + name: 'report.txt', + size: 128, + md5: '00112233445566778899aabbccddeeff', + }, + }], false); + + expect(result.messageId).not.toBe(0); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({ + post_type: 'message_sent', + message_type: 'private', + self_id: SELF_ID, + user_id: SELF_ID, + target_id: PEER_ID, + message: [expect.objectContaining({ + type: 'file', + data: expect.objectContaining({ + file_id: 'file-uuid', + file: 'report.txt', + file_size: 128, + }), + })], + }), 'send'); + }); + + it('reports a private file uploaded and sent through an action', async () => { + const { ctx, dispatchEvent } = makeContext(); + const api = buildApiContext(ctx); + + await api.sendPrivateMessage(PEER_ID, [{ + type: 'file', + data: { + file: 'base64://AQID', + name: 'inline.txt', + }, + }], false); + + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({ + post_type: 'message_sent', + message_type: 'private', + target_id: PEER_ID, + message: [expect.objectContaining({ + type: 'file', + data: expect.objectContaining({ + file: 'inline.txt', + url: 'base64://AQID', + }), + })], + }), 'send'); + }); + + it('reports each QQ message produced by a mixed private action', async () => { + const fileReceipt: Receipt = { + messageId: 654321, + sequence: 88, + clientSequence: 10, + random: 654321, + timestamp: RECEIPT.timestamp + 1, + }; + const { ctx, dispatchEvent } = makeContext([RECEIPT, fileReceipt]); + const api = buildApiContext(ctx); + + const result = await api.sendPrivateMessage(PEER_ID, [ + { type: 'text', data: { text: 'attachment:' } }, + { + type: 'file', + data: { + file_id: 'mixed-file-uuid', + name: 'mixed.txt', + size: 64, + md5: '00112233445566778899aabbccddeeff', + }, + }, + ], false); + + expect(dispatchEvent).toHaveBeenCalledTimes(2); + expect(dispatchEvent.mock.calls[0]?.[0]).toMatchObject({ + post_type: 'message_sent', + message_seq: RECEIPT.clientSequence, + message: [{ type: 'text', data: { text: 'attachment:' } }], + }); + expect(dispatchEvent.mock.calls[1]?.[0]).toMatchObject({ + post_type: 'message_sent', + message_seq: fileReceipt.clientSequence, + message: [{ + type: 'file', + data: expect.objectContaining({ file_id: 'mixed-file-uuid' }), + }], + }); + expect(result.messageId).toBe(hashMessageIdInt32( + fileReceipt.sequence, + PEER_ID, + PRIVATE_NT_MESSAGE_EVENT, + )); + }); + + it('reports each file in a multi-file private action separately', async () => { + const secondReceipt: Receipt = { + messageId: 654321, + sequence: 88, + clientSequence: 10, + random: 654321, + timestamp: RECEIPT.timestamp + 1, + }; + const { ctx, dispatchEvent } = makeContext([RECEIPT, secondReceipt]); + const api = buildApiContext(ctx); + + await api.sendPrivateMessage(PEER_ID, [ + { + type: 'file', + data: { + file_id: 'first-file', + name: 'first.txt', + size: 1, + md5: '00112233445566778899aabbccddeeff', + }, + }, + { + type: 'file', + data: { + file_id: 'second-file', + name: 'second.txt', + size: 2, + md5: 'ffeeddccbbaa00998877665544332211', + }, + }, + ], false); + + expect(dispatchEvent).toHaveBeenCalledTimes(2); + expect(dispatchEvent.mock.calls.map(([event]) => + ((event.message as JsonObject[])[0]?.data as JsonObject)?.file_id, + )).toEqual(['first-file', 'second-file']); + }); + it('does not report a later QQ echo after the action event', () => { const { dispatch, emitEvent, stored } = makeInstanceHarness(); const sentEvent = privateSentEvent(); diff --git a/packages/onebot/tests/send-private-c2c-file.test.ts b/packages/onebot/tests/send-private-c2c-file.test.ts index 3f2868a0..e3b2d6f8 100644 --- a/packages/onebot/tests/send-private-c2c-file.test.ts +++ b/packages/onebot/tests/send-private-c2c-file.test.ts @@ -250,18 +250,27 @@ describe('send_private_msg with {type:"file"} segment', () => { expect(sendC2cFileMessage).not.toHaveBeenCalled(); }); - it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => { - // uploadPrivate() internally calls sendC2cFile() — must NOT call it again. + it('file segment with url uploads without publishing, then sends once with the cached metadata', async () => { const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) => - ({ fileId: 'auto-fid', fileHash: null })); - const sendC2cFileMessage = vi.fn(); + ({ fileId: 'auto-fid', fileHash: 'auto-hash' })); + const sendC2cFileMessage = vi.fn(async () => goodReceipt); const bridge = fakeBridge({ apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage }, groupFile: { uploadPrivate }, } as any, resolveUserUid: vi.fn(async () => 'u_peer'), - recallUploadedFile: vi.fn(() => undefined), + recallUploadedFile: vi.fn(() => ({ + fileId: 'auto-fid', + scope: 'private', + userId: 67890, + fileName: 'audio.wav', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'auto-hash', + rememberedAt: Date.now(), + })), } as any); const ctx = makeCtx(bridge); @@ -275,7 +284,56 @@ describe('send_private_msg with {type:"file"} segment', () => { expect(src).toBe('/tmp/audio.wav'); expect(name).toBe('audio.wav'); expect(doUpload).toBe(true); - // sendC2cFile must NOT be called — uploadPrivate() handles it internally - expect(sendC2cFileMessage).not.toHaveBeenCalled(); + expect(uploadPrivate).toHaveBeenCalledWith(67890, '/tmp/audio.wav', 'audio.wav', true, false); + expect(sendC2cFileMessage).toHaveBeenCalledOnce(); + expect(sendC2cFileMessage).toHaveBeenCalledWith(67890, 'u_peer', expect.objectContaining({ + fileId: 'auto-fid', + fileName: 'audio.wav', + fileSize: 3, + fileHash: 'auto-hash', + })); + }); + + it('surfaces a failed chat post after uploading a file source', async () => { + const uploadPrivate = vi.fn(async () => ({ + fileId: 'uploaded-but-unsent', + fileHash: 'upload-hash', + })); + const sendC2cFile = vi.fn(async () => { + throw new Error('chat post rejected'); + }); + const bridge = fakeBridge({ + apis: { + message: { sendPrivate: vi.fn(), sendC2cFile }, + groupFile: { uploadPrivate }, + } as any, + resolveUserUid: vi.fn(async () => 'u_peer'), + recallUploadedFile: vi.fn(() => ({ + fileId: 'uploaded-but-unsent', + scope: 'private', + userId: 67890, + fileName: 'failed.txt', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'upload-hash', + rememberedAt: Date.now(), + })), + } as any); + const ctx = makeCtx(bridge); + + await expect(sendPrivateMessage(ctx, 67890, [{ + type: 'file', + data: { file: 'base64://AQID', name: 'failed.txt' }, + }] as any, false)).rejects.toThrow('chat post rejected'); + + expect(uploadPrivate).toHaveBeenCalledWith( + 67890, + 'base64://AQID', + 'failed.txt', + true, + false, + ); + expect(sendC2cFile).toHaveBeenCalledOnce(); }); });