Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: attach PDF, markdown, and text files in the agent chat (#243)

Croff0b6dca2149e9
diff --git a/apps/api/package.json b/apps/api/package.json
index c6570a72..24cb1a48 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -22,6 +22,7 @@
"@aws-sdk/client-s3": "^3.1109.0",
"@elysiajs/cors": "^1.4.2",
"@elysiajs/swagger": "^1.3.1",
+ "@firecrawl/pdf-inspector": "^1.17.0",
"@mastra/core": "^1.58.0",
"@mastra/memory": "^1.26.1",
"@mastra/pg": "^1.20.0",
diff --git a/apps/api/src/modules/agents/chat/service.ts b/apps/api/src/modules/agents/chat/service.ts
index afd4760e..feeb44da 100644
--- a/apps/api/src/modules/agents/chat/service.ts
+++ b/apps/api/src/modules/agents/chat/service.ts
@@ -11,7 +11,7 @@ import {
type ContextUsage,
} from '../chat-usage';
import { intEnv } from '../core/helpers/env';
-import { chartPreamble, projectPreamble } from '../core/prompt/framing';
+import { attachmentPreamble, chartPreamble, projectPreamble } from '../core/prompt/framing';
import { peoplePreamble, type Person } from '../core/prompt/run-context';
import type { ChatMessagePage, ChatPart, ChatThreadPage } from '../model';
import { newChatThreadId } from '../core/runtime/thread-ids';
@@ -434,6 +434,7 @@ function buildSystemPrompt(agent: RunnerAgent, requester: Person): string {
projectPreamble({ key: agent.projectKey, name: agent.projectName }) +
chatModePreamble() +
chartPreamble() +
+ attachmentPreamble() +
peoplePreamble({ requester }) +
(instructions ? `## Instructions\n${instructions}\n` : '')
);
diff --git a/apps/api/src/modules/agents/core/index.ts b/apps/api/src/modules/agents/core/index.ts
index aef7fa51..d8b3af2f 100644
--- a/apps/api/src/modules/agents/core/index.ts
+++ b/apps/api/src/modules/agents/core/index.ts
@@ -35,7 +35,7 @@ import {
} from './model';
import { runAgent, streamAgent, type AgentRunEvent, type RunOpts } from './runtime';
import { peoplePreamble } from './prompt/run-context';
-import { chartPreamble } from './prompt/framing';
+import { attachmentPreamble, chartPreamble } from './prompt/framing';
import type { SessionUser } from '#shared/auth-context';
import { listAgentRuns } from './run-queue';
import {
@@ -66,6 +66,7 @@ function chatRunOpts(user: SessionUser | null, agentId: number, threadId?: strin
threadId: threadId ?? null,
contextPreamble:
chartPreamble() +
+ attachmentPreamble() +
peoplePreamble({
requester: {
name: user?.name ?? caller.email ?? 'User',
diff --git a/apps/api/src/modules/agents/core/prompt/framing.ts b/apps/api/src/modules/agents/core/prompt/framing.ts
index db8ca873..6adb4326 100644
--- a/apps/api/src/modules/agents/core/prompt/framing.ts
+++ b/apps/api/src/modules/agents/core/prompt/framing.ts
@@ -159,6 +159,18 @@ export function chartPreamble(): string {
].join('\n');
}
+// Only the chat paths carry this: a file is attached to a chat message, so an
+// autonomous run never meets the marker.
+export function attachmentPreamble(): string {
+ return [
+ '## Attached files',
+ 'A [file: "name" (attachment id: …)] marker in the person\'s message means they attached',
+ 'that file. Read it with the read_chat_attachment tool.',
+ '',
+ '',
+ ].join('\n');
+}
+
export function peopleContext(run: RunForPrompt): string {
const requester: Person | null = run.requesterName
? { name: run.requesterName, username: run.requesterUsername ?? null }
diff --git a/apps/api/src/modules/chat-attachments/__tests__/fixtures/scanned.pdf b/apps/api/src/modules/chat-attachments/__tests__/fixtures/scanned.pdf
new file mode 100644
index 00000000..51d783c8
Binary files /dev/null and b/apps/api/src/modules/chat-attachments/__tests__/fixtures/scanned.pdf differ
diff --git a/apps/api/src/modules/chat-attachments/__tests__/fixtures/text.pdf b/apps/api/src/modules/chat-attachments/__tests__/fixtures/text.pdf
new file mode 100644
index 00000000..f388c3d1
Binary files /dev/null and b/apps/api/src/modules/chat-attachments/__tests__/fixtures/text.pdf differ
diff --git a/apps/api/src/modules/chat-attachments/__tests__/integration/chat-attachments.test.ts b/apps/api/src/modules/chat-attachments/__tests__/integration/chat-attachments.test.ts
index fa6c8f80..e87b03c4 100644
--- a/apps/api/src/modules/chat-attachments/__tests__/integration/chat-attachments.test.ts
+++ b/apps/api/src/modules/chat-attachments/__tests__/integration/chat-attachments.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
+import { readFileSync } from 'node:fs';
import { api, authedApi } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
@@ -14,6 +15,15 @@ async function setup() {
return { asOwner };
}
+function uploadPdf(client: ReturnType<typeof authedApi>, fixture: string) {
+ const bytes = readFileSync(new URL(`../fixtures/${fixture}`, import.meta.url));
+ return client.projects({ projectKey: 'MKT' })['chat-attachments'].post({
+ filename: fixture,
+ contentBase64: bytes.toString('base64'),
+ contentType: 'application/pdf',
+ });
+}
+
function upload(client: ReturnType<typeof authedApi>, filename: string, text: string) {
return client.projects({ projectKey: 'MKT' })['chat-attachments'].post({
filename,
@@ -48,19 +58,61 @@ describe('chat attachments', () => {
});
});
- it('reads a text file as an excerpt', async () => {
+ it('reads a text file in full, however long', async () => {
const { asOwner } = await setup();
+ const long = 'line one\nline two\n' + 'x'.repeat(10_000);
const uploaded = await asOwner.projects({ projectKey: 'MKT' })['chat-attachments'].post({
filename: 'server.log',
- contentBase64: Buffer.from('line one\nline two').toString('base64'),
+ contentBase64: Buffer.from(long).toString('base64'),
contentType: 'text/plain',
});
expect(uploaded.status).toBe(201);
const read = await asOwner['chat-attachments']({ publicId: uploaded.data!.id }).get();
- expect(read.data!.text).toBe('line one\nline two');
+ expect(read.data!.text).toBe(long);
expect(read.data!.table).toBeUndefined();
});
+ // A browser reports no type for a .md file on some platforms; the extension
+ // has to answer for it, or the instance allowlist refuses the upload.
+ it('accepts a markdown file the browser could not type', async () => {
+ const { asOwner } = await setup();
+ const uploaded = await asOwner.projects({ projectKey: 'MKT' })['chat-attachments'].post({
+ filename: 'spec.md',
+ contentBase64: Buffer.from('# Spec\n\nThe body.').toString('base64'),
+ });
+ expect(uploaded.status).toBe(201);
+ expect(uploaded.data).toMatchObject({ contentType: 'text/markdown' });
+ const read = await asOwner['chat-attachments']({ publicId: uploaded.data!.id }).get();
+ expect(read.data!.text).toBe('# Spec\n\nThe body.');
+ });
+
+ it('stores a text PDF as the markdown it converts to', async () => {
+ const { asOwner } = await setup();
+ const uploaded = await uploadPdf(asOwner, 'text.pdf');
+ expect(uploaded.status).toBe(201);
+ expect(uploaded.data).toMatchObject({
+ filename: 'text.md',
+ contentType: 'text/markdown',
+ });
+
+ const read = await asOwner['chat-attachments']({ publicId: uploaded.data!.id }).get();
+ expect(read.data!.text).toContain('# Release Notes');
+ expect(read.data!.text).toContain('accepts documents as well as spreadsheets');
+
+ // The public link serves the markdown, not the discarded PDF.
+ const raw = await api['chat-attachments']({ publicId: uploaded.data!.id }).raw.get({
+ query: { download: '1' },
+ });
+ expect(String(raw.data)).toBe(read.data!.text!);
+ });
+
+ it('refuses a scanned PDF, naming the missing text layer', async () => {
+ const { asOwner } = await setup();
+ const refused = await uploadPdf(asOwner, 'scanned.pdf');
+ expect(refused.status).toBe(400);
+ expect(refused.error!.value).toMatchObject({ error: expect.stringContaining('no text layer') });
+ });
+
it('rejects an empty upload', async () => {
const { asOwner } = await setup();
// The schema refuses an empty string...
diff --git a/apps/api/src/modules/chat-attachments/__tests__/unit/pdf.test.ts b/apps/api/src/modules/chat-attachments/__tests__/unit/pdf.test.ts
new file mode 100644
index 00000000..33ef9f40
--- /dev/null
+++ b/apps/api/src/modules/chat-attachments/__tests__/unit/pdf.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect } from 'bun:test';
+import { stripPdfImagePlaceholders } from '../../pdf';
+
+describe('pdf image placeholders', () => {
+ it('drops the placeholders and the blank lines they leave behind', () => {
+ const markdown = [
+ '# Report',
+ '',
+ '![image](pdf-image://0)',
+ '',
+ 'The first paragraph.',
+ '',
+ '![](pdf-image://12)',
+ '',
+ 'The last paragraph.',
+ ].join('\n');
+ expect(stripPdfImagePlaceholders(markdown)).toBe(
+ '# Report\n\nThe first paragraph.\n\nThe last paragraph.',
+ );
+ });
+
+ it('leaves a real image link alone', () => {
+ const markdown = '![chart](https://example.com/chart.png)';
+ expect(stripPdfImagePlaceholders(markdown)).toBe(markdown);
+ });
+});
diff --git a/apps/api/src/modules/chat-attachments/index.ts b/apps/api/src/modules/chat-attachments/index.ts
index 0cdcb795..1ec93d6a 100644
--- a/apps/api/src/modules/chat-attachments/index.ts
+++ b/apps/api/src/modules/chat-attachments/index.ts
@@ -22,6 +22,7 @@ import {
rawAttachmentQuery,
uploadChatAttachmentBody,
} from './model';
+import { pdfToMarkdown } from './pdf';
import {
createChatAttachment,
getChatAttachmentByPublicId,
@@ -63,6 +64,13 @@ async function assertUploadAllowed(
}
}
+// A browser reports no type for a .md or .txt file on some platforms, and the
+// instance allowlist matches on the type, so the extension answers for it.
+const EXTENSION_TYPES: Record<string, string> = {
+ md: 'text/markdown',
+ txt: 'text/plain',
+};
+
// Object keys are grouped by project so a project's bytes sit under one prefix in
// the bucket, which is what makes per-project listing, cleanup, and policies
// possible. The original filename stays the last key segment so the extension is
@@ -106,13 +114,24 @@ export const chatAttachmentRoutes = new Elysia({
if (bytes.length === 0) {
throw new HttpError(400, 'contentBase64 is empty or not valid base64');
}
- const filename = body.filename;
- const contentType = body.contentType || 'application/octet-stream';
+ let filename = body.filename;
+ const extension = filename.toLowerCase().split('.').pop() ?? '';
+ let contentType =
+ body.contentType || EXTENSION_TYPES[extension] || 'application/octet-stream';
await assertUploadAllowed(await getStorageSettings(), project.id, bytes.length, contentType);
+ // A PDF is stored as the Markdown it converts to: the original is
+ // discarded, so the row, the download link, and the agent all see text.
+ let content = bytes;
+ if (/\.pdf$/i.test(filename) || contentType === 'application/pdf') {
+ content = Buffer.from(await pdfToMarkdown(bytes), 'utf8');
+ filename = filename.replace(/\.pdf$/i, '') + '.md';
+ contentType = 'text/markdown';
+ }
+
const key = chatAttachmentKey(project.id, filename);
try {
- await putObject(key, bytes, contentType);
+ await putObject(key, content, contentType);
} catch (err) {
throw new HttpError(502, `Object store error: ${err instanceof Error ? err.message : err}`);
}
@@ -123,7 +142,7 @@ export const chatAttachmentRoutes = new Elysia({
s3Key: key,
filename,
contentType,
- sizeBytes: bytes.length,
+ sizeBytes: content.length,
});
set.status = 201;
return chatAttachmentDto(row);
@@ -137,6 +156,7 @@ export const chatAttachmentRoutes = new Elysia({
summary: 'Upload a chat attachment',
description:
'Store a file for the agent chat: a spreadsheet to import issues from, a spec, or a log. ' +
+ 'A PDF is converted to Markdown and stored as a .md file; a scanned PDF is refused. ' +
'Send the bytes as base64 in `contentBase64`. Read it back with read_chat_attachment.',
...mcpTool('upload_chat_attachment'),
},
@@ -144,7 +164,7 @@ export const chatAttachmentRoutes = new Elysia({
)
// Reads a stored file back: its metadata and, when the file holds one, its
- // content — a parsed table for a spreadsheet or document, an excerpt for a
+ // content — a parsed table for a spreadsheet or document, the full text for a
// text file.
.get(
'/chat-attachments/:publicId',
@@ -160,10 +180,13 @@ export const chatAttachmentRoutes = new Elysia({
detail: {
summary: 'Read a chat attachment',
description:
- 'Read a file uploaded in the chat: its metadata and, for a spreadsheet or document ' +
- '(.xlsx, .csv, .docx), the column headers and first rows; for a text file, its first ' +
- 'characters. The id comes from the [file: "name" (attachment id: …)] marker in the ' +
- "user's message. To turn a table into issues, map its columns with prepare_issue_import.",
+ 'Read a file the person attached in the chat. A [file: "name" (attachment id: …)] ' +
+ 'marker in their message means that file is attached: it is stored in the chat and ' +
+ 'is not on your filesystem, so read it with this tool and the id from the marker — ' +
+ 'never look for it on disk. Answers with the file metadata and, for a spreadsheet or ' +
+ 'document (.xlsx, .csv, .docx), the column headers and first rows; for a text file ' +
+ '(.md, .txt, and a PDF converted to Markdown on upload), its full text. To turn a ' +
+ 'table into issues, map its columns with prepare_issue_import.',
...mcpTool('read_chat_attachment'),
},
},
diff --git a/apps/api/src/modules/chat-attachments/model.ts b/apps/api/src/modules/chat-attachments/model.ts
index 5c1d3807..dba9d926 100644
--- a/apps/api/src/modules/chat-attachments/model.ts
+++ b/apps/api/src/modules/chat-attachments/model.ts
@@ -24,7 +24,7 @@ export const ChatAttachmentResponse = t.Object({
});
// The read route answers with the metadata plus the content in the shape the
-// file holds: a parsed table for a spreadsheet or document, a text excerpt for
+// file holds: a parsed table for a spreadsheet or document, the full text for
// a text file, neither for a binary one.
export const ChatAttachmentContentResponse = t.Object({
id: t.String(),
diff --git a/apps/api/src/modules/chat-attachments/pdf.ts b/apps/api/src/modules/chat-attachments/pdf.ts
new file mode 100644
index 00000000..4bbfb9af
--- /dev/null
+++ b/apps/api/src/modules/chat-attachments/pdf.ts
@@ -0,0 +1,33 @@
+import { processPdfAsync } from '@firecrawl/pdf-inspector';
+import { HttpError } from '#shared/lib';
+
+// The images a PDF holds are not extracted, so the placeholders the converter
+// emits for them would be links to nothing.
+export function stripPdfImagePlaceholders(markdown: string): string {
+ return markdown
+ .replace(/!\[[^\]]*\]\(pdf-image:\/\/\d+\)/g, '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+const NO_TEXT_LAYER =
+ 'This PDF has no text layer (it is a scan or a set of images). ' +
+ 'Attach a PDF with selectable text, or a .md/.txt file instead.';
+
+// processPdfAsync parses on the libuv thread pool, so a large document does not
+// block the event loop.
+export async function pdfToMarkdown(bytes: Buffer): Promise<string> {
+ let result;
+ try {
+ result = await processPdfAsync(bytes);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : err;
+ throw new HttpError(400, `The file is not a readable PDF: ${reason}`);
+ }
+ if (result.pdfType === 'Scanned' || result.pdfType === 'ImageBased') {
+ throw new HttpError(400, NO_TEXT_LAYER);
+ }
+ const markdown = stripPdfImagePlaceholders(result.markdown ?? '');
+ if (markdown === '') throw new HttpError(400, NO_TEXT_LAYER);
+ return markdown;
+}
diff --git a/apps/api/src/modules/chat-attachments/service.ts b/apps/api/src/modules/chat-attachments/service.ts
index 6c62d27f..a9452999 100644
--- a/apps/api/src/modules/chat-attachments/service.ts
+++ b/apps/api/src/modules/chat-attachments/service.ts
@@ -83,17 +83,16 @@ export interface ChatAttachmentContent {
text?: string;
}
-// The most an agent is shown of a text file in one read.
-const MAX_TEXT_EXCERPT = 4000;
-
function isTextLike(row: ChatAttachmentRow): boolean {
if (/^(text\/|application\/(json|xml))/.test(row.contentType)) return true;
return /\.(txt|md|log|json|xml|ya?ml)$/i.test(row.filename);
}
// The content of a stored file in the shape the read route answers with: a table
-// for a spreadsheet or document, a text excerpt for a text file, nothing for a
-// binary one (its download url is in the metadata either way).
+// for a spreadsheet or document, the full text for a text file, nothing for a
+// binary one (its download url is in the metadata either way). A text file is
+// returned whole: what it costs in context is the user's call, and the chat
+// shows the conversation's context size.
export async function readChatAttachmentContent(
row: ChatAttachmentRow,
): Promise<ChatAttachmentContent> {
@@ -108,6 +107,6 @@ export async function readChatAttachmentContent(
},
};
}
- if (isTextLike(row)) return { text: bytes.toString('utf8').slice(0, MAX_TEXT_EXCERPT) };
+ if (isTextLike(row)) return { text: bytes.toString('utf8') };
return {};
}
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 04929595..7a6ae403 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -99,9 +99,10 @@
"unreachable": "تعذّر الوصول إلى الوكيل. حاول مرة أخرى.",
"runnerOffline": "المنفّذ (runner) مش متصل",
"runnerOfflineHint": "شغّل المنفّذ على جهازك عشان تقدر تكلّم الوكيل ده.",
- "attachFile": "أرفق جدول بيانات أو مستند ليستورده الوكيل",
+ "attachFile": "إرفاق جدول بيانات أو مستند أو ملف PDF أو ملف نصي ليقرأه الوكيل",
"removeAttachment": "إزالة المرفق",
"uploadFailed": "تعذّر رفع الملف.",
+ "tooManyAttachments": "يمكنك إرفاق ما يصل إلى {max} ملفات برسالة واحدة.",
"importRows": "{count, plural, one {صف واحد} other {# صفوف}}",
"confirmImport": "تأكيد الاستيراد",
"cancelImport": "إلغاء",
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index a9b572f6..da53635d 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -99,9 +99,10 @@
"unreachable": "Could not reach the agent. Try again.",
"runnerOffline": "Runner offline",
"runnerOfflineHint": "Start the runner on your machine to chat with this agent.",
- "attachFile": "Attach a spreadsheet or document for the agent to import",
+ "attachFile": "Attach a spreadsheet, document, PDF, or text file for the agent to read",
"removeAttachment": "Remove attachment",
"uploadFailed": "Could not upload the file.",
+ "tooManyAttachments": "You can attach up to {max} files to one message.",
"importRows": "{count, plural, one {# row} other {# rows}}",
"confirmImport": "Confirm import",
"cancelImport": "Cancel",
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index c1e24d36..a4f4c4e3 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -99,9 +99,10 @@
"unreachable": "Не удалось связаться с агентом. Попробуйте ещё раз.",
"runnerOffline": "Раннер не на связи",
"runnerOfflineHint": "Запустите раннер на своей машине, чтобы писать этому агенту.",
- "attachFile": "Прикрепить таблицу или документ для импорта агентом",
+ "attachFile": "Прикрепить таблицу, документ, PDF или текстовый файл для агента",
"removeAttachment": "Убрать вложение",
"uploadFailed": "Не удалось загрузить файл.",
+ "tooManyAttachments": "К одному сообщению можно прикрепить не более {max} файлов.",
"importRows": "{count, plural, one {# строка} few {# строки} many {# строк} other {# строки}}",
"confirmImport": "Подтвердить импорт",
"cancelImport": "Отмена",
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index f2f6e4f7..96becb2e 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -99,9 +99,10 @@
"unreachable": "Не вдалося зв'язатися з агентом. Спробуйте ще раз.",
"runnerOffline": "Раннер не на зв’язку",
"runnerOfflineHint": "Запустіть раннер на своїй машині, щоб писати цьому агенту.",
- "attachFile": "Прикріпити таблицю чи документ для імпорту агентом",
+ "attachFile": "Прикріпити таблицю, документ, PDF або текстовий файл для агента",
"removeAttachment": "Вилучити вкладення",
"uploadFailed": "Не вдалося завантажити файл.",
+ "tooManyAttachments": "До одного повідомлення можна прикріпити не більше {max} файлів.",
"importRows": "{count, plural, one {# рядок} few {# рядки} many {# рядків} other {# рядка}}",
"confirmImport": "Підтвердити імпорт",
"cancelImport": "Скасувати",
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index 87aefe10..87647058 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -99,9 +99,10 @@
"unreachable": "无法连接代理,请重试。",
"runnerOffline": "运行器未连接",
"runnerOfflineHint": "在你的机器上启动运行器,才能与该智能体聊天。",
- "attachFile": "附加电子表格或文档供智能体导入",
+ "attachFile": "附加表格、文档、PDF 或文本文件供智能体读取",
"removeAttachment": "移除附件",
"uploadFailed": "文件上传失败。",
+ "tooManyAttachments": "一条消息最多可附加 {max} 个文件。",
"importRows": "{count} 行",
"confirmImport": "确认导入",
"cancelImport": "取消",
diff --git a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
index 269550cc..d06baaa8 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
@@ -24,6 +24,8 @@ import {
} from '@/components/ui/input-group';
import { useTranslations } from 'next-intl';
+const MAX_ATTACHMENTS = 10;
+
// The running transcript and the composer for one agent conversation. The
// conversation state lives above this panel (in the agent chat host), so it is
// presentational: it renders what it is given and reports sends.
@@ -94,20 +96,36 @@ export function AgentChatPanel({
onSend(marker ? `${text}\n\n${marker}` : text);
}
+ // The upload route takes one file per request, so a multi-file pick is sent as
+ // one request each and a file that fails does not lose the ones that succeeded.
async function attach(files: FileList | null) {
- const file = files?.[0];
- if (!file || uploading) return;
+ const picked = Array.from(files ?? []);
+ if (picked.length === 0 || uploading) return;
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ if (attachments.length + picked.length > MAX_ATTACHMENTS) {
+ setUploadError(t('tooManyAttachments', { max: MAX_ATTACHMENTS }));
+ return;
+ }
setUploading(true);
setUploadError(null);
- try {
- const uploaded = await uploadChatAttachment(projectKey!, file);
- setAttachments((current) => [...current, uploaded]);
- } catch (err) {
- setUploadError(err instanceof Error ? err.message : t('uploadFailed'));
- } finally {
- setUploading(false);
- if (fileInputRef.current) fileInputRef.current.value = '';
- }
+ const results = await Promise.allSettled(
+ picked.map((file) => uploadChatAttachment(projectKey!, file)),
+ );
+ const uploaded: ChatAttachment[] = [];
+ const failed: string[] = [];
+ results.forEach((result, i) => {
+ if (result.status === 'fulfilled') {
+ uploaded.push(result.value);
+ } else {
+ const reason = result.reason;
+ failed.push(
+ `${picked[i].name}: ${reason instanceof Error ? reason.message : t('uploadFailed')}`,
+ );
+ }
+ });
+ setAttachments((current) => [...current, ...uploaded]);
+ setUploadError(failed.length > 0 ? failed.join('; ') : null);
+ setUploading(false);
}
return (
@@ -174,13 +192,16 @@ export function AgentChatPanel({
</button>
</span>
))}
- {uploadError && <span className="text-xs text-destructive">{uploadError}</span>}
+ {uploadError && (
+ <span className="w-full text-xs text-destructive">{uploadError}</span>
+ )}
</div>
)}
<input
ref={fileInputRef}
type="file"
- accept=".xlsx,.csv,.docx"
+ accept=".xlsx,.csv,.docx,.pdf,.md,.txt"
+ multiple
className="hidden"
onChange={(e) => void attach(e.target.files)}
/>
diff --git a/bun.lock b/bun.lock
index 0d3716ee..8891613a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -22,6 +22,7 @@
"@aws-sdk/client-s3": "^3.1109.0",
"@elysiajs/cors": "^1.4.2",
"@elysiajs/swagger": "^1.3.1",
+ "@firecrawl/pdf-inspector": "^1.17.0",
"@mastra/core": "^1.58.0",
"@mastra/memory": "^1.26.1",
"@mastra/pg": "^1.20.0",
@@ -509,6 +510,20 @@
"@fast-csv/parse": ["@fast-csv/[email protected]", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.groupby": "^4.6.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0", "lodash.isundefined": "^3.0.1", "lodash.uniq": "^4.5.0" } }, "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA=="],
+ "@firecrawl/pdf-inspector": ["@firecrawl/[email protected]", "", { "optionalDependencies": { "@firecrawl/pdf-inspector-darwin-arm64": "1.17.0", "@firecrawl/pdf-inspector-linux-arm64-gnu": "1.17.0", "@firecrawl/pdf-inspector-linux-arm64-musl": "1.17.0", "@firecrawl/pdf-inspector-linux-x64-gnu": "1.17.0", "@firecrawl/pdf-inspector-linux-x64-musl": "1.17.0", "@firecrawl/pdf-inspector-win32-x64-msvc": "1.17.0" }, "bin": { "pdf-inspector": "bin/pdf-inspector.mjs" } }, "sha512-qSXKbJ6s3psJSjwFopssxUzUfpdwwTJ0f0IFj8xqzF/ZeO4dDTpZG0mpo+D8iLlfH+ks3CEIC72dedzevnoohQ=="],
+
+ "@firecrawl/pdf-inspector-darwin-arm64": ["@firecrawl/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-1Bbri4vHGAmsCot/wHHku9BiXO1DQMy3N2aSEK4vDpWrkV/n7hyuSt/0ErE1k/3952/Ng4Z7Dxrw5gsYFxDXAw=="],
+
+ "@firecrawl/pdf-inspector-linux-arm64-gnu": ["@firecrawl/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-ssduGacOBq1MoZJANAovcb6wLQFqnIx7bvnkZ64ZgUxK6tXPwZoW0JWVb2EKjB/EnHNrEplAGs/GNE36Hl68Vw=="],
+
+ "@firecrawl/pdf-inspector-linux-arm64-musl": ["@firecrawl/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-bR/crKWcJZWT7bZfMC9+GWEWrbfrE8m2x3azMUUAFWwpRChNJzHCMQeat8X6/JHilWJKMABV2aghwilgTU1Gqw=="],
+
+ "@firecrawl/pdf-inspector-linux-x64-gnu": ["@firecrawl/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-S38w/sigwvTPk57hGBPjYyogPdmHvUCdsi4OU6xzOo3pyJVjvXO7lCpywU1QhzDH1l5a3weCzgK3+zZPiIb3kQ=="],
+
+ "@firecrawl/pdf-inspector-linux-x64-musl": ["@firecrawl/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Ow1zQgS0vroLXxXdvDq4KMXhqE5n9TtqnQ8O2SQxTqi/o8WEzDdFAylGQ95WMZg/Nbddyi89eEFTpOdfn1P7nA=="],
+
+ "@firecrawl/pdf-inspector-win32-x64-msvc": ["@firecrawl/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-P4Z9s34DHoG6g/b9zcvmCGhg1RB7yilLRo1+p1GVSW9RBh+IN4ZWqZpgBDErcQ0eHjPKw0spzZ9mGex8tHewKA=="],
+
"@floating-ui/core": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="],
"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="],