From e1f5267764bde0d6fe30e2962047b770636b8bdf Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 27 Jun 2026 16:27:33 +0800 Subject: [PATCH] fix(onebot): make group large-video file fallback actually fire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #153 added a video→file fallback but the group side was dead code: it lived in element-builder behind `isGroup && element.fileId`, and a video sent by url/path has no fileId, so oversize group videos just rethrew the raw Highway error (real bot: `error_code=323` on a 1.4 GB group send). Move the fallback to the OneBot layer for groups, mirroring the private path: on a failed Highway send, re-route oversize videos through groupFile.upload. Verified on a live bot — a 1.4 GB group video now lands as `[文件:video.mp4]` instead of failing. Extract the shared heuristic (isHighwaySizeError / videoNeedsFileFallback / splitVideoFileFallback) so private and group stay in sync, and drop the now-unreachable element-builder video catch. Adds send-video-fallback tests covering both the known-oversize and remote-error-heuristic paths. --- .../onebot/src/modules/message-actions.ts | 111 ++++++++++------ .../onebot/tests/send-video-fallback.test.ts | 121 ++++++++++++++++++ packages/protocol/src/element-builder.ts | 34 +++-- 3 files changed, 211 insertions(+), 55 deletions(-) create mode 100644 packages/onebot/tests/send-video-fallback.test.ts diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 86473897..e2d4da1c 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -13,6 +13,49 @@ import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types'; const log = createLogger('OneBot'); +// A video larger than QQ's Highway video ceiling can't be sent through the +// element pipeline — it must fall back to a regular file upload. The fallback +// is decided at the OneBot layer (not element-builder) because building a +// group/c2c file element needs an uploaded file, which only the file-upload +// pipeline produces. See send-video-fallback.test.ts. + +/** Whether a Highway upload error message looks size-related. */ +export function isHighwaySizeError(err: unknown): boolean { + return err instanceof Error && /size limit|too large|413|too big|exceed/i.test(err.message); +} + +/** + * A video element should fall back to file upload when its source size is + * known to exceed the limit, or — when the size can't be inferred (remote + * URL) — when the upload error itself looks size-related. + */ +export function videoNeedsFileFallback(element: MessageElement, isSizeErr: boolean): boolean { + if (element.type !== 'video') return false; + const sz = getVideoSourceSize(element); + return sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr; +} + +/** + * Partition elements after a failed Highway send: oversized videos become + * `file` elements (re-routed through the file-upload pipeline), everything + * else is returned for a normal re-send. + */ +export function splitVideoFileFallback( + elements: MessageElement[], + isSizeErr: boolean, +): { fileEls: MessageElement[]; remaining: MessageElement[] } { + const fileEls: MessageElement[] = []; + const remaining: MessageElement[] = []; + for (const e of elements) { + if (videoNeedsFileFallback(e, isSizeErr)) { + fileEls.push({ type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' }); + } else { + remaining.push(e); + } + } + return { fileEls, remaining }; +} + export async function getGroupMsgHistory( messageStore: MessageStore, groupId: number, @@ -546,38 +589,18 @@ export async function sendPrivateMessage( lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); logSentMessage(false, userId, nonFileElements); } catch (err) { - // Highway upload failed — check if a large video element triggered it - // and fall back to file upload for that element (private messages - // cannot carry file elements through the element pipeline). - const isSizeErr = err instanceof Error && /size limit|too large|413|too big|exceed/i.test(err.message); - const videoElements = nonFileElements.filter(e => e.type === 'video'); - // Trigger fallback when a video element is known to exceed the size - // limit, OR when the error message itself indicates a size-related - // failure (covers remote videos whose size couldn't be inferred). - const needsFallback = videoElements.some(e => { - const sz = getVideoSourceSize(e); - return sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr; - }); - if (needsFallback) { - log.warn('[OneBot] private video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err)); - const remaining: MessageElement[] = []; - for (const e of nonFileElements) { - if (e.type === 'video') { - const sz = getVideoSourceSize(e); - if (sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr) { - allFileElements = [...allFileElements, { type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' }]; - continue; - } - } - remaining.push(e); - } - nonFileElements = remaining; - if (nonFileElements.length > 0) { - lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); - logSentMessage(false, userId, nonFileElements); - } - } else { - throw err; + // Highway upload failed — if a large video triggered it, fall back to + // file upload for that element (private messages cannot carry file + // elements through the element pipeline). + const isSizeErr = isHighwaySizeError(err); + if (!nonFileElements.some(e => videoNeedsFileFallback(e, isSizeErr))) throw err; + log.warn('[OneBot] private video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err)); + const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr); + allFileElements = [...allFileElements, ...fileEls]; + nonFileElements = remaining; + if (nonFileElements.length > 0) { + lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); + logSentMessage(false, userId, nonFileElements); } } } @@ -664,13 +687,29 @@ export async function sendGroupMessage( // Two sub-paths for group file segments: // a) has url/path but no file_id → upload() which internally calls publish() // b) has file_id from a prior upload_group_file → publish() only - const allFileElements = elements.filter(e => e.type === 'file'); - const nonFileElements = elements.filter(e => e.type !== 'file'); + let allFileElements = elements.filter(e => e.type === 'file'); + let nonFileElements = elements.filter(e => e.type !== 'file'); let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { - lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements); - logSentMessage(true, groupId, nonFileElements); + try { + lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements); + logSentMessage(true, groupId, nonFileElements); + } catch (err) { + // Highway upload failed — if a large video triggered it, fall back to + // group file upload (mirrors the private path; element-builder cannot + // build a group file element without an already-uploaded file_id). + const isSizeErr = isHighwaySizeError(err); + if (!nonFileElements.some(e => videoNeedsFileFallback(e, isSizeErr))) throw err; + log.warn('[OneBot] group video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err)); + const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr); + allFileElements = [...allFileElements, ...fileEls]; + nonFileElements = remaining; + if (nonFileElements.length > 0) { + lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements); + logSentMessage(true, groupId, nonFileElements); + } + } } for (const fileEl of allFileElements) { let fileId: string; diff --git a/packages/onebot/tests/send-video-fallback.test.ts b/packages/onebot/tests/send-video-fallback.test.ts new file mode 100644 index 00000000..95b45ace --- /dev/null +++ b/packages/onebot/tests/send-video-fallback.test.ts @@ -0,0 +1,121 @@ +// Regression coverage for large-video → file-upload fallback. +// +// When a video exceeds QQ's Highway video ceiling the element-pipeline +// send throws. The OneBot layer catches that and re-routes the video +// through the dedicated file-upload pipeline (group: groupFile.upload, +// private: groupFile.uploadPrivate). The element-builder cannot produce +// a group file element on its own because it has no uploaded file_id at +// build time — so the fallback MUST live at the OneBot layer for both +// scenes (private already did; #153 left the group side broken). + +import { describe, expect, it, vi } from 'vitest'; +import type { MessageElement } from '@snowluma/protocol/events'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { OneBotInstanceContext } from '../src/instance-context'; +import { sendGroupMessage, videoNeedsFileFallback } from '../src/modules/message-actions'; + +const MB = 1024 * 1024; + +function fakeBridge(overrides: Partial = {}): 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, resolveReplySequence: () => 0 } as any, + cacheMessageMeta: vi.fn(), + mediaStore: {} as any, + musicSignUrl: '', + } as unknown as OneBotInstanceContext; +} + +describe('send_group_msg large-video fallback', () => { + it('routes the video through groupFile.upload when the Highway send fails with a size error', async () => { + const sendGroup = vi.fn(async (_gid: number, _elements: any[]) => { + throw new Error('video file too large: 1200 MB exceeds limit'); + }); + const upload = vi.fn(async (_gid: number, _src: string, _name: string, _folder: string, _doUpload: boolean) => + ({ fileId: 'auto-fid', fileHash: null })); + const publish = vi.fn(); + const bridge = fakeBridge({ + apis: { + message: { sendGroup }, + groupFile: { upload, publish }, + } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await sendGroupMessage(ctx, 12345, [{ + type: 'video', data: { file: 'http://example.com/big.mp4' }, + }] as any, false); + + // Highway send was attempted once (and threw)... + expect(sendGroup).toHaveBeenCalledOnce(); + // ...then the video was re-routed through the group file pipeline. + expect(upload).toHaveBeenCalledOnce(); + const [gid, src, name] = upload.mock.calls[0]!; + expect(gid).toBe(12345); + expect(src).toBe('http://example.com/big.mp4'); + expect(name).toBe('video.mp4'); + // upload() publishes internally — no second publish(). + expect(publish).not.toHaveBeenCalled(); + }); + + it('rethrows (no fallback) when a remote video fails with a non-size error', async () => { + // Size can't be inferred for a remote URL, and the error isn't + // size-related — we must not silently swallow an unrelated failure + // by converting it to a file upload. + const sendGroup = vi.fn(async (_gid: number, _elements: any[]) => { + throw new Error('network reset while streaming chunk 3'); + }); + const upload = vi.fn(); + const bridge = fakeBridge({ + apis: { + message: { sendGroup }, + groupFile: { upload, publish: vi.fn() }, + } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await expect(sendGroupMessage(ctx, 12345, [{ + type: 'video', data: { file: 'http://example.com/big.mp4' }, + }] as any, false)).rejects.toThrow('network reset'); + + expect(upload).not.toHaveBeenCalled(); + }); +}); + +describe('videoNeedsFileFallback', () => { + it('triggers on a known oversize source regardless of the error message', () => { + // The real-bot case: a local 1.4 GB video whose Highway upload fails + // with a cryptic `error_code=323` (not size-worded). Source size is + // known, so the file fallback must still fire. + const big = { type: 'video', fileSize: 1400 * MB } as MessageElement; + expect(videoNeedsFileFallback(big, /* isSizeErr */ false)).toBe(true); + }); + + it('does not trigger for a known under-limit source', () => { + const small = { type: 'video', fileSize: 50 * MB } as MessageElement; + expect(videoNeedsFileFallback(small, true)).toBe(false); + }); + + it('falls back to the error heuristic when the source size is unknown', () => { + const remote = { type: 'video', url: 'http://example.com/v.mp4' } as MessageElement; + expect(videoNeedsFileFallback(remote, true)).toBe(true); + expect(videoNeedsFileFallback(remote, false)).toBe(false); + }); + + it('never triggers for non-video elements', () => { + const img = { type: 'image', fileSize: 1400 * MB } as MessageElement; + expect(videoNeedsFileFallback(img, true)).toBe(false); + }); +}); diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index c10b0803..dbc36354 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -375,26 +375,22 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise throw new Error('private video target uid is missing'); } - try { - const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element); + const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element); - // commonElem.businessType is the QQ NT scene tag the receive-side - // decoder pairs with: 11=c2c, 21=group. Sending the group tag on a - // c2c message bounces with PbSendMsg result=79. - return { - commonElem: { - serviceType: 48, - pbElem: msgInfo, - businessType: isGroup ? 21 : 11, - }, - }; - } catch (err) { - if (isGroup && element.fileId) { - console.warn('[ElemBuilder] video upload failed, falling back to file element: %s', err instanceof Error ? err.message : String(err)); - return makeGroupFileElem(element, ctx); - } - throw err; - } + // commonElem.businessType is the QQ NT scene tag the receive-side + // decoder pairs with: 11=c2c, 21=group. Sending the group tag on a + // c2c message bounces with PbSendMsg result=79. + // + // Oversize videos throw here; the OneBot layer catches that and falls + // back to file upload (see message-actions.ts video fallback). A file + // element can't be built here — there's no uploaded file_id yet. + return { + commonElem: { + serviceType: 48, + pbElem: msgInfo, + businessType: isGroup ? 21 : 11, + }, + }; } /**