fix(onebot): support custom nested forward previews (#493)

Accept custom preview metadata on nested forward messages and carry it through card creation.

Refs #493
This commit is contained in:
under-the-ocean authored and GitHub committed 2026-10-04 15:44:06 +08:00
1 parent 1919e16081
commit 89275ae279
5 files changed
+208 -5

No files matched your search

@@ -1531,6 +1531,9 @@ export async function getForwardMessage(
nickname: node.nickname,
};
if (isGroup) sender.card = node.senderCard ?? '';
if (node.title !== undefined && node.title.length > 0) {
sender.title = node.title;
}
const message: JsonObject = {
self_id: ref.selfId,
@@ -1679,6 +1682,11 @@ function assertForwardNodeMetadataIsScalar(
value === undefined || value === null || typeof value === 'string'
|| typeof value === 'number' || typeof value === 'boolean'
) continue;
// OneBot 生态兼容:多个上游框架(NapCat / LLOneBot / AstrBot 等)
// 允许 forward node 携带 `news` 预览元数据(数组形态,
// `[{ text: string }]`,与 ForwardPreviewMeta.news 同构)。这些字段
// 仅用于生成卡片预览,不影响上传;直接放行而非拒绝整个转发。
if (field === 'news' && isForwardNewsArray(value)) continue;
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].${field} must be a scalar value`,
@@ -1688,6 +1696,16 @@ function assertForwardNodeMetadataIsScalar(
}
}
/** Whether a value looks like OneBot preview news: `Array<{ text: string }>`. */
function isForwardNewsArray(value: JsonValue): boolean {
if (!Array.isArray(value)) return false;
for (const item of value) {
const obj = asJsonObject(item);
if (!obj || typeof obj.text !== 'string') return false;
}
return true;
}
function assertForwardMessageInputPolicies(
ref: OneBotInstanceContext,
messages: JsonValue,
@@ -1914,6 +1932,20 @@ async function parseForwardNodes(
}
const node: ForwardNodePayload = { userUin, nickname, elements };
// Forward optional preview news lines (OneBot `data.news`) onto the
// payload so nested-forward bubble previews can prefer caller-supplied
// lines over auto-generated ones. Only accepted when the array shape
// is valid (already asserted by assertForwardNodeMetadataIsScalar).
if (isForwardNewsArray(nodeData.news)) {
node.news = nodeData.news as Array<{ text: string }>;
}
// Forward optional OneBot bubble-preview metadata so nested-forward
// cards can prefer caller-supplied titles/source/summary/prompt over
// auto-derived ones (all scalar, already asserted above).
if (nodeData.title !== undefined && typeof nodeData.title === 'string') node.title = nodeData.title;
if (nodeData.source !== undefined && typeof nodeData.source === 'string') node.source = nodeData.source;
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') node.summary = nodeData.summary;
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') node.prompt = nodeData.prompt;
// Honour an explicit per-node display time (OneBot `data.time`, unix
// seconds) so a custom forward can set/back-date each node's timestamp
// (#209). The wire field is uint32, so reject a millisecond value or any
@@ -615,4 +615,63 @@ describe('forward — nested {type:"node"} content', () => {
expect((nodes as any[])[0].nickname).toBe('PixivBot'); // custom nickname preserved
expect((nodes as any[])[1].userUin).toBe(10001); // omitted → self_id
});
it('accepts node metadata `news` preview arrays (OneBot ecosystem compat)', async () => {
// Upstream frameworks (NapCat / LLOneBot / AstrBot etc.) attach
// `news: [{ text }]` preview metadata to forward nodes. Only scalar
// metadata was allowed before, so a standard OneBot-style node was
// rejected with `forward messages[i].news must be a scalar value`.
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111,
nickname: 'outer',
news: [{ text: '预览行 1' }, { text: '预览行 2' }],
summary: '共 2 条',
content: [{ type: 'node', data: { user_id: 222, nickname: 'inner', content: [{ type: 'text', data: { text: 'hi' } }] } }],
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])[0].userUin).toBe(111);
expect((nodes as any[])[0].innerForward).toHaveLength(1);
});
it('rejects non-scalar node metadata that is not an accepted preview field', async () => {
// The news carve-out must stay narrow: any other non-scalar metadata
// (e.g. an accidental nested object) is still rejected up front.
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111,
nickname: 'bad',
arbitrary: { nested: true },
content: [{ type: 'text', data: { text: 'hi' } }],
},
}];
await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'node',
field: 'arbitrary',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
});