From 76846f40b141afec1a7d8a11673a1cca1d9ee0fd Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 20 Oct 2026 13:27:40 +0800 Subject: [PATCH] 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 --- AGENTS.md | 1 + packages/onebot/src/action-kit.ts | 2 +- packages/onebot/src/event-pipeline.ts | 13 ++- .../onebot/src/modules/ptt-trans-waiter.ts | 19 ++- packages/onebot/tests/event-pipeline.test.ts | 110 +++++++++++++++++- packages/onebot/tests/message-id.test.ts | 4 + .../onebot/tests/ptt-trans-waiter.test.ts | 10 +- packages/proto-defs/src/ptt-trans.ts | 8 +- packages/protocol/src/events.ts | 2 +- .../src/msg-push/decoders/event-0x210.ts | 2 +- 10 files changed, 153 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 091aa0e5..0cce7035 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,6 +86,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful - **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests. - **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry. - **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content. +- **Preserve signed message IDs.** OneBot `message_id` / `messageId` values generated by [message-id.ts](packages/onebot/src/message-id.ts) are non-zero signed 32-bit integers; negative values are valid. Use `f.messageId()` for action inputs and preserve the value through storage, replies, lookups and result matching. Protocol representations must be converted losslessly at their boundary; changing the sign or generation rule changes existing message identities. - **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible. - **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter. - **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior. diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index ccb358f3..6d05b37c 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -302,7 +302,7 @@ function arrayField( } export const f = { - /** Positive integer (>0): group_id / user_id / message_id. */ + /** Positive integer (>0): group_id / user_id. */ uint(): Field { return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 2318b36c..6124298d 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -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, 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( diff --git a/packages/onebot/src/modules/ptt-trans-waiter.ts b/packages/onebot/src/modules/ptt-trans-waiter.ts index 06415c4a..d810dc95 100644 --- a/packages/onebot/src/modules/ptt-trans-waiter.ts +++ b/packages/onebot/src/modules/ptt-trans-waiter.ts @@ -5,8 +5,12 @@ interface Pending { const pending = new Map(); -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; } diff --git a/packages/onebot/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts index f26126e8..97479c9a 100644 --- a/packages/onebot/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -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({ + message: { + contentHead: { msgType: 528, subType: 61, timestamp: 1700000000 }, + body: { + msgContent: protobuf_encode({ item: { msgId, text } }), + }, + }, + }), + }, + IdentityService.memory(String(selfId)), + ); +} + function makeContext(extra: Partial = {}): { ctx: OneBotInstanceContext; bus: BridgeEventBus; @@ -168,6 +201,79 @@ function makeContext(extra: Partial = {}): { } 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( diff --git a/packages/onebot/tests/message-id.test.ts b/packages/onebot/tests/message-id.test.ts index 9af24493..7a03d372 100644 --- a/packages/onebot/tests/message-id.test.ts +++ b/packages/onebot/tests/message-id.test.ts @@ -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, ''); diff --git a/packages/onebot/tests/ptt-trans-waiter.test.ts b/packages/onebot/tests/ptt-trans-waiter.test.ts index 09a42728..f248c779 100644 --- a/packages/onebot/tests/ptt-trans-waiter.test.ts +++ b/packages/onebot/tests/ptt-trans-waiter.test.ts @@ -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 () => { diff --git a/packages/proto-defs/src/ptt-trans.ts b/packages/proto-defs/src/ptt-trans.ts index 66b0574f..9c7eca1e 100644 --- a/packages/proto-defs/src/ptt-trans.ts +++ b/packages/proto-defs/src/ptt-trans.ts @@ -12,10 +12,8 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton'; * fields (uuid / md5) and the response `text` tag should be confirmed with a * single live capture before relying on them. * - * Flow: send Trans{C2C,Group}PttReq → response carries the text inline when - * transcription is already done; when it's empty the server transcribes - * asynchronously (no dedicated push command exists — see NotifyTransUpdate), - * so the caller re-sends with backoff until the text arrives or it times out. + * Flow: the response can carry completed text inline. Otherwise, the caller + * waits for an asynchronous result correlated with the original message ID. */ /** Source ptt-element field (NT internal tag) noted in the comment after each. */ @@ -73,7 +71,7 @@ export interface GroupPttTransResult { /** * Outer response. `type` echoes the scene; result is at field 2 (group) / * field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing, - * retry later". + * await the result push". */ export interface PttTransResp { type?: pb<1, uint_32>; diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 0d28418d..840abce6 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -495,7 +495,7 @@ export interface GroupMsgEmojiLikeEvent extends QQEvent { */ export interface PttTransResultEvent extends QQEvent { kind: 'ptt_trans_result'; - msgId: number; + msgId: bigint; text: string; } diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 46b2c519..87cef430 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -205,7 +205,7 @@ function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] { return []; } - const msgId = Number(item.msgId ?? 0n); + const msgId = item.msgId ?? 0n; const text = item.text ?? ''; if (!msgId || !text) {