fix(onebot): recursively parse nested forward chains (node-inside-node)

A custom forward node's `content` field can itself be a list of
`{type:'node'}` entries — that's the nested-forward case where one
forward bubble contains another. `parseForwardNodes` used to pass
the whole `content` straight into `parseMessage`, which routed
each inner `{type:'node'}` through `message-parser.ts:217 case
'node':` and turned them into opaque
`MessageElement{type:'node', resId: JSON.stringify(content)}`
placeholders. `element-builder.buildSendElems` then dropped those
at its default branch — so the outer forward shipped with either
zero elements (pure-nested → server rejects with "message is
empty") or text-only elements (mixed content → silently truncated
chat bubble). User-facing symptom: "嵌套转发解析后发不出去".

Add depth-aware recursion to `parseForwardNodes`, modelled on
NapCat's `SendMsg.uploadForwardedNodesPacket` (3-level cap):

  - When a node's `content` is *all* `{type:'node'}` entries,
    recurse: parse the inner chain into ForwardNodePayload[],
    upload it via `bridge.uploadForwardNodes` to mint an
    inner res_id, then embed a `{type:'forward', resId}` element
    in the outer node. The receive-side rendering pipeline already
    builds the ARK preview card for that element shape, so the
    QQ client renders a tap-to-expand nested bubble.
  - Mixed content (text + node siblings) deliberately stays on the
    flat path — the meaning is ambiguous, and forcing a recursion
    would silently drop the non-node siblings.
  - Hard cap at depth 3; deeper attempts throw "depth exceeds 3".
    Matches NapCat and prevents one slow inner upload from
    aborting an unreasonably deep tree.

Threading: each forward send entry point passes its destination
into the parser (`{groupId}` from group-send, `{userId}` from
private-send) so the inner forward uploads against the same
res_id namespace.

Test coverage in `tests/onebot/forward-nested.test.ts`:
  - group: inner uploads first, outer wraps inner res_id in a
    forward element, both calls happen in order
  - private: c2c path threads userId (not groupId) into the
    inner uploadForwardNodes
  - depth cap rejects 4-level nesting with /depth/
  - flat (non-nested) content still uploads exactly once
  - mixed content stays on the legacy parseMessage path

core: 626/626 tests pass (+5), typecheck clean, prod build clean.
This commit is contained in:
DrSmoothl
2026-05-19 12:53:24 +08:00
parent 10154cfbff
commit c758eb6569
2 changed files with 303 additions and 4 deletions
@@ -215,7 +215,11 @@ export async function sendGroupForwardMessage(
messages: JsonValue,
meta?: ForwardPreviewMeta,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
// Thread `groupId` into the parser so any nested forward inside a
// node's content uploads its inner forward against the same group
// namespace — otherwise the ARK card's res_id won't be resolvable
// when the recipient taps to expand.
const nodes = await parseForwardNodes(ref, messages, { groupId });
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
const receipt = await ref.bridge.sendGroupMessage(groupId, [previewElement]);
@@ -240,7 +244,7 @@ export async function sendPrivateForwardMessage(
messages: JsonValue,
meta?: ForwardPreviewMeta,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const nodes = await parseForwardNodes(ref, messages, { userId });
// userId is plumbed through so inner image/record/video can be uploaded
// under the recipient's scene (otherwise the OIDB private-image upload
// has no target uid and the element builder bails).
@@ -267,7 +271,7 @@ export async function uploadForwardMessage(
messages: JsonValue,
groupId?: number,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const nodes = await parseForwardNodes(ref, messages, { groupId });
// groupId controls the resId namespace (group vs private). Without it,
// a resId minted here is unusable when later sent into a group.
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
@@ -535,10 +539,49 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
log.info(`${type} ${targetId} | 发送:${content}`);
}
// Cap forward nesting at the same depth NapCat uses
// (`SendMsg.ts:225-228`). QQ NT itself renders only a few levels of
// nested forward bubbles before collapsing into "查看更多" — going
// deeper just wastes long-msg uploads and increases the odds of one
// inner upload timing out and aborting the whole tree.
const MAX_FORWARD_DEPTH = 3;
interface ParseForwardOptions {
/** Destination group, when the parent forward is going to a group. */
groupId?: number;
/** Destination user, when the parent forward is going to a c2c peer. */
userId?: number;
/** Internal: current recursion depth. Callers should leave this 0. */
depth?: number;
}
/**
* Are all entries of this array `{type:'node'}` segments? Then `content`
* itself is a nested forward chain (vs a regular flat segment list).
* Mixed content (some nodes + some text/image) returns false: that's
* not a meaningful protocol shape, so we treat it as flat-segment and
* let the node entries fall through to parseMessage (which drops them
* with a warning).
*/
function isNestedNodeArray(value: JsonValue): boolean {
if (!Array.isArray(value) || value.length === 0) return false;
for (const item of value) {
const seg = asJsonObject(item);
if (!seg || String(seg.type ?? '') !== 'node') return false;
}
return true;
}
async function parseForwardNodes(
ref: OneBotInstanceContext,
messages: JsonValue,
options: ParseForwardOptions = {},
): Promise<ForwardNodePayload[]> {
const depth = options.depth ?? 0;
if (depth >= MAX_FORWARD_DEPTH) {
throw new Error(`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`);
}
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}
@@ -590,7 +633,33 @@ async function parseForwardNodes(
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
let elements: MessageElement[];
if (isNestedNodeArray(content)) {
// Nested forward chain — `content` is itself a list of `{type:'node'}`
// segments. Recursively parse them into ForwardNodePayloads, upload
// that inner chain as its own forward, then embed an ARK preview
// card pointing at the inner res_id. The receiving QQ client renders
// it as a tap-to-expand nested forward bubble. Matches NapCat's
// `SendMsg.uploadForwardedNodesPacket` recursion contract.
//
// Without this, the inner `{type:'node'}` entries fell through to
// `parseMessage` which produced useless `MessageElement{type:'node'}`
// entries that `element-builder` silently drops — leaving the outer
// forward with an empty body that QQ refuses with "message is empty"
// (single-node case) or a node whose content is missing the inner
// forward (mixed case).
const innerNodes = await parseForwardNodes(ref, content, {
groupId: options.groupId,
userId: options.userId,
depth: depth + 1,
});
const innerResId = await ref.bridge.uploadForwardNodes(innerNodes, options.groupId, options.userId);
const isGroup = options.groupId !== undefined;
elements = [buildForwardPreviewElement(innerResId, innerNodes, isGroup, undefined)];
} else {
elements = await parseMessage(content, false);
}
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
nodes.push({ userUin, nickname, elements });
@@ -0,0 +1,230 @@
// Regression coverage for nested forward (forward-inside-forward).
//
// Bug being pinned: when a custom forward node's `content` is itself
// a list of `{type:'node'}` entries (a forward chain inside a forward
// chain), the parser used to call `parseMessage(content, false)`
// which routes each inner node through `message-parser.ts:217 case
// 'node':`. That case JSON-stringifies `content` into the
// `resId` field of a `MessageElement{type:'node'}` placeholder —
// which `element-builder.buildSendElems` then silently drops at its
// default case. End result: the outer forward goes out with an empty
// (or text-only) body, the nested chain is lost.
//
// Fix:`parseForwardNodes` now detects an all-node content array,
// recursively builds the inner ForwardNodePayload[], uploads it as a
// separate forward to obtain a `res_id`, then embeds an ARK preview
// element (`{type:'forward', resId}`) in the outer node — which is
// exactly the shape `element-builder.makeForwardElem` already knows
// how to render. Matches NapCat's `uploadForwardedNodesPacket`
// recursion (capped at 3 levels deep).
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
import {
sendGroupForwardMessage,
sendPrivateForwardMessage,
} from '../../src/onebot/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('forward — nested {type:"node"} content', () => {
it('group: nested forward uploads inner chain first, outer embeds ARK preview pointing at it', async () => {
const uploadForwardNodes = vi.fn(async (nodes: any[]) => {
// Inner gets uploaded before outer; track the order by inspecting
// the elements shape. The inner chain's payload is a plain text
// node; the outer chain's only element is a `forward` ARK preview
// referencing the inner res_id we returned just before.
const innerNode = nodes[0];
const onlyElem = innerNode.elements[0];
if (onlyElem.type === 'text' && onlyElem.text === 'hello from inner') {
return 'INNER_RESID';
}
if (onlyElem.type === 'forward' && onlyElem.resId === 'INNER_RESID') {
return 'OUTER_RESID';
}
throw new Error(`unexpected upload payload: ${JSON.stringify(nodes)}`);
});
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hello from inner' } }],
},
}],
},
}];
const result = await sendGroupForwardMessage(ctx, 12345, messages as any);
// Two uploads: inner first, then outer.
expect(uploadForwardNodes).toHaveBeenCalledTimes(2);
// Inner upload: nodes[0] is the leaf node, scoped to the outer group.
const [innerNodes, innerGroupId] = uploadForwardNodes.mock.calls[0]!;
expect(innerGroupId).toBe(12345);
expect((innerNodes as any[])[0]!.userUin).toBe(222);
expect((innerNodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'hello from inner' }]);
// Outer upload: the wrapper node carries a single `forward` ARK
// preview element that points at the inner res_id we minted above.
const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[1]!;
expect(outerGroupId).toBe(12345);
expect((outerNodes as any[])[0]!.userUin).toBe(111);
expect((outerNodes as any[])[0]!.elements).toHaveLength(1);
expect((outerNodes as any[])[0]!.elements[0]).toMatchObject({
type: 'forward',
resId: 'INNER_RESID',
});
expect(result.forwardId).toBe('OUTER_RESID');
expect(sendGroupMessage).toHaveBeenCalledOnce();
});
it('private: nested forward threads userId into inner uploadForwardNodes', async () => {
// Same shape but routed via sendPrivateForwardMessage. The c2c path
// passes `userId` instead of `groupId` so any inner image/record
// uploads can pick up the recipient's UID scene (otherwise the
// OIDB private-media upload has no target uid).
const uploadForwardNodes = vi.fn(async () => 'RESID');
const sendPrivateMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendPrivateMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hi' } }],
},
}],
},
}];
await sendPrivateForwardMessage(ctx, 67890, messages as any);
// Inner upload: groupId undefined, userId is the c2c recipient.
const innerCall = uploadForwardNodes.mock.calls[0]!;
expect(innerCall[1]).toBeUndefined();
expect(innerCall[2]).toBe(67890);
});
it('rejects nesting deeper than 3 levels', async () => {
// Build a 4-level nested chain. NapCat caps at 3 too, going further
// wastes long-msg uploads and risks one inner upload timing out
// and aborting the whole tree. Better to fail loud here.
const uploadForwardNodes = vi.fn(async () => 'X');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
function wrap(content: any, depth: number): any {
if (depth === 0) return [{ type: 'text', data: { text: 'leaf' } }];
return [{
type: 'node',
data: { user_id: 100 + depth, nickname: `lvl-${depth}`, content: wrap(content, depth - 1) },
}];
}
await expect(
sendGroupForwardMessage(ctx, 12345, wrap(null, 4) as any),
).rejects.toThrow(/depth/);
});
it('flat content (no nesting) still goes through the unchanged path', async () => {
// Backwards-compat: a single-level forward with plain text nodes
// calls uploadForwardNodes exactly once and never touches the
// recursive branch.
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [
{ type: 'node', data: { user_id: 111, nickname: 'a', content: [{ type: 'text', data: { text: 'one' } }] } },
{ type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'two' } }] } },
];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])).toHaveLength(2);
expect((nodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'one' }]);
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
});
it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => {
// Recursion only kicks in when *all* content entries are nodes —
// mixed content is ambiguous (do the non-node parts belong to the
// outer node or are they parallel siblings?), so we keep the legacy
// behaviour and let parseMessage handle it. Non-node parts come
// through, node parts get parsed via `case 'node':` and then
// dropped by element-builder. A user who wants nested forward
// should pass a pure node list.
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'mixed',
content: [
{ type: 'text', data: { text: 'a sibling' } },
{ type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'lost' } }] } },
],
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
// Only the text element survives — the legacy "node MessageElement"
// that parseMessage produces is opaque to the element-builder.
const [nodes] = uploadForwardNodes.mock.calls[0]!;
const elements = (nodes as any[])[0]!.elements;
expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true);
});
});