fix(protocol): preserve private voice playback on older clients

Keep private voice messages playable on older clients while retaining the existing voice message for current clients. Cover the reported upload response in a regression test.

Refs #614
This commit is contained in:
DrSmoothl committed 2026-10-31 18:28:05 +08:00
1 parent eb119ecb92
commit a557bf72e7
11 files changed
+223 -39

No files matched your search

+6 -10
View File
@@ -8,7 +8,7 @@ import type {
SsoReadedReportReq,
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import { datalineTextFromElements, encodeDatalineText } from '@snowluma/protocol/dataline/codec';
@@ -22,7 +22,7 @@ import {
fetchC2cRoamMessagePage,
fetchGroupMessageRange,
} from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { type bytes, 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';
@@ -548,15 +548,15 @@ export class MessageApi {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, {
bridge: this.ctx as unknown as Bridge,
const richText = await encodePrivateRichText(elements, {
bridge: this.ctx,
userUid,
scene: 'direct-private',
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const request = protobuf_encode<SendMessageRequest>({
const request = protobuf_encode<SendMessageRequest<bytes>>({
routingHead: {
c2c: {
uin: userUin,
@@ -568,11 +568,7 @@ export class MessageApi {
subType: 0,
c2cCmd: 11,
},
messageBody: {
richText: {
elems: protoElems,
},
},
messageBody: { richText },
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
@@ -6,7 +6,7 @@ import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPtt: vi.fn() }));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
describe('forward metadata through upload and cached reads', () => {
@@ -33,7 +33,7 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array() })),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
@@ -2,7 +2,11 @@ import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type {
SendMessageRequest,
SendMessageResponse,
SendRichText,
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
@@ -10,6 +14,9 @@ import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-acti
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
encodePrivateRichText: vi.fn(async () =>
protobuf_encode<SendRichText>({ elems: [{ text: { str: 'stub media elem' } }] }),
),
}));
// Imported statically (not via `await import` inside each `it`) so the heavy
+35 -3
View File
@@ -1,3 +1,4 @@
import type { SendRichText } from '@snowluma/proto-defs/action';
// Regression test for the c2c-vs-group businessType asymmetry that made
// private-chat video / record sends bounce with `send private message
// rejected: result=79`. The receive-side decoder
@@ -22,15 +23,16 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])),
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array([4, 5, 6]) })),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { protobuf_encode } from '@snowluma/proton';
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
@@ -569,3 +571,33 @@ describe('element-builder / forward preview', () => {
).rejects.toBeInstanceOf(MessageElementValidationError);
});
});
describe('private voice compatibility', () => {
const context = { bridge: fakeBridge, userUid: 'u_peer', scene: 'direct-private' } as const;
const record = { type: 'record', url: 'voice.amr' } as const;
const modern = Uint8Array.of(4, 5, 6);
it('keeps all modern clips when one legacy voice slot cannot represent the message', async () => {
const compat = protobuf_encode<{ ptt?: pb<4, bytes> }>({ ptt: Uint8Array.of(8, 4) });
vi.mocked(uploadPtt)
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat })
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat });
const rich = await encodePrivateRichText([record, record], context);
expect(protobuf_decode<{ ptt?: pb<4, bytes> }>(rich).ptt).toBeNull();
expect(protobuf_decode<SendRichText>(rich).elems).toHaveLength(2);
});
it('sends modern voice when no compatibility data is available and rejects malformed data', async () => {
vi.mocked(uploadPtt).mockResolvedValueOnce({ msgInfo: modern });
expect(
protobuf_decode<SendRichText>(await encodePrivateRichText([record], context)).elems,
).toHaveLength(1);
vi.mocked(uploadPtt).mockResolvedValueOnce({
msgInfo: modern,
compatQMsg: Uint8Array.of(0x12, 0),
});
await expect(encodePrivateRichText([record], context)).rejects.toThrow(
'incomplete playback information',
);
});
});
@@ -0,0 +1,14 @@
08ed241064180022ef0412ec0432b9020af6010af3010a7d08fb3d122030303030303030303030303030303030303030
303030303030303030303030301a28303030303030303030303030303030303030303030303030303030303030303030
30303030303030222430303030303030303030303030303030303030303030303030303030303030302e616d722a0408
032001400312637878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
7878787878787878787818012081808080012881800138fa0a123e0a0612047465737412001a3208818080800110012a
22081e121e0505050505050505050505050505050505050505050505050505050505055a040800380042ad02122baa02
289a0125aa0322081e121e05050505050505050505050505050505050505050505050505050505050522fd0108041081
808080011a97017878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
78787878787878787878787878782210000000000000000000000000000000002a243030303030303030303030303030
3030303030303030303030303030303030302e616d7230fb3d3a16000000000000000000000000000000000000000000
005801980103e80101
@@ -0,0 +1,91 @@
import { readFileSync } from 'node:fs';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { Elem } from '@snowluma/proto-defs/element';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { IdentityService } from '@snowluma/protocol/identity-service';
import {
type bytes,
type pb,
type pb_repeated,
protobuf_decode,
protobuf_encode,
} from '@snowluma/proton';
import { expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
interface VoiceParts {
elems?: pb_repeated<2, bytes>;
ptt?: pb<4, bytes>;
}
interface UploadReply {
upload?: pb<2, { compat?: pb<8, bytes> }>;
}
interface OutgoingMessage {
body?: pb<3, { richText?: pb<1, VoiceParts> }>;
}
it('preserves the private voice returned for older clients alongside the modern voice', async () => {
// The upload reply from #614, with identifiers redacted and transport credentials removed.
const upload = Buffer.from(
readFileSync(
new URL('./fixtures/issue-614-private-voice-upload.hex', import.meta.url),
'utf8',
).replace(/\s/g, ''),
'hex',
);
const captured = protobuf_decode<OidbBase<UploadReply>>(Uint8Array.from(upload)).body!.upload!
.compat!;
const expected = protobuf_decode<VoiceParts>(captured);
expect(captured).toHaveLength(301);
expect(expected.ptt).toHaveLength(253);
let sent: VoiceParts | undefined;
class VoiceBridge extends Bridge {
override async resolveUserUid(): Promise<string> {
return 'u_peer';
}
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
let response: Uint8Array;
if (cmd === 'OidbSvcTrpcTcp.0x126d_100') {
response = upload;
} else if (cmd === 'MessageSvc.PbSendMsg') {
sent = protobuf_decode<OutgoingMessage>(body).body!.richText!;
response = protobuf_encode<SendMessageResponse>({ privateSequence: 88 });
} else {
throw new Error(`Unexpected packet ${cmd}`);
}
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(response),
};
}
}
const bridge = new VoiceBridge(IdentityService.memory('10000'));
await bridge.apis.message.sendPrivate(10001, [
{
type: 'record',
noByteFallback: true,
fileSize: 7931,
duration: 3,
md5Hex: '0'.repeat(32),
sha1Hex: '0'.repeat(40),
fileName: 'voice.amr',
},
]);
expect(protobuf_decode<Elem>(sent!.elems![0]!).commonElem).toMatchObject({
serviceType: 48,
businessType: 12,
});
expect(sent!.ptt).toEqual(expected.ptt);
expect(sent!.elems!.slice(1)).toEqual(expected.elems);
});
+5 -5
View File
@@ -47,24 +47,24 @@ export interface MessageControl {
msgFlag?: pb<1, int_32>;
}
// RichText (for send — only elems)
// RichText for outgoing message elements.
export interface SendRichText {
elems?: pb_repeated<2, Elem>;
}
// MessageBody (for send)
export interface SendMessageBody {
richText?: pb<1, SendRichText>;
export interface SendMessageBody<TRichText = SendRichText> {
richText?: pb<1, TRichText>;
// C2C 离线文件元数据(NotOnlineFile)必须序列化后塞入此字段
// 服务器不会读取 richText.notOnlineFile。
msgContent?: pb<2, bytes>;
}
// SendMessageRequest
export interface SendMessageRequest {
export interface SendMessageRequest<TRichText = SendRichText> {
routingHead?: pb<1, RoutingHead>;
contentHead?: pb<2, SendContentHead>;
messageBody?: pb<3, SendMessageBody>;
messageBody?: pb<3, SendMessageBody<TRichText>>;
clientSequence?: pb<4, uint_32>;
random?: pb<5, uint_32>;
syncCookie?: pb<6, bytes>;
+1
View File
@@ -322,6 +322,7 @@ export interface NTV2UploadRespBody {
ipv4s?: pb_repeated<3, NTV2IPv4>;
msgSeq?: pb<5, uint_64>;
msgInfo?: pb<6, NTV2UploadRespMsgInfo>;
compatQMsg?: pb<8, bytes>;
subFileInfos?: pb_repeated<10, NTV2SubFileInfoResp>;
}
+49 -15
View File
@@ -1,4 +1,4 @@
import type { MarkdownData, MentionExtraSend } from '@snowluma/proto-defs/action';
import type { MarkdownData, MentionExtraSend, SendRichText } from '@snowluma/proto-defs/action';
import type {
Elem,
GroupFileExtra,
@@ -8,7 +8,7 @@ import type {
QFaceExtra,
QSmallFaceExtra,
} from '@snowluma/proto-defs/element';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'crypto';
import { deflateSync } from 'zlib';
@@ -24,7 +24,7 @@ import {
} from './element-manifest';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadPtt } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
type ProtoElem = Partial<Elem>;
@@ -562,7 +562,7 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise
return legacy ? [nt, legacy] : [nt];
}
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
async function makePttElem(ctx: SendContext, element: MessageElement) {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
@@ -570,17 +570,14 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
throw new Error('private record target uid is missing');
}
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
const { msgInfo, compatQMsg } = await uploadPtt(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 22 : 12,
},
elem: { commonElem: { serviceType: 48, pbElem: msgInfo, businessType: isGroup ? 22 : 12 } },
compatQMsg,
};
}
@@ -689,10 +686,10 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
* Supports: text, face, mface, at, reply, json, xml, markdown, image, record, video, forward, poke.
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(
async function buildSendContent(
elements: MessageElement[],
ctx?: SendContext,
): Promise<ProtoElem[]> {
): Promise<{ elems: ProtoElem[]; voiceCompatibility?: Uint8Array }> {
// Validate the whole message before the first upload or packet build. This
// preserves all-or-nothing semantics: a malformed later segment cannot make
// an earlier media segment perform side effects before the send is rejected.
@@ -732,6 +729,9 @@ export async function buildSendElems(
}
const result: ProtoElem[] = [];
let voiceCompatibility: Uint8Array | undefined;
const singlePrivateVoice =
ctx?.scene === 'direct-private' && elements.filter((e) => e.type === 'record').length === 1;
// A user-supplied @ that lands immediately after a reply's srcMsg isn't
// honored by the QQ NT group server (the @ shows but never notifies, #129).
// When a reply and an @ coexist, emit the replied sender as a trailing
@@ -796,9 +796,16 @@ export async function buildSendElems(
result.push(makeForwardElem(elem));
break;
case 'record':
result.push(await makePttElem(ctx!, elem));
case 'record': {
const voice = await makePttElem(ctx!, elem);
result.push(voice.elem);
if (singlePrivateVoice) {
voiceCompatibility = voice.compatQMsg;
}
break;
}
case 'video':
result.push(await makeVideoElem(ctx!, elem));
@@ -851,5 +858,32 @@ export async function buildSendElems(
}
}
return result;
return { elems: result, voiceCompatibility };
}
export async function buildSendElems(
elements: MessageElement[],
ctx?: SendContext,
): Promise<ProtoElem[]> {
return (await buildSendContent(elements, ctx)).elems;
}
export async function encodePrivateRichText(
elements: MessageElement[],
ctx: SendContext,
): Promise<Uint8Array> {
const { elems, voiceCompatibility } = await buildSendContent(elements, ctx);
const modern = protobuf_encode<SendRichText>({ elems });
// Both parts encode the same RichText message. Preserve the server's playback
// data verbatim, including extensions our receive schema does not interpret.
if (!voiceCompatibility?.length) {
return modern;
}
if (!protobuf_decode<{ ptt?: pb<4, bytes> }>(voiceCompatibility).ptt?.length) {
throw new Error('private voice upload returned incomplete playback information');
}
return Buffer.concat([modern, voiceCompatibility]);
}
+12 -3
View File
@@ -211,12 +211,12 @@ async function tryPttWaveform(
* Upload a voice clip and return the encoded MsgInfo bytes that go inside
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
export async function uploadPtt(
bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
): Promise<{ msgInfo: Uint8Array; compatQMsg?: Uint8Array }> {
const log = loggerFor(bridge);
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
@@ -313,7 +313,7 @@ export async function uploadPttMsgInfo(
fileId: mediaNode?.fileUuid,
mediaNode,
});
return encoded;
return { msgInfo: encoded, compatQMsg: upload.compatQMsg };
} finally {
for (const fn of ptt.cleanups) {
try {
@@ -324,3 +324,12 @@ export async function uploadPttMsgInfo(
}
}
}
export async function uploadPttMsgInfo(
bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
return (await uploadPtt(bridge, isGroup, targetIdOrUid, element)).msgInfo;
}