diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts new file mode 100644 index 00000000..38a082a0 --- /dev/null +++ b/packages/core/src/bridge/actions/extras.ts @@ -0,0 +1,155 @@ +// Tier-2 napcat-parity actions ported as pure oidb calls. Each function +// here corresponds to one napcat PacketApi.pkt.operation.* entry; the +// schemas live in proto/oidb-action.ts. Nothing in this file touches +// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip. + +import type { Bridge } from '../bridge'; +import { runOidb } from '../bridge-oidb'; +import { + OidbGroupTodoSchema, + OidbStrangerStatusReqSchema, + OidbStrangerStatusRespSchema, + OidbAiVoiceListReqSchema, + OidbAiVoiceListRespSchema, + OidbAiVoiceReqSchema, + OidbAiVoiceRespSchema, +} from '../proto/oidb-action'; +import type { MediaIndexNode } from './shared'; + +// ─────────────── Group todo (0xF90) ─────────────── + +export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { + await runOidb(bridge, { + cmd: 'OidbSvcTrpcTcp.0xf90_1', + oidbCmd: 0xF90, subCmd: 1, + request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, + }); +} + +export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { + await runOidb(bridge, { + cmd: 'OidbSvcTrpcTcp.0xf90_2', + oidbCmd: 0xF90, subCmd: 2, + request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, + }); +} + +export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { + await runOidb(bridge, { + cmd: 'OidbSvcTrpcTcp.0xf90_3', + oidbCmd: 0xF90, subCmd: 3, + request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, + }); +} + +// ─────────────── 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 resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, { + cmd: 'OidbSvcTrpcTcp.0xfe1_2', + oidbCmd: 0xFE1, subCmd: 2, + request: { + schema: OidbStrangerStatusReqSchema, + value: { uin, key: [{ key: 27372 }] }, + }, + response: { schema: OidbStrangerStatusRespSchema }, + }); + 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 resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, { + cmd: 'OidbSvcTrpcTcp.0x929d_0', + oidbCmd: 0x929D, subCmd: 0, + request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } }, + response: { schema: OidbAiVoiceListRespSchema }, + }); + return resp?.content ?? []; +} + +/** + * 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 resp = await runOidb<{ + statusCode?: number; + msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> }; + }>(bridge, { + cmd: 'OidbSvcTrpcTcp.0x929b_0', + oidbCmd: 0x929B, subCmd: 0, + request: { + schema: OidbAiVoiceReqSchema, + value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, + }, + response: { schema: OidbAiVoiceRespSchema }, + }); + const node = resp?.msgInfo?.msgInfoBody?.[0]?.index; + if (node) return node; + } + throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); +} diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index ca841697..97b237cb 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -23,6 +23,7 @@ import type { DownloadRKeyInfo, ClientKeyInfo, } from './bridge'; +import type { SendPacketResult } from '../protocol/packet-sender'; export interface BridgeInterface { // ─── Shared state ─── @@ -33,6 +34,12 @@ export interface BridgeInterface { // ─── Resolution ─── resolveUserUid(uin: number, groupId?: number): Promise; + // ─── Raw packet (deliberate escape hatch for `send_packet` action) ─── + // OneBot clients use this to debug or invoke commands SnowLuma has no + // typed wrapper for. Every other method on this interface eventually + // routes through here. + sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; + // ─── Send (messages) ─── sendGroupMessage(groupId: number, elements: MessageElement[]): Promise; sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise; @@ -127,4 +134,12 @@ export interface BridgeInterface { getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise; clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise; sendGroupSign(groupId: number): Promise; + + // ─── 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; } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index fc7932ea..00973246 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -99,6 +99,20 @@ import { clickInlineKeyboardButton as clickInlineKeyboardButton_, sendGroupSign as sendGroupSign_, } from './actions/misc'; +import { + setGroupTodo as setGroupTodo_, + completeGroupTodo as completeGroupTodo_, + cancelGroupTodo as cancelGroupTodo_, + getStrangerStatus as getStrangerStatus_, + fetchAiVoiceList as fetchAiVoiceList_, + fetchAiVoice as fetchAiVoice_, + AiVoiceChatType, + type AiVoiceCategory, + type AiVoiceChatType as AiVoiceChatTypeT, + type StrangerStatus, +} from './actions/extras'; +export { AiVoiceChatType }; +export type { AiVoiceCategory, StrangerStatus }; import { getGroupHonorInfo as getGroupHonorInfo_, forceFetchClientKey as forceFetchClientKey_, @@ -528,5 +542,26 @@ export class Bridge implements BridgeInterface { async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) { return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie); } + + // --- 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); + } } diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index 5e4b8a78..83635c64 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -1125,4 +1125,121 @@ export const Oidb0xf16ReqSchema = { field12: { field: 12, type: 'uint32' as const }, } satisfies ProtoSchema; -export const Oidb0xf16RespSchema = {} satisfies ProtoSchema; \ No newline at end of file +export const Oidb0xf16RespSchema = {} satisfies ProtoSchema; + +// --- 0xF90_{1,2,3}: Set / complete / cancel group todo --- +// All three subCmds share the same body (groupUin + msgSeq); only the +// envelope subCmd differs. Sources: napcat +// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts. + +export const OidbGroupTodoSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + msgSeq: { field: 2, type: 'uint64' as const }, +} satisfies ProtoSchema; + +// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) --- + +export const OidbStrangerStatusKeySchema = { + key: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbStrangerStatusReqSchema = { + uin: { field: 1, type: 'uint32' as const }, + key: { field: 3, type: 'repeated_message' as const, schema: OidbStrangerStatusKeySchema }, +} satisfies ProtoSchema; + +export const OidbStrangerStatusRespStatusSchema = { + key: { field: 1, type: 'uint32' as const }, + value: { field: 2, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const OidbStrangerStatusRespDataSchema = { + status: { field: 2, type: 'message' as const, schema: OidbStrangerStatusRespStatusSchema }, +} satisfies ProtoSchema; + +export const OidbStrangerStatusRespSchema = { + data: { field: 1, type: 'message' as const, schema: OidbStrangerStatusRespDataSchema }, +} satisfies ProtoSchema; + +// --- 0x929D_0: Fetch AI voice character list --- + +export const OidbAiVoiceListReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + chatType: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceListEntrySchema = { + voiceId: { field: 1, type: 'string' as const }, + voiceDisplayName: { field: 2, type: 'string' as const }, + voiceExampleUrl: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceListCategorySchema = { + category: { field: 1, type: 'string' as const }, + voices: { field: 2, type: 'repeated_message' as const, schema: OidbAiVoiceListEntrySchema }, +} satisfies ProtoSchema; + +export const OidbAiVoiceListRespSchema = { + content: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceListCategorySchema }, +} satisfies ProtoSchema; + +// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) --- + +export const OidbAiVoiceSessionSchema = { + sessionId: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + voiceId: { field: 2, type: 'string' as const }, + text: { field: 3, type: 'string' as const }, + chatType: { field: 4, type: 'uint32' as const }, + session: { field: 5, type: 'message' as const, schema: OidbAiVoiceSessionSchema }, +} satisfies ProtoSchema; + +// We only need the fields the OneBot adapter consumes back: the +// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the +// statusCode that the server uses to signal "still rendering, retry". + +export const OidbAiVoiceFileTypeSchema = { + type: { field: 1, type: 'uint32' as const }, + picFormat: { field: 2, type: 'uint32' as const }, + videoFormat: { field: 3, type: 'uint32' as const }, + voiceFormat: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceFileInfoSchema = { + fileSize: { field: 1, type: 'uint32' as const }, + fileHash: { field: 2, type: 'string' as const }, + fileSha1: { field: 3, type: 'string' as const }, + fileName: { field: 4, type: 'string' as const }, + type: { field: 5, type: 'message' as const, schema: OidbAiVoiceFileTypeSchema }, + width: { field: 6, type: 'uint32' as const }, + height: { field: 7, type: 'uint32' as const }, + time: { field: 8, type: 'uint32' as const }, + original: { field: 9, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceIndexNodeSchema = { + info: { field: 1, type: 'message' as const, schema: OidbAiVoiceFileInfoSchema }, + fileUuid: { field: 2, type: 'string' as const }, + storeId: { field: 3, type: 'uint32' as const }, + uploadTime: { field: 4, type: 'uint32' as const }, + ttl: { field: 5, type: 'uint32' as const }, + subType: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbAiVoiceMsgInfoBodySchema = { + index: { field: 1, type: 'message' as const, schema: OidbAiVoiceIndexNodeSchema }, +} satisfies ProtoSchema; + +export const OidbAiVoiceMsgInfoSchema = { + msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceMsgInfoBodySchema }, +} satisfies ProtoSchema; + +export const OidbAiVoiceRespSchema = { + statusCode: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + msgInfo: { field: 4, type: 'message' as const, schema: OidbAiVoiceMsgInfoSchema }, +} satisfies ProtoSchema; \ No newline at end of file diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 5400c464..4de48262 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -221,12 +221,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { // --- RKey --- - h.registerAction('get_rkey', async () => { + const handleGetRkey = async () => { if (ctx.getDownloadRKeys) { return okResponse(await ctx.getDownloadRKeys()); } return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }); + }; + h.registerAction('get_rkey', handleGetRkey); + // napcat exposes the same payload under `nc_get_rkey`; mirror the alias + // so clients that follow napcat's docs work out-of-the-box. + h.registerAction('nc_get_rkey', handleGetRkey); // --- OCR stubs --- @@ -597,10 +601,56 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); + // Filtered (机器人/被忽略) group join requests. SnowLuma already + // implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests; + // these three actions just rename / project the same data for the + // OneBot dialects clients use in the wild. + const fetchFilteredGroupRequests = async () => { + try { + return await ctx.bridge.fetchGroupRequests(true); + } catch { + return []; + } + }; + h.registerAction('get_group_ignored_notifies', async () => { - return okResponse([]); + const reqs = await fetchFilteredGroupRequests(); + return okResponse(reqs.map((r) => ({ + group_id: r.groupId, + group_name: r.groupName, + request_id: r.sequence, + requester_uin: r.targetUin, + requester_nick: r.targetName, + message: r.comment, + checked: r.state !== 1, + actor: r.operatorUin, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, + }))); }); + // napcat name for the subset of ignored notifies that are join requests + // (notify type==7). We map every entry that flowed through filtered + // 0x10c8_2 into napcat's shape — eventType already encodes the request + // category in our pipeline. + h.registerAction('get_group_ignore_add_request', async () => { + const reqs = await fetchFilteredGroupRequests(); + return okResponse(reqs.map((r) => ({ + request_id: r.sequence, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + group_id: r.groupId, + message: r.comment, + group_name: r.groupName, + checked: r.state !== 1, + actor: r.operatorUin, + requester_nick: r.targetName, + }))); + }); + + // get_group_shut_list lives behind an oidb we don't yet wrap; honour + // the napcat contract (empty list) so callers don't blow up. h.registerAction('get_group_shut_list', async () => { return okResponse([]); }); @@ -934,9 +984,170 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); }); - h.registerAction('.send_packet', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + // --- Raw packet escape hatch (napcat parity) --- + // + // napcat exposes both names; the dot-prefix variant is the original + // gocqhttp-era backdoor, the no-prefix one is the modern API. They do + // the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex. + const handleSendPacket = async (params: import('../types').JsonObject) => { + const cmd = asString(params.cmd); + const dataHex = asString(params.data); + const rsp = asBoolean(params.rsp, true); + if (!cmd) return failedResponse(RETCODE.BAD_REQUEST, 'cmd is required'); + if (!/^[0-9a-fA-F]*$/.test(dataHex) || dataHex.length % 2 !== 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); + } + try { + const body = hexToBytes(dataHex); + const result = await ctx.bridge.sendRawPacket(cmd, body); + if (!result.success) { + return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); + } + if (!rsp) return okResponse(null); + const respHex = result.responseData ? bytesToHex(result.responseData) : ''; + return okResponse(respHex); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }; + h.registerAction('send_packet', handleSendPacket); + h.registerAction('.send_packet', handleSendPacket); + + // --- Bot lifecycle (napcat parity) --- + + h.registerAction('bot_exit', async () => { + // Defer so the OK response actually flushes before the process dies. + setTimeout(() => process.exit(0), 50); + return okResponse(); }); + + // SnowLuma has no separate packet-backend process (napcat's packet + // service runs out-of-process and can fail independently). Always + // report healthy. + h.registerAction('nc_get_packet_status', async () => { + return okResponse(null); + }); + + // napcat exposes `delete_group_folder`; SnowLuma's existing + // `delete_group_file_folder` is the same operation. Alias so clients + // following napcat docs work without rewriting payloads. + h.registerAction('delete_group_folder', async (params) => { + const groupId = asNumber(params.group_id); + const folderId = asString(params.folder_id); + if (!groupId || !folderId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); + } + await ctx.bridge.deleteGroupFileFolder(groupId, folderId); + return okResponse(); + }); + + // --- Group todo (oidb 0xF90) --- + // + // The three subcommands share an identical payload (group + msgSeq); + // we extract once and dispatch by action name. msgSeq comes from the + // message metadata cache (set/complete/cancel always target a real + // message the bot has seen). + type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise; + const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => { + const groupId = asNumber(params.group_id); + const messageId = asNumber(params.message_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + const meta = ctx.getMessageMeta(messageId); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + if (!meta.isGroup || meta.targetId !== groupId) { + return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); + } + try { + await op(groupId, BigInt(meta.sequence)); + return okResponse(); + } catch (err) { + 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))); + + // --- 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); + if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); + return okResponse(status); + }); + + // --- AI voice (oidb 0x929D / 0x929B) --- + + h.registerAction('get_ai_characters', async (params) => { + const groupId = asNumber(params.group_id); + 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); + return okResponse(list.map((cat) => ({ + type: cat.category, + characters: cat.voices.map((v) => ({ + character_id: v.voiceId, + character_name: v.voiceDisplayName, + preview_url: v.voiceExampleUrl, + })), + }))); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }); + + h.registerAction('get_ai_record', async (params) => { + const groupId = asNumber(params.group_id); + const character = asString(params.character); + const text = asString(params.text); + const chatType = asNumber(params.chat_type) || 1; + if (!groupId || !character || !text) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); + } + try { + const node = await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); + const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node); + return okResponse(url); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }); + + // napcat's send_group_ai_record is a side-effect-only call: invoking + // fetchAiVoice publishes the voice into the group; the returned + // message_id is always 0 because the oidb call doesn't echo one back. + h.registerAction('send_group_ai_record', async (params) => { + const groupId = asNumber(params.group_id); + const character = asString(params.character); + const text = asString(params.text); + const chatType = asNumber(params.chat_type) || 1; + if (!groupId || !character || !text) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); + } + try { + await ctx.bridge.fetchAiVoice(groupId, character, text, chatType); + return okResponse({ message_id: 0 }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }); +} + +function hexToBytes(hex: string): Uint8Array { + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) { + out[i] = parseInt(hex.substr(i * 2, 2), 16); + } + return out; +} + +function bytesToHex(buf: Buffer | Uint8Array): string { + const arr = buf instanceof Buffer ? buf : Buffer.from(buf); + return arr.toString('hex'); } /** diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts new file mode 100644 index 00000000..eca813a8 --- /dev/null +++ b/packages/core/tests/actions/extras.test.ts @@ -0,0 +1,141 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Same stub-the-oidb-runner pattern as actions/group-admin.test.ts — +// we don't care about wire bytes, just that each function targets the +// right cmd / subCmd / schema. +vi.mock('../../src/bridge/bridge-oidb', () => ({ + runOidb: vi.fn(async () => ({})), +})); + +import * as oidb from '../../src/bridge/bridge-oidb'; +import * as extras from '../../src/bridge/actions/extras'; +import * as schemas from '../../src/bridge/proto/oidb-action'; +import { mockBridge } from './_helpers'; + +describe('actions/extras / group todo (0xF90)', () => { + beforeEach(() => vi.mocked(oidb.runOidb).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) => { + const bridge = mockBridge(); + await fn(bridge as any, 12345, 9876543210n); + const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; + expect(call.cmd).toBe(cmd); + expect(call.oidbCmd).toBe(0xF90); + expect(call.subCmd).toBe(subCmd); + expect(call.request.schema).toBe(schemas.OidbGroupTodoSchema); + expect(call.request.value).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); + }); +}); + +describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { + beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + + it('issues the FE1_2 query with key=27372', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 5n } } } as any); + await extras.getStrangerStatus(bridge as any, 100200); + const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; + expect(call.cmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); + expect(call.oidbCmd).toBe(0xFE1); + expect(call.subCmd).toBe(2); + expect(call.request.value).toMatchObject({ uin: 100200, key: [{ key: 27372 }] }); + }); + + it('low-band values (≤10) map to status*10 with ext_status=0', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 7n } } } as any); + expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 }); + }); + + it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => { + const bridge = mockBridge(); + // value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100; + // bits 16-23 (>>16 & 0xff) = 0x42. + // ext_status = 0xF100 + 0x42 = 0xF142. + vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 0x42F100n } } } as any); + const status = await extras.getStrangerStatus(bridge as any, 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(); + }); + + it('returns null when the server omits the status field', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); + }); +}); + +describe('actions/extras / AI voice (0x929D / 0x929B)', () => { + beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + + it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => { + const bridge = mockBridge(); + const fake = [ + { category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] }, + ]; + vi.mocked(oidb.runOidb).mockResolvedValueOnce({ content: fake } as any); + const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound); + expect(out).toEqual(fake); + const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; + expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929d_0'); + expect(call.request.value).toEqual({ groupUin: 4242, chatType: 1 }); + }); + + it('fetchAiVoiceList returns [] when server replies with no content', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any); + expect(out).toEqual([]); + }); + + it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => { + const bridge = mockBridge(); + const node = { fileUuid: 'uuid-1', subType: 0 }; + vi.mocked(oidb.runOidb) + .mockResolvedValueOnce({ statusCode: 2 } as any) + .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [] } } as any) + .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound); + expect(out).toBe(node); + expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); + const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; + expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929b_0'); + expect(call.request.value).toMatchObject({ + groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1, + }); + // sessionId is randomized but must be a uint32. + expect((call.request.value as any).session.sessionId).toBeTypeOf('number'); + expect((call.request.value as any).session.sessionId).toBeGreaterThanOrEqual(0); + expect((call.request.value as any).session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); + }); + + it('fetchAiVoice throws after exhausting the retry budget', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValue({ statusCode: 1 } as any); + await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow( + /AI voice synthesis did not complete/, + ); + expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); + }); + + it('fetchAiVoice keeps the same sessionId across retries', async () => { + const bridge = mockBridge(); + const node = { fileUuid: 'uuid', subType: 0 }; + vi.mocked(oidb.runOidb) + .mockResolvedValueOnce({} as any) + .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any); + const first = (vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value as any).session.sessionId; + const second = (vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value 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 new file mode 100644 index 00000000..74f0b588 --- /dev/null +++ b/packages/core/tests/onebot/extended-actions.test.ts @@ -0,0 +1,458 @@ +// End-to-end OneBot action tests for the napcat-parity surface added in +// Tier 1 + Tier 2: send_packet, bot_exit, nc_*, group-todo, AI voice, +// and the rewired ignored-notifies family. We drive everything through +// the public `ApiHandler.handle()` entry point so the wiring (including +// param coercion, retcode shape) is part of what's under test. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { ApiHandler, type ApiActionContext } from '../../src/onebot/api-handler'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { GroupRequestInfo } from '../../src/bridge/qq-info'; +import type { MessageMeta } from '../../src/onebot/types'; + +function fakeMeta(overrides: Partial = {}): MessageMeta { + return { + isGroup: true, + targetId: 100, + sequence: 555, + eventName: 'group_message', + clientSequence: 0, + random: 0, + timestamp: 0, + ...overrides, + }; +} + +/** + * Build a BridgeInterface stub that throws on any method we haven't + * pre-stubbed for the test. Same pattern as contact-actions.test.ts — + * keeps tests honest about which surface they actually need. + */ +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(overrides as BridgeInterface, { + get(target, prop) { + if (prop in target) return (target as any)[prop]; + throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`); + }, + }); +} + +/** + * Build the minimum ApiActionContext needed for the tested actions. + * Anything not stubbed throws on access — keeps the dependency surface + * explicit. Only fields the tested actions read are populated. + */ +function fakeCtx(bridge: BridgeInterface, overrides: Partial = {}): ApiActionContext { + const base = { + bridge, + getMessageMeta: () => null, + getMessage: () => null, + getLoginInfo: () => ({ userId: 1, nickname: '' }), + isOnline: () => true, + canSendImage: () => true, + canSendRecord: () => true, + getDownloadRKeys: async () => [], + ...overrides, + }; + return new Proxy(base as ApiActionContext, { + get(target, prop) { + if (prop in target) return (target as any)[prop]; + throw new Error(`fakeCtx: '${String(prop)}' was not stubbed`); + }, + }); +} + +function makeHandler(ctx: ApiActionContext): ApiHandler { + return new ApiHandler(ctx); +} + +// ─── Tier 1: send_packet / .send_packet ─── + +describe('extended-actions / send_packet', () => { + it('hex-decodes data, calls Bridge.sendRawPacket, hex-encodes the response', async () => { + const sendRawPacket: BridgeInterface['sendRawPacket'] = vi.fn(async () => ({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from([0xDE, 0xAD, 0xBE, 0xEF]), + })); + const bridge = fakeBridge({ sendRawPacket }); + const h = makeHandler(fakeCtx(bridge)); + const res = await h.handle('send_packet', { cmd: 'Some.Cmd', data: 'cafebabe', rsp: true }); + const spy = vi.mocked(sendRawPacket); + expect(spy).toHaveBeenCalledOnce(); + const sentBody = spy.mock.calls[0]![1]; + expect(Buffer.from(sentBody).toString('hex')).toBe('cafebabe'); + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: 'deadbeef' }); + }); + + it('.send_packet shares the same handler', async () => { + const sendRawPacket = vi.fn(async () => ({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0), + })); + const h = makeHandler(fakeCtx(fakeBridge({ sendRawPacket: sendRawPacket as any }))); + const res = await h.handle('.send_packet', { cmd: 'C', data: '' }); + expect(res.status).toBe('ok'); + expect(sendRawPacket).toHaveBeenCalledOnce(); + }); + + it('with rsp=false returns null and ignores responseData', async () => { + const bridge = fakeBridge({ + sendRawPacket: (async () => ({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from('00ff', 'hex'), + })) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '', rsp: false }); + expect(res).toMatchObject({ status: 'ok', data: null }); + }); + + it('rejects missing cmd', async () => { + const bridge = fakeBridge({ sendRawPacket: vi.fn() as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: '', data: '' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); + + it('rejects malformed hex', async () => { + const sendRawPacket = vi.fn(); + const bridge = fakeBridge({ sendRawPacket: sendRawPacket as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'ZZZZ' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(sendRawPacket).not.toHaveBeenCalled(); + }); + + it('rejects odd-length hex', async () => { + const bridge = fakeBridge({ sendRawPacket: vi.fn() as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'abc' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); + + it('propagates wire-level failure as action_failed', async () => { + const bridge = fakeBridge({ + sendRawPacket: (async () => ({ + success: false, gotResponse: false, errorCode: -1, errorMessage: 'no sender', responseData: null, + })) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '' }); + expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'no sender' }); + }); +}); + +// ─── Tier 1: bot_exit ─── + +describe('extended-actions / bot_exit', () => { + let exitSpy: ReturnType; + beforeEach(() => { + vi.useFakeTimers(); + exitSpy = vi.spyOn(process, 'exit').mockImplementation(((_code?: number) => undefined) as any); + }); + afterEach(() => { + vi.useRealTimers(); + exitSpy.mockRestore(); + }); + + it('returns ok immediately, then exits on the deferred timer', async () => { + const h = makeHandler(fakeCtx(fakeBridge())); + const res = await h.handle('bot_exit', {}); + expect(res).toMatchObject({ status: 'ok', retcode: 0 }); + expect(exitSpy).not.toHaveBeenCalled(); + vi.advanceTimersByTime(100); + expect(exitSpy).toHaveBeenCalledWith(0); + }); +}); + +// ─── Tier 1: nc_get_packet_status / nc_get_rkey ─── + +describe('extended-actions / nc_get_packet_status', () => { + it('reports healthy with no dependency on bridge', async () => { + const h = makeHandler(fakeCtx(fakeBridge())); + const res = await h.handle('nc_get_packet_status', {}); + expect(res).toEqual({ status: 'ok', retcode: 0, data: null }); + }); +}); + +describe('extended-actions / nc_get_rkey', () => { + it('reuses the same data the get_rkey handler returns', async () => { + const ctx = fakeCtx(fakeBridge(), { + getDownloadRKeys: async () => [{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }], + }); + const h = makeHandler(ctx); + const a = await h.handle('get_rkey', {}); + const b = await h.handle('nc_get_rkey', {}); + expect(b).toEqual(a); + expect(b.data).toEqual([{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }]); + }); +}); + +// ─── Tier 1: group-request ignored / shut list / ignore-add ─── + +function fakeFilteredRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 999, + groupName: 'g', + targetUid: 'u_t', + targetUin: 5555, + targetName: 'target', + invitorUid: 'u_i', + invitorUin: 7777, + invitorName: 'inviter', + operatorUid: 'u_o', + operatorUin: 8888, + operatorName: 'op', + sequence: 42, + state: 1, + eventType: 7, + comment: 'pls', + filtered: true, + ...overrides, + }; +} + +describe('extended-actions / get_group_ignored_notifies', () => { + it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => + filtered ? [fakeFilteredRequest()] : [] + ); + const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any }); + const h = makeHandler(fakeCtx(bridge)); + const res = await h.handle('get_group_ignored_notifies', {}); + expect(fetchGroupRequests).toHaveBeenCalledWith(true); + expect(res.status).toBe('ok'); + expect(res.data).toEqual([{ + group_id: 999, + group_name: 'g', + request_id: 42, + requester_uin: 5555, + requester_nick: 'target', + message: 'pls', + checked: false, // state == 1 → un-checked + actor: 8888, + invitor_uin: 7777, + invitor_nick: 'inviter', + flag: '7:999:u_t:filtered', + }]); + }); + + it('returns [] when the fetch throws', async () => { + const bridge = fakeBridge({ + fetchGroupRequests: (async () => { throw new Error('boom'); }) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignored_notifies', {}); + expect(res).toMatchObject({ status: 'ok', data: [] }); + }); +}); + +describe('extended-actions / get_group_ignore_add_request', () => { + it('projects the same filtered list into napcat\'s ignore-add-request shape', async () => { + const bridge = fakeBridge({ + fetchGroupRequests: (async () => [fakeFilteredRequest({ state: 2 })]) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignore_add_request', {}); + expect(res.status).toBe('ok'); + expect(res.data).toEqual([{ + request_id: 42, + invitor_uin: 7777, + invitor_nick: 'inviter', + group_id: 999, + message: 'pls', + group_name: 'g', + checked: true, // state == 2 → checked + actor: 8888, + requester_nick: 'target', + }]); + }); +}); + +describe('extended-actions / get_group_shut_list', () => { + it('returns empty list (oidb not yet wrapped)', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {}); + expect(res).toEqual({ status: 'ok', retcode: 0, data: [] }); + }); +}); + +// ─── Tier 1: delete_group_folder alias ─── + +describe('extended-actions / delete_group_folder', () => { + it('forwards to bridge.deleteGroupFileFolder', async () => { + const deleteGroupFileFolder = vi.fn(async () => {}); + const bridge = fakeBridge({ deleteGroupFileFolder: deleteGroupFileFolder as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { + group_id: 100, folder_id: 'fid-1', + }); + expect(deleteGroupFileFolder).toHaveBeenCalledWith(100, 'fid-1'); + expect(res.status).toBe('ok'); + }); + + it('rejects missing fields', async () => { + const bridge = fakeBridge({ deleteGroupFileFolder: vi.fn() as any }); + const r1 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { folder_id: 'x' }); + const r2 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { group_id: 1 }); + expect(r1).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(r2).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── Tier 2: group todo ─── + +describe('extended-actions / set_/complete_/cancel_group_todo', () => { + it.each([ + ['set_group_todo', 'setGroupTodo'], + ['complete_group_todo', 'completeGroupTodo'], + ['cancel_group_todo', 'cancelGroupTodo'], + ] as const)('%s resolves message meta then calls bridge.%s with the sequence', async (action, method) => { + const bridgeMethod = vi.fn(async () => {}); + const bridge = fakeBridge({ [method]: bridgeMethod } as any); + const ctx = fakeCtx(bridge, { + getMessageMeta: (id: number) => id === 7 ? fakeMeta({ targetId: 100, sequence: 555 }) : null, + }); + const res = await makeHandler(ctx).handle(action, { group_id: 100, message_id: 7 }); + expect(res.status).toBe('ok'); + expect(bridgeMethod).toHaveBeenCalledWith(100, 555n); + }); + + it('rejects when message meta is missing', async () => { + const ctx = fakeCtx(fakeBridge(), { getMessageMeta: () => null }); + const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 1, message_id: 9999 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'message not found' }); + }); + + it('rejects when message belongs to a different chat', async () => { + const ctx = fakeCtx(fakeBridge(), { + getMessageMeta: () => fakeMeta({ targetId: 222 }), + }); + const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); + + it('rejects when message is a private message', async () => { + const ctx = fakeCtx(fakeBridge(), { + getMessageMeta: () => fakeMeta({ isGroup: false }), + }); + const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); + + it('rejects missing params', async () => { + const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 }); + const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 }); + expect(r1).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(r2).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── Tier 2: nc_get_user_status ─── + +describe('extended-actions / nc_get_user_status', () => { + it('returns whatever bridge.getStrangerStatus reports', async () => { + const getStrangerStatus = vi.fn(async () => ({ status: 10, ext_status: 0x1234 })); + const bridge = fakeBridge({ getStrangerStatus: getStrangerStatus as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 999 }); + expect(getStrangerStatus).toHaveBeenCalledWith(999); + expect(res).toMatchObject({ status: 'ok', data: { status: 10, ext_status: 0x1234 } }); + }); + + it('reports action_failed when bridge returns null', async () => { + const bridge = fakeBridge({ getStrangerStatus: (async () => null) as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 1 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); + + it('rejects missing user_id', async () => { + const bridge = fakeBridge({ getStrangerStatus: vi.fn() as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── Tier 2: AI voice trio ─── + +describe('extended-actions / get_ai_characters', () => { + it('flattens server categories into {type, characters[]}', async () => { + const fetchAiVoiceList = vi.fn(async () => [{ + category: 'cute', + voices: [ + { voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://a' }, + { voiceId: 'v2', voiceDisplayName: 'V2', voiceExampleUrl: 'http://b' }, + ], + }]); + const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { + group_id: 100, chat_type: 1, + }); + expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1); + expect(res.data).toEqual([{ + type: 'cute', + characters: [ + { character_id: 'v1', character_name: 'V1', preview_url: 'http://a' }, + { character_id: 'v2', character_name: 'V2', preview_url: 'http://b' }, + ], + }]); + }); + + it('defaults chat_type to 1 (Sound) when unspecified', async () => { + const fetchAiVoiceList = vi.fn(async () => []); + const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any }); + await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 }); + expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1); + }); + + it('surfaces bridge errors as action_failed', async () => { + const bridge = fakeBridge({ + fetchAiVoiceList: (async () => { throw new Error('rate limited'); }) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rate limited' }); + }); +}); + +describe('extended-actions / get_ai_record', () => { + it('feeds IndexNode from fetchAiVoice into fetchGroupPttUrlByNode and returns the URL', async () => { + const node = { fileUuid: 'voice-uuid' }; + const fetchAiVoice = vi.fn(async () => node); + const fetchGroupPttUrlByNode = vi.fn(async () => 'http://voice.silk'); + const bridge = fakeBridge({ + fetchAiVoice: fetchAiVoice as any, + fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', { + group_id: 100, character: 'v1', text: 'hello', + }); + expect(fetchAiVoice).toHaveBeenCalledWith(100, 'v1', 'hello', 1); + expect(fetchGroupPttUrlByNode).toHaveBeenCalledWith(100, node); + expect(res).toMatchObject({ status: 'ok', data: 'http://voice.silk' }); + }); + + it('rejects missing fields', async () => { + const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { character: 'v', text: 't' }); + const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, text: 't' }); + const r3 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, character: 'v' }); + expect(r1).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(r2).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(r3).toMatchObject({ status: 'failed', retcode: 1400 }); + }); + + it('reports action_failed when synthesis exhausts retries', async () => { + const bridge = fakeBridge({ + fetchAiVoice: (async () => { throw new Error('AI voice synthesis did not complete'); }) as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', { + group_id: 1, character: 'v', text: 't', + }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); +}); + +describe('extended-actions / send_group_ai_record', () => { + it('side-effects fetchAiVoice (no URL fetch) and returns message_id=0', async () => { + const fetchAiVoice = vi.fn(async () => ({ fileUuid: 'uuid' })); + const fetchGroupPttUrlByNode = vi.fn(); + const bridge = fakeBridge({ + fetchAiVoice: fetchAiVoice as any, + fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any, + }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', { + group_id: 100, character: 'v', text: 'hi', + }); + expect(fetchAiVoice).toHaveBeenCalledOnce(); + expect(fetchGroupPttUrlByNode).not.toHaveBeenCalled(); + expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } }); + }); +});