🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(messenger): make pushed attachments actually reach Telegram and WeChat (#18561)
Rdmclin2388773ab53d5
diff --git a/apps/server/src/routers/lambda/__tests__/messenger.test.ts b/apps/server/src/routers/lambda/__tests__/messenger.test.tsindex fe9ea281c17..c014798af63 100644--- a/apps/server/src/routers/lambda/__tests__/messenger.test.ts+++ b/apps/server/src/routers/lambda/__tests__/messenger.test.ts@@ -920,6 +920,9 @@ describe('messengerRouter.sendMessengerPush', () => {mimeType: 'application/pdf',name: 'report.pdf',size: 123_456,+ // Server-generated from a row this caller owns, which is what lets+ // the outbound guard accept our own private origins for it.+ trustedUrl: true,type: 'file',},],diff --git a/apps/server/src/routers/lambda/botMessage.ts b/apps/server/src/routers/lambda/botMessage.tsindex 058b149fd49..3274c1dda71 100644--- a/apps/server/src/routers/lambda/botMessage.ts+++ b/apps/server/src/routers/lambda/botMessage.ts@@ -56,15 +56,20 @@ const botMessageWriteProcedure = botMessageProcedure.use(withScopedPermission('m* three procedures stay in lockstep — the platform-specific helpers* downstream only see one shape.*/-const attachmentsInputSchema = z.array(- z.object({- data: z.string().optional(),- fetchUrl: z.string().url().optional(),- mimeType: z.string().optional(),- name: z.string().optional(),- type: z.enum(['image', 'file', 'video', 'audio']),- }),-);+const attachmentsInputSchema = z+ .array(+ z.object({+ data: z.string().optional(),+ fetchUrl: z.string().url().optional(),+ mimeType: z.string().optional(),+ name: z.string().optional(),+ type: z.enum(['image', 'file', 'video', 'audio']),+ }),+ )+ // Bounded like the push path: an unmeasured `fetchUrl` costs a size probe+ // before anything is sent, so an unbounded array is unbounded latency inside+ // one serverless request.+ .max(10);// ── Service Factory ──────────────────────────────────────diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.tsindex b2622336002..96fb1c7aba9 100644--- a/apps/server/src/routers/lambda/messenger.ts+++ b/apps/server/src/routers/lambda/messenger.ts@@ -897,6 +897,10 @@ export const messengerRouter = router({return {fetchUrl: await fileService.getFileAccessUrl({ id: file.id, url: file.url }),+ // Built here from a row this caller was checked to own, so the+ // outbound guard may accept our own configured origins for it —+ // which self-hosted storage and dev (localhost storage URL) need.+ trustedUrl: true,mimeType: file.fileType,name: file.name,// Byte size from the owned row — the send path uses it to applydiff --git a/apps/server/src/services/bot/platforms/attachmentBudget.test.ts b/apps/server/src/services/bot/platforms/attachmentBudget.test.tsindex cef56a6bac4..734915958fc 100644--- a/apps/server/src/services/bot/platforms/attachmentBudget.test.ts+++ b/apps/server/src/services/bot/platforms/attachmentBudget.test.ts@@ -1,6 +1,16 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('./publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const sharpMocks = vi.hoisted(() => ({metadata: vi.fn(),toBuffer: vi.fn(),@@ -91,12 +101,100 @@ describe('prepareAttachmentsForBudget', () => {expect(result.fallbackLines).toEqual([]);});- it('passes attachments with unknown size through untouched', async () => {+ it('probes an unmeasured attachment and keeps it when it fits', async () => {+ // `attachmentsInputSchema` carries no `size`, so raw botMessage attachments+ // arrive unmeasured — the budget has to establish the size itself.+ const attachment = {+ fetchUrl: 'https://example.com/f/small.mp4',+ name: 'small.mp4',+ type: 'video' as const,+ };+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ headers: new Headers({ 'content-length': String(1 * MB) }),+ ok: true,+ status: 200,+ }),+ );++ const result = await prepareAttachmentsForBudget([attachment], budget);++ expect(result.attachments).toEqual([attachment]);+ expect(result.fallbackLines).toEqual([]);+ });++ it('degrades an unmeasured attachment the probe reports as over budget', async () => {const attachment = {- fetchUrl: 'https://example.com/f/unknown.mp4',- name: 'unknown.mp4',+ fetchUrl: 'https://example.com/f/huge.mp4',+ name: 'huge.mp4',type: 'video' as const,};+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ headers: new Headers({ 'content-length': String(500 * MB) }),+ ok: true,+ status: 200,+ }),+ );++ const result = await prepareAttachmentsForBudget([attachment], budget);++ expect(result.attachments).toEqual([]);+ expect(result.fallbackLines[0]).toContain('https://example.com/f/huge.mp4');+ });++ it('degrades rather than silently dropping when the size cannot be established', async () => {+ // Regression: an unmeasurable attachment used to skip every budget rule and+ // then be refused by the loader's in-memory cap during materialization —+ // the sender skipped it, still posted the text, and reported success, so it+ // vanished with neither file nor link.+ const attachment = {+ fetchUrl: 'https://example.com/f/chunked.mp4',+ name: 'chunked.mp4',+ type: 'video' as const,+ };+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({ headers: new Headers(), ok: true, status: 200 }),+ );++ const result = await prepareAttachmentsForBudget([attachment], budget);++ expect(result.attachments).toEqual([]);+ expect(result.fallbackLines[0]).toContain('https://example.com/f/chunked.mp4');+ });++ it('probes unmeasured attachments concurrently, not one after another', async () => {+ // Regression: serial probing meant N slow URLs cost N x the timeout before+ // the first platform send even began.+ let inFlight = 0;+ let peak = 0;+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockImplementation(async () => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 20));+ inFlight -= 1;+ return { headers: new Headers({ 'content-length': String(1024) }), ok: true, status: 200 };+ }),+ );++ const attachments = Array.from({ length: 5 }, (_, i) => ({+ fetchUrl: `https://example.com/f/file-${i}.mp4`,+ name: `file-${i}.mp4`,+ type: 'video' as const,+ }));++ await prepareAttachmentsForBudget(attachments, budget);++ expect(peak).toBeGreaterThan(1);+ });++ it('keeps an unmeasurable attachment that has no link to fall back to', async () => {+ const attachment = { data: 'AAAA', name: 'inline.bin', type: 'file' as const };const result = await prepareAttachmentsForBudget([attachment], budget);@@ -206,6 +304,30 @@ describe('prepareAttachmentsForBudget', () => {expect(result.fallbackLines[0]).toContain('https://example.com/f/movie.mp4');});+ it('degrades a Slack file above the in-memory ceiling instead of dropping it', async () => {+ // Regression: Slack's budget used to be the API's 1GB cap, so a 60MB file+ // passed the budget pass as an upload and was then refused during+ // materialization — the attachment vanished with neither file nor link.+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ const result = await prepareAttachmentsForBudget(+ [+ {+ fetchUrl: 'https://example.com/f/big.zip',+ name: 'big.zip',+ size: 60 * MB,+ type: 'file' as const,+ },+ ],+ PLATFORM_ATTACHMENT_BUDGETS.slack,+ );++ expect(fetchMock).not.toHaveBeenCalled();+ expect(result.attachments).toEqual([]);+ expect(result.fallbackLines[0]).toContain('https://example.com/f/big.zip');+ });+it('keeps an over-budget attachment without a fetchUrl as a last resort', async () => {const attachment = {data: Buffer.alloc(30 * MB).toString('base64'),diff --git a/apps/server/src/services/bot/platforms/attachmentBudget.ts b/apps/server/src/services/bot/platforms/attachmentBudget.tsindex 33e22c1cab9..00c23d5bb88 100644--- a/apps/server/src/services/bot/platforms/attachmentBudget.ts+++ b/apps/server/src/services/bot/platforms/attachmentBudget.ts@@ -2,6 +2,8 @@ import type { MessengerAttachmentBudget } from '@lobechat/const';import { MESSENGER_ATTACHMENT_BUDGETS } from '@lobechat/const';import debug from 'debug';+import { loadAttachmentBuffer } from './loadAttachmentBuffer';+import { fetchPublicUrl } from './publicUrlFetch';import type { BotMessageAttachment } from './types';const log = debug('bot-platform:attachment-budget');@@ -92,33 +94,15 @@ const toJpegFilename = (name: string | undefined): string | undefined => {return `${trimmed.replace(/\.[^./\\]*$/, '')}.jpg`;};-/** Refuse to buffer arbitrarily large remote files into memory for compression. */+/**+ * Refuse to buffer arbitrarily large remote files into memory for compression.+ * Enforced as the response streams in, so an image with an absent or lying+ * `content-length` cannot be fully allocated before it is rejected.+ */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;-};+const loadSourceBuffer = async (attachment: BotMessageAttachment): Promise<Buffer | undefined> =>+ loadAttachmentBuffer(attachment, { limit: MAX_COMPRESSION_SOURCE_BYTES });/*** Ladder of (max dimension, JPEG quality) attempts, largest/best first. The@@ -207,6 +191,47 @@ const knownSize = (attachment: BotMessageAttachment): number | undefined => {* `fallbackLines` when a `fetchUrl` exists. Without a URL the original* attachment is kept as a last resort (old behavior) rather than dropped.*/+/** How long to wait for a size probe before giving up on it. */+const SIZE_PROBE_TIMEOUT_MS = 5000;++/**+ * The attachment's byte size, established without downloading it.+ *+ * `attachmentsInputSchema` carries no `size`, so raw `botMessage` attachments+ * arrive unmeasured — and an unmeasured attachment used to skip every budget+ * rule, only to be refused later by the loader's in-memory cap and dropped+ * without a trace. Inline base64 is measured directly; a remote URL is probed+ * with a HEAD request through the same SSRF guard the download uses.+ */+const resolveSize = async (attachment: BotMessageAttachment): Promise<number | undefined> => {+ const declared = knownSize(attachment);+ if (declared !== undefined) return declared;++ if (attachment.data) return Buffer.byteLength(attachment.data, 'base64');+ if (!attachment.fetchUrl) return undefined;++ const probed = await fetchPublicUrl(attachment.fetchUrl, SIZE_PROBE_TIMEOUT_MS, {+ allowConfiguredOrigins: attachment.trustedUrl === true,+ method: 'HEAD',+ }).catch(() => undefined);+ if (!probed) return undefined;++ try {+ // A 404's `content-length` describes the error page, not the file.+ if (!probed.response.ok) return undefined;++ // Absent header must stay "unknown": `Number(null)` is 0, which would read+ // as a zero-byte file that fits every budget.+ const header = probed.response.headers.get('content-length');+ if (header === null) return undefined;++ const length = Number(header);+ return Number.isFinite(length) && length >= 0 ? length : undefined;+ } finally {+ await probed.dispose();+ }+};+export const prepareAttachmentsForBudget = async (attachments: BotMessageAttachment[],budget: PlatformAttachmentBudget,@@ -216,16 +241,38 @@ export const prepareAttachmentsForBudget = async (const degraded: BotMessageAttachment[] = [];const fallbackLines: string[] = [];- for (const attachment of attachments) {+ // Probe every unmeasured attachment at once rather than once per loop turn:+ // serially, N slow URLs cost N x the probe timeout before the first send.+ const sizes = await Promise.all(attachments.map((attachment) => resolveSize(attachment)));++ for (const [index, attachment] of attachments.entries()) {const limit = attachment.type === 'image' ? budget.imageMaxBytes : budget.fileMaxBytes;- const size = knownSize(attachment);+ const size = sizes[index];- if (size === undefined || size <= limit) {+ if (size !== undefined && size <= limit) {kept.push(attachment);keptOriginals.push(attachment);continue;}+ // Size still unknown after the probe: the server declared no length, so we+ // cannot promise the bytes fit. Uploading anyway is the silent-loss case —+ // the loader's in-memory cap would refuse it during materialization and the+ // sender would skip it, delivering neither file nor link. Degrade instead;+ // an attachment with no link to fall back to is kept as a last resort+ // below.+ if (size === undefined) {+ if (!attachment.fetchUrl) {+ kept.push(attachment);+ keptOriginals.push(attachment);+ continue;+ }+ log('prepareAttachmentsForBudget: unverifiable size for %s, degrading', attachment.name);+ degraded.push(attachment);+ fallbackLines.push(buildAttachmentFallbackLine(attachment, attachment.fetchUrl));+ 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.diff --git a/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/discord/sendAttachments.test.tsindex 488928974d5..066e13857b4 100644--- a/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts@@ -7,6 +7,16 @@ import {materializeAttachmentsForDiscord,} from './sendAttachments';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+describe('materializeAttachmentsForDiscord', () => {beforeEach(() => {vi.stubGlobal('fetch', vi.fn());diff --git a/apps/server/src/services/bot/platforms/discord/sendAttachments.ts b/apps/server/src/services/bot/platforms/discord/sendAttachments.tsindex c46dbef507e..e211e43598b 100644--- a/apps/server/src/services/bot/platforms/discord/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/discord/sendAttachments.ts@@ -1,6 +1,7 @@import type { RawFile } from '@discordjs/rest';import debug from 'debug';+import { loadAttachmentBuffer } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';const log = debug('bot-platform:discord:send-attachments');@@ -13,37 +14,6 @@ const log = debug('bot-platform:discord:send-attachments');*/export const DISCORD_MAX_ATTACHMENTS_PER_MESSAGE = 10;-/**- * Materialize an attachment's bytes from `data` (base64) or `fetchUrl` (HTTP- * GET, 15s timeout). Returns undefined if neither source resolves so the- * caller can skip the failing item without aborting the whole batch.- */-const loadAttachmentBuffer = async (- attachment: BotMessageAttachment,-): Promise<Buffer | undefined> => {- if (attachment.data) {- try {- return Buffer.from(attachment.data, 'base64');- } catch (error) {- log('loadAttachmentBuffer: failed to decode base64: %O', error);- }- }- if (attachment.fetchUrl) {- try {- const response = await fetch(attachment.fetchUrl, {- signal: AbortSignal.timeout(15_000),- });- if (response.ok) {- return Buffer.from(await response.arrayBuffer());- }- log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);- } catch (error) {- log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);- }- }- return undefined;-};-/*** Pick a filename for the Discord upload. Falls back to a generic name with* the appropriate extension inferred from `mimeType` so Discord's previewdiff --git a/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.tsindex 50d09078122..413a69ab507 100644--- a/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts@@ -3,6 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { sendFeishuAttachments } from './sendAttachments';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const makeApi = () => ({sendMessageWithMsgType: vi.fn().mockResolvedValue({ messageId: 'm-1', raw: {} }),uploadFile: vi.fn().mockResolvedValue({ file_key: 'file_xyz' }),diff --git a/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts b/apps/server/src/services/bot/platforms/feishu/sendAttachments.tsindex 5c83824be34..727c8353921 100644--- a/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts@@ -1,6 +1,7 @@import type { LarkApiClient } from '@lobechat/chat-adapter-feishu';import debug from 'debug';+import { loadAttachmentBuffer } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';const log = debug('bot-platform:feishu:send-attachments');@@ -42,32 +43,6 @@ const fallbackFilename = (att: BotMessageAttachment, index: number): string => {return `attachment-${index + 1}`;};-const loadAttachmentBuffer = async (- attachment: BotMessageAttachment,-): Promise<Buffer | undefined> => {- if (attachment.data) {- try {- return Buffer.from(attachment.data, 'base64');- } catch (error) {- log('loadAttachmentBuffer: failed to decode base64: %O', error);- }- }- if (attachment.fetchUrl) {- try {- const response = await fetch(attachment.fetchUrl, {- signal: AbortSignal.timeout(15_000),- });- if (response.ok) {- return Buffer.from(await response.arrayBuffer());- }- log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);- } catch (error) {- log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);- }- }- return undefined;-};-/*** Upload + send each attachment as its own Lark/Feishu message:*diff --git a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.ts b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.tsnew file mode 100644index 00000000000..8e1398b8b5f--- /dev/null+++ b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { fetchCappedBuffer, loadAttachmentBuffer } from './loadAttachmentBuffer';++// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('./publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));++const streamOf = (chunks: Uint8Array[], cancel = vi.fn()) => {+ let i = 0;+ return {+ getReader: () => ({+ cancel,+ read: async () =>+ i < chunks.length ? { done: false, value: chunks[i++] } : { done: true, value: undefined },+ }),+ };+};++const responseOf = (chunks: Uint8Array[], headers: Record<string, string> = {}, cancel?: any) =>+ ({ body: streamOf(chunks, cancel), headers: new Headers(headers), ok: true, status: 200 }) as any;++describe('fetchCappedBuffer', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('returns the body when it fits the cap', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(responseOf([new Uint8Array([1, 2, 3])])));++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toEqual(Buffer.from([1, 2, 3]));+ });++ it('reassembles multi-chunk bodies in order', async () => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValue(+ responseOf([new Uint8Array([1, 2]), new Uint8Array([3]), new Uint8Array([4, 5])]),+ ),+ );++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toEqual(+ Buffer.from([1, 2, 3, 4, 5]),+ );+ });++ it('grows past its initial capacity without corrupting the bytes', async () => {+ // No content-length, so the read starts small and has to grow repeatedly.+ const chunks = Array.from({ length: 40 }, (_, i) => new Uint8Array(4096).fill(i));+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(responseOf(chunks)));++ const buffer = await fetchCappedBuffer('https://x/f', { limit: 10 * 1024 * 1024 });++ expect(buffer).toHaveLength(40 * 4096);+ expect(buffer!.subarray(0, 4096).every((b) => b === 0)).toBe(true);+ expect(buffer!.subarray(39 * 4096).every((b) => b === 39)).toBe(true);+ });++ it('rejects on content-length without reading the body at all', async () => {+ const getReader = vi.fn();+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ body: { getReader },+ headers: new Headers({ 'content-length': '999' }),+ ok: true,+ status: 200,+ }),+ );++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toBeUndefined();+ expect(getReader).not.toHaveBeenCalled();+ });++ it('cancels the transfer when a size-less body streams past the cap', async () => {+ const cancel = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(responseOf([new Uint8Array(80), new Uint8Array(80)], {}, cancel)),+ );++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toBeUndefined();+ expect(cancel).toHaveBeenCalled();+ });++ it('returns undefined on a non-OK response', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }));++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toBeUndefined();+ });++ it('returns undefined instead of throwing when the fetch fails', async () => {+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('boom')));++ expect(await fetchCappedBuffer('https://x/f', { limit: 100 })).toBeUndefined();+ });+});++describe('loadAttachmentBuffer', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('prefers inline base64 over a round-trip', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ const buffer = await loadAttachmentBuffer(+ { data: Buffer.from('hi').toString('base64'), fetchUrl: 'https://x/f' },+ { limit: 100 },+ );++ expect(buffer).toEqual(Buffer.from('hi'));+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('applies the same cap to inline base64, without falling back to the URL', async () => {+ // The inline copy IS the attachment — re-fetching it would be just as big.+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ const buffer = await loadAttachmentBuffer(+ { data: Buffer.alloc(200).toString('base64'), fetchUrl: 'https://x/f' },+ { limit: 100 },+ );++ expect(buffer).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('falls back to fetchUrl when there is no inline data', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(responseOf([new Uint8Array([7])])));++ expect(await loadAttachmentBuffer({ fetchUrl: 'https://x/f' }, { limit: 100 })).toEqual(+ Buffer.from([7]),+ );+ });++ it('returns undefined when the attachment carries no source', async () => {+ expect(await loadAttachmentBuffer({}, { limit: 100 })).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.ts b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.tsnew file mode 100644index 00000000000..f0d83294e2c--- /dev/null+++ b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.ts@@ -0,0 +1,208 @@+import debug from 'debug';++import { fetchPublicUrl } from './publicUrlFetch';++const log = debug('bot-platform:load-attachment');++const MB = 1024 * 1024;++/**+ * Hard ceiling on how many bytes of ONE attachment may be held in memory.+ *+ * This is a worker-memory guard, not a platform policy cap.+ *+ * On the PUSH path, per-platform limits are applied upstream by+ * `prepareAttachmentsForBudget`, which degrades anything over budget to a+ * download link before the bytes are ever fetched — so this cap should never+ * be the thing that stops a push.+ *+ * The agent-facing `botMessage` procedures do NOT go through that pass: the+ * router hands raw attachments straight to the platform services. There, an+ * oversized body is refused here and the sender skips the attachment, which+ * means it is dropped without a fallback link. That gap is tracked separately+ * (see LOBE-13364) — routing those sends through the budget pass is a change+ * to the agent tool contract, not something to bolt on inside this loader.+ */+export const MAX_IN_MEMORY_ATTACHMENT_BYTES = 50 * MB;++/** Default budget for materializing one attachment into memory. */+const DEFAULT_DOWNLOAD_TIMEOUT_MS = 15_000;++export interface LoadAttachmentOptions {+ /**+ * Accept our own configured origins without the private-address check. Set+ * only for URLs the server produced from an owned record.+ */+ allowConfiguredOrigins?: boolean;+ /**+ * Hard byte cap. The transfer is aborted the moment it is crossed, so the+ * cap holds without trusting the caller's declared size.+ */+ limit?: number;+ timeoutMs?: number;+}++/** The subset of every outbound attachment shape this module needs. */+interface LoadableAttachment {+ data?: string;+ fetchUrl?: string;+ /** Server-generated from an owned record — see `BotMessageAttachment`. */+ trustedUrl?: boolean;+}++/** Starting capacity when the response declares no usable `content-length`. */+const INITIAL_CAPACITY_BYTES = 64 * 1024;++/**+ * Read a response body into a Buffer, stopping the moment `limit` is crossed.+ *+ * `response.arrayBuffer()` materializes the WHOLE body first, so checking the+ * length afterwards is too late — the allocation that would kill the worker has+ * already happened. Reading through the stream lets us abort the transfer+ * instead of merely rejecting the result.+ *+ * Bytes are copied into ONE growing buffer rather than collected as chunks and+ * `Buffer.concat`-ed at the end: concat holds the chunk list and the combined+ * result alive simultaneously, so a download near the cap would peak at roughly+ * twice it — undermining the very ceiling this module exists to enforce. With a+ * usable `content-length` the buffer is sized exactly once and never grows.+ */+const readCappedBody = async (+ response: Response,+ limit: number,+ declaredLength?: number,+): Promise<Buffer | undefined> => {+ if (!response.body) return undefined;++ const reader = response.body.getReader();+ const initial =+ declaredLength && declaredLength > 0 ? Math.min(declaredLength, limit) : INITIAL_CAPACITY_BYTES;++ let buffer = Buffer.allocUnsafe(Math.min(initial, limit));+ let total = 0;++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ if (total + value.byteLength > limit) {+ // Cancel so the remaining bytes are never pulled over the wire.+ await reader.cancel();+ return undefined;+ }++ if (total + value.byteLength > buffer.length) {+ const grown = Buffer.allocUnsafe(+ Math.min(limit, Math.max(buffer.length * 2, total + value.byteLength)),+ );+ buffer.copy(grown, 0, 0, total);+ buffer = grown;+ }++ buffer.set(value, total);+ total += value.byteLength;+ }+ } catch (error) {+ log('readCappedBody: stream failed after %d bytes: %O', total, error);+ return undefined;+ }++ // A view, not a copy — the backing allocation is already capped at `limit`.+ return buffer.subarray(0, total);+};++/**+ * Download a URL into memory, refusing anything past `limit` bytes. Returns+ * `undefined` on any failure so callers can skip one item without aborting the+ * whole batch.+ */+export const fetchCappedBuffer = async (+ url: string,+ {+ allowConfiguredOrigins = false,+ limit = MAX_IN_MEMORY_ATTACHMENT_BYTES,+ timeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS,+ }: LoadAttachmentOptions = {},+): Promise<Buffer | undefined> => {+ try {+ // Caller-supplied URLs reach here (see `botMessage`'s `fetchUrl` input), so+ // the fetch must refuse anything pointing inside the network.+ const fetched = await fetchPublicUrl(url, timeoutMs, { allowConfiguredOrigins });+ if (!fetched) return undefined;++ const { response } = fetched;+ try {+ if (!response.ok) {+ log('fetchCappedBuffer: HTTP %d for %s', response.status, url);+ return undefined;+ }++ // Reject on the advertised size before a single byte is buffered. The+ // header is absent often enough (and wrong often enough) that the+ // streaming cap below still has to hold on its own.+ const declared = Number(response.headers.get('content-length'));+ if (Number.isFinite(declared) && declared > limit) {+ log(+ 'fetchCappedBuffer: content-length %d exceeds the %d byte cap for %s',+ declared,+ limit,+ url,+ );+ return undefined;+ }++ // A trustworthy length lets the read allocate exactly once; a missing or+ // bogus one just falls back to growing, still capped at `limit`.+ const buffer = await readCappedBody(+ response,+ limit,+ Number.isFinite(declared) ? declared : undefined,+ );+ if (!buffer) log('fetchCappedBuffer: %s exceeded the %d byte cap', url, limit);+ return buffer;+ } finally {+ // Only safe once the body has been read: disposing earlier would abort+ // the stream we are still consuming.+ await fetched.dispose();+ }+ } catch (error) {+ log('fetchCappedBuffer: fetch failed for %s: %O', url, error);+ return undefined;+ }+};++/**+ * Materialize an attachment's bytes: inline base64 first (no round-trip), then+ * `fetchUrl`. Both sources honour the same cap — refusing a 60MB download while+ * happily decoding 60MB of inline base64 would defeat the point.+ *+ * Returns `undefined` when no source is usable so the caller can skip the item+ * without aborting the whole batch.+ */+export const loadAttachmentBuffer = async (+ attachment: LoadableAttachment,+ options: LoadAttachmentOptions = {},+): Promise<Buffer | undefined> => {+ const limit = options.limit ?? MAX_IN_MEMORY_ATTACHMENT_BYTES;++ if (attachment.data) {+ const buffer = Buffer.from(attachment.data, 'base64');+ if (buffer.length <= limit) return buffer;+ // The inline copy IS the attachment, so a URL for it would be just as+ // large — skip the pointless download.+ log('loadAttachmentBuffer: %d inline bytes exceeds the %d byte cap', buffer.length, limit);+ return undefined;+ }++ if (attachment.fetchUrl)+ return fetchCappedBuffer(attachment.fetchUrl, {+ ...options,+ // Provenance rides on the attachment, never on the call site: only a URL+ // the server built from an owned record may relax the guard.+ allowConfiguredOrigins: attachment.trustedUrl === true,+ limit,+ });++ return undefined;+};diff --git a/apps/server/src/services/bot/platforms/publicUrlFetch.test.ts b/apps/server/src/services/bot/platforms/publicUrlFetch.test.tsnew file mode 100644index 00000000000..e14201a5833--- /dev/null+++ b/apps/server/src/services/bot/platforms/publicUrlFetch.test.ts@@ -0,0 +1,360 @@+// @vitest-environment node+import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ lookup: vi.fn() }));++vi.mock('node:dns', () => ({ promises: { lookup: mocks.lookup } }));+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));+vi.mock('@/envs/file', () => ({+ fileEnv: { S3_ENDPOINT: 'http://minio.internal:9000', S3_PUBLIC_DOMAIN: undefined },+}));++const { fetchPublicUrl } = await import('./publicUrlFetch');++const ok = () => ({ headers: new Headers(), ok: true, status: 200 }) as any;++describe('fetchPublicUrl', () => {+ beforeEach(() => {+ mocks.lookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }]);+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ it('fetches a public host', async () => {+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(result?.response.ok).toBe(true);+ expect(fetchMock).toHaveBeenCalled();+ await result!.dispose();+ });++ it.each([+ ['loopback', 'http://127.0.0.1/admin'],+ ['cloud metadata', 'http://169.254.169.254/latest/meta-data/'],+ ['RFC1918', 'http://10.1.2.3/internal'],+ ['RFC1918 (192.168)', 'http://192.168.0.1/'],+ ['IPv6 loopback', 'http://[::1]/'],+ ['IPv6 unique-local', 'http://[fd00::1]/'],+ // `new URL()` canonicalizes these to ::ffff:a00:1 / ::ffff:a9fe:a9fe, so a+ // regex looking for a dotted quad never sees them.+ ['IPv4-mapped RFC1918', 'http://[::ffff:10.0.0.1]/'],+ ['IPv4-mapped metadata', 'http://[::ffff:169.254.169.254]/'],+ ['IPv4-mapped loopback', 'http://[::ffff:127.0.0.1]/'],+ ['already-canonical IPv4-mapped', 'http://[::ffff:a00:1]/'],+ ['IPv4-compatible loopback', 'http://[::127.0.0.1]/'],+ ])('refuses a literal %s address', async (_label, url) => {+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl(url, 1000)).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('refuses a public hostname that resolves to a private address', async () => {+ // The classic DNS-based bypass: the name looks fine, the answer does not.+ mocks.lookup.mockResolvedValue([{ address: '169.254.169.254', family: 4 }]);+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl('https://evil.example.com/x', 1000)).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('refuses when any resolved address is private', async () => {+ mocks.lookup.mockResolvedValue([+ { address: '93.184.216.34', family: 4 },+ { address: '10.0.0.5', family: 4 },+ ]);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(ok()));++ expect(await fetchPublicUrl('https://evil.example.com/x', 1000)).toBeUndefined();+ });++ it.each([+ ['a non-HTTP protocol', 'file:///etc/passwd'],+ ['embedded credentials', 'https://user:[email protected]/a.png'],+ ])('refuses %s', async (_label, url) => {+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl(url, 1000)).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('trusts our own app origin only when the URL is server-generated', async () => {+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ const result = await fetchPublicUrl('https://app.example.com/f/file_1', 1000, {+ allowConfiguredOrigins: true,+ });++ expect(result).toBeTruthy();+ // Trusted origins skip resolution entirely.+ expect(mocks.lookup).not.toHaveBeenCalled();+ await result!.dispose();+ });++ it('trusts a private storage endpoint we configured ourselves, when opted in', async () => {+ // Self-hosted deployments legitimately run object storage on the LAN, and+ // dev hands back a localhost storage URL.+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(ok()));++ const result = await fetchPublicUrl('http://minio.internal:9000/bucket/k', 1000, {+ allowConfiguredOrigins: true,+ });++ expect(result).toBeTruthy();+ await result!.dispose();+ });++ it('does NOT trust a configured private origin for a caller-supplied URL', async () => {+ // Regression: a configured origin is not proof of ownership. Without+ // provenance, any caller could name our internal storage host and walk+ // straight past the private-address guard.+ mocks.lookup.mockResolvedValue([{ address: '10.0.0.5', family: 4 }]);+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl('http://minio.internal:9000/bucket/k', 1000)).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('still resolves our own app origin normally without the opt-in', async () => {+ // A public APP_URL keeps working for caller URLs — it just goes through the+ // same DNS check as anything else rather than skipping it.+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ const result = await fetchPublicUrl('https://app.example.com/f/file_1', 1000);++ expect(result).toBeTruthy();+ expect(mocks.lookup).toHaveBeenCalled();+ await result!.dispose();+ });++ it('trusts the virtual-hosted bucket subdomain of our own storage endpoint', async () => {+ // Regression: S3 (and every S3-compatible service) defaults to+ // virtual-hosted addressing, so our own presigned URL lives on+ // `<bucket>.<endpoint>` and never equals the endpoint origin. Falling+ // through to the private-address check made every attachment silently+ // degrade to a download link.+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(ok()));++ const result = await fetchPublicUrl('http://my-bucket.minio.internal:9000/k', 1000, {+ allowConfiguredOrigins: true,+ });++ expect(result).toBeTruthy();+ expect(mocks.lookup).not.toHaveBeenCalled();+ await result!.dispose();+ });++ it.each([+ ['a look-alike sibling host', 'http://evil-minio.internal:9000/k'],+ ['a different port on the same host', 'http://bucket.minio.internal:9001/k'],+ ['a different scheme', 'https://bucket.minio.internal:9000/k'],+ ])('does not extend that trust to %s', async (_label, url) => {+ // The suffix match is anchored on a `.` boundary and still pins scheme and+ // port, so it trusts strictly more of OUR endpoint and nothing else. Asserted+ // WITH the opt-in, which is the stronger claim.+ mocks.lookup.mockResolvedValue([{ address: '10.0.0.5', family: 4 }]);+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl(url, 1000, { allowConfiguredOrigins: true })).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('pins the request to the vetted address so a rebinding answer cannot be used', async () => {+ // Validating a hostname and then letting undici resolve it again is the+ // rebinding hole: the name answers publicly for our lookup and privately+ // for the connection.+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ await result!.dispose();+ });++ it('keeps pinning when a proxy env var is set but nothing is actually proxied', async () => {+ // Regression: the decision used to read HTTPS_PROXY directly. The global+ // proxy dispatcher is only installed under NODE_ENV=development, so in+ // production a stray env var proxies nothing — and skipping the pin on that+ // basis handed the hostname back to undici, reopening the rebinding hole.+ vi.stubEnv('HTTPS_PROXY', 'http://proxy.internal:3128');+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ await result!.dispose();+ vi.unstubAllEnvs();+ });++ it('does not pin when a proxy dispatcher is actually installed', async () => {+ // The proxy resolves DNS itself, so pinning a locally resolved address+ // would bypass it and the egress policy it enforces, and mean nothing.+ const previous = getGlobalDispatcher();+ const proxy = new EnvHttpProxyAgent({ httpsProxy: 'http://proxy.internal:3128' });+ setGlobalDispatcher(proxy);+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ try {+ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeUndefined();+ await result!.dispose();+ } finally {+ setGlobalDispatcher(previous);+ await proxy.close();+ }+ });++ it('hands back a dispose hook so the pinned pool is released', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(ok()));++ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(result?.dispose).toBeTypeOf('function');+ await expect(result!.dispose()).resolves.toBeUndefined();+ });++ it('still pins a destination NO_PROXY tells the proxy to bypass', async () => {+ // Regression: the check was class-level, so an installed proxy marked every+ // request proxied — but a NO_PROXY destination is dispatched DIRECTLY, and+ // that is precisely where the pin is still needed.+ const previous = getGlobalDispatcher();+ const proxy = new EnvHttpProxyAgent({ httpsProxy: 'http://proxy.internal:3128' });+ setGlobalDispatcher(proxy);+ vi.stubEnv('NO_PROXY', 'cdn.example.com');+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ try {+ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ await result!.dispose();+ } finally {+ vi.unstubAllEnvs();+ setGlobalDispatcher(previous);+ await proxy.close();+ }+ });++ it('still pins when NO_PROXY is a wildcard', async () => {+ const previous = getGlobalDispatcher();+ const proxy = new EnvHttpProxyAgent({ httpsProxy: 'http://proxy.internal:3128' });+ setGlobalDispatcher(proxy);+ vi.stubEnv('NO_PROXY', '*');+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ try {+ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ await result!.dispose();+ } finally {+ vi.unstubAllEnvs();+ setGlobalDispatcher(previous);+ await proxy.close();+ }+ });++ it('still pins when NO_PROXY uses a wildcard suffix', async () => {+ // Regression: `*.example.com` kept its `*` through normalization, so the+ // bypass went unrecognized and the direct request lost its pin.+ const previous = getGlobalDispatcher();+ const proxy = new EnvHttpProxyAgent({ httpsProxy: 'http://proxy.internal:3128' });+ setGlobalDispatcher(proxy);+ vi.stubEnv('NO_PROXY', '*.example.com');+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ try {+ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ await result!.dispose();+ } finally {+ vi.unstubAllEnvs();+ setGlobalDispatcher(previous);+ await proxy.close();+ }+ });++ it('does not pin a host the proxy actually handles', async () => {+ const previous = getGlobalDispatcher();+ const proxy = new EnvHttpProxyAgent({ httpsProxy: 'http://proxy.internal:3128' });+ setGlobalDispatcher(proxy);+ vi.stubEnv('NO_PROXY', 'other.example.com');+ const fetchMock = vi.fn().mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ try {+ const result = await fetchPublicUrl('https://cdn.example.com/a.png', 1000);++ expect(fetchMock.mock.calls[0][1].dispatcher).toBeUndefined();+ await result!.dispose();+ } finally {+ vi.unstubAllEnvs();+ setGlobalDispatcher(previous);+ await proxy.close();+ }+ });++ it('re-validates every redirect hop', async () => {+ // Regression: our file proxy answers /f/:id with a 302, so redirects must be+ // followed — which means a public host could bounce us to the metadata IP.+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce({+ body: null,+ headers: new Headers({ location: 'http://169.254.169.254/latest/' }),+ status: 302,+ } as any)+ .mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl('https://cdn.example.com/a.png', 1000)).toBeUndefined();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('follows a redirect that stays public', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce({+ body: null,+ headers: new Headers({ location: 'https://cdn.example.com/real.png' }),+ status: 302,+ } as any)+ .mockResolvedValue(ok());+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl('https://cdn.example.com/a.png', 1000)).toBeTruthy();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('gives up on a redirect loop', async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ body: null,+ headers: new Headers({ location: 'https://cdn.example.com/loop' }),+ status: 302,+ } as any);+ vi.stubGlobal('fetch', fetchMock);++ expect(await fetchPublicUrl('https://cdn.example.com/loop', 1000)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/platforms/publicUrlFetch.ts b/apps/server/src/services/bot/platforms/publicUrlFetch.tsnew file mode 100644index 00000000000..451fa989c65--- /dev/null+++ b/apps/server/src/services/bot/platforms/publicUrlFetch.ts@@ -0,0 +1,370 @@+import { promises as dns } from 'node:dns';+import { isIP } from 'node:net';++import debug from 'debug';+import { Agent, EnvHttpProxyAgent, getGlobalDispatcher, ProxyAgent } from 'undici';++import { appEnv } from '@/envs/app';+import { fileEnv } from '@/envs/file';++const log = debug('bot-platform:public-url-fetch');++/**+ * Origins we serve ourselves. They are trusted even when they resolve to a+ * private address, because a self-hosted deployment legitimately runs its app+ * and its object storage on an internal network — and in dev `getFileAccessUrl`+ * hands back a `localhost` storage URL. These are OUR origins, not+ * caller-supplied ones, so trusting them adds no attacker-reachable surface.+ */+interface TrustedOrigin {+ hostname: string;+ port: string;+ protocol: string;+}++const trustedOrigins = (): TrustedOrigin[] => {+ const origins: TrustedOrigin[] = [];+ for (const candidate of [appEnv.APP_URL, fileEnv.S3_PUBLIC_DOMAIN, fileEnv.S3_ENDPOINT]) {+ if (!candidate) continue;+ try {+ const { hostname, port, protocol } = new URL(candidate);+ origins.push({ hostname, port, protocol });+ } catch {+ // A misconfigured env value simply contributes no trusted origin.+ }+ }+ return origins;+};++/**+ * Whether a URL points at storage/app infrastructure we configured ourselves.+ *+ * The bucket subdomain is why this is not a plain origin comparison: S3 and+ * every S3-compatible service default to VIRTUAL-HOSTED-style addressing, so+ * the presigned URL our own file service hands out lives on+ * `<bucket>.<S3_ENDPOINT host>` and never equals the configured endpoint+ * origin. Without this, our own storage falls through to the private-address+ * check — which is exactly the case the trusted list exists to cover, and it+ * bit us for real: every WeChat/Telegram attachment silently degraded to a+ * download link because its bytes could not be fetched.+ *+ * Matching is anchored on a `.` boundary and still requires the same scheme and+ * port, so this trusts strictly more of OUR endpoint and nothing else — a+ * caller cannot reach `evil-<endpoint>` or a different port with it.+ */+const isTrustedOrigin = (url: URL, trusted: TrustedOrigin[]): boolean =>+ trusted.some(+ (origin) =>+ origin.protocol === url.protocol &&+ origin.port === url.port &&+ (origin.hostname === url.hostname || url.hostname.endsWith(`.${origin.hostname}`)),+ );++const inV4Range = (ip: string, prefix: string, bits: number): boolean => {+ const toInt = (value: string) =>+ value.split('.').reduce((acc, part) => (acc << 8) + Number(part), 0) >>> 0;+ const mask = bits === 0 ? 0 : (0xff_ff_ff_ff << (32 - bits)) >>> 0;+ return (toInt(ip) & mask) === (toInt(prefix) & mask);+};++/**+ * Address ranges that must never be reachable through a caller-supplied URL:+ * loopback, the link-local metadata endpoint (169.254.169.254 on every major+ * cloud), RFC1918 networks, CGNAT, benchmarking, multicast and reserved space.+ */+const isPrivateV4 = (ip: string): boolean =>+ [+ ['0.0.0.0', 8],+ ['10.0.0.0', 8],+ ['100.64.0.0', 10],+ ['127.0.0.0', 8],+ ['169.254.0.0', 16],+ ['172.16.0.0', 12],+ ['192.0.0.0', 24],+ ['192.168.0.0', 16],+ ['198.18.0.0', 15],+ ['224.0.0.0', 4],+ ['240.0.0.0', 4],+ ].some(([prefix, bits]) => inV4Range(ip, prefix as string, bits as number));++/**+ * Expand an IPv6 address into its 8 hextets.+ *+ * Parsing rather than pattern-matching is the point: `new URL()` canonicalizes+ * `[::ffff:10.0.0.1]` to `::ffff:a00:1`, so a regex looking for a dotted quad+ * silently misses the mapped form the browser/Node actually hands us — and the+ * embedded address is what decides whether it is private.+ */+const toHextets = (raw: string): number[] | undefined => {+ let address = raw.toLowerCase().split('%')[0];++ // A trailing dotted quad (::ffff:10.0.0.1) is two hextets.+ const dotted = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(address);+ if (dotted) {+ const octets = dotted[1].split('.').map(Number);+ if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255))+ return undefined;+ address =+ address.slice(0, dotted.index) ++ [+ ((octets[0] << 8) | octets[1]).toString(16),+ ((octets[2] << 8) | octets[3]).toString(16),+ ].join(':');+ }++ const halves = address.split('::');+ if (halves.length > 2) return undefined;++ const parse = (part: string) =>+ part ? part.split(':').map((hextet) => Number.parseInt(hextet, 16)) : [];+ const left = parse(halves[0]);+ const right = halves.length === 2 ? parse(halves[1]) : [];+ if ([...left, ...right].some((value) => !Number.isInteger(value) || value < 0 || value > 0xff_ff))+ return undefined;++ if (halves.length === 1) return left.length === 8 ? left : undefined;++ const gap = 8 - left.length - right.length;+ if (gap < 1) return undefined;+ return [...left, ...Array.from({ length: gap }, () => 0), ...right];+};++const isPrivateV6 = (ip: string): boolean => {+ const hextets = toHextets(ip);+ // Anything we cannot parse is refused rather than assumed public.+ if (!hextets) return true;++ // `::` (unspecified) and `::1` (loopback).+ if (hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] <= 1) return true;++ // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d) are decided by+ // the embedded v4 address, in whichever textual form they arrived.+ if (+ hextets.slice(0, 5).every((hextet) => hextet === 0) &&+ (hextets[5] === 0xff_ff || hextets[5] === 0)+ ) {+ const embedded = [hextets[6] >> 8, hextets[6] & 0xff, hextets[7] >> 8, hextets[7] & 0xff].join(+ '.',+ );+ return isPrivateV4(embedded);+ }++ // fc00::/7 unique-local, fe80::/10 link-local.+ if ((hextets[0] & 0xfe_00) === 0xfc_00) return true;+ return (hextets[0] & 0xff_c0) === 0xfe_80;+};++const isPrivateAddress = (ip: string): boolean =>+ isIP(ip) === 6 ? isPrivateV6(ip) : isPrivateV4(ip);++/**+ * Resolve a caller-supplied URL and refuse anything that points inside the+ * network. Returns the parsed URL when it is safe to fetch.+ *+ * Hostnames are resolved and EVERY answer is checked: a name that resolves to+ * `169.254.169.254` is just as dangerous as the literal address, and cloud+ * metadata is the classic target.+ */+interface SafeTarget {+ /** The vetted address, so the request can be pinned to the answer we checked. */+ pinned?: { address: string; family: number };+ url: URL;+}++const resolveSafeUrl = async (+ raw: string,+ trusted: TrustedOrigin[],+): Promise<SafeTarget | undefined> => {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ log('resolveSafeUrl: not a URL: %s', raw);+ return undefined;+ }++ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ log('resolveSafeUrl: refusing protocol %s', url.protocol);+ return undefined;+ }++ // Credentials in the URL are never legitimate here and can confuse+ // downstream parsers about which host is really being contacted.+ if (url.username || url.password) {+ log('resolveSafeUrl: refusing URL carrying credentials');+ return undefined;+ }++ if (isTrustedOrigin(url, trusted)) return { url };++ const host = url.hostname.replaceAll(/^\[|\]$/g, '');+ let answers: Array<{ address: string; family: number }>;+ if (isIP(host)) {+ answers = [{ address: host, family: isIP(host) }];+ } else {+ try {+ answers = await dns.lookup(host, { all: true });+ } catch (error) {+ log('resolveSafeUrl: DNS lookup failed for %s: %O', host, error);+ return undefined;+ }+ }++ if (answers.length === 0 || answers.some((entry) => isPrivateAddress(entry.address))) {+ log('resolveSafeUrl: refusing %s — resolves to a private address', host);+ return undefined;+ }++ return { pinned: answers[0], url };+};++/**+ * Whether `NO_PROXY` tells the proxy agent to send this host directly.+ *+ * `EnvHttpProxyAgent` applies this per destination, so a proxy being installed+ * does not mean THIS request is proxied — and a bypassed request is dispatched+ * directly, where the pin is exactly what we still need.+ */+const bypassesProxy = (hostname: string): boolean => {+ const configured = process.env.NO_PROXY || process.env.no_proxy;+ if (!configured) return false;++ const host = hostname.toLowerCase();+ return configured+ .split(',')+ .map((entry) => entry.trim().toLowerCase())+ .filter(Boolean)+ .some((entry) => {+ if (entry === '*') return true;+ // Entries may carry a port and may lead with `.` or `*.`; all of those+ // forms mean "this host and anything under it".+ const bare = entry.replace(/:\d+$/, '').replace(/^\*?\./, '');+ return host === bare || host.endsWith(`.${bare}`);+ });+};++/**+ * Whether THIS request actually goes through a proxy.+ *+ * Decided from the dispatcher in force, NOT from proxy environment variables:+ * `setGlobalDispatcher(EnvHttpProxyAgent)` only happens under+ * `NODE_ENV === 'development'` (see `libs/better-auth/define-config.ts`), so in+ * production a stray `HTTPS_PROXY` in the environment proxies nothing — and+ * skipping the pin on that basis would hand the hostname back to undici to+ * resolve a second time, reopening the rebinding hole.+ *+ * When a proxy IS in force for this destination, the proxy resolves DNS itself;+ * pinning a locally resolved address would bypass it along with the egress+ * policy it enforces, and would mean nothing anyway.+ */+const requestIsProxied = (url: URL): boolean => {+ const dispatcher = getGlobalDispatcher();+ const proxying = dispatcher instanceof ProxyAgent || dispatcher instanceof EnvHttpProxyAgent;+ return proxying && !bypassesProxy(url.hostname);+};++/** Redirect hops to follow before giving up. */+const MAX_REDIRECTS = 5;++export interface PublicFetchOptions {+ /**+ * Accept our own configured origins (APP_URL / S3) without the private-address+ * check. Only for URLs the SERVER produced from an owned record — a+ * caller-supplied URL that happens to sit on a configured origin is not+ * owned, and would otherwise walk straight through the guard.+ */+ allowConfiguredOrigins?: boolean;+ method?: 'GET' | 'HEAD';+}++export interface PublicFetchResult {+ /** Releases the pinned connection pool. Call once the body has been read. */+ dispose: () => Promise<void>;+ response: Response;+}++/**+ * `fetch` for a URL that may have come from a caller.+ *+ * Attachments reach the outbound senders in two ways: the push path resolves an+ * owned `fileId` server-side, but the agent-facing `botMessage` procedures+ * accept a raw `fetchUrl`. Downloading that URL server-side (which every+ * platform sender now does, in order to upload the bytes) would otherwise be an+ * SSRF primitive — and the response is handed to the chat platform, so it is an+ * exfiltration path too.+ *+ * Two properties make the check hold:+ *+ * - The connection is PINNED to the address we vetted. Validating a hostname+ * and then letting undici resolve it again is a DNS-rebinding hole: the+ * attacker's name answers publicly for our lookup and privately for the+ * connection. (Skipped behind a proxy — see `proxyConfigured`.)+ * - Redirects are followed MANUALLY so every hop is re-validated: our own file+ * proxy answers `/f/:id` with a 302, so they cannot simply be refused, and+ * validating only the first URL would let a public host bounce us straight to+ * the metadata endpoint.+ */+export const fetchPublicUrl = async (+ rawUrl: string,+ timeoutMs: number,+ { allowConfiguredOrigins = false, method = 'GET' }: PublicFetchOptions = {},+): Promise<PublicFetchResult | undefined> => {+ // Not opting in simply contributes no trusted origins, so a caller-supplied+ // URL on a configured private origin still faces the private-address check.+ const trusted = allowConfiguredOrigins ? trustedOrigins() : [];+ const pools: Agent[] = [];+ const dispose = async () => {+ await Promise.all(pools.map((pool) => pool.close().catch(() => pool.destroy())));+ };++ let target = rawUrl;++ try {+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {+ const safe = await resolveSafeUrl(target, trusted);+ if (!safe) {+ await dispose();+ return undefined;+ }++ let dispatcher: Agent | undefined;+ if (safe.pinned && !requestIsProxied(safe.url)) {+ const { address, family } = safe.pinned;+ dispatcher = new Agent({+ connect: {+ // Hand undici the address we vetted instead of letting it resolve+ // the name a second time. Host/SNI still come from the URL.+ lookup: (_hostname, _options, callback) => callback(null, address, family),+ },+ });+ pools.push(dispatcher);+ }++ const response = await fetch(safe.url, {+ dispatcher,+ method,+ redirect: 'manual',+ signal: AbortSignal.timeout(timeoutMs),+ } as RequestInit);++ if (response.status < 300 || response.status >= 400) return { dispose, response };++ const location = response.headers.get('location');+ // Release the redirect body before following the hop.+ await response.body?.cancel().catch(() => undefined);+ if (!location) {+ log('fetchPublicUrl: %d with no location header', response.status);+ await dispose();+ return undefined;+ }+ target = new URL(location, safe.url).toString();+ }++ log('fetchPublicUrl: too many redirects for %s', rawUrl);+ await dispose();+ return undefined;+ } catch (error) {+ await dispose();+ throw error;+ }+};diff --git a/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/slack/sendAttachments.test.tsindex 61090eeef5a..55bd9a7fe46 100644--- a/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts@@ -3,6 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { sendSlackAttachments } from './sendAttachments';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const makeApi = () => ({completeFileUpload: vi.fn().mockResolvedValue(undefined),getFileUploadUrl: vi.fn().mockResolvedValue({diff --git a/apps/server/src/services/bot/platforms/slack/sendAttachments.ts b/apps/server/src/services/bot/platforms/slack/sendAttachments.tsindex bfaeee88b14..8f47a96f020 100644--- a/apps/server/src/services/bot/platforms/slack/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/slack/sendAttachments.ts@@ -1,36 +1,11 @@import debug from 'debug';+import { loadAttachmentBuffer } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';import type { SlackApi } from './api';const log = debug('bot-platform:slack:send-attachments');-const loadAttachmentBuffer = async (- attachment: BotMessageAttachment,-): Promise<Buffer | undefined> => {- if (attachment.data) {- try {- return Buffer.from(attachment.data, 'base64');- } catch (error) {- log('loadAttachmentBuffer: failed to decode base64: %O', error);- }- }- if (attachment.fetchUrl) {- try {- const response = await fetch(attachment.fetchUrl, {- signal: AbortSignal.timeout(15_000),- });- if (response.ok) {- return Buffer.from(await response.arrayBuffer());- }- log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);- } catch (error) {- log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);- }- }- return undefined;-};-const fallbackFilename = (att: BotMessageAttachment, index: number): string => {if (att.name) return att.name;if (att.fetchUrl) {diff --git a/apps/server/src/services/bot/platforms/telegram/api.test.ts b/apps/server/src/services/bot/platforms/telegram/api.test.tsindex 7ee1fb71897..1be809109d8 100644--- a/apps/server/src/services/bot/platforms/telegram/api.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/api.test.ts@@ -115,6 +115,26 @@ describe('TelegramApi HTML parse fallback', () => {expect(retryBody.caption).toContain('the answer is 42');});+ it('sendVideo asks for a streaming-capable player on both source shapes', async () => {+ // Without `supports_streaming` clients render a download-then-play blob+ // instead of a seekable player. It does NOT prevent Telegram from badging+ // a soundless MP4 as a GIF — nothing in the Bot API does.+ // A Response body reads once, so each call needs its own.+ fetchSpy.mockImplementation(async () => okResponse({ message_id: 3 }));+ const api = new TelegramApi(BOT_TOKEN);++ await api.sendVideo({ chatId: 'chat-1', source: { url: 'https://example.com/a.mp4' } });+ const jsonBody = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string);+ expect(jsonBody.supports_streaming).toBe(true);++ await api.sendVideo({+ chatId: 'chat-1',+ source: { buffer: Buffer.from('mp4'), filename: 'a.mp4', mimeType: 'video/mp4' },+ });+ const form = (fetchSpy.mock.calls[1][1] as RequestInit).body as FormData;+ expect(form.get('supports_streaming')).toBe('true');+ });+it('sendDocument with Buffer source retries caption without HTML on parse error', async () => {fetchSpy.mockResolvedValueOnce(diff --git a/apps/server/src/services/bot/platforms/telegram/api.ts b/apps/server/src/services/bot/platforms/telegram/api.tsindex 4380481efa0..1ba3b61e644 100644--- a/apps/server/src/services/bot/platforms/telegram/api.ts+++ b/apps/server/src/services/bot/platforms/telegram/api.ts@@ -12,6 +12,15 @@ export const TELEGRAM_API_BASE = 'https://api.telegram.org';*/const TELEGRAM_FETCH_TIMEOUT_MS = 8000;+/**+ * Multipart uploads carry up to tens of MB of binary payload, which cannot+ * fit inside the 8s JSON-call budget — a 20MB document upload alone can take+ * longer than that on a cold serverless egress path. Uploads happen on the+ * proactive-push path (one per request), not the per-chunk reply loop, so a+ * generous cap does not threaten the function budget the same way.+ */+const TELEGRAM_UPLOAD_TIMEOUT_MS = 60_000;+const isParseEntitiesError = (error: unknown): boolean => {const msg = (error as { message?: string } | null)?.message;return typeof msg === 'string' && msg.includes("can't parse entities");@@ -491,7 +500,7 @@ export class TelegramApi {body: buildForm(),method: 'POST',// Let undici set the multipart boundary header automatically.- signal: AbortSignal.timeout(TELEGRAM_FETCH_TIMEOUT_MS),+ signal: AbortSignal.timeout(file ? TELEGRAM_UPLOAD_TIMEOUT_MS : TELEGRAM_FETCH_TIMEOUT_MS),});if (!response.ok) {@@ -542,6 +551,8 @@ export class TelegramApi {params: {caption?: string;chatId: string | number;+ /** Method-specific scalars (e.g. `supports_streaming` on sendVideo). */+ extraFields?: Record<string, boolean | number | string | undefined>;source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };},): Promise<{ message_id: number }> {@@ -557,6 +568,7 @@ export class TelegramApi {if ('url' in params.source) {return this.call(method, {+ ...params.extraFields,caption: captionForSend,chat_id: params.chatId,parse_mode: captionForSend && useHtml ? 'HTML' : undefined,@@ -567,6 +579,7 @@ export class TelegramApi {return this.callMultipart(method,{+ ...params.extraFields,caption: captionForSend,chat_id: params.chatId,parse_mode: captionForSend && useHtml ? 'HTML' : undefined,@@ -613,13 +626,29 @@ export class TelegramApi {return this.sendMedia('sendDocument', 'document', params);}+ /**+ * `supports_streaming` is always on: it is what makes clients render a+ * seekable player instead of a download-then-play blob, and every MP4 we+ * forward is already a progressive file.+ *+ * NOTE it does NOT stop Telegram from rendering a SOUNDLESS MP4 as an+ * animation (the "GIF" badge). That classification happens server-side from+ * the absence of an audio stream, and no Bot API parameter overrides it —+ * `sendDocument` re-detects the content type just the same, and only+ * `disable_content_type_detection` escapes it, at the cost of losing inline+ * playback entirely. Adding a silent audio track is the only real fix and+ * needs ffmpeg, which this path deliberately does not carry.+ */async sendVideo(params: {caption?: string;chatId: string | number;source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };}): Promise<{ message_id: number }> {log('sendVideo: chatId=%s', params.chatId);- return this.sendMedia('sendVideo', 'video', params);+ return this.sendMedia('sendVideo', 'video', {+ ...params,+ extraFields: { supports_streaming: true },+ });}async sendAudio(params: {diff --git a/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.tsindex 2fb64ed6d35..7f5c2c46203 100644--- a/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts@@ -3,6 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { sendTelegramAttachments } from './sendAttachments';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const makeApi = () => ({sendAudio: vi.fn().mockResolvedValue({ message_id: 1 }),sendDocument: vi.fn().mockResolvedValue({ message_id: 1 }),@@ -59,18 +69,26 @@ describe('sendTelegramAttachments', () => {it('only carries the caption on the first attachment', async () => {const api = makeApi();-- await sendTelegramAttachments(- api as any,- 'chat-1',- [- { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },- { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },- { fetchUrl: 'https://cdn.example.com/c.pdf', type: 'file' },- ],- 'hello',+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response(Buffer.from('pdf-bytes'), { status: 200 })),);+ try {+ await sendTelegramAttachments(+ api as any,+ 'chat-1',+ [+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },+ { fetchUrl: 'https://cdn.example.com/c.pdf', type: 'file' },+ ],+ 'hello',+ );+ } finally {+ vi.unstubAllGlobals();+ }+expect(api.sendPhoto).toHaveBeenCalledTimes(2);expect(api.sendDocument).toHaveBeenCalledTimes(1);expect(api.sendPhoto.mock.calls[0][0].caption).toBe('hello');@@ -78,19 +96,321 @@ describe('sendTelegramAttachments', () => {expect(api.sendDocument.mock.calls[0][0].caption).toBeUndefined();});+ it('downloads a URL-only document and uploads it as multipart instead of passing the URL', async () => {+ // Regression: `sendDocument` by URL only works for .pdf/.zip per the Bot+ // API, and the extension-less redirecting file-proxy URL fails even for+ // those — md/csv/pdf pushes all died with "wrong file identifier".+ const api = makeApi();+ const fetchMock = vi+ .fn()+ .mockResolvedValue(new Response(Buffer.from('markdown-bytes'), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ {+ fetchUrl: 'https://app.example.com/f/file_123',+ mimeType: 'text/markdown',+ name: 'notes.md',+ type: 'file',+ },+ ]);++ expect(n).toBe(1);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(fetchMock).toHaveBeenCalledWith('https://app.example.com/f/file_123', expect.anything());+ expect(api.sendDocument).toHaveBeenCalledWith({+ caption: undefined,+ chatId: 'chat-1',+ source: expect.objectContaining({+ buffer: expect.any(Buffer),+ filename: 'notes.md',+ mimeType: 'text/markdown',+ }),+ });+ });++ it('uploads a video as multipart bytes through sendVideo', async () => {+ // `sendVideo`, not `sendDocument`: routing video through the document+ // endpoint does NOT avoid the "GIF" rendering (the Bot API re-detects the+ // content type unless `disable_content_type_detection` is set, which would+ // cost inline playback), and it would drop `supports_streaming`. The+ // multipart upload is the part that matters — a URL source is unreliable+ // for the extension-less file-proxy URL.+ const api = makeApi();++ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ {+ data: Buffer.from('mp4-bytes').toString('base64'),+ mimeType: 'video/mp4',+ name: 'ad.mp4',+ type: 'video',+ },+ ]);++ expect(n).toBe(1);+ expect(api.sendDocument).not.toHaveBeenCalled();+ expect(api.sendVideo).toHaveBeenCalledWith({+ caption: undefined,+ chatId: 'chat-1',+ source: expect.objectContaining({ filename: 'ad.mp4', mimeType: 'video/mp4' }),+ });+ });++ it('refuses an oversize download on content-length before reading the body', async () => {+ const api = makeApi();+ const bodyRead = vi.fn();+ const fetchMock = vi.fn().mockResolvedValue({+ body: {+ getReader: () => {+ bodyRead();+ throw new Error('body must not be read');+ },+ },+ headers: new Headers({ 'content-length': String(80 * 1024 * 1024) }),+ ok: true,+ status: 200,+ });+ vi.stubGlobal('fetch', fetchMock);++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { fetchUrl: 'https://app.example.com/f/huge', name: 'huge.bin', type: 'file' },+ ]);++ expect(n).toBe(0);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(bodyRead).not.toHaveBeenCalled();+ expect(api.sendDocument).not.toHaveBeenCalled();+ });++ it('aborts a size-less download once it streams past the cap', async () => {+ // Regression (P1): the cap used to be checked AFTER `arrayBuffer()`, so a+ // response with no `content-length` was fully allocated before rejection.+ const api = makeApi();+ const cancel = vi.fn().mockResolvedValue(undefined);+ // 8 x 8MB = 64MB, past the 50MB cap — the reader must be cancelled partway.+ let served = 0;+ const fetchMock = vi.fn().mockResolvedValue({+ body: {+ getReader: () => ({+ cancel,+ read: async () => {+ served += 1;+ if (served > 8) return { done: true, value: undefined };+ return { done: false, value: new Uint8Array(8 * 1024 * 1024) };+ },+ }),+ },+ headers: new Headers(),+ ok: true,+ status: 200,+ });+ vi.stubGlobal('fetch', fetchMock);++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { fetchUrl: 'https://app.example.com/f/sizeless', name: 'big.bin', type: 'file' },+ ]);++ expect(n).toBe(0);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(cancel).toHaveBeenCalled();+ // Stopped at the first chunk that crossed 50MB, not after draining all 64MB.+ expect(served).toBe(7);+ expect(api.sendDocument).not.toHaveBeenCalled();+ });++ it('skips inline base64 that exceeds the upload cap without downloading it', async () => {+ const api = makeApi();+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ {+ data: Buffer.alloc(51 * 1024 * 1024).toString('base64'),+ fetchUrl: 'https://app.example.com/f/huge',+ name: 'huge.bin',+ type: 'file',+ },+ ]);++ expect(n).toBe(0);+ } finally {+ vi.unstubAllGlobals();+ }++ // The inline copy IS the attachment — re-fetching it would be just as big.+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('skips a document whose download fails without aborting the batch', async () => {+ const api = makeApi();+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('boom')));++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { fetchUrl: 'https://app.example.com/f/file_bad', name: 'bad.csv', type: 'file' },+ {+ data: Buffer.from('ok').toString('base64'),+ name: 'ok.pdf',+ type: 'file',+ },+ ]);++ expect(n).toBe(1);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(api.sendDocument).toHaveBeenCalledTimes(1);+ });+it('continues with remaining attachments when one fails', async () => {const api = makeApi();api.sendPhoto.mockRejectedValueOnce(new Error('Telegram 429')).mockResolvedValueOnce({ message_id: 2 });+ // The rejected photo now tries a document fallback, which materializes the+ // bytes first — stub the download so the test stays off the network.+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));- const n = await sendTelegramAttachments(api as any, 'chat-1', [- { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },- { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },+ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },+ ]);++ expect(n).toBe(1);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(api.sendPhoto).toHaveBeenCalledTimes(2);+ });++ it('uploads audio as multipart bytes rather than handing Telegram the URL', async () => {+ // Regression: `sendAudio` by URL needs the declared MIME type to match, so+ // our extension-less 302 proxy URL came back as+ // `Bad Request: failed to get HTTP URL content` and the audio was dropped.+ const api = makeApi();+ const fetchMock = vi+ .fn()+ .mockResolvedValue(new Response(Buffer.from('mp3-bytes'), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ try {+ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ {+ fetchUrl: 'https://app.example.com/f/file_1',+ mimeType: 'audio/mpeg',+ name: 'take.mp3',+ type: 'audio',+ },+ ]);++ expect(n).toBe(1);+ } finally {+ vi.unstubAllGlobals();+ }++ expect(fetchMock).toHaveBeenCalled();+ expect(api.sendAudio).toHaveBeenCalledWith({+ caption: undefined,+ chatId: 'chat-1',+ source: expect.objectContaining({ buffer: expect.any(Buffer), filename: 'take.mp3' }),+ });+ });++ it.each([+ ['a wav', 'audio/wav', 'clip.wav'],+ ['an octet-stream blob', 'application/octet-stream', 'clip.flac'],+ ])(+ 'routes %s through sendDocument, which sendAudio would have rejected',+ async (_label, mimeType, name) => {+ // The Bot API only accepts .mp3/.m4a on sendAudio; anything else 400s+ // instead of degrading, so pick the endpoint that takes arbitrary bytes.+ const api = makeApi();++ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { data: Buffer.from('bytes').toString('base64'), mimeType, name, type: 'audio' },+ ]);++ expect(n).toBe(1);+ expect(api.sendAudio).not.toHaveBeenCalled();+ expect(api.sendDocument).toHaveBeenCalledWith({+ caption: undefined,+ chatId: 'chat-1',+ source: expect.objectContaining({ filename: name }),+ });+ },+ );++ it('keeps sendAudio for an m4a named file whose MIME type is generic', async () => {+ const api = makeApi();++ await sendTelegramAttachments(api as any, 'chat-1', [+ {+ data: Buffer.from('bytes').toString('base64'),+ mimeType: 'application/octet-stream',+ name: 'voice.m4a',+ type: 'audio',+ },]);+ expect(api.sendAudio).toHaveBeenCalledTimes(1);+ expect(api.sendDocument).not.toHaveBeenCalled();+ });++ it('falls back to sendDocument when a typed endpoint rejects the file', async () => {+ // A rejection used to drop the attachment outright: the caller saw zero+ // deliveries and answered "push unavailable" with no file at all.+ const api = makeApi();+ api.sendVideo.mockRejectedValueOnce(new Error('Telegram 400: unsupported video'));++ const n = await sendTelegramAttachments(+ api as any,+ 'chat-1',+ [+ {+ data: Buffer.from('mp4').toString('base64'),+ mimeType: 'video/mp4',+ name: 'clip.mp4',+ type: 'video',+ },+ ],+ 'here you go',+ );+expect(n).toBe(1);- expect(api.sendPhoto).toHaveBeenCalledTimes(2);+ expect(api.sendDocument).toHaveBeenCalledWith({+ // The caption still rides the first DELIVERED message.+ caption: 'here you go',+ chatId: 'chat-1',+ source: expect.objectContaining({ filename: 'clip.mp4' }),+ });+ });++ it('does not retry sendDocument against itself', async () => {+ const api = makeApi();+ api.sendDocument.mockRejectedValueOnce(new Error('Telegram 413'));++ const n = await sendTelegramAttachments(api as any, 'chat-1', [+ { data: Buffer.from('x').toString('base64'), name: 'a.bin', type: 'file' },+ ]);++ expect(n).toBe(0);+ expect(api.sendDocument).toHaveBeenCalledTimes(1);});it('skips attachments with no resolvable source', async () => {diff --git a/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts b/apps/server/src/services/bot/platforms/telegram/sendAttachments.tsindex ed9563a87f7..cff7779b650 100644--- a/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts@@ -1,5 +1,6 @@import debug from 'debug';+import { loadAttachmentBuffer, MAX_IN_MEMORY_ATTACHMENT_BYTES } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';import type { TelegramApi } from './api';@@ -11,8 +12,18 @@ const log = debug('bot-platform:telegram:send-attachments');* bytes server-side, saving us a round-trip + base64 inflation.*/type TelegramMediaSource =- | { url: string }- | { buffer: Buffer; filename: string; mimeType?: string };+ { url: string } | { buffer: Buffer; filename: string; mimeType?: string };++/**+ * Refuse to buffer arbitrarily large remote files into memory for a multipart+ * upload. Matches the Bot API's 50MB upload cap; the attachment-budget pass+ * has already degraded anything over the platform budget to a download link,+ * so this only guards attachments whose size was unknown up front.+ */+const MAX_UPLOAD_SOURCE_BYTES = MAX_IN_MEMORY_ATTACHMENT_BYTES;++/** Download timeout for materializing an attachment (up to ~50MB). */+const DOWNLOAD_TIMEOUT_MS = 30_000;const fallbackFilename = (att: BotMessageAttachment, index: number): string => {if (att.name) return att.name;@@ -28,55 +39,110 @@ const fallbackFilename = (att: BotMessageAttachment, index: number): string => {};/**- * Resolve a `BotMessageAttachment` into a Telegram-ready source. Prefers- * `fetchUrl` so Telegram fetches the bytes server-side. Falls back to- * materializing `data` (base64) as a Buffer for multipart upload. Returns- * `undefined` when neither source is usable so the caller can skip the item.+ * Materialize the attachment's bytes for a multipart upload. The cap is+ * enforced while the body streams in, so an attachment whose size was unknown+ * or under-reported cannot exhaust the worker before being rejected.*/-const resolveTelegramSource = (+const uploadSource = async (att: BotMessageAttachment,index: number,-): TelegramMediaSource | undefined => {- if (att.fetchUrl) {- return { url: att.fetchUrl };- }- if (att.data) {- try {- return {- buffer: Buffer.from(att.data, 'base64'),- filename: fallbackFilename(att, index),- mimeType: att.mimeType,- };- } catch (error) {- log('resolveTelegramSource: failed to decode base64 for "%s": %O', att.name, error);+): Promise<TelegramMediaSource | undefined> => {+ const buffer = await loadAttachmentBuffer(att, {+ limit: MAX_UPLOAD_SOURCE_BYTES,+ timeoutMs: DOWNLOAD_TIMEOUT_MS,+ });+ if (!buffer) return undefined;++ return { buffer, filename: fallbackFilename(att, index), mimeType: att.mimeType };+};++/**+ * Resolve a `BotMessageAttachment` into a Telegram-ready source.+ *+ * Only IMAGES prefer `fetchUrl` — `sendPhoto` is the one endpoint that ingests+ * an arbitrary URL reliably, and letting Telegram pull the bytes saves a+ * round-trip + base64 inflation. Everything else is materialized into a Buffer+ * for multipart upload, because Bot API URL ingestion is documented per method+ * and our URL shape satisfies none of it:+ * - `sendDocument` by URL only works for .pdf/.zip, and the stable file-proxy+ * URL (`/f/:id`) carries no extension and answers with a 302 — Telegram+ * rejects it for every document type, including PDFs.+ * - `sendAudio` by URL needs the declared MIME type to match (audio/mpeg);+ * anything else comes back as `failed to get HTTP URL content`.+ * - `sendVideo` is just as fragile on that URL shape, and uploading the bytes+ * is also what lets Telegram probe duration/dimensions so the message arrives+ * with a real player rather than a bare blob.+ *+ * Returns `undefined` when no source is usable so the caller can skip the+ * item without aborting the whole batch.+ */+const resolveTelegramSource = async (+ att: BotMessageAttachment,+ index: number,+): Promise<TelegramMediaSource | undefined> => {+ if (att.type === 'image' && att.fetchUrl) return { url: att.fetchUrl };+ return uploadSource(att, index);+};++/**+ * `sendAudio` renders a playable audio message, but the Bot API accepts only+ * .MP3 / .M4A there — a .wav / .flac / .ogg is rejected outright rather than+ * degraded. Those still reach the user as a document, which Telegram happily+ * plays inline for common audio types.+ */+const TELEGRAM_AUDIO_MIME_TYPES = new Set(['audio/mp4', 'audio/mpeg', 'audio/x-m4a']);+const TELEGRAM_AUDIO_EXTENSIONS = new Set(['m4a', 'mp3']);++const isTelegramPlayableAudio = (att: BotMessageAttachment): boolean => {+ const mime = att.mimeType?.toLowerCase().split(';')[0].trim();+ if (mime && TELEGRAM_AUDIO_MIME_TYPES.has(mime)) return true;++ // A correct extension still wins when the MIME type is a generic+ // `application/octet-stream`, which object storage hands back often enough.+ const name = att.name?.toLowerCase() ?? '';+ const dot = name.lastIndexOf('.');+ return dot > 0 && TELEGRAM_AUDIO_EXTENSIONS.has(name.slice(dot + 1));+};++type TelegramMediaMethod = 'sendAudio' | 'sendDocument' | 'sendPhoto' | 'sendVideo';++const methodFor = (att: BotMessageAttachment): TelegramMediaMethod => {+ switch (att.type) {+ case 'image': {+ return 'sendPhoto';+ }+ case 'video': {+ return 'sendVideo';+ }+ case 'audio': {+ return isTelegramPlayableAudio(att) ? 'sendAudio' : 'sendDocument';+ }+ default: {+ return 'sendDocument';}}- return undefined;};const dispatch = async (api: TelegramApi,- chatId: string | number,- att: BotMessageAttachment,- source: TelegramMediaSource,- caption: string | undefined,+ method: TelegramMediaMethod,+ params: { caption?: string; chatId: string | number; source: TelegramMediaSource },): Promise<void> => {- switch (att.type) {- case 'image': {- await api.sendPhoto({ caption, chatId, source });+ switch (method) {+ case 'sendPhoto': {+ await api.sendPhoto(params);return;}- case 'video': {- await api.sendVideo({ caption, chatId, source });+ case 'sendVideo': {+ await api.sendVideo(params);return;}- case 'audio': {- await api.sendAudio({ caption, chatId, source });+ case 'sendAudio': {+ await api.sendAudio(params);return;}- case 'file':default: {- await api.sendDocument({ caption, chatId, source });+ await api.sendDocument(params);}}};@@ -99,22 +165,42 @@ export const sendTelegramAttachments = async (): Promise<number> => {let delivered = 0;for (const [index, att] of attachments.entries()) {- const source = resolveTelegramSource(att, index);+ const source = await resolveTelegramSource(att, index);if (!source) {log('sendTelegramAttachments: skipping attachment without resolvable source');continue;}++ const attemptCaption = delivered === 0 ? caption : undefined;+ const method = methodFor(att);try {- await dispatch(api, chatId, att, source, delivered === 0 ? caption : undefined);+ await dispatch(api, method, { caption: attemptCaption, chatId, source });delivered += 1;+ continue;} catch (error) {log(- 'sendTelegramAttachments: failed to send %s "%s": %O',+ 'sendTelegramAttachments: %s failed for %s "%s": %O',+ method,att.type,att.name ?? '(unnamed)',error,);}++ // Every typed endpoint enforces format rules of its own, and each time one+ // of them rejected us the attachment was DROPPED — the caller saw zero+ // deliveries and the user got "push unavailable" with no file at all+ // (.md/.csv/.pdf, then .wav, all the same shape). `sendDocument` takes+ // arbitrary bytes, so spend one more call there before giving up.+ if (method === 'sendDocument') continue;+ const bytes = 'buffer' in source ? source : await uploadSource(att, index);+ if (!bytes) continue;+ try {+ await api.sendDocument({ caption: attemptCaption, chatId, source: bytes });+ delivered += 1;+ } catch (error) {+ log('sendTelegramAttachments: document fallback failed for "%s": %O', att.name, error);+ }}return delivered;};diff --git a/apps/server/src/services/bot/platforms/telegram/service.test.ts b/apps/server/src/services/bot/platforms/telegram/service.test.tsindex 0a584ecb055..6f098011cad 100644--- a/apps/server/src/services/bot/platforms/telegram/service.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/service.test.ts@@ -3,6 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { TelegramMessageService } from './service';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const makeApi = () => ({sendAudio: vi.fn().mockResolvedValue({ message_id: 1 }),sendDocument: vi.fn().mockResolvedValue({ message_id: 1 }),@@ -34,16 +44,27 @@ describe('TelegramMessageService.sendMessage', () => {it('dispatches attachments to typed media methods with content as caption', async () => {const api = makeApi();const service = new TelegramMessageService(api as any);+ // Documents are uploaded as bytes now (a URL only works for .pdf/.zip and+ // fails outright for the extension-less file proxy), so the document leg+ // has to materialize before `sendDocument` is reached.+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response(Buffer.from('pdf-bytes'), { status: 200 })),+ );- await service.sendMessage({- attachments: [- { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },- { fetchUrl: 'https://cdn.example.com/b.pdf', type: 'file' },- ],- channelId: 'chat-1',- content: 'caption',- platform: 'telegram',- });+ try {+ await service.sendMessage({+ attachments: [+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },+ { fetchUrl: 'https://cdn.example.com/b.pdf', type: 'file' },+ ],+ channelId: 'chat-1',+ content: 'caption',+ platform: 'telegram',+ });+ } finally {+ vi.unstubAllGlobals();+ }expect(api.sendMessage).not.toHaveBeenCalled();expect(api.sendPhoto).toHaveBeenCalledWith(diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex d0675939767..dab8f6f143d 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -132,6 +132,17 @@ export interface BotMessageAttachment {* downloading URL-sourced attachments first.*/size?: number;+ /**+ * Set ONLY when the server itself produced `fetchUrl` from a record the+ * caller was checked to own (see `sendMessengerPush`). It relaxes the+ * outbound SSRF guard to accept our own configured origins even when they+ * resolve privately, which self-hosted storage and local dev need.+ *+ * Never set it from request input: a caller-supplied URL that merely lands+ * on a configured origin is not owned, and trusting it would turn the+ * relaxation into the bypass it exists to avoid.+ */+ trustedUrl?: boolean;type: 'image' | 'file' | 'video' | 'audio';}diff --git a/apps/server/src/services/bot/platforms/wechat/client.test.ts b/apps/server/src/services/bot/platforms/wechat/client.test.tsindex 8763eb4d4ba..c3803ab0f51 100644--- a/apps/server/src/services/bot/platforms/wechat/client.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/client.test.ts@@ -1,5 +1,15 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const mockCreateWechatAdapter = vi.hoisted(() => vi.fn());const mockGetUpdates = vi.hoisted(() => vi.fn());const mockStartTyping = vi.hoisted(() => vi.fn());diff --git a/apps/server/src/services/bot/platforms/wechat/contextWindow.test.ts b/apps/server/src/services/bot/platforms/wechat/contextWindow.test.tsindex 39ad630be8c..5c34689012c 100644--- a/apps/server/src/services/bot/platforms/wechat/contextWindow.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/contextWindow.test.ts@@ -202,7 +202,7 @@ describe('pending push queue', () => {await enqueuePendingPush(redis, APP, USER, payload('second'));const drained: string[] = [];- const sent = await drainPendingPushes(redis, APP, USER, async (p) => {+ const { sent } = await drainPendingPushes(redis, APP, USER, async (p) => {drained.push(p.content!);return 'sent';});@@ -218,7 +218,7 @@ describe('pending push queue', () => {await enqueuePendingPush(redis, APP, USER, payload('second'));let calls = 0;- const sent = await drainPendingPushes(redis, APP, USER, async () => {+ const { sent } = await drainPendingPushes(redis, APP, USER, async () => {calls++;return calls === 1 ? 'sent' : 'stop';});@@ -234,19 +234,94 @@ describe('pending push queue', () => {await enqueuePendingPush(redis, APP, USER, payload('first'));await redis.set(`wechat:pending-flush:${APP}:${USER}`, '1', 'EX', 30);- const sent = await drainPendingPushes(redis, APP, USER, async () => 'sent');+ const { sent } = await drainPendingPushes(redis, APP, USER, async () => 'sent');expect(sent).toBe(0);expect(redis.lists.get(wechatPendingPushKey(APP, USER))).toHaveLength(1);});+ it('reports the lock it could not take, so callers do not read an empty queue as drained', async () => {+ // Regression: the in-flight drain has already LPOP'd its current item, so+ // the list reads empty from outside while an older message is still being+ // delivered. `drained: false` is what stops a caller trusting that.+ const redis = new FakeRedis();+ await enqueuePendingPush(redis, APP, USER, payload('first'));+ await redis.set(`wechat:pending-flush:${APP}:${USER}`, '1', 'EX', 30);++ const result = await drainPendingPushes(redis, APP, USER, async () => 'sent');++ expect(result).toEqual({ drained: false, remaining: 0, sent: 0 });+ });++ it('does not delete a lock a new owner took after the lease expired', async () => {+ // Regression: one delivery can outlive the 30s TTL (probe + download ++ // upload is not bounded by it). An unconditional DEL on the way out would+ // drop the lock the NEXT drainer is holding and admit a third one.+ const redis = new FakeRedis();+ await enqueuePendingPush(redis, APP, USER, payload('first'));+ const lockKey = `wechat:pending-flush:${APP}:${USER}`;++ await drainPendingPushes(redis, APP, USER, async () => {+ // Simulate the lease expiring mid-delivery and someone else claiming it.+ await redis.set(lockKey, 'someone-elses-token', 'EX', 30);+ return 'sent';+ });++ expect(await redis.get(lockKey)).toBe('someone-elses-token');+ });++ it('stops draining when the lease is lost mid-delivery', async () => {+ // Regression: a send that outlasts the lease lets a second drainer in. The+ // first must not keep popping items the second is also popping, and must+ // not renew the lease that now belongs to the new owner.+ const redis = new FakeRedis();+ await enqueuePendingPush(redis, APP, USER, payload('first'));+ await enqueuePendingPush(redis, APP, USER, payload('second'));+ const lockKey = `wechat:pending-flush:${APP}:${USER}`;++ const delivered: string[] = [];+ const result = await drainPendingPushes(redis, APP, USER, async (p) => {+ delivered.push(p.content!);+ // The lease lapsed while this delivery ran and another drainer took it.+ await redis.set(lockKey, 'new-owner-token', 'EX', 30);+ return 'sent';+ });++ expect(delivered).toEqual(['first']);+ expect(result.sent).toBe(1);+ // The newer item is left for the drainer that now owns the lease.+ expect(redis.lists.get(wechatPendingPushKey(APP, USER))).toHaveLength(1);+ expect(await redis.get(lockKey)).toBe('new-owner-token');+ });++ it('renews its own lease across deliveries and releases it at the end', async () => {+ const redis = new FakeRedis();+ await enqueuePendingPush(redis, APP, USER, payload('first'));+ const lockKey = `wechat:pending-flush:${APP}:${USER}`;++ await drainPendingPushes(redis, APP, USER, async () => 'sent');++ // Its own lease is cleaned up, so the next drain is not blocked for 30s.+ expect(await redis.get(lockKey)).toBeNull();+ });++ it('reports what is still queued when the drain stops early', async () => {+ const redis = new FakeRedis();+ await enqueuePendingPush(redis, APP, USER, payload('first'));+ await enqueuePendingPush(redis, APP, USER, payload('second'));++ const result = await drainPendingPushes(redis, APP, USER, async () => 'stop');++ expect(result).toEqual({ drained: true, remaining: 2, sent: 0 });+ });+it('drops malformed payloads instead of blocking the queue', async () => {const redis = new FakeRedis();await redis.rpush(wechatPendingPushKey(APP, USER), 'not-json');await enqueuePendingPush(redis, APP, USER, payload('valid'));const drained: string[] = [];- const sent = await drainPendingPushes(redis, APP, USER, async (p) => {+ const { sent } = await drainPendingPushes(redis, APP, USER, async (p) => {drained.push(p.content!);return 'sent';});diff --git a/apps/server/src/services/bot/platforms/wechat/contextWindow.ts b/apps/server/src/services/bot/platforms/wechat/contextWindow.tsindex fd04e3cd6ad..ec7196f48f8 100644--- a/apps/server/src/services/bot/platforms/wechat/contextWindow.ts+++ b/apps/server/src/services/bot/platforms/wechat/contextWindow.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import { getWechatTextSendCount } from '@lobechat/chat-adapter-wechat';import debug from 'debug';@@ -229,6 +231,24 @@ export const enqueuePendingPush = async (return Math.min(length, PENDING_QUEUE_MAX);};+export interface DrainPendingResult {+ /**+ * `false` when another drain already held the lock. Its current item is+ * LPOP'd — out of the list but not yet delivered — so the queue can look+ * empty from outside while an older message is still in flight. Callers that+ * order their own work against the backlog must treat this as "unknown", not+ * as "empty".+ */+ drained: boolean;+ /**+ * Items still queued when the lock was released. Measured INSIDE the lock,+ * so it never observes the transient gap described above. Only meaningful+ * when `drained` is true.+ */+ remaining: number;+ sent: number;+}+/*** Replay queued pushes in FIFO order under a short NX lock (concurrent inbound* messages must not double-send). The handler returns `sent` to continue or@@ -239,10 +259,30 @@ export const drainPendingPushes = async (applicationId: string,userId: string,send: (payload: WechatPendingPush) => Promise<'sent' | 'stop' | { requeue: WechatPendingPush }>,-): Promise<number> => {+): Promise<DrainPendingResult> => {const lockKey = flushLockKey(applicationId, userId);- const locked = await redis.set(lockKey, '1', 'EX', FLUSH_LOCK_TTL_SECONDS, 'NX');- if (locked !== 'OK') return 0;+ // A token, not a constant: one delivery can outlive the TTL (probing,+ // downloading and uploading an attachment is not bounded by 30s), and the+ // expired holder must not then delete the lock a NEW owner is holding.+ const token = randomUUID();+ const locked = await redis.set(lockKey, token, 'EX', FLUSH_LOCK_TTL_SECONDS, 'NX');+ if (locked !== 'OK') return { drained: false, remaining: 0, sent: 0 };++ const stillOurs = async () => (await redis.get(lockKey)) === token;++ // Renew DURING the delivery, not after it: one send can outlast the lease on+ // its own (probe + download + upload), and a renewal that only runs once the+ // send returns is too late to have kept it alive. Ownership-checked, so a+ // lapsed holder never extends the lease of whoever took over.+ const heartbeat = setInterval(+ () => {+ void (async () => {+ if (await stillOurs()) await redis.expire(lockKey, FLUSH_LOCK_TTL_SECONDS);+ })();+ },+ Math.floor((FLUSH_LOCK_TTL_SECONDS / 3) * 1000),+ );+ heartbeat.unref?.();let sent = 0;try {@@ -260,6 +300,16 @@ export const drainPendingPushes = async (}const result = await send(payload);++ // If the lease lapsed and someone else took over mid-delivery, stop:+ // continuing would pop items a second drainer is also popping, and+ // renewing here would extend THEIR lease, not ours.+ if (!(await stillOurs())) {+ log('drainPendingPushes: lost the lease for %s:%s mid-drain', applicationId, userId);+ if (result === 'sent') sent++;+ return { drained: true, remaining: await redis.llen(pendingKey), sent };+ }+ await redis.expire(lockKey, FLUSH_LOCK_TTL_SECONDS);if (result === 'stop') {await redis.lpush(pendingKey, raw);break;@@ -272,8 +322,14 @@ export const drainPendingPushes = async (}sent++;}+ // Read under the lock: outside it, an item popped for delivery is missing+ // from the list and the queue would read as empty mid-flight. The `finally`+ // still releases the lock on the way out of this return.+ return { drained: true, remaining: await redis.llen(pendingKey), sent };} finally {- await redis.del(lockKey);+ clearInterval(heartbeat);+ // Only release a lease we still own: if it expired and someone else took+ // it, an unconditional DEL would drop THEIR lock and admit a third drainer.+ if (await stillOurs()) await redis.del(lockKey);}- return sent;};diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.tsindex b85148511c4..b7e88b95ccc 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts@@ -1,6 +1,16 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const budgetMocks = vi.hoisted(() => ({compressImageToBudget: vi.fn(),}));diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.tsindex d91794b8d43..a429ab89846 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts@@ -8,6 +8,7 @@ import {PLATFORM_ATTACHMENT_BUDGETS,splitFallbackMessages,} from '../attachmentBudget';+import { loadAttachmentBuffer } from '../loadAttachmentBuffer';const log = debug('bot-platform:wechat:send-attachments');@@ -51,36 +52,6 @@ const mapAttachmentTypeToUploadMediaType = (}};-/**- * Materialize an attachment's bytes from `data` (base64) or `fetchUrl` (HTTP- * GET, 15s timeout). Returns undefined if neither source resolves.- */-const loadAttachmentBuffer = async (- attachment: WechatOutboundAttachment,-): Promise<Buffer | undefined> => {- if (attachment.data) {- try {- return Buffer.from(attachment.data, 'base64');- } catch (error) {- log('loadAttachmentBuffer: failed to decode base64: %O', error);- }- }- if (attachment.fetchUrl) {- try {- const response = await fetch(attachment.fetchUrl, {- signal: AbortSignal.timeout(15_000),- });- if (response.ok) {- return Buffer.from(await response.arrayBuffer());- }- log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);- } catch (error) {- log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);- }- }- return undefined;-};-const buildMediaItemFromUpload = (mediaType: WechatUploadMediaType,cdnMedia: { aes_key: string; encrypt_query_param: string; encrypt_type: 1 },diff --git a/apps/server/src/services/bot/platforms/wechat/service.test.ts b/apps/server/src/services/bot/platforms/wechat/service.test.tsindex b7950ea4684..9e22d5b398b 100644--- a/apps/server/src/services/bot/platforms/wechat/service.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/service.test.ts@@ -1,6 +1,16 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS+// for real, which has nothing to do with what they assert. Its own behaviour is+// covered in publicUrlFetch.test.ts.+vi.mock('../publicUrlFetch', () => ({+ fetchPublicUrl: async (url: string, timeoutMs: number) => ({+ dispose: async () => undefined,+ response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),+ }),+}));+const MessageItemType = vi.hoisted(() => ({FILE: 4,IMAGE: 1,diff --git a/apps/server/src/services/messenger/outbound.test.ts b/apps/server/src/services/messenger/outbound.test.tsindex 3f172082e2e..e532ca87696 100644--- a/apps/server/src/services/messenger/outbound.test.ts+++ b/apps/server/src/services/messenger/outbound.test.ts@@ -3,6 +3,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { InstallationCredentials } from './installations/types';+// Attachments in these fixtures carry no `size`, so the budget pass probes the+// URL for one. These tests are about delivery mechanics, not budgeting — answer+// the probe with a small, in-budget length. The probe's own behaviour is+// covered in attachmentBudget.test.ts.+vi.mock('@/server/services/bot/platforms/publicUrlFetch', () => ({+ fetchPublicUrl: async () => ({+ dispose: async () => undefined,+ response: { headers: new Headers({ 'content-length': '1024' }), ok: true, status: 200 },+ }),+}));+const mocks = vi.hoisted(() => ({batchDiscordFiles: vi.fn(),createDMChannel: vi.fn(),diff --git a/apps/server/src/services/messenger/wechatPush.test.ts b/apps/server/src/services/messenger/wechatPush.test.tsindex 971b9708728..a37307dbc00 100644--- a/apps/server/src/services/messenger/wechatPush.test.ts+++ b/apps/server/src/services/messenger/wechatPush.test.ts@@ -204,6 +204,120 @@ describe('sendProactiveWechatMessage', () => {);});+ it('degrades an in-budget attachment whose upload failed to a download link and reports sent', async () => {+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');++ // Within budget, so it goes down the upload path — which fails (the mocked+ // client has no uploadCdnMedia). Regression: this used to requeue forever+ // (each replay failed the same way) and the caller was told "queued".+ const result = await sendProactiveWechatMessage({+ attachments: [+ {+ data: Buffer.alloc(1024, 1).toString('base64'),+ fetchUrl: 'https://example.com/f/video.mp4',+ name: 'video.mp4',+ size: 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/video.mp4'),+ 'token-1',+ );+ // Nothing left to replay — the link IS the delivery.+ expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER)) ?? []).toHaveLength(0);+ });++ it('reports quota_exhausted when the open window has fewer sends left than the delivery needs', async () => {+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');+ // 1 credit left, but text + attachment needs 2. Regression: the UI showed+ // "1 send left", the user hit send, and got "the window is closed".+ await consumeSendCredits(redis, APP, WECHAT_USER, WECHAT_WINDOW_MAX_SENDS - 1);++ const result = await sendProactiveWechatMessage({+ attachments: [+ { data: Buffer.alloc(1024, 1).toString('base64'), name: 'small.png', type: 'image' },+ ],+ content: 'text plus attachment',+ serverDB,+ userId: LOBE_USER,+ });++ expect(result).toEqual({ reason: 'quota_exhausted', status: 'queued' });+ expect(mockSendMessage).not.toHaveBeenCalled();+ expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(1);+ });++ it('drains the queued backlog before sending a new push into an open window', async () => {+ // Backlog accumulated while the window was closed…+ await enqueuePendingPush(redis, APP, WECHAT_USER, { content: 'queued first', enqueuedAt: 1 });+ // …then the window reopened without the inbound flush having run.+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');++ const result = await sendProactiveWechatMessage({+ content: 'fresh push',+ serverDB,+ userId: LOBE_USER,+ });++ expect(result.status).toBe('sent');+ // FIFO: the backlog lands before the new message.+ expect(mockSendMessage).toHaveBeenNthCalledWith(1, WECHAT_USER, 'queued first', 'token-1');+ expect(mockSendMessage).toHaveBeenNthCalledWith(2, WECHAT_USER, 'fresh push', 'token-1');+ expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER)) ?? []).toHaveLength(0);+ });++ it('queues a fresh push behind a backlog the drain could not finish', async () => {+ // Regression (P2): the drain stops once the backlog would eat into the+ // credits reserved for the live reply. The fresh push used to sail past the+ // still-queued older message, breaking the FIFO the drain exists to keep.+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');+ await consumeSendCredits(redis, APP, WECHAT_USER, WECHAT_WINDOW_MAX_SENDS - 2);+ await enqueuePendingPush(redis, APP, WECHAT_USER, { content: 'queued first', enqueuedAt: 1 });++ const result = await sendProactiveWechatMessage({+ content: 'fresh push',+ serverDB,+ userId: LOBE_USER,+ });++ expect(result).toEqual({ reason: 'quota_exhausted', status: 'queued' });+ // The fresh message never jumped the queue.+ expect(mockSendMessage).not.toHaveBeenCalledWith(WECHAT_USER, 'fresh push', 'token-1');+ const queued = redis.lists+ .get(wechatPendingPushKey(APP, WECHAT_USER))!+ .map((raw) => JSON.parse(raw).content);+ expect(queued).toEqual(['queued first', 'fresh push']);+ });++ it('queues behind an in-flight drain instead of reading the queue as empty', async () => {+ // Regression (P2, round 2): a concurrent drain holds the lock with its+ // current item already LPOP'd, so the list looks empty from here. Sending+ // now would overtake a message that is still being delivered.+ await recordInboundToken(redis, APP, WECHAT_USER, 'token-1');+ // Someone else's drain is in flight; the queue is transiently empty.+ await redis.set(`wechat:pending-flush:${APP}:${WECHAT_USER}`, '1', 'EX', 30);++ const result = await sendProactiveWechatMessage({+ content: 'fresh push',+ serverDB,+ userId: LOBE_USER,+ });++ expect(result).toEqual({ reason: 'delivery_in_progress', status: 'queued' });+ expect(mockSendMessage).not.toHaveBeenCalled();+ expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(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);@@ -220,7 +334,7 @@ describe('sendProactiveWechatMessage', () => {});expect(finalSend).toEqual({ remaining: 0, status: 'sent' });- expect(queued).toEqual({ status: 'queued' });+ expect(queued).toEqual({ reason: 'window_closed', status: 'queued' });expect(mockSendMessage).toHaveBeenCalledTimes(1);});@@ -231,7 +345,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'window_closed', status: 'queued' });expect(mockSendMessage).not.toHaveBeenCalled();expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(1);});@@ -246,7 +360,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'window_closed', status: 'queued' });expect(mockSendMessage).not.toHaveBeenCalled();});@@ -260,7 +374,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'send_failed', status: 'queued' });expect(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))).toHaveLength(1);});@@ -284,7 +398,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'send_failed', 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.@@ -314,7 +428,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'send_failed', 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.@@ -337,7 +451,7 @@ describe('sendProactiveWechatMessage', () => {userId: LOBE_USER,});- expect(result).toEqual({ status: 'queued' });+ expect(result).toEqual({ reason: 'send_failed', status: 'queued' });const queued = JSON.parse(redis.lists.get(wechatPendingPushKey(APP, WECHAT_USER))![0]);expect(queued.content).toBeUndefined();expect(queued.attachments).toHaveLength(1);diff --git a/apps/server/src/services/messenger/wechatPush.ts b/apps/server/src/services/messenger/wechatPush.tsindex 3dc0b9881d4..6e8b3f4efab 100644--- a/apps/server/src/services/messenger/wechatPush.ts+++ b/apps/server/src/services/messenger/wechatPush.ts@@ -6,22 +6,22 @@ import type { LobeChatDatabase } from '@/database/type';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import {+ buildAttachmentFallbackLine,PLATFORM_ATTACHMENT_BUDGETS,prepareAttachmentsForBudget,splitFallbackMessages,} from '@/server/services/bot/platforms/attachmentBudget';-import type {- WechatPendingPush,- WechatWindowRedis,-} from '@/server/services/bot/platforms/wechat/contextWindow';import {consumeSendCredits,drainPendingPushes,+ type DrainPendingResult,enqueuePendingPush,peekWindow,WECHAT_WINDOW_MAX_SENDS,+ type WechatPendingPush,wechatPendingPushKey,wechatWindowKey,+ type WechatWindowRedis,} from '@/server/services/bot/platforms/wechat/contextWindow';import type { WechatOutboundAttachment } from '@/server/services/bot/platforms/wechat/sendAttachments';import { sendWechatAttachments } from '@/server/services/bot/platforms/wechat/sendAttachments';@@ -45,7 +45,25 @@ export type WechatPushStatus =/** Redis (window state) is unavailable — cannot deliver or queue. */| 'unavailable';+/**+ * Why a push ended up `queued`. The client picks its toast off this — telling+ * a user whose window is visibly open that "the send window is closed" reads+ * as a bug (and was reported as one), so the three queue paths are kept+ * distinguishable.+ */+export type WechatPushQueueReason =+ /** No open send window — the classic "message the bot to receive it" case. */+ | 'window_closed'+ /** Window open but not enough sends left for this delivery. */+ | 'quota_exhausted'+ /** Delivery was attempted and partially failed; the rest is queued for retry. */+ | 'send_failed'+ /** An earlier message is still being delivered; this one waits behind it. */+ | 'delivery_in_progress';+export interface WechatPushResult {+ /** Set when `status` is `queued` — why delivery had to wait. */+ reason?: WechatPushQueueReason;/** Remaining locally tracked sends after delivery (only for `sent`). */remaining?: number;status: WechatPushStatus;@@ -197,13 +215,45 @@ const deliver = async (}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`);+ // An attachment can pass the byte budget yet still be unsendable through+ // iLink (observed: an ~11MB MP4 where every upload attempt fails). Blindly+ // requeueing such an attachment retries it on every inbound message and it+ // NEVER reaches the user — not even as a link — until the 72h queue TTL+ // silently drops it. So degrade upload failures with a `fetchUrl` to a+ // download-link message right now, exactly what the budget pass would have+ // produced had it known the platform would refuse the file. The extra link+ // sends are not pre-reserved against the window quota; the quota is+ // best-effort bookkeeping (WeChat enforces the real limit) and undercounting+ // here beats losing the attachment.+ if (failedOriginals.length > 0) {+ const linkable = failedOriginals.filter((attachment) => attachment.fetchUrl);+ const unlinkable = failedOriginals.filter((attachment) => !attachment.fetchUrl);++ if (linkable.length > 0) {+ const rescueMessages = splitFallbackMessages(+ linkable.map((attachment) => buildAttachmentFallbackLine(attachment, attachment.fetchUrl!)),+ PLATFORM_ATTACHMENT_BUDGETS.wechat.textMaxChars,+ );+ try {+ for (const message of rescueMessages) {+ await api.sendMessage(platformUserId, message, token);+ }+ progress.undeliveredAttachments = unlinkable;+ } catch (error) {+ // The rescue leg itself failed — keep the linkable originals owed so+ // the replay path can try the degrade again (bounded by the queue TTL).+ log('deliver: link fallback for failed uploads also failed: %O', error);+ }+ }++ // Only attachments with no smaller representation left (no fetchUrl, or a+ // failed rescue leg) are retried on the next inbound message — the queue's+ // 72h TTL and size cap bound the retries.+ if (progress.undeliveredAttachments.length > 0)+ throw new Error(+ `${progress.undeliveredAttachments.length} WeChat attachment(s) failed to send`,+ );+ }};export interface WechatPushWindowStatus {@@ -296,7 +346,48 @@ export const sendProactiveWechatMessage = async (params: {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' };+ return { reason: 'window_closed', status: 'queued' };+ }++ // The window is open: drain any backlog queued while it was closed BEFORE+ // sending the new message. Without this the settings UI can show an open+ // window sitting next to "N messages queued" (the queue only replays on the+ // next INBOUND message), and a fresh push would overtake the backlog,+ // breaking FIFO delivery.+ const drain = await drainQueuedPushes({+ api: target.api,+ applicationId: target.applicationId,+ platformUserId: target.platformUserId,+ redis,+ });++ // Only send now if THIS call drained the queue and left it empty.+ //+ // The drain does not always empty the queue: it stops once the backlog would+ // eat into the credits reserved for the live reply, and it requeues any leg+ // that failed mid-delivery. And when it could not take the lock at all, a+ // concurrent drain is mid-flight with its current item already LPOP'd — the+ // list would read as empty from here while an older message is still being+ // delivered. Sending in either case lets a fresh (often smaller) push jump+ // ahead of older ones, exactly the FIFO break this block exists to prevent.+ if (!drain.drained || drain.remaining > 0) {+ await enqueuePendingPush(redis, target.applicationId, target.platformUserId, payload);+ log(+ 'sendProactiveWechatMessage: queued behind backlog for %s (drained=%s, remaining=%d)',+ target.platformUserId,+ drain.drained,+ drain.remaining,+ );+ if (!drain.drained) return { reason: 'delivery_in_progress', status: 'queued' };++ // Distinguish "the drain ran out of credits" from "a replay failed", so the+ // toast matches what the user sees in the window state.+ const afterDrain = await peekWindow(redis, target.applicationId, target.platformUserId);+ if (!afterDrain) return { reason: 'window_closed', status: 'queued' };+ return {+ reason: afterDrain.remaining <= RESERVED_REPLY_CREDITS ? 'quota_exhausted' : 'send_failed',+ status: 'queued',+ };}const prepared = await prepareWechatDelivery(payload);@@ -314,7 +405,12 @@ export const sendProactiveWechatMessage = async (params: {credit.status,target.platformUserId,);- return { status: 'queued' };+ // `missing` means the window vanished between the peek and the consume+ // (TTL expiry) — from the user's perspective the window closed.+ return {+ reason: credit.status === 'exhausted' ? 'quota_exhausted' : 'window_closed',+ status: 'queued',+ };}const progress: DeliveryProgress = { contentDelivered: false };@@ -328,26 +424,24 @@ export const sendProactiveWechatMessage = async (params: {const remaining = undeliveredPayload(payload, progress);if (!remaining) return { remaining: credit.remaining, status: 'sent' };await enqueuePendingPush(redis, target.applicationId, target.platformUserId, remaining);- return { status: 'queued' };+ return { reason: 'send_failed', status: 'queued' };}};/**- * Replay pushes queued while the window was closed. Called after an inbound- * message refreshes the window (see WechatInstallationStore.resolveByPayload).- * Stops early when the backlog would eat into the credits reserved for the- * live reply.+ * Replay pushes queued while the window was closed, against an existing API+ * client. Shared by the inbound-message flush (`flushPendingWechatPushes`)+ * and the proactive-push path, which drains the backlog before sending a new+ * message whenever it finds the window already open. Stops early when the+ * backlog would eat into the credits reserved for the live reply.*/-export const flushPendingWechatPushes = async (params: {+const drainQueuedPushes = async (params: {+ api: WechatApiClient;applicationId: string;- baseUrl?: string;- botId?: string;- botToken: string;platformUserId: string;redis: WechatWindowRedis;-}): Promise<number> => {- const { redis, applicationId, platformUserId } = params;- const api = new WechatApiClient(params.botToken, params.botId, params.baseUrl);+}): Promise<DrainPendingResult> => {+ const { api, redis, applicationId, platformUserId } = params;return drainPendingPushes(redis, applicationId, platformUserId, async (payload) => {const sendWindow = await peekWindow(redis, applicationId, platformUserId);@@ -369,10 +463,29 @@ export const flushPendingWechatPushes = async (params: {await deliver(api, platformUserId, credit.token, prepared, progress);return 'sent';} catch (error) {- log('flushPendingWechatPushes: replay failed for %s: %O', platformUserId, error);+ log('drainQueuedPushes: replay failed for %s: %O', platformUserId, error);// Requeue only the legs still owed — `undefined` means everything landed.const remaining = undeliveredPayload(payload, progress);return remaining ? { requeue: remaining } : 'sent';}});};++/**+ * Replay pushes queued while the window was closed. Called after an inbound+ * message refreshes the window (see WechatInstallationStore.resolveByPayload).+ */+export const flushPendingWechatPushes = async (params: {+ applicationId: string;+ baseUrl?: string;+ botId?: string;+ botToken: string;+ platformUserId: string;+ redis: WechatWindowRedis;+}): Promise<number> =>+ drainQueuedPushes({+ api: new WechatApiClient(params.botToken, params.botId, params.baseUrl),+ applicationId: params.applicationId,+ platformUserId: params.platformUserId,+ redis: params.redis,+ }).then((result) => result.sent);diff --git a/locales/ar/messenger.json b/locales/ar/messenger.jsonindex b8008c448ae..828fca72e4e 100644--- a/locales/ar/messenger.json+++ b/locales/ar/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "تعذر تحميل حالة الرسائل الاستباقية.","messenger.push.placeholder": "اكتب رسالة لإرسالها إلى {{platform}}…","messenger.push.queued": "{{count}} رسالة (رسائل) في الانتظار سيتم تسليمها بعد أن ترسل رسالة إلى الروبوت في {{platform}}.",+ "messenger.push.queuedBusyToast": "لا يزال يتم تسليم رسالة أخرى — تم وضع رسالتك في قائمة الانتظار خلفها. أرسل رسالة إلى الروبوت في {{platform}} لتلقيها.",+ "messenger.push.queuedQuotaToast": "لا توجد عمليات إرسال متبقية في هذه الفترة الزمنية — تم وضع رسالتك في قائمة الانتظار. أرسل رسالة إلى الروبوت في {{platform}} لإعادة ضبط الفترة الزمنية واستلامها.",+ "messenger.push.queuedRetryToast": "جزء من رسالتك لم يتم تسليمه — تم وضع الباقي في قائمة الانتظار وسيتم إعادة المحاولة بعد أن ترسل رسالة إلى الروبوت في {{platform}}.","messenger.push.queuedToast": "نافذة الإرسال مغلقة — تم وضع رسالتك في الانتظار. أرسل رسالة إلى الروبوت في {{platform}} لاستلامها.","messenger.push.resource.description": "سيتم إرسال الملف كمرفق إلى حسابك المرتبط على {{platform}}.","messenger.push.resource.oversizeFileHint": "يتجاوز هذا الملف الحد الأقصى {{limit}} الخاص بـ {{platform}} وسيتم إرساله كرابط تنزيل.",diff --git a/locales/bg-BG/messenger.json b/locales/bg-BG/messenger.jsonindex d1e34aafab4..7c4826f8ec2 100644--- a/locales/bg-BG/messenger.json+++ b/locales/bg-BG/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Неуспешно зареждане на статуса на проактивното съобщение.","messenger.push.placeholder": "Напишете съобщение за изпращане до {{platform}}…","messenger.push.queued": "{{count}} съобщение(я) в опашката ще бъдат доставени, след като изпратите съобщение до бота в {{platform}}.",+ "messenger.push.queuedBusyToast": "Друго съобщение все още се доставя — вашето е поставено в опашката след него. Изпратете съобщение на бота в {{platform}}, за да го получите.",+ "messenger.push.queuedQuotaToast": "Няма останали изпращания в този прозорец — вашето съобщение е поставено в опашка. Изпратете съобщение до бота в {{platform}}, за да нулирате прозореца и да го получите.",+ "messenger.push.queuedRetryToast": "Част от вашето съобщение не можа да бъде доставена — останалата част е поставена в опашка и ще бъде опитана отново, след като изпратите съобщение до бота в {{platform}}.","messenger.push.queuedToast": "Прозорецът за изпращане е затворен — вашето съобщение е в опашката. Изпратете съобщение до бота в {{platform}}, за да го получите.","messenger.push.resource.description": "Файлът ще бъде изпратен като прикачен файл към свързания ви {{platform}} акаунт.","messenger.push.resource.oversizeFileHint": "Този файл надвишава лимита от {{limit}} на {{platform}} и ще бъде изпратен като линк за изтегляне.",diff --git a/locales/de-DE/messenger.json b/locales/de-DE/messenger.jsonindex eaadb4e3e7e..7f4728729b8 100644--- a/locales/de-DE/messenger.json+++ b/locales/de-DE/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Status der proaktiven Nachricht konnte nicht geladen werden.","messenger.push.placeholder": "Schreiben Sie eine Nachricht, die an {{platform}} gesendet werden soll…","messenger.push.queued": "{{count}} Nachricht(en) in der Warteschlange werden zugestellt, nachdem Sie den Bot in {{platform}} kontaktiert haben.",+ "messenger.push.queuedBusyToast": "Eine andere Nachricht wird noch zugestellt – Ihre Nachricht ist dahinter in der Warteschlange. Schreiben Sie dem Bot in {{platform}}, um sie zu erhalten.",+ "messenger.push.queuedQuotaToast": "Keine Sendungen mehr in diesem Zeitfenster – Ihre Nachricht wurde in die Warteschlange gestellt. Schreiben Sie dem Bot in {{platform}}, um das Zeitfenster zurückzusetzen und die Nachricht zu erhalten.",+ "messenger.push.queuedRetryToast": "Ein Teil Ihrer Nachricht konnte nicht zugestellt werden – der Rest wurde in die Warteschlange gestellt und wird erneut versucht, nachdem Sie dem Bot in {{platform}} geschrieben 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.",diff --git a/locales/en-US/messenger.json b/locales/en-US/messenger.jsonindex 8688e6eb48d..2e10ddc909d 100644--- a/locales/en-US/messenger.json+++ b/locales/en-US/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Could not load proactive message status.","messenger.push.placeholder": "Write a message to send to {{platform}}…","messenger.push.queued": "{{count}} queued message(s) will be delivered after you message the bot in {{platform}}.",+ "messenger.push.queuedBusyToast": "Another message is still being delivered — yours is queued behind it. Message the bot in {{platform}} to receive it.",+ "messenger.push.queuedQuotaToast": "No sends left in this window — your message is queued. Message the bot in {{platform}} to reset the window and receive it.",+ "messenger.push.queuedRetryToast": "Part of your message could not be delivered — the rest is queued and will be retried 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.",diff --git a/locales/es-ES/messenger.json b/locales/es-ES/messenger.jsonindex 046b1826047..f3caa552d51 100644--- a/locales/es-ES/messenger.json+++ b/locales/es-ES/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "No se pudo cargar el estado del mensaje proactivo.","messenger.push.placeholder": "Escribe un mensaje para enviar a {{platform}}…","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.queuedBusyToast": "Otro mensaje aún está siendo entregado — el tuyo está en cola detrás de él. Envía un mensaje al bot en {{platform}} para recibirlo.",+ "messenger.push.queuedQuotaToast": "No quedan envíos en este período — tu mensaje está en cola. Envía un mensaje al bot en {{platform}} para reiniciar el período y recibirlo.",+ "messenger.push.queuedRetryToast": "Parte de tu mensaje no pudo ser entregado — el resto está en cola y se reintentará 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.",diff --git a/locales/fa-IR/messenger.json b/locales/fa-IR/messenger.jsonindex 7018fe77495..022431fea04 100644--- a/locales/fa-IR/messenger.json+++ b/locales/fa-IR/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "وضعیت پیام فعال بارگذاری نشد.","messenger.push.placeholder": "پیامی برای ارسال به {{platform}} بنویسید…","messenger.push.queued": "{{count}} پیام در صف قرار دارد و پس از ارسال پیام شما به ربات در {{platform}} تحویل داده خواهد شد.",+ "messenger.push.queuedBusyToast": "یک پیام دیگر هنوز در حال ارسال است — پیام شما در صف انتظار قرار گرفته است. برای دریافت آن، به ربات در {{platform}} پیام دهید.",+ "messenger.push.queuedQuotaToast": "ارسالی در این بازه زمانی باقی نمانده است — پیام شما در صف قرار گرفته است. به ربات در {{platform}} پیام دهید تا بازه زمانی تنظیم شود و پیام دریافت شود.",+ "messenger.push.queuedRetryToast": "بخشی از پیام شما ارسال نشد — باقی پیام در صف قرار گرفته و پس از پیام دادن به ربات در {{platform}} دوباره تلاش خواهد شد.","messenger.push.queuedToast": "پنجره ارسال بسته است — پیام شما در صف قرار گرفت. به ربات در {{platform}} پیام دهید تا آن را دریافت کنید.","messenger.push.resource.description": "فایل بهعنوان پیوست به حساب مرتبط شما در {{platform}} ارسال خواهد شد.","messenger.push.resource.oversizeFileHint": "این فایل از حد {{limit}} در {{platform}} فراتر رفته و به صورت یک لینک دانلود ارسال خواهد شد.",diff --git a/locales/fr-FR/messenger.json b/locales/fr-FR/messenger.jsonindex 4bba8c72b46..2e57ee58855 100644--- a/locales/fr-FR/messenger.json+++ b/locales/fr-FR/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Impossible de charger le statut des messages proactifs.","messenger.push.placeholder": "Écrivez un message à envoyer à {{platform}}…","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.queuedBusyToast": "Un autre message est en cours de livraison — le vôtre est en file d'attente derrière celui-ci. Envoyez un message au bot sur {{platform}} pour le recevoir.",+ "messenger.push.queuedQuotaToast": "Aucun envoi restant dans cette fenêtre — votre message est mis en file d'attente. Envoyez un message au bot sur {{platform}} pour réinitialiser la fenêtre et le recevoir.",+ "messenger.push.queuedRetryToast": "Une partie de votre message n'a pas pu être livrée — le reste est mis en file d'attente et sera réessayé 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.",diff --git a/locales/it-IT/messenger.json b/locales/it-IT/messenger.jsonindex fdf009d3ff9..2137b979471 100644--- a/locales/it-IT/messenger.json+++ b/locales/it-IT/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Impossibile caricare lo stato del messaggio proattivo.","messenger.push.placeholder": "Scrivi un messaggio da inviare a {{platform}}…","messenger.push.queued": "{{count}} messaggio/i in coda verrà/verranno consegnato/i dopo che avrai inviato un messaggio al bot su {{platform}}.",+ "messenger.push.queuedBusyToast": "Un altro messaggio è ancora in consegna — il tuo è in coda dietro di esso. Invia un messaggio al bot su {{platform}} per riceverlo.",+ "messenger.push.queuedQuotaToast": "Nessun invio rimasto in questa finestra temporale — il tuo messaggio è in coda. Invia un messaggio al bot su {{platform}} per reimpostare la finestra e riceverlo.",+ "messenger.push.queuedRetryToast": "Parte del tuo messaggio non è stata consegnata — il resto è in coda e verrà ritentato 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.",diff --git a/locales/ja-JP/messenger.json b/locales/ja-JP/messenger.jsonindex d38e373aac6..e09d0eb07db 100644--- a/locales/ja-JP/messenger.json+++ b/locales/ja-JP/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "プロアクティブメッセージのステータスを読み込めませんでした。","messenger.push.placeholder": "{{platform}}に送信するメッセージを入力してください…","messenger.push.queued": "{{count}}件のキューに入ったメッセージは、{{platform}}でボットにメッセージを送信した後に配信されます。",+ "messenger.push.queuedBusyToast": "別のメッセージがまだ送信中です — あなたのメッセージはその後ろにキューされています。{{platform}}でボットにメッセージを送信して受け取ってください。",+ "messenger.push.queuedQuotaToast": "このウィンドウでは送信可能なメッセージがありません — メッセージはキューに入れられました。ウィンドウをリセットしてメッセージを受信するには、{{platform}}でボットにメッセージを送信してください。",+ "messenger.push.queuedRetryToast": "メッセージの一部が配信できませんでした — 残りの部分はキューに入れられ、{{platform}}でボットにメッセージを送信した後に再試行されます。","messenger.push.queuedToast": "送信ウィンドウが閉じています — メッセージはキューに入れられました。{{platform}}でボットにメッセージを送信すると受信できます。","messenger.push.resource.description": "ファイルはリンクされた{{platform}}アカウントに添付ファイルとして送信されます。","messenger.push.resource.oversizeFileHint": "このファイルは{{platform}}の{{limit}}制限を超えているため、ダウンロードリンクとして送信されます。",diff --git a/locales/ko-KR/messenger.json b/locales/ko-KR/messenger.jsonindex a924d8446f1..5a2c2a968c4 100644--- a/locales/ko-KR/messenger.json+++ b/locales/ko-KR/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "능동 메시지 상태를 불러오지 못했습니다.","messenger.push.placeholder": "{{platform}}에 보낼 메시지를 작성하세요…","messenger.push.queued": "{{count}}개의 대기 중인 메시지가 {{platform}}에서 봇에게 메시지를 보낸 후 전달됩니다.",+ "messenger.push.queuedBusyToast": "다른 메시지가 아직 전달 중입니다 — 귀하의 메시지는 그 뒤에 대기 중입니다. {{platform}}에서 봇에게 메시지를 보내 이를 수신하세요.",+ "messenger.push.queuedQuotaToast": "이 창에서 보낼 수 있는 메시지가 없습니다. 메시지가 대기열에 추가되었습니다. {{platform}}에서 봇에게 메시지를 보내 창을 재설정하고 메시지를 받으세요.",+ "messenger.push.queuedRetryToast": "메시지의 일부를 전달할 수 없습니다. 나머지 메시지는 대기열에 추가되었으며 {{platform}}에서 봇에게 메시지를 보낸 후 다시 시도됩니다.","messenger.push.queuedToast": "전송 창이 닫혔습니다 — 메시지가 대기 중입니다. {{platform}}에서 봇에게 메시지를 보내면 받을 수 있습니다.","messenger.push.resource.description": "파일은 연결된 {{platform}} 계정에 첨부 파일로 전송됩니다.","messenger.push.resource.oversizeFileHint": "{{platform}}의 제한인 {{limit}}을 초과하여 이 파일은 다운로드 링크로 전송됩니다.",diff --git a/locales/nl-NL/messenger.json b/locales/nl-NL/messenger.jsonindex ee4fb92ae5b..12d83f65421 100644--- a/locales/nl-NL/messenger.json+++ b/locales/nl-NL/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Kon de status van het proactieve bericht niet laden.","messenger.push.placeholder": "Schrijf een bericht om te verzenden naar {{platform}}…","messenger.push.queued": "{{count}} bericht(en) in de wachtrij worden afgeleverd nadat je de bot een bericht stuurt in {{platform}}.",+ "messenger.push.queuedBusyToast": "Er wordt nog een ander bericht afgeleverd — jouw bericht staat in de wachtrij. Stuur een bericht naar de bot in {{platform}} om het te ontvangen.",+ "messenger.push.queuedQuotaToast": "Geen verzendmogelijkheden meer in dit venster — je bericht is in de wachtrij geplaatst. Stuur een bericht naar de bot in {{platform}} om het venster te resetten en het bericht te ontvangen.",+ "messenger.push.queuedRetryToast": "Een deel van je bericht kon niet worden afgeleverd — de rest is in de wachtrij geplaatst en wordt opnieuw geprobeerd nadat je de bot in {{platform}} een bericht stuurt.","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.",diff --git a/locales/pl-PL/messenger.json b/locales/pl-PL/messenger.jsonindex 5df3765d380..89e59d5f107 100644--- a/locales/pl-PL/messenger.json+++ b/locales/pl-PL/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Nie udało się załadować statusu wiadomości proaktywnych.","messenger.push.placeholder": "Napisz wiadomość do wysłania na {{platform}}…","messenger.push.queued": "{{count}} wiadomość(i) w kolejce zostanie dostarczona po wysłaniu wiadomości do bota na {{platform}}.",+ "messenger.push.queuedBusyToast": "Inna wiadomość jest nadal dostarczana — Twoja została umieszczona w kolejce za nią. Wyślij wiadomość do bota na {{platform}}, aby ją otrzymać.",+ "messenger.push.queuedQuotaToast": "Brak wysyłek w tym oknie — Twoja wiadomość została zakolejkowana. Napisz do bota na {{platform}}, aby zresetować okno i ją otrzymać.",+ "messenger.push.queuedRetryToast": "Część Twojej wiadomości nie mogła zostać dostarczona — reszta została zakolejkowana i zostanie ponownie wysłana po napisaniu 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.",diff --git a/locales/pt-BR/messenger.json b/locales/pt-BR/messenger.jsonindex 7524762f6f0..7f4b54eb563 100644--- a/locales/pt-BR/messenger.json+++ b/locales/pt-BR/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Não foi possível carregar o status da mensagem proativa.","messenger.push.placeholder": "Escreva uma mensagem para enviar ao {{platform}}…","messenger.push.queued": "{{count}} mensagem(ns) na fila será(ão) entregue(s) após você enviar uma mensagem ao bot no {{platform}}.",+ "messenger.push.queuedBusyToast": "Outra mensagem ainda está sendo entregue — a sua está na fila atrás dela. Envie uma mensagem ao bot no {{platform}} para recebê-la.",+ "messenger.push.queuedQuotaToast": "Sem envios restantes nesta janela — sua mensagem está na fila. Envie uma mensagem para o bot no {{platform}} para redefinir a janela e recebê-la.",+ "messenger.push.queuedRetryToast": "Parte da sua mensagem não pôde ser entregue — o restante está na fila e será reenviado após você enviar uma mensagem para o 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.",diff --git a/locales/ru-RU/messenger.json b/locales/ru-RU/messenger.jsonindex f7bb7314acc..1a6dd56ebe2 100644--- a/locales/ru-RU/messenger.json+++ b/locales/ru-RU/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Не удалось загрузить статус проактивного сообщения.","messenger.push.placeholder": "Напишите сообщение для отправки в {{platform}}…","messenger.push.queued": "{{count}} сообщение(й) в очереди будет доставлено после того, как вы отправите сообщение боту в {{platform}}.",+ "messenger.push.queuedBusyToast": "Другое сообщение все еще доставляется — ваше поставлено в очередь за ним. Напишите боту в {{platform}}, чтобы получить его.",+ "messenger.push.queuedQuotaToast": "Нет отправок в этом окне — ваше сообщение поставлено в очередь. Напишите боту в {{platform}}, чтобы сбросить окно и получить сообщение.",+ "messenger.push.queuedRetryToast": "Часть вашего сообщения не была доставлена — остальное поставлено в очередь и будет повторно отправлено после того, как вы напишете боту в {{platform}}.","messenger.push.queuedToast": "Окно отправки закрыто — ваше сообщение добавлено в очередь. Отправьте сообщение боту в {{platform}}, чтобы получить его.","messenger.push.resource.description": "Файл будет отправлен в виде вложения на ваш связанный аккаунт {{platform}}.","messenger.push.resource.oversizeFileHint": "Этот файл превышает лимит {{limit}} на {{platform}} и будет отправлен в виде ссылки для скачивания.",diff --git a/locales/tr-TR/messenger.json b/locales/tr-TR/messenger.jsonindex a2c3f2a55ca..9d60b9e820d 100644--- a/locales/tr-TR/messenger.json+++ b/locales/tr-TR/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Proaktif mesaj durumu yüklenemedi.","messenger.push.placeholder": "{{platform}}'a göndermek için bir mesaj yazın…","messenger.push.queued": "{{count}} bekleyen mesaj, {{platform}}'da bota mesaj gönderdikten sonra teslim edilecek.",+ "messenger.push.queuedBusyToast": "Başka bir mesaj hâlâ teslim ediliyor — sizin mesajınız onun arkasında sıraya alındı. Mesajı almak için {{platform}} üzerinde bota mesaj gönderin.",+ "messenger.push.queuedQuotaToast": "Bu zaman aralığında gönderim hakkınız kalmadı — mesajınız sıraya alındı. Zaman aralığını sıfırlamak ve mesajı almak için {{platform}} üzerinde bota mesaj gönderin.",+ "messenger.push.queuedRetryToast": "Mesajınızın bir kısmı teslim edilemedi — geri kalan kısmı sıraya alındı ve {{platform}} üzerinde bota mesaj gönderdikten sonra yeniden gönderilmeye çalışılacak.","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.",diff --git a/locales/vi-VN/messenger.json b/locales/vi-VN/messenger.jsonindex cc415cf728f..28434749619 100644--- a/locales/vi-VN/messenger.json+++ b/locales/vi-VN/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "Không thể tải trạng thái tin nhắn chủ động.","messenger.push.placeholder": "Viết tin nhắn để gửi đến {{platform}}…","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.queuedBusyToast": "Một tin nhắn khác vẫn đang được gửi — tin nhắn của bạn đang được xếp hàng phía sau. Nhắn tin cho bot trên {{platform}} để nhận tin nhắn.",+ "messenger.push.queuedQuotaToast": "Không còn lượt gửi nào trong khoảng thời gian này — tin nhắn của bạn đã được xếp hàng chờ. Nhắn tin cho bot trên {{platform}} để đặt lại khoảng thời gian và nhận tin nhắn.",+ "messenger.push.queuedRetryToast": "Một phần tin nhắn của bạn không thể được gửi — phần còn lại đã được xếp hàng chờ và sẽ được thử lạ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.",diff --git a/locales/zh-CN/messenger.json b/locales/zh-CN/messenger.jsonindex 63a6ce5d1f3..ac5fc219c03 100644--- a/locales/zh-CN/messenger.json+++ b/locales/zh-CN/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "无法加载主动推送状态。","messenger.push.placeholder": "输入要发送到 {{platform}} 的消息…","messenger.push.queued": "{{count}} 条消息排队中,你在 {{platform}} 中给机器人发送消息后将自动送达。",+ "messenger.push.queuedBusyToast": "另一条消息正在发送中,你的消息已排在其后。在 {{platform}} 中给机器人发送消息即可收到。",+ "messenger.push.queuedQuotaToast": "本发送窗口的剩余条数不足,消息已排队。在 {{platform}} 中给机器人发送消息即可重置窗口并收到它。",+ "messenger.push.queuedRetryToast": "部分内容未能送达,剩余部分已排队。在 {{platform}} 中给机器人发送消息后将自动重试。","messenger.push.queuedToast": "发送窗口未打开,消息已排队。在 {{platform}} 中给机器人发送消息后即可收到。","messenger.push.resource.description": "文件将作为附件发送到你绑定的 {{platform}} 账号。","messenger.push.resource.oversizeFileHint": "文件超过 {{platform}} 的 {{limit}} 限制,将以下载链接形式发送。",diff --git a/locales/zh-TW/messenger.json b/locales/zh-TW/messenger.jsonindex 9a8b9f47d51..5a5ca75b085 100644--- a/locales/zh-TW/messenger.json+++ b/locales/zh-TW/messenger.json@@ -73,6 +73,9 @@"messenger.push.loadFailed": "無法載入主動訊息狀態。","messenger.push.placeholder": "撰寫訊息以發送到 {{platform}}…","messenger.push.queued": "{{count}} 則排隊中的訊息將在您於 {{platform}} 與機器人互動後送達。",+ "messenger.push.queuedBusyToast": "另一則訊息仍在傳送中——您的訊息已排隊等待。請在 {{platform}} 上向機器人發送訊息以接收它。",+ "messenger.push.queuedQuotaToast": "此時段內已無可用發送次數——您的訊息已排入佇列。請在 {{platform}} 上向機器人發送訊息以重置時段並接收訊息。",+ "messenger.push.queuedRetryToast": "您的部分訊息無法送達——其餘部分已排入佇列,並將在您於 {{platform}} 上向機器人發送訊息後重新嘗試送出。","messenger.push.queuedToast": "發送窗口已關閉 — 您的訊息已排隊。請在 {{platform}} 與機器人互動以接收訊息。","messenger.push.resource.description": "檔案將作為附件發送到您連結的 {{platform}} 帳戶。","messenger.push.resource.oversizeFileHint": "此檔案超過 {{platform}} 的 {{limit}} 限制,將以下載連結的形式發送。",diff --git a/packages/const/src/bot.ts b/packages/const/src/bot.tsindex caf8592ac00..db723b99e7a 100644--- a/packages/const/src/bot.ts+++ b/packages/const/src/bot.ts@@ -28,7 +28,11 @@ export const MIN_BOT_HISTORY_LIMIT = 1;* 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.+ * - slack: 50MB — `files.upload` v2 itself allows 1GB, but every sender+ * materializes the file in memory to upload it, so the real ceiling is+ * MAX_IN_MEMORY_ATTACHMENT_BYTES. Budgeting at 1GB made the 50MB–1GB band+ * pass the budget pass as an upload and then fail during materialization,+ * dropping the attachment with neither a file nor a download link.* - 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.@@ -57,7 +61,7 @@ export const MESSENGER_ATTACHMENT_BUDGETS: Record<MessengerAttachmentBudget> = {discord: { fileMaxBytes: 10 * MB, imageMaxBytes: 10 * MB, textMaxChars: 2000 },- slack: { fileMaxBytes: 1024 * MB, imageMaxBytes: 1024 * MB, textMaxChars: 3000 },+ slack: { fileMaxBytes: 50 * MB, imageMaxBytes: 50 * 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.tsindex 4783e7f1a48..b82b8503598 100644--- a/packages/locales/src/default/messenger.ts+++ b/packages/locales/src/default/messenger.ts@@ -134,6 +134,12 @@ export default {'messenger.push.placeholder': 'Write a message to send to {{platform}}…','messenger.push.queued':'{{count}} queued message(s) will be delivered after you message the bot in {{platform}}.',+ 'messenger.push.queuedBusyToast':+ 'Another message is still being delivered — yours is queued behind it. Message the bot in {{platform}} to receive it.',+ 'messenger.push.queuedQuotaToast':+ 'No sends left in this window — your message is queued. Message the bot in {{platform}} to reset the window and receive it.',+ 'messenger.push.queuedRetryToast':+ 'Part of your message could not be delivered — the rest is queued and will be retried 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':diff --git a/src/components/Avatar/fallback.test.ts b/src/components/Avatar/fallback.test.tsindex 6d7d94f4cc2..315e46351c7 100644--- a/src/components/Avatar/fallback.test.ts+++ b/src/components/Avatar/fallback.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getAvatarBackground, getAvatarInitials, remoteAvatarSrc, resolveAvatar } from './fallback';+import { getAvatarInitials, remoteAvatarSrc, resolveAvatar } from './fallback';describe('getAvatarInitials', () => {it('returns nothing for a missing name', () => {@@ -32,25 +32,6 @@ describe('getAvatarInitials', () => {});});-describe('getAvatarBackground', () => {- it('returns nothing without a seed', () => {- expect(getAvatarBackground()).toBeUndefined();- expect(getAvatarBackground(' ')).toBeUndefined();- });-- it('is stable for the same seed', () => {- expect(getAvatarBackground('贺素青')).toBe(getAvatarBackground('贺素青'));- expect(getAvatarBackground('Claude Code')).toBe(getAvatarBackground('Claude Code'));- });-- it('spreads different seeds across the palette', () => {- const seeds = ['贺素青', 'Claude Code', 'lobehub', 'agent-default', 'Verify', 'Inbox'];- const colors = new Set(seeds.map((seed) => getAvatarBackground(seed)));-- expect(colors.size).toBeGreaterThan(1);- });-});-describe('resolveAvatar', () => {it('keeps a working avatar and its background untouched', () => {expect(@@ -66,7 +47,16 @@ describe('resolveAvatar', () => {});expect(avatar).toBe('贺');- expect(background).toBe(getAvatarBackground('贺素青'));+ // The name picks the glyphs, never the color — the tile stays the Avatar's+ // own neutral grey so a random hue never reads as status.+ expect(background).toBeUndefined();+ });++ it('gives every unconfigured name the same neutral tile', () => {+ const seeds = ['贺素青', 'Claude Code', 'lobehub', 'agent-default', 'Verify', 'Inbox'];+ const backgrounds = new Set(seeds.map((name) => resolveAvatar({ name }).background));++ expect(backgrounds).toEqual(new Set([undefined]));});it('falls back when there is no avatar at all', () => {@@ -78,8 +68,7 @@ describe('resolveAvatar', () => {const broken = resolveAvatar({ avatar: '/avatars/agent-default.png', isBroken: true });expect(broken.avatar).toBe('');- // The URL still seeds a color, so unnamed avatars aren't all the same grey.- expect(broken.background).toBe(getAvatarBackground('/avatars/agent-default.png'));+ expect(broken.background).toBeUndefined();});it('keeps an explicitly chosen background even when the image is broken', () => {@@ -114,13 +103,15 @@ describe('resolveAvatar background sentinels', () => {name: '林知微',});- expect(background).toBe(getAvatarBackground('林知微'));+ // Dropped rather than forwarded, so the Avatar paints `colorBorder` behind+ // the initials instead of leaving them on the page background.+ expect(background).toBeUndefined();});it('also ignores rgba(0, 0, 0, 0)', () => {- expect(resolveAvatar({ background: 'rgba(0, 0, 0, 0)', name: 'Verify' }).background).toBe(- getAvatarBackground('Verify'),- );+ expect(+ resolveAvatar({ background: 'rgba(0, 0, 0, 0)', name: 'Verify' }).background,+ ).toBeUndefined();});it('keeps a transparent background behind a working image', () => {diff --git a/src/components/Avatar/fallback.ts b/src/components/Avatar/fallback.tsindex 4250158e44f..142c94be01c 100644--- a/src/components/Avatar/fallback.ts+++ b/src/components/Avatar/fallback.ts@@ -1,5 +1,3 @@-import { primaryColorsSwatches } from '@lobehub/ui';-/*** Characters that already read as a whole word on their own — one of them is* enough for an avatar, two would be unreadable at 16px.@@ -28,30 +26,11 @@ export const getAvatarInitials = (name?: string | null): string => {return words[0].slice(0, 2).toUpperCase();};-/**- * Deterministic FNV-1a so the same name always lands on the same swatch — an- * agent keeps its color across sessions, devices and list positions.- */-const hash = (seed: string): number => {- let value = 0x81_1c_9d_c5;- for (let i = 0; i < seed.length; i++) {- value ^= seed.codePointAt(i)!;- value = Math.imul(value, 0x01_00_01_93);- }- return Math.abs(value);-};--export const getAvatarBackground = (seed?: string | null): string | undefined => {- const text = seed?.trim();- if (!text) return undefined;-- return primaryColorsSwatches[hash(text) % primaryColorsSwatches.length];-};-/*** Selectors hand a literal `'transparent'` (or `rgba(0,0,0,0)`) down as "no* color chosen". Behind a real image that is correct; behind fallback initials- * it renders unreadable text on the page background, so it counts as absent.+ * it renders unreadable text on the page background, so it counts as absent —+ * dropping it lets the Avatar fall back to its neutral `colorBorder` tile.*/const BLANK_BACKGROUNDS = new Set(['transparent', 'rgba(0,0,0,0)', 'none']);@@ -79,8 +58,9 @@ interface ResolveAvatarParams<T> {/*** Decide what the Avatar actually renders. A missing or broken image falls back- * to the name's initials over a hashed background, so the avatar still carries- * the identity instead of collapsing into an anonymous grey box.+ * to the name's initials, so the avatar still carries the identity. The tile+ * itself stays neutral unless a background was explicitly chosen — a color+ * derived from the name reads as meaningful when it isn't.*/export const resolveAvatar = <T>({avatar,@@ -97,7 +77,8 @@ export const resolveAvatar = <T>({// Only a real name makes initials; a URL would render as its own first// character ("/"), which says even less than an empty tile.avatar: getAvatarInitials(label),- background:- usableBackground(background) || getAvatarBackground(label || remoteAvatarSrc(avatar)),+ // No explicit color means no color: the Avatar paints its own `colorBorder`+ // tile, the same neutral grey every unconfigured avatar gets.+ background: usableBackground(background),};};diff --git a/src/components/Avatar/index.tsx b/src/components/Avatar/index.tsxindex c10cdb1b836..fed61fe230a 100644--- a/src/components/Avatar/index.tsx+++ b/src/components/Avatar/index.tsx@@ -8,8 +8,8 @@ import { useBrokenSrc } from './useBrokenSrc';export interface AvatarProps extends LobeAvatarProps {/**- * Seed for the fallback initials and background color. Defaults to `title`;- * pass it when the visible name differs from the tooltip title.+ * Seed for the fallback initials. Defaults to `title`; pass it when the+ * visible name differs from the tooltip title.*/name?: string;}@@ -19,9 +19,9 @@ export interface AvatarProps extends LobeAvatarProps {** `@lobehub/ui`'s Avatar falls back to `String(title).slice(0, 2)`, which* renders a literal "UN" — the first letters of `"undefined"` — whenever the- * image 404s and no title was passed. This wrapper derives the initials and a- * stable hashed background from the name instead, so a missing image still- * reads as *this* agent rather than as a broken one.+ * image 404s and no title was passed. This wrapper derives the initials from+ * the name instead, so a missing image still reads as *this* agent rather than+ * as a broken one.** The image element is rendered here rather than left to the library so this* component owns the `error` event. Probing the URL separately would let thediff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.tsindex 53fcde392c4..d43fc6d1ab9 100644--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.ts@@ -32,8 +32,8 @@ export const resolveSenderIdentity = ({const senderName = sender?.fullName || sender?.username || '';const title = isOwn ? senderName || selfTitle || '' : senderName || unknownLabel;// Left undefined on purpose for an avatar-less other member: `@/components/Avatar`- // derives initials and a hashed background from the resolved `title`, which is a- // far better placeholder than borrowing the viewer's picture.+ // derives initials from the resolved `title`, which is a far better+ // placeholder than borrowing the viewer's picture.const avatar = sender?.avatar || (isOwn ? selfAvatar : undefined);return { avatar, isOwn, title };diff --git a/src/features/Messenger/IntegrationDetail/MessengerPush.tsx b/src/features/Messenger/IntegrationDetail/MessengerPush.tsxindex 1fb0336ee99..88e6aeb9afc 100644--- a/src/features/Messenger/IntegrationDetail/MessengerPush.tsx+++ b/src/features/Messenger/IntegrationDetail/MessengerPush.tsx@@ -11,7 +11,7 @@ import { messengerKeys } from '@/libs/swr/keys';import { messengerService } from '@/services/messenger';import type { MessengerPlatform } from '../constants';-import { getMessengerErrorMessage } from '../i18n';+import { getMessengerErrorMessage, getMessengerQueuedToast } from '../i18n';import { MessengerPushWindowState } from './MessengerPushWindowState';import { styles } from './shared';@@ -92,7 +92,7 @@ export const MessengerPushSection = memo<MessengerPushSectionProps>(break;}case 'queued': {- toast.info(t('messenger.push.queuedToast', { platform: name }));+ toast.info(getMessengerQueuedToast(t, name, result.reason));setContent('');break;}diff --git a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx b/src/features/Messenger/PushResourceModal/PushResourceContent.tsxindex 57961567770..559b3f2aaa5 100644--- a/src/features/Messenger/PushResourceModal/PushResourceContent.tsx+++ b/src/features/Messenger/PushResourceModal/PushResourceContent.tsx@@ -13,7 +13,7 @@ import { messengerService } from '@/services/messenger';import { formatSize } from '@/utils/format';import type { MessengerPlatform } from '../constants';-import { getMessengerErrorMessage } from '../i18n';+import { getMessengerErrorMessage, getMessengerQueuedToast } from '../i18n';import { MessengerPushWindowState } from '../IntegrationDetail/MessengerPushWindowState';import { resolveAttachmentType } from './resolveAttachmentType';@@ -123,7 +123,7 @@ export const PushResourceContent = memo<PushResourceModalProps>(break;}case 'queued': {- toast.info(t('messenger.push.queuedToast', { platform: platformName }));+ toast.info(getMessengerQueuedToast(t, platformName, result.reason));close();break;}diff --git a/src/features/Messenger/i18n.ts b/src/features/Messenger/i18n.tsindex ebe1ded1354..04b7996110e 100644--- a/src/features/Messenger/i18n.ts+++ b/src/features/Messenger/i18n.ts@@ -1,6 +1,10 @@import type { TFunction } from 'i18next';+import type { MessengerPushResult } from '@/server/services/messenger/push';+type MessengerT = TFunction<'messenger'>;+/** Why a push had to be queued — kept in sync with the server by derivation. */+type MessengerPushQueueReason = NonNullable<MessengerPushResult['reason']>;export type MessengerTranslationKey = `messenger.${string}` | `verify.${string}`;const SLACK_INSTALL_ERROR_REASON_KEYS = {@@ -36,6 +40,28 @@ const getMessengerTranslationKey = (error: unknown): MessengerTranslationKey | u}};+const QUEUED_TOAST_KEYS = {+ delivery_in_progress: 'messenger.push.queuedBusyToast',+ quota_exhausted: 'messenger.push.queuedQuotaToast',+ send_failed: 'messenger.push.queuedRetryToast',+ window_closed: 'messenger.push.queuedToast',+} as const satisfies Record<MessengerPushQueueReason, MessengerTranslationKey>;++/**+ * Toast key for a `queued` push result. The server distinguishes WHY the+ * message had to queue (`reason`); the default key claims "the send window is+ * closed", which is a lie for the quota / partial-failure paths and confused+ * users whose window was visibly open.+ *+ * `reason` is optional because a platform without a send window never sets one+ * — those fall back to the plain "window closed" copy.+ */+export const getMessengerQueuedToast = (+ t: MessengerT,+ platform: string,+ reason?: MessengerPushQueueReason,+): string => t(QUEUED_TOAST_KEYS[reason ?? 'window_closed'], { platform });+export const getMessengerErrorMessage = (error: unknown,t: MessengerT,diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsxnew file mode 100644index 00000000000..fd251cbaed7--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx@@ -0,0 +1,72 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++interface SendToMessengerParams {+ enabled: boolean;+ file: { fileType?: string; id: string; name?: string; size?: number };+}++const mocks = vi.hoisted(() => ({+ useSendToMessengerMenuItem: vi.fn((_params: SendToMessengerParams) => undefined),+}));++vi.mock('@/features/Messenger/PushResourceModal/useSendToMessengerMenuItem', () => ({+ useSendToMessengerMenuItem: mocks.useSendToMessengerMenuItem,+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.example.com' }));+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));+vi.mock('@/hooks/useResourceManageable', () => ({ useResourceManageable: () => true }));+vi.mock('@/features/ResourceManager/components/KnowledgeBaseListProvider', () => ({+ useKnowledgeBaseListContext: () => [],+}));+vi.mock('@/store/user', () => ({ useUserStore: () => 'user-1' }));+vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: { userId: vi.fn() } }));+vi.mock('@/store/file', () => ({+ useFileStore: () => ({+ deleteResource: vi.fn(),+ moveResource: vi.fn(),+ publishFileToWorkspace: vi.fn(),+ refreshFileList: vi.fn(),+ setFileVisibility: vi.fn(),+ }),+}));+vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: () => [vi.fn(), vi.fn()] }));+vi.mock('@/store/tree', () => ({ useTreeStore: () => vi.fn() }));++const { useFileItemDropdown } = await import('./useFileItemDropdown');++const baseParams = {+ fileType: 'markdown',+ filename: 'notes.md',+ id: 'resource-id',+ size: 10,+ url: 'https://storage.example.com/notes.md',+};++const pushedFile = () => mocks.useSendToMessengerMenuItem.mock.calls.at(-1)![0].file;++describe('useFileItemDropdown — messenger push id', () => {+ it('sends the underlying fileId, not the list id, for a file behind a derived page', () => {+ // Regression: the unified resource list keys such a row by the PAGE id, but+ // the server resolves the attachment by `files.id` — pushing sent an id the+ // file table has never seen and the call failed with NOT_FOUND.+ renderHook(() => useFileItemDropdown({ ...baseParams, fileId: 'file-id' } as any));++ expect(pushedFile().id).toBe('file-id');+ });++ it('falls back to the row id when there is no separate fileId', () => {+ renderHook(() => useFileItemDropdown({ ...baseParams, fileId: undefined } as any));++ expect(pushedFile().id).toBe('resource-id');+ });++ it('falls back to the row id when fileId is null', () => {+ // `toTreeItem` carries `fileId` straight from the API, which yields null+ // (not undefined) for rows with no backing file.+ renderHook(() => useFileItemDropdown({ ...baseParams, fileId: null } as any));++ expect(pushedFile().id).toBe('resource-id');+ });+});diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsxindex 52a9759656e..96f5c97889b 100644--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx@@ -39,6 +39,13 @@ import { openMoveToFolderModal } from '../MoveToFolderModal';interface UseFileItemDropdownParams {enabled?: boolean;+ /**+ * The underlying `files.id` when the row is a file. The unified resource+ * list addresses a file that backs a derived page by the PAGE id+ * (`COALESCE(d.id, f.id)` in KnowledgeRepo), so `id` alone cannot be used+ * for file-table lookups such as the messenger push.+ */+ fileId?: string | null;filename: string;fileType: string;id: string;@@ -62,6 +69,7 @@ interface UseFileItemDropdownReturn {* Shared with folder tree and explorer*/export const useFileItemDropdown = ({+ fileId,id,libraryId,url,@@ -123,10 +131,12 @@ export const useFileItemDropdown = ({(sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE);// Pages/documents have no storage URL to attach, so only real files get the- // "Send to chat platform" entry.+ // "Send to chat platform" entry. The server resolves the attachment by+ // `files.id`, but a file that backs a derived page is listed under the PAGE+ // id — always prefer the row's underlying `fileId` when it carries one.const sendToMessengerItem = useSendToMessengerMenuItem({enabled: !isFolder && !isPage && !!url,- file: { fileType, id, name: filename, size },+ file: { fileType, id: fileId ?? 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.tsxindex 0dba9d7e10c..6a097ecb3a7 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx@@ -237,6 +237,7 @@ const FileListItem = ({slug,});const { menuItems } = useFileItemDropdown({+ fileId,fileType,filename: name,id,diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsxindex 004b6b308fc..de219c9365e 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx@@ -388,6 +388,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(}, [isMarkdown, isPage, url, isInView, markdownContent, id]);const { menuItems } = useFileItemDropdown({+ fileId,fileType,filename: name,id,diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsxindex e8e9f70c15f..8fcb3c691e8 100644--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx@@ -109,6 +109,7 @@ export const HierarchyNode = memo<HierarchyNodeProps>(}, [item.name]);const { menuItems } = useFileItemDropdown({+ fileId: item.fileId,fileType: item.fileType,filename: item.name,id: item.id,diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.tsindex 9fbddf8841c..e5b96e2f5ee 100644--- a/src/store/tree/actions.ts+++ b/src/store/tree/actions.ts@@ -16,6 +16,7 @@ export const sortTreeItems = <T extends TreeItem>(items: T[]): T[] => {};export const toTreeItem = (item: {+ fileId?: string | null;fileType: string;id: string;metadata?: Record<string, any> | null;@@ -27,6 +28,7 @@ export const toTreeItem = (item: {userId?: string | null;visibility?: 'private' | 'public' | null;}): TreeItem => ({+ fileId: item.fileId,fileType: item.fileType,id: item.id,isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,diff --git a/src/store/tree/store.ts b/src/store/tree/store.tsindex 3825de47d3c..80982f8581c 100644--- a/src/store/tree/store.ts+++ b/src/store/tree/store.ts@@ -38,6 +38,7 @@ useFileStore.subscribe((state) => {parentKey,resourceList.map((item) =>toTreeItem({+ fileId: item.fileId,fileType: item.fileType,id: item.id,metadata: item.metadata,diff --git a/src/store/tree/types.ts b/src/store/tree/types.tsindex 57e9140b920..01c5f456f07 100644--- a/src/store/tree/types.ts+++ b/src/store/tree/types.ts@@ -1,6 +1,12 @@import type { StoreHandle } from '@/store/utils/optimisticEngine';export interface TreeItem {+ /**+ * Underlying `files.id` for file nodes. The unified resource list addresses+ * a file that backs a derived page by the page id, so file-table lookups+ * (e.g. the messenger push) must go through this instead of `id`.+ */+ fileId?: string | null;fileType: string;id: string;isFolder: boolean;