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:
DrSmoothl committed 2026-05-23 12:45:26 +08:00
1 parent 5724f490b4
commit cd9403f27a
7 files changed
+583 -65

No files matched your search

+47 -38
View File
@@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
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,
};
}
+10 -2
View File
@@ -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 });
}
}
}