fix(protocol): send super/new faces with the right wire encoding (#168)

A face was always built as a legacy FaceElem (face.index). QQ-NT only renders
classic small faces that way; newer 'super'/animated faces sent as face.index
are silently remapped by the server (e.g. 424→168) or shown as a placeholder.

Classify each face id off QQ's own system-face catalog (0x9154_1, ported from
SLE/Lagrange) and pick the matching wire form:
  - super (animated, aniSticker pack ≠ (1,1)) → CommonElem 37 + QFaceExtra
  - other id ≥ 260                            → CommonElem 33 + QSmallFaceExtra
  - classic id < 260                          → legacy FaceElem

The catalog is fetched once (shared, lazy-warmed off the first face send) and
classify falls back to an id-range guess until it lands. Data-driven so all 66
non-(1,1) super faces encode correctly, not just a hardcoded few.

Verified on a live account: 424→424 (was 168), super 392→392, classic 14→14.
This commit is contained in:
DrSmoothl committed 2026-06-30 16:09:28 +08:00
1 parent f9900053b0
commit c839121fdb
6 files changed
+429 -6

No files matched your search

+42 -6
View File
@@ -2,11 +2,12 @@ import type {
MarkdownData,
MentionExtraSend,
} from '@snowluma/proto-defs/action';
import type { Elem, GroupFileExtra, MarketFacePbReserve } from '@snowluma/proto-defs/element';
import type { Elem, GroupFileExtra, MarketFacePbReserve, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
import { protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { deflateSync } from 'zlib';
import type { BridgeContext } from './bridge-context';
import { sysFaceStore } from './sys-face-store';
import type { MessageElement } from './events';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
@@ -39,10 +40,45 @@ function makeTextElem(text: string): ProtoElem {
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId },
};
// QQ-NT splits face ids across three wire encodings. The legacy FaceElem only
// renders classic small faces; newer "super" / animated faces sent that way are
// silently remapped by the server (e.g. 424→168, issue #168). The split is
// data-driven off the system-face catalog (0x9154_1, see sys-face-store):
// super (animated, aniSticker not pack (1,1)) → CommonElem 37 + QFaceExtra
// other id ≥ 260 → CommonElem 33 + QSmallFaceExtra
// classic id < 260 → legacy FaceElem
function makeFaceElem(faceId: number, ctx?: SendContext): ProtoElem {
// Keep the catalog warm so subsequent super-face sends are classified even if
// this one raced ahead of the first fetch.
if (ctx) sysFaceStore.ensureWarm(ctx.bridge);
const wire = sysFaceStore.classify(faceId);
if (wire.kind === 'super') {
return {
commonElem: {
serviceType: 37,
pbElem: protobuf_encode<QFaceExtra>({
packId: wire.packId,
stickerId: wire.stickerId,
qsid: faceId,
sourceType: 1,
stickerType: wire.stickerType,
randomType: 1,
}),
businessType: 1,
},
};
}
if (wire.kind === 'small') {
return {
commonElem: {
serviceType: 33,
pbElem: protobuf_encode<QSmallFaceExtra>({ faceId, preview: '', preview2: '' }),
businessType: 1,
},
};
}
return { face: { index: faceId } };
}
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
@@ -414,7 +450,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId, ctx));
break;
case 'mface':
@@ -0,0 +1,125 @@
// 0x9154_1 — fetch the bot's system face / emoji catalog.
//
// Mirrors Lagrange.Core's `FetchFullSysFacesService`. One server round-trip
// returns the entire pack list — common faces, "big"/super faces (the giant
// animated emoji), and the magic-face pack. The send path uses each emoji's
// `aniSticker*` metadata to pick the right wire encoding for a face id (see
// element-builder's makeFaceElem + sys-face-store).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbFaceEmoji,
OidbFetchSysFacesReq,
OidbFetchSysFacesResp,
} from '@snowluma/proto-defs/oidb-actions/sys-faces';
import { invokeOidb, type OidbSender } from '../../oidb-service';
/** A single system face / emoji. Field names match Lagrange's `SysFaceEntry`;
* `qSid` is the numeric face ID as a string. */
export interface SysFaceEntry {
qSid: string;
qDes: string;
emCode: string;
qCid: number | null;
aniStickerType: number | null;
aniStickerPackId: number | null;
aniStickerId: number | null;
url: string | null;
emojiNameAlias: string[];
aniStickerWidth: number | null;
aniStickerHeight: number | null;
}
/** One named pack of system faces (e.g. "经典", "MagicFace"). */
export interface SysFacePackEntry {
packName: string;
emojis: SysFaceEntry[];
}
function emojiToEntry(e: OidbFaceEmoji): SysFaceEntry {
return {
qSid: e.qSid ?? '',
qDes: e.qDes ?? '',
emCode: e.emCode ?? '',
qCid: e.qCid ?? null,
aniStickerType: e.aniStickerType ?? null,
aniStickerPackId: e.aniStickerPackId ?? null,
aniStickerId: e.aniStickerId ?? null,
url: e.url?.baseUrl ?? null,
emojiNameAlias: e.emojiNameAlias ?? [],
aniStickerWidth: e.aniStickerWidth ?? null,
aniStickerHeight: e.aniStickerHeight ?? null,
};
}
export namespace FetchSysFaces {
export const command = 0x9154;
export const subCommand = 1;
export type Params = Record<never, never>;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, _p: Params): OidbFetchSysFacesReq => ({
field1: 0,
field2: 7,
field3: '0',
});
export const deserialize = (_ctx: Deps, body: OidbFetchSysFacesResp): SysFacePackEntry[] => {
const packs: SysFacePackEntry[] = [];
// common + special-big share the same content shape.
for (const content of [body.commonFace, body.specialBigFace]) {
for (const list of content?.emojiList ?? []) {
packs.push({
packName: list.emojiPackName ?? '',
emojis: (list.emojiDetail ?? []).map(emojiToEntry),
});
}
}
// Magic faces arrive as a single un-named bundle — Lagrange tags it
// "MagicFace" client-side, so we match for parity.
const magicEmojis = body.specialMagicFace?.field1?.emojiList ?? [];
if (magicEmojis.length > 0) {
packs.push({ packName: 'MagicFace', emojis: magicEmojis.map(emojiToEntry) });
}
return packs;
};
export const encode = (env: OidbBase<OidbFetchSysFacesReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbFetchSysFacesReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbFetchSysFacesResp> =>
protobuf_decode<OidbBase<OidbFetchSysFacesResp>>(bytes);
export const invoke = (deps: Deps, params: Params = {}): Promise<SysFacePackEntry[]> =>
invokeOidb(deps, FetchSysFaces, params);
}
/** Walk a pack list to find an emoji by its numeric face ID, or null. */
export function findFaceEntity(packs: SysFacePackEntry[], faceId: number): SysFaceEntry | null {
const idStr = String(faceId);
for (const pack of packs) {
for (const emoji of pack.emojis) {
if (emoji.qSid === idStr) return emoji;
}
}
return null;
}
/** True when `faceId` is an animated "super face" — has both aniStickerType
* and aniStickerPackId set, and is NOT the (1,1) pack (the regular static
* emojis). Matches Lagrange's `GetUniqueSuperQSids` filter. Super faces ride
* CommonElem serviceType 37 (QFaceExtra); the (1,1) ones ride serviceType 33. */
export function isSuperFaceEntry(emoji: SysFaceEntry): boolean {
if (emoji.aniStickerType == null || emoji.aniStickerPackId == null) return false;
return !(emoji.aniStickerType === 1 && emoji.aniStickerPackId === 1);
}
export function isSuperFaceId(packs: SysFacePackEntry[], faceId: number): boolean {
const emoji = findFaceEntity(packs, faceId);
return emoji !== null && isSuperFaceEntry(emoji);
}
+93
View File
@@ -0,0 +1,93 @@
// Process-wide cache of QQ's system-face catalog (fetched once via 0x9154_1),
// used by the send path to pick a face id's wire encoding. The catalog is the
// same for every account, so a single shared store is fetched lazily and reused.
//
// `classify` is synchronous (the element builder is sync); a face sent before
// the catalog is warm falls back to an id-range guess. `ensureWarm` kicks off
// the one-shot fetch — call it proactively at login so the first super-face
// send is already classified.
import { createLogger } from '@snowluma/common/logger';
import {
FetchSysFaces,
isSuperFaceEntry,
type SysFaceEntry,
type SysFacePackEntry,
} from './oidb-services/sys-faces/fetch-sys-faces';
import type { OidbSender } from './oidb-service';
const log = createLogger('SysFace');
/** Wire encoding a face id maps to. `classic` → legacy FaceElem; `small` →
* CommonElem serviceType 33 (QSmallFaceExtra); `super` → CommonElem
* serviceType 37 (QFaceExtra) for animated/super faces. */
export type FaceWire =
| { kind: 'classic' }
| { kind: 'small' }
| { kind: 'super'; packId: string; stickerId: string; stickerType: number };
/** Pure classification: a super face (per the catalog entry) → `super` with its
* pack/sticker ids; otherwise an id-range guess (`< 260` = classic, else
* small). Used both warm (entry from the catalog) and cold (entry undefined). */
export function faceWireFor(entry: SysFaceEntry | null | undefined, faceId: number): FaceWire {
if (entry && isSuperFaceEntry(entry)) {
return {
kind: 'super',
packId: String(entry.aniStickerPackId ?? 1),
stickerId: String(entry.aniStickerId ?? 0),
stickerType: entry.aniStickerType ?? 0,
};
}
return faceId < 260 ? { kind: 'classic' } : { kind: 'small' };
}
const RETRY_COOLDOWN_MS = 30_000;
class SysFaceStore {
private byId: Map<string, SysFaceEntry> | null = null;
private inflight: Promise<void> | null = null;
private lastFailedAt = 0;
/** Index a fetched catalog (also used by tests to seed without a network). */
load(packs: SysFacePackEntry[]): void {
this.byId = buildIndex(packs);
}
/** Synchronous classification. Falls back to an id-range guess when the
* catalog isn't warm yet or the id is unknown. */
classify(faceId: number): FaceWire {
return faceWireFor(this.byId?.get(String(faceId)), faceId);
}
/** Fire-and-forget one-shot warm. Coalesces concurrent callers; backs off
* briefly after a failure so a flaky fetch isn't hammered per message. */
ensureWarm(sender: OidbSender): void {
if (this.byId || this.inflight) return;
if (Date.now() - this.lastFailedAt < RETRY_COOLDOWN_MS) return;
this.inflight = FetchSysFaces.invoke(sender)
.then((packs) => {
this.load(packs);
log.info('system face catalog loaded: %d faces', this.byId?.size ?? 0);
})
.catch((err) => {
this.lastFailedAt = Date.now();
log.warn('failed to load system face catalog: %s', err instanceof Error ? err.message : String(err));
})
.finally(() => {
this.inflight = null;
});
}
}
function buildIndex(packs: SysFacePackEntry[]): Map<string, SysFaceEntry> {
const map = new Map<string, SysFaceEntry>();
for (const pack of packs) {
for (const emoji of pack.emojis) {
if (emoji.qSid) map.set(emoji.qSid, emoji);
}
}
return map;
}
/** Shared, process-wide catalog (the face set is account-independent). */
export const sysFaceStore = new SysFaceStore();