"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(web): add multi-file drag and paste uploads
huanghua01472f7709447c
diff --git a/README.md b/README.mdindex a305d57b3..68affb382 100644--- a/README.md+++ b/README.md@@ -283,7 +283,7 @@ It is designed for research, simulation, and backtesting — and, when you choos| **Ask a trading question** | Market research with tools, data, documents, and reusable session context. || **Backtest a strategy idea** | Strategy code, metrics, benchmark context, validation artifacts, and run cards. || **Review your own trades** | Broker-journal parsing, behavior diagnostics, rule extraction, and Shadow Account comparisons. |-| **Read documents & charts** | Parse PDF / DOCX / XLSX / PPTX / images with pluggable OCR (`read_document`), and read chart screenshots semantically with a vision model (`analyze_image`). |+| **Read documents & charts** | Parse PDF / DOCX / XLSX / PPTX / images with pluggable OCR (`read_document`), and read chart screenshots semantically with a vision model (`analyze_image`). Web chat accepts up to five files at once through the picker, drag-and-drop, or clipboard paste. || **Read institutional filings & fund books** | SEC 13F manager books with quarter-over-quarter position diffs, ETF constituents across markets, event-contract implied probability, and arXiv / OpenAlex factor extraction — all read-only, on free public sources. || **Improve repeated research** | Persistent memory and editable skills turn useful routines into reusable workflows. || **Run analyst teams** | Multi-agent research reviews for investment, quant, crypto, macro, and risk workflows. |@@ -1132,7 +1132,7 @@ vibe-trading serve --port 8899| `POST` | `/sessions` | Create session || `POST` | `/sessions/{id}/messages` | Send message || `GET` | `/sessions/{id}/events` | SSE event stream |-| `POST` | `/upload` | Upload PDF/file |+| `POST` | `/upload` | Upload a document, data file, or image || `GET` | `/swarm/presets` | List swarm presets || `POST` | `/swarm/runs` | Start swarm run || `GET` | `/swarm/runs/{id}/events` | Swarm SSE stream |diff --git a/frontend/src/components/chat/Composer.tsx b/frontend/src/components/chat/Composer.tsxindex d32cc967d..4d99ffdc7 100644--- a/frontend/src/components/chat/Composer.tsx+++ b/frontend/src/components/chat/Composer.tsx@@ -7,6 +7,8 @@ import {useRef,useState,type ChangeEvent,+ type ClipboardEvent,+ type DragEvent,type FormEvent,type ReactNode,} from "react";@@ -25,6 +27,7 @@ import {} from "lucide-react";import { toast } from "sonner";import { api } from "@/lib/api";+import type { UploadedAttachment } from "@/lib/attachments";import type { AgentActivity } from "@/stores/agent";import {LiveRuntimeControl,@@ -37,12 +40,19 @@ const CONNECTOR_PORTFOLIO_PROMPT ="Use the selected trading connector profile to summarize my account, positions, concentration, cash, and portfolio risk. Do not place or modify orders.";const ACCEPTED_FILE_TYPES =- ".pdf,.docx,.xlsx,.xls,.pptx,.csv,.tsv,.txt,.md,.log,.json,.yaml,.yml,.toml,.html,.xml,.rst,.png,.jpg,.jpeg,.gif,.bmp,.webp,.tiff";+ ".pdf,.docx,.xlsx,.xls,.pptx,.csv,.tsv,.txt,.md,.log,.json,.toml,.html,.xml,.rst,.png,.jpg,.jpeg,.gif,.bmp,.webp,.tiff";+const MAX_ATTACHMENT_COUNT = 5;+const MAX_FILE_SIZE = 50 * 1024 * 1024;+const BLOCKED_EXTENSIONS = [+ ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",+ ".so", ".dll", ".dylib", ".py", ".pyw", ".sh", ".bash", ".zsh",+ ".fish", ".ps1", ".yaml", ".yml", ".j2", ".jinja", ".jinja2",+ ".template", ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2",+ ".xz",+];+const BLOCKED_FILENAMES = new Set(["dockerfile", "containerfile"]);-export interface ComposerAttachment {- filename: string;- filePath: string;-}+export type ComposerAttachment = UploadedAttachment;export interface ComposerHandle {fill(prompt: string): void;@@ -59,7 +69,7 @@ interface Props {goalComposerActive: boolean;swarmPreset: { name: string; title: string } | null;panels?: ReactNode;- onSubmit: (prompt: string, attachment: ComposerAttachment | null) => void;+ onSubmit: (prompt: string, attachments: ComposerAttachment[]) => void;onCancel: () => void;onExport: () => void;onStartGoal: () => void;@@ -90,8 +100,10 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composerconst inputRef = useRef<HTMLTextAreaElement>(null);const isComposingRef = useRef(false);const lastCompositionEndRef = useRef(0);- const [attachment, setAttachment] = useState<ComposerAttachment | null>(null);+ const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);const [uploading, setUploading] = useState(false);+ const [draggingFiles, setDraggingFiles] = useState(false);+ const dragDepthRef = useRef(0);const [showUploadMenu, setShowUploadMenu] = useState(false);const uploadMenuRef = useRef<HTMLDivElement>(null);const uploadMenuTriggerRef = useRef<HTMLButtonElement>(null);@@ -102,14 +114,14 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer}, []);const submitPrompt = useCallback((prompt: string) => {- if (!prompt.trim() || streaming) return;+ if ((!prompt.trim() && attachments.length === 0) || streaming || uploading) return;setInput("");if (inputRef.current) inputRef.current.style.height = "auto";- const submittedAttachment = attachment;- if (!goalComposerActive) setAttachment(null);- onSubmit(prompt.trim(), submittedAttachment);+ const submittedAttachments = [...attachments];+ if (!goalComposerActive) setAttachments([]);+ onSubmit(prompt.trim(), submittedAttachments);inputRef.current?.focus();- }, [attachment, goalComposerActive, onSubmit, streaming]);+ }, [attachments, goalComposerActive, onSubmit, streaming, uploading]);useImperativeHandle(ref, () => ({fill(prompt: string) {@@ -131,38 +143,89 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function ComposersubmitPrompt(input);}, [input, submitPrompt]);- const handleFileSelect = useCallback(async (event: ChangeEvent<HTMLInputElement>) => {- const file = event.target.files?.[0];- if (!file) return;- event.target.value = "";- const blockedExts = [- ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",- ".so", ".dll", ".dylib",- ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",- ];- const lowered = file.name.toLowerCase();- if (blockedExts.some((ext) => lowered.endsWith(ext))) {- toast.error(t("agent.executablesNotAllowed"));+ const uploadFiles = useCallback(async (files: File[]) => {+ if (files.length === 0 || streaming || uploading) return;+ const remainingSlots = MAX_ATTACHMENT_COUNT - attachments.length;+ if (remainingSlots <= 0) {+ toast.error(t("agent.attachmentLimit", { count: MAX_ATTACHMENT_COUNT }));return;}- if (file.size > 50 * 1024 * 1024) {- toast.error(t("agent.fileSizeExceeds"));- return;+ const validFiles = files.filter((file) => {+ const lowered = file.name.toLowerCase();+ if (+ BLOCKED_FILENAMES.has(lowered)+ || BLOCKED_EXTENSIONS.some((extension) => lowered.endsWith(extension))+ ) {+ toast.error(t("agent.executablesNotAllowed"));+ return false;+ }+ if (file.size > MAX_FILE_SIZE) {+ toast.error(t("agent.fileSizeExceeds"));+ return false;+ }+ return true;+ });+ if (validFiles.length > remainingSlots) {+ toast.error(t("agent.attachmentLimit", { count: MAX_ATTACHMENT_COUNT }));}+ const accepted = validFiles.slice(0, remainingSlots);+ if (accepted.length === 0) return;+setUploading(true);setShowUploadMenu(false);try {- const result = await api.uploadFile(file);- setAttachment({ filename: result.filename, filePath: result.file_path });- toast.success(t("agent.uploaded", { filename: result.filename }));- } catch (error) {- toast.error(t("agent.uploadFailed", {- error: error instanceof Error ? error.message : "Unknown error",- }));+ for (const file of accepted) {+ try {+ const result = await api.uploadFile(file);+ setAttachments((current) => [+ ...current,+ { filename: result.filename, filePath: result.file_path },+ ]);+ toast.success(t("agent.uploaded", { filename: result.filename }));+ } catch (error) {+ toast.error(t("agent.uploadFailed", {+ error: error instanceof Error ? error.message : "Unknown error",+ }));+ }+ }} finally {setUploading(false);}- }, [t]);+ }, [attachments.length, streaming, t, uploading]);++ const handleFileSelect = useCallback((event: ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(event.target.files ?? []);+ event.target.value = "";+ void uploadFiles(files);+ }, [uploadFiles]);++ const handlePaste = useCallback((event: ClipboardEvent<HTMLFormElement>) => {+ const files = Array.from(event.clipboardData.files ?? []);+ if (files.length === 0) return;+ event.preventDefault();+ void uploadFiles(files);+ }, [uploadFiles]);++ const handleDragEnter = useCallback((event: DragEvent<HTMLFormElement>) => {+ if (streaming || uploading) return;+ if (!Array.from(event.dataTransfer.types ?? []).includes("Files")) return;+ event.preventDefault();+ dragDepthRef.current += 1;+ setDraggingFiles(true);+ }, [streaming, uploading]);++ const handleDragLeave = useCallback((event: DragEvent<HTMLFormElement>) => {+ event.preventDefault();+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);+ if (dragDepthRef.current === 0) setDraggingFiles(false);+ }, []);++ const handleDrop = useCallback((event: DragEvent<HTMLFormElement>) => {+ event.preventDefault();+ dragDepthRef.current = 0;+ setDraggingFiles(false);+ void uploadFiles(Array.from(event.dataTransfer.files ?? []));+ }, [uploadFiles]);useEffect(() => {const handleClickOutside = (event: MouseEvent) => {@@ -187,7 +250,20 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer}, [showUploadMenu]);return (- <form onSubmit={handleSubmit} className="space-y-2">+ <form+ onSubmit={handleSubmit}+ onPaste={handlePaste}+ onDragEnter={handleDragEnter}+ onDragOver={(event) => event.preventDefault()}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ className="relative space-y-2"+ >+ {draggingFiles && (+ <div role="status" className="pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary bg-background/90 text-sm font-medium text-primary">+ {t("agent.dropFiles")}+ </div>+ )}{swarmPreset && (<div className="flex items-center gap-1"><span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">@@ -212,15 +288,22 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer)}{panels}<LiveRuntimeStatus />- {attachment && (- <div className="flex items-center gap-1">- <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">- <Paperclip className="h-3 w-3" />- {attachment.filename}- <button type="button" onClick={() => setAttachment(null)} className="hover:text-destructive transition-colors">- <X className="h-3 w-3" />- </button>- </span>+ {attachments.length > 0 && (+ <div className="flex flex-wrap items-center gap-1">+ {attachments.map((attachment, index) => (+ <span key={attachment.filePath} className="inline-flex max-w-full items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/10 text-primary text-xs font-medium">+ <Paperclip className="h-3 w-3 shrink-0" />+ <span className="truncate">{attachment.filename}</span>+ <button+ type="button"+ aria-label={t("agent.removeAttachment", { filename: attachment.filename })}+ onClick={() => setAttachments((current) => current.filter((_, itemIndex) => itemIndex !== index))}+ className="hover:text-destructive transition-colors"+ >+ <X className="h-3 w-3" />+ </button>+ </span>+ ))}</div>)}{uploading && (@@ -261,7 +344,7 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function ComposerclassName="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"><Paperclip className="h-4 w-4" />- {t("agent.uploadPdf")}+ {t("agent.uploadFile")}</button><div className="border-t my-1" /><button@@ -321,6 +404,7 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer<inputref={fileInputRef}type="file"+ multipleaccept={ACCEPTED_FILE_TYPES}onChange={handleFileSelect}className="hidden"@@ -397,7 +481,7 @@ export const Composer = memo(forwardRef<ComposerHandle, Props>(function Composer) : (<buttontype="submit"- disabled={goalComposerActive ? !input.trim() : (!input.trim() && !attachment)}+ disabled={uploading || (goalComposerActive ? !input.trim() : (!input.trim() && attachments.length === 0))}className="h-10 px-4 rounded-xl bg-primary text-primary-foreground text-sm font-medium disabled:opacity-40 hover:opacity-90 transition-opacity"title={t("agent.send")}aria-label={t("agent.send")}diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsxindex c5ae132f4..89ae6d649 100644--- a/frontend/src/components/chat/MessageBubble.tsx+++ b/frontend/src/components/chat/MessageBubble.tsx@@ -187,21 +187,24 @@ function formatElapsed(elapsedMs: number): string {export const MessageBubble = memo(function MessageBubble({ msg, onRetry }: Props) {if (msg.type === "user") {const meta = msg.meta;+ const attachments = meta?.attachments+ ?? (meta?.attachment ? [meta.attachment] : []);return (<div className="flex justify-end group"><div className="max-w-[72%] max-h-[40vh] overflow-y-auto break-words rounded-[18px] bg-muted px-4 py-3 text-[15px] text-foreground leading-relaxed whitespace-pre-wrap">- {meta && (meta.attachment || meta.swarmMode || meta.goalMode) && (+ {meta && (attachments.length > 0 || meta.swarmMode || meta.goalMode) && (<div className="mb-1.5 flex flex-wrap justify-end gap-1.5 text-[10px] leading-none text-muted-foreground">- {meta.attachment && (+ {attachments.map((attachment, index) => (<span+ key={`${attachment.filename}-${index}`}className="inline-flex max-w-full items-center gap-1 rounded-full bg-background/60 px-2 py-1 text-muted-foreground"title={i18n.t("agent.attachmentChip" as never)}><Paperclip className="h-3 w-3 shrink-0" /><span className="sr-only">{i18n.t("agent.attachmentChip" as never)}: </span>- <span className="truncate">{meta.attachment.filename}</span>+ <span className="truncate">{attachment.filename}</span></span>- )}+ ))}{meta.swarmMode && (<span className="inline-flex items-center gap-1 rounded-full bg-background/60 px-2 py-1 text-muted-foreground"><Users className="h-3 w-3" />diff --git a/frontend/src/components/chat/__tests__/Composer.test.tsx b/frontend/src/components/chat/__tests__/Composer.test.tsxindex 4a247017c..ef7a0565f 100644--- a/frontend/src/components/chat/__tests__/Composer.test.tsx+++ b/frontend/src/components/chat/__tests__/Composer.test.tsx@@ -1,9 +1,18 @@import { memo } from "react";-import { fireEvent, render, screen } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import i18n from "../../../i18n";+import { api } from "@/lib/api";import { Composer } from "../Composer";+vi.mock("@/lib/api", () => ({+ api: { uploadFile: vi.fn() },+}));++vi.mock("sonner", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));+const baseProps = {streaming: false,hasCompletedTurn: false,@@ -27,6 +36,11 @@ describe("Composer", () => {beforeEach(() => {vi.clearAllMocks();+ vi.mocked(api.uploadFile).mockImplementation(async (file: File) => ({+ status: "ok",+ filename: file.name,+ file_path: `uploads/${file.name}`,+ }));});afterEach(() => {@@ -51,7 +65,7 @@ describe("Composer", () => {vi.advanceTimersByTime(81);fireEvent.keyDown(textarea, { key: "Enter", code: "Enter" });expect(baseProps.onSubmit).toHaveBeenCalledTimes(1);- expect(baseProps.onSubmit).toHaveBeenCalledWith("你好", null);+ expect(baseProps.onSubmit).toHaveBeenCalledWith("你好", []);});it("keeps composer keystrokes inside the composer render boundary", async () => {@@ -74,4 +88,69 @@ describe("Composer", () => {expect(messageListRenderCount).toBe(1);});++ it("uploads multiple dropped files and submits them together", async () => {+ const user = userEvent.setup();+ const { container } = render(<Composer {...baseProps} />);+ const form = container.querySelector("form");+ expect(form).not.toBeNull();+ const files = [+ new File(["trade,date"], "trades.csv", { type: "text/csv" }),+ new File(["chart"], "chart.png", { type: "image/png" }),+ ];++ fireEvent.drop(form!, {+ dataTransfer: { files, types: ["Files"] },+ });++ await waitFor(() => expect(api.uploadFile).toHaveBeenCalledTimes(2));+ expect(screen.getByText("trades.csv")).toBeInTheDocument();+ expect(screen.getByText("chart.png")).toBeInTheDocument();++ await user.type(screen.getByRole("textbox"), "Compare these files");+ await user.click(screen.getByRole("button", { name: "Send message" }));+ expect(baseProps.onSubmit).toHaveBeenCalledWith("Compare these files", [+ { filename: "trades.csv", filePath: "uploads/trades.csv" },+ { filename: "chart.png", filePath: "uploads/chart.png" },+ ]);+ });++ it("uploads an image pasted from the clipboard and allows attachment-only submit", async () => {+ const user = userEvent.setup();+ render(<Composer {...baseProps} />);+ const textarea = screen.getByRole("textbox");+ const image = new File(["pixels"], "clipboard.png", { type: "image/png" });++ fireEvent.paste(textarea, {+ clipboardData: { files: [image] },+ });++ await screen.findByText("clipboard.png");+ await user.click(screen.getByRole("button", { name: "Send message" }));+ expect(baseProps.onSubmit).toHaveBeenCalledWith("", [+ { filename: "clipboard.png", filePath: "uploads/clipboard.png" },+ ]);+ });++ it("shows a drop target while files are dragged over the composer", () => {+ const { container } = render(<Composer {...baseProps} />);+ const form = container.querySelector("form");+ fireEvent.dragEnter(form!, {+ dataTransfer: { files: [], types: ["Files"] },+ });+ expect(screen.getByText("Drop files here")).toBeInTheDocument();+ });++ it("caps one composer turn at five attachments", async () => {+ const { container } = render(<Composer {...baseProps} />);+ const files = Array.from(+ { length: 6 },+ (_, index) => new File([String(index)], `file-${index}.txt`, { type: "text/plain" }),+ );+ fireEvent.drop(container.querySelector("form")!, {+ dataTransfer: { files, types: ["Files"] },+ });+ await waitFor(() => expect(api.uploadFile).toHaveBeenCalledTimes(5));+ expect(screen.queryByText("file-5.txt")).not.toBeInTheDocument();+ });});diff --git a/frontend/src/components/chat/__tests__/MessageBubble.test.tsx b/frontend/src/components/chat/__tests__/MessageBubble.test.tsxindex 83238ae9c..19498ae51 100644--- a/frontend/src/components/chat/__tests__/MessageBubble.test.tsx+++ b/frontend/src/components/chat/__tests__/MessageBubble.test.tsx@@ -77,6 +77,25 @@ describe("MessageBubble", () => {"text-muted-foreground",);});++ it("renders every attachment in a multi-file request", () => {+ render(+ <MessageBubble+ msg={makeMsg({+ type: "user",+ content: "Compare these",+ meta: {+ attachments: [+ { filename: "report.pdf" },+ { filename: "chart.png" },+ ],+ },+ })}+ />,+ );+ expect(screen.getByText("report.pdf")).toBeInTheDocument();+ expect(screen.getByText("chart.png")).toBeInTheDocument();+ });});describe("answer messages", () => {diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 087f471e3..c2df0b8ae 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -508,6 +508,9 @@"executablesNotAllowed": "غير مسموح بالملفات التنفيذية والأرشيفات","fileSizeExceeds": "حجم الملف يتجاوز حد 50 ميغابايت","uploaded": "تم الرفع: {{filename}}",+ "attachmentLimit": "يمكنك إرفاق ما يصل إلى {{count}} ملفات",+ "dropFiles": "أفلت الملفات هنا",+ "removeAttachment": "إزالة {{filename}}","uploadFailed": "فشل الرفع: {{error}}","failedToSend": "فشل إرسال الرسالة، يُرجى المحاولة مرة أخرى.","failedToContinue": "فشل متابعة الهدف، يُرجى المحاولة مرة أخرى.",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex a98e8305a..1b9ff5b51 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -513,6 +513,9 @@"executablesNotAllowed": "Ausführbare Dateien und Archive sind nicht erlaubt","fileSizeExceeds": "Dateigröße überschreitet 50 MB Grenze","uploaded": "Hochgeladen: {{filename}}",+ "attachmentLimit": "Du kannst bis zu {{count}} Dateien anhängen",+ "dropFiles": "Dateien hier ablegen",+ "removeAttachment": "{{filename}} entfernen","uploadFailed": "Hochladen fehlgeschlagen: {{error}}","failedToSend": "Nachricht konnte nicht gesendet werden, bitte erneut versuchen.","failedToContinue": "Ziel konnte nicht fortgesetzt werden, bitte erneut versuchen.",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex a8f3401e3..27c7e43e9 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -513,6 +513,9 @@"executablesNotAllowed": "Executables and archives are not allowed","fileSizeExceeds": "File size exceeds 50 MB limit","uploaded": "Uploaded: {{filename}}",+ "attachmentLimit": "You can attach up to {{count}} files",+ "dropFiles": "Drop files here",+ "removeAttachment": "Remove {{filename}}","uploadFailed": "Upload failed: {{error}}","failedToSend": "Failed to send message, please retry.","failedToContinue": "Failed to continue goal, please retry.",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 4ea913f88..2dd2a3662 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -513,6 +513,9 @@"executablesNotAllowed": "No se permiten ejecutables ni archivos comprimidos","fileSizeExceeds": "El tamaño del archivo supera el límite de 50 MB","uploaded": "Subido: {{filename}}",+ "attachmentLimit": "Puedes adjuntar hasta {{count}} archivos",+ "dropFiles": "Suelta los archivos aquí",+ "removeAttachment": "Eliminar {{filename}}","uploadFailed": "Error al subir: {{error}}","failedToSend": "Error al enviar el mensaje, intenta de nuevo.","failedToContinue": "Error al continuar el objetivo, intenta de nuevo.",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 358d0a00a..4f7adba33 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -508,6 +508,9 @@"executablesNotAllowed": "実行ファイルとアーカイブはアップロードできません","fileSizeExceeds": "ファイルサイズが 50 MB の上限を超えています","uploaded": "アップロードしました: {{filename}}",+ "attachmentLimit": "最大 {{count}} 件のファイルを添付できます",+ "dropFiles": "ここにファイルをドロップ",+ "removeAttachment": "{{filename}} を削除","uploadFailed": "アップロードに失敗しました: {{error}}","failedToSend": "メッセージ送信に失敗しました。再試行してください。","failedToContinue": "目標の続行に失敗しました。再試行してください。",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 20e5391c6..f71e2a39a 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -508,6 +508,9 @@"executablesNotAllowed": "실행 파일 및 압축 파일은 업로드할 수 없습니다","fileSizeExceeds": "파일 크기가 50 MB 한도를 초과합니다","uploaded": "업로드 완료: {{filename}}",+ "attachmentLimit": "파일을 최대 {{count}}개 첨부할 수 있습니다",+ "dropFiles": "여기에 파일 놓기",+ "removeAttachment": "{{filename}} 제거","uploadFailed": "업로드 실패: {{error}}","failedToSend": "메시지 전송에 실패했습니다. 다시 시도해 주세요.","failedToContinue": "목표 진행에 실패했습니다. 다시 시도해 주세요.",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 26d1a0ed7..bfba80662 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -508,6 +508,9 @@"executablesNotAllowed": "不允许上传可执行文件和压缩包","fileSizeExceeds": "文件大小超过 50 MB 限制","uploaded": "已上传:{{filename}}",+ "attachmentLimit": "最多可添加 {{count}} 个附件",+ "dropFiles": "拖放文件到这里",+ "removeAttachment": "移除 {{filename}}","uploadFailed": "上传失败:{{error}}","failedToSend": "发送消息失败,请重试。","failedToContinue": "继续目标失败,请重试。",diff --git a/frontend/src/lib/__tests__/attachments.test.ts b/frontend/src/lib/__tests__/attachments.test.tsnew file mode 100644index 000000000..29f8b2d21--- /dev/null+++ b/frontend/src/lib/__tests__/attachments.test.ts@@ -0,0 +1,35 @@+import {+ extractUploadedAttachments,+ prependUploadedAttachments,+} from "@/lib/attachments";++describe("attachment prompt envelope", () => {+ it("round-trips multiple attachments without exposing paths in display metadata", () => {+ const prompt = prependUploadedAttachments("Compare them", [+ { filename: "trades.csv", filePath: "uploads/a.csv" },+ { filename: "chart.png", filePath: "uploads/b.png" },+ ]);++ expect(prompt).toContain("uploads/a.csv");+ expect(extractUploadedAttachments(prompt)).toEqual({+ content: "Compare them",+ filenames: ["trades.csv", "chart.png"],+ });+ });++ it("keeps legacy single-attachment history readable", () => {+ expect(+ extractUploadedAttachments(+ "[Uploaded file: old.pdf, path: uploads/old.pdf]\n\nSummarize it",+ ),+ ).toEqual({ content: "Summarize it", filenames: ["old.pdf"] });+ });++ it("leaves malformed envelopes untouched", () => {+ const prompt = "[Uploaded files: not json]\n\nAnalyze";+ expect(extractUploadedAttachments(prompt)).toEqual({+ content: prompt,+ filenames: [],+ });+ });+});diff --git a/frontend/src/lib/attachments.ts b/frontend/src/lib/attachments.tsnew file mode 100644index 000000000..44eb704ac--- /dev/null+++ b/frontend/src/lib/attachments.ts@@ -0,0 +1,61 @@+export interface UploadedAttachment {+ filename: string;+ filePath: string;+}++const ATTACHMENTS_OPEN = "[Uploaded files: ";+const ATTACHMENTS_CLOSE = "]\n\n";+const LEGACY_ATTACHMENT = /^\[Uploaded file: (.+), path: [^\n]*\]\n\n/;++/** Add a machine-readable attachment envelope to the agent prompt. */+export function prependUploadedAttachments(+ prompt: string,+ attachments: UploadedAttachment[],+): string {+ if (attachments.length === 0) return prompt;+ const payload = attachments.map(({ filename, filePath }) => ({+ filename,+ path: filePath,+ }));+ return `${ATTACHMENTS_OPEN}${JSON.stringify(payload)}${ATTACHMENTS_CLOSE}${prompt}`;+}++/** Strip attachment paths from a stored prompt before rendering it. */+export function extractUploadedAttachments(content: string): {+ content: string;+ filenames: string[];+} {+ if (content.startsWith(ATTACHMENTS_OPEN)) {+ const closeIndex = content.indexOf(ATTACHMENTS_CLOSE, ATTACHMENTS_OPEN.length);+ if (closeIndex >= 0) {+ const serialized = content.slice(ATTACHMENTS_OPEN.length, closeIndex);+ try {+ const payload: unknown = JSON.parse(serialized);+ if (Array.isArray(payload)) {+ const filenames = payload.flatMap((item) => {+ if (!item || typeof item !== "object") return [];+ const filename = (item as Record<string, unknown>).filename;+ return typeof filename === "string" && filename ? [filename] : [];+ });+ if (filenames.length > 0) {+ return {+ content: content.slice(closeIndex + ATTACHMENTS_CLOSE.length),+ filenames,+ };+ }+ }+ } catch {+ // Preserve malformed prompts verbatim instead of hiding user content.+ }+ }+ }++ const legacy = content.match(LEGACY_ATTACHMENT);+ if (legacy) {+ return {+ content: content.slice(legacy[0].length),+ filenames: [legacy[1]],+ };+ }+ return { content, filenames: [] };+}diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 487b7b277..c87d10b68 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -11,6 +11,10 @@ import {} from "@/stores/agent";import { useSSE } from "@/hooks/useSSE";import { ApiError, AUTH_REQUIRED_MESSAGE, api, isAuthRequiredError, type GoalSnapshot, type MandateProposal, type MandateCommitted, type LiveAction, type LiveHalted, type LLMSettings } from "@/lib/api";+import {+ extractUploadedAttachments,+ prependUploadedAttachments,+} from "@/lib/attachments";import { isReportWorthyRun } from "@/lib/runReports";import type { AgentMessage, SwarmRunStatus, ToolCallEntry } from "@/types/agent";import { AgentAvatar } from "@/components/chat/AgentAvatar";@@ -118,14 +122,11 @@ function toDisplayPrompt(content: string): {content: string;meta?: AgentMessageMeta;} {- let display = content;+ const extractedAttachments = extractUploadedAttachments(content);+ let display = extractedAttachments.content;const meta: AgentMessageMeta = { requestText: content };- const attachmentMatch = display.match(- /^\[Uploaded file: (.+), path: [^\n]*\]\n\n/,- );- if (attachmentMatch) {- meta.attachment = { filename: attachmentMatch[1] };- display = display.slice(attachmentMatch[0].length);+ if (extractedAttachments.filenames.length > 0) {+ meta.attachments = extractedAttachments.filenames.map((filename) => ({ filename }));}if (display.startsWith(SWARM_PROMPT_PREFIX)) {meta.swarmMode = true;@@ -1264,9 +1265,9 @@ export function Agent() {const runPrompt = useCallback(async (prompt: string,- attachment: ComposerAttachment | null = null,+ attachments: ComposerAttachment[] = [],) => {- if (!prompt.trim() || status === "streaming") return;+ if ((!prompt.trim() && attachments.length === 0) || status === "streaming") return;clearStreamingView();if (goalComposerActive) {@@ -1315,9 +1316,9 @@ export function Agent() {finalPrompt = `${SWARM_PROMPT_PREFIX}${prompt}`;}- if (attachment) {- messageMeta.attachment = { filename: attachment.filename };- finalPrompt = `[Uploaded file: ${attachment.filename}, path: ${attachment.filePath}]\n\n${finalPrompt}`;+ if (attachments.length > 0) {+ messageMeta.attachments = attachments.map(({ filename }) => ({ filename }));+ finalPrompt = prependUploadedAttachments(finalPrompt, attachments);}messageMeta.requestText = finalPrompt;act().addMessage({@@ -1334,7 +1335,9 @@ export function Agent() {try {let sid = act().sessionId;if (!sid) {- const session = await api.createSession(prompt.slice(0, 50));+ const sessionTitle = prompt.trim()+ || attachments.map(({ filename }) => filename).join(", ");+ const session = await api.createSession(sessionTitle.slice(0, 50));sid = session.session_id;act().setSessionId(sid);setSearchParams({ session: sid }, { replace: true });diff --git a/frontend/src/stores/agent.ts b/frontend/src/stores/agent.tsindex b786d385c..5bafd86ce 100644--- a/frontend/src/stores/agent.ts+++ b/frontend/src/stores/agent.ts@@ -45,6 +45,7 @@ export function deriveActivityVerb(tool: string | undefined): ActivityVerb {export interface AgentMessageMeta {attachment?: { filename: string };+ attachments?: Array<{ filename: string }>;swarmMode?: boolean;goalMode?: boolean;requestText?: string;