diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 8a85336a..07c1db36 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -5,10 +5,11 @@ import type { Bridge } from '../bridge'; import { gunzipSync, gzipSync } from 'zlib'; +import { randomUUID } from 'crypto'; import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; import { buildSendElems } from '../element-builder'; import { parseMsgPush } from '../msg-push'; -import type { ForwardNodePayload } from '../events'; +import type { ForwardNodePayload, MessageElement } from '../events'; import type { PacketInfo } from '../../protocol/types'; import type { LongMsgResult, @@ -73,12 +74,60 @@ async function buildForwardPushBody( }; } +// Per-layer piggyback entry. Each level of a nested forward attaches +// its own msgBody under a uuid `actionCommand`, so when the receiver +// fetches the outermost res_id it gets every layer in one shot +// (modelled on NapCat's `uploadForwardedNodesPacket` — see +// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2 +// both ship a single-action model and silently break when the +// recipient is a NapCat instance trying to walk the tree. +interface ForwardInnerAction { + uuid: string; + msgBody: PushMsgBody[]; +} + +interface ForwardUploadResult { + resId: string; + // The current level's msgBody + uuid — what an outer caller would + // piggyback to expose this layer through the tree. + msgBody: PushMsgBody[]; + uuid: string; + // All accumulated piggyback entries from deeper levels. Outer + // callers concatenate these to their own actions list so the + // outermost upload carries the full tree. + innerActions: ForwardInnerAction[]; +} + export async function uploadForwardNodes( bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number, userId?: number, ): Promise { + const { resId } = await uploadForwardNodesRecursive(bridge, nodes, groupId, userId); + return resId; +} + +/** + * Recursive upload with NapCat-style piggyback. Each invocation: + * 1. Walks `nodes`. For any node whose `innerForward` is set, + * recursively uploads that inner chain first (which itself runs + * this same recursion). + * 2. Replaces the node's `elements` with an ARK preview pointing at + * the inner res_id (and inner uuid for receiver-side walking). + * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of + * ITS accumulated `innerActions` into this level's piggyback list. + * 4. Encodes this level's long-msg payload as + * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, + * returns `{resId, msgBody, uuid, innerActions}` so an outer + * caller can keep piggybacking up the tree. + */ +async function uploadForwardNodesRecursive( + bridge: Bridge, + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, +): Promise { if (!Array.isArray(nodes) || nodes.length === 0) { throw new Error('forward nodes are required'); } @@ -86,25 +135,77 @@ export async function uploadForwardNodes( // For a private forward to `userId`, any image/record/video inside a node // needs the recipient's uid as upload scene. Resolve it once up-front, // and only when at least one node actually contains media (saves an RPC - // for text-only forwards). + // for text-only forwards). Also need it when a node is itself a nested + // forward — the inner upload uses the same scene. let userUid: string | undefined; if (groupId === undefined && userId !== undefined && userId > 0) { - const hasMedia = nodes.some(node => node.elements.some( - e => e.type === 'image' || e.type === 'record' || e.type === 'video', - )); - if (hasMedia) { + const needsUid = nodes.some(node => !!node.innerForward + || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video')); + if (needsUid) { const resolved = await bridge.resolveUserUid(userId); if (resolved) userUid = resolved; } } - const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid))); + // Walk nodes and resolve nested forwards first (so we know their + // 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`. + const myInnerActions: ForwardInnerAction[] = []; + const processedNodes: ForwardNodePayload[] = []; + const isGroup = groupId !== undefined; + for (const node of nodes) { + if (node.innerForward && node.innerForward.length > 0) { + const inner = await uploadForwardNodesRecursive(bridge, node.innerForward, groupId, userId); + // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` + // + the entire `inner.innerPacketMsg` array up to its caller. We + // mirror that — `inner.uuid` indexes the inner level itself, + // and `inner.innerActions` already contains deeper layers. + 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. + const previewElement: MessageElement = { + type: 'forward', + resId: inner.resId, + forwardSource: deriveInnerSource(node.innerForward, isGroup), + forwardSummary: `查看${node.innerForward.length}条转发消息`, + forwardPrompt: '[聊天记录]', + forwardNews: previewLinesFromNodes(node.innerForward), + forwardTSum: node.innerForward.length, + }; + processedNodes.push({ + userUin: node.userUin, + nickname: node.nickname, + elements: [previewElement], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + }); + } else { + processedNodes.push(node); + } + } + + // Encode this level's msgBody. + const msgBody = await Promise.all(processedNodes.map( + node => buildForwardPushBody(bridge, node, groupId, userUid), + )); + + // Compose the action list: own MultiMsg + piggybacked inner actions. const longMsgResult = protobuf_encode({ action: [ - { - actionCommand: 'MultiMsg', - actionData: { msgBody }, - }, + { actionCommand: 'MultiMsg', actionData: { msgBody } }, + ...myInnerActions.map(a => ({ + actionCommand: a.uuid, + actionData: { msgBody: a.msgBody }, + })), ], }); @@ -137,7 +238,7 @@ export async function uploadForwardNodes( throw new Error('upload forward message response missing res_id'); } - forwardResCache.set(resId, nodes.map(node => ({ + forwardResCache.set(resId, processedNodes.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements], @@ -149,7 +250,53 @@ export async function uploadForwardNodes( messageType: node.messageType ?? (groupId ? 'group' : 'private'), }))); - return resId; + return { + resId, + msgBody, + uuid: randomUUID(), + innerActions: myInnerActions, + }; +} + +// Inner forward preview metadata — kept minimal here (the OneBot +// `parseForwardNodes` caller can override these on the top-level +// node by passing custom forwardSource/forwardSummary on the +// non-nested send path; nested levels just get sensible defaults +// since they're synthesised by us and never reach OneBot input). +function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string { + const nicks: string[] = []; + const seen = new Set(); + for (const node of innerNodes) { + const name = (node.nickname ?? '').trim(); + if (name && !seen.has(name)) { + seen.add(name); + nicks.push(name); + } + if (nicks.length >= 4) break; + } + if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录'; + return `${nicks.join('和')}的聊天记录`; +} + +function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> { + return innerNodes.slice(0, 4).map(node => { + const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); + const previewText = previewFromElements(node.elements); + return { text: previewText ? `${name}: ${previewText}` : name }; + }); +} + +function previewFromElements(elements: MessageElement[]): string { + for (const elem of elements) { + if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30); + if (elem.type === 'image') return '[图片]'; + if (elem.type === 'record') return '[语音]'; + if (elem.type === 'video') return '[视频]'; + if (elem.type === 'file') return '[文件]'; + if (elem.type === 'forward') return '[聊天记录]'; + if (elem.type === 'face') return '[表情]'; + } + return ''; } export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise { diff --git a/packages/core/src/bridge/events.ts b/packages/core/src/bridge/events.ts index e2665791..dcfe20ac 100644 --- a/packages/core/src/bridge/events.ts +++ b/packages/core/src/bridge/events.ts @@ -83,6 +83,18 @@ export interface ForwardNodePayload { groupId?: number; senderCard?: string; messageType?: 'group' | 'private'; + // When set, this node's `content` is a nested forward chain. The + // upload pipeline (see `actions/forward.ts::uploadForwardNodes`) + // recursively uploads the inner chain and replaces this node's + // `elements` with an ARK preview element pointing at the inner + // res_id. We also piggyback the inner chain's msgBody onto the + // outer long-msg upload as an extra `actionCommand` slot so the + // NapCat-compatible receiver can walk the whole tree from one + // server fetch without resolving each layer's res_id separately + // (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`). + // Caller never sets this on top-level OneBot input — `parseForward + // Nodes` synthesises it when it detects a nested-node array. + innerForward?: ForwardNodePayload[]; } export interface QQEvent { diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index a7b171a3..911b1bc7 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -635,34 +635,42 @@ async function parseForwardNodes( const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue; let elements: MessageElement[]; + let innerForward: ForwardNodePayload[] | undefined; 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. + // segments. We recursively parse them into a sibling + // `ForwardNodePayload[]` and attach it to this node as `innerForward`. + // `uploadForwardNodes` then drives the recursive upload + ARK-preview + // generation + msgBody piggyback in one pass over the whole tree. // - // 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, { + // Why hand it off instead of uploading here: NapCat (`dev/NapCatQQ/ + // .../SendMsg.uploadForwardedNodesPacket`) carries every inner level's + // packetMsg up to the outermost long-msg upload as extra + // `actionCommand` slots, so the receiver gets the whole tree from one + // server fetch. That cross-layer piggyback needs the upload pipeline + // to own the recursion — doing it in `parseForwardNodes` would force + // each level to do its own independent long-msg upload, which is what + // the previous implementation did and what a NapCat-compatible + // receiver couldn't walk. + innerForward = 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)]; + // Placeholder — `uploadForwardNodes` replaces these with a real + // forward-preview MessageElement once it has the inner res_id + + // uuid in hand. + elements = []; } else { elements = await parseMessage(content, false); } - if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`); + if (!innerForward && elements.length === 0) { + throw new Error(`forward node content is empty: ${userUin}`); + } - nodes.push({ userUin, nickname, elements }); + const node: ForwardNodePayload = { userUin, nickname, elements }; + if (innerForward) node.innerForward = innerForward; + nodes.push(node); } if (nodes.length === 0) { diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 2e63e515..8226118c 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -104,4 +104,50 @@ describe('actions/forward', () => { await expect(forward.fetchForwardNodes(bridge as any, 'cold-cache-miss')) .rejects.toThrow(/download forward message failed|down/); }); + + it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => { + // Regression: nested forward needs the inner chain to be uploaded + // first (so we have its res_id for the outer ARK preview), AND + // the inner level's msgBody to be carried up to the outermost + // long-msg upload as an extra `actionCommand` slot keyed on a + // uuid. Matches `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket` + // — the receiver gets the whole tree from a single fetch instead + // of resolving each layer's res_id separately. + const responses = ['inner-res', 'outer-res']; + const sendRawPacket = vi.fn(async () => uploadResponseWithResId(responses.shift()!)) as any; + const bridge = mockBridge({ sendRawPacket }); + + const resId = await forward.uploadForwardNodes(bridge as any, [ + { + userUin: 111, + nickname: 'outer', + elements: [], + innerForward: [ + { userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] }, + ], + }, + ]); + + // Two server roundtrips: one for the inner chain, then one for + // the outer (which piggybacks the inner msgBody onto its actions + // array). The outer res_id is what the caller gets back. + expect(resId).toBe('outer-res'); + expect(sendRawPacket).toHaveBeenCalledTimes(2); + }); + + it('uploadForwardNodes leaves flat (non-nested) sends at a single roundtrip', async () => { + // Backwards-compat: the common case (no inner forward) must still + // be one SsoSendLongMsg call. Without this we'd double upload + // every regular forward send. + const sendRawPacket = vi.fn(async () => uploadResponseWithResId('flat-res')) as any; + const bridge = mockBridge({ sendRawPacket }); + + const resId = await forward.uploadForwardNodes(bridge as any, [ + { userUin: 10001, nickname: 'a', elements: [{ type: 'text', text: 'hello' }] }, + { userUin: 10002, nickname: 'b', elements: [{ type: 'text', text: 'world' }] }, + ]); + + expect(resId).toBe('flat-res'); + expect(sendRawPacket).toHaveBeenCalledOnce(); + }); }); diff --git a/packages/core/tests/onebot/forward-nested.test.ts b/packages/core/tests/onebot/forward-nested.test.ts index 9e5979fd..39863dd5 100644 --- a/packages/core/tests/onebot/forward-nested.test.ts +++ b/packages/core/tests/onebot/forward-nested.test.ts @@ -1,22 +1,17 @@ // 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. +// `parseForwardNodes` detects an all-`{type:'node'}` content array, +// recursively builds the inner `ForwardNodePayload[]`, and attaches it +// to the outer node as `innerForward`. `uploadForwardNodes` then drives +// the recursive long-msg upload + ARK-preview generation + msgBody +// piggyback in one pass over the tree — modelled on NapCat's +// `uploadForwardedNodesPacket` (`dev/NapCatQQ/.../SendMsg.ts:208`). // -// 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). +// These tests stub `bridge.uploadForwardNodes` so we can inspect the +// payload that the upload pipeline receives: outer nodes carry an +// `innerForward` field holding the parsed inner chain, and the +// upload helper is invoked exactly ONCE (the recursive walk happens +// inside the real implementation; mocks see only the top call). import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; @@ -47,22 +42,13 @@ function makeCtx(bridge: BridgeInterface): 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[], _groupId?: number, _userId?: number) => { - // 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)}`); - }); + it('group: nested forward attaches inner chain to outer node via `innerForward`', async () => { + // Single upload call, but the outer payload now carries an + // `innerForward` field with the recursively-parsed inner chain. + // The real `uploadForwardNodes` (the production module) walks + // that tree and does the recursive long-msg uploads with NapCat + // piggyback — we're just testing the parse-side handoff here. + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'OUTER_RESID'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, })); @@ -86,35 +72,34 @@ describe('forward — nested {type:"node"} content', () => { const result = await sendGroupForwardMessage(ctx, 12345, messages as any); - // Two uploads: inner first, then outer. - expect(uploadForwardNodes).toHaveBeenCalledTimes(2); + // Exactly one upload call: the production-side recursive walker + // owns the inner upload, the OneBot parser just hands off the tree. + expect(uploadForwardNodes).toHaveBeenCalledOnce(); - // 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]!; + const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[0]!; 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', + const outerNode = (outerNodes as any[])[0]!; + expect(outerNode.userUin).toBe(111); + // Outer node's `elements` is empty — the upload pipeline replaces + // it with the real ARK preview once it has the inner res_id. + expect(outerNode.elements).toEqual([]); + // The inner chain rides along as `innerForward`. + expect(Array.isArray(outerNode.innerForward)).toBe(true); + expect(outerNode.innerForward).toHaveLength(1); + expect(outerNode.innerForward[0]).toMatchObject({ + userUin: 222, + nickname: 'inner', + elements: [{ type: 'text', text: 'hello from inner' }], }); expect(result.forwardId).toBe('OUTER_RESID'); expect(sendGroupMessage).toHaveBeenCalledOnce(); }); - it('private: nested forward threads userId into inner uploadForwardNodes', async () => { + it('private: nested forward threads userId into 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). + // passes `userId` instead of `groupId` so the upload pipeline can + // pick up the recipient's UID scene for any inner media element. const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID'); const sendPrivateMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, @@ -139,10 +124,15 @@ describe('forward — nested {type:"node"} content', () => { 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); + // Single call, c2c-scoped (groupId undefined, userId = recipient). + expect(uploadForwardNodes).toHaveBeenCalledOnce(); + const call = uploadForwardNodes.mock.calls[0]!; + expect(call[1]).toBeUndefined(); + expect(call[2]).toBe(67890); + // Inner chain attached via `innerForward`. + const outerNode = (call[0] as any[])[0]!; + expect(outerNode.innerForward).toHaveLength(1); + expect(outerNode.innerForward[0]!.userUin).toBe(222); }); it('rejects nesting deeper than 3 levels', async () => {