refactor(oidb): migrate extras.ts OIDB cmds to namespaces

5 logical OIDB cmds → 4 namespace files (group todo's 3 sub-cmds
collapse into one namespace with a dynamic resolver):

  - GroupTodo          (0xF90_1/2/3) — set/complete/cancel via the
                                       new `action` discriminator
  - GetStrangerStatus  (0xFE1_2)     — uinForm=true; preserves the
                                       (status*10, ext_status) decode
                                       quirk verbatim
  - FetchAiVoiceList   (0x929D_0)
  - FetchAiVoice       (0x929B_0)    — single poll; retry loop
                                       stays on the facade so callers
                                       can plug their own back-off

Facade keeps the 6 public methods (setGroupTodo / completeGroupTodo /
cancelGroupTodo / getStrangerStatus / fetchAiVoiceList / fetchAiVoice)
as one-line forwarders; only `getStrangerStatus` wraps in try/catch
to preserve its "return null on transport failure" contract, and
`fetchAiVoice` keeps the polling loop.

30 new namespace-level tests; extras.test.ts moved onto the
sendRawPacket assertion model.

Verification:
  - typecheck green
  - @snowluma/bridge: 24 files / 195 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
This commit is contained in:
DrSmoothl committed 2026-05-22 23:45:13 +08:00
1 parent 8356121518
commit 80afa31f5c
11 files changed
+606 -180

No files matched your search

