Files
SnowLuma/packages/core/tests/actions/forward.test.ts
T
DrSmoothl cec38b4c1b fix(forward): piggyback every nested level onto the outermost long-msg upload (NapCat model)
Cross-referenced `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`
(208-347): every layer of a nested forward attaches its own msgBody to
the *outer* long-msg upload under a uuid `actionCommand` slot. Receiver
walks the whole tree from one server fetch instead of resolving each
layer's res_id separately.

`dev/Lagrange.Core` (V2 branch on `linwenxuan04/v2`,
`MultiMsgUploadService.cs:23-31`) only writes a single MultiMsg action
— that's why NapCat-style receivers couldn't follow our previous
nested-forward sends past the first level.

Refactor:

1. `ForwardNodePayload` gets an optional `innerForward?:
   ForwardNodePayload[]` field. `parseForwardNodes` no longer eagerly
   uploads inner chains — it just attaches them here.

2. `uploadForwardNodes` now drives the whole recursion. The new
   `uploadForwardNodesRecursive`:
   - walks each node, recursively uploads any `innerForward` first
   - replaces that node's `elements` with a real `{type:'forward'}`
     preview pointing at the inner res_id
   - piggybacks the inner level's `{uuid, msgBody}` + every deeper
     level it surfaced into this level's `myInnerActions`
   - encodes the long-msg payload as
     `[{MultiMsg, ownMsgBody}, ...innerActions.map(uuid+msgBody)]`
   - returns `{resId, msgBody, uuid, innerActions}` so an outer call
     can keep climbing

   Top-level public signature unchanged: `Promise<string>`.

3. New `deriveInnerSource` / `previewLinesFromNodes` /
   `previewFromElements` helpers synthesise the ARK preview metadata
   the inner bubble shows before the user taps to expand. They handle
   text/image/record/video/file/forward/face element previews.

4. `parseForwardNodes`: when `content` is an all-node array, attach
   the parsed inner chain to `node.innerForward` and let the upload
   pipeline take over. `elements = []` placeholder is replaced by
   `uploadForwardNodes` once it has the real res_id.

Tests:

- `actions/forward.test.ts`:
  - `uploadForwardNodes recursively uploads nested innerForward chains
    (NapCat piggyback model)` — asserts two SsoSendLongMsg roundtrips
    (inner first, then outer) and the outer res_id propagates up
  - `flat sends still take a single roundtrip` — backwards-compat

- `onebot/forward-nested.test.ts`: rewritten — mock now sees exactly
  one `uploadForwardNodes` call with `innerForward` attached, instead
  of two sequential calls; depth-limit + mixed-content tests
  unchanged.
2026-05-19 23:29:59 +08:00

154 lines
6.1 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
// element-builder reaches into protoEncode with element-specific schemas
// that we don't want to construct manually in tests; stub it to return
// a benign placeholder.
vi.mock('../../src/bridge/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import { protoEncode } from '../../src/protobuf/decode';
import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg';
import * as forward from '../../src/bridge/actions/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema);
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(encoded),
};
}
describe('actions/forward', () => {
it('uploadForwardNodes rejects empty arrays', async () => {
const bridge = mockBridge();
await expect(forward.uploadForwardNodes(bridge as any, []))
.rejects.toThrow(/required/);
});
it('uploadForwardNodes dispatches to SsoSendLongMsg with a non-empty body and returns the res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-001')) as any,
});
const resId = await forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'alice', elements: [] },
]);
expect(resId).toBe('res-001');
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg');
expect((body as Uint8Array).length).toBeGreaterThan(0);
});
it('uploadForwardNodes throws when sendRawPacket reports failure', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'pipe broken', responseData: null,
})) as any,
});
await expect(forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/pipe broken/);
});
it('uploadForwardNodes throws when the response is missing res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('')) as any,
});
await expect(forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/missing res_id/);
});
it('fetchForwardNodes serves from cache after a successful upload (no second sendRawPacket)', async () => {
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-cache')) as any;
const bridge = mockBridge({ sendRawPacket });
const nodes = [
{ userUin: 10001, nickname: 'alice', elements: [] },
{ userUin: 10002, nickname: 'bob', elements: [] },
];
const resId = await forward.uploadForwardNodes(bridge as any, nodes);
expect(resId).toBe('res-cache');
const fetched = await forward.fetchForwardNodes(bridge as any, 'res-cache');
// Same nicknames + uins; elements have been deep-copied so the shape
// is preserved but the array reference is different.
expect(fetched).toHaveLength(2);
expect(fetched.map(n => n.nickname)).toEqual(['alice', 'bob']);
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
it('fetchForwardNodes throws on transport failure when nothing is cached', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'down', responseData: null,
})) as any,
});
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();
});
});