From 590ae8f590d37dcb9c41b2ab622ab2b115a389e4 Mon Sep 17 00:00:00 2001 From: OrwellVII <56531592+OrwellVII@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:28:28 +0800 Subject: [PATCH 1/5] feat(composer): attach any file or folder as an uploaded path reference Files that cannot be inlined (binaries, text past the inline budget or slots) were dropped. They are now uploaded through a new chunked /api/attachments route into /omp-web/attachments// and listed in an 'Attached paths' block the model reads with its own tools. The plus menu gains Add folder, dropped folders are walked via webkitGetAsEntry, and pasted files attach like picked ones. Batches are capped at 2,000 files / 200 MB, every relative path is validated, and batches older than 30 days are pruned. --- AGENTS.md | 20 + CHANGELOG.md | 4 + app/api/attachments/[batchId]/route.ts | 69 ++++ app/api/attachments/route.ts | 37 ++ components/ChatInput-draft-attachments.ts | 10 +- .../ChatInput.attachment-references.test.mjs | 194 ++++++++++ components/ChatInput.tsx | 364 ++++++++++++++---- components/ChatWindow.tsx | 6 +- hooks/useDragDrop.ts | 12 +- lib/attachment-store.test.mjs | 238 ++++++++++++ lib/attachment-store.ts | 314 +++++++++++++++ lib/attachment-upload.test.mjs | 151 ++++++++ lib/attachment-upload.ts | 199 ++++++++++ lib/chat-attachments.test.mjs | 137 +++++-- lib/chat-attachments.ts | 129 +++++-- lib/draft-store.test.mjs | 18 + lib/draft-store.ts | 17 +- lib/i18n/locales/en.json | 15 +- lib/i18n/locales/ja.json | 15 +- lib/i18n/locales/zh-CN.json | 15 +- 20 files changed, 1806 insertions(+), 158 deletions(-) create mode 100644 app/api/attachments/[batchId]/route.ts create mode 100644 app/api/attachments/route.ts create mode 100644 components/ChatInput.attachment-references.test.mjs create mode 100644 lib/attachment-store.test.mjs create mode 100644 lib/attachment-store.ts create mode 100644 lib/attachment-upload.test.mjs create mode 100644 lib/attachment-upload.ts diff --git a/AGENTS.md b/AGENTS.md index 197270781..77c05084c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,8 @@ app/api/ sessions/[id]/export/route.ts GET exported HTML for a session agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? } agent/[id]/route.ts GET state | POST any RPC command + attachments/route.ts POST { kind, name, files: [{ path, size }] } → 201 { batchId } (composer path attachments) + attachments/[batchId]/route.ts PUT multipart (path, offset, data) chunks | POST complete → { path, kind, name, size, fileCount } events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq } @@ -100,6 +102,9 @@ lib/ omp/ shared omp foundations (paths, CLI probe, RpcProcess) provider-accounts.ts distinct omp accounts per provider from `omp usage` reports (Models → provider detail) agent-client.ts typed fetch helper for /api/agent commands + attachment-store.ts server: composer upload batches under /omp-web/attachments (path validation, caps, pruning) + attachment-upload.ts browser: chunked upload to /api/attachments + folder pick/drop traversal + chat-attachments.ts pure composer attachment rules: inline text budget, caps, prompt composition (Attached paths block) btw.ts /btw side-question records + pure frame/snapshot merge (order-safe) draft-store.ts local draft persistence helpers event-stream.ts tab-side EventSource-shaped streams over the shared worker @@ -564,6 +569,21 @@ during the wait. - `/api/files` is intentionally not a general filesystem browser. Allowed roots come from session cwds, their resolved project roots, `~/omp-cwd-*`, and roots explicitly added with `allowFileRoot()`. - `/api/cwd/validate`, `/api/default-cwd`, and `/api/worktrees` call `allowFileRoot()` when they make a new location browsable. +### Composer path attachments (`lib/attachment-store.ts`, `/api/attachments`) +- Small text files are inlined, images go as RPC `images`; everything else + (binary, past the inline budget or slots, folders) is uploaded and the prompt + ends with an `Attached paths` list (`composeMessageWithAttachments`). The + model reads those absolute paths with its own tools. +- One batch = one chip: declared first (every relative path validated and the + 2,000-file / 200 MB caps checked before any byte), then filled by ordered + ≤ 8 MiB multipart chunks, then completed. Chunking is required: while + `proxy.ts` runs, Next buffers at most 10 MB of a request body + (`proxyClientMaxBodySize`) and silently truncates the rest. +- Batches older than 30 days are pruned on batch creation (at most hourly). + Removing a chip leaves its batch for pruning. References live in the draft + store (memory-only, like other attachment payloads) and are folded into the + prompt text, so queue recovery restores them with the text. + ### Session list caching — new sessions must appear immediately - `listAllSessions()` (sidebar, command palette) is cached twice: a 30s TTL list cache in `lib/session-reader.ts` plus an mtime-keyed directory walk in diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..94e5171e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Attach any file, or a whole folder, for the model to read.** Files that cannot be inlined as text — PDFs, Office documents, archives and other binaries, or text past the inline budget — used to be dropped; they are now uploaded and sent as a path reference, and the new **Add folder** item in the composer's plus menu (or dropping a folder onto the chat) uploads a folder with its structure intact. The prompt ends with an `Attached paths` list of absolute paths the model reads with its own tools. Uploads are stored under `~/.omp/agent/omp-web/attachments/`, limited to 2,000 files and 200 MB per file or folder, and removed after 30 days. Small text files and images attach as before. + ### Fixes & Improvements - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. diff --git a/app/api/attachments/[batchId]/route.ts b/app/api/attachments/[batchId]/route.ts new file mode 100644 index 000000000..410a21536 --- /dev/null +++ b/app/api/attachments/[batchId]/route.ts @@ -0,0 +1,69 @@ +import { NextResponse } from "next/server"; +import { parseFormDataWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { ATTACHMENT_CHUNK_BYTES } from "@/lib/chat-attachments"; +import { + AttachmentError, + completeAttachmentBatch, + writeAttachmentChunks, + type AttachmentChunk, +} from "@/lib/attachment-store"; + +export const dynamic = "force-dynamic"; + +// Multipart boundaries and part headers are not file bytes, but are bounded too. +const MAX_CHUNK_REQUEST_BYTES = ATTACHMENT_CHUNK_BYTES + 1024 * 1024; + +type Params = { params: Promise<{ batchId: string }> }; + +function errorResponse(error: unknown): NextResponse { + if (error instanceof AttachmentError) { + return NextResponse.json({ error: error.message, code: error.code }, { status: error.status }); + } + return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); +} + +/** PUT multipart repeated (path, offset, data) parts → 200 { ok: true }. */ +export async function PUT(request: Request, { params }: Params) { + try { + const { batchId } = await params; + let formData: FormData; + try { + formData = await parseFormDataWithinLimit(request, MAX_CHUNK_REQUEST_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return NextResponse.json({ error: "Attachment chunk is too large", code: "attachment_chunk_too_large" }, { status: 413 }); + } + return NextResponse.json({ error: "Invalid multipart body", code: "invalid_attachment" }, { status: 400 }); + } + const paths = formData.getAll("path"); + const offsets = formData.getAll("offset"); + const data = formData.getAll("data"); + if (paths.length !== offsets.length || paths.length !== data.length) { + return NextResponse.json({ error: "Each chunk needs a path, an offset and data", code: "invalid_attachment" }, { status: 400 }); + } + const chunks: AttachmentChunk[] = []; + for (let index = 0; index < paths.length; index += 1) { + const chunkPath = paths[index]; + const offset = offsets[index]; + const blob = data[index]; + if (typeof chunkPath !== "string" || typeof offset !== "string" || !/^\d+$/.test(offset) || typeof blob === "string") { + return NextResponse.json({ error: "Malformed attachment chunk", code: "invalid_attachment" }, { status: 400 }); + } + chunks.push({ path: chunkPath, offset: Number(offset), data: new Uint8Array(await blob.arrayBuffer()) }); + } + await writeAttachmentChunks(batchId, chunks); + return NextResponse.json({ ok: true }); + } catch (error) { + return errorResponse(error); + } +} + +/** POST → 200 { batchId, kind, name, path, size, fileCount } once every byte arrived. */ +export async function POST(_request: Request, { params }: Params) { + try { + const { batchId } = await params; + return NextResponse.json(await completeAttachmentBatch(batchId)); + } catch (error) { + return errorResponse(error); + } +} diff --git a/app/api/attachments/route.ts b/app/api/attachments/route.ts new file mode 100644 index 000000000..04120710e --- /dev/null +++ b/app/api/attachments/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { + AttachmentError, + createAttachmentBatch, + maybePruneAttachmentBatches, + parseAttachmentBatchRequest, +} from "@/lib/attachment-store"; + +export const dynamic = "force-dynamic"; + +// 2,000 paths of up to 1,024 characters each, plus JSON punctuation. +const MAX_BATCH_REQUEST_BYTES = 3 * 1024 * 1024; + +/** POST { kind, name, files: [{ path, size }] } → 201 { batchId }. Every cap + * and path is checked here, before any file byte is uploaded. */ +export async function POST(request: Request) { + try { + let body: unknown; + try { + body = await parseJsonWithinLimit(request, MAX_BATCH_REQUEST_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return NextResponse.json({ error: "Attachment manifest is too large", code: "attachment_manifest_too_large" }, { status: 413 }); + } + return NextResponse.json({ error: "Invalid JSON body", code: "invalid_attachment" }, { status: 400 }); + } + const batch = parseAttachmentBatchRequest(body); + await maybePruneAttachmentBatches(); + return NextResponse.json(await createAttachmentBatch(batch), { status: 201 }); + } catch (error) { + if (error instanceof AttachmentError) { + return NextResponse.json({ error: error.message, code: error.code }, { status: error.status }); + } + return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + } +} diff --git a/components/ChatInput-draft-attachments.ts b/components/ChatInput-draft-attachments.ts index b4fb8d6ef..5991ef0c6 100644 --- a/components/ChatInput-draft-attachments.ts +++ b/components/ChatInput-draft-attachments.ts @@ -1,5 +1,5 @@ -import type { ChatDraftFile, ChatDraftImage } from "@/lib/draft-store"; -import type { AttachedTextFileData } from "@/lib/chat-attachments"; +import type { ChatDraftFile, ChatDraftImage, ChatDraftReference } from "@/lib/draft-store"; +import { isAttachmentReferenceData, type AttachedTextFileData, type AttachmentReferenceData } from "@/lib/chat-attachments"; import { isBase64ImageWithinLimits } from "@/lib/image-attachments"; export interface AttachedImage { @@ -9,6 +9,7 @@ export interface AttachedImage { } export type AttachedTextFile = AttachedTextFileData; +export type AttachedReference = AttachmentReferenceData; export function imageToDraftImage(image: AttachedImage): ChatDraftImage { return { data: image.data, mimeType: image.mimeType }; @@ -45,6 +46,11 @@ export function draftFilesToAttachedFiles(files: ChatDraftFile[] | undefined): A && file.size >= 0); } +/** Uploaded paths are plain data; keep every well-formed one. */ +export function draftReferencesToAttachedReferences(references: ChatDraftReference[] | undefined): AttachedReference[] { + return (references ?? []).filter(isAttachmentReferenceData); +} + export function revokeImagePreview(image: AttachedImage): void { if (image.previewUrl.startsWith("blob:")) { URL.revokeObjectURL(image.previewUrl); diff --git a/components/ChatInput.attachment-references.test.mjs b/components/ChatInput.attachment-references.test.mjs new file mode 100644 index 000000000..d1cf01a7d --- /dev/null +++ b/components/ChatInput.attachment-references.test.mjs @@ -0,0 +1,194 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach, beforeEach } from "node:test"; +import React, { act } from "react"; +import { cleanup, render, screen, waitFor } from "@testing-library/react/pure.js"; +import userEvent from "@testing-library/user-event"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); +const { ChatInput } = await jiti.import("./ChatInput.tsx"); +const { clearDraft, getDraft } = await jiti.import("@/lib/draft-store"); +const { MAX_ATTACHED_TEXT_BYTES } = await jiti.import("@/lib/chat-attachments"); + +const KEY = "attachment-references"; +const OTHER_KEY = "attachment-references-other"; +const PDF_BYTES = Uint8Array.of(0x25, 0x50, 0x44, 0x46, 0x00, 0x01); + +const previousFetch = globalThis.fetch; +afterEach(() => { + try { + cleanup(); + } finally { + clearDraft(KEY); + clearDraft(OTHER_KEY); + localStorage.clear(); + delete window.matchMedia; + globalThis.fetch = previousFetch; + } +}); +beforeEach(() => { + window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); +}); + +/** In-memory /api/attachments. `holdCompletion()` keeps the final POST open. */ +function installAttachmentServer() { + const batches = new Map(); + const requests = []; + let held = null; + globalThis.fetch = async (url, init = {}) => { + const method = init.method ?? "GET"; + requests.push(`${method} ${url}`); + if (url === "/api/attachments" && method === "POST") { + const batchId = `00000000-0000-4000-8000-${String(batches.size).padStart(12, "0")}`; + batches.set(batchId, JSON.parse(init.body)); + return Response.json({ batchId }, { status: 201 }); + } + const batchId = decodeURIComponent(String(url).split("/").pop()); + const batch = batches.get(batchId); + if (!batch) return Response.json({ error: "Attachment not found", code: "attachment_not_found" }, { status: 404 }); + if (method === "PUT") return Response.json({ ok: true }); + if (held) await held.promise; + return Response.json({ + batchId, + kind: batch.kind, + name: batch.name, + path: `/srv/attachments/${batchId}/${batch.name}`, + size: batch.files.reduce((total, file) => total + file.size, 0), + fileCount: batch.files.length, + }); + }; + return { + batches, + requests, + holdCompletion() { + let release; + held = { promise: new Promise((resolve) => { release = resolve; }) }; + return () => { held = null; release(); }; + }, + }; +} + +function renderComposer(props = {}) { + const sent = []; + const ref = React.createRef(); + const inputProps = { + ref, + draftKey: KEY, + isStreaming: false, + onSend: async (message) => { + sent.push(message); + return { status: "accepted" }; + }, + onAbort() {}, + ...props, + }; + const view = render(React.createElement(ChatInput, inputProps)); + return { sent, ref, rerender: (changes) => view.rerender(React.createElement(ChatInput, { ...inputProps, ...changes })) }; +} + +test("a binary file becomes an uploaded path reference that the sent prompt lists", async () => { + const server = installAttachmentServer(); + const user = userEvent.setup(); + const { sent, ref } = renderComposer(); + await act(async () => { + ref.current.addFiles([new File([PDF_BYTES], "report.pdf", { type: "application/pdf" })]); + }); + await waitFor(() => assert.equal(getDraft(KEY)?.references?.length, 1)); + const [reference] = getDraft(KEY).references; + assert.equal(reference.name, "report.pdf"); + assert.equal(reference.kind, "file"); + assert.deepEqual(getDraft(KEY).files, [], "binary content is never inlined"); + assert.deepEqual([...server.batches.values()][0], { kind: "file", name: "report.pdf", files: [{ path: "report.pdf", size: 6 }] }); + assert.ok(screen.getByText("report.pdf")); + assert.equal(screen.queryByRole("alert"), null, "nothing is reported as skipped"); + + await user.type(screen.getByRole("textbox"), "Summarize"); + await user.click(screen.getByRole("button", { name: /^send$/i })); + await waitFor(() => assert.equal(sent.length, 1)); + assert.equal( + sent[0], + `Summarize\n\nAttached paths (uploaded by the user; read them with your tools as needed):\n- ${reference.path} (file, 6 B)`, + ); + await waitFor(() => assert.equal(getDraft(KEY), null), "sending clears the reference with the draft"); +}); + +test("text too large to inline is uploaded instead of skipped", async () => { + installAttachmentServer(); + const { ref } = renderComposer(); + await act(async () => { + ref.current.addFiles([ + new File(["x".repeat(MAX_ATTACHED_TEXT_BYTES + 1)], "huge.log", { type: "text/plain" }), + new File(["small"], "small.txt", { type: "text/plain" }), + ]); + }); + await waitFor(() => { + assert.deepEqual(getDraft(KEY)?.references?.map((item) => item.name), ["huge.log"]); + assert.deepEqual(getDraft(KEY)?.files.map((file) => file.name), ["small.txt"]); + }); +}); + +test("a folder upload shows its file count, holds back sending until done, and survives navigation", async () => { + const server = installAttachmentServer(); + const release = server.holdCompletion(); + const user = userEvent.setup(); + const { sent, ref, rerender } = renderComposer(); + const folder = { + name: "dataset", + entries: async () => [ + { path: "dataset/a.csv", file: new File(["1,2"], "a.csv") }, + { path: "dataset/sub/b.bin", file: new File([PDF_BYTES], "b.bin") }, + ], + }; + act(() => { ref.current.addFolders([folder]); }); + assert.ok(await screen.findByRole("status", { name: "Uploading dataset" })); + await user.type(screen.getByRole("textbox"), "look"); + await user.click(screen.getByRole("button", { name: /^send$/i })); + assert.match((await screen.findByRole("alert")).textContent, /still uploading/); + assert.deepEqual(sent, [], "a send during the upload is refused"); + + await act(async () => { release(); }); + await waitFor(() => assert.equal(getDraft(KEY)?.references?.length, 1)); + assert.deepEqual([...server.batches.values()][0].files, [ + { path: "dataset/a.csv", size: 3 }, + { path: "dataset/sub/b.bin", size: 6 }, + ]); + assert.ok(screen.getByText("dataset/")); + assert.ok(screen.getByText("2 files · 9 B")); + + // Switching away and back restores the chip from the draft. + rerender({ draftKey: OTHER_KEY }); + assert.equal(screen.queryByText("dataset/"), null); + rerender({ draftKey: KEY }); + assert.ok(screen.getByText("dataset/")); + + await user.click(screen.getByRole("button", { name: /^send$/i })); + await waitFor(() => assert.equal(sent.length, 1)); + const [batchId] = server.batches.keys(); + assert.ok(sent[0].endsWith(`- /srv/attachments/${batchId}/dataset/ (folder, 2 files, 9 B)`), sent[0]); +}); + +test("removing a reference chip drops it from the prompt", async () => { + installAttachmentServer(); + const user = userEvent.setup(); + const { sent, ref } = renderComposer(); + await act(async () => { + ref.current.addFiles([new File([PDF_BYTES], "drop.zip", { type: "application/zip" })]); + }); + await waitFor(() => assert.equal(getDraft(KEY)?.references?.length, 1)); + await user.click(screen.getByRole("button", { name: "Remove attachment" })); + assert.equal(getDraft(KEY), null); + await user.type(screen.getByRole("textbox"), "plain"); + await user.click(screen.getByRole("button", { name: /^send$/i })); + await waitFor(() => assert.deepEqual(sent, ["plain"])); +}); + +test("a failed upload reports the server's reason", async () => { + globalThis.fetch = async () => Response.json({ error: "Invalid attachment name: bad", code: "invalid_attachment" }, { status: 400 }); + const { ref } = renderComposer(); + await act(async () => { + ref.current.addFiles([new File([PDF_BYTES], "bad.bin", { type: "application/octet-stream" })]); + }); + assert.equal((await screen.findByRole("alert")).textContent, "Could not upload bad.bin: Invalid attachment name: bad"); + assert.equal(getDraft(KEY), null); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index dacc49fc8..a51118686 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -2,7 +2,7 @@ import React, { useRef, useState, useCallback, useEffect, useLayoutEffect, useImperativeHandle, forwardRef, memo, KeyboardEvent } from "react"; import { createPortal } from "react-dom"; -import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Mic, Paperclip, Plus, RotateCw, Shrink, Snail, Sparkles, Wrench, X, Zap } from "lucide-react"; +import { ChevronDown, ClipboardPaste, CornerDownRight, FolderPlus, ListChecks, Loader2, Mic, Paperclip, Plus, RotateCw, Shrink, Snail, Sparkles, Wrench, X, Zap } from "lucide-react"; import { getSubmitDuringRunBehavior, isWordCompletionEnabled } from "@/lib/composer-prefs"; import type { BuiltinSlashCommandResult, CompactResultInfo, PromptSubmissionResult, QueuedMessages, SlashCommandInfo } from "@/hooks/useAgentSession"; import type { ActiveGoal, ActivePlan } from "@/lib/web-mode-state"; @@ -17,10 +17,11 @@ import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; import { clearDraft, getDraft, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftRecovery, type ChatDraft, type ChatDraftImage } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; -import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; +import type { AttachedImage, AttachedReference, AttachedTextFile } from "./ChatInput-draft-attachments"; import { draftFilesToAttachedFiles, draftImagesToAttachedImages, + draftReferencesToAttachedReferences, imageToDraftImage, revokeImagePreview, textFileToDraftFile, @@ -48,12 +49,24 @@ import { ModelPickerPanel } from "./ChatInput-model-picker"; import { ComposerModeStatus, ModelErrorBanner, QueuedActionButton } from "./ChatInput-banners"; import { CHAT_COLUMN_MAX_WIDTH } from "@/lib/chat-layout"; import { - composeMessageWithTextAttachments, - describeTextAttachmentSkip, + composeMessageWithAttachments, + exceededAttachmentBatchLimit, formatAttachmentBytes, + formatReferenceBytes, + isBinaryText, MAX_ATTACHED_TEXT_FILES, + MAX_ATTACHMENT_BATCH_BYTES, + MAX_ATTACHMENT_BATCH_FILES, selectTextAttachments, + type AttachmentReferenceKind, } from "@/lib/chat-attachments"; +import { + AttachmentUploadError, + foldersFromDirectoryInput, + uploadAttachment, + type AttachmentUploadEntry, + type FolderAttachmentSource, +} from "@/lib/attachment-upload"; import { MAX_ATTACHED_IMAGE_BYTES, MAX_ATTACHED_IMAGES, @@ -248,10 +261,24 @@ export interface ChatInputHandle { insertIfEmpty: (text: string) => void; prependText: (text: string) => void; addFiles: (files: File[]) => void; + /** Upload folders (picked or dropped) as path references. */ + addFolders: (folders: FolderAttachmentSource[]) => void; openContextPanel: () => void; /** Retarget captured queue recoveries before a confirmed move can render. */ retargetPendingRecovery: (from: string, to: string) => void; } + +/** A file or folder upload in flight (`/api/attachments`). Counts are null + * until a dropped folder has been walked. */ +interface PendingReferenceUpload { + id: number; + kind: AttachmentReferenceKind; + name: string; + fileCount: number | null; + size: number | null; + uploaded: number; +} + const COMPOSITION_END_ENTER_GRACE_MS = 100; // The history / slash / @ menus are absolutely positioned relative to the @@ -423,9 +450,15 @@ export const ChatInput = memo(forwardRef(function ChatIn const [attachedTextFiles, setAttachedTextFiles] = useState(() => ( draftKey ? draftFilesToAttachedFiles(getDraft(draftKey)?.files) : [] )); + const [attachedReferences, setAttachedReferences] = useState(() => ( + draftKey ? draftReferencesToAttachedReferences(getDraft(draftKey)?.references) : [] + )); + // Uploads still in flight: shown as chips, and they hold back sending. + const [pendingReferences, setPendingReferences] = useState([]); const [attachError, setAttachError] = useState(null); const trimmedValue = value.trimStart(); - const bashMode = attachedImages.length === 0 && attachedTextFiles.length === 0 && trimmedValue.startsWith("!"); + const hasAttachments = attachedImages.length > 0 || attachedTextFiles.length > 0 || attachedReferences.length > 0; + const bashMode = !hasAttachments && trimmedValue.startsWith("!"); const bashExcluded = bashMode && trimmedValue.startsWith("!!"); const [slashMenuOpen, setSlashMenuOpen] = useState(false); const [slashActiveIndex, setSlashActiveIndex] = useState(0); @@ -457,6 +490,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const slashMenuRef = useRef(null); const atMenuRef = useRef(null); const fileInputRef = useRef(null); + const folderInputRef = useRef(null); const isComposingRef = useRef(false); const lastCompositionEndAtRef = useRef(0); const slashCommandsRequestedRef = useRef(false); @@ -476,6 +510,12 @@ export const ChatInput = memo(forwardRef(function ChatIn const valueRef = useRef(value); const attachedImagesRef = useRef(attachedImages); const attachedTextFilesRef = useRef(attachedTextFiles); + const attachedReferencesRef = useRef(attachedReferences); + const nextPendingReferenceIdRef = useRef(0); + // Upload id → the attachment revision it started in. Counted synchronously + // so a send right after a pick is held back before the chip has rendered; + // uploads from a cleared or navigated-away composer no longer count. + const pendingReferenceRevisionsRef = useRef(new Map()); // Bumped whenever the user clears/sends the composer: in-flight FileReader // and file.text() reads must not re-append their results afterwards. const attachmentRevisionRef = useRef(0); @@ -487,6 +527,7 @@ export const ChatInput = memo(forwardRef(function ChatIn valueRef.current = value; attachedImagesRef.current = attachedImages; attachedTextFilesRef.current = attachedTextFiles; + attachedReferencesRef.current = attachedReferences; const insertTextAtCursor = useCallback((text: string) => { const ta = textareaRef.current; @@ -554,6 +595,9 @@ export const ChatInput = memo(forwardRef(function ChatIn addFiles(files: File[]) { processFiles(files); }, + addFolders(folders: FolderAttachmentSource[]) { + attachFolders(folders); + }, openContextPanel() { setContextOpen(true); }, @@ -629,26 +673,79 @@ export const ChatInput = memo(forwardRef(function ChatIn } }, []); + /** Upload one file or folder as a path reference. Its chip shows while it + * uploads. A clear/send/navigation (revision bump) drops the result and + * leaves the server batch for pruning; an Edit move keeps it, like reads. */ + const uploadReference = useCallback(async ( + kind: AttachmentReferenceKind, + name: string, + listEntries: () => Promise, + ) => { + const revision = attachmentRevisionRef.current; + const id = nextPendingReferenceIdRef.current++; + const updatePending = (changes: Partial) => { + setPendingReferences((prev) => prev.map((item) => (item.id === id ? { ...item, ...changes } : item))); + }; + const limitMessage = (code: string | undefined) => { + if (code === "attachment_too_many_files") return t("chatInput.attachmentTooManyFiles", { name, count: MAX_ATTACHMENT_BATCH_FILES }); + if (code === "attachment_batch_too_large") return t("chatInput.attachmentTooLarge", { name, size: formatAttachmentBytes(MAX_ATTACHMENT_BATCH_BYTES) }); + return null; + }; + pendingReferenceRevisionsRef.current.set(id, revision); + setPendingReferences((prev) => [...prev, { id, kind, name, fileCount: null, size: null, uploaded: 0 }]); + try { + const entries = await listEntries(); + if (attachmentRevisionRef.current !== revision) return; + if (entries.length === 0) { + setAttachError(t("chatInput.attachmentFolderEmpty", { name })); + return; + } + const size = entries.reduce((total, entry) => total + entry.file.size, 0); + const limit = exceededAttachmentBatchLimit(entries.length, size); + if (limit) { + setAttachError(limitMessage(limit.code)); + return; + } + updatePending({ fileCount: entries.length, size }); + const reference = await uploadAttachment({ kind, name, entries }, { + onProgress: (uploaded) => updatePending({ uploaded }), + }); + if (attachmentRevisionRef.current !== revision) return; + setAttachedReferences((prev) => [...prev, reference]); + } catch (error) { + if (attachmentRevisionRef.current !== revision) return; + const code = error instanceof AttachmentUploadError ? error.code : undefined; + setAttachError(limitMessage(code) ?? t("chatInput.attachmentUploadFailed", { + name, + error: error instanceof Error ? error.message : String(error), + })); + } finally { + pendingReferenceRevisionsRef.current.delete(id); + setPendingReferences((prev) => prev.filter((item) => item.id !== id)); + } + }, [t]); + + const attachFileReferences = useCallback((files: readonly File[]) => { + for (const file of files) void uploadReference("file", file.name, async () => [{ path: file.name, file }]); + }, [uploadReference]); + + const attachFolders = useCallback((folders: readonly FolderAttachmentSource[]) => { + for (const folder of folders) { + void uploadReference("folder", folder.name, () => folder.entries(MAX_ATTACHMENT_BATCH_FILES)); + } + }, [uploadReference]); + + /** Small text files are inlined; anything else (too large, over the + * message budget or slots, or binary) is uploaded as a path reference. */ const processTextFiles = useCallback(async (files: File[]) => { - const remaining = Math.max( - 0, - MAX_ATTACHED_TEXT_FILES - attachedTextFilesRef.current.length - pendingTextFileCountRef.current, - ); // In-flight batches reserve their bytes too, so two overlapping drops // cannot each fit under the aggregate budget on their own. - const { accepted: textFiles, tooLarge, overBudget } = selectTextAttachments(files, { + const { accepted: textFiles, overflow } = selectTextAttachments(files, { usedBytes: attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + pendingTextFileBytesRef.current, usedSlots: attachedTextFilesRef.current.length + pendingTextFileCountRef.current, }); - // Report every dropped candidate, not just an entirely rejected batch: a - // drop of several files can lose some to the budget while accepting others. - const limitMessage = remaining === 0 && files.length > 0 - ? t("chatInput.attachmentTextFilesLimit", { count: MAX_ATTACHED_TEXT_FILES }) - : describeTextAttachmentSkip({ tooLarge, overBudget }); - if (!textFiles.length) { - if (files.length > 0) setAttachError(limitMessage ?? t("chatInput.attachmentFilesSkipped", { count: files.length })); - return; - } + attachFileReferences(overflow); + if (!textFiles.length) return; const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; pendingTextFileCountRef.current += textFiles.length; @@ -665,30 +762,21 @@ export const ChatInput = memo(forwardRef(function ChatIn // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. if (attachmentRevisionRef.current !== revision) return; - // Binary content cannot be inlined into the prompt: NUL bytes, or - // U+FFFD replacement characters left by mis-decoded binary (e.g. - // UTF-16 text read as UTF-8). - const newFiles = readFiles.filter( - (file) => !file.content.includes("\u0000") && !file.content.includes("\uFFFD"), - ); - const skipped = textFiles.length - newFiles.length; + const newFiles = readFiles.filter((file) => !isBinaryText(file.content)); + attachFileReferences(textFiles.filter((_, index) => isBinaryText(readFiles[index].content))); setAttachedTextFiles((prev) => [ ...prev, ...(identityRevision !== attachmentIdentityRevisionRef.current ? newFiles : newFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length))), ]); - setAttachError( - limitMessage - ?? (skipped > 0 ? t("chatInput.attachmentBinarySkipped", { count: skipped }) : null), - ); } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { pendingTextFileCountRef.current -= textFiles.length; pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0); } - }, []); + }, [attachFileReferences, t]); const processFiles = useCallback((files: File[]) => { const imageFiles = files.filter((file) => file.type.startsWith("image/")); @@ -763,6 +851,12 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachError(null); }, []); + // The uploaded batch stays on the server until pruning removes it. + const removeReference = useCallback((index: number) => { + setAttachedReferences((prev) => prev.filter((_, referenceIndex) => referenceIndex !== index)); + setAttachError(null); + }, []); + const clearImages = useCallback(() => { setAttachedImages((prev) => { prev.forEach(revokeImagePreview); @@ -770,10 +864,6 @@ export const ChatInput = memo(forwardRef(function ChatIn }); }, []); - const clearTextFiles = useCallback(() => { - setAttachedTextFiles([]); - }, []); - const clearInput = useCallback(() => { setValue(""); setAtQuery(null); @@ -782,24 +872,27 @@ export const ChatInput = memo(forwardRef(function ChatIn if (draftKey) clearDraft(draftKey); if (draftKeyRef.current && draftKeyRef.current !== draftKey) clearDraft(draftKeyRef.current); clearImages(); - clearTextFiles(); - // Invalidate any attachment reads still in flight. + setAttachedTextFiles([]); + setAttachedReferences([]); + setPendingReferences([]); + // Invalidate any attachment reads and uploads still in flight. attachmentRevisionRef.current += 1; if (textareaRef.current) { textareaRef.current.style.height = "auto"; } - }, [clearImages, clearTextFiles, draftKey]); + }, [clearImages, draftKey]); useLayoutEffect(() => { if (!draftKey || draftKeyRef.current !== draftKey) return; - const draft = { + const draft: ChatDraft = { value, images: attachedImages.map(imageToDraftImage), files: attachedTextFiles.map(textFileToDraftFile), + ...(attachedReferences.length > 0 ? { references: attachedReferences } : {}), }; persistedDraftRef.current = draft; setDraft(draftKey, draft); - }, [attachedImages, attachedTextFiles, draftKey, value]); + }, [attachedImages, attachedReferences, attachedTextFiles, draftKey, value]); useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; @@ -847,6 +940,16 @@ export const ChatInput = memo(forwardRef(function ChatIn }); return [...draftFilesToAttachedFiles(draft?.files), ...added]; }); + setAttachedReferences((current) => { + const remaining = [...(source?.references ?? [])]; + const added = current.filter((reference) => { + const index = remaining.findIndex((item) => item.batchId === reference.batchId); + if (index === -1) return Boolean(source); + remaining.splice(index, 1); + return false; + }); + return [...draftReferencesToAttachedReferences(draft?.references), ...added]; + }); setQueuedDeleteTarget(null); return; } @@ -860,10 +963,12 @@ export const ChatInput = memo(forwardRef(function ChatIn setQueuedDeleteTarget(null); if (previousDraftKey) { + const references = attachedReferencesRef.current; setDraft(previousDraftKey, { value: valueRef.current, images: attachedImagesRef.current.map(imageToDraftImage), files: attachedTextFilesRef.current.map(textFileToDraftFile), + ...(references.length > 0 ? { references } : {}), }); } @@ -878,6 +983,8 @@ export const ChatInput = memo(forwardRef(function ChatIn return draftImagesToAttachedImages(draft?.images); }); setAttachedTextFiles(draftFilesToAttachedFiles(draft?.files)); + setAttachedReferences(draftReferencesToAttachedReferences(draft?.references)); + setPendingReferences([]); }, [draftKey, draftIdentityMove]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { @@ -936,6 +1043,15 @@ export const ChatInput = memo(forwardRef(function ChatIn return error !== null; }, []); + /** An upload still running would be missing from the prompt: hold the send + * (draft and chips kept) until it lands. */ + const refusesWhileUploading = useCallback((): boolean => { + const revision = attachmentRevisionRef.current; + if (![...pendingReferenceRevisionsRef.current.values()].includes(revision)) return false; + setAttachError(t("chatInput.attachmentUploadsPending")); + return true; + }, [t]); + /** Run a client builtin. True once handled; the composer is cleared only on * success and only if it still holds what was sent (the user may have * started typing while the command ran). */ @@ -953,7 +1069,7 @@ export const ChatInput = memo(forwardRef(function ChatIn * rather than drop them. False when `msg` is not `/btw`. */ const sendSideQuestion = useCallback((msg: string, overrideText?: string): boolean => { if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand) return false; - if (attachedImagesRef.current.length || attachedTextFilesRef.current.length) { + if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedReferencesRef.current.length) { toast.error(t("btw.attachmentsUnsupported")); return true; } @@ -964,12 +1080,16 @@ export const ChatInput = memo(forwardRef(function ChatIn const handleSend = useCallback(async (overrideText?: string) => { const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; + if (refusesWhileUploading()) return; + const hasAttachedContent = attachedImagesRef.current.length > 0 + || attachedTextFilesRef.current.length > 0 + || attachedReferencesRef.current.length > 0; + if (!msg && !hasAttachedContent) return; if (submissionBlockedRef.current || isStreaming) return; onAudioUnlock?.(); if (sendSideQuestion(msg, overrideText)) return; - const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); - if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && msg.startsWith("/") && onBuiltinCommand) { + const composedMessage = composeMessageWithAttachments(msg, attachedTextFilesRef.current, attachedReferencesRef.current); + if (!hasAttachedContent && msg.startsWith("/") && onBuiltinCommand) { const expansion = expandWebSlashCommand(msg); if (expansion.kind === "expand" && rejectsOversizedPrompt(expansion.prompt, attachedImagesRef.current)) return; if (await runBuiltinCommand(msg, overrideText)) return; @@ -991,7 +1111,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, refusesWhileUploading, rejectsOversizedPrompt, runBuiltinCommand, sendSideQuestion]); const { isRecording, isPaused, @@ -1431,7 +1551,8 @@ export const ChatInput = memo(forwardRef(function ChatIn if (submissionBlockedRef.current) return; const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; + if (refusesWhileUploading()) return; + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedReferencesRef.current.length) return; if (sendSideQuestion(msg, overrideText)) return; const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; // The queue callbacks resolve false when omp refused the message: it goes @@ -1445,6 +1566,7 @@ export const ChatInput = memo(forwardRef(function ChatIn }); }; const files = attachedTextFilesRef.current; + const references = attachedReferencesRef.current; onAudioUnlock?.(); const streamingBehavior = mode === "steer" ? "steer" : "followUp"; if (msg.startsWith("/") && onPromptWithStreamingBehavior) { @@ -1461,7 +1583,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // own ACP handlers can run them. const expansion = expandWebSlashCommand(msg); if (expansion.kind === "expand") { - const prompt = composeMessageWithTextAttachments(expansion.prompt, files); + const prompt = composeMessageWithAttachments(expansion.prompt, files, references); if (rejectsOversizedPrompt(prompt, attachedImagesRef.current)) return; recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images), prompt); clearInput(); @@ -1474,13 +1596,13 @@ export const ChatInput = memo(forwardRef(function ChatIn })); return; } - const prompt = composeMessageWithTextAttachments(msg, files); + const prompt = composeMessageWithAttachments(msg, files, references); if (rejectsOversizedPrompt(prompt, attachedImagesRef.current)) return; recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images), prompt); clearInput(); return; } - const composedMessage = composeMessageWithTextAttachments(msg, files); + const composedMessage = composeMessageWithAttachments(msg, files, references); if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; if (mode === "steer" && onSteer) { recoverOnFailure(onSteer(composedMessage, images), composedMessage); @@ -1488,7 +1610,7 @@ export const ChatInput = memo(forwardRef(function ChatIn recoverOnFailure(onFollowUp(composedMessage, images), composedMessage); } clearInput(); - }, [value, onPromptWithStreamingBehavior, onSteer, onFollowUp, clearInput, onAudioUnlock, t, advisorEnabled, rejectsOversizedPrompt, sendSideQuestion]); + }, [value, onPromptWithStreamingBehavior, onSteer, onFollowUp, clearInput, onAudioUnlock, t, advisorEnabled, refusesWhileUploading, rejectsOversizedPrompt, sendSideQuestion]); // A typed message or attachment during a run is a queued follow-up — and so // is a dictation in progress: the primary button must take the same state it // would have if the composer already held text. Keep Stop as the action @@ -1496,7 +1618,7 @@ export const ChatInput = memo(forwardRef(function ChatIn const dictationCapturing = isRecording || isPaused || isReviewing; const primaryActionQueuesMessage = isStreaming - && (Boolean(value.trim()) || attachedImages.length > 0 || attachedTextFiles.length > 0 || dictationCapturing) + && (Boolean(value.trim()) || hasAttachments || dictationCapturing) && Boolean(onFollowUp); // The button follows the same Settings choice as Enter: soft keyboards have no // Enter to submit with, so this button is how touch devices steer. @@ -1777,12 +1899,14 @@ export const ChatInput = memo(forwardRef(function ChatIn ); + // Pasted files (an image, or files copied in a file manager) attach like + // picked ones; plain-text pastes stay ordinary typing. const handlePaste = useCallback((e: React.ClipboardEvent) => { const items = Array.from(e.clipboardData?.items ?? []); - const imageItems = items.filter((item) => item.type.startsWith("image/")); - if (!imageItems.length) return; + const fileItems = items.filter((item) => item.kind === "file" || item.type.startsWith("image/")); + if (!fileItems.length) return; e.preventDefault(); - const files = imageItems.map((item) => item.getAsFile()).filter((f): f is File => f !== null); + const files = fileItems.map((item) => item.getAsFile()).filter((f): f is File => f !== null); processFiles(files); }, [processFiles]); @@ -2012,6 +2136,16 @@ export const ChatInput = memo(forwardRef(function ChatIn background: "transparent", color: "var(--text-muted)", cursor: "pointer", fontSize: 12, textAlign: "left", }; + const attachmentChipStyle: React.CSSProperties = { + display: "flex", alignItems: "center", gap: 7, + maxWidth: 260, height: 30, + padding: "0 6px 0 9px", + border: "1px solid var(--border)", + borderRadius: 6, + background: "var(--bg-panel)", + fontSize: 12, + color: "var(--text)", + }; return (
(function ChatIn (function ChatIn e.target.value = ""; }} /> + {/* Hidden folder input: each picked folder is uploaded as one reference. */} + { + const { folders, looseFiles } = foldersFromDirectoryInput(Array.from(e.target.files ?? [])); + attachFolders(folders); + if (looseFiles.length) processFiles(looseFiles); + e.target.value = ""; + }} + />
@@ -2158,21 +2306,12 @@ export const ChatInput = memo(forwardRef(function ChatIn ))}
)} - {attachedTextFiles.length > 0 && ( + {(attachedTextFiles.length > 0 || attachedReferences.length > 0 || pendingReferences.length > 0) && (
{attachedTextFiles.map((file, i) => (
@@ -2214,6 +2353,75 @@ export const ChatInput = memo(forwardRef(function ChatIn
))} + {attachedReferences.map((reference, i) => ( +
+ + {reference.kind === "folder" ? : getFileIcon(reference.name, 13)} + + + {reference.kind === "folder" ? `${reference.name}/` : reference.name} + + + {reference.kind === "folder" + ? `${tn("chatInput.referenceFileCount", reference.fileCount)} · ${formatReferenceBytes(reference.size)}` + : formatReferenceBytes(reference.size)} + + +
+ ))} + {pendingReferences.map((pending) => ( +
+
+ ))}
)} @@ -2980,6 +3188,16 @@ export const ChatInput = memo(forwardRef(function ChatIn