+16
View File
@@ -115,6 +115,22 @@
"types": "./src/oidb-services/web/get-pskey.ts",
"default": "./src/oidb-services/web/get-pskey.ts"
},
"./oidb-services/extras/group-todo": {
"types": "./src/oidb-services/extras/group-todo.ts",
"default": "./src/oidb-services/extras/group-todo.ts"
},
"./oidb-services/extras/get-stranger-status": {
"types": "./src/oidb-services/extras/get-stranger-status.ts",
"default": "./src/oidb-services/extras/get-stranger-status.ts"
},
"./oidb-services/extras/fetch-ai-voice-list": {
"types": "./src/oidb-services/extras/fetch-ai-voice-list.ts",
"default": "./src/oidb-services/extras/fetch-ai-voice-list.ts"
},
"./oidb-services/extras/fetch-ai-voice": {
"types": "./src/oidb-services/extras/fetch-ai-voice.ts",
"default": "./src/oidb-services/extras/fetch-ai-voice.ts"
},
"./bridge-context": {
"types": "./src/bridge-context.ts",
"default": "./src/bridge-context.ts"
@@ -0,0 +1,50 @@
// 0x929D_0 — fetch the catalog of AI voices available for synthesis
// in a given group, grouped by category. Returns the categories
// straight from the wire (caller already expects the wire shape).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbAiVoiceListReq, OidbAiVoiceListResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export namespace FetchAiVoiceList {
export const command = 0x929D;
export const subCommand = 0;
export interface Params {
groupId: number;
chatType: number;
}
export type Deps = OidbSender;
export const serialize = (p: Params): OidbAiVoiceListReq => ({
groupUin: p.groupId,
chatType: p.chatType,
});
export const deserialize = (body: OidbAiVoiceListResp): AiVoiceCategory[] =>
(body.content as AiVoiceCategory[] | undefined) ?? [];
export const encode = (env: OidbBase<OidbAiVoiceListReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceListResp> =>
protobuf_decode<OidbBase<OidbAiVoiceListResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceCategory[]> =>
invokeOidb(deps, FetchAiVoiceList, params);
}
@@ -0,0 +1,68 @@
// 0x929B_0 — kick off AI voice synthesis and poll until the rendered
// media is available. The server may return an empty msgInfo while
// the render is in-flight; the facade polls up to `maxRetries` times.
//
// `sessionId` is a random 32-bit value used by the server to
// de-duplicate retries of the same synthesis request.
//
// Each `invoke()` is a SINGLE poll — the retry loop lives on the
// facade so callers can plug their own back-off / cancellation in
// without forking the namespace.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbAiVoiceReq, OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
/** Subset of AiVoiceMediaIndex (defined in @snowluma/core/apis/shared)
* that the AI voice response payload populates. Kept inline here so
* the namespace stays self-contained against @snowluma/bridge — the
* facade casts back to the richer core-side type. */
export interface AiVoiceMediaIndex {
info?: { fileSize?: number; fileName?: string; type?: { type?: number; voiceFormat?: number } };
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
export namespace FetchAiVoice {
export const command = 0x929B;
export const subCommand = 0;
export interface Params {
groupId: number;
voiceId: string;
text: string;
chatType: number;
/** Random 32-bit session id; server uses this to deduplicate polls. */
sessionId: number;
}
export type Deps = OidbSender;
export const serialize = (p: Params): OidbAiVoiceReq => ({
groupUin: p.groupId,
voiceId: p.voiceId,
text: p.text,
chatType: p.chatType,
session: { sessionId: p.sessionId },
});
export const deserialize = (body: OidbAiVoiceResp): AiVoiceMediaIndex | null => {
const node = body.msgInfo?.msgInfoBody?.[0]?.index as AiVoiceMediaIndex | undefined;
return node ?? null;
};
export const encode = (env: OidbBase<OidbAiVoiceReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbAiVoiceReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbAiVoiceResp> =>
protobuf_decode<OidbBase<OidbAiVoiceResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<AiVoiceMediaIndex | null> =>
invokeOidb(deps, FetchAiVoice, params);
}
@@ -0,0 +1,60 @@
// 0xFE1_2 — fetch the stranger's status (online / away / busy /
// invisible). Same OIDB cmd as fetchUserProfile but a different
// request shape (only key 27372 = status, no other property keys),
// and we decode the ext-bigint status word into napcat's
// (status × 10, ext_status) pair.
//
// `uinForm` is set so the server takes the UIN-form validation path;
// without it newer NTQQ rejects with `[oidb] one of uid/openid is
// invaild`. Same flag fetchUserProfile uses.
//
// On any transport / decode failure the deserialize step is bypassed
// — the facade swallows the namespace-level exception and surfaces
// `null` so callers get a clean retcode.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface StrangerStatus {
status: number;
ext_status: number;
}
export namespace GetStrangerStatus {
export const command = 0xFE1;
export const subCommand = 2;
export const uinForm = true;
export interface Params {
uin: number;
}
export type Deps = OidbSender;
export const serialize = (p: Params): OidbStrangerStatusReq => ({
uin: p.uin,
key: [{ key: 27372 }],
});
export const deserialize = (body: OidbStrangerStatusResp): StrangerStatus | null => {
const raw = body.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw as any);
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 };
};
export const encode = (env: OidbBase<OidbStrangerStatusReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbStrangerStatusReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbStrangerStatusResp> =>
protobuf_decode<OidbBase<OidbStrangerStatusResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<StrangerStatus | null> =>
invokeOidb(deps, GetStrangerStatus, params);
}
@@ -0,0 +1,48 @@
// 0xF90 — group todo (群待办) CRUD.
// subCommand 1 = set, 2 = complete, 3 = cancel
//
// All three sub-cmds share the same request shape ((groupUin, msgSeq))
// so they collapse into one namespace with a dynamic subcmd resolver.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export type GroupTodoAction = 'set' | 'complete' | 'cancel';
const ACTION_TO_SUBCMD: Record<GroupTodoAction, number> = {
set: 1,
complete: 2,
cancel: 3,
};
export namespace GroupTodo {
export const command = 0xF90;
export interface Params {
groupId: number;
msgSeq: bigint;
action: GroupTodoAction;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => ACTION_TO_SUBCMD[p.action];
export const serialize = (p: Params): OidbGroupTodo => ({
groupUin: p.groupId,
msgSeq: p.msgSeq,
});
export const deserialize = (_: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbGroupTodo>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupTodo>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, GroupTodo, params);
}
@@ -0,0 +1,63 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbAiVoiceListReq, OidbAiVoiceListResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchAiVoiceList } from '../../../src/oidb-services/extras/fetch-ai-voice-list';
function makeSender(body?: OidbAiVoiceListResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchAiVoiceList namespace', () => {
it('declares 0x929D_0', () => {
expect(FetchAiVoiceList.command).toBe(0x929D);
expect(FetchAiVoiceList.subCommand).toBe(0);
});
describe('serialize', () => {
it('passes groupUin / chatType verbatim', () => {
expect(FetchAiVoiceList.serialize({ groupId: 4242, chatType: 1 })).toEqual({
groupUin: 4242, chatType: 1,
});
});
});
describe('deserialize', () => {
it('returns content array verbatim', () => {
const out = FetchAiVoiceList.deserialize({
content: [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
],
});
expect(out).toEqual([
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
]);
});
it('returns [] when content is omitted', () => {
expect(FetchAiVoiceList.deserialize({})).toEqual([]);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x929d_0', async () => {
const sender = makeSender({ content: [] });
await FetchAiVoiceList.invoke(sender, { groupId: 100, chatType: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929d_0');
});
it('encodes envelope body correctly', async () => {
const sender = makeSender({ content: [] });
await FetchAiVoiceList.invoke(sender, { groupId: 4242, chatType: 2 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbAiVoiceListReq>>(bytes);
expect(env.body).toMatchObject({ groupUin: 4242, chatType: 2 });
});
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbAiVoiceReq, OidbAiVoiceResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchAiVoice } from '../../../src/oidb-services/extras/fetch-ai-voice';
function makeSender(body?: OidbAiVoiceResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchAiVoice namespace', () => {
it('declares 0x929B_0', () => {
expect(FetchAiVoice.command).toBe(0x929B);
expect(FetchAiVoice.subCommand).toBe(0);
});
describe('serialize', () => {
it('packages every field including sessionId into session sub-message', () => {
const out = FetchAiVoice.serialize({
groupId: 100, voiceId: 'v', text: 'hi', chatType: 1, sessionId: 0xCAFE,
});
expect(out).toEqual({
groupUin: 100, voiceId: 'v', text: 'hi', chatType: 1,
session: { sessionId: 0xCAFE },
});
});
});
describe('deserialize', () => {
it('returns the first msgInfoBody index when present', () => {
const node = { fileUuid: 'uuid', subType: 1 };
expect(FetchAiVoice.deserialize({
msgInfo: { msgInfoBody: [{ index: node }] },
} as any)).toMatchObject(node);
});
it('returns null when msgInfo is empty / missing', () => {
expect(FetchAiVoice.deserialize({} as any)).toBeNull();
expect(FetchAiVoice.deserialize({ msgInfo: {} } as any)).toBeNull();
expect(FetchAiVoice.deserialize({ msgInfo: { msgInfoBody: [] } } as any)).toBeNull();
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x929b_0', async () => {
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: { fileUuid: 'u' } }] } } as any);
await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929b_0');
});
it('returns the parsed index node', async () => {
const node = { fileUuid: 'uuid', subType: 1 };
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(out).toMatchObject(node);
});
it('returns null when server polls back empty msgInfo (in-flight)', async () => {
const sender = makeSender({} as any);
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(out).toBeNull();
});
it('passes the sessionId through to the wire envelope verbatim', async () => {
const sender = makeSender({} as any);
await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 0xCAFEBABE });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bytes);
expect(env.body?.session?.sessionId).toBe(0xCAFEBABE);
});
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetStrangerStatus } from '../../../src/oidb-services/extras/get-stranger-status';
function makeSender(body?: OidbStrangerStatusResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetStrangerStatus namespace', () => {
it('declares 0xFE1_2 with uinForm=true', () => {
expect(GetStrangerStatus.command).toBe(0xFE1);
expect(GetStrangerStatus.subCommand).toBe(2);
expect(GetStrangerStatus.uinForm).toBe(true);
});
describe('serialize', () => {
it('always queries only key 27372 (status property)', () => {
const out = GetStrangerStatus.serialize({ uin: 100200 });
expect(out).toEqual({ uin: 100200, key: [{ key: 27372 }] });
});
});
describe('deserialize', () => {
it('low-band (≤10) values map to (value*10, 0)', () => {
expect(GetStrangerStatus.deserialize({ data: { status: { value: 7n } } })).toEqual({ status: 70, ext_status: 0 });
expect(GetStrangerStatus.deserialize({ data: { status: { value: 10n } } })).toEqual({ status: 100, ext_status: 0 });
});
it('high-band values decompose into (0xff00 + (>>16 & 0xff)) ext_status', () => {
// 0x42F100 → bits 8..15 = 0xF1<<8 = 0xF100, bits 16..23 = 0x42 → 0xF142
expect(GetStrangerStatus.deserialize({ data: { status: { value: 0x42F100n } } }))
.toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when status field is missing', () => {
expect(GetStrangerStatus.deserialize({})).toBeNull();
expect(GetStrangerStatus.deserialize({ data: {} })).toBeNull();
expect(GetStrangerStatus.deserialize({ data: { status: {} } })).toBeNull();
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfe1_2 with uinForm=true (envelope reserved=1)', async () => {
const sender = makeSender({ data: { status: { value: 5n } } });
await GetStrangerStatus.invoke(sender, { uin: 100200 });
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbStrangerStatusReq>>(bytes);
expect(env.reserved).toBe(1);
});
it('returns the decoded status object', async () => {
const sender = makeSender({ data: { status: { value: 5n } } });
const out = await GetStrangerStatus.invoke(sender, { uin: 1 });
expect(out).toEqual({ status: 50, ext_status: 0 });
});
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GroupTodo } from '../../../src/oidb-services/extras/group-todo';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GroupTodo namespace', () => {
it('declares 0xF90', () => {
expect(GroupTodo.command).toBe(0xF90);
});
describe('resolveSubCommand', () => {
it('maps set → 1', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'set' })).toBe(1);
});
it('maps complete → 2', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'complete' })).toBe(2);
});
it('maps cancel → 3', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'cancel' })).toBe(3);
});
});
describe('serialize', () => {
it('packages groupUin + msgSeq verbatim regardless of action', () => {
for (const action of ['set', 'complete', 'cancel'] as const) {
const out = GroupTodo.serialize({ groupId: 12345, msgSeq: 9876543210n, action });
expect(out).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
}
});
});
describe('invoke (e2e)', () => {
it.each([
['set', 'OidbSvcTrpcTcp.0xf90_1'] as const,
['complete', 'OidbSvcTrpcTcp.0xf90_2'] as const,
['cancel', 'OidbSvcTrpcTcp.0xf90_3'] as const,
])('action %s routes to %s', async (action, expectedWire) => {
const sender = makeSender();
await GroupTodo.invoke(sender, { groupId: 12345, msgSeq: 100n, action });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe(expectedWire);
});
it('encodes envelope body correctly', async () => {
const sender = makeSender();
await GroupTodo.invoke(sender, { groupId: 100, msgSeq: 999n, action: 'set' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupTodo>>(bytes);
expect(env.body).toEqual({ groupUin: 100, msgSeq: 999n });
});
});
});
+27 -82
View File
@@ -1,34 +1,21 @@
// 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).
// ExtrasApi — facade over Tier-2 napcat-parity OIDB cmds (group
// todo CRUD / stranger status decode / AI voice list + synthesis).
// Every method is a one-line forwarder to a self-contained namespace
// under @snowluma/bridge/oidb-services/extras.
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 './shared';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
import { GroupTodo } from '@snowluma/bridge/oidb-services/extras/group-todo';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/bridge/oidb-services/extras/get-stranger-status';
import {
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/bridge/oidb-services/extras/fetch-ai-voice-list';
import { FetchAiVoice } from '@snowluma/bridge/oidb-services/extras/fetch-ai-voice';
// ─────────────── public types (re-exported from bridge.ts as before) ───
export interface StrangerStatus {
status: number;
ext_status: number;
}
export type StrangerStatus = NamespaceStrangerStatus;
export const AiVoiceChatType = {
Unknown: 0,
@@ -37,71 +24,40 @@ export const AiVoiceChatType = {
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
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<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 1, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
async completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 2, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 3, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
// ─────────────── 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.
* Returns `null` on transport / decode failure rather than throwing,
* so the OneBot action can produce a clean retcode without try/catch
* gymnastics. Namespace throws on transport failure → swallow here.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
const bridge = asBridge(this.ctx);
try {
const env = makeOidbEnvelope<OidbStrangerStatusReq>(
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<OidbBase<OidbStrangerStatusReq>>(env));
const resp = protobuf_decode<OidbBase<OidbStrangerStatusResp>>(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 };
return await GetStrangerStatus.invoke(this.ctx, { uin });
} catch {
return null;
}
@@ -109,12 +65,8 @@ export class ExtrasApi {
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbAiVoiceListReq>(0x929D, 0, { groupUin: groupId, chatType });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env));
const resp = protobuf_decode<OidbBase<OidbAiVoiceListResp>>(respBytes).body;
return (resp?.content as AiVoiceCategory[] | undefined) ?? [];
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
@@ -133,18 +85,11 @@ export class ExtrasApi {
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
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<OidbAiVoiceReq>(
0x929B, 0,
{ groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode<OidbBase<OidbAiVoiceReq>>(env));
const resp = protobuf_decode<OidbBase<OidbAiVoiceResp>>(respBytes).body;
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined;
if (node) return node;
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
+71 -98
View File
@@ -1,189 +1,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { describe, it, expect } from 'vitest';
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';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (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('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
// namespaces under @snowluma/bridge/oidb-services/extras. Tests assert
// against bridge.sendRawPacket directly.
import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras';
import { mockBridge } from './_helpers';
describe('apis/extras / group todo (0xF90)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
describe('apis/extras / group todo (0xF90)', () => {
it.each([
['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) => {
['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1'] as const,
['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2'] as const,
['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3'] as const,
])('%s dispatches the right subCmd with shared body', async (method, cmd) => {
const bridge = mockBridge();
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]!;
expect(oidbCmd).toBe(0xF90);
expect(sub).toBe(subCmd);
expect(body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe(cmd);
const env = protobuf_decode<OidbBase<OidbGroupTodo>>(bytes);
expect(env.body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
});
});
describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('issues the FE1_2 query with key=27372', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 5n } } } }),
);
));
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]!;
expect(oidbCmd).toBe(0xFE1);
expect(sub).toBe(2);
expect(body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbStrangerStatusReq>>(bytes);
expect(env.command).toBe(0xFE1);
expect(env.subCommand).toBe(2);
expect(env.body).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(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 7n } } } }),
);
));
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 () => {
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(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 0x42F100n } } } }),
);
));
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'));
bridge.sendRawPacket.mockRejectedValueOnce(new Error('boom'));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
it('returns null when the server omits the status field', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: {} }),
);
));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
});
describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).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(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: { content: fake } } as any),
);
));
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');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toEqual({ groupUin: 4242, chatType: 1 });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929d_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceListReq>>(bytes);
expect(env.body).toEqual({ groupUin: 4242, chatType: 1 });
});
it('fetchAiVoiceList returns [] when server replies with no content', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: {} }),
);
));
const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1);
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
const bridge = mockBridge();
// subType is non-zero so proto3 doesn't omit it from the wire (the
// re-decoded object must include the field for the matcher to spot it).
const node = { fileUuid: 'uuid-1', subType: 1 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } } as any)))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
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]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0x929b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any;
expect(body).toMatchObject({
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929b_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bytes);
expect(env.body).toMatchObject({
groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1,
});
// sessionId is randomized but must be a uint32.
expect(body.session.sessionId).toBeTypeOf('number');
expect(body.session.sessionId).toBeGreaterThanOrEqual(0);
expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
const sessionId = env.body?.session?.sessionId;
expect(typeof sessionId).toBe('number');
expect(sessionId).toBeGreaterThanOrEqual(0);
expect(sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
});
it('fetchAiVoice throws after exhausting the retry budget', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } }),
);
bridge.sendRawPacket.mockResolvedValue(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } as any }),
));
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);
expect(bridge.sendRawPacket).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(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
const node = { fileUuid: 'uuid', subType: 1 };
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } 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);
const env1 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[0]![1]);
const env2 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId);
});
});