fix(forward): align resid+uniseq for nested forwards
Multi-layer 合并转发 was uploading correctly but the outer's
LongMsgResult piggyback was *unreachable* by the receiver because
two things were missing:
1. The forward preview element was emitted as the old XML
`richMsg serviceID=35 m_resid=…` shape, which carries the
inner resId but has NO uniseq field.
2. The piggyback `actionCommand: <uuid>` slot generated a fresh
UUID that was never reflected into the preview either.
Result: QQ-NT receivers saw the inner preview's resid, scanned the
outer's actions[] for a matching uniseq, found none, and either
fell back to a fresh server fetch per layer or dropped the layer
entirely.
Cross-checked against:
- dev/Lagrange.Core/Lagrange.Core/Message/Entity/MultiMsgEntity.cs:43-115
- dev/NapCatQQ/packages/napcat-core/helper/forward-msg-builder.ts:52-122
- dev/NapCatQQ/packages/napcat-onebot/action/msg/SendMsg.ts:208-347
Both upstream impls use the modern `com.tencent.multimsg` LightApp
JSON whose `meta.detail.uniseq` is the round-trip key that links
the inner preview to the matching `actionCommand` in the outer's
LongMsgResult — no separate fetch needed.
Changes:
- `element-builder.makeForwardElem` now emits a deflated
`com.tencent.multimsg` LightApp JSON (LightAppElem, field 51)
instead of the XML RichMsg (field 12). `forwardUuid` on the
MessageElement is baked into `meta.detail.uniseq` and
`extra.filename`. Auto-generates a UUID when absent.
- `MessageElement.forwardUuid?: string` added for the round-trip.
- `forward.uploadRecursive` threads `inner.uuid` into the outer's
preview element AND uses the same uuid for the outer's
piggyback actionCommand — closing the receiver-side lookup loop.
- `forward.fetch` now walks ALL actions (not just `MultiMsg`),
indexes piggybacks by uuid, and pre-populates the cache for
each inner resId discovered in the outer's preview bubbles.
Follow-up `fetch(innerResId)` hits the cache instead of the wire.
- `rich-body-decoder` parses LightApp JSON; when `app ===
com.tencent.multimsg`, emits `{type: 'forward', resId,
forwardUuid}` so the OneBot layer can walk in. Legacy XML
serviceID=35 path stays as a fallback for mobile QQ senders.
Wire-byte tests cover:
- send: lightApp.data is 0x01-prefixed deflated JSON with the
right meta + extra fields
- send/nested: outer LongMsgResult carries `MultiMsg` AND a
uuid-keyed piggyback; the piggyback uuid matches the
preview's `meta.detail.uniseq` baked into the same outer
msgBody
- send/3-deep: outermost action[] has 1 + 2 entries (own
MultiMsg + 2 piggybacks hoisted from deeper levels)
- recv: lightApp `com.tencent.multimsg` → forward element with
both resId and forwardUuid; non-multimsg LightApp falls
through to {type:'json'}; legacy XML path still emits
{type:'forward'}.
641 tests pass (was 628 + 13 new); typecheck clean; lint clean.
This commit is contained in:
7 files changed
+583
-65
No files matched your search
@@ -1,4 +1,6 @@
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { deflateSync } from 'zlib';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
import type { MessageElement } from './events';
|
||||
import { uploadImageMsgInfo } from './highway/image-upload';
|
||||
@@ -145,14 +147,6 @@ function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
};
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
const resId = (element.resId ?? '').trim();
|
||||
@@ -160,10 +154,12 @@ function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
throw new Error('forward resId is required');
|
||||
}
|
||||
|
||||
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
|
||||
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
|
||||
// entries become per-line previews ("nick: text"), `summary` is the
|
||||
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
|
||||
// `uniseq` MUST round-trip between the preview JSON and the outer
|
||||
// upload's piggyback `actionCommand` for nested forwards to resolve
|
||||
// without an extra server hit. Generate one fresh if absent (flat
|
||||
// forwards don't piggyback anyway, so the value is cosmetic there).
|
||||
const uniseq = (element.forwardUuid ?? '').trim() || randomUUID();
|
||||
|
||||
const source = element.forwardSource && element.forwardSource.length > 0
|
||||
? element.forwardSource
|
||||
: '聊天记录';
|
||||
@@ -178,35 +174,48 @@ function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
? element.forwardTSum
|
||||
: Math.max(news.length, 1);
|
||||
|
||||
const newsTitles = news
|
||||
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
|
||||
.join('');
|
||||
// LightApp / `com.tencent.multimsg` is the modern wire shape both
|
||||
// QQ-NT, Lagrange.Core, and NapCat emit and decode. The older
|
||||
// `richMsg serviceID=35 m_resid=…` XML still renders on mobile QQ
|
||||
// but it doesn't carry `uniseq`, so nested forwards lose the link
|
||||
// between the inner preview and the piggybacked actions on the
|
||||
// outer's LongMsgResult — cross-checked against
|
||||
// `dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115`
|
||||
// and `dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122`.
|
||||
const lightApp = {
|
||||
app: 'com.tencent.multimsg',
|
||||
config: {
|
||||
autosize: 1,
|
||||
forward: 1,
|
||||
round: 1,
|
||||
type: 'normal',
|
||||
width: 300,
|
||||
},
|
||||
desc: prompt,
|
||||
extra: JSON.stringify({ filename: uniseq, tsum: tSum }),
|
||||
meta: {
|
||||
detail: {
|
||||
news: news.map(n => ({ text: n.text ?? '' })),
|
||||
resid: resId,
|
||||
source,
|
||||
summary,
|
||||
uniseq,
|
||||
},
|
||||
},
|
||||
prompt,
|
||||
ver: '0.0.0.5',
|
||||
view: 'contact',
|
||||
};
|
||||
|
||||
const resIdAttr = escapeXml(resId);
|
||||
const xml =
|
||||
`<?xml version="1.0" encoding="utf-8"?>` +
|
||||
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
|
||||
` brief="${escapeXml(prompt)}"` +
|
||||
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
|
||||
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
|
||||
`<item layout="1">` +
|
||||
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
|
||||
newsTitles +
|
||||
`<hr hidden="false" style="0"/>` +
|
||||
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
|
||||
`</item>` +
|
||||
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
|
||||
`</msg>`;
|
||||
|
||||
const encodedXml = new TextEncoder().encode(xml);
|
||||
const payload = new Uint8Array(encodedXml.length + 1);
|
||||
payload[0] = 0x00;
|
||||
payload.set(encodedXml, 1);
|
||||
const json = JSON.stringify(lightApp);
|
||||
const deflated = deflateSync(Buffer.from(json, 'utf8'));
|
||||
const payload = new Uint8Array(deflated.length + 1);
|
||||
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
|
||||
payload.set(deflated, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 35,
|
||||
template1: payload,
|
||||
lightApp: {
|
||||
data: payload,
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ export interface MessageElement {
|
||||
flash?: boolean;
|
||||
resId?: string;
|
||||
fileHash?: string;
|
||||
// Preview-bubble metadata for the `forward` element. Drives the XML
|
||||
// template (brief/title/news/summary/tSum) the recipient renders before
|
||||
// Preview-bubble metadata for the `forward` element. Drives the
|
||||
// `com.tencent.multimsg` LightApp JSON the recipient renders before
|
||||
// they tap to expand. When unset, the element builder falls back to
|
||||
// generic defaults so old call sites keep working.
|
||||
forwardSource?: string;
|
||||
@@ -33,6 +33,14 @@ export interface MessageElement {
|
||||
forwardPrompt?: string;
|
||||
forwardNews?: Array<{ text: string }>;
|
||||
forwardTSum?: number;
|
||||
/** `uniseq` baked into the preview's LightApp JSON. For a nested
|
||||
* forward, the *outer* upload uses this same uuid as the
|
||||
* `actionCommand` for the piggyback entry carrying the inner
|
||||
* layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can
|
||||
* resolve the inner layer from the outer's single fetch instead of
|
||||
* hitting the server again. Defaults to a fresh UUID on send when
|
||||
* omitted (i.e. for non-nested forwards). */
|
||||
forwardUuid?: string;
|
||||
// Server-side fingerprints carried from receive side so a forward can do a
|
||||
// pure md5/sha1 fast-upload without re-downloading the original bytes.
|
||||
// Set together with `noByteFallback: true` to make the upload modules throw
|
||||
|
||||
@@ -213,7 +213,33 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const la = elem.lightApp;
|
||||
if (la.data && la.data.length > 0) {
|
||||
const content = decompressData(la.data);
|
||||
if (content) result.push({ type: 'json', text: content });
|
||||
if (content) {
|
||||
// `com.tencent.multimsg` is the multi-msg / forward preview
|
||||
// LightApp (the modern replacement for the XML serviceID=35
|
||||
// shape). Parse out resid + uniseq so downstream callers can
|
||||
// both render a `[聊天记录]` placeholder and walk into the
|
||||
// forward chain via `fetch(resId)` — the uniseq is what links
|
||||
// the inner layer to its piggybacked actions on the outer's
|
||||
// LongMsgResult. Other LightApp messages fall through to the
|
||||
// generic `{type: 'json'}` path.
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
if (parsed && parsed.app === 'com.tencent.multimsg') {
|
||||
const detail = parsed.meta?.detail ?? {};
|
||||
const resId = typeof detail.resid === 'string' ? detail.resid : '';
|
||||
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
|
||||
if (resId) {
|
||||
result.push({
|
||||
type: 'forward',
|
||||
resId,
|
||||
forwardUuid: uniseq || undefined,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch { /* fall through to generic json element */ }
|
||||
result.push({ type: 'json', text: content });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Receive-side decode for `com.tencent.multimsg` LightApp — verifies
|
||||
// the inverse of element-builder.makeForwardElem so a forward sent by
|
||||
// SnowLuma (or any QQ-NT / Lagrange / NapCat client) round-trips
|
||||
// back to `{type: 'forward', resId, forwardUuid}` on the receiver.
|
||||
//
|
||||
// Without this the receiver-side decoder sees `lightApp` and falls
|
||||
// back to a generic `{type: 'json', text: <json>}` element, which
|
||||
// means the OneBot layer can't surface a forward bubble OR walk into
|
||||
// the nested forward via fetch(resId).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { deflateSync } from 'zlib';
|
||||
import { decodeRichBody } from '../../src/msg-push/rich-body-decoder';
|
||||
import type { MessageBody } from '@snowluma/proto-defs/message';
|
||||
|
||||
function lightAppBytes(json: unknown): Uint8Array {
|
||||
const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8'));
|
||||
const out = new Uint8Array(buf.length + 1);
|
||||
out[0] = 0x01; // deflate prefix
|
||||
out.set(buf, 1);
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('decodeRichBody / forward LightApp', () => {
|
||||
it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => {
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
lightApp: {
|
||||
data: lightAppBytes({
|
||||
app: 'com.tencent.multimsg',
|
||||
meta: { detail: { resid: 'inner-res-1', uniseq: 'uuid-1' } },
|
||||
}),
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = decodeRichBody(body, true);
|
||||
expect(out).toEqual([{ type: 'forward', resId: 'inner-res-1', forwardUuid: 'uuid-1' }]);
|
||||
});
|
||||
|
||||
it('omits forwardUuid when the sender did not set uniseq (XML-era forwards)', () => {
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
lightApp: {
|
||||
data: lightAppBytes({
|
||||
app: 'com.tencent.multimsg',
|
||||
meta: { detail: { resid: 'only-resid' } },
|
||||
}),
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = decodeRichBody(body, true);
|
||||
expect(out).toEqual([{ type: 'forward', resId: 'only-resid' }]);
|
||||
});
|
||||
|
||||
it('falls back to {type:"json"} for non-multimsg LightApp (e.g. mini-app card)', () => {
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
lightApp: {
|
||||
data: lightAppBytes({ app: 'com.tencent.miniapp_01', meta: {} }),
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = decodeRichBody(body, true);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]!.type).toBe('json');
|
||||
expect(typeof (out[0] as any).text).toBe('string');
|
||||
});
|
||||
|
||||
it('falls back to {type:"json"} when com.tencent.multimsg is missing resid (malformed)', () => {
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
lightApp: {
|
||||
data: lightAppBytes({
|
||||
app: 'com.tencent.multimsg',
|
||||
meta: { detail: {} },
|
||||
}),
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = decodeRichBody(body, true);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]!.type).toBe('json');
|
||||
});
|
||||
|
||||
it('still decodes the legacy richMsg serviceID=35 path (backward compat with mobile QQ)', () => {
|
||||
// Older clients (and some bridges) still emit the m_resid XML
|
||||
// shape. The decoder must keep treating it as a forward element
|
||||
// so SnowLuma can fetch the resid downstream.
|
||||
const xml = '<?xml version="1.0"?><msg m_resid="legacy-res" />';
|
||||
const xmlBuf = new Uint8Array(xml.length + 1);
|
||||
xmlBuf[0] = 0x00;
|
||||
xmlBuf.set(new TextEncoder().encode(xml), 1);
|
||||
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
richMsg: { serviceId: 35, template1: xmlBuf },
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = decodeRichBody(body, true);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]).toMatchObject({ type: 'forward', resId: 'legacy-res' });
|
||||
});
|
||||
});
|
||||
@@ -265,6 +265,14 @@ export class ForwardApi {
|
||||
// res_id / uuid before encoding the outer ARK previews). Build
|
||||
// `processedNodes` with elements rewritten for nested layers,
|
||||
// and collect every inner level's piggyback in `myInnerActions`.
|
||||
//
|
||||
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
|
||||
// outer's preview element as `forwardUuid` AND used as the
|
||||
// `actionCommand` for the outer's piggyback entry. That's the
|
||||
// alignment the QQ-NT receiver uses to find the inner layer
|
||||
// inside the outer's LongMsgResult without a second server fetch
|
||||
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
||||
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
||||
const myInnerActions: ForwardInnerAction[] = [];
|
||||
const processedNodes: ForwardNodePayload[] = [];
|
||||
const isGroup = groupId !== undefined;
|
||||
@@ -278,13 +286,13 @@ export class ForwardApi {
|
||||
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
||||
myInnerActions.push(...inner.innerActions);
|
||||
// Replace the inner placeholder element with a forward preview
|
||||
// pointing at the inner res_id. The wire-side element builder
|
||||
// turns this into the same XML m_resid blob it already produced
|
||||
// for top-level forwards — see `makeForwardElem` in
|
||||
// element-builder.ts:153.
|
||||
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
||||
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
||||
// closes the loop with our piggyback action above.
|
||||
const previewElement: MessageElement = {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: '[聊天记录]',
|
||||
@@ -367,6 +375,14 @@ export class ForwardApi {
|
||||
return {
|
||||
resId,
|
||||
msgBody,
|
||||
// UUID generated here so the OUTER caller can use it as both
|
||||
// (1) the `actionCommand` for its piggyback entry carrying our
|
||||
// msgBody, and
|
||||
// (2) the `forwardUuid` baked into its forward-preview element
|
||||
// pointing at our resId.
|
||||
// Receivers walking the outer's LongMsgResult find the inner
|
||||
// layer by matching `uniseq` from (2) against `actionCommand`
|
||||
// from (1) — no separate fetch needed.
|
||||
uuid: randomUUID(),
|
||||
innerActions: myInnerActions,
|
||||
};
|
||||
@@ -417,10 +433,46 @@ export class ForwardApi {
|
||||
|
||||
const inflate = gunzipSync(Buffer.from(payload));
|
||||
const longMsg = protobuf_decode<LongMsgResult>(inflate);
|
||||
const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
// Piggyback index: any non-`MultiMsg` action carries an inner
|
||||
// layer keyed by the uuid the sender baked into its forward
|
||||
// preview's `uniseq`. Build a lookup so we can resolve inner
|
||||
// forwards (via their uniseq → inner msgBody) without a second
|
||||
// server roundtrip — matches the sender-side piggyback emitted in
|
||||
// `uploadRecursive` above.
|
||||
const piggybackByUuid = new Map<string, PushMsgBody[]>();
|
||||
for (const action of actions) {
|
||||
const cmd = action?.actionCommand;
|
||||
if (!cmd || cmd === 'MultiMsg') continue;
|
||||
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
piggybackByUuid.set(cmd, body);
|
||||
}
|
||||
|
||||
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
|
||||
|
||||
// Walk the decoded outer nodes for inner-forward previews
|
||||
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
|
||||
// matching piggyback body, decode it into inner nodes, and seed
|
||||
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
||||
// hits the cache instead of the wire.
|
||||
if (piggybackByUuid.size > 0) {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** Walk a list of PushMsgBody, run each through the regular msg-push
|
||||
* pipeline, and shape the result into ForwardNodePayloads. Extracted
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
|
||||
const out: ForwardNodePayload[] = [];
|
||||
for (const msgBody of msgBodyList) {
|
||||
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
|
||||
const pkt: PacketInfo = {
|
||||
@@ -438,7 +490,7 @@ export class ForwardApi {
|
||||
if (!event) continue;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
nodes.push({
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
elements: event.elements,
|
||||
@@ -450,7 +502,7 @@ export class ForwardApi {
|
||||
messageType: 'group',
|
||||
});
|
||||
} else if (event.kind === 'friend_message') {
|
||||
nodes.push({
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
@@ -460,7 +512,7 @@ export class ForwardApi {
|
||||
messageType: 'private',
|
||||
});
|
||||
} else {
|
||||
nodes.push({
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
@@ -471,20 +523,51 @@ export class ForwardApi {
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
})));
|
||||
}
|
||||
return nodes;
|
||||
/** Recursively resolve forward previews against the piggyback table.
|
||||
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
||||
* look up the uniseq in the piggyback map; if hit, decode the
|
||||
* inner msgBody and cache it by inner resId, then descend into that
|
||||
* inner layer to resolve deeper nestings carried in the SAME
|
||||
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
||||
* the outermost action list). */
|
||||
private consumePiggybacks(
|
||||
nodes: ForwardNodePayload[],
|
||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||
): void {
|
||||
const seen = new Set<string>();
|
||||
const visit = (chain: ForwardNodePayload[]): void => {
|
||||
for (const node of chain) {
|
||||
for (const elem of node.elements) {
|
||||
if (elem.type !== 'forward') continue;
|
||||
const uuid = elem.forwardUuid;
|
||||
const innerResId = elem.resId;
|
||||
if (!uuid || !innerResId || seen.has(uuid)) continue;
|
||||
const body = piggybackByUuid.get(uuid);
|
||||
if (!body) continue;
|
||||
seen.add(uuid);
|
||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
||||
visit(innerNodes);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(nodes);
|
||||
}
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Wire-byte alignment regression for nested forward upload — verifies
|
||||
// that the OUTER LongMsgResult's `actions[]` carries:
|
||||
// - `{actionCommand: 'MultiMsg', actionData.msgBody: <outer nodes>}`
|
||||
// - `{actionCommand: <inner.uuid>, actionData.msgBody: <inner nodes>}`
|
||||
// AND that the same uuid appears as `meta.detail.uniseq` inside the
|
||||
// LightApp `com.tencent.multimsg` JSON of the outer's preview element
|
||||
// pointing at the inner res_id.
|
||||
//
|
||||
// Without this alignment the QQ-NT recipient has no way to walk the
|
||||
// piggyback — they see the inner preview's resid, look for a matching
|
||||
// uniseq among the actions, find none, and either fall back to a fresh
|
||||
// server fetch (extra latency) or render an empty bubble.
|
||||
//
|
||||
// Reference impls cross-checked:
|
||||
// dev/NapCatQQ/.../SendMsg.ts:208-347
|
||||
// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115
|
||||
// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { gunzipSync, inflateSync } from 'zlib';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
|
||||
// Don't mock element-builder — we WANT the real forward preview
|
||||
// element to land in the encoded wire bytes so we can verify the
|
||||
// `uniseq` round-trip against the piggyback's `actionCommand`.
|
||||
|
||||
// Mock highway uploads only — they're irrelevant for text-only nodes
|
||||
// but the import would otherwise pull in the native ffmpeg addon.
|
||||
vi.mock('@snowluma/bridge/highway/image-upload', () => ({
|
||||
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
vi.mock('@snowluma/bridge/highway/ptt-upload', () => ({
|
||||
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
vi.mock('@snowluma/bridge/highway/video-upload', () => ({
|
||||
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function uploadResponseWithResId(resId: string) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({ result: { resId } })),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
|
||||
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
|
||||
const payload = env.info?.payload;
|
||||
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on the SendLongMsgReq');
|
||||
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
|
||||
}
|
||||
|
||||
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
|
||||
for (const body of msgBody) {
|
||||
const elems: Elem[] = body.body?.richText?.elems ?? [];
|
||||
for (const elem of elems) {
|
||||
if (elem.lightApp?.data && elem.lightApp.data.length > 1) {
|
||||
const data = elem.lightApp.data;
|
||||
if (data[0] !== 0x01) continue;
|
||||
try {
|
||||
const json = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
const parsed = JSON.parse(json);
|
||||
if (parsed?.app === 'com.tencent.multimsg') {
|
||||
return {
|
||||
app: parsed.app,
|
||||
resid: parsed.meta?.detail?.resid,
|
||||
uniseq: parsed.meta?.detail?.uniseq,
|
||||
};
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('forward / nested upload wire alignment', () => {
|
||||
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
|
||||
// Inner upload returns inner-res; outer upload returns outer-res.
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
const resId = await new ForwardApi(bridge as any).upload([
|
||||
{
|
||||
userUin: 111, nickname: 'outer', elements: [],
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(resId).toBe('outer-res');
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Second call is the OUTER's upload (the inner went first).
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerLongMsg = decodeOuterLongMsg(outerBytes);
|
||||
|
||||
const actions = outerLongMsg.action ?? [];
|
||||
expect(actions).toHaveLength(2);
|
||||
expect(actions[0]!.actionCommand).toBe('MultiMsg');
|
||||
// The second action carries the inner's msgBody under a uuid
|
||||
// actionCommand (NOT 'MultiMsg').
|
||||
const piggybackUuid = actions[1]!.actionCommand!;
|
||||
expect(piggybackUuid).not.toBe('MultiMsg');
|
||||
expect(piggybackUuid).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(actions[1]!.actionData?.msgBody?.length ?? 0).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('outer preview LightApp uniseq matches the piggyback actionCommand uuid', async () => {
|
||||
// This is the alignment bug: without it the QQ-NT receiver
|
||||
// can't link the inner preview to its piggyback in actions[].
|
||||
const responses = ['inner-res-A', 'outer-res-A'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([
|
||||
{
|
||||
userUin: 111, nickname: 'outer', elements: [],
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerLongMsg = decodeOuterLongMsg(outerBytes);
|
||||
|
||||
const piggybackUuid = outerLongMsg.action![1]!.actionCommand!;
|
||||
const outerMsgBody = outerLongMsg.action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
expect(preview!.app).toBe('com.tencent.multimsg');
|
||||
expect(preview!.resid).toBe('inner-res-A');
|
||||
expect(preview!.uniseq).toBe(piggybackUuid);
|
||||
});
|
||||
|
||||
it('three-deep nesting: outermost action[] carries 1+2 entries (MultiMsg + 2 piggybacks)', async () => {
|
||||
// The middle level's upload produces 1 MultiMsg + 1 piggyback
|
||||
// (for the deepest). The outermost level then concatenates its
|
||||
// own MultiMsg + the middle's piggyback set, so action[].length = 3.
|
||||
const responses = ['deepest', 'middle', 'outermost'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([
|
||||
{
|
||||
userUin: 1, nickname: 'L1', elements: [],
|
||||
innerForward: [{
|
||||
userUin: 2, nickname: 'L2', elements: [],
|
||||
innerForward: [
|
||||
{ userUin: 3, nickname: 'L3', elements: [{ type: 'text', text: 'deep' }] },
|
||||
],
|
||||
}],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
const outermostBytes = sendRawPacket.mock.calls[2]![1] as Uint8Array;
|
||||
const outermost = decodeOuterLongMsg(outermostBytes);
|
||||
expect(outermost.action).toHaveLength(3);
|
||||
expect(outermost.action![0]!.actionCommand).toBe('MultiMsg');
|
||||
expect(outermost.action![1]!.actionCommand).not.toBe('MultiMsg');
|
||||
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
|
||||
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@
|
||||
// recognise and got rejected with result=79.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { inflateSync } from 'zlib';
|
||||
|
||||
vi.mock('@snowluma/bridge/highway/image-upload', () => ({
|
||||
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
|
||||
@@ -118,3 +119,90 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () => {
|
||||
// The forward preview is the bubble the recipient renders in chat
|
||||
// before tapping to expand. It MUST be the modern LightApp /
|
||||
// `com.tencent.multimsg` JSON (not the older `richMsg serviceID=35`
|
||||
// XML) because nested forwards rely on `meta.detail.uniseq` to link
|
||||
// each inner preview to the matching `actionCommand` piggyback on
|
||||
// the outer's LongMsgResult — without uniseq the QQ-NT client has
|
||||
// no way to walk the tree and has to re-fetch each inner resId.
|
||||
function decodeLightApp(elem: any): unknown {
|
||||
const data: Uint8Array = elem.lightApp.data;
|
||||
expect(data[0]).toBe(0x01); // deflate prefix
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
return JSON.parse(inflated);
|
||||
}
|
||||
|
||||
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'forward', resId: 'res-XYZ' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
expect(elem.lightApp).toBeDefined();
|
||||
expect((elem as any).richMsg).toBeUndefined();
|
||||
expect(elem.lightApp!.data![0]).toBe(0x01);
|
||||
});
|
||||
|
||||
it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'forward', resId: 'res-XYZ', forwardUuid: 'fixed-uuid-1234' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
const json = decodeLightApp(elem) as any;
|
||||
expect(json.app).toBe('com.tencent.multimsg');
|
||||
expect(json.meta.detail.resid).toBe('res-XYZ');
|
||||
expect(json.meta.detail.uniseq).toBe('fixed-uuid-1234');
|
||||
// `extra` is a JSON string holding {filename, tsum}; filename must
|
||||
// round-trip the same uniseq so the QQ-NT client links them.
|
||||
const extra = JSON.parse(json.extra);
|
||||
expect(extra.filename).toBe('fixed-uuid-1234');
|
||||
});
|
||||
|
||||
it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'forward', resId: 'res-flat' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
const json = decodeLightApp(elem) as any;
|
||||
expect(json.meta.detail.resid).toBe('res-flat');
|
||||
// Auto-generated UUID — non-empty, non-trivial.
|
||||
expect(json.meta.detail.uniseq).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
const extra = JSON.parse(json.extra);
|
||||
expect(extra.filename).toBe(json.meta.detail.uniseq);
|
||||
});
|
||||
|
||||
it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{
|
||||
type: 'forward', resId: 'r1', forwardUuid: 'u1',
|
||||
forwardSource: 'alice和bob的聊天记录',
|
||||
forwardSummary: '查看3条转发消息',
|
||||
forwardPrompt: '[聊天记录]',
|
||||
forwardNews: [{ text: 'alice: hi' }, { text: 'bob: hey' }],
|
||||
forwardTSum: 3,
|
||||
} as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
const json = decodeLightApp(elem) as any;
|
||||
expect(json.meta.detail.source).toBe('alice和bob的聊天记录');
|
||||
expect(json.meta.detail.summary).toBe('查看3条转发消息');
|
||||
expect(json.meta.detail.news).toEqual([{ text: 'alice: hi' }, { text: 'bob: hey' }]);
|
||||
expect(json.desc).toBe('[聊天记录]');
|
||||
expect(json.prompt).toBe('[聊天记录]');
|
||||
expect(JSON.parse(json.extra).tsum).toBe(3);
|
||||
});
|
||||
|
||||
it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => {
|
||||
// The dispatcher's `case 'forward': if (elem.resId) ...` short-
|
||||
// circuits when resId is empty so a malformed segment from the
|
||||
// OneBot client doesn't blow up the whole send. Receiver sees
|
||||
// no forward bubble — same outcome as omitting the segment.
|
||||
const out = await buildSendElems(
|
||||
[{ type: 'forward' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user