From 22add4ad1c0bdc2dcbf1a7c6a166a465b3539f82 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 23:40:57 +0800 Subject: [PATCH] refactor(api): move Tier-2 extras to ExtrasApi (#6 commit 11/13) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inlines `actions/extras.ts` into `apis/extras.ts::ExtrasApi`. Covers the napcat-parity Tier-2 surface: group todo CRUD (0xF90_1/2/3), stranger online/ext status decode (0xFE1_2), and AI voice list + synthesis (0x929D / 0x929B). `StrangerStatus`, `AiVoiceChatType`, `AiVoiceCategory`, `AiVoiceItem` are now exported from `apis/extras.ts` and re-exported through `bridge.ts` for backwards compatibility (the OneBot side imports them via `@snowluma/core`). No renaming — the names already read cleanly under `apis.extras.X`. The `fetchAiVoiceList` / `fetchAiVoice` chatType parameter is widened to `AiVoiceChatType | number` because the OneBot side passes a raw number from JSON. The wire encoder is happy with any integer; the strict enum just gives autocompletion at call sites that have it. Callers updated: `actions/extended.ts` (7 sites). Tests rewritten: - `extras.test.ts` → uses `new ExtrasApi(bridge as any).method(...)` and the it.each dispatch switches to method-name strings. - `extended-actions.test.ts` APIS_ROUTING gains the extras block. 587/587 tests pass. --- packages/core/src/bridge/actions/extras.ts | 136 ---------------- packages/core/src/bridge/apis/extras.ts | 151 ++++++++++++++++++ packages/core/src/bridge/apis/index.ts | 5 + packages/core/src/bridge/bridge-interface.ts | 12 +- packages/core/src/bridge/bridge.ts | 34 +--- packages/core/src/onebot/actions/extended.ts | 16 +- packages/core/tests/actions/extras.test.ts | 48 +++--- .../tests/onebot/extended-actions.test.ts | 7 + 8 files changed, 205 insertions(+), 204 deletions(-) delete mode 100644 packages/core/src/bridge/actions/extras.ts create mode 100644 packages/core/src/bridge/apis/extras.ts diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts deleted file mode 100644 index fd8c1391..00000000 --- a/packages/core/src/bridge/actions/extras.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; -import { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbGroupTodo, - OidbStrangerStatusReq, - OidbStrangerStatusResp, -} from '@snowluma/proto-defs/oidb-actions/base'; -import type { - OidbAiVoiceListReq, - OidbAiVoiceListResp, - OidbAiVoiceReq, - OidbAiVoiceResp, -} from '@snowluma/proto-defs/oidb-actions/media'; -import type { MediaIndexNode } from './shared'; - -// ─────────────── Group todo (0xF90) ─────────────── - -export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode>(env)); -} - -export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode>(env)); -} - -export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode>(env)); -} - -// ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── - -export interface StrangerStatus { - status: number; - ext_status: number; -} - -/** - * Mirror napcat's GetStrangerStatus: decode the extBigInt status word. - * Values ≤10 fold into a 10×status; everything else is split into the - * high-byte / low-byte ext_status the OneBot dialect uses. - * - * Returns null on transport / decode failure rather than throwing, so - * the OneBot action can produce a clean retcode without try/catch - * gymnastics. - */ -export async function getStrangerStatus(bridge: Bridge, uin: number): Promise { - try { - const env = makeOidbEnvelope( - 0xFE1, 2, - { uin, key: [{ key: 27372 }] } as any, - // Same UIN-form flag fetchUserProfile sets — without it newer - // QQ NT rejects with `[oidb] one of uid/openid is invaild`. - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - const raw = resp?.data?.status?.value; - if (raw === undefined || raw === null) return null; - const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); - if (extBig <= 10n) { - return { status: Number(extBig) * 10, ext_status: 0 }; - } - const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); - return { status: 10, ext_status: status }; - } catch { - return null; - } -} - -// ─────────────── AI voice (0x929D / 0x929B) ─────────────── - -export const AiVoiceChatType = { - Unknown: 0, - Sound: 1, - Sing: 2, -} as const; -export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; - -export interface AiVoiceItem { - voiceId: string; - voiceDisplayName: string; - voiceExampleUrl: string; -} - -export interface AiVoiceCategory { - category: string; - voices: AiVoiceItem[]; -} - -export async function fetchAiVoiceList( - bridge: Bridge, - groupId: number, - chatType: AiVoiceChatType, -): Promise { - const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - return (resp?.content as AiVoiceCategory[] | undefined) ?? []; -} - -/** - * Trigger AI voice synthesis. Server may return an empty msgInfo while - * 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 - * `bridge.fetchGroupPttUrlByNode`, which already handles every other - * download-URL fetch in SnowLuma. - */ -export async function fetchAiVoice( - bridge: Bridge, - groupId: number, - voiceId: string, - text: string, - chatType: AiVoiceChatType, - maxRetries = 30, -): Promise { - // Random 32-bit session id — server uses this to deduplicate polls. - const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; - for (let i = 0; i < maxRetries; i++) { - const env = makeOidbEnvelope( - 0x929B, 0, - { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; - if (node) return node; - } - throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); -} diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts new file mode 100644 index 00000000..4ec0c3e8 --- /dev/null +++ b/packages/core/src/bridge/apis/extras.ts @@ -0,0 +1,151 @@ +// ExtrasApi — Tier-2 napcat-parity surfaces that don't fit anywhere +// else: group todo CRUD, stranger online/ext status decode, AI voice +// list + synthesis. Inlined from `actions/extras.ts` (deleted alongside +// actions/* in commit 13). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupTodo, + OidbStrangerStatusReq, + OidbStrangerStatusResp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { + OidbAiVoiceListReq, + OidbAiVoiceListResp, + OidbAiVoiceReq, + OidbAiVoiceResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import type { MediaIndexNode } from '../actions/shared'; +import type { BridgeContext } from '../bridge-context'; +import type { Bridge } from '../bridge'; +import { makeOidbEnvelope, runOidb } from '../bridge-oidb'; + +function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } + +// ─────────────── public types (re-exported from bridge.ts as before) ─── + +export interface StrangerStatus { + status: number; + ext_status: number; +} + +export const AiVoiceChatType = { + Unknown: 0, + Sound: 1, + Sing: 2, +} as const; +export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; + +export interface AiVoiceItem { + voiceId: string; + voiceDisplayName: string; + voiceExampleUrl: string; +} + +export interface AiVoiceCategory { + category: string; + voices: AiVoiceItem[]; +} + +export class ExtrasApi { + constructor(private readonly ctx: BridgeContext) {} + + // ─────────────── Group todo (0xF90) ─────────────── + + async setGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode>(env)); + } + + async completeGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode>(env)); + } + + async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode>(env)); + } + + // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── + + /** + * Mirror napcat's GetStrangerStatus: decode the extBigInt status word. + * Values ≤10 fold into a 10×status; everything else is split into the + * high-byte / low-byte ext_status the OneBot dialect uses. + * + * Returns null on transport / decode failure rather than throwing, so + * the OneBot action can produce a clean retcode without try/catch + * gymnastics. + */ + async getStrangerStatus(uin: number): Promise { + const bridge = asBridge(this.ctx); + try { + const env = makeOidbEnvelope( + 0xFE1, 2, + { uin, key: [{ key: 27372 }] } as any, + // Same UIN-form flag fetchUserProfile sets — without it newer + // QQ NT rejects with `[oidb] one of uid/openid is invaild`. + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + const raw = resp?.data?.status?.value; + if (raw === undefined || raw === null) return null; + const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); + if (extBig <= 10n) { + return { status: Number(extBig) * 10, ext_status: 0 }; + } + const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); + return { status: 10, ext_status: status }; + } catch { + return null; + } + } + + // ─────────────── AI voice (0x929D / 0x929B) ─────────────── + + async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise { + const bridge = asBridge(this.ctx); + const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + return (resp?.content as AiVoiceCategory[] | undefined) ?? []; + } + + /** + * Trigger AI voice synthesis. Server may return an empty msgInfo while + * 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 + * `apis.groupFile.getPttUrl`, which already handles every other + * download-URL fetch in SnowLuma. + */ + async fetchAiVoice( + groupId: number, + voiceId: string, + text: string, + chatType: AiVoiceChatType | number, + maxRetries = 30, + ): Promise { + const bridge = asBridge(this.ctx); + // Random 32-bit session id — server uses this to deduplicate polls. + const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; + for (let i = 0; i < maxRetries; i++) { + const env = makeOidbEnvelope( + 0x929B, 0, + { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode>(env)); + const resp = protobuf_decode>(respBytes).body; + const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; + if (node) return node; + } + throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); + } +} diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 11fab588..856ac316 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -22,6 +22,7 @@ import type { BridgeContext } from '../bridge-context'; import { ContactsApi } from './contacts'; +import { ExtrasApi } from './extras'; import { ForwardApi } from './forward'; import { FriendApi } from './friend'; import { GroupAdminApi } from './group-admin'; @@ -53,6 +54,8 @@ export interface ApiHub { readonly forward: ForwardApi; /** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */ readonly misc: MiscApi; + /** Tier-2 napcat-parity: group todo / stranger status / AI voice. */ + readonly extras: ExtrasApi; // Pending — added as later commits land: // readonly interaction: InteractionApi; // readonly profile: ProfileApi; @@ -82,6 +85,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { profile: new ProfileApi(ctx), forward: new ForwardApi(ctx), misc: new MiscApi(ctx), + extras: new ExtrasApi(ctx), }; } @@ -89,6 +93,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { // `import type { MessageApi } from '@snowluma/core/.../apis'` for // signature use. Concrete instances always come from `bridge.apis.*`. export { ContactsApi } from './contacts'; +export { ExtrasApi } from './extras'; export { ForwardApi } from './forward'; export { FriendApi } from './friend'; export { GroupAdminApi } from './group-admin'; diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 8009592c..3dcddf4f 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -1,6 +1,5 @@ import type { SendPacketResult } from '../protocol/packet-sender'; import type { ApiHub } from './apis'; -import type { MediaIndexNode } from './actions/shared'; import type { ClientKeyInfo, DownloadRKeyInfo, @@ -90,11 +89,8 @@ export interface BridgeInterface { // ─── Misc (moved to apis.misc) ─── // - translateEn2Zh / getMiniAppArk / clickInlineKeyboardButton / sendGroupSign - // ─── Tier-2 napcat parity extras ─── - setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise; - getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>; - fetchAiVoiceList(groupId: number, chatType: number): Promise }>>; - fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise; + // ─── Tier-2 napcat parity extras (moved to apis.extras) ─── + // - setGroupTodo / completeGroupTodo / cancelGroupTodo + // - getStrangerStatus + // - fetchAiVoiceList / fetchAiVoice } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 0df74573..86398b05 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -9,18 +9,14 @@ import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline'; import { type ApiHub, buildApiHub } from './apis'; // Delegated modules +// Group-todo / stranger-status / AI-voice moved to apis/extras.ts. +// Public types stay re-exported through this file for backwards +// compatibility — the OneBot side imports them via `@snowluma/core`. import { AiVoiceChatType, - cancelGroupTodo as cancelGroupTodo_, - completeGroupTodo as completeGroupTodo_, - fetchAiVoice as fetchAiVoice_, - fetchAiVoiceList as fetchAiVoiceList_, - getStrangerStatus as getStrangerStatus_, - setGroupTodo as setGroupTodo_, type AiVoiceCategory, - type AiVoiceChatType as AiVoiceChatTypeT, type StrangerStatus, -} from './actions/extras'; +} from './apis/extras'; // actions/forward.ts removed — moved to apis/forward.ts::ForwardApi. // actions/friend.ts removed — moved to apis/friend.ts::FriendApi. // actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`. @@ -342,25 +338,7 @@ export class Bridge implements BridgeInterface { // Misc methods (translateEn2Zh / getMiniAppArk / // clickInlineKeyboardButton / sendGroupSign) moved to apis.misc. - // --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) --- - - async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return setGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return completeGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise { - return cancelGroupTodo_(this, groupId, BigInt(msgSeq)); - } - async getStrangerStatus(uin: number): Promise { - return getStrangerStatus_(this, uin); - } - async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise { - return fetchAiVoiceList_(this, groupId, chatType); - } - async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) { - return fetchAiVoice_(this, groupId, voiceId, text, chatType); - } + // --- Tier-2 napcat-parity extras (group todo / stranger status / + // AI voice) moved to apis.extras. --- } diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index b73c2eb3..3b3ee8fe 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -1170,18 +1170,18 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } }; - h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.setGroupTodo(g, s))); - h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.completeGroupTodo(g, s))); - h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.cancelGroupTodo(g, s))); + h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.setGroupTodo(g, BigInt(s)))); + h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s)))); + h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s)))); // --- User online/ext status (napcat: nc_get_user_status) --- h.registerAction('nc_get_user_status', async (params) => { const userId = asNumber(params.user_id); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const status = await ctx.bridge.getStrangerStatus(userId); + const status = await ctx.bridge.apis.extras.getStrangerStatus(userId); if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); - return okResponse(status); + return okResponse({ ...status }); }); // --- AI voice (oidb 0x929D / 0x929B) --- @@ -1191,7 +1191,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const chatType = asNumber(params.chat_type) || 1; if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); try { - const list = await ctx.bridge.fetchAiVoiceList(groupId, chatType); + const list = await ctx.bridge.apis.extras.fetchAiVoiceList(groupId, chatType); return okResponse(list.map((cat) => ({ type: cat.category, characters: cat.voices.map((v) => ({ @@ -1214,7 +1214,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); } try { - const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); + const node = await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); const url = await ctx.bridge.apis.groupFile.getPttUrl(groupId, node); return okResponse(url); } catch (err) { @@ -1234,7 +1234,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); } try { - await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); + await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); return okResponse({ message_id: 0 }); } catch (err) { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index 4d77aee9..0b6734f8 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -10,11 +10,10 @@ import type { } from '@snowluma/proto-defs/oidb-actions/media'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers -// that the plugin substitutes at the call site with the inlined codec, so -// mocking them on the module object is a no-op. The only mockable point -// is `runOidb` (non-generic, untouched by proton) returning real bytes -// that the production-side codec then decodes. `makeOidbEnvelope` is a -// pure TS helper, so its mock works for introspection. +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic) to return real proton-encoded bytes +// that the production-side codec actually decodes. vi.mock('../../src/bridge/bridge-oidb', async () => { const actual = await vi.importActual( '../../src/bridge/bridge-oidb', @@ -27,22 +26,23 @@ vi.mock('../../src/bridge/bridge-oidb', async () => { }); import * as oidb from '../../src/bridge/bridge-oidb'; -import * as extras from '../../src/bridge/actions/extras'; +import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras'; import { mockBridge } from './_helpers'; -describe('actions/extras / group todo (0xF90)', () => { +describe('apis/extras / group todo (0xF90)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it.each([ - ['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1], - ['completeGroupTodo', extras.completeGroupTodo, 'OidbSvcTrpcTcp.0xf90_2', 2], - ['cancelGroupTodo', extras.cancelGroupTodo, 'OidbSvcTrpcTcp.0xf90_3', 3], - ] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => { + ['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1', 1] as const, + ['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2', 2] as const, + ['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3', 3] as const, + ])('%s dispatches the right subCmd with shared body', async (method, cmd, subCmd) => { const bridge = mockBridge(); - await fn(bridge as any, 12345, 9876543210n); + const api = new ExtrasApi(bridge as any); + await (api as any)[method](12345, 9876543210n); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe(cmd); const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; @@ -52,7 +52,7 @@ describe('actions/extras / group todo (0xF90)', () => { }); }); -describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { +describe('apis/extras / getStrangerStatus (0xFE1_2)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -64,7 +64,7 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 5n } } } }), ); - await extras.getStrangerStatus(bridge as any, 100200); + await new ExtrasApi(bridge as any).getStrangerStatus(100200); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; @@ -78,7 +78,7 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 7n } } } }), ); - expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 }); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 }); }); it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => { @@ -89,14 +89,14 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { data: { status: { value: 0x42F100n } } } }), ); - const status = await extras.getStrangerStatus(bridge as any, 1); + const status = await new ExtrasApi(bridge as any).getStrangerStatus(1); expect(status).toEqual({ status: 10, ext_status: 0xF142 }); }); it('returns null when the runner throws (transport error)', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockRejectedValueOnce(new Error('boom')); - expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); it('returns null when the server omits the status field', async () => { @@ -104,11 +104,11 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); + expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); }); -describe('actions/extras / AI voice (0x929D / 0x929B)', () => { +describe('apis/extras / AI voice (0x929D / 0x929B)', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); @@ -123,7 +123,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { content: fake } } as any), ); - const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound); + const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(4242, AiVoiceChatType.Sound); expect(out).toEqual(fake); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0'); @@ -136,7 +136,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: {} }), ); - const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any); + const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1); expect(out).toEqual([]); }); @@ -149,7 +149,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { .mockResolvedValueOnce(protobuf_encode>({ body: { statusCode: 2 } })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); - const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound); + const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound); expect(out).toMatchObject(node); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; @@ -169,7 +169,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb).mockResolvedValue( protobuf_encode>({ body: { statusCode: 1 } }), ); - await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow( + await expect(new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1, 3)).rejects.toThrow( /AI voice synthesis did not complete/, ); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); @@ -181,7 +181,7 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { vi.mocked(oidb.runOidb) .mockResolvedValueOnce(protobuf_encode>({ body: {} })) .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); - await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any); + await new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1); const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId; const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId; expect(first).toBe(second); diff --git a/packages/core/tests/onebot/extended-actions.test.ts b/packages/core/tests/onebot/extended-actions.test.ts index c4554391..92fd1055 100644 --- a/packages/core/tests/onebot/extended-actions.test.ts +++ b/packages/core/tests/onebot/extended-actions.test.ts @@ -62,6 +62,13 @@ const APIS_ROUTING: Record = { setFriendRemark: ['friend', 'setRemark'], deleteFriend: ['friend', 'delete'], setFriendAddRequest: ['friend', 'handleRequest'], + // ExtrasApi: group todo / stranger status / AI voice. + setGroupTodo: ['extras', 'setGroupTodo'], + completeGroupTodo: ['extras', 'completeGroupTodo'], + cancelGroupTodo: ['extras', 'cancelGroupTodo'], + getStrangerStatus: ['extras', 'getStrangerStatus'], + fetchAiVoiceList: ['extras', 'fetchAiVoiceList'], + fetchAiVoice: ['extras', 'fetchAiVoice'], }; function fakeBridge(overrides: Record = {}): BridgeInterface {