refactor(protocol): decide message bubbles after decode

Live push and history now share one keep-or-drop decision. Control
signals and empty bodies stay hidden; undecodable content is kept and
logged on both paths.
This commit is contained in:
DrSmoothl committed 2026-08-30 13:45:22 +08:00
1 parent f6adadcd12
commit a0f152229d
7 files changed
+252 -90

No files matched your search

+90 -17
View File
@@ -1,6 +1,11 @@
import { hexPreview } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { Elem } from '@snowluma/proto-defs/element';
import type { MsgPushHead, PushMsgBody } from './context';
import { hasDecodableContent } from './rich-body-decoder';
const log = createLogger('MsgPush');
// C2C-family message types (private 166, temp 141, and 167) whose pushes QQ NT
// classifies by `c2c_cmd`. RE: `long_cnn_msg_mgr.cc::OnRecvSysMsg` gates on
// exactly this set (svr_msg_type-141 bitmask 0x6000001 → {141,166,167}).
@@ -13,13 +18,15 @@ const C2C_CONTROL_TYPES = new Set<number>([141, 166, 167]);
// phantom (#102) is one of them.
const C2C_CONTROL_CMDS = new Set<number>([1, 73, 75, 129, 131, 133, 135, 192]);
export type MessageSurvival = 'drop-control' | 'drop-blank' | 'keep-undecoded' | 'keep';
/**
* Whether a push is a C2C control/system signal that QQ NT never renders as a
* chat message (it dispatches it through `OnRecvSysMsg` instead). Matched by
* `(msgType, c2cCmd)` exactly as the official client's header codec does, so it
* catches these even on the rare occasion they carry junk content that would
* otherwise decode to a stray element. The precise complement to
* {@link isBlankMessage}, which only catches the content-less case.
* otherwise decode to a stray element. History may skip these before decode;
* the post-decode filter still returns `drop-control` for the same decision.
*/
export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>): boolean {
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
@@ -27,21 +34,7 @@ export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>):
/**
* A message-kind event is "blank" — the "[空消息]" phantom from #102 — when it
* decoded to zero elements AND its body carried nothing decodable. These are
* QQ's content-less C2C control/system pushes (msgType 166/141/167 carrying a
* `c2c_cmd`, routed by the official client through `OnRecvSysMsg` rather than
* shown as a bubble).
*
* QQ NT drops such records before the UI ever sees them, in BOTH the live push
* path and the history (roam) fetch path — RE of `wrapper.linux.node`:
* - live/roam C2C: `c2c_roam_msg_mgr.cc::FilterBlankMsgAndRetryFetch`
* - group roam: `group_roam_msg_worker.cc::FilterBlankSeqsMsg`
* So we mirror it everywhere a message event is produced — live (`parseMsgPush`)
* and history (`fetchC2cMessageRange` / `fetchGroupMessageRange`).
*
* NOTE: a body that DID carry content but still decoded to zero elements is a
* missing decoder, not a blank message — this returns false for that case so
* the caller can keep (and warn about) it rather than silently dropping content.
* decoded to zero elements AND its body carried nothing decodable.
*/
export function isBlankMessage(
elements: readonly unknown[],
@@ -49,3 +42,83 @@ export function isBlankMessage(
): boolean {
return elements.length === 0 && !hasDecodableContent(body);
}
/**
* Decoder-after bubble decision for friend / group / temp messages.
* Control drops even when a body decoded to elements. Blank drops only when
* there is nothing to decode. A body that had content but decoded to zero
* elements is keep-undecoded, not blank.
*/
export function classifyMessageSurvival(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
): MessageSurvival {
if (isC2cControlPush(head)) return 'drop-control';
if (elements.length !== 0) return 'keep';
if (hasDecodableContent(body)) return 'keep-undecoded';
return 'drop-blank';
}
/** Summarise a body that decoded to zero elements despite carrying content. */
export function describeUndecodedBody(body: PushMsgBody | undefined): string {
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) extras.push('ptt');
if (body?.richText?.notOnlineFile) extras.push('notOnlineFile');
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
/** Keep when the message should appear as a bubble. Warns on keep-undecoded. */
export function keepDecodedMessage(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd' | 'sequence' | 'subType'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
kind: string,
fromUin: number,
): boolean {
const survival = classifyMessageSurvival(head, elements, body);
if (survival === 'drop-control' || survival === 'drop-blank') return false;
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind,
sequence: head.sequence,
fromUin,
msgType: head.msgType,
subType: head.subType,
body,
});
}
return true;
}
export function warnUndecodedMessage(info: {
kind: string;
sequence: number;
fromUin: number;
msgType: number;
subType: number;
body: PushMsgBody | undefined;
}): void {
log.warn(
'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
info.kind,
info.sequence,
info.fromUin,
info.msgType,
info.subType,
describeUndecodedBody(info.body),
);
}
@@ -10,7 +10,7 @@ import type {
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { isBlankMessage, isC2cControlPush } from './blank-filter';
import { isC2cControlPush, keepDecodedMessage } from './blank-filter';
import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
import { requirePacketResponse } from './packet-response';
@@ -46,7 +46,7 @@ function decodeC2cMessages(
if (isC2cControlPush(ctx.head)) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') continue;
if (isBlankMessage(ev.elements, ctx.body)) continue;
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence `
@@ -4,7 +4,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { isBlankMessage } from './blank-filter';
import { keepDecodedMessage } from './blank-filter';
import { buildContextFromMessage } from './context';
import { decodeGroupMessage } from './decoders/group-message';
import { requirePacketResponse } from './packet-response';
@@ -93,9 +93,7 @@ export async function fetchGroupMessageRange(
+ `(expected=${groupUin} range=${startSeq}-${endSeq})`,
);
}
// Drop content-less control pushes (the "[空消息]" phantom, #102) just as
// QQ NT does on its group roam/history fetch — keep history parity with live.
if (isBlankMessage(ev.elements, ctx.body)) continue;
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
out.push(ev);
}
}
+33 -65
View File
@@ -1,12 +1,9 @@
import { hexPreview } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { Elem } from '@snowluma/proto-defs/element';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { isC2cControlPush } from './blank-filter';
import { hasDecodableContent } from './rich-body-decoder';
import { buildContext, type PushMsgBody } from './context';
import { classifyMessageSurvival, warnUndecodedMessage } from './blank-filter';
import { buildContext } from './context';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
@@ -65,36 +62,11 @@ registry.register([
const log = createLogger('MsgPush');
// Kinds that carry decoded `elements`; an empty list surfaces to clients as the
// confusing "[空消息]".
const MESSAGE_KINDS = new Set<QQEventVariant['kind']>([
'friend_message', 'group_message', 'temp_message',
]);
/**
* Summarise a body that decoded to zero elements despite carrying content —
* each element's field names, every `commonElem`'s serviceType/businessType +
* payload hex, and any `msgContent` — so a missing decoder can be identified
* from one log line rather than swallowed silently.
*/
function describeUndecodedBody(body: PushMsgBody | undefined): string {
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) extras.push('ptt');
if (body?.richText?.notOnlineFile) extras.push('notOnlineFile');
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
function messageElements(ev: QQEventVariant): readonly unknown[] | undefined {
if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') {
return ev.elements;
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
return undefined;
}
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
@@ -188,11 +160,10 @@ function parseMsgPushInternal(
? registry.decodeOrThrow(ctx)
: registry.decode(ctx);
const out = events.filter((ev) => {
if (!MESSAGE_KINDS.has(ev.kind)) return true;
// C2C control/system signal (#102): QQ NT routes these via OnRecvSysMsg and
// never shows them as a bubble. Drop by (msgType, c2cCmd) regardless of body
// — the precise discriminator, the group-invite "[空消息]" phantom being one.
if (isC2cControlPush(ctx.head)) {
const elements = messageElements(ev);
if (elements === undefined) return true;
const survival = classifyMessageSurvival(ctx.head, elements, ctx.body);
if (survival === 'drop-control') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
@@ -202,38 +173,35 @@ function parseMsgPushInternal(
ctx.head.c2cCmd,
ctx.head.sequence,
]);
const elemCount = (ev as { elements?: unknown[] }).elements?.length ?? 0;
if (elemCount > 0) {
if (elements.length > 0) {
log.debug('dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
elemCount, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd);
elements.length, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd);
}
return false;
}
if ((ev as { elements?: unknown[] }).elements?.length !== 0) {
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
if (survival === 'drop-blank') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
}
// Empty-element message that's NOT a known control cmd. Drop it when the body
// is genuinely empty (a content-less push we don't yet classify by c2cCmd).
// If instead the body *had* content we just couldn't decode, keep the
// (still-empty) event but warn so the missing decoder gets noticed rather
// than silently swallowed.
if (hasDecodableContent(ctx.body)) {
log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType,
describeUndecodedBody(ctx.body));
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind: ev.kind,
sequence: ctx.head.sequence,
fromUin: ctx.fromUin,
msgType: ctx.head.msgType,
subType: ctx.head.subType,
body: ctx.body,
});
}
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
});
return out;