A local-first multi-agent app development platform, built on PenguinHarness
feat(web): drag-and-drop file upload onto the chat area (#319)
Yaowei Zhenge661e66cdf56
diff --git a/changelog/unreleased/2026-08-18-web-drag-drop-upload.md b/changelog/unreleased/2026-08-18-web-drag-drop-upload.mdnew file mode 100644index 00000000..04de9b2f--- /dev/null+++ b/changelog/unreleased/2026-08-18-web-drag-drop-upload.md@@ -0,0 +1,29 @@+# Composer attachments: drag files onto the chat area++- **Date:** 2026-08-18+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#319](https://github.com/Prism-Shadow/penguin-harness/pull/319)+- **Issue:** [#311](https://github.com/Prism-Shadow/penguin-harness/issues/311)++[中文版](2026-08-18-web-drag-drop-upload.zh.md)++Dragging OS files onto the **chat area** — the conversation and the composer — became a third entry point into the composer's existing attachment intake, alongside the "+" menu's pickers and image paste. Until then a file dropped on the page got the browser's default: the tab navigated to the file, replacing the running app and any unsent draft.++## Dropping on the chat area++- A file drag over the chat area shows a "Drop files to attach" overlay bounded to that region, and releasing hands the whole batch to the composer. It works on the chat page and the draft page alike, and while a Task is running just the same.+- Images join the pasted-image pipeline (`image_url` parts; vision-less models keep the scratchpad-path fallback), everything else becomes a file attachment (scratchpad plus an `[attached file: <path>]` line). Validation and errors match the "+" menu — an oversize file is refused before it is read, with the existing toast.+- Goal mode takes dropped images and refuses dropped files with a toast, the same rule that grays out the "+" menu's file entry there.+- Non-file drags are ignored everywhere — text selections, dragged links and page images, the sidebar's session reorder — so dropping selected text into the composer still inserts it natively.++## Outside the chat area++- The sidebar, the top bar, the conversation toolbar, the docked Files and Subagents panels and every page without a composer sit outside the drop target: no overlay lights up and nothing is attached.+- An app-shell guard (`guardWindowDragOver` / `guardWindowDrop`) cancels the browser's navigate-to-file default for any file drag the chat area did not claim, and shows the no-drop cursor while such a drag hovers. It was kept deliberately silent — no overlay, no attachment, no toast — so that a file dropped there does nothing at all instead of discarding the app.++## Details++- The overlay is re-derived on every event from the drag's current position rather than accumulated from enter/leave counts, so a drag that ends outside the browser — firing neither `drop` nor `dragend` — cannot strand it on screen.+- The decision logic — file-drag detection, the region hit test, batch splitting and the shell guard — landed in `packages/web/src/lib/file-drop.ts`, kept DOM-free and covered by unit tests; `ChatDropRegion` and `FileDropZone` in `packages/web/src/features/chat/drop-zone.tsx` bind it to the chat column and the composer.+- The web-app docs page describes the flow in both languages.diff --git a/changelog/unreleased/2026-08-18-web-drag-drop-upload.zh.md b/changelog/unreleased/2026-08-18-web-drag-drop-upload.zh.mdnew file mode 100644index 00000000..ed491543--- /dev/null+++ b/changelog/unreleased/2026-08-18-web-drag-drop-upload.zh.md@@ -0,0 +1,29 @@+# 输入框附件:把文件拖拽到聊天区++- **Date:** 2026-08-18+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#319](https://github.com/Prism-Shadow/penguin-harness/pull/319)+- **Issue:** [#311](https://github.com/Prism-Shadow/penguin-harness/issues/311)++[English](2026-08-18-web-drag-drop-upload.md)++把操作系统的文件拖拽到**聊天区**(即对话与输入框所在的区域),成为输入框既有附件通道的第三个入口,与「+」菜单的选择器和粘贴图片并列。在此之前,文件被放到页面上只会触发浏览器的默认行为:标签页跳转去打开该文件,正在运行的应用连同尚未发送的草稿一起被顶掉。++## 拖到聊天区++- 文件拖动经过聊天区时,会显示一层限定在该区域内的「松开以添加附件」浮层,松手即把整批文件交给输入框。会话页与草稿页都可用,Task 运行期间同样可用。+- 图片走粘贴图片的同一管线(`image_url` 部件;不支持视觉的模型仍回退为 scratchpad 路径),其余文件成为文件附件(写入 scratchpad,并追加一行 `[attached file: <path>]`)。校验与报错与「+」菜单一致——超限的文件在读取前即被拒绝,弹出原有的提示。+- 目标模式接受拖入的图片,拖入文件则以提示拒绝,与该模式下「+」菜单把文件项置灰是同一条规则。+- 非文件的拖动在任何位置都被忽略——选中的文本、拖动的链接与页面图片、侧边栏的会话拖动排序——所以把选中的文本拖进输入框,依旧是浏览器原生的插入行为。++## 聊天区之外++- 侧边栏、顶栏、对话工具条、右侧停靠的 Files 与 Subagents 面板,以及任何没有输入框的页面,都在拖放目标之外:不会亮起浮层,也不会添加任何附件。+- 应用外壳上的一道守卫(`guardWindowDragOver` / `guardWindowDrop`)会取消浏览器「跳转去打开文件」的默认行为——只针对聊天区没有接管的文件拖动——并在这类拖动悬停时显示禁止放置的光标。这道守卫刻意保持沉默:不显示浮层、不添加附件、不弹提示,只为让文件放在那里彻底无事发生,而不是把应用丢掉。++## 细节++- 浮层的显隐在每个事件上依据拖动的当前位置重新推导,而不是靠 enter/leave 计数累加,因此拖动若在浏览器之外结束(既不触发 `drop` 也不触发 `dragend`),也不会把浮层永久留在屏幕上。+- 判定逻辑——文件拖动识别、区域命中判断、批次拆分与外壳守卫——落在 `packages/web/src/lib/file-drop.ts`,保持不依赖 DOM 并配有单元测试;`packages/web/src/features/chat/drop-zone.tsx` 中的 `ChatDropRegion` 与 `FileDropZone` 负责把它接到聊天区与输入框上。+- Web 应用文档页以中英两种语言补充了这一流程的说明。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex b1c576fc..dcc8b208 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -57,6 +57,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to- Enter sends, Shift+Enter inserts a newline, and images can be pasted;- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, ≤ 10MB each and 12MB in total; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;+- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area reacts: dropping a file on the sidebar, the top bar, the docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file;- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced;- **Goal mode** (the "+" menu, or `/goal`) turns the draft into an objective the system loops Tasks against. Attached images ride along and are always sent as scratchpad paths (a goal objective is re-injected as text every round — see [Goal mode](/goal-mode)); text is still required, since a picture alone states no objective, and file attachments are refused. Round 1's bubble shows the attachments in full, later rounds collapse them into a chip that expands on click;diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex e30b1cac..946b5aa5 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -57,6 +57,7 @@ penguin web- Enter 发送,Shift+Enter 换行,支持粘贴图片;- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,单个 ≤ 10MB、合计 ≤ 12MB;超限的文件在读取前即被拒绝,不会先上传再报错),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;+- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会响应:把文件放到侧边栏、顶栏、右侧停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件;- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失);- `/agent` 与 `/model` 都是暂存而非立即生效:选中的 Agent 或模型只在文本区上方留下一枚 chip,此时不发送任何内容,可以继续输入——按 Enter / 点发送才真正交接(为该 Agent 新开一个对话)或换用所选模型继续本对话,输入的文字随之带走;正文为空时自动填入默认消息,点 chip 上的 × 即可取消。两枚 chip 都随草稿缓存,刷新页面或切到别的会话再回来时与文字一同恢复;其中切换模型还需等待会话空闲——新会话要从本会话的 Trace 接续,而运行中的一轮或压缩仍在写入——等待期间输入框上方会给出说明;diff --git a/packages/web/src/app.tsx b/packages/web/src/app.tsxindex 40cf1ba7..9dd1ad4e 100644--- a/packages/web/src/app.tsx+++ b/packages/web/src/app.tsx@@ -2,14 +2,33 @@* App root component: Locale -> Theme -> Auth -> LocaleScope -> Router provider composition.* LocaleScope (a remount boundary) sits inside AuthProvider: switching language rebuilds the UI tree without* re-fetching auth, avoiding a full-screen white flash from RequireAuth briefly seeing user=undefined.+ * Also installs the app-wide file-drop guard: a file dropped outside the chat area — the only+ * region that claims file drags (features/chat/drop-zone.tsx) — must not trigger the browser's+ * default navigate-to-file, which would silently replace the running app and any unsent draft.+ * The guard is deliberately silent: no overlay, no attachment, no toast. It does not make a+ * drop on the sidebar do something; it makes it do nothing.*/+import { useEffect } from "react";import { LocaleProvider, LocaleScope } from "./state/locale";import { ThemeProvider } from "./state/theme";import { AuthProvider } from "./state/auth";import { AppRouter } from "./router";import { Toaster } from "./components/ui/toast";+import { guardWindowDragOver, guardWindowDrop } from "./lib/file-drop";export function App() {+ // The guard reads `defaultPrevented` rather than assuming it runs last: the chat area's+ // drop zone is a window listener too, so the two fire in registration order. Both orders+ // converge — whichever runs second either finds the drag already claimed and bails, or+ // upgrades the no-drop cursor to copy (see lib/file-drop.ts).+ useEffect(() => {+ window.addEventListener("dragover", guardWindowDragOver);+ window.addEventListener("drop", guardWindowDrop);+ return () => {+ window.removeEventListener("dragover", guardWindowDragOver);+ window.removeEventListener("drop", guardWindowDrop);+ };+ }, []);return (<LocaleProvider><ThemeProvider>diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex bbddbc18..17cac14c 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -39,7 +39,9 @@* session scratchpad and appends an `[attached file: <path>]` line to the message, so the model* opens them by path), and goal mode; selected files show as removable chips above the text* body, next to the image thumbnails, and — like images — an attachments-only message is- * sendable with no text at all.+ * sendable with no text at all. Dragging files onto the chat area feeds the same two intakes+ * (images → paste pipeline, other files → attachments; see FileDropZone/addDroppedFiles),+ * with an overlay bounded to that region while the drag is over it.* The bottom toolbar provides a searchable multi-select skills dropdown (styled like the model* selector: a top search box filtering by name and localized description, plus a checklist;* clicking a row toggles its selection without closing the menu; the button = book icon + label +@@ -109,6 +111,8 @@ import {import type { HistoryStep } from "./input-history";import { midRunAction } from "./composer-send";import { PAPERCLIP_ICON } from "./attached-files-banner";+import { FileDropZone } from "./drop-zone";+import { splitDroppedFiles } from "../../lib/file-drop";const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];@@ -1907,6 +1911,23 @@ export function ChatInput({if (e.target.files) addAttachments(e.target.files);e.target.value = "";};++ /**+ * Files dropped onto the chat area (see FileDropZone): one batch, routed into the SAME two+ * intakes the "+" menu and paste use — images join the pasted-image pipeline, everything+ * else joins the file-attachment pipeline (10MB cap, same rejection toast). Goal mode takes+ * images but not files (nothing folds a file into the re-injected objective — the "+" menu+ * grays its file entry out for the same reason); a drop has no disabled affordance to gray,+ * so the refusal is said out loud instead of silently swallowing the files.+ */+ const addDroppedFiles = (dropped: File[]) => {+ const batch = splitDroppedFiles(dropped);+ if (batch.images.length > 0) addFiles(batch.images);+ if (batch.files.length > 0) {+ if (goalOn) toastInfo(S.chat.dropFilesGoalHint);+ else addAttachments(batch.files);+ }+ };/*** The image picker moved into the "+" menu, so the file input can no longer be a `<label>`* wrapper: the menu unmounts its items on select. It lives outside the menu instead and the@@ -1918,6 +1939,11 @@ export function ChatInput({return (<div className="relative" ref={anchorRef}>+ {/* Drag-and-drop upload: mounted with the composer (chat page and draft page alike, and+ kept while a Task runs), so dropping works exactly when there is a composer to attach+ to — but bounded to the enclosing ChatDropRegion, so only the chat area reacts.+ Dropped files go through addDroppedFiles into the same intake as the "+" menu. */}+ <FileDropZone onFiles={addDroppedFiles} />{/* Slash command menu (triggered by typing /; /compact plus one entry per installed skill).Height is capped to the room measured above the composer (see upwardMaxH) with internalscrolling, so a long skill list never pushes the menu's top edge out of view; the activediff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 7f1be305..02c0cf36 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -61,6 +61,7 @@ import { MessageStream } from "./message-stream";import type { StreamRenderContext } from "./message-stream";import { latestTaskHasSubagent, taskStartCount } from "./agent-topology";import { ChatInput } from "./chat-input";+import { ChatDropRegion } from "./drop-zone";import { ConversationOutline, OutlineMenuButton, useOutlineRailFit } from "./conversation-outline";import { DraftView } from "./draft-view";import { parkActiveDraft } from "./draft-sessions";@@ -1647,7 +1648,12 @@ export function ChatPage() {{/* Body: chat column + the docked panels on the right (message file cards jump to and locate a file in the tree via onOpenFile). */}<div className="flex min-h-0 flex-1">- <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ {/* The chat area, and the only region a dragged file may be dropped on (#311): it+ covers the conversation and the composer in both branches below, and nothing else+ — the sidebar, the mobile top bar, the toolbar above and the docked panels beside+ it are all outside, where a file drop is inert (see drop-zone.tsx). `relative`+ bounds the drop overlay to this column. */}+ <ChatDropRegion className="relative flex min-h-0 min-w-0 flex-1 flex-col">{draft ? (// Draft state: DraftView's vertically centered input card + Agent / Workspace// selection panel; the Session is only created once the first message is sent. Keyed@@ -1752,7 +1758,7 @@ export function ChatPage() {)}</div>)}- </div>+ </ChatDropRegion>{selected && (<SubagentsPaneldiff --git a/packages/web/src/features/chat/drop-zone.tsx b/packages/web/src/features/chat/drop-zone.tsxnew file mode 100644index 00000000..4e72040c--- /dev/null+++ b/packages/web/src/features/chat/drop-zone.tsx@@ -0,0 +1,152 @@+/**+ * Drop target for composer attachments (#311), scoped to the chat area: dragging OS files+ * over the conversation + composer column shows a "drop to attach" overlay bounded to that+ * column, and releasing hands the batch to the composer's existing intake (images → the+ * pasted-image pipeline, everything else → the file-attachment pipeline; same validation,+ * same errors).+ *+ * Two pieces, because the region and the composer are not the same element:+ * - `ChatDropRegion` wraps the chat column (chat-page.tsx) and publishes its DOM node+ * through context. It is the only element a drop counts on: the sidebar, the mobile top+ * bar, the chat toolbar and the docked Files/Subagents panels sit outside it and are+ * inert, and pages with no chat column never render one.+ * - `FileDropZone` stays mounted by ChatInput, which keeps "dropping works exactly when+ * there is a composer to attach to" true by construction — chat page and draft page+ * alike, and while a Task runs just the same. With no region above it (nothing does that+ * today) it renders nothing and listens for nothing, rather than falling back to the+ * window.+ *+ * The listeners are on `window` even though the target is a region, because the region only+ * needs to be the *subject* of the hit test, not the receiver: a window listener still sees+ * the drag after it has moved off the chat column — over the sidebar, over a docked panel,+ * out of the window — which is exactly when the overlay has to come down. Every event is+ * tested against the region with `contains`, so where the pointer is decides everything and+ * no state accumulates (see dropRegionAction in lib/file-drop.ts for why that matters).+ *+ * The overlay is pure feedback: `pointer-events-none` (so it never becomes the drag target+ * itself and the hit test keeps seeing the real element underneath), `aria-hidden` — it+ * exists only during a pointer drag, and the accessible entry point stays the "+" menu —+ * and `absolute inset-0` portaled into the region, on the overlay z tier (z-50).+ *+ * Interplay with the app-shell guard (see lib/file-drop.ts): over the chat area this+ * component claims the drag — preventDefault on dragover plus a copy cursor — so the guard's+ * no-drop fallback stands aside; everywhere else the guard alone runs, silently cancelling+ * the browser's navigate-to-file default so a stray drop is inert instead of destructive,+ * while non-file drags keep their native behavior. Both orders of the two window listeners+ * converge on the same outcome, so mount order cannot matter.+ */+import { createContext, useContext, useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import { createPortal } from "react-dom";+import { dropRegionAction, isFileDrag } from "../../lib/file-drop";+import type { DragSignal, DropRegionAction } from "../../lib/file-drop";+import { S } from "../../lib/strings";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { PAPERCLIP_ICON } from "./attached-files-banner";++/** The chat area's DOM node, or null when the composer is mounted outside a region. */+const ChatDropRegionContext = createContext<HTMLElement | null>(null);++/**+ * Marks the chat column as the one region file drops apply to. `relative` is the caller's+ * job (the overlay is positioned against this element); the element is held in state rather+ * than a ref so that consumers re-render once it exists.+ *+ * `ref={setRegion}` passes the state setter itself, not a closure over it: React re-invokes a+ * callback ref whenever its identity changes, so an inline arrow would detach (null) and+ * re-attach (element) on every render, and the pair of state updates that produces would+ * schedule the next render — a loop. A useState setter is stable for the component's life.+ */+export function ChatDropRegion({+ className,+ children,+}: {+ className: string;+ children: ReactNode;+}) {+ const [region, setRegion] = useState<HTMLElement | null>(null);+ return (+ <div className={className} ref={setRegion}>+ <ChatDropRegionContext.Provider value={region}>{children}</ChatDropRegionContext.Provider>+ </div>+ );+}++export function FileDropZone({ onFiles }: { onFiles: (files: File[]) => void }) {+ const region = useContext(ChatDropRegionContext);+ const [active, setActive] = useState(false);+ // Mirror of `active` the listeners can read: they are registered once per region, so they+ // close over the mount's render, not the current one.+ const activeRef = useRef(false);+ // Latest callback without re-registering the listeners.+ const onFilesRef = useRef(onFiles);+ useEffect(() => {+ onFilesRef.current = onFiles;+ });++ useEffect(() => {+ if (!region) return;+ /** Is this node the chat area or inside it? A null relatedTarget (drag left the window) is not. */+ const within = (node: EventTarget | null): boolean =>+ node instanceof Node && region.contains(node);+ const apply = (signal: DragSignal, e: DragEvent, inside: boolean): DropRegionAction => {+ const action = dropRegionAction(signal, isFileDrag(e.dataTransfer?.types), inside);+ // dragover fires tens of times a second; only a real change is routed through state.+ if (activeRef.current !== action.active) {+ activeRef.current = action.active;+ setActive(action.active);+ }+ if (action.claim) {+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";+ }+ return action;+ };+ const onDragOver = (e: DragEvent) => {+ apply("over", e, within(e.target));+ };+ // `relatedTarget` is where the drag is going: still inside the region means an internal+ // element boundary was crossed and nothing changed.+ const onDragLeave = (e: DragEvent) => {+ apply("leave", e, within(e.relatedTarget));+ };+ const onDrop = (e: DragEvent) => {+ const action = apply("drop", e, within(e.target));+ if (!action.accept || !e.dataTransfer) return;+ const files = Array.from(e.dataTransfer.files);+ if (files.length > 0) onFilesRef.current(files);+ };+ const onDragEnd = (e: DragEvent) => {+ apply("end", e, false);+ };+ window.addEventListener("dragover", onDragOver);+ window.addEventListener("dragleave", onDragLeave);+ window.addEventListener("drop", onDrop);+ window.addEventListener("dragend", onDragEnd);+ return () => {+ window.removeEventListener("dragover", onDragOver);+ window.removeEventListener("dragleave", onDragLeave);+ window.removeEventListener("drop", onDrop);+ window.removeEventListener("dragend", onDragEnd);+ activeRef.current = false;+ setActive(false);+ };+ }, [region]);++ if (!active || !region) return null;+ return createPortal(+ <div+ aria-hidden+ className="anim-fade pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-white/70 p-6 backdrop-blur-sm dark:bg-gray-950/70"+ >+ <div className="flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-gray-400 bg-white/80 px-10 py-8 text-center dark:border-gray-500 dark:bg-gray-900/80">+ <GlyphIcon d={PAPERCLIP_ICON} size={28} className="text-gray-400 dark:text-gray-500" />+ <p className="text-base font-medium text-gray-800 dark:text-gray-100">+ {S.chat.dropFilesTitle}+ </p>+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.chat.dropFilesDesc}</p>+ </div>+ </div>,+ region,+ );+}diff --git a/packages/web/src/lib/file-drop.ts b/packages/web/src/lib/file-drop.tsnew file mode 100644index 00000000..5985f2bf--- /dev/null+++ b/packages/web/src/lib/file-drop.ts@@ -0,0 +1,160 @@+/**+ * Drag-and-drop file upload logic (#311), kept DOM-free so it can be unit-tested.+ *+ * Dropping files onto the chat area is a third entry point into the composer's existing+ * attachment intake (after the "+" menu pickers and image paste); everything here is about+ * deciding, not doing:+ * - which drags count as file drags at all (`isFileDrag`) — text selections, in-app drags+ * such as the sidebar's session reorder (a custom MIME for exactly this reason) and+ * dragged page images must never light the overlay;+ * - what the chat area's drop zone should do with one drag event (`dropRegionAction`) —+ * show the overlay, claim the drag, take the files, or stand aside;+ * - which staged intake a dropped file belongs to (`splitDroppedFiles`) — images join the+ * pasted-image pipeline, everything else joins the file-attachment pipeline;+ * - the app-shell fallback (`guardWindowDragOver` / `guardWindowDrop`) — anywhere no drop+ * zone claimed the drag, the browser's default is to navigate to the dropped file,+ * silently replacing the app; the guard cancels that default for file drags only, so+ * native text drag-and-drop (e.g. dropping selected text into the composer) keeps+ * working.+ *+ * The two halves are deliberately different in scope. The drop zone is confined to the chat+ * area: overlay, copy cursor and attachment happen only there. The guard is app-wide and+ * entirely silent — no overlay, no attachment, no toast — because the alternative to+ * cancelling the default is the browser navigating the tab to the dropped file and discarding+ * the running app along with any unsent draft. Outside the chat area the gesture is inert,+ * not destructive.+ */++/**+ * True when a drag carries OS files: `DataTransfer.types` contains `"Files"`. Every other+ * drag — text selections (`text/plain`), links, dragged `<img>` elements (`text/uri-list`),+ * the sidebar's session reorder MIME — lacks it and must be left to its native behavior.+ * Accepts null/undefined because `dataTransfer` is nullable on the DOM event type.+ */+export function isFileDrag(types: readonly string[] | null | undefined): boolean {+ return types !== null && types !== undefined && types.includes("Files");+}++/**+ * The drag lifecycle moments the chat area's drop zone listens for, on `window` so it sees+ * the drag wherever it goes:+ * - `over` — `dragover`, the authoritative signal. It fires continuously while a drag is+ * anywhere over the page (per spec at least every 350ms) and names the element+ * currently under the pointer, so it answers "is the drag over the chat area+ * right now" outright, with no state to accumulate.+ * - `leave` — `dragleave`, needed for one case `over` cannot cover: once the drag leaves+ * the window entirely, `dragover` simply stops firing, and without this the+ * last "inside" answer would stand forever.+ * - `drop` — the release.+ * - `end` — `dragend`, which only fires for drags that STARTED in this page (an OS file+ * drag ends with drop or dragleave instead); cheap insurance for in-page sources.+ */+export type DragSignal = "over" | "leave" | "drop" | "end";++/** What the chat area's drop zone should do about one drag event. */+export interface DropRegionAction {+ /** Whether the region overlay should be showing once this event has been handled. */+ readonly active: boolean;+ /** Claim the drag: `preventDefault` plus the copy cursor. Cancelling `dragover` is also what makes a later `drop` fire at all. */+ readonly claim: boolean;+ /** Hand this event's files to the composer's attachment intake. */+ readonly accept: boolean;+}++/**+ * The drop zone's whole decision, as a pure function of the current event — never of an+ * accumulated count.+ *+ * `inside` is "the drag is over the chat area once this event has been applied": the event+ * target for `over` and `drop`, the *related* target for `leave` (where the drag is heading —+ * `null`, i.e. outside, when it left the window). That asymmetry is the point: a `dragleave`+ * whose related target is still inside the region is nothing but an internal element+ * boundary being crossed, and must not disturb the overlay.+ *+ * Being stateless is what makes the overlay impossible to strand. The obvious alternative —+ * a dragenter/dragleave depth counter — is an accumulator whose only unconditional resets+ * are `drop` and `dragend`, and neither fires for a file drag that ends outside the browser;+ * one missed `dragleave` would leave the counter permanently off by one, with the overlay+ * stuck on screen. Here, every `dragover` re-derives the answer from scratch, so any missed+ * event is corrected by the next one within a frame.+ */+export function dropRegionAction(+ signal: DragSignal,+ fileDrag: boolean,+ inside: boolean,+): DropRegionAction {+ const over = fileDrag && inside;+ switch (signal) {+ // The drag is over the region: show the overlay and claim the drag, so the browser+ // delivers the drop here instead of applying its navigate-to-file default.+ case "over":+ return { active: over, claim: over, accept: false };+ // Only a departure matters. Still inside (crossed into a child) → nothing changes;+ // gone from the region or from the window → hide. Claiming a dragleave would be+ // meaningless, so it never does.+ case "leave":+ return { active: over, claim: false, accept: false };+ // The release. Files are taken only when they were released inside the region — a drop+ // on the sidebar or a docked panel reaches the app-shell guard instead and does nothing.+ case "drop":+ return { active: false, claim: over, accept: over };+ // The drag is over, wherever it ended.+ case "end":+ return { active: false, claim: false, accept: false };+ }+}++/**+ * Splits one dropped batch into the composer's two intakes, preserving drop order within+ * each: images ride the message as `image_url` parts exactly like pasted images, everything+ * else becomes a file attachment (scratchpad + `[attached file: <path>]` line). Generic over+ * "has a MIME type" so tests don't need a DOM `File`.+ */+export function splitDroppedFiles<T extends { readonly type: string }>(+ dropped: readonly T[],+): { images: T[]; files: T[] } {+ const images: T[] = [];+ const files: T[] = [];+ for (const item of dropped) {+ (item.type.startsWith("image/") ? images : files).push(item);+ }+ return { images, files };+}++/**+ * The slice of a DragEvent the guards read/write — structural, so DOM `DragEvent` satisfies+ * it and tests can pass plain objects (the vitest environment has no DOM).+ */+export interface DragGuardEvent {+ readonly defaultPrevented: boolean;+ preventDefault(): void;+ readonly dataTransfer: {+ readonly types: readonly string[];+ dropEffect: string;+ } | null;+}++/**+ * Window-level dragover fallback for the whole app shell. Runs after the chat area's drop+ * zone on the bubble path, so `defaultPrevented` is exactly "the chat area claimed this+ * drag": when it did not — the pointer is over the sidebar, the top bar, a docked panel, or+ * a page with no composer at all — cancel the default and show the no-drop cursor, an honest+ * "dropping here does nothing" instead of the browser's copy cursor over a page that would+ * navigate away. Non-file drags pass through untouched (see isFileDrag).+ */+export function guardWindowDragOver(e: DragGuardEvent): void {+ if (e.defaultPrevented || !isFileDrag(e.dataTransfer?.types)) return;+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = "none";+}++/**+ * Window-level drop fallback, paired with guardWindowDragOver: cancels the browser's default+ * open-file navigation for any file drop the chat area did not claim. It attaches nothing and+ * says nothing — outside the chat area a file drop is simply inert. Text/link drops keep+ * their native behavior (dropping text into the composer textarea must still insert it).+ */+export function guardWindowDrop(e: DragGuardEvent): void {+ if (e.defaultPrevented || !isFileDrag(e.dataTransfer?.types)) return;+ e.preventDefault();+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 67114d21..adb13f00 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1273,6 +1273,11 @@ Scenarios:removeFile: "Remove file",attachmentTooLarge: (name: string): string =>`${name} exceeds the 10MB limit and was not attached.`,+ /** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */+ dropFilesTitle: "Drop files to attach",+ dropFilesDesc: "Images and files are added to the message draft",+ /** Toast when non-image files are dropped in goal mode (the objective carries images only). */+ dropFilesGoalHint: "Goal mode takes images only; the files were not attached.",goalMode: "Goal mode",goalModeDesc: "Loop until the goal completes",goalBudgetLabel: "Token budget",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 9b521b51..0f9444dd 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1223,6 +1223,11 @@ Benchmark:removeFile: "移除文件",/** Toast for a picked file rejected before reading (the server's per-file cap is 10MB). */attachmentTooLarge: (name: string): string => `${name} 超过 10MB 上限,未添加。`,+ /** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */+ dropFilesTitle: "松开以添加附件",+ dropFilesDesc: "图片与文件将添加到输入框",+ /** Toast when non-image files are dropped in goal mode (the objective carries images only). */+ dropFilesGoalHint: "目标模式仅支持附加图片,文件未添加。",goalMode: "目标模式",goalModeDesc: "循环运行直至目标完成",goalBudgetLabel: "Token 预算",diff --git a/packages/web/test/file-drop.test.ts b/packages/web/test/file-drop.test.tsnew file mode 100644index 00000000..07fd5362--- /dev/null+++ b/packages/web/test/file-drop.test.ts@@ -0,0 +1,210 @@+/**+ * Drag-and-drop upload logic (lib/file-drop.ts): what counts as a file drag, what the chat+ * area's drop zone does with one drag event, how a dropped batch splits across the composer's+ * two intakes, and the app-shell guard that cancels the browser's navigate-to-file default.+ *+ * The region decision is the part that earns the tests, because it is where the feature's+ * scope lives: the overlay and the attachment happen only while the drag is over the chat+ * area, and a file released on the sidebar, the top bar or a docked panel must produce no+ * attachments at all — while still being cancelled by the app-wide guard, so the browser does+ * not navigate to the file. Being stateless is the other half: the overlay is re-derived from+ * every event rather than accumulated, so no missed event can strand it on screen.+ */+import { describe, expect, it } from "vitest";+import {+ dropRegionAction,+ guardWindowDragOver,+ guardWindowDrop,+ isFileDrag,+ splitDroppedFiles,+} from "../src/lib/file-drop";+import type { DragGuardEvent, DragSignal } from "../src/lib/file-drop";++describe("isFileDrag", () => {+ it("recognizes an OS file drag by the Files type, alone or among others", () => {+ expect(isFileDrag(["Files"])).toBe(true);+ // Chrome lists extra types alongside Files for some sources.+ expect(isFileDrag(["text/uri-list", "Files"])).toBe(true);+ });++ it("ignores every non-file drag: text selections, links, in-app drags", () => {+ expect(isFileDrag(["text/plain"])).toBe(false);+ expect(isFileDrag(["text/uri-list", "text/html"])).toBe(false);+ // The sidebar's session reorder uses a private MIME precisely so nothing else reacts.+ expect(isFileDrag(["application/x-penguin-session-id"])).toBe(false);+ expect(isFileDrag([])).toBe(false);+ });++ it("treats a missing dataTransfer (null/undefined types) as not a file drag", () => {+ expect(isFileDrag(null)).toBe(false);+ expect(isFileDrag(undefined)).toBe(false);+ });+});++describe("dropRegionAction", () => {+ const INSIDE = true;+ const OUTSIDE = false;+ const FILES = true;++ it("shows the overlay and claims the drag while a file drag is over the chat area", () => {+ // Claiming (preventDefault) is also what makes the browser deliver a drop here at all.+ expect(dropRegionAction("over", FILES, INSIDE)).toEqual({+ active: true,+ claim: true,+ accept: false,+ });+ });++ it("attaches a file released inside the chat area, and hides the overlay with it", () => {+ expect(dropRegionAction("drop", FILES, INSIDE)).toEqual({+ active: false,+ claim: true,+ accept: true,+ });+ });++ it("takes nothing from a drop outside the chat area — the sidebar, the top bar, a docked panel", () => {+ // The whole point of the region: the app-shell guard still cancels the browser's+ // navigate-to-file for this drop (see the guard tests below), but the composer gets+ // nothing and no overlay was ever shown.+ expect(dropRegionAction("drop", FILES, OUTSIDE)).toEqual({+ active: false,+ claim: false,+ accept: false,+ });+ expect(dropRegionAction("over", FILES, OUTSIDE)).toEqual({+ active: false,+ claim: false,+ accept: false,+ });+ });++ it("ignores non-file drags wherever they are, so native behavior survives", () => {+ // Dragging selected text into the composer, or a sidebar session reorder crossing the+ // chat area: no overlay, and above all no claim — claiming would swallow the text drop.+ const signals: DragSignal[] = ["over", "leave", "drop", "end"];+ for (const signal of signals) {+ expect(dropRegionAction(signal, false, INSIDE)).toEqual({+ active: false,+ claim: false,+ accept: false,+ });+ }+ });++ it("keeps the overlay up when a dragleave only crossed into a child element", () => {+ // dragleave fires for every element boundary; `inside` is the RELATED target, so a leave+ // heading somewhere still inside the region changes nothing.+ expect(dropRegionAction("leave", FILES, INSIDE).active).toBe(true);+ });++ it("hides the overlay when the drag leaves the region or the window", () => {+ // Leaving for the sidebar, and leaving the window entirely (relatedTarget null → outside)+ // are the same answer.+ expect(dropRegionAction("leave", FILES, OUTSIDE).active).toBe(false);+ // A dragleave is never claimed — there is nothing to allow or cancel about a departure.+ expect(dropRegionAction("leave", FILES, INSIDE).claim).toBe(false);+ });++ it("ends the overlay on dragend whatever the drag was", () => {+ expect(dropRegionAction("end", FILES, INSIDE)).toEqual({+ active: false,+ claim: false,+ accept: false,+ });+ });++ it("is a pure function of the current event, so no missed event can strand the overlay", () => {+ // The regression this replaces: a dragenter/dragleave depth counter drifts permanently+ // out of balance if one dragleave is missed (a drag that ends outside the browser fires+ // neither drop nor dragend), leaving the overlay stuck. Here the answer never depends on+ // history — a lone "over" inside is enough to show it, a lone one outside to hide it,+ // in any order and any number of times.+ const replay: DragSignal[] = ["leave", "leave", "over", "drop", "leave", "end", "over"];+ for (const signal of replay) {+ expect(dropRegionAction(signal, FILES, INSIDE).active).toBe(+ signal !== "drop" && signal !== "end",+ );+ }+ expect(dropRegionAction("over", FILES, INSIDE).active).toBe(true);+ expect(dropRegionAction("over", FILES, OUTSIDE).active).toBe(false);+ });+});++describe("splitDroppedFiles", () => {+ it("routes by MIME type: image/* to the image intake, everything else to attachments", () => {+ const png = { type: "image/png", name: "a.png" };+ const pdf = { type: "application/pdf", name: "b.pdf" };+ const svg = { type: "image/svg+xml", name: "c.svg" };+ const none = { type: "", name: "Makefile" }; // OS gives some files no MIME type at all+ const { images, files } = splitDroppedFiles([png, pdf, svg, none]);+ expect(images).toEqual([png, svg]);+ expect(files).toEqual([pdf, none]);+ });++ it("keeps drop order within each intake and handles an empty batch", () => {+ const a = { type: "text/plain" };+ const b = { type: "application/zip" };+ expect(splitDroppedFiles([a, b]).files).toEqual([a, b]);+ expect(splitDroppedFiles([])).toEqual({ images: [], files: [] });+ });+});++/** A window-level guard event: `types` = the drag's payload, null = no dataTransfer at all. */+function guardEvent(+ types: readonly string[] | null,+ defaultPrevented = false,+): DragGuardEvent & { prevented: boolean } {+ return {+ defaultPrevented,+ prevented: false,+ preventDefault() {+ this.prevented = true;+ },+ dataTransfer: types === null ? null : { types, dropEffect: "copy" },+ };+}++describe("app-shell drop guard", () => {+ it("cancels a file drag outside the chat area: no-drop cursor, no navigation, nothing attached", () => {+ // The deliberate remainder of scoping the zone down: dropping a file on the sidebar must+ // do NOTHING — not open the file in the tab, which is the browser's default and would+ // discard the running app. Silent by design: this path has no overlay and no toast.+ const over = guardEvent(["Files"]);+ guardWindowDragOver(over);+ expect(over.prevented).toBe(true);+ expect(over.dataTransfer?.dropEffect).toBe("none");+ const drop = guardEvent(["Files"]);+ guardWindowDrop(drop);+ expect(drop.prevented).toBe(true);+ // And the region agrees the composer gets nothing from it.+ expect(dropRegionAction("drop", true, false).accept).toBe(false);+ });++ it("stands aside when the chat area already claimed the drag (defaultPrevented)", () => {+ // The two are window listeners in registration order, so the guard must not overwrite the+ // zone's copy cursor with its no-drop one when it happens to run second.+ const over = guardEvent(["Files"], true);+ guardWindowDragOver(over);+ expect(over.prevented).toBe(false);+ expect(over.dataTransfer?.dropEffect).toBe("copy");+ const drop = guardEvent(["Files"], true);+ guardWindowDrop(drop);+ expect(drop.prevented).toBe(false);+ });++ it("leaves non-file drags to their native behavior (text drops into the composer)", () => {+ const over = guardEvent(["text/plain"]);+ guardWindowDragOver(over);+ expect(over.prevented).toBe(false);+ expect(over.dataTransfer?.dropEffect).toBe("copy");+ const drop = guardEvent(["text/plain"]);+ guardWindowDrop(drop);+ expect(drop.prevented).toBe(false);+ // No dataTransfer at all: nothing to judge, nothing to cancel.+ const bare = guardEvent(null);+ guardWindowDragOver(bare);+ guardWindowDrop(bare);+ expect(bare.prevented).toBe(false);+ });+});