fix(file): route group publish through OIDB 0x6d9_4 and cache upload meta for c2c resend

The chat-publish step after upload_group_file used to ship a PbSendMsg
with a transElem(elemType=24) — but that wire shape is RECEIVE-side
only, and current QQ-NT rejects it on send with `result=79`. Lagrange.
Core V2 uses a dedicated `OidbSvcTrpcTcp.0x6d9_4` for the publish
(`GroupSendFileService.cs`); mirror that. Send_group_msg with a
`{type:'file', file_id}` segment now routes through the same path
after the OneBot layer splits file segments out (matching the c2c
file split pattern).

Separately, send_private_msg with just `{file_id}` was shipping a 0 B
file because the wire packet for c2c file send needs fileSize/fileMd5/
fileName/fileHash but the OneBot caller only echoes the file_id from
upload_private_file. Add a bounded (1024-entry, FIFO) bridge cache
populated at upload time so the send-message path can rehydrate the
full tuple; inline segment fields still take precedence so callers
that track the metadata themselves can bypass the cache. Parser now
also accepts `file_hash`/`fileHash` on file segments.

Also: file segments no longer get a `[空消息]` log line — the format
string now shows `[文件:<name-or-id>]`.
This commit is contained in:
DrSmoothl committed 2026-05-20 13:30:13 +08:00
1 parent 6de2e071be
commit c83c333e73
12 files changed
+634 -158

No files matched your search

+10 -1
View File
@@ -26,11 +26,17 @@ export interface MockBridge {
resolveUserUid: ReturnType<typeof vi.fn>;
// High-level message senders. Default to no-op resolves so actions
// that fire off a follow-up chat message after their main work
// (e.g. `upload_group_file` → `sendGroupMessage` to publish the
// (e.g. `upload_group_file` → `sendGroupFileMessage` to publish the
// file in chat) don't crash test setups that don't care about it.
sendGroupMessage: ReturnType<typeof vi.fn>;
sendPrivateMessage: ReturnType<typeof vi.fn>;
sendC2cFileMessage: ReturnType<typeof vi.fn>;
sendGroupFileMessage: ReturnType<typeof vi.fn>;
// Uploaded-file metadata cache helpers — actions like uploadGroupFile
// / uploadPrivateFile call these to remember the upload, so tests
// covering those code paths get a default-no-op shim.
rememberUploadedFile: ReturnType<typeof vi.fn>;
recallUploadedFile: ReturnType<typeof vi.fn>;
}
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
@@ -59,6 +65,9 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendGroupFileMessage: vi.fn(async () => undefined),
rememberUploadedFile: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
...overrides,
};
}
+89 -16
View File
@@ -136,12 +136,14 @@ describe('actions/group-file', () => {
.rejects.toThrow(/code=999/);
});
it('uploadGroupFile publishes the file as a chat message after upload (the "empty message" regression)', async () => {
it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing
// `sendGroupMessage` the file never appears in the chat. Asserts
// that `bridge.sendGroupMessage` is invoked with a single
// `{type:'file'}` element pointing at the uploaded fileId.
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
// call the file never appears in the chat. Earlier attempts used
// PbSendMsg with a transElem(24) but the QQ-NT server rejects that
// with result=79 (transElem(24) is a receive-side decoding shape,
// not a send-side one). Asserts that `bridge.sendGroupFileMessage`
// is invoked with the uploaded fileId.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
@@ -149,15 +151,13 @@ describe('actions/group-file', () => {
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt');
expect(bridge.sendGroupMessage).toHaveBeenCalledOnce();
const [groupId, elements] = bridge.sendGroupMessage.mock.calls[0]!;
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(elements).toHaveLength(1);
expect(elements[0]).toMatchObject({
type: 'file',
fileId: 'fid-pub',
fileName: 'mynote.txt',
});
expect(fileId).toBe('fid-pub');
// sendGroupMessage must NOT be touched — the previous wire shape
// (PbSendMsg w/ transElem(24)) is the bug we're guarding against.
expect(bridge.sendGroupMessage).not.toHaveBeenCalled();
});
it('uploadGroupFile skips the chat post when uploadFile=false', async () => {
@@ -168,12 +168,12 @@ describe('actions/group-file', () => {
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false);
expect(bridge.sendGroupMessage).not.toHaveBeenCalled();
expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled();
});
it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
vi.mocked(bridge.sendGroupMessage).mockRejectedValueOnce(new Error('message rejected'));
vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected'));
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
@@ -181,7 +181,55 @@ describe('actions/group-file', () => {
);
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-tolerant' });
expect(bridge.sendGroupMessage).toHaveBeenCalledOnce();
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
});
it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => {
// After upload, a later `send_group_msg` carrying just the file_id
// needs to recover the name/size/md5 from somewhere. Production
// populates `bridge.rememberUploadedFile` with the full tuple.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
fileId: 'fid-cached',
scope: 'group',
groupId: 12345,
fileName: 'x.bin',
});
});
it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => {
// Direct cover of the new bridge method. The previous send-shape
// (PbSendMsg + transElem(24)) failed with result=79; this is the
// Lagrange-V2-mirrored fix.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array());
await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4');
// The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`.
expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith(
0x6D9, 4,
expect.objectContaining({
body: expect.objectContaining({
groupUin: 12345,
type: 2,
info: expect.objectContaining({
busiType: 102,
fileId: 'fid-publish',
field5: true,
}),
}),
}),
);
});
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
@@ -230,6 +278,31 @@ describe('actions/group-file', () => {
expect(bridge.sendPrivateMessage).not.toHaveBeenCalled();
});
it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => {
// C2C file resend (send_private_msg with just file_id) was the
// "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/
// fileName/fileHash, but the OneBot caller only knows the file_id.
// Caching the upload tuple lets the OneBot send-message path
// recover the rest via `bridge.recallUploadedFile(fileId)`.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
fileId: 'pfid-cache',
scope: 'private',
userId: 67890,
fileName: 'cache-me.txt',
fileHash: 'addon-hash',
});
});
it('uploadPrivateFile skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
+13 -41
View File
@@ -93,16 +93,18 @@ describe('element-builder / commonElem.businessType per scene', () => {
});
});
describe('element-builder / group file element wire shape', () => {
// Regression for the same `result=79` class: the GroupFileExtra outer
// wrapper was missing the magic `field1=6` + `fileName` slots and the
// inner GroupFileInfo had fileSha/extInfoString/fileMd5 shifted one
// tag to the left (5/6/7 instead of the correct 6/7/8). Both
// mistakes made the current QQ-NT server reject the chat post. This
// test decodes the element back through the proton-generated codec
// and asserts each field lands at the right tag.
it('encodes outer field1=6 + fileName, and inner fields at tags 6/7/8', async () => {
const [elem] = await buildSendElems(
describe('element-builder / file element is no longer carried in elems[]', () => {
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
// shape. The fix moves group-file publishing onto a dedicated OIDB
// call (`OidbSvcTrpcTcp.0x6d9_4`), driven from the OneBot layer in
// `modules/message-actions.ts::sendGroupMessage` after the file
// segment is split off. The element-builder therefore must NOT emit
// any element for `{type:'file'}` anymore — if it does, the message
// ships with a transElem(24) payload and result=79 returns.
it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => {
const result = await buildSendElems(
[{
type: 'file',
fileId: 'fid-abc',
@@ -113,36 +115,6 @@ describe('element-builder / group file element wire shape', () => {
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const transElem = (elem as any).transElem as { elemType: number; elemValue: Uint8Array };
expect(transElem.elemType).toBe(24);
// 0x01 prefix + BE16 length + payload
expect(transElem.elemValue[0]).toBe(0x01);
const len = (transElem.elemValue[1] << 8) | transElem.elemValue[2];
const payload = transElem.elemValue.subarray(3, 3 + len);
// Hand-walk the wire bytes to verify each tag lands where the
// server expects. Each varint tag = (field << 3) | wire_type:
// outer field1=6 → tag 8 (wire 0 / varint), value 6
// outer fileName → tag 18 (wire 2 / length-delimited), 'doc.txt'
// outer inner → tag 58 (field 7 wire 2)
// inner.info → tag 18 (field 2 wire 2)
// info.busId → tag 8 (field 1 wire 0), value 102
// info.fileId → tag 18 (field 2 wire 2)
// info.fileSize → tag 24 (field 3 wire 0), value 123
// info.fileName → tag 34 (field 4 wire 2)
// info.fileSha → tag 50 (field 6 wire 2) ← was 42 (field 5)
// info.extInfoString → tag 58 (field 7 wire 2) ← was 50 (field 6)
// info.fileMd5 → tag 66 (field 8 wire 2) ← was 58 (field 7)
const tagAt = (i: number) => payload[i];
expect(tagAt(0)).toBe(8); // outer field1 tag — regression: missing entirely before
expect(payload[1]).toBe(6); // value of field1 (NapCat hardcodes 6)
expect(tagAt(2)).toBe(18); // outer fileName tag — regression: missing
// Locate the inner GroupFileExtraInfo by scanning for tag 50 (was 42
// in the bug). A naive scan for `0x32` is enough because no string
// field happens to contain that byte in this test fixture.
expect(payload.includes(50)).toBe(true); // fileSha at tag 50 (field 6)
expect(payload.includes(58)).toBe(true); // extInfoString at tag 58 (field 7)
expect(payload.includes(66)).toBe(true); // fileMd5 at tag 66 (field 8)
expect(payload.includes(42)).toBe(false); // sanity: nothing at the old (wrong) tag for fileSha
expect(result).toEqual([]);
});
});
@@ -0,0 +1,120 @@
// Regression coverage for the group-file-in-send_group_msg bug.
//
// Symptom in the wild: bot uploaded a group file via `upload_group_file`,
// then sent `{type:'file', file_id}` through `send_group_msg`; the
// element-builder wrapped it as `transElem(elemType=24, ...)` inside
// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The
// QQ-NT server rejected the message with `result=79` because that wire
// shape is RECEIVE-side only (rich-body-decoder unpacks it into a
// FileEntity for inbound messages, but the server's intake validator
// flags it on the send side).
//
// Fix: split file segments off at the OneBot layer (same pattern as
// the c2c-file split for private messages) and dispatch through
// `bridge.sendGroupFileMessage`, which calls dedicated OIDB
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
// `GroupSendFileService.cs`.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
import { sendGroupMessage } from '../../src/onebot/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
describe('send_group_msg with {type:"file"} segment', () => {
it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => {
// Pure-file case — the elems[] path used to ship a transElem(24)
// and got result=79. The dedicated OIDB-0x6d9_4 route must take
// over for group file publishing.
const sendGroupMessage_bridge = vi.fn();
const sendGroupFileMessage = vi.fn(async () => undefined);
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('gfid-abc');
});
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn(async () => undefined);
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'here is the file:' } },
{ type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } },
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!;
expect(textGid).toBe(12345);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!;
expect(fileGid).toBe(12345);
expect(fileFileId).toBe('gfid-xyz');
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn();
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).not.toHaveBeenCalled();
});
});
@@ -50,10 +50,12 @@ describe('send_private_msg with {type:"file"} segment', () => {
const sendPrivateMessage_bridge = vi.fn();
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const recallUploadedFile = vi.fn(() => undefined);
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid,
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
@@ -77,6 +79,84 @@ describe('send_private_msg with {type:"file"} segment', () => {
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
});
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
// Reproduces the "0 B file" bug: a caller passes only `file_id` from
// a previous upload_private_file, with no size/md5/name. Without
// the cache lookup the wire packet ships fileSize=0/md5=empty and
// the recipient sees a 0-byte file. With the cache we recover the
// real tuple.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? {
fileId: 'uuid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'real-doc.pdf',
fileSize: 4096,
fileMd5: Buffer.from('aabbccddeeff', 'hex'),
fileSha1: new Uint8Array(20),
fileHash: 'srv-hash',
rememberedAt: 0,
} : undefined);
const bridge = fakeBridge({
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-cached' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileId: 'uuid-cached',
fileName: 'real-doc.pdf',
fileSize: 4096,
fileHash: 'srv-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex'));
});
it('inline segment fields take precedence over the upload cache', async () => {
// If the caller threads the metadata inline (e.g. they tracked the
// upload response themselves), honour that over the cache so a
// refresh of an evicted file still works.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn(() => ({
fileId: 'uuid-x',
scope: 'private' as const,
userId: 67890,
fileName: 'stale-cache-name.txt',
fileSize: 99,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'stale-hash',
rememberedAt: 0,
}));
const bridge = fakeBridge({
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
}] as any, false);
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileName: 'inline.txt',
fileSize: 200,
fileHash: 'inline-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
});
it('mixed file + text splits across two sends (text first, file second)', async () => {
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
@@ -85,6 +165,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid,
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
@@ -118,6 +199,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
@@ -141,6 +223,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => ''), // intentional empty
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);