Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(messenger): apply per-platform attachment size budgets on push (#18535)

Rdmclin2578f57b0425e
diff --git a/apps/server/src/routers/lambda/__tests__/messenger.test.ts b/apps/server/src/routers/lambda/__tests__/messenger.test.ts
index 51e5ac73e5b..fe9ea281c17 100644
--- a/apps/server/src/routers/lambda/__tests__/messenger.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/messenger.test.ts
@@ -895,6 +895,7 @@ describe('messengerRouter.sendMessengerPush', () => {
fileType: 'application/pdf',
id: 'file-1',
name: 'report.pdf',
+ size: 123_456,
url: 's3://bucket/report.pdf',
});
});
@@ -918,6 +919,7 @@ describe('messengerRouter.sendMessengerPush', () => {
fetchUrl: 'https://app.lobehub.com/f/file-1',
mimeType: 'application/pdf',
name: 'report.pdf',
+ size: 123_456,
type: 'file',
},
],
diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.ts
index 06e9a6575d1..b2622336002 100644
--- a/apps/server/src/routers/lambda/messenger.ts
+++ b/apps/server/src/routers/lambda/messenger.ts
@@ -899,6 +899,10 @@ export const messengerRouter = router({
fetchUrl: await fileService.getFileAccessUrl({ id: file.id, url: file.url }),
mimeType: file.fileType,
name: file.name,
+ // Byte size from the owned row — the send path uses it to apply
+ // per-platform budgets (compress / degrade-to-link) without
+ // having to download URL-sourced attachments first.
+ size: file.size,
type: attachment.type,
};
}),
diff --git a/apps/server/src/services/bot/platforms/attachmentBudget.test.ts b/apps/server/src/services/bot/platforms/attachmentBudget.test.ts
new file mode 100644
index 00000000000..cef56a6bac4
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/attachmentBudget.test.ts
@@ -0,0 +1,244 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const sharpMocks = vi.hoisted(() => ({
+ metadata: vi.fn(),
+ toBuffer: vi.fn(),
+}));
+
+vi.mock('sharp', () => {
+ const chain = {
+ flatten: vi.fn(() => chain),
+ jpeg: vi.fn(() => chain),
+ metadata: sharpMocks.metadata,
+ resize: vi.fn(() => chain),
+ rotate: vi.fn(() => chain),
+ toBuffer: sharpMocks.toBuffer,
+ };
+ return { default: vi.fn(() => chain) };
+});
+
+const {
+ compressImageToBudget,
+ PLATFORM_ATTACHMENT_BUDGETS,
+ prepareAttachmentsForBudget,
+ splitFallbackMessages,
+} = await import('./attachmentBudget');
+
+const MB = 1024 * 1024;
+
+describe('compressImageToBudget', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ sharpMocks.metadata.mockResolvedValue({ pages: 1 });
+ });
+
+ it('returns the first ladder rung that fits the budget', async () => {
+ sharpMocks.toBuffer
+ .mockResolvedValueOnce(Buffer.alloc(3 * MB))
+ .mockResolvedValueOnce(Buffer.alloc(1 * MB));
+
+ const result = await compressImageToBudget(Buffer.alloc(5 * MB), 2 * MB);
+
+ expect(result?.length).toBe(1 * MB);
+ expect(sharpMocks.toBuffer).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns undefined when no rung fits', async () => {
+ sharpMocks.toBuffer.mockResolvedValue(Buffer.alloc(3 * MB));
+
+ const result = await compressImageToBudget(Buffer.alloc(5 * MB), 2 * MB);
+
+ expect(result).toBeUndefined();
+ });
+
+ it('refuses an animated image instead of flattening it to one frame', async () => {
+ sharpMocks.metadata.mockResolvedValue({ pages: 24 });
+
+ expect(await compressImageToBudget(Buffer.alloc(64), 1024)).toBeUndefined();
+ expect(sharpMocks.toBuffer).not.toHaveBeenCalled();
+ });
+
+ it('returns undefined when sharp cannot decode the source', async () => {
+ sharpMocks.toBuffer.mockRejectedValue(new Error('unsupported image format'));
+
+ const result = await compressImageToBudget(Buffer.from('not an image'), 2 * MB);
+
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('prepareAttachmentsForBudget', () => {
+ const budget = PLATFORM_ATTACHMENT_BUDGETS.wechat;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ sharpMocks.metadata.mockResolvedValue({ pages: 1 });
+ });
+
+ it('passes attachments within budget through untouched', async () => {
+ const attachment = {
+ fetchUrl: 'https://example.com/f/small.png',
+ name: 'small.png',
+ size: 100 * 1024,
+ type: 'image' as const,
+ };
+
+ const result = await prepareAttachmentsForBudget([attachment], budget);
+
+ expect(result.attachments).toEqual([attachment]);
+ expect(result.fallbackLines).toEqual([]);
+ });
+
+ it('passes attachments with unknown size through untouched', async () => {
+ const attachment = {
+ fetchUrl: 'https://example.com/f/unknown.mp4',
+ name: 'unknown.mp4',
+ type: 'video' as const,
+ };
+
+ const result = await prepareAttachmentsForBudget([attachment], budget);
+
+ expect(result.attachments).toEqual([attachment]);
+ expect(result.fallbackLines).toEqual([]);
+ });
+
+ it('recompresses an over-budget image into inline data', async () => {
+ const source = Buffer.alloc(3 * MB, 1);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(source, { status: 200 })));
+ sharpMocks.toBuffer.mockResolvedValueOnce(Buffer.alloc(1 * MB, 2));
+
+ const result = await prepareAttachmentsForBudget(
+ [
+ {
+ fetchUrl: 'https://example.com/f/big.png',
+ name: 'big.png',
+ size: 3 * MB,
+ type: 'image' as const,
+ },
+ ],
+ budget,
+ );
+
+ expect(result.fallbackLines).toEqual([]);
+ expect(result.attachments).toHaveLength(1);
+ expect(result.attachments[0]).toMatchObject({
+ fetchUrl: undefined,
+ mimeType: 'image/jpeg',
+ // Discord and Slack upload `name` verbatim, so JPEG bytes must not keep
+ // a `.png` extension.
+ name: 'big.jpg',
+ size: 1 * MB,
+ type: 'image',
+ });
+ expect(result.attachments[0].data).toBe(Buffer.alloc(1 * MB, 2).toString('base64'));
+ });
+
+ it('degrades an over-budget image to a link when compression cannot fit it', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(Buffer.alloc(3 * MB), { status: 200 })),
+ );
+ sharpMocks.toBuffer.mockResolvedValue(Buffer.alloc(3 * MB));
+
+ const result = await prepareAttachmentsForBudget(
+ [
+ {
+ fetchUrl: 'https://example.com/f/huge.png',
+ name: 'huge.png',
+ size: 3 * MB,
+ type: 'image' as const,
+ },
+ ],
+ budget,
+ );
+
+ expect(result.attachments).toEqual([]);
+ expect(result.fallbackLines).toHaveLength(1);
+ expect(result.fallbackLines[0]).toContain('huge.png');
+ expect(result.fallbackLines[0]).toContain('https://example.com/f/huge.png');
+ });
+
+ it('caps the displayed filename so one fallback line stays short', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ const result = await prepareAttachmentsForBudget(
+ [
+ {
+ fetchUrl: 'https://example.com/f/long',
+ name: `${'n'.repeat(300)}.zip`,
+ size: 40 * MB,
+ type: 'file' as const,
+ },
+ ],
+ budget,
+ );
+
+ expect(result.attachments).toEqual([]);
+ expect(result.fallbackLines).toHaveLength(1);
+ expect(result.fallbackLines[0]).toBe(
+ `📎 ${'n'.repeat(59)}\u2026 (40.0MB)\nhttps://example.com/f/long`,
+ );
+ });
+
+ it('degrades an over-budget file to a download link without fetching it', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ const result = await prepareAttachmentsForBudget(
+ [
+ {
+ fetchUrl: 'https://example.com/f/movie.mp4',
+ name: 'movie.mp4',
+ size: 100 * MB,
+ type: 'video' as const,
+ },
+ ],
+ budget,
+ );
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(result.attachments).toEqual([]);
+ expect(result.fallbackLines[0]).toContain('movie.mp4');
+ expect(result.fallbackLines[0]).toContain('100.0MB');
+ expect(result.fallbackLines[0]).toContain('https://example.com/f/movie.mp4');
+ });
+
+ it('keeps an over-budget attachment without a fetchUrl as a last resort', async () => {
+ const attachment = {
+ data: Buffer.alloc(30 * MB).toString('base64'),
+ name: 'inline.bin',
+ type: 'file' as const,
+ };
+
+ const result = await prepareAttachmentsForBudget([attachment], budget);
+
+ expect(result.attachments).toEqual([attachment]);
+ expect(result.fallbackLines).toEqual([]);
+ });
+});
+
+describe('splitFallbackMessages', () => {
+ it('packs lines into one message while they fit', () => {
+ expect(splitFallbackMessages(['📎 a\nurl', '📎 b\nurl'], 2000)).toEqual([
+ '📎 a\nurl\n\n📎 b\nurl',
+ ]);
+ expect(splitFallbackMessages([], 2000)).toEqual([]);
+ });
+
+ it('starts a new message rather than exceeding the platform cap', () => {
+ const lines = ['a'.repeat(40), 'b'.repeat(40), 'c'.repeat(40)];
+
+ // Two 40-char lines plus the blank-line separator are 82 chars, so a
+ // 100-char cap fits two lines per message and never splits one.
+ expect(splitFallbackMessages(lines, 100)).toEqual([`${lines[0]}\n\n${lines[1]}`, lines[2]]);
+ });
+
+ it('never truncates a single line, even when it alone exceeds the cap', () => {
+ const line = 'x'.repeat(50);
+
+ expect(splitFallbackMessages([line], 10)).toEqual([line]);
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/attachmentBudget.ts b/apps/server/src/services/bot/platforms/attachmentBudget.ts
new file mode 100644
index 00000000000..33e22c1cab9
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/attachmentBudget.ts
@@ -0,0 +1,293 @@
+import type { MessengerAttachmentBudget } from '@lobechat/const';
+import { MESSENGER_ATTACHMENT_BUDGETS } from '@lobechat/const';
+import debug from 'debug';
+
+import type { BotMessageAttachment } from './types';
+
+const log = debug('bot-platform:attachment-budget');
+
+/**
+ * Per-platform attachment size budgets for the proactive push path.
+ *
+ * Every platform enforces (or silently applies) its own attachment cap, and
+ * an over-budget upload either errors at the platform API (Telegram, Discord)
+ * or — worse — succeeds end-to-end and never renders on the recipient's
+ * client (WeChat iLink: a 2.3MB PNG returns 200 on `getuploadurl`, the CDN
+ * upload AND `sendmessage`, yet the message never appears). Budgets let the
+ * sender degrade deliberately instead of failing silently:
+ *
+ * original attachment → recompressed image → download-link text
+ *
+ * The values live in `@lobechat/const` (MESSENGER_ATTACHMENT_BUDGETS) because
+ * the push modal uses the same table to warn the user before sending.
+ */
+export type PlatformAttachmentBudget = MessengerAttachmentBudget;
+
+export const PLATFORM_ATTACHMENT_BUDGETS = MESSENGER_ATTACHMENT_BUDGETS;
+
+const MB = 1024 * 1024;
+
+export interface PreparedAttachments {
+ attachments: BotMessageAttachment[];
+ /**
+ * The original attachments behind `fallbackLines`. Callers with a replay
+ * queue requeue these (rather than the whole input) when the link leg fails,
+ * so an attachment that already uploaded is not sent twice.
+ */
+ degraded: BotMessageAttachment[];
+ /**
+ * One line per attachment that could not be delivered as a file within the
+ * platform budget. Callers append these to the outbound text leg so the
+ * recipient still gets the resource as a download link.
+ */
+ fallbackLines: string[];
+ /**
+ * The untouched inputs behind `attachments`, index-aligned with it. A
+ * recompressed image carries megabytes of base64 in `attachments`; a caller
+ * requeueing a failed send wants the small original back, not that.
+ */
+ keptOriginals: BotMessageAttachment[];
+}
+
+const formatBytes = (bytes: number): string => {
+ if (bytes >= MB) return `${(bytes / MB).toFixed(1)}MB`;
+ return `${Math.max(1, Math.round(bytes / 1024))}KB`;
+};
+
+/**
+ * Cap the displayed filename so one fallback line stays well inside every
+ * platform's message limit — a name can legitimately be 255 chars, and the
+ * URL after it is the part that must never be truncated.
+ */
+const MAX_FALLBACK_NAME_CHARS = 60;
+
+const truncateName = (name: string): string =>
+ name.length <= MAX_FALLBACK_NAME_CHARS ? name : `${name.slice(0, MAX_FALLBACK_NAME_CHARS - 1)}…`;
+
+/**
+ * Language-neutral download-link line for an attachment that exceeds the
+ * platform budget. In production `fetchUrl` is the stable anonymous
+ * file-proxy URL (`/f/:id`), so the link keeps working after the presigned
+ * storage snapshot would have expired.
+ */
+export const buildAttachmentFallbackLine = (
+ attachment: BotMessageAttachment,
+ url: string,
+): string => {
+ const name = truncateName(attachment.name?.trim() || 'file');
+ const size = attachment.size ? ` (${formatBytes(attachment.size)})` : '';
+ return `📎 ${name}${size}\n${url}`;
+};
+
+/**
+ * Re-point a filename at the JPEG bytes we just produced. Discord and Slack
+ * upload `name` verbatim and Discord picks its preview from the extension,
+ * so leaving a recompressed PNG named `.png` ships JPEG bytes under a lying
+ * extension. `undefined` stays undefined — the platform senders then infer a
+ * generic name from `mimeType`, which is already `image/jpeg`.
+ */
+const toJpegFilename = (name: string | undefined): string | undefined => {
+ const trimmed = name?.trim();
+ if (!trimmed) return undefined;
+ return `${trimmed.replace(/\.[^./\\]*$/, '')}.jpg`;
+};
+
+/** Refuse to buffer arbitrarily large remote files into memory for compression. */
+const MAX_COMPRESSION_SOURCE_BYTES = 100 * MB;
+
+const loadSourceBuffer = async (attachment: BotMessageAttachment): Promise<Buffer | undefined> => {
+ if (attachment.data) {
+ try {
+ return Buffer.from(attachment.data, 'base64');
+ } catch (error) {
+ log('loadSourceBuffer: failed to decode base64: %O', error);
+ }
+ }
+ if (attachment.fetchUrl) {
+ try {
+ const response = await fetch(attachment.fetchUrl, { signal: AbortSignal.timeout(15_000) });
+ if (response.ok) {
+ const buffer = Buffer.from(await response.arrayBuffer());
+ if (buffer.length <= MAX_COMPRESSION_SOURCE_BYTES) return buffer;
+ log('loadSourceBuffer: %d bytes exceeds compression source cap', buffer.length);
+ } else {
+ log('loadSourceBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);
+ }
+ } catch (error) {
+ log('loadSourceBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);
+ }
+ }
+ return undefined;
+};
+
+/**
+ * Ladder of (max dimension, JPEG quality) attempts, largest/best first. The
+ * first re-encode that fits the byte budget wins. JPEG is deliberate: chat
+ * screenshots and photos re-encode an order of magnitude smaller than PNG,
+ * and every push platform renders JPEG. Alpha flattens to white.
+ */
+const COMPRESSION_LADDER: Array<[number, number]> = [
+ [4096, 82],
+ [2048, 80],
+ [2048, 65],
+ [1600, 60],
+ [1200, 55],
+ [900, 50],
+];
+
+/**
+ * Re-encode an image to fit `maxBytes`, or return undefined when it cannot
+ * (not an image sharp can decode, or still over budget at the smallest rung).
+ *
+ * sharp is imported lazily: this module is reachable from the outbound push
+ * path, which deliberately keeps heavy native dependencies out of its module
+ * graph (see services/messenger/outbound.ts) — the import cost is only paid
+ * when an over-budget image actually needs recompression.
+ */
+export const compressImageToBudget = async (
+ source: Buffer,
+ maxBytes: number,
+): Promise<Buffer | undefined> => {
+ try {
+ const { default: sharp } = await import('sharp');
+
+ // An animated GIF or WebP re-encodes to a single static frame, silently
+ // turning the user's animation into a still. There is no JPEG that can
+ // carry it, so refuse and let the caller fall back to a download link.
+ const { pages } = await sharp(source).metadata();
+ if (pages && pages > 1) {
+ log('refusing to flatten a %d-page animated image — falling back to a link', pages);
+ return undefined;
+ }
+
+ for (const [dimension, quality] of COMPRESSION_LADDER) {
+ const result = await sharp(source)
+ .rotate() // apply EXIF orientation before it is stripped by re-encode
+ .resize(dimension, dimension, { fit: 'inside', withoutEnlargement: true })
+ .flatten({ background: '#ffffff' })
+ .jpeg({ quality })
+ .toBuffer();
+ if (result.length <= maxBytes) {
+ log(
+ 'compressed image %d → %d bytes (dim=%d q=%d)',
+ source.length,
+ result.length,
+ dimension,
+ quality,
+ );
+ return result;
+ }
+ }
+ log('compression exhausted ladder without fitting %d bytes', maxBytes);
+ return undefined;
+ } catch (error) {
+ log('compressImageToBudget failed: %O', error);
+ return undefined;
+ }
+};
+
+const knownSize = (attachment: BotMessageAttachment): number | undefined => {
+ if (typeof attachment.size === 'number' && attachment.size > 0) return attachment.size;
+ // Base64 inflates by 4/3 — close enough for a budget check.
+ if (attachment.data) return Math.floor(attachment.data.length * 0.75);
+ return undefined;
+};
+
+/**
+ * Fit attachments to a platform budget before handing them to the platform
+ * sender. Three-tier degradation per attachment:
+ *
+ * 1. Within budget (or size unknown): passed through untouched — senders keep
+ * their existing behavior, including Telegram's URL pass-through.
+ * 2. Over-budget image: downloaded and recompressed under `imageMaxBytes`;
+ * the attachment is rewritten to carry the compressed bytes as base64
+ * `data` (the platform senders all accept `data` over `fetchUrl`).
+ * 3. Over-budget file / video / audio — or an image that cannot be
+ * compressed under budget: replaced by a download-link line in
+ * `fallbackLines` when a `fetchUrl` exists. Without a URL the original
+ * attachment is kept as a last resort (old behavior) rather than dropped.
+ */
+export const prepareAttachmentsForBudget = async (
+ attachments: BotMessageAttachment[],
+ budget: PlatformAttachmentBudget,
+): Promise<PreparedAttachments> => {
+ const kept: BotMessageAttachment[] = [];
+ const keptOriginals: BotMessageAttachment[] = [];
+ const degraded: BotMessageAttachment[] = [];
+ const fallbackLines: string[] = [];
+
+ for (const attachment of attachments) {
+ const limit = attachment.type === 'image' ? budget.imageMaxBytes : budget.fileMaxBytes;
+ const size = knownSize(attachment);
+
+ if (size === undefined || size <= limit) {
+ kept.push(attachment);
+ keptOriginals.push(attachment);
+ continue;
+ }
+
+ // Only images are worth downloading — and only when the declared size is
+ // small enough that buffering it for re-encode is safe. A 500MB "image"
+ // goes straight to the link fallback instead of into memory.
+ if (attachment.type === 'image' && size <= MAX_COMPRESSION_SOURCE_BYTES) {
+ const source = await loadSourceBuffer(attachment);
+ const compressed = source && (await compressImageToBudget(source, budget.imageMaxBytes));
+ if (compressed) {
+ kept.push({
+ ...attachment,
+ data: compressed.toString('base64'),
+ fetchUrl: undefined,
+ mimeType: 'image/jpeg',
+ name: toJpegFilename(attachment.name),
+ size: compressed.length,
+ });
+ keptOriginals.push(attachment);
+ continue;
+ }
+ }
+
+ if (attachment.fetchUrl) {
+ log(
+ 'attachment "%s" (%d bytes) exceeds %d-byte budget — degrading to link',
+ attachment.name ?? '(unnamed)',
+ size,
+ limit,
+ );
+ fallbackLines.push(buildAttachmentFallbackLine(attachment, attachment.fetchUrl));
+ degraded.push(attachment);
+ continue;
+ }
+
+ // No URL to link to and no smaller representation — keep the original and
+ // let the platform sender try (matches pre-budget behavior).
+ kept.push(attachment);
+ keptOriginals.push(attachment);
+ }
+
+ return { attachments: kept, degraded, fallbackLines, keptOriginals };
+};
+
+/**
+ * Pack fallback link lines into as few follow-up text messages as fit under
+ * `maxChars`. Batching is by whole line: Discord rejects a message over its
+ * limit outright and Telegram truncates at its own, either of which would
+ * cut a URL in half and hand the user a dead link. Lines are already length
+ * capped (see MAX_FALLBACK_NAME_CHARS), so a single line always fits.
+ */
+export const splitFallbackMessages = (fallbackLines: string[], maxChars: number): string[] => {
+ const messages: string[] = [];
+ let current = '';
+
+ for (const line of fallbackLines) {
+ const candidate = current ? `${current}\n\n${line}` : line;
+ if (current && candidate.length > maxChars) {
+ messages.push(current);
+ current = line;
+ } else {
+ current = candidate;
+ }
+ }
+ if (current) messages.push(current);
+
+ return messages;
+};
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index ae688eca4f3..d0675939767 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -126,6 +126,12 @@ export interface BotMessageAttachment {
fetchUrl?: string;
mimeType?: string;
name?: string;
+ /**
+ * Size of the underlying bytes, when the caller knows it (e.g. from the
+ * files table). Lets the send path apply platform size budgets without
+ * downloading URL-sourced attachments first.
+ */
+ size?: number;
type: 'image' | 'file' | 'video' | 'audio';
}
diff --git a/apps/server/src/services/bot/platforms/wechat/contextWindow.ts b/apps/server/src/services/bot/platforms/wechat/contextWindow.ts
index 9b93565ca52..fd04e3cd6ad 100644
--- a/apps/server/src/services/bot/platforms/wechat/contextWindow.ts
+++ b/apps/server/src/services/bot/platforms/wechat/contextWindow.ts
@@ -238,7 +238,7 @@ export const drainPendingPushes = async (
redis: WechatWindowRedis,
applicationId: string,
userId: string,
- send: (payload: WechatPendingPush) => Promise<'sent' | 'stop'>,
+ send: (payload: WechatPendingPush) => Promise<'sent' | 'stop' | { requeue: WechatPendingPush }>,
): Promise<number> => {
const lockKey = flushLockKey(applicationId, userId);
const locked = await redis.set(lockKey, '1', 'EX', FLUSH_LOCK_TTL_SECONDS, 'NX');
@@ -264,6 +264,12 @@ export const drainPendingPushes = async (
await redis.lpush(pendingKey, raw);
break;
}
+ if (typeof result === 'object') {
+ // Partial delivery: put back only what still needs sending, so the
+ // next replay does not repeat a leg the user already received.
+ await redis.lpush(pendingKey, JSON.stringify(result.requeue));
+ break;
+ }
sent++;
}
} finally {
diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts
new file mode 100644
index 00000000000..84b2c1c7be3
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts
@@ -0,0 +1,181 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const budgetMocks = vi.hoisted(() => ({
+ compressImageToBudget: vi.fn(),
+}));
+
+vi.mock('../attachmentBudget', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ compressImageToBudget: budgetMocks.compressImageToBudget,
+}));
+
+const { PLATFORM_ATTACHMENT_BUDGETS } = await import('../attachmentBudget');
+const { sendWechatAttachments } = await import('./sendAttachments');
+
+const MB = 1024 * 1024;
+
+const makeApi = () => ({
+ sendItem: vi.fn().mockResolvedValue({}),
+ sendMessage: vi.fn().mockResolvedValue({}),
+ uploadCdnMedia: vi.fn().mockResolvedValue({
+ aesKey: 'key',
+ cipherSize: 16,
+ encryptQueryParam: 'param',
+ rawSize: 10,
+ }),
+});
+
+describe('sendWechatAttachments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('uploads an in-budget attachment as-is', async () => {
+ const api = makeApi();
+ const bytes = Buffer.alloc(1024, 1);
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [{ data: bytes.toString('base64'), name: 'a.png', type: 'image' }],
+ 'token-1',
+ );
+
+ expect(budgetMocks.compressImageToBudget).not.toHaveBeenCalled();
+ expect(api.uploadCdnMedia).toHaveBeenCalledTimes(1);
+ expect(api.sendItem).toHaveBeenCalledTimes(1);
+ expect(api.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('recompresses an over-budget image before uploading', async () => {
+ const api = makeApi();
+ const oversized = Buffer.alloc(3 * MB, 1);
+ const compressed = Buffer.alloc(1 * MB, 2);
+ budgetMocks.compressImageToBudget.mockResolvedValueOnce(compressed);
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [{ data: oversized.toString('base64'), name: 'big.png', type: 'image' }],
+ 'token-1',
+ );
+
+ expect(budgetMocks.compressImageToBudget).toHaveBeenCalledWith(
+ expect.any(Buffer),
+ PLATFORM_ATTACHMENT_BUDGETS.wechat.imageMaxBytes,
+ );
+ expect(api.uploadCdnMedia).toHaveBeenCalledWith('user-1', expect.anything(), compressed);
+ expect(api.sendItem).toHaveBeenCalledTimes(1);
+ });
+
+ it('sends a download link when an image cannot be compressed under budget', async () => {
+ const api = makeApi();
+ const oversized = Buffer.alloc(3 * MB, 1);
+ budgetMocks.compressImageToBudget.mockResolvedValueOnce(undefined);
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [
+ {
+ data: oversized.toString('base64'),
+ fetchUrl: 'https://example.com/f/big.png',
+ name: 'big.png',
+ type: 'image',
+ },
+ ],
+ 'token-1',
+ );
+
+ expect(api.uploadCdnMedia).not.toHaveBeenCalled();
+ expect(api.sendMessage).toHaveBeenCalledWith(
+ 'user-1',
+ expect.stringContaining('https://example.com/f/big.png'),
+ 'token-1',
+ );
+ });
+
+ it('sends a download link for an over-budget file without trying compression', async () => {
+ const api = makeApi();
+ const oversized = Buffer.alloc(21 * MB, 1);
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [
+ {
+ data: oversized.toString('base64'),
+ fetchUrl: 'https://example.com/f/big.zip',
+ name: 'big.zip',
+ type: 'file',
+ },
+ ],
+ 'token-1',
+ );
+
+ expect(budgetMocks.compressImageToBudget).not.toHaveBeenCalled();
+ expect(api.uploadCdnMedia).not.toHaveBeenCalled();
+ expect(api.sendMessage).toHaveBeenCalledWith(
+ 'user-1',
+ expect.stringContaining('big.zip'),
+ 'token-1',
+ );
+ });
+
+ it('propagates a fallback-link failure so the replay queue keeps the payload', async () => {
+ const api = makeApi();
+ api.sendMessage.mockRejectedValue(new Error('iLink down'));
+
+ await expect(
+ sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [
+ {
+ data: Buffer.alloc(21 * MB, 1).toString('base64'),
+ fetchUrl: 'https://example.com/f/big.zip',
+ name: 'big.zip',
+ type: 'file',
+ },
+ ],
+ 'token-1',
+ ),
+ ).rejects.toThrow('iLink down');
+ });
+
+ it('batches several fallback links into one message', async () => {
+ const api = makeApi();
+ const oversized = Buffer.alloc(21 * MB, 1).toString('base64');
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [
+ { data: oversized, fetchUrl: 'https://example.com/f/a', name: 'a.zip', type: 'file' },
+ { data: oversized, fetchUrl: 'https://example.com/f/b', name: 'b.zip', type: 'file' },
+ ],
+ 'token-1',
+ );
+
+ expect(api.sendMessage).toHaveBeenCalledTimes(1);
+ expect(api.sendMessage.mock.calls[0][1]).toContain('a.zip');
+ expect(api.sendMessage.mock.calls[0][1]).toContain('b.zip');
+ });
+
+ it('skips an over-budget attachment with no fetchUrl instead of uploading it', async () => {
+ const api = makeApi();
+ budgetMocks.compressImageToBudget.mockResolvedValueOnce(undefined);
+
+ await sendWechatAttachments(
+ api as any,
+ 'user-1',
+ [{ data: Buffer.alloc(3 * MB).toString('base64'), name: 'big.png', type: 'image' }],
+ 'token-1',
+ );
+
+ expect(api.uploadCdnMedia).not.toHaveBeenCalled();
+ expect(api.sendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts
index 58988aad3e7..d91794b8d43 100644
--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts
+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts
@@ -2,6 +2,13 @@ import type { MessageItem, WechatApiClient } from '@lobechat/chat-adapter-wechat
import { MessageItemType, WechatUploadMediaType } from '@lobechat/chat-adapter-wechat';
import debug from 'debug';
+import {
+ buildAttachmentFallbackLine,
+ compressImageToBudget,
+ PLATFORM_ATTACHMENT_BUDGETS,
+ splitFallbackMessages,
+} from '../attachmentBudget';
+
const log = debug('bot-platform:wechat:send-attachments');
/**
@@ -19,6 +26,8 @@ export interface WechatOutboundAttachment {
fetchUrl?: string;
mimeType?: string;
name?: string;
+ /** Byte size when known — lets the push path apply size budgets up front. */
+ size?: number;
type: 'image' | 'file' | 'video' | 'audio';
}
@@ -117,20 +126,62 @@ const buildMediaItemFromUpload = (
* protocol §6.7, one MessageItem per request). Single-attachment failures
* are logged and skipped so the rest still ship — mirroring the chat-adapter
* adapter's per-item try/catch.
+ *
+ * Returns the attachments that did NOT reach the user, so a caller with a
+ * replay queue can requeue exactly those instead of assuming the whole leg
+ * landed. Attachments degraded to a download link count as delivered once
+ * the link message sends; if that send throws, the whole call throws and the
+ * return value is moot.
*/
export const sendWechatAttachments = async (
api: WechatApiClient,
toUserId: string,
attachments: WechatOutboundAttachment[],
contextToken: string,
-): Promise<void> => {
+): Promise<WechatOutboundAttachment[]> => {
+ const budget = PLATFORM_ATTACHMENT_BUDGETS.wechat;
+ const fallbackLines: string[] = [];
+ const undelivered: WechatOutboundAttachment[] = [];
+
for (const attachment of attachments) {
try {
- const buffer = await loadAttachmentBuffer(attachment);
+ let buffer = await loadAttachmentBuffer(attachment);
if (!buffer) {
log('sendWechatAttachments: skipping attachment without resolvable bytes');
+ undelivered.push(attachment);
continue;
}
+
+ // Enforcement backstop for callers that reach this helper without the
+ // push path's budget pass (bot replies, queued payloads with no size):
+ // iLink accepts over-budget media with a 200 on every call and then
+ // never renders the message, so an unchecked upload is a silent loss.
+ const limit = attachment.type === 'image' ? budget.imageMaxBytes : budget.fileMaxBytes;
+ if (buffer.length > limit && attachment.type === 'image') {
+ const compressed = await compressImageToBudget(buffer, budget.imageMaxBytes);
+ if (compressed) buffer = compressed;
+ }
+ if (buffer.length > limit) {
+ if (attachment.fetchUrl) {
+ log(
+ 'sendWechatAttachments: "%s" (%d bytes) over %d-byte budget — sending link instead',
+ attachment.name ?? '(unnamed)',
+ buffer.length,
+ limit,
+ );
+ // Queued, not sent here: the send must sit OUTSIDE the per-attachment
+ // catch below. That catch exists so one bad upload cannot take down
+ // the rest, but a failing `sendMessage` means the text channel itself
+ // is down — swallowing it would let `deliver` resolve and the replay
+ // queue drop a payload that was never delivered.
+ fallbackLines.push(buildAttachmentFallbackLine(attachment, attachment.fetchUrl));
+ } else {
+ log('sendWechatAttachments: skipping over-budget attachment without fetchUrl');
+ undelivered.push(attachment);
+ }
+ continue;
+ }
+
const mediaType = mapAttachmentTypeToUploadMediaType(attachment.type);
const uploadResult = await api.uploadCdnMedia(toUserId, mediaType, buffer);
const cdnMedia = {
@@ -153,6 +204,15 @@ export const sendWechatAttachments = async (
attachment.name ?? '(unnamed)',
error,
);
+ undelivered.push(attachment);
}
}
+
+ // Deliberately outside the loop's try/catch — see the note above.
+ const linkMessages = splitFallbackMessages(fallbackLines, budget.textMaxChars);
+ for (const message of linkMessages) {
+ await api.sendMessage(toUserId, message, contextToken);
+ }
+
+ return undelivered;
};
diff --git a/apps/server/src/services/messenger/outbound.test.ts b/apps/server/src/services/messenger/outbound.test.ts
index 07d00bf4597..3f172082e2e 100644
--- a/apps/server/src/services/messenger/outbound.test.ts
+++ b/apps/server/src/services/messenger/outbound.test.ts
@@ -234,4 +234,67 @@ describe('sendOutboundDirectMessage', () => {
expect(mocks.postMessage).toHaveBeenCalledWith('U-slack', 'files');
});
});
+
+ describe('size budgets', () => {
+ const oversizedFile = {
+ fetchUrl: 'https://example.com/f/big.mp4',
+ name: 'big.mp4',
+ size: 100 * 1024 * 1024,
+ type: 'video' as const,
+ };
+
+ it('degrades an over-budget Telegram file to a download-link message', async () => {
+ await sendOutboundDirectMessage({
+ attachments: [oversizedFile],
+ content: 'see attached',
+ credentials: creds('telegram'),
+ platformUserId: '12345',
+ });
+
+ // No attachment survives the budget pass, so the sender is never called.
+ expect(mocks.sendTelegramAttachments).not.toHaveBeenCalled();
+ expect(mocks.sendTelegramMessage).toHaveBeenNthCalledWith(1, '12345', 'see attached');
+ expect(mocks.sendTelegramMessage).toHaveBeenNthCalledWith(
+ 2,
+ '12345',
+ expect.stringContaining('https://example.com/f/big.mp4'),
+ );
+ });
+
+ it('delivers a link-only message when an attachment-only push is over budget', async () => {
+ await sendOutboundDirectMessage({
+ attachments: [oversizedFile],
+ credentials: creds('telegram'),
+ platformUserId: '12345',
+ });
+
+ expect(mocks.sendTelegramMessage).toHaveBeenCalledTimes(1);
+ expect(mocks.sendTelegramMessage).toHaveBeenCalledWith(
+ '12345',
+ expect.stringContaining('big.mp4'),
+ );
+ });
+
+ it('sends Discord in-budget files and over-budget links in the same push', async () => {
+ const rawFiles = [{ name: 'report.pdf' }];
+ mocks.materializeAttachmentsForDiscord.mockResolvedValueOnce(rawFiles);
+ mocks.batchDiscordFiles.mockReturnValueOnce([rawFiles]);
+
+ await sendOutboundDirectMessage({
+ attachments: [fileAttachment, oversizedFile],
+ content: 'files',
+ credentials: creds('discord'),
+ platformUserId: 'U-discord',
+ });
+
+ // Only the in-budget attachment reaches the materializer.
+ expect(mocks.materializeAttachmentsForDiscord).toHaveBeenCalledWith([fileAttachment]);
+ expect(mocks.createMessage).toHaveBeenNthCalledWith(1, 'dm-channel-1', 'files', rawFiles);
+ expect(mocks.createMessage).toHaveBeenNthCalledWith(
+ 2,
+ 'dm-channel-1',
+ expect.stringContaining('https://example.com/f/big.mp4'),
+ );
+ });
+ });
});
diff --git a/apps/server/src/services/messenger/outbound.ts b/apps/server/src/services/messenger/outbound.ts
index cb1542464fb..20f0624f426 100644
--- a/apps/server/src/services/messenger/outbound.ts
+++ b/apps/server/src/services/messenger/outbound.ts
@@ -1,5 +1,10 @@
import debug from 'debug';
+import {
+ PLATFORM_ATTACHMENT_BUDGETS,
+ prepareAttachmentsForBudget,
+ splitFallbackMessages,
+} from '@/server/services/bot/platforms/attachmentBudget';
import { DiscordApi } from '@/server/services/bot/platforms/discord/api';
import {
batchDiscordFiles,
@@ -43,25 +48,58 @@ export const sendOutboundDirectMessage = async (params: {
const { attachments, content, credentials, platformUserId } = params;
const { botToken, platform } = credentials;
const text = content?.trim();
- const files = attachments?.length ? attachments : undefined;
- if (!text && !files) throw new Error('Outbound direct message requires content or attachments');
+ if (!text && !attachments?.length)
+ throw new Error('Outbound direct message requires content or attachments');
+
+ // Fit attachments to the platform's size budget first: over-budget images
+ // get recompressed; files that can't fit at all become download-link lines,
+ // delivered as separate follow-up text messages. Separate messages — never
+ // merged into the text leg — because Telegram truncates captions at 1024
+ // chars and Discord caps messages at 2000, and a truncated URL is a dead
+ // link. See attachmentBudget.ts for the budget rationale.
+ const budget =
+ platform in PLATFORM_ATTACHMENT_BUDGETS
+ ? PLATFORM_ATTACHMENT_BUDGETS[platform as keyof typeof PLATFORM_ATTACHMENT_BUDGETS]
+ : undefined;
+ const prepared =
+ attachments?.length && budget
+ ? await prepareAttachmentsForBudget(attachments, budget)
+ : { attachments: attachments ?? [], fallbackLines: [] };
+
+ // Every prepared attachment lands in exactly one of these two legs, so the
+ // guard above already covers "nothing to send". The link leg is batched to
+ // the platform's per-message character cap so a long list of fallbacks is
+ // never rejected or truncated mid-URL.
+ const linkMessages = budget
+ ? splitFallbackMessages(prepared.fallbackLines, budget.textMaxChars)
+ : [];
+ const files = prepared.attachments.length ? prepared.attachments : undefined;
- log('sending %s DM to %s (attachments=%d)', platform, platformUserId, files?.length ?? 0);
+ log(
+ 'sending %s DM to %s (attachments=%d, link-fallbacks=%d)',
+ platform,
+ platformUserId,
+ files?.length ?? 0,
+ prepared.fallbackLines.length,
+ );
switch (platform) {
case 'telegram': {
// A Telegram private chat id *is* the user id, so no DM to open.
const api = new TelegramApi(botToken);
+ let textDelivered = false;
if (files) {
// The first attachment carries the text as its caption; if every
// attachment fails, fall back to a plain message so the text leg
// still lands.
const delivered = await sendTelegramAttachments(api, platformUserId, files, text);
- if (delivered > 0) return;
- if (!text) throw new Error('All Telegram attachments failed to send');
+ textDelivered = delivered > 0;
+ if (delivered === 0 && !text && !linkMessages.length)
+ throw new Error('All Telegram attachments failed to send');
}
- await api.sendMessage(platformUserId, text!);
+ if (text && !textDelivered) await api.sendMessage(platformUserId, text);
+ for (const message of linkMessages) await api.sendMessage(platformUserId, message);
return;
}
case 'discord': {
@@ -69,6 +107,7 @@ export const sendOutboundDirectMessage = async (params: {
// existing channel when one is already open.
const api = new DiscordApi(botToken);
const channel = await api.createDMChannel(platformUserId);
+ let textDelivered = false;
if (files) {
const rawFiles = await materializeAttachmentsForDiscord(files);
if (rawFiles.length > 0) {
@@ -78,15 +117,18 @@ export const sendOutboundDirectMessage = async (params: {
for (const [index, batch] of batches.entries()) {
await api.createMessage(channel.id, index === 0 ? (text ?? '') : '', batch);
}
- return;
+ textDelivered = true;
+ } else if (!text && !linkMessages.length) {
+ throw new Error('All Discord attachments failed to materialize');
}
- if (!text) throw new Error('All Discord attachments failed to materialize');
}
- await api.createMessage(channel.id, text!);
+ if (text && !textDelivered) await api.createMessage(channel.id, text);
+ for (const message of linkMessages) await api.createMessage(channel.id, message);
return;
}
case 'slack': {
const api = new SlackApi(botToken);
+ let textDelivered = false;
if (files) {
// `files.completeUploadExternal` needs a real channel id (unlike
// `chat.postMessage`, which resolves a user id), so open the DM first.
@@ -96,11 +138,13 @@ export const sendOutboundDirectMessage = async (params: {
channelId: channel.id,
initialComment: text,
});
- if (uploaded > 0) return;
- if (!text) throw new Error('All Slack attachments failed to upload');
+ textDelivered = uploaded > 0;
+ if (uploaded === 0 && !text && !linkMessages.length)
+ throw new Error('All Slack attachments failed to upload');
}
// Slack resolves a user id passed as `channel` to that user's DM.
- await api.postMessage(platformUserId, text!);
+ if (text && !textDelivered) await api.postMessage(platformUserId, text);
+ for (const message of linkMessages) await api.postMessage(platformUserId, message);
return;
}
default: {
diff --git a/apps/server/src/services/messenger/wechatPush.test.ts b/apps/server/src/services/messenger/wechatPush.test.ts
index 27ae156d213..971b9708728 100644
--- a/apps/server/src/services/messenger/wechatPush.test.ts
+++ b/apps/server/src/services/messenger/wechatPush.test.ts
@@ -177,6 +177,33 @@ describe('sendProactiveWechatMessage', () => {
expect(mockSendMessage).toHaveBeenCalledWith(WECHAT_USER, 'hello', 'token-1');
});
+ it('degrades an over-budget attachment to a download-link message at deliver time', async () => {
+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');
+
+ const result = await sendProactiveWechatMessage({
+ attachments: [
+ {
+ fetchUrl: 'https://example.com/f/big.mp4',
+ name: 'big.mp4',
+ size: 100 * 1024 * 1024,
+ type: 'video',
+ },
+ ],
+ content: 'here is the video',
+ serverDB,
+ userId: LOBE_USER,
+ });
+
+ expect(result.status).toBe('sent');
+ expect(mockSendMessage).toHaveBeenNthCalledWith(1, WECHAT_USER, 'here is the video', 'token-1');
+ expect(mockSendMessage).toHaveBeenNthCalledWith(
+ 2,
+ WECHAT_USER,
+ expect.stringContaining('https://example.com/f/big.mp4'),
+ 'token-1',
+ );
+ });
+
it('delivers the displayed final send before queueing the next message', async () => {
await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');
await consumeSendCredits(redis, APP, WECHAT_USER, WECHAT_WINDOW_MAX_SENDS - 1);
@@ -237,6 +264,86 @@ describe('sendProactiveWechatMessage', () => {
expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(1);
});
+ it('requeues only the undelivered leg when the link follow-up fails', async () => {
+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');
+ // First call is the text leg (succeeds), second is the download-link
+ // follow-up for the over-budget attachment (fails).
+ mockSendMessage.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('iLink down'));
+
+ const result = await sendProactiveWechatMessage({
+ attachments: [
+ {
+ fetchUrl: 'https://example.com/f/big.mp4',
+ name: 'big.mp4',
+ size: 100 * 1024 * 1024,
+ type: 'video',
+ },
+ ],
+ content: 'here is the video',
+ serverDB,
+ userId: LOBE_USER,
+ });
+
+ expect(result).toEqual({ status: 'queued' });
+ const queued = redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))!;
+ expect(queued).toHaveLength(1);
+ // The text already arrived — replaying it would show it twice.
+ expect(JSON.parse(queued[0]).content).toBeUndefined();
+ expect(JSON.parse(queued[0]).attachments).toHaveLength(1);
+ });
+
+ it('requeues an attachment whose upload failed alongside the degraded one', async () => {
+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');
+ // Text lands; the in-budget upload fails inside sendWechatAttachments (the
+ // mocked client has no uploadCdnMedia) and is swallowed; the link
+ // follow-up then fails too.
+ mockSendMessage.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('iLink down'));
+
+ const result = await sendProactiveWechatMessage({
+ attachments: [
+ { data: Buffer.alloc(1024, 1).toString('base64'), name: 'small.png', type: 'image' },
+ {
+ fetchUrl: 'https://example.com/f/big.mp4',
+ name: 'big.mp4',
+ size: 100 * 1024 * 1024,
+ type: 'video',
+ },
+ ],
+ content: 'here you go',
+ serverDB,
+ userId: LOBE_USER,
+ });
+
+ expect(result).toEqual({ status: 'queued' });
+ const queued = JSON.parse(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))![0]);
+ expect(queued.content).toBeUndefined();
+ // Neither attachment reached the user, so both must survive the replay.
+ expect(queued.attachments.map((a: { name: string }) => a.name)).toEqual([
+ 'small.png',
+ 'big.mp4',
+ ]);
+ });
+
+ it('queues an upload failure for retry even when nothing else fails', async () => {
+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');
+ // Text lands; the upload fails inside sendWechatAttachments (the mocked
+ // client has no uploadCdnMedia) and there is no link leg at all.
+ const result = await sendProactiveWechatMessage({
+ attachments: [
+ { data: Buffer.alloc(1024, 1).toString('base64'), name: 'small.png', type: 'image' },
+ ],
+ content: 'here you go',
+ serverDB,
+ userId: LOBE_USER,
+ });
+
+ expect(result).toEqual({ status: 'queued' });
+ const queued = JSON.parse(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))![0]);
+ expect(queued.content).toBeUndefined();
+ expect(queued.attachments).toHaveLength(1);
+ expect(queued.attachments[0].name).toBe('small.png');
+ });
+
it('reports unlinked when the user has no WeChat account link', async () => {
mockFindByPlatform.mockResolvedValueOnce(undefined);
@@ -348,6 +455,33 @@ describe('flushPendingWechatPushes', () => {
expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(1);
});
+ it('replays a backlog of oversized attachments that collapse into one link message', async () => {
+ // 9 over-budget attachments would need 9 credits counted raw, so with a
+ // 10-credit window and 2 reserved for replies the item could never pass
+ // its own quota check and would sit queued until it expired. Degradation
+ // collapses them into a single download-link message — 1 credit.
+ await enqueuePendingPush(redis, APP, WECHAT_USER, {
+ attachments: Array.from({ length: 9 }, (_, index) => ({
+ fetchUrl: `https://example.com/f/big-${index}.mp4`,
+ name: `big-${index}.mp4`,
+ size: 100 * 1024 * 1024,
+ type: 'video' as const,
+ })),
+ enqueuedAt: 1,
+ });
+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-2');
+
+ const sent = await flushPendingWechatPushes({ ...flushParams, redis });
+
+ expect(sent).toBe(1);
+ expect(mockSendMessage).toHaveBeenCalledTimes(1);
+ expect(mockSendMessage.mock.calls[0][1]).toContain('big-8.mp4');
+ expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(0);
+ expect((await peekWindow(redis, APP, WECHAT_USER))?.remaining).toBe(
+ WECHAT_WINDOW_MAX_SENDS - 1,
+ );
+ });
+
it('does nothing when the window never reopened', async () => {
await enqueuePendingPush(redis, APP, WECHAT_USER, { content: 'first', enqueuedAt: 1 });
diff --git a/apps/server/src/services/messenger/wechatPush.ts b/apps/server/src/services/messenger/wechatPush.ts
index 88fe1259a35..3dc0b9881d4 100644
--- a/apps/server/src/services/messenger/wechatPush.ts
+++ b/apps/server/src/services/messenger/wechatPush.ts
@@ -1,10 +1,15 @@
-import { WechatApiClient } from '@lobechat/chat-adapter-wechat';
+import { getWechatTextSendCount, WechatApiClient } from '@lobechat/chat-adapter-wechat';
import debug from 'debug';
import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
import type { LobeChatDatabase } from '@/database/type';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import {
+ PLATFORM_ATTACHMENT_BUDGETS,
+ prepareAttachmentsForBudget,
+ splitFallbackMessages,
+} from '@/server/services/bot/platforms/attachmentBudget';
import type {
WechatPendingPush,
WechatWindowRedis,
@@ -14,7 +19,6 @@ import {
drainPendingPushes,
enqueuePendingPush,
peekWindow,
- pendingPushSendCount,
WECHAT_WINDOW_MAX_SENDS,
wechatPendingPushKey,
wechatWindowKey,
@@ -84,18 +88,122 @@ const resolveWechatTarget = async (
};
};
+/**
+ * A push resolved into the exact iLink calls it will take.
+ *
+ * The budget pass runs *before* window quota is reserved, not at send time:
+ * degradation collapses N over-budget attachments into one download-link
+ * message, so counting the raw attachments would reserve credits for sends
+ * that never happen — with a 10-credit window and 2 reserved for replies, a
+ * 9-attachment push would fail its own quota check on every replay and expire
+ * undelivered. It also keeps the Redis-queued payload carrying small URLs
+ * instead of megabytes of recompressed base64, since only the original payload
+ * is ever enqueued.
+ */
+interface PreparedWechatDelivery {
+ /** In-budget attachments, uploaded as media. */
+ attachments: WechatOutboundAttachment[];
+ content?: string;
+ /** Originals behind `linkMessages`, requeued when the link leg fails. */
+ degraded: WechatOutboundAttachment[];
+ /** Untouched originals of `attachments`, index-aligned — see PreparedAttachments. */
+ keptOriginals: WechatOutboundAttachment[];
+ /** Download-link follow-ups, batched to the platform's text limit. */
+ linkMessages: string[];
+}
+
+const prepareWechatDelivery = async (
+ payload: Pick<WechatPendingPush, 'attachments' | 'content'>,
+): Promise<PreparedWechatDelivery> => {
+ const budget = PLATFORM_ATTACHMENT_BUDGETS.wechat;
+ const prepared = payload.attachments?.length
+ ? await prepareAttachmentsForBudget(payload.attachments, budget)
+ : { attachments: [], degraded: [], fallbackLines: [], keptOriginals: [] };
+
+ return {
+ attachments: prepared.attachments,
+ content: payload.content?.trim() ? payload.content : undefined,
+ degraded: prepared.degraded,
+ keptOriginals: prepared.keptOriginals,
+ linkMessages: splitFallbackMessages(prepared.fallbackLines, budget.textMaxChars),
+ };
+};
+
+/** Window credits this delivery will actually consume. */
+const wechatDeliverySendCount = (prepared: PreparedWechatDelivery): number =>
+ Math.max(
+ 1,
+ (prepared.content ? getWechatTextSendCount(prepared.content) : 0) +
+ prepared.attachments.length +
+ prepared.linkMessages.length,
+ );
+
+/**
+ * Which legs of a push have already landed. A push is delivered in up to three
+ * calls (text, attachment uploads, download-link follow-ups) and any of them
+ * can fail after an earlier one succeeded — without this, requeueing the whole
+ * payload would re-send content the user already has on every replay.
+ */
+interface DeliveryProgress {
+ contentDelivered: boolean;
+ /**
+ * Attachments still owed. Starts as the whole input and narrows to just the
+ * degraded ones once the upload leg is done, so a failing link message never
+ * requeues an attachment that already arrived.
+ */
+ undeliveredAttachments?: WechatOutboundAttachment[];
+}
+
+/** The part of a payload still owed to the user after a failed `deliver`. */
+const undeliveredPayload = (
+ payload: WechatPendingPush,
+ progress: DeliveryProgress,
+): WechatPendingPush | undefined => {
+ const remaining = {
+ ...payload,
+ attachments: progress.undeliveredAttachments ?? payload.attachments,
+ content: progress.contentDelivered ? undefined : payload.content,
+ };
+ if (!remaining.content?.trim() && !remaining.attachments?.length) return undefined;
+ return remaining;
+};
+
const deliver = async (
api: WechatApiClient,
platformUserId: string,
token: string,
- payload: Pick<WechatPendingPush, 'attachments' | 'content'>,
+ prepared: PreparedWechatDelivery,
+ progress: DeliveryProgress,
): Promise<void> => {
- if (payload.content?.trim()) {
- await api.sendMessage(platformUserId, payload.content, token);
+ if (prepared.content) {
+ await api.sendMessage(platformUserId, prepared.content, token);
+ progress.contentDelivered = true;
}
- if (payload.attachments?.length) {
- await sendWechatAttachments(api, platformUserId, payload.attachments, token);
+ // Per-item upload failures are swallowed inside `sendWechatAttachments` by
+ // design, but it reports which attachments never landed. Map them back to
+ // the untouched originals so a failed recompressed image is requeued as its
+ // small source rather than megabytes of base64.
+ const failed = prepared.attachments.length
+ ? await sendWechatAttachments(api, platformUserId, prepared.attachments, token)
+ : [];
+ const failedOriginals = failed.map(
+ (attachment) => prepared.keptOriginals[prepared.attachments.indexOf(attachment)] ?? attachment,
+ );
+ // Degraded attachments are owed their link until the loop below sends it.
+ progress.undeliveredAttachments = [...failedOriginals, ...prepared.degraded];
+
+ for (const message of prepared.linkMessages) {
+ await api.sendMessage(platformUserId, message, token);
}
+ progress.undeliveredAttachments = failedOriginals;
+
+ // A reported upload failure is retried on the next inbound message rather
+ // than dropped — the same rule the link leg follows, so an attachment is
+ // never silently lost just because a *different* leg happened to succeed.
+ // Bounded by the queue's own 72h TTL and size cap, so a permanently
+ // unsendable attachment cannot retry forever.
+ if (failedOriginals.length > 0)
+ throw new Error(`${failedOriginals.length} WeChat attachment(s) failed to send`);
};
export interface WechatPushWindowStatus {
@@ -181,12 +289,22 @@ export const sendProactiveWechatMessage = async (params: {
}
const payload: WechatPendingPush = { attachments, content, enqueuedAt: Date.now() };
- const count = pendingPushSendCount(payload);
+
+ // Skip the budget pass entirely when the window is already closed: the queue
+ // stores the untouched payload and the replay prepares it again.
+ const window = await peekWindow(redis, target.applicationId, target.platformUserId);
+ if (!window || window.remaining <= 0) {
+ await enqueuePendingPush(redis, target.applicationId, target.platformUserId, payload);
+ log('sendProactiveWechatMessage: window closed for user %s — queued', target.platformUserId);
+ return { status: 'queued' };
+ }
+
+ const prepared = await prepareWechatDelivery(payload);
const credit = await consumeSendCredits(
redis,
target.applicationId,
target.platformUserId,
- count,
+ wechatDeliverySendCount(prepared),
);
if (credit.status !== 'ok') {
@@ -199,14 +317,17 @@ export const sendProactiveWechatMessage = async (params: {
return { status: 'queued' };
}
+ const progress: DeliveryProgress = { contentDelivered: false };
try {
- await deliver(target.api, target.platformUserId, credit.token, payload);
+ await deliver(target.api, target.platformUserId, credit.token, prepared, progress);
return { remaining: credit.remaining, status: 'sent' };
} catch (error) {
// The consumed credit is intentionally not refunded — a rejected send
// usually means the token is stale, so undercounting is the safe side.
log('sendProactiveWechatMessage: send failed, queueing for replay: %O', error);
- await enqueuePendingPush(redis, target.applicationId, target.platformUserId, payload);
+ const remaining = undeliveredPayload(payload, progress);
+ if (!remaining) return { remaining: credit.remaining, status: 'sent' };
+ await enqueuePendingPush(redis, target.applicationId, target.platformUserId, remaining);
return { status: 'queued' };
}
};
@@ -229,19 +350,29 @@ export const flushPendingWechatPushes = async (params: {
const api = new WechatApiClient(params.botToken, params.botId, params.baseUrl);
return drainPendingPushes(redis, applicationId, platformUserId, async (payload) => {
- const count = pendingPushSendCount(payload);
const sendWindow = await peekWindow(redis, applicationId, platformUserId);
- if (!sendWindow || sendWindow.remaining - count < RESERVED_REPLY_CREDITS) return 'stop';
+ if (!sendWindow || sendWindow.remaining <= RESERVED_REPLY_CREDITS) return 'stop';
+
+ // Prepare before the quota check: degradation collapses over-budget
+ // attachments into a single link message, and counting the raw payload
+ // would reserve credits for sends that never happen — enough to make a
+ // large backlog item fail its own check forever.
+ const prepared = await prepareWechatDelivery(payload);
+ const count = wechatDeliverySendCount(prepared);
+ if (sendWindow.remaining - count < RESERVED_REPLY_CREDITS) return 'stop';
const credit = await consumeSendCredits(redis, applicationId, platformUserId, count);
if (credit.status !== 'ok') return 'stop';
+ const progress: DeliveryProgress = { contentDelivered: false };
try {
- await deliver(api, platformUserId, credit.token, payload);
+ await deliver(api, platformUserId, credit.token, prepared, progress);
return 'sent';
} catch (error) {
log('flushPendingWechatPushes: replay failed for %s: %O', platformUserId, error);
- return 'stop';
+ // Requeue only the legs still owed — `undefined` means everything landed.
+ const remaining = undeliveredPayload(payload, progress);
+ return remaining ? { requeue: remaining } : 'sent';
}
});
};
diff --git a/locales/ar/messenger.json b/locales/ar/messenger.json
index 5a6eb19c4cc..b8008c448ae 100644
--- a/locales/ar/messenger.json
+++ b/locales/ar/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} رسالة (رسائل) في الانتظار سيتم تسليمها بعد أن ترسل رسالة إلى الروبوت في {{platform}}.",
"messenger.push.queuedToast": "نافذة الإرسال مغلقة — تم وضع رسالتك في الانتظار. أرسل رسالة إلى الروبوت في {{platform}} لاستلامها.",
"messenger.push.resource.description": "سيتم إرسال الملف كمرفق إلى حسابك المرتبط على {{platform}}.",
+ "messenger.push.resource.oversizeFileHint": "يتجاوز هذا الملف الحد الأقصى {{limit}} الخاص بـ {{platform}} وسيتم إرساله كرابط تنزيل.",
+ "messenger.push.resource.oversizeImageHint": "تتجاوز هذه الصورة الحد المسموح به {{limit}} على {{platform}}. سيتم ضغطها قبل الإرسال، أو سيتم إرسالها كرابط تحميل إذا لم تكن مناسبة.",
"messenger.push.resource.placeholder": "أضف رسالة (اختياري)…",
"messenger.push.retry": "حاول مرة أخرى",
"messenger.push.sectionTitle": "دفع الرسائل",
diff --git a/locales/bg-BG/messenger.json b/locales/bg-BG/messenger.json
index da229dd3081..d1e34aafab4 100644
--- a/locales/bg-BG/messenger.json
+++ b/locales/bg-BG/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} съобщение(я) в опашката ще бъдат доставени, след като изпратите съобщение до бота в {{platform}}.",
"messenger.push.queuedToast": "Прозорецът за изпращане е затворен — вашето съобщение е в опашката. Изпратете съобщение до бота в {{platform}}, за да го получите.",
"messenger.push.resource.description": "Файлът ще бъде изпратен като прикачен файл към свързания ви {{platform}} акаунт.",
+ "messenger.push.resource.oversizeFileHint": "Този файл надвишава лимита от {{limit}} на {{platform}} и ще бъде изпратен като линк за изтегляне.",
+ "messenger.push.resource.oversizeImageHint": "Това изображение надвишава лимита от {{limit}} на {{platform}}. То ще бъде компресирано преди изпращане или изпратено като линк за изтегляне, ако все още не се побира.",
"messenger.push.resource.placeholder": "Добавете съобщение (по избор)…",
"messenger.push.retry": "Опитайте отново",
"messenger.push.sectionTitle": "Изпращане на съобщения",
diff --git a/locales/de-DE/messenger.json b/locales/de-DE/messenger.json
index d56f3e8b62f..eaadb4e3e7e 100644
--- a/locales/de-DE/messenger.json
+++ b/locales/de-DE/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} Nachricht(en) in der Warteschlange werden zugestellt, nachdem Sie den Bot in {{platform}} kontaktiert haben.",
"messenger.push.queuedToast": "Das Sendezeitfenster ist geschlossen — Ihre Nachricht ist in der Warteschlange. Kontaktieren Sie den Bot in {{platform}}, um sie zu erhalten.",
"messenger.push.resource.description": "Die Datei wird als Anhang an Ihr verknüpftes {{platform}}-Konto gesendet.",
+ "messenger.push.resource.oversizeFileHint": "Diese Datei überschreitet das {{limit}}-Limit von {{platform}} und wird als Download-Link gesendet.",
+ "messenger.push.resource.oversizeImageHint": "Dieses Bild überschreitet das {{limit}}-Limit von {{platform}}. Es wird vor dem Senden komprimiert oder als Download-Link gesendet, falls es immer noch nicht passt.",
"messenger.push.resource.placeholder": "Fügen Sie eine Nachricht hinzu (optional)…",
"messenger.push.retry": "Erneut versuchen",
"messenger.push.sectionTitle": "Nachrichten-Push",
diff --git a/locales/en-US/messenger.json b/locales/en-US/messenger.json
index 461e004fcae..8688e6eb48d 100644
--- a/locales/en-US/messenger.json
+++ b/locales/en-US/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} queued message(s) will be delivered after you message the bot in {{platform}}.",
"messenger.push.queuedToast": "The send window is closed — your message is queued. Message the bot in {{platform}} to receive it.",
"messenger.push.resource.description": "The file will be sent as an attachment to your linked {{platform}} account.",
+ "messenger.push.resource.oversizeFileHint": "This file exceeds the {{limit}} limit of {{platform}} and will be sent as a download link.",
+ "messenger.push.resource.oversizeImageHint": "This image exceeds the {{limit}} limit of {{platform}}. It will be compressed before sending, or sent as a download link if it still does not fit.",
"messenger.push.resource.placeholder": "Add a message (optional)…",
"messenger.push.retry": "Try again",
"messenger.push.sectionTitle": "Message Push",
diff --git a/locales/es-ES/messenger.json b/locales/es-ES/messenger.json
index b766e19226f..046b1826047 100644
--- a/locales/es-ES/messenger.json
+++ b/locales/es-ES/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} mensaje(s) en cola se entregarán después de que envíes un mensaje al bot en {{platform}}.",
"messenger.push.queuedToast": "La ventana de envío está cerrada — tu mensaje está en cola. Envía un mensaje al bot en {{platform}} para recibirlo.",
"messenger.push.resource.description": "El archivo se enviará como un adjunto a tu cuenta vinculada de {{platform}}.",
+ "messenger.push.resource.oversizeFileHint": "Este archivo supera el límite de {{limit}} de {{platform}} y se enviará como un enlace de descarga.",
+ "messenger.push.resource.oversizeImageHint": "Esta imagen supera el límite de {{limit}} de {{platform}}. Se comprimirá antes de enviarla, o se enviará como un enlace de descarga si aún no cabe.",
"messenger.push.resource.placeholder": "Añade un mensaje (opcional)…",
"messenger.push.retry": "Intentar de nuevo",
"messenger.push.sectionTitle": "Envío de mensajes",
diff --git a/locales/fa-IR/messenger.json b/locales/fa-IR/messenger.json
index fbba07f7af7..7018fe77495 100644
--- a/locales/fa-IR/messenger.json
+++ b/locales/fa-IR/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} پیام در صف قرار دارد و پس از ارسال پیام شما به ربات در {{platform}} تحویل داده خواهد شد.",
"messenger.push.queuedToast": "پنجره ارسال بسته است — پیام شما در صف قرار گرفت. به ربات در {{platform}} پیام دهید تا آن را دریافت کنید.",
"messenger.push.resource.description": "فایل به‌عنوان پیوست به حساب مرتبط شما در {{platform}} ارسال خواهد شد.",
+ "messenger.push.resource.oversizeFileHint": "این فایل از حد {{limit}} در {{platform}} فراتر رفته و به صورت یک لینک دانلود ارسال خواهد شد.",
+ "messenger.push.resource.oversizeImageHint": "این تصویر از حد {{limit}} در {{platform}} فراتر رفته است. قبل از ارسال فشرده خواهد شد، یا اگر هنوز مناسب نباشد، به صورت لینک دانلود ارسال می‌شود.",
"messenger.push.resource.placeholder": "یک پیام اضافه کنید (اختیاری)…",
"messenger.push.retry": "دوباره تلاش کنید",
"messenger.push.sectionTitle": "ارسال پیام",
diff --git a/locales/fr-FR/messenger.json b/locales/fr-FR/messenger.json
index 8cecf24a707..4bba8c72b46 100644
--- a/locales/fr-FR/messenger.json
+++ b/locales/fr-FR/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} message(s) en file d'attente seront délivrés après que vous ayez envoyé un message au bot sur {{platform}}.",
"messenger.push.queuedToast": "La fenêtre d'envoi est fermée — votre message est en file d'attente. Envoyez un message au bot sur {{platform}} pour le recevoir.",
"messenger.push.resource.description": "Le fichier sera envoyé en tant que pièce jointe à votre compte {{platform}} lié.",
+ "messenger.push.resource.oversizeFileHint": "Ce fichier dépasse la limite de {{limit}} de {{platform}} et sera envoyé sous forme de lien de téléchargement.",
+ "messenger.push.resource.oversizeImageHint": "Cette image dépasse la limite de {{limit}} de {{platform}}. Elle sera compressée avant l'envoi, ou envoyée sous forme de lien de téléchargement si elle ne rentre toujours pas.",
"messenger.push.resource.placeholder": "Ajoutez un message (facultatif)…",
"messenger.push.retry": "Réessayer",
"messenger.push.sectionTitle": "Envoi de messages",
diff --git a/locales/it-IT/messenger.json b/locales/it-IT/messenger.json
index 5da85219901..fdf009d3ff9 100644
--- a/locales/it-IT/messenger.json
+++ b/locales/it-IT/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} messaggio/i in coda verrà/verranno consegnato/i dopo che avrai inviato un messaggio al bot su {{platform}}.",
"messenger.push.queuedToast": "La finestra di invio è chiusa — il tuo messaggio è in coda. Invia un messaggio al bot su {{platform}} per riceverlo.",
"messenger.push.resource.description": "Il file verrà inviato come allegato al tuo account {{platform}} collegato.",
+ "messenger.push.resource.oversizeFileHint": "Questo file supera il limite di {{limit}} di {{platform}} e verrà inviato come link per il download.",
+ "messenger.push.resource.oversizeImageHint": "Questa immagine supera il limite di {{limit}} di {{platform}}. Verrà compressa prima dell'invio o inviata come link per il download se non rientra ancora nei limiti.",
"messenger.push.resource.placeholder": "Aggiungi un messaggio (facoltativo)…",
"messenger.push.retry": "Riprova",
"messenger.push.sectionTitle": "Invio messaggi",
diff --git a/locales/ja-JP/messenger.json b/locales/ja-JP/messenger.json
index 11fde4deda7..d38e373aac6 100644
--- a/locales/ja-JP/messenger.json
+++ b/locales/ja-JP/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}}件のキューに入ったメッセージは、{{platform}}でボットにメッセージを送信した後に配信されます。",
"messenger.push.queuedToast": "送信ウィンドウが閉じています — メッセージはキューに入れられました。{{platform}}でボットにメッセージを送信すると受信できます。",
"messenger.push.resource.description": "ファイルはリンクされた{{platform}}アカウントに添付ファイルとして送信されます。",
+ "messenger.push.resource.oversizeFileHint": "このファイルは{{platform}}の{{limit}}制限を超えているため、ダウンロードリンクとして送信されます。",
+ "messenger.push.resource.oversizeImageHint": "この画像は{{platform}}の制限である{{limit}}を超えています。送信前に圧縮されますが、それでも収まらない場合はダウンロードリンクとして送信されます。",
"messenger.push.resource.placeholder": "メッセージを追加してください(任意)…",
"messenger.push.retry": "再試行",
"messenger.push.sectionTitle": "メッセージプッシュ",
diff --git a/locales/ko-KR/messenger.json b/locales/ko-KR/messenger.json
index 66ee6535d3f..a924d8446f1 100644
--- a/locales/ko-KR/messenger.json
+++ b/locales/ko-KR/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}}개의 대기 중인 메시지가 {{platform}}에서 봇에게 메시지를 보낸 후 전달됩니다.",
"messenger.push.queuedToast": "전송 창이 닫혔습니다 — 메시지가 대기 중입니다. {{platform}}에서 봇에게 메시지를 보내면 받을 수 있습니다.",
"messenger.push.resource.description": "파일은 연결된 {{platform}} 계정에 첨부 파일로 전송됩니다.",
+ "messenger.push.resource.oversizeFileHint": "{{platform}}의 제한인 {{limit}}을 초과하여 이 파일은 다운로드 링크로 전송됩니다.",
+ "messenger.push.resource.oversizeImageHint": "{{platform}}의 제한인 {{limit}}을 초과하는 이미지입니다. 전송 전에 압축되거나, 여전히 제한을 초과할 경우 다운로드 링크로 전송됩니다.",
"messenger.push.resource.placeholder": "메시지를 추가하세요 (선택 사항)…",
"messenger.push.retry": "다시 시도",
"messenger.push.sectionTitle": "메시지 푸시",
diff --git a/locales/nl-NL/messenger.json b/locales/nl-NL/messenger.json
index b5a13fbcd8f..ee4fb92ae5b 100644
--- a/locales/nl-NL/messenger.json
+++ b/locales/nl-NL/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} bericht(en) in de wachtrij worden afgeleverd nadat je de bot een bericht stuurt in {{platform}}.",
"messenger.push.queuedToast": "Het verzendvenster is gesloten — je bericht staat in de wachtrij. Stuur een bericht naar de bot in {{platform}} om het te ontvangen.",
"messenger.push.resource.description": "Het bestand wordt als bijlage verzonden naar je gekoppelde {{platform}} account.",
+ "messenger.push.resource.oversizeFileHint": "Dit bestand overschrijdt de {{limit}} limiet van {{platform}} en zal worden verzonden als een downloadlink.",
+ "messenger.push.resource.oversizeImageHint": "Deze afbeelding overschrijdt de {{limit}} limiet van {{platform}}. Het wordt gecomprimeerd voordat het wordt verzonden, of verzonden als een downloadlink als het nog steeds niet past.",
"messenger.push.resource.placeholder": "Voeg een bericht toe (optioneel)…",
"messenger.push.retry": "Opnieuw proberen",
"messenger.push.sectionTitle": "Bericht Push",
diff --git a/locales/pl-PL/messenger.json b/locales/pl-PL/messenger.json
index 69cdfee831c..5df3765d380 100644
--- a/locales/pl-PL/messenger.json
+++ b/locales/pl-PL/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} wiadomość(i) w kolejce zostanie dostarczona po wysłaniu wiadomości do bota na {{platform}}.",
"messenger.push.queuedToast": "Okno wysyłania jest zamknięte — Twoja wiadomość jest w kolejce. Wyślij wiadomość do bota na {{platform}}, aby ją otrzymać.",
"messenger.push.resource.description": "Plik zostanie wysłany jako załącznik do Twojego powiązanego konta {{platform}}.",
+ "messenger.push.resource.oversizeFileHint": "Ten plik przekracza limit {{limit}} dla {{platform}} i zostanie wysłany jako link do pobrania.",
+ "messenger.push.resource.oversizeImageHint": "Ten obraz przekracza limit {{limit}} dla {{platform}}. Zostanie skompresowany przed wysłaniem lub przesłany jako link do pobrania, jeśli nadal nie będzie pasował.",
"messenger.push.resource.placeholder": "Dodaj wiadomość (opcjonalnie)…",
"messenger.push.retry": "Spróbuj ponownie",
"messenger.push.sectionTitle": "Wysyłanie wiadomości",
diff --git a/locales/pt-BR/messenger.json b/locales/pt-BR/messenger.json
index 0010acfa913..7524762f6f0 100644
--- a/locales/pt-BR/messenger.json
+++ b/locales/pt-BR/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} mensagem(ns) na fila será(ão) entregue(s) após você enviar uma mensagem ao bot no {{platform}}.",
"messenger.push.queuedToast": "A janela de envio está fechada — sua mensagem está na fila. Envie uma mensagem ao bot no {{platform}} para recebê-la.",
"messenger.push.resource.description": "O arquivo será enviado como um anexo para sua conta vinculada no {{platform}}.",
+ "messenger.push.resource.oversizeFileHint": "Este arquivo excede o limite de {{limit}} do {{platform}} e será enviado como um link para download.",
+ "messenger.push.resource.oversizeImageHint": "Esta imagem excede o limite de {{limit}} do {{platform}}. Ela será comprimida antes de ser enviada ou enviada como um link de download caso ainda não se encaixe.",
"messenger.push.resource.placeholder": "Adicione uma mensagem (opcional)…",
"messenger.push.retry": "Tentar novamente",
"messenger.push.sectionTitle": "Envio de Mensagens",
diff --git a/locales/ru-RU/messenger.json b/locales/ru-RU/messenger.json
index 0d82be12c23..f7bb7314acc 100644
--- a/locales/ru-RU/messenger.json
+++ b/locales/ru-RU/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} сообщение(й) в очереди будет доставлено после того, как вы отправите сообщение боту в {{platform}}.",
"messenger.push.queuedToast": "Окно отправки закрыто — ваше сообщение добавлено в очередь. Отправьте сообщение боту в {{platform}}, чтобы получить его.",
"messenger.push.resource.description": "Файл будет отправлен в виде вложения на ваш связанный аккаунт {{platform}}.",
+ "messenger.push.resource.oversizeFileHint": "Этот файл превышает лимит {{limit}} на {{platform}} и будет отправлен в виде ссылки для скачивания.",
+ "messenger.push.resource.oversizeImageHint": "Это изображение превышает лимит {{limit}} для {{platform}}. Оно будет сжато перед отправкой или отправлено как ссылка для скачивания, если все еще не соответствует требованиям.",
"messenger.push.resource.placeholder": "Добавьте сообщение (необязательно)…",
"messenger.push.retry": "Попробовать снова",
"messenger.push.sectionTitle": "Отправка сообщений",
diff --git a/locales/tr-TR/messenger.json b/locales/tr-TR/messenger.json
index a9d2cbe10d9..a2c3f2a55ca 100644
--- a/locales/tr-TR/messenger.json
+++ b/locales/tr-TR/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} bekleyen mesaj, {{platform}}'da bota mesaj gönderdikten sonra teslim edilecek.",
"messenger.push.queuedToast": "Gönderim penceresi kapalı — mesajınız sıraya alındı. Mesajı almak için {{platform}}'da bota mesaj gönderin.",
"messenger.push.resource.description": "Dosya, bağlı {{platform}} hesabınıza ek olarak gönderilecektir.",
+ "messenger.push.resource.oversizeFileHint": "Bu dosya, {{platform}} platformunun {{limit}} sınırını aşıyor ve indirme bağlantısı olarak gönderilecektir.",
+ "messenger.push.resource.oversizeImageHint": "Bu resim {{platform}} için {{limit}} sınırını aşıyor. Gönderilmeden önce sıkıştırılacak veya hala sığmazsa indirme bağlantısı olarak gönderilecektir.",
"messenger.push.resource.placeholder": "Bir mesaj ekleyin (isteğe bağlı)…",
"messenger.push.retry": "Tekrar dene",
"messenger.push.sectionTitle": "Mesaj Gönderimi",
diff --git a/locales/vi-VN/messenger.json b/locales/vi-VN/messenger.json
index ff311c13e71..cc415cf728f 100644
--- a/locales/vi-VN/messenger.json
+++ b/locales/vi-VN/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} tin nhắn trong hàng đợi sẽ được gửi sau khi bạn nhắn tin cho bot trên {{platform}}.",
"messenger.push.queuedToast": "Cửa sổ gửi đã đóng — tin nhắn của bạn đang trong hàng đợi. Nhắn tin cho bot trên {{platform}} để nhận tin nhắn.",
"messenger.push.resource.description": "Tệp sẽ được gửi dưới dạng tệp đính kèm đến tài khoản {{platform}} được liên kết của bạn.",
+ "messenger.push.resource.oversizeFileHint": "Tệp này vượt quá giới hạn {{limit}} của {{platform}} và sẽ được gửi dưới dạng liên kết tải xuống.",
+ "messenger.push.resource.oversizeImageHint": "Hình ảnh này vượt quá giới hạn {{limit}} của {{platform}}. Nó sẽ được nén trước khi gửi, hoặc gửi dưới dạng liên kết tải xuống nếu vẫn không phù hợp.",
"messenger.push.resource.placeholder": "Thêm tin nhắn (tùy chọn)…",
"messenger.push.retry": "Thử lại",
"messenger.push.sectionTitle": "Đẩy tin nhắn",
diff --git a/locales/zh-CN/messenger.json b/locales/zh-CN/messenger.json
index e780f11e669..63a6ce5d1f3 100644
--- a/locales/zh-CN/messenger.json
+++ b/locales/zh-CN/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} 条消息排队中,你在 {{platform}} 中给机器人发送消息后将自动送达。",
"messenger.push.queuedToast": "发送窗口未打开,消息已排队。在 {{platform}} 中给机器人发送消息后即可收到。",
"messenger.push.resource.description": "文件将作为附件发送到你绑定的 {{platform}} 账号。",
+ "messenger.push.resource.oversizeFileHint": "文件超过 {{platform}} 的 {{limit}} 限制,将以下载链接形式发送。",
+ "messenger.push.resource.oversizeImageHint": "图片超过 {{platform}} 的 {{limit}} 限制,发送前将自动压缩;若压缩后仍超出限制,则以下载链接形式发送。",
"messenger.push.resource.placeholder": "附带一条消息(可选)…",
"messenger.push.retry": "重试",
"messenger.push.sectionTitle": "消息推送",
diff --git a/locales/zh-TW/messenger.json b/locales/zh-TW/messenger.json
index 5b8ca40856e..9a8b9f47d51 100644
--- a/locales/zh-TW/messenger.json
+++ b/locales/zh-TW/messenger.json
@@ -75,6 +75,8 @@
"messenger.push.queued": "{{count}} 則排隊中的訊息將在您於 {{platform}} 與機器人互動後送達。",
"messenger.push.queuedToast": "發送窗口已關閉 — 您的訊息已排隊。請在 {{platform}} 與機器人互動以接收訊息。",
"messenger.push.resource.description": "檔案將作為附件發送到您連結的 {{platform}} 帳戶。",
+ "messenger.push.resource.oversizeFileHint": "此檔案超過 {{platform}} 的 {{limit}} 限制,將以下載連結的形式發送。",
+ "messenger.push.resource.oversizeImageHint": "此圖片超過 {{platform}} 的 {{limit}} 限制。圖片將在發送前壓縮,若仍無法符合限制,將以下載連結的形式發送。",
"messenger.push.resource.placeholder": "新增訊息(選填)…",
"messenger.push.retry": "再試一次",
"messenger.push.sectionTitle": "訊息推送",
diff --git a/packages/const/src/bot.ts b/packages/const/src/bot.ts
index 05d867dde8a..caf8592ac00 100644
--- a/packages/const/src/bot.ts
+++ b/packages/const/src/bot.ts
@@ -16,3 +16,48 @@ export const MAX_BOT_HISTORY_LIMIT = 999;
/** Minimum number of messages allowed for history limit. */
export const MIN_BOT_HISTORY_LIMIT = 1;
+
+/**
+ * Per-platform attachment size budgets for the proactive messenger push path.
+ *
+ * Shared between the server (which enforces them: over-budget images are
+ * recompressed, files that cannot fit degrade to a download-link message —
+ * see apps/server/src/services/bot/platforms/attachmentBudget.ts) and the
+ * client (which uses them to warn the user in the push modal BEFORE sending).
+ *
+ * Values are deliberately conservative:
+ * - telegram: 5MB photo / 20MB file — Bot API caps for URL-sourced media.
+ * - discord: 10MB — default upload cap for bots (DMs never get guild boosts).
+ * - slack: 1GB — `files.upload` v2 cap; effectively unlimited here.
+ * - wechat: 2MB image — empirical: iLink silently drops larger images
+ * (every API call returns 200 yet the message never renders); 20MB file
+ * as a best-effort cap, the iLink protocol documents no explicit number.
+ *
+ * `textMaxChars` is the single-message character cap used to batch the
+ * download-link fallbacks: Discord rejects a message over 2000 chars,
+ * Telegram truncates at 4096 (which would cut a URL in half), Slack's
+ * practical `chat.postMessage` limit is ~3000, and iLink documents none —
+ * so WeChat reuses Discord's conservative number.
+ */
+export interface MessengerAttachmentBudget {
+ fileMaxBytes: number;
+ imageMaxBytes: number;
+ /**
+ * Character cap for a single outbound text message. Used to batch
+ * download-link fallbacks: a message over the cap is either rejected
+ * (Discord) or truncated mid-URL (Telegram), both of which lose the link.
+ */
+ textMaxChars: number;
+}
+
+const MB = 1024 * 1024;
+
+export const MESSENGER_ATTACHMENT_BUDGETS: Record<
+ 'discord' | 'slack' | 'telegram' | 'wechat',
+ MessengerAttachmentBudget
+> = {
+ discord: { fileMaxBytes: 10 * MB, imageMaxBytes: 10 * MB, textMaxChars: 2000 },
+ slack: { fileMaxBytes: 1024 * MB, imageMaxBytes: 1024 * MB, textMaxChars: 3000 },
+ telegram: { fileMaxBytes: 20 * MB, imageMaxBytes: 5 * MB, textMaxChars: 4096 },
+ wechat: { fileMaxBytes: 20 * MB, imageMaxBytes: 2 * MB, textMaxChars: 2000 },
+};
diff --git a/packages/locales/src/default/messenger.ts b/packages/locales/src/default/messenger.ts
index 0a00d800014..4783e7f1a48 100644
--- a/packages/locales/src/default/messenger.ts
+++ b/packages/locales/src/default/messenger.ts
@@ -138,6 +138,10 @@ export default {
'The send window is closed — your message is queued. Message the bot in {{platform}} to receive it.',
'messenger.push.resource.description':
'The file will be sent as an attachment to your linked {{platform}} account.',
+ 'messenger.push.resource.oversizeFileHint':
+ 'This file exceeds the {{limit}} limit of {{platform}} and will be sent as a download link.',
+ 'messenger.push.resource.oversizeImageHint':
+ 'This image exceeds the {{limit}} limit of {{platform}}. It will be compressed before sending, or sent as a download link if it still does not fit.',
'messenger.push.resource.placeholder': 'Add a message (optional)…',
'messenger.push.retry': 'Try again',
'messenger.push.sectionTitle': 'Message Push',
diff --git a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx b/src/features/Messenger/PushResourceModal/PushResourceContent.tsx
index 8659953ab82..57961567770 100644
--- a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx
+++ b/src/features/Messenger/PushResourceModal/PushResourceContent.tsx
@@ -1,5 +1,6 @@
'use client';
+import { MESSENGER_ATTACHMENT_BUDGETS } from '@lobechat/const';
import { Block, Flexbox, Input, Text } from '@lobehub/ui';
import { Alert, Button, ModalFooter, Select, toast, useModalContext } from '@lobehub/ui/base-ui';
import { memo, useState } from 'react';
@@ -9,6 +10,7 @@ import useSWR from 'swr';
import FileIcon from '@/components/FileIcon';
import { messengerKeys } from '@/libs/swr/keys';
import { messengerService } from '@/services/messenger';
+import { formatSize } from '@/utils/format';
import type { MessengerPlatform } from '../constants';
import { getMessengerErrorMessage } from '../i18n';
@@ -21,6 +23,12 @@ export interface PushResourceFile {
fileType?: string;
id: string;
name: string;
+ /**
+ * Byte size when the caller has it — drives the pre-send oversize hint
+ * (image → "will be compressed", file → "sent as a link"). When absent the
+ * hint is skipped; the server still applies the same budget on send.
+ */
+ size?: number;
}
export interface PushResourceTarget {
@@ -63,6 +71,24 @@ export const PushResourceContent = memo<PushResourceModalProps>(
const canPush = status?.deliverability === 'always' ? status.linked : !!status?.windowOpen;
+ // Pre-send oversize hint: with the file size and the platform budget both
+ // known here, tell the user up front whether the server will compress the
+ // image or degrade the file to a download link (mirrors attachmentBudget
+ // on the server). Size unknown → no hint; the result toast still reports
+ // what actually happened.
+ const attachmentType = resolveAttachmentType(file.name, file.fileType);
+ const budget = MESSENGER_ATTACHMENT_BUDGETS[platform];
+ const budgetLimit = attachmentType === 'image' ? budget.imageMaxBytes : budget.fileMaxBytes;
+ const oversizeHint =
+ file.size && file.size > budgetLimit
+ ? t(
+ attachmentType === 'image'
+ ? 'messenger.push.resource.oversizeImageHint'
+ : 'messenger.push.resource.oversizeFileHint',
+ { limit: formatSize(budgetLimit, 0), platform: platformName },
+ )
+ : undefined;
+
const handleSend = async () => {
if (sending || !canPush) return;
@@ -76,7 +102,7 @@ export const PushResourceContent = memo<PushResourceModalProps>(
attachments: [
{
fileId: file.id,
- type: resolveAttachmentType(file.name, file.fileType),
+ type: attachmentType,
},
],
content: content.trim() || undefined,
@@ -135,6 +161,8 @@ export const PushResourceContent = memo<PushResourceModalProps>(
</Flexbox>
</Block>
+ {oversizeHint && <Alert showIcon message={oversizeHint} type="info" />}
+
{targets && targets.length > 1 && (
<Flexbox gap={6}>
<Text style={{ fontSize: 12 }} type="secondary">
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index ef55dc938c7..52a9759656e 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -44,6 +44,8 @@ interface UseFileItemDropdownParams {
id: string;
libraryId?: string;
onRenameStart?: () => void;
+ /** Byte size when available — powers the push modal's oversize pre-warning. */
+ size?: number;
sourceType?: string;
url: string;
userId?: string | null;
@@ -65,6 +67,7 @@ export const useFileItemDropdown = ({
url,
filename,
fileType,
+ size,
sourceType,
onRenameStart,
userId,
@@ -123,7 +126,7 @@ export const useFileItemDropdown = ({
// "Send to chat platform" entry.
const sendToMessengerItem = useSendToMessengerMenuItem({
enabled: !isFolder && !isPage && !!url,
- file: { fileType, id, name: filename },
+ file: { fileType, id, name: filename, size },
});
const menuItems = useCallback(() => {
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index 1075e6ffc68..0dba9d7e10c 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -242,6 +242,7 @@ const FileListItem = ({
id,
libraryId: resourceManagerState.libraryId,
onRenameStart: isFolder ? handleRenameStart : undefined,
+ size,
sourceType,
url,
userId,
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 573eabb8e5b..004b6b308fc 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -392,6 +392,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
filename: name,
id,
libraryId: knowledgeBaseId,
+ size,
sourceType,
url,
userId,
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index dea3fea5612..e8e9f70c15f 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -114,6 +114,7 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
id: item.id,
libraryId,
onRenameStart: item.isFolder ? handleRenameStart : undefined,
+ size: item.size,
sourceType: item.sourceType,
url: item.url,
userId: item.userId,
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index 36fc0d30dd2..9fbddf8841c 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -20,6 +20,7 @@ export const toTreeItem = (item: {
id: string;
metadata?: Record<string, any> | null;
name: string;
+ size?: number | null;
slug?: string | null;
sourceType?: string;
url?: string;
@@ -31,6 +32,7 @@ export const toTreeItem = (item: {
isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,
metadata: item.metadata ?? undefined,
name: item.name,
+ size: item.size ?? undefined,
slug: item.slug,
sourceType: item.sourceType,
url: item.url ?? '',
diff --git a/src/store/tree/store.ts b/src/store/tree/store.ts
index 15bd1116368..3825de47d3c 100644
--- a/src/store/tree/store.ts
+++ b/src/store/tree/store.ts
@@ -42,6 +42,7 @@ useFileStore.subscribe((state) => {
id: item.id,
metadata: item.metadata,
name: item.name,
+ size: item.size,
slug: item.slug,
sourceType: item.sourceType,
url: item.url,
diff --git a/src/store/tree/types.ts b/src/store/tree/types.ts
index 8a7cf9c785b..57e9140b920 100644
--- a/src/store/tree/types.ts
+++ b/src/store/tree/types.ts
@@ -6,6 +6,8 @@ export interface TreeItem {
isFolder: boolean;
metadata?: Record<string, any>;
name: string;
+ /** Byte size for file nodes — drives the push modal's oversize pre-warning. */
+ size?: number;
slug?: string | null;
sourceType?: string;
url: string;