fix(onebot): resolve voice transcription for signed message IDs

Allow voice transcription results to complete for messages with negative IDs while preserving existing message identities and account isolation.

Report unmatched transcription results accurately and document the signed message ID contract.

Fixes #554
This commit is contained in:
DrSmoothl committed 2026-10-20 13:27:40 +08:00
1 parent 79522d949f
commit 76846f40b1
10 files changed
+153 -18

No files matched your search

+1 -1
View File
@@ -302,7 +302,7 @@ function arrayField<E>(
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
/** Positive integer (>0): group_id / user_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), {
type: 'uint',
+10 -3
View File
@@ -166,7 +166,8 @@ type PipelineEventReason =
| 'pipeline_threw'
| 'recalled_before_backfill'
| 'recalled_after_backfill'
| 'waiter_notified';
| 'waiter_notified'
| 'waiter_not_found';
async function convertAndDispatch(
ctx: OneBotInstanceContext,
@@ -458,8 +459,14 @@ function handlePttTransResult(
event: Extract<QQEventVariant, { kind: 'ptt_trans_result' }>,
state: EventTraceState,
): void {
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified');
const notified = deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(
log,
event.kind,
state,
'internal',
notified ? 'waiter_notified' : 'waiter_not_found',
);
}
function convertOnly<K extends EventKind>(
@@ -5,8 +5,12 @@ interface Pending {
const pending = new Map<string, Pending>();
export function pttTransKey(selfUin: number, msgId: number): string {
return selfUin + ':' + msgId;
export function pttTransKey(selfUin: number, msgId: number | bigint): string {
if (typeof msgId === 'number' && !Number.isSafeInteger(msgId)) {
throw new RangeError('PTT message id must be a safe integer or bigint');
}
return selfUin + ':' + BigInt.asIntN(64, BigInt(msgId));
}
/** Register before triggering; only this request may settle its own response or timeout. */
@@ -53,6 +57,13 @@ export function requestPttTransText(
}
/** QQ push results identify the account and message, not an individual trigger request. */
export function deliverPttTransText(key: string, text: string): void {
pending.get(key)?.resolve(text);
export function deliverPttTransText(key: string, text: string): boolean {
const waiter = pending.get(key);
if (!waiter) {
return false;
}
waiter.resolve(text);
return true;
}
+108 -2
View File
@@ -9,6 +9,11 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow } from '@snowluma/protocol/msg-push';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_encode } from '@snowluma/proton';
// Wrap convertEvent in a vi.fn that delegates to the real impl by
// default, so one test can override it to return null without making
@@ -29,7 +34,13 @@ vi.mock('../src/modules/message-actions', async () => {
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { registerEventPipeline } from '../src/event-pipeline';
import type { OneBotInstanceContext } from '../src/instance-context';
import { hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import { backfillReplyTarget } from '../src/modules/message-actions';
import {
deliverPttTransText,
pttTransKey,
requestPttTransText,
} from '../src/modules/ptt-trans-waiter';
import { TempSessionStore } from '../src/temp-session-store';
import type {
FriendMessage,
@@ -107,6 +118,28 @@ function makeMemberJoin(): GroupMemberJoin {
};
}
function decodePttTransPush(selfId: number, msgId: bigint, text: string): QQEventVariant[] {
return parseMsgPushOrThrow(
{
pid: 1,
uin: String(selfId),
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({
message: {
contentHead: { msgType: 528, subType: 61, timestamp: 1700000000 },
body: {
msgContent: protobuf_encode<PttTransPush>({ item: { msgId, text } }),
},
},
}),
},
IdentityService.memory(String(selfId)),
);
}
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
ctx: OneBotInstanceContext;
bus: BridgeEventBus;
@@ -168,6 +201,79 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
}
describe('registerEventPipeline', () => {
it('matches transcription pushes to signed message IDs without rounding or crossing accounts', async () => {
vi.useFakeTimers();
const previousLevel = getLogLevel();
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
setLogLevel('trace');
const cases = [
{ selfId: SELF_ID, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -373767943, wireId: 18446744073335783673n },
{ selfId: SELF_ID + 1, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -2147483648, wireId: 18446744071562067968n },
{ selfId: SELF_ID, msgId: -1, wireId: 18446744073709551615n },
{ selfId: SELF_ID, msgId: 147311541, wireId: 147311541n },
{ selfId: SELF_ID, msgId: 2147483647, wireId: 2147483647n },
{
selfId: SELF_ID,
msgId: hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT),
wireId: 18446744073124008294n,
},
];
const requests = cases.map((item, index) => {
const context = makeContext({ selfId: item.selfId, uin: String(item.selfId) });
const handle = registerEventPipeline(context.ctx);
const key = pttTransKey(item.selfId, item.msgId);
const text = `transcription ${index}`;
const result = requestPttTransText(key, 20_000, async () => '');
return { ...item, ...context, handle, key, text, result };
});
const settled = Promise.allSettled(requests.map(({ result }) => result));
try {
expect(cases.at(-1)?.msgId).toBe(-585543322);
for (const request of requests.toReversed()) {
const events = decodePttTransPush(request.selfId, request.wireId, request.text);
expect(events).toHaveLength(1);
await request.bus.emit(events[0]!);
}
await vi.advanceTimersByTimeAsync(20_000);
expect(await settled).toEqual(
requests.map(({ text }) => ({ status: 'fulfilled', value: text })),
);
expect(vi.getTimerCount()).toBe(0);
expect(requests.flatMap(({ dispatchCalls }) => dispatchCalls)).toEqual([]);
expect(
entries.filter(
(entry) =>
entry.scope === 'Event' &&
entry.message.startsWith('event_terminal kind=ptt_trans_result') &&
entry.message.includes('reason=waiter_notified'),
),
).toHaveLength(requests.length);
expect(
entries.some(
(entry) =>
entry.message.startsWith('event_input kind=ptt_trans_result') &&
entry.message.includes('msgId:18446744073335783674'),
),
).toBe(true);
} finally {
for (const request of requests) {
deliverPttTransText(request.key, 'cleanup');
request.handle.stop();
await request.handle.drain();
}
unsubscribe();
setLogLevel(previousLevel);
vi.useRealTimers();
}
});
it('caches meta and dispatches a converted event for friend_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
@@ -540,7 +646,7 @@ describe('registerEventPipeline', () => {
kind: 'ptt_trans_result',
time: 1700000000,
selfUin: SELF_ID,
msgId: 99,
msgId: 99n,
text: 'done',
});
@@ -555,7 +661,7 @@ describe('registerEventPipeline', () => {
expect.stringContaining('outcome=dropped reason=converter_returned_null'),
expect.stringContaining('outcome=failed reason=converter_threw'),
expect.stringContaining('outcome=dropped reason=recalled_before_backfill'),
expect.stringContaining('outcome=internal reason=waiter_notified'),
expect.stringContaining('outcome=internal reason=waiter_not_found'),
]),
);
expect(
+4
View File
@@ -8,6 +8,10 @@ describe('hashMessageIdInt32', () => {
expect(id1).toBe(id2);
});
it('preserves negative hashes as valid message IDs', () => {
expect(hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT)).toBe(-585543322);
});
it('returns non-zero', () => {
// The function ensures id !== 0 by setting it to 1
const id = hashMessageIdInt32(0, 0, '');
@@ -8,6 +8,13 @@ import {
afterEach(() => vi.useRealTimers());
describe('PTT transcription requests', () => {
it.each([Number(18446744073335783674n), 1.5, NaN, Infinity])(
'rejects an inexact numeric message id: %s',
(msgId) => {
expect(() => pttTransKey(10001, msgId)).toThrow(RangeError);
},
);
it('keeps accounts isolated for the same message id', async () => {
const first = requestPttTransText(pttTransKey(10001, 1), 20_000, async () => '');
const second = requestPttTransText(pttTransKey(10002, 1), 20_000, async () => '');
@@ -19,8 +26,9 @@ describe('PTT transcription requests', () => {
it.each(['text', ''])('accepts a pushed transcription: %j', async (text) => {
const result = requestPttTransText('account:push', 20_000, async () => '');
deliverPttTransText('account:push', text);
expect(deliverPttTransText('account:push', text)).toBe(true);
await expect(result).resolves.toBe(text);
expect(deliverPttTransText('account:push', text)).toBe(false);
});
it('registers before triggering so an immediate push is not lost', async () => {