fix(core): correlate AI voice send receipts
Wait for the canonical self group-message event after AI voice synthesis instead of interpreting undocumented response fields as a message sequence. Correlate receipts by exact media UUID, buffer response races, and claim each semantic message identity only once across concurrent calls and duplicate multi-process pushes. Reject missing identifiers, invalid sequences, bounded-buffer overflow, and receipt timeouts with explicit diagnostics. Keep fetchAiVoice focused on returning the media node and add regression coverage for race ordering, unrelated events, identical concurrent audio, duplicate pushes, malformed receipts, and timeout cleanup. Fixes #250
This commit is contained in:
3 files changed
+328
-9
No files matched your search
@@ -8,6 +8,7 @@ import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
@@ -49,9 +50,41 @@ export interface AiVoiceItem {
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export interface AiVoiceSendReceipt {
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge.Extras');
|
||||
const AI_VOICE_RECEIPT_TIMEOUT_MS = 5_000;
|
||||
const AI_VOICE_CANDIDATE_LIMIT = 64;
|
||||
const AI_VOICE_CLAIM_LIMIT = 256;
|
||||
|
||||
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
|
||||
function normalizeMediaUuid(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
|
||||
const expectedUuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (!expectedUuid) return false;
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') continue;
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
if (actualUuid === expectedUuid) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
|
||||
const uuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (uuid) return `uuid:${uuid.slice(-12)}`;
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
@@ -94,9 +127,11 @@ export class ExtrasApi {
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned MediaIndexNode plugs directly into
|
||||
* The returned node plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
* download-URL fetch in SnowLuma. The synthesis response does not contain a
|
||||
* reliable message sequence; callers that need one must use `sendAiVoice`,
|
||||
* which correlates the subsequent self-message receipt.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
@@ -109,11 +144,121 @@ export class ExtrasApi {
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
if (node) return node as MediaIndexNode;
|
||||
if (node) {
|
||||
log.debug(
|
||||
'AI voice synthesis completed group=%d media=%s polls=%d',
|
||||
groupId,
|
||||
describeAiVoiceFingerprint(node),
|
||||
i + 1,
|
||||
);
|
||||
return node as MediaIndexNode;
|
||||
}
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish an AI voice and wait for QQ's canonical self-message receipt.
|
||||
*
|
||||
* The 0x929B completion response carries the media node but, on live QQ,
|
||||
* omits the group message sequence. Subscribe before publishing so an echo
|
||||
* that wins the response race is buffered, then correlate by the exact media
|
||||
* UUID. Never guess from content hashes or "the next voice in the group":
|
||||
* concurrent requests can legitimately render byte-identical audio.
|
||||
*/
|
||||
async sendAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
|
||||
): Promise<AiVoiceSendReceipt> {
|
||||
const candidates: GroupMessageEvent[] = [];
|
||||
let candidatesOverflowed = false;
|
||||
let expectedNode: MediaIndexNode | null = null;
|
||||
let receiptSettled = false;
|
||||
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
|
||||
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
|
||||
resolveReceipt = resolve;
|
||||
});
|
||||
|
||||
const claim = (event: GroupMessageEvent): boolean => {
|
||||
if (receiptSettled) return false;
|
||||
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
|
||||
this.claimedAiVoiceReceiptKeys.add(key);
|
||||
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
|
||||
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
|
||||
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
}
|
||||
receiptSettled = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const accept = (event: GroupMessageEvent): void => {
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
|
||||
if (!event.elements.some(element => element.type === 'record')) return;
|
||||
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
|
||||
resolveReceipt?.(event);
|
||||
return;
|
||||
}
|
||||
candidates.push(event);
|
||||
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
|
||||
candidates.shift();
|
||||
candidatesOverflowed = true;
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = this.ctx.events.on('group_message', accept);
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
|
||||
expectedNode = node;
|
||||
const fingerprint = describeAiVoiceFingerprint(node);
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
|
||||
}
|
||||
|
||||
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
|
||||
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
);
|
||||
}
|
||||
const event = buffered ?? await Promise.race([
|
||||
receiptPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
|
||||
+ `(group=${groupId} media=${fingerprint})`,
|
||||
));
|
||||
}, receiptTimeoutMs);
|
||||
timeout.unref?.();
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
|
||||
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
|
||||
groupId,
|
||||
fingerprint,
|
||||
event.msgSeq,
|
||||
event.msgId,
|
||||
);
|
||||
return {
|
||||
sequence: event.msgSeq,
|
||||
};
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupTodo,
|
||||
@@ -115,13 +117,15 @@ describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
|
||||
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
|
||||
it('fetchAiVoice retries while msgInfo is empty and returns the media node', async () => {
|
||||
const bridge = mockBridge();
|
||||
const node = { fileUuid: 'uuid-1', subType: 1 };
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } } as any)))
|
||||
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any })))
|
||||
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
|
||||
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { field2: 319, field3: 20, msgInfo: { msgInfoBody: [{ index: node }] } } as any,
|
||||
})));
|
||||
const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound);
|
||||
expect(out).toMatchObject(node);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
@@ -159,4 +163,168 @@ describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
|
||||
const env2 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
|
||||
expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId);
|
||||
});
|
||||
|
||||
it('sendAiVoice correlates an echo that arrives before the synthesis response', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
const node = { fileUuid: 'voice-uuid', info: { fileHash: 'AABB' } };
|
||||
bridge.sendRawPacket.mockImplementationOnce(async () => {
|
||||
await events.emit({
|
||||
kind: 'group_message',
|
||||
time: 1234,
|
||||
selfUin: 10001,
|
||||
groupId: 100,
|
||||
groupName: 'test',
|
||||
senderUin: 10001,
|
||||
senderNick: 'self',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 319,
|
||||
msgId: 456,
|
||||
elements: [{ type: 'record', fileId: 'voice-uuid', fileHash: 'AABB' }],
|
||||
});
|
||||
return packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
|
||||
} as any));
|
||||
});
|
||||
|
||||
const receipt = await new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 50);
|
||||
expect(receipt).toEqual({ sequence: 319 });
|
||||
});
|
||||
|
||||
it('sendAiVoice ignores unrelated self voice messages and matches the media UUID', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
const node = { fileUuid: 'expected-uuid', info: { fileHash: 'aabb' } };
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
|
||||
} as any),
|
||||
));
|
||||
const pending = new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 100);
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 0, selfUin: 10001, groupId: 999, groupName: 'other',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 10, msgId: 20,
|
||||
elements: [{ type: 'record', fileId: 'expected-uuid' }],
|
||||
});
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 0, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 20002, senderNick: 'other', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 11, msgId: 21,
|
||||
elements: [{ type: 'record', fileId: 'expected-uuid' }],
|
||||
});
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 0, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 12, msgId: 22,
|
||||
elements: [{ type: 'text', text: 'not a voice' }],
|
||||
});
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 1, msgId: 2,
|
||||
elements: [{ type: 'record', fileId: 'EXPECTED-UUID', fileHash: 'AABB' }],
|
||||
});
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 3, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 4, msgId: 5, elements: [{ type: 'record', mediaNode: { fileUuid: 'expected-uuid' } }],
|
||||
});
|
||||
|
||||
await expect(pending).resolves.toEqual({ sequence: 4 });
|
||||
});
|
||||
|
||||
it('sendAiVoice lets each self-message receipt satisfy only one concurrent request', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
const node = { fileUuid: 'shared-uuid', info: { fileHash: 'AABB' } };
|
||||
bridge.sendRawPacket.mockResolvedValue(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
|
||||
} as any),
|
||||
));
|
||||
const api = new ExtrasApi(bridge as any);
|
||||
const first = api.sendAiVoice(100, 'v', 'same text', 1, 100);
|
||||
const second = api.sendAiVoice(100, 'v', 'same text', 1, 100);
|
||||
|
||||
const firstReceipt: Extract<QQEventVariant, { kind: 'group_message' }> = {
|
||||
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 10, msgId: 20, elements: [{ type: 'record', fileId: 'shared-uuid' }],
|
||||
};
|
||||
await events.emit(firstReceipt);
|
||||
// A second QQ process can decode the same push into a different object.
|
||||
await events.emit({ ...firstReceipt, elements: [...firstReceipt.elements] });
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 2, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 11, msgId: 21, elements: [{ type: 'record', fileId: 'shared-uuid' }],
|
||||
});
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ sequence: 10 },
|
||||
{ sequence: 11 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('sendAiVoice fails explicitly when QQ omits every correlation key', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: { subType: 1 } }] } },
|
||||
} as any),
|
||||
));
|
||||
|
||||
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 10)).rejects.toThrow(
|
||||
/no exact media identifier/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('sendAiVoice refuses hash-only correlation because concurrent audio can be identical', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: { info: { fileHash: 'AABB' } } }] } },
|
||||
} as any),
|
||||
));
|
||||
|
||||
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 10)).rejects.toThrow(
|
||||
/no exact media identifier/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('sendAiVoice rejects a matched receipt with an invalid message sequence', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uuid' } }] } },
|
||||
} as any),
|
||||
));
|
||||
const pending = new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 50);
|
||||
await events.emit({
|
||||
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
|
||||
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 0, msgId: 2, elements: [{ type: 'record', fileId: 'uuid' }],
|
||||
});
|
||||
|
||||
await expect(pending).rejects.toThrow(/invalid message sequence: 0/i);
|
||||
});
|
||||
|
||||
it('sendAiVoice fails explicitly when the canonical echo never arrives', async () => {
|
||||
const events = new BridgeEventBus();
|
||||
const bridge = mockBridge({ events: events as any });
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
|
||||
body: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uuid' } }] } },
|
||||
} as any),
|
||||
));
|
||||
|
||||
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 5)).rejects.toThrow(
|
||||
/published but no matching group-message receipt/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -33,11 +33,13 @@ describe('FetchAiVoice namespace', () => {
|
||||
});
|
||||
|
||||
describe('deserialize', () => {
|
||||
it('returns the first msgInfoBody index when present', () => {
|
||||
it('returns the first msgInfoBody index', () => {
|
||||
const node = { fileUuid: 'uuid', subType: 1 };
|
||||
expect(FetchAiVoice.deserialize({} as any, {
|
||||
field2: 319,
|
||||
field3: 20,
|
||||
msgInfo: { msgInfoBody: [{ index: node }] },
|
||||
} as any)).toMatchObject(node);
|
||||
} as any)).toEqual(node);
|
||||
});
|
||||
|
||||
it('returns null when msgInfo is empty / missing', () => {
|
||||
@@ -54,9 +56,13 @@ describe('FetchAiVoice namespace', () => {
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929b_0');
|
||||
});
|
||||
|
||||
it('returns the parsed index node', async () => {
|
||||
it('returns the parsed media node', async () => {
|
||||
const node = { fileUuid: 'uuid', subType: 1 };
|
||||
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
|
||||
const sender = makeSender({
|
||||
field2: 319,
|
||||
field3: 20,
|
||||
msgInfo: { msgInfoBody: [{ index: node }] },
|
||||
} as any);
|
||||
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
|
||||
expect(out).toMatchObject(node);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user