From 201d10c5343139c330a0d9044764800c7d4045e2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 13 Sep 2026 21:14:46 +0800 Subject: [PATCH] fix(onebot): rebuild merged forwards for the target chat Resending another chat's merged-forward card leaves an unopenable bubble. Fetch the inner tree and upload it for the destination. Fixes #437 --- .../onebot/src/modules/message-actions.ts | 102 +++++++++++++-- packages/onebot/tests/forward-nested.test.ts | 118 ++++++++++++++++++ 2 files changed, 212 insertions(+), 8 deletions(-) diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index b85996f1..ed773efe 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1228,12 +1228,11 @@ export async function uploadForwardMessage( /** * Forward a previously-received message to another peer. * - * We look up the cached event + media fingerprints, then re-send via the - * normal send pipeline with `noByteFallback` set on media elements so the - * upload modules fast-path through OIDB md5/sha1 instead of re-downloading - * the original CDN bytes. Fails fast if a media segment has no cached - * fingerprints or contains a file segment (file forwarding has its own - * separate protocol and is not in scope here). + * Plain text/image/record/video reuse the cached fingerprints and the + * normal send pipeline. A merged-forward card cannot be resent as-is: + * long-msg resid is scoped to the source chat, so the inner tree is + * fetched and uploaded again for the target. Fail the Action rather + * than leave an unopenable bubble. */ export async function forwardSingleMessage( ref: OneBotInstanceContext, @@ -1253,7 +1252,7 @@ export async function forwardSingleMessage( const parsed = await parseMessage(content, false); if (parsed.length === 0) throw new Error('message has no content'); - const elements = parsed.map((el) => enrichForForward(ref, el)); + const elements = await prepareSingleForwardElements(ref, parsed, target); let receipt; let messageIdOut: number; @@ -1277,11 +1276,98 @@ export async function forwardSingleMessage( return { messageId: messageIdOut }; } +async function prepareSingleForwardElements( + ref: OneBotInstanceContext, + elements: MessageElement[], + target: { groupId?: number; userId?: number }, +): Promise { + const out: MessageElement[] = []; + for (const element of elements) { + if (element.type !== 'forward') { + out.push(enrichForForward(ref, element)); + continue; + } + const resId = element.resId.trim(); + if (!resId) throw new Error('forward id is missing'); + const nodes = await expandForwardTreeForTarget(ref, resId, target, 0); + if (nodes.length === 0) throw new Error('forward content is empty'); + const newResId = await ref.bridge.apis.forward.upload(nodes, target.groupId, target.userId); + if (!newResId) throw new Error('forward regenerate failed'); + out.push(buildForwardPreviewElement(newResId, nodes, target.groupId !== undefined, undefined)); + } + return out; +} + +async function expandForwardTreeForTarget( + ref: OneBotInstanceContext, + resId: string, + target: { groupId?: number; userId?: number }, + depth: number, +): Promise { + if (depth >= MAX_FORWARD_DEPTH) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`, + 'forward', + 'id', + ); + } + const nodes = await ref.bridge.apis.forward.fetch(resId); + if (!Array.isArray(nodes) || nodes.length === 0) { + throw new Error('forward content is empty'); + } + const expanded: ForwardNodePayload[] = []; + for (const node of nodes) { + expanded.push(await expandForwardNodeForTarget(ref, node, target, depth)); + } + return expanded; +} + +async function expandForwardNodeForTarget( + ref: OneBotInstanceContext, + node: ForwardNodePayload, + target: { groupId?: number; userId?: number }, + depth: number, +): Promise { + const forwards = node.elements.filter((element): element is MessageElementOf<'forward'> => ( + element.type === 'forward' + )); + if (forwards.length === 0) return node; + + if (forwards.length === node.elements.length && forwards.length === 1) { + const innerId = forwards[0]!.resId.trim(); + if (!innerId) throw new Error('nested forward id is missing'); + return { + ...node, + elements: [], + innerForward: await expandForwardTreeForTarget(ref, innerId, target, depth + 1), + }; + } + + const elements: MessageElement[] = []; + for (const element of node.elements) { + if (element.type !== 'forward') { + elements.push(element); + continue; + } + const innerId = element.resId.trim(); + if (!innerId) throw new Error('nested forward id is missing'); + const inner = await expandForwardTreeForTarget(ref, innerId, target, depth + 1); + const newResId = await ref.bridge.apis.forward.upload(inner, target.groupId, target.userId); + if (!newResId) throw new Error('forward regenerate failed'); + elements.push(buildForwardPreviewElement(newResId, inner, target.groupId !== undefined, undefined)); + } + return { ...node, elements }; +} + function enrichForForward(ref: OneBotInstanceContext, element: MessageElement): MessageElement { + if (element.type === 'forward') { + throw new Error('merged forward must be regenerated for the target chat'); + } // The send path takes care of these as-is; nothing extra to do. if (element.type === 'text' || element.type === 'face' || element.type === 'at' || element.type === 'reply' || element.type === 'json' || element.type === 'xml' - || element.type === 'poke' || element.type === 'forward' || element.type === 'mface') { + || element.type === 'poke' || element.type === 'mface') { return element; } diff --git a/packages/onebot/tests/forward-nested.test.ts b/packages/onebot/tests/forward-nested.test.ts index a9bbf823..b0be2e18 100644 --- a/packages/onebot/tests/forward-nested.test.ts +++ b/packages/onebot/tests/forward-nested.test.ts @@ -237,6 +237,124 @@ describe('forward — nested {type:"node"} content', () => { expect(sendGroupMessage).not.toHaveBeenCalled(); }); + it('regenerates a cached merged forward for the target chat (#437)', async () => { + const fetch = vi.fn(async (resId: string) => { + expect(resId).toBe('OLD_RES'); + return [{ + userUin: 111, + nickname: 'alice', + elements: [{ type: 'text', text: 'hi' }], + }]; + }); + const upload = vi.fn(async (nodes: any[], groupId?: number, userId?: number) => { + expect(groupId).toBeUndefined(); + expect(userId).toBe(67890); + expect(nodes).toEqual([expect.objectContaining({ + userUin: 111, + elements: [{ type: 'text', text: 'hi' }], + })]); + return 'NEW_RES'; + }); + const sendPrivate = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 14, random: 1, timestamp: 1700000000, + })); + const bridge = fakeBridge({ + apis: { message: { sendPrivate }, forward: { fetch, upload } }, + } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { + findEvent: () => ({ + message: [{ type: 'forward', data: { id: 'OLD_RES' } }], + }), + }; + + const result = await forwardSingleMessage(ctx, 77, { userId: 67890 }); + + expect(result.messageId).not.toBe(0); + expect(fetch).toHaveBeenCalledOnce(); + expect(upload).toHaveBeenCalledOnce(); + expect(sendPrivate).toHaveBeenCalledOnce(); + expect(sendPrivate.mock.calls[0]![1]).toEqual([ + expect.objectContaining({ type: 'forward', resId: 'NEW_RES' }), + ]); + }); + + it('fails a merged-forward single send when the inner tree cannot be fetched (#437)', async () => { + const fetch = vi.fn(async () => { + throw new Error('download forward message failed'); + }); + const upload = vi.fn(async () => 'NEW_RES'); + const sendPrivate = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendPrivate }, forward: { fetch, upload } }, + } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { + findEvent: () => ({ + message: [{ type: 'forward', data: { id: 'OLD_RES' } }], + }), + }; + + await expect(forwardSingleMessage(ctx, 77, { userId: 67890 })) + .rejects.toThrow(/download forward message failed/); + expect(upload).not.toHaveBeenCalled(); + expect(sendPrivate).not.toHaveBeenCalled(); + }); + + it('expands a nested forward card into an inner tree before upload (#437)', async () => { + const fetch = vi.fn(async (resId: string) => { + if (resId === 'OUTER') { + return [{ + userUin: 111, + nickname: 'outer', + elements: [{ type: 'forward', resId: 'INNER' }], + }]; + } + if (resId === 'INNER') { + return [{ + userUin: 222, + nickname: 'inner', + elements: [{ type: 'text', text: 'leaf' }], + }]; + } + throw new Error(`unexpected fetch ${resId}`); + }); + const upload = vi.fn(async (nodes: any[]) => { + expect(nodes[0]).toMatchObject({ + userUin: 111, + elements: [], + innerForward: [ + expect.objectContaining({ + userUin: 222, + elements: [{ type: 'text', text: 'leaf' }], + }), + ], + }); + return 'NEW_OUTER'; + }); + const sendGroup = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, + })); + const bridge = fakeBridge({ + apis: { message: { sendGroup }, forward: { fetch, upload } }, + } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { + findEvent: () => ({ + message: [{ type: 'forward', data: { id: 'OUTER' } }], + }), + }; + + await forwardSingleMessage(ctx, 88, { groupId: 12345 }); + + expect(fetch).toHaveBeenCalledTimes(2); + expect(upload).toHaveBeenCalledOnce(); + expect(upload.mock.calls[0]![1]).toBe(12345); + expect(sendGroup).toHaveBeenCalledWith(12345, [ + expect.objectContaining({ type: 'forward', resId: 'NEW_OUTER' }), + ]); + }); + it('rejects hidden siblings before forwarding a cached video message', async () => { const sendGroupMessage = vi.fn(); const findVideo = vi.fn();