Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(chat): both chats take files again — dropped, pasted or picked, with what is in them

rubenluetke10-beep3078b821b11c
diff --git a/jarvis/agent_chat/attachments.py b/jarvis/agent_chat/attachments.py
new file mode 100644
index 0000000000..bc84f8a635
--- /dev/null
+++ b/jarvis/agent_chat/attachments.py
@@ -0,0 +1,221 @@
+"""Files dropped, pasted or picked into a chat composer.
+
+The typed chats — the front page and the Agentic IDE's chat mode — take a
+sentence and nothing else. Someone with a screenshot of a broken layout has to
+describe it in words, which is the one thing a screenshot exists to avoid. The
+IDE's TERMINAL panes have taken dropped files since 2026-08 (``drops`` +
+``drop_analysis``); the chats were never wired to any of it, so a drop landed
+on a bare ``<textarea>`` and the browser navigated away to the file.
+
+This module is that wiring, and it is deliberately thin: everything hard was
+already solved one layer down and is reused rather than rewritten.
+
+* :mod:`jarvis.agentic_ide.drops` writes the bytes into the chat's own working
+ directory (``.jarvis/drops``, self-ignoring) and hands back a reference the
+ agent can open.
+* :mod:`jarvis.agentic_ide.drop_analysis` has a vision-capable model describe
+ an image and extracts a document's text.
+* :func:`jarvis.agentic_ide.prompt_blueprint.attachment_block` lays the result
+ out for whatever answers the turn.
+
+Why the description travels with the message rather than the file alone: a
+chat can be answered by a coding CLI, by a provider's own API loop, or by
+Jarvis' brain, and several of those cannot open an image at all. Sending only
+a path means the person drops a picture, types "what is wrong here", and the
+model receives a filename and a pronoun. The description is what makes the
+gesture work on every seat instead of the maintainer's.
+
+Import-light on purpose (AP-26): the heavy halves are imported inside the
+functions, so a boot that never sees an attachment pays nothing for this.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "MAX_TOTAL_BYTES",
+ "AttachmentError",
+ "compose",
+ "ingest",
+ "to_analysis",
+]
+
+#: Total cap for one attach gesture, shared with the terminal drop path so the
+#: two surfaces cannot disagree about what is too large.
+MAX_TOTAL_BYTES = 100 * 1024 * 1024
+
+
+class AttachmentError(RuntimeError):
+ """The attach carried nothing usable, or the copies could not be written."""
+
+
+async def ingest(
+ cwd: str | Path,
+ *,
+ paths: list[str] | None = None,
+ uploads: list[tuple[str, bytes]] | None = None,
+ provider: str = "",
+) -> list[Any]:
+ """Store what was dropped in ``cwd`` and read what is in it.
+
+ ``paths`` are real locations the browser managed to hand over (an Explorer
+ or Finder drag usually carries them, and inside the desktop shell the host
+ resolves them for every drop). ``uploads`` are ``(name, bytes)`` for
+ everything with no path at all — a pasted screenshot, an image dragged off
+ a web page.
+
+ A path already inside ``cwd`` is referenced where it lies; anything else is
+ copied in, because an agent's reach outside its working directory is
+ neither guaranteed nor silent.
+
+ Returns ``drop_analysis.DropAnalysis`` entries — one per file, in the order
+ they arrived. Raises :class:`AttachmentError` when nothing usable was
+ carried; an analysis that fails costs the description and nothing else, so
+ the file still travels.
+ """
+ from jarvis.agentic_ide import drops
+
+ folder = Path(cwd).expanduser() # noqa: ASYNC240 — string work; the stat below is threaded
+ if not await asyncio.to_thread(folder.is_dir):
+ raise AttachmentError(f"Not a folder: {folder}")
+
+ references: list[str] = []
+ # (name, bytes, reference) for everything attached — the reference travels
+ # with the bytes so a description can never drift onto another file.
+ readable: list[tuple[str, bytes, str]] = []
+ to_copy: list[tuple[str, bytes]] = []
+
+ for raw in paths or []:
+ candidate = (raw or "").strip()
+ if not candidate:
+ continue
+ inside = drops.within_workspace(candidate, folder)
+ if inside is not None:
+ reference = drops.reference(inside, agent=provider)
+ references.append(reference)
+ try:
+ body = await asyncio.to_thread((folder / inside).read_bytes)
+ except OSError as exc:
+ # The reference still ships; the file simply goes undescribed.
+ log.info("chat attach: %r not readable for analysis (%s)", inside, exc)
+ else:
+ readable.append((Path(inside).name, body, reference))
+ continue
+ # expanduser() is string work; the read itself goes to a worker thread
+ # (a dropped file may live on a slow network share).
+ resolved = Path(candidate).expanduser() # noqa: ASYNC240
+ try:
+ data = await asyncio.to_thread(resolved.read_bytes)
+ except OSError as exc:
+ log.info("chat attach: unreadable dropped path %r (%s)", candidate, exc)
+ continue
+ to_copy.append((resolved.name, data))
+
+ total = sum(len(data) for _name, data in to_copy)
+ for name, data in uploads or []:
+ total += len(data)
+ if total > MAX_TOTAL_BYTES:
+ megabytes = MAX_TOTAL_BYTES // (1024 * 1024)
+ raise AttachmentError(f"That attachment is too large (max {megabytes} MB in total).")
+ if data:
+ to_copy.append((name or "file", data))
+
+ # ``store`` skips empty entries silently, so they are dropped HERE instead —
+ # that keeps ``stored[i]`` paired with ``to_copy[i]`` positionally.
+ to_copy = [(name, data) for name, data in to_copy if data]
+
+ if to_copy:
+ try:
+ stored = await asyncio.to_thread(drops.store, folder, to_copy)
+ except drops.DropError as exc:
+ raise AttachmentError(str(exc)) from exc
+ for item, (_original, data) in zip(stored, to_copy, strict=True):
+ reference = drops.reference(item.relative_path, agent=provider)
+ references.append(reference)
+ readable.append((item.name, data, reference))
+
+ if not references:
+ raise AttachmentError("That attachment carried nothing this chat could use.")
+
+ return await _analyze(readable)
+
+
+async def _analyze(readable: list[tuple[str, bytes, str]]) -> list[Any]:
+ """Describe images and extract documents. Never raises — this is a bonus.
+
+ The files are already stored and referenced by the time this runs, so a
+ provider outage here must cost the description and nothing more.
+ """
+ import mimetypes
+
+ from jarvis.agentic_ide import drop_analysis
+ from jarvis.brain.drop_context import DroppedItem
+
+ if not readable:
+ return []
+ items = [
+ (
+ DroppedItem(
+ name=name,
+ mime=mimetypes.guess_type(name)[0] or "application/octet-stream",
+ data=data,
+ ),
+ reference,
+ )
+ for name, data, reference in readable
+ ]
+ try:
+ return await drop_analysis.analyze(items)
+ except Exception as exc: # noqa: BLE001 — the attach itself already succeeded
+ log.info("chat attach: analysis failed (%s)", exc)
+ return []
+
+
+def to_analysis(raw: list[dict[str, Any]] | None) -> list[Any]:
+ """Rebuild the analyses a composer hands back on the wire.
+
+ The client holds what :func:`ingest` returned while the person finishes
+ typing, then posts it with the message. It is request data, so nothing here
+ may assume a shape: a malformed entry becomes an empty-detail attachment
+ rather than a 500 on a message somebody is waiting to send.
+ """
+ from jarvis.agentic_ide import drop_analysis
+
+ out: list[Any] = []
+ for entry in raw or []:
+ if not isinstance(entry, dict):
+ continue
+ item = drop_analysis.DropAnalysis.from_dict(entry)
+ if item.name:
+ out.append(item)
+ return out
+
+
+def compose(text: str, attachments: list[Any] | None) -> str:
+ """The message as the turn will actually receive it.
+
+ The person's sentence first, then what was attached — the sentence is the
+ task, the files are context for it, and a model reads the instruction
+ better when it is not buried under a page of extracted PDF.
+
+ Returns ``text`` unchanged when nothing is attached, so an ordinary message
+ is never reshaped by a feature it did not use.
+ """
+ from jarvis.agentic_ide.prompt_blueprint import attachment_block
+
+ said = (text or "").strip()
+ block = attachment_block(list(attachments or []))
+ if not block:
+ return said
+ lead = (
+ "Files the user attached to this message are below. Their contents are "
+ "given in full because the file itself may not be openable from here — "
+ "read them as part of the message."
+ )
+ return "\n\n".join(part for part in (said, lead, block) if part)
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 273a039657..dee39299d9 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -27,6 +27,7 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any
+from jarvis.agent_chat import attachments as chat_attachments
from jarvis.agent_chat.approval_bridge import ChatApprovalBridge
from jarvis.agent_chat.catalog import provider_row
from jarvis.agent_chat.effort import normalize_effort
@@ -72,11 +73,6 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:
kit = kit_for(surface)
api_runner = "brain" if kit.brain_runner else "api"
row = provider_row(provider)
- if kit.brain_only:
- # The surface's tools only exist inside the brain loop: a CLI seat
- # (agy-cli, codex-cli, claude-cli) would run the vendor's coding agent
- # without them, so any provider the brain knows is driven by the brain.
- return "brain" if row is not None or supports_api_runner(provider) else "unknown"
if row is None:
return api_runner if supports_api_runner(provider) else "unknown"
if row.id == "claude-api":
@@ -131,8 +127,29 @@ class AgentChatService:
# ------------------------------------------------------------ sessions
- def default_cwd(self) -> str:
- return self._default_cwd()
+ def default_cwd(self, surface: str = DEFAULT_SURFACE) -> str:
+ """Where a new ``surface`` session starts when nobody picked a folder.
+
+ A surface that brings its own workspace (the Jarvis chat) gets that
+ directory, created on first use. One that cannot be created — a
+ read-only install, no writable app data — falls back to the service
+ default rather than handing a chat a folder it cannot work in.
+ """
+ workspace = kit_for(surface).workspace_dir
+ if workspace is None:
+ return self._default_cwd()
+ folder = workspace()
+ try:
+ folder.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ log.warning(
+ "chat workspace %s could not be created (%s) — starting in the "
+ "fallback folder instead",
+ folder,
+ exc,
+ )
+ return self._default_cwd()
+ return str(folder)
def _bridge_for(self, bus: Any | None) -> ChatApprovalBridge | None:
"""The approval bridge, built on the first Jarvis turn that has a bus."""
@@ -167,7 +184,7 @@ class AgentChatService:
provider=provider,
model=model or (row.default_model if row else ""),
effort=eff,
- cwd=cwd or self.default_cwd(),
+ cwd=cwd or self.default_cwd(surface),
permission_mode=permission_mode,
title=title,
surface=surface,
@@ -208,16 +225,36 @@ class AgentChatService:
# ---------------------------------------------------------------- turns
- async def send(self, session_id: str, text: str) -> str:
- """Persist the person's message and start the turn. Returns turn_id."""
+ async def send(
+ self,
+ session_id: str,
+ text: str,
+ attachments: list[dict[str, Any]] | None = None,
+ ) -> str:
+ """Persist the person's message and start the turn. Returns turn_id.
+
+ ``attachments`` are what the composer already had read for this message
+ (``jarvis.agent_chat.attachments``): a described screenshot, an
+ extracted document. Their contents go INTO the message the turn
+ receives, because a chat may be answered by a coding CLI or a
+ text-only model that cannot open the file itself.
+
+ A message with attachments may carry no sentence at all — dropping a
+ picture and pressing Enter is a complete gesture — but an empty message
+ with nothing attached is still refused.
+ """
session = self.store.get_session(session_id)
if session is None:
raise NoSuchSession(session_id)
if self.is_running(session_id):
raise SessionBusy(session_id)
text = text.strip()
- if not text:
+ attached = chat_attachments.to_analysis(attachments)
+ if not text and not attached:
raise ValueError("empty message")
+ # What the turn receives; ``text`` stays what the person typed so the
+ # timeline shows their sentence rather than a page of extracted PDF.
+ prompt = chat_attachments.compose(text, attached)
turn_id = uuid.uuid4().hex
cancel = asyncio.Event()
@@ -225,7 +262,37 @@ class AgentChatService:
self._running[session_id] = run
history = self.store.list_events(session_id)
- await self._emit(session_id, make_event("user_message", {"text": text}))
+ await self._emit(
+ session_id,
+ make_event(
+ "user_message",
+ {
+ # The full prompt: this is what was actually sent, and the
+ # API runner rebuilds the conversation from these events —
+ # storing only the sentence would lose the picture on the
+ # NEXT turn (runner_api.messages_from_events).
+ "text": prompt,
+ # What the person typed, when it differs from the prompt.
+ # Absent on an ordinary message, so nothing changes there.
+ **({"typed": text} if attached else {}),
+ **(
+ {
+ "attachments": [
+ {
+ "name": item.name,
+ "kind": item.kind,
+ "described_by": item.described_by,
+ "note": item.note,
+ }
+ for item in attached
+ ]
+ }
+ if attached
+ else {}
+ ),
+ },
+ ),
+ )
runner = resolve_runner(session.provider, surface=session.surface)
await self._emit(
session_id,
@@ -235,13 +302,12 @@ class AgentChatService:
"turn_id": turn_id,
"provider": session.provider,
"model": session.model,
- # The effort the turn RUNS with: a surface may ask for more
- # than the session's own pick (the setup helper does), and
- # the timeline must not report the stale one.
- "effort": normalize_effort(
- session.provider,
- kit_for(session.surface).effort or session.effort,
- ),
+ # The effort the turn RUNS with. It is the session's own
+ # pick: no surface overrides it any more (the kit's
+ # `effort` went with the setup helper), so reading one off
+ # the kit would only be a way to raise an AttributeError
+ # on every turn.
+ "effort": normalize_effort(session.provider, session.effort),
"runner": runner,
"surface": session.surface,
},
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 9254709938..accbb0de68 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -9,10 +9,11 @@ Prefix ``/api/agent-chat``:
GET /sessions/{id} session + its persisted events
PATCH /sessions/{id} title/provider/model/effort/cwd/permission_mode
DELETE /sessions/{id}
- POST /sessions/{id}/messages {text} -> starts a turn, returns turn_id
+ POST /sessions/{id}/messages {text, attachments} -> starts a turn
POST /sessions/{id}/cancel
POST /sessions/{id}/approvals/{aid} {decision: allow | allow_always | deny}
WS /sessions/{id}/ws?after=<seq> snapshot, then live events
+ POST /attachments drop/paste/pick files for the next message
POST /pick-folder the system folder dialog (desktop only)
GET /check-folder?path= does the folder exist / is it a directory
@@ -29,9 +30,20 @@ import os
from pathlib import Path
from typing import Any, Literal
-from fastapi import APIRouter, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
+from fastapi import (
+ APIRouter,
+ File,
+ Form,
+ HTTPException,
+ Query,
+ Request,
+ UploadFile,
+ WebSocket,
+ WebSocketDisconnect,
+)
from pydantic import BaseModel, Field
+from jarvis.agent_chat import attachments as chat_attachments
from jarvis.agent_chat.catalog import CLAUDE_CODE_MODELS, PROVIDER_ROWS
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
@@ -55,7 +67,12 @@ log = logging.getLogger(__name__)
#: The Pydantic twin of ``jarvis.agent_chat.store.SURFACES`` (AP-4; the parity
#: test in tests/unit/agent_chat/test_agent_chat_surface_parity.py pins it).
-SurfaceName = Literal["jarvis", "agent", "local-models"]
+SurfaceName = Literal["jarvis", "agent"]
+
+#: The same names, as data — a multipart form field cannot be typed by a
+#: ``Literal`` without turning an unknown surface into a 422 on a file the
+#: person just dropped.
+SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent"})
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
@@ -88,7 +105,13 @@ class PatchSessionBody(BaseModel):
class MessageBody(BaseModel):
- text: str = Field(min_length=1, max_length=200_000)
+ #: May be empty when files are attached — dropping a screenshot and
+ #: pressing Enter is a complete gesture. The service refuses a message
+ #: that carries neither.
+ text: str = Field(default="", max_length=200_000)
+ #: What ``POST /attachments`` returned for the files going in with this
+ #: message; the wire shape of ``drop_analysis.DropAnalysis``.
+ attachments: list[dict[str, Any]] = Field(default_factory=list)
class ApprovalBody(BaseModel):
@@ -225,7 +248,7 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[
rows.append(d)
return {
"providers": rows,
- "default_cwd": svc.default_cwd(),
+ "default_cwd": svc.default_cwd(surface),
"shell": shell_label(),
}
@@ -309,10 +332,10 @@ async def patch_session(
if body.effort is not None:
provider = fields.get("provider") or svc.store.get_session(session_id).provider # type: ignore[union-attr]
fields["effort"] = normalize_effort(provider, body.effort)
- if body.cwd is not None:
- fields["cwd"] = _validate_cwd(body.cwd) or svc.default_cwd()
current = svc.store.get_session(session_id)
assert current is not None
+ if body.cwd is not None:
+ fields["cwd"] = _validate_cwd(body.cwd) or svc.default_cwd(current.surface)
runner = resolve_runner(fields.get("provider") or current.provider, surface=current.surface)
ladder = ladder_key(current.surface, runner)
if body.permission_mode is not None:
@@ -355,7 +378,7 @@ async def delete_session(session_id: str, request: Request) -> dict[str, Any]:
async def post_message(session_id: str, body: MessageBody, request: Request) -> dict[str, Any]:
svc = _service(request)
try:
- turn_id = await svc.send(session_id, body.text)
+ turn_id = await svc.send(session_id, body.text, body.attachments)
except NoSuchSession as exc:
raise HTTPException(status_code=404, detail="session not found") from exc
except SessionBusy as exc:
@@ -387,6 +410,77 @@ async def resolve_approval(
return {"ok": True, "approval_id": approval_id, "decision": body.decision}
+# ------------------------------------------------------------------ attachments
+
+
[email protected]("/attachments", summary="Drop, paste or pick files into a chat composer")
+async def attach_files(
+ request: Request,
+ files: list[UploadFile] | None = File(default=None), # noqa: B008
+ paths: str | None = Form(default=None), # noqa: B008
+ session_id: str | None = Form(default=None), # noqa: B008
+ cwd: str | None = Form(default=None), # noqa: B008
+ provider: str = Form(default=""), # noqa: B008
+ surface: str = Form(default="agent"), # noqa: B008
+) -> dict[str, Any]:
+ """Hold files for the message the person is still typing.
+
+ Two inputs, either or both:
+
+ * ``paths`` — newline-separated real locations. An Explorer or Finder drag
+ usually carries them, and inside the desktop shell the host resolves one
+ for every dropped file (``jarvis/ui/native_drop.py``). A path already
+ inside the chat's folder is referenced where it lies; anything else is
+ copied in.
+ * ``files`` — raw bytes, for everything with no path at all: a screenshot
+ pasted from the clipboard, an image dragged off a web page.
+
+ Nothing is sent. Each file is stored, then READ — an image described by a
+ vision-capable model, a document extracted — and the result comes back for
+ the composer to hold and post with the message. That reading is the whole
+ point: a chat can be answered by a coding CLI or a text-only model, so
+ without it the person drops a picture, types "what is wrong here", and the
+ model receives a filename.
+
+ Which folder the copies land in, in order: the open session's, the
+ composer's own ``cwd``, then the surface's default working directory. So an
+ attach works before the first message, when no session exists yet.
+ """
+ svc = _service(request)
+ folder = ""
+ if session_id:
+ session = svc.store.get_session(session_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="session not found")
+ folder = session.cwd or ""
+ if not folder:
+ try:
+ folder = _validate_cwd(cwd) or ""
+ except HTTPException:
+ # A composer whose remembered folder has gone (a moved checkout, a
+ # detached drive) must still be able to take a file — the surface's
+ # own directory below always exists.
+ folder = ""
+ if not folder:
+ folder = svc.default_cwd(surface if surface in SURFACE_NAMES else "agent")
+
+ uploads: list[tuple[str, bytes]] = []
+ for upload in files or []:
+ uploads.append((upload.filename or "file", await upload.read()))
+
+ try:
+ found = await chat_attachments.ingest(
+ folder,
+ paths=(paths or "").splitlines(),
+ uploads=uploads,
+ provider=provider,
+ )
+ except chat_attachments.AttachmentError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ return {"attachments": [item.to_dict() for item in found], "cwd": folder}
+
+
# ------------------------------------------------------------------ folders
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index 9a74c9c212..d32e2fe8c9 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -7,6 +7,7 @@ import { useVoiceStatus } from "@/hooks/useVoiceStatus";
import { useVoiceStateResync } from "@/hooks/useVoiceStateResync";
import { useAssistantNameSeed } from "@/hooks/useAssistantNameSeed";
import { useCodingMode } from "@/hooks/useCodingMode";
+import { useFileDropGuard } from "@/hooks/useFileDropGuard";
import { useSectionUrlMemory } from "@/hooks/useSectionUrlMemory";
import {
Sidebar,
@@ -156,6 +157,7 @@ export default function App() {
useVoiceStateResync();
useAssistantNameSeed();
useCodingMode();
+ useFileDropGuard();
/*
* A reload puts the user back on the section they were on.
*
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
index 4e2437eb3b..eb64dae80c 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState, type KeyboardEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import {
ArrowUp,
Bot,
@@ -9,6 +9,7 @@ import {
Hammer,
Mic,
NotebookPen,
+ Paperclip,
ShieldCheck,
Square,
} from "lucide-react";
@@ -23,6 +24,9 @@ import { pickAgentChatFolder } from "@/lib/agentChatApi";
import { runningTurn } from "@/components/agentchat/reduce";
import { permissionModeIcon } from "@/components/agentchat/permissionIcons";
import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
+import { useChatAttachments } from "@/components/agentchat/useChatAttachments";
+import { usePasteRescue } from "@/components/agentchat/usePasteRescue";
+import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -82,6 +86,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
const connections = useAgentChat((s) => s.connections);
const liveModels = useAgentChat((s) => s.liveModels);
const draft = useAgentChat((s) => s.draft);
+ const activeSessionId = useAgentChat((s) => s.activeSessionId);
const timeline = useAgentChat((s) => s.timeline);
const busy = useAgentChat((s) => s.busy);
const lastError = useAgentChat((s) => s.lastError);
@@ -108,17 +113,49 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
setValue,
);
+ // Files going in with this message. Held here rather than in the store: they
+ // belong to the sentence being typed, and a chat opened elsewhere must not
+ // inherit them.
+ const [attachError, setAttachError] = useState("");
+ const onAttachProblem = useCallback(
+ (message: string, severity: "warning" | "error") => {
+ setAttachError(severity === "warning" ? t("agent_chat.attach_nothing") : message);
+ },
+ [t],
+ );
+ const files = useChatAttachments(
+ {
+ sessionId: activeSessionId,
+ cwd: draft.cwd,
+ provider: draft.provider,
+ surface,
+ },
+ onAttachProblem,
+ );
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const pasteRescue = usePasteRescue();
+
const running = runningTurn(timeline) !== null;
async function onSend() {
const content = value.trim();
- if (!content || running || busy) return;
+ // A message may be files alone: dropping a screenshot and pressing Enter
+ // is a complete gesture, and refusing it would be the composer insisting
+ // on a sentence the picture already is.
+ if ((!content && files.attachments.length === 0) || running || busy) return;
+ if (files.analyzing > 0) return; // a file still being read would be sent without its contents
if (dictating) stopDictation();
setValueState("");
- await send(content);
+ setAttachError("");
+ const attached = files.attachments;
+ files.clear();
+ await send(content, attached);
}
function onKeyDown(ev: KeyboardEvent<HTMLTextAreaElement>) {
+ // Watches for a Ctrl+V the embedded browser may never answer; does nothing
+ // in a real browser, where the box pastes on its own.
+ pasteRescue.onKeyDown(ev);
if (ev.key === "Enter" && !ev.shiftKey) {
ev.preventDefault();
void onSend();
@@ -278,7 +315,13 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
const permissionDescription =
(provider?.permission_modes ?? []).find((m) => m.id === draft.permissionMode)?.description ?? "";
- const canSend = connected && Boolean(value.trim()) && !running && !busy && Boolean(provider?.connected);
+ const canSend =
+ connected &&
+ (Boolean(value.trim()) || files.attachments.length > 0) &&
+ files.analyzing === 0 &&
+ !running &&
+ !busy &&
+ Boolean(provider?.connected);
const placeholder = connected
? t("agent_chat.placeholder")
: wsWarming
@@ -288,11 +331,26 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
return (
<div
data-testid="agent-composer"
+ data-dragging={files.dragging ? "true" : undefined}
+ // The whole card is the drop target, not just the text box: someone
+ // dragging a screenshot aims at the composer, and a target smaller than
+ // the thing it looks like is a target people miss.
+ {...files.dragHandlers}
className={cn(
- "flex flex-col gap-2 rounded-2xl border border-border bg-card p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_8px_24px_rgb(var(--scrim-rgb)/0.06)] transition-[border-color,box-shadow]",
+ "relative flex flex-col gap-2 rounded-2xl border border-border bg-card p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_8px_24px_rgb(var(--scrim-rgb)/0.06)] transition-[border-color,box-shadow]",
"focus-within:border-primary/40",
+ files.dragging && "border-primary/60",
)}
>
+ {files.dragging && (
+ <div
+ data-testid="composer-drop-overlay"
+ aria-hidden
+ className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary/70 bg-card/90 text-sm font-medium text-primary"
+ >
+ {t("agent_chat.attach_drop_hint")}
+ </div>
+ )}
{dictating && (
<div
className="flex items-center gap-2 rounded-lg border border-primary/30 bg-primary/10 px-3 py-1.5 text-xs text-primary"
@@ -306,12 +364,21 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
<span className="font-medium">{t("chats_view.dictation_listening")}</span>
</div>
)}
+ <ChatAttachmentStrip
+ attachments={files.attachments}
+ analyzing={files.analyzing}
+ onRemove={files.remove}
+ />
<textarea
data-jarvis-chat-input=""
autoFocus={autoFocus}
value={value}
onChange={(e) => setValueState(e.target.value)}
onKeyDown={onKeyDown}
+ onPaste={(e) => {
+ pasteRescue.onPaste();
+ files.onPaste(e);
+ }}
placeholder={placeholder}
disabled={!connected}
rows={2}
@@ -425,22 +492,59 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
{planOn ? t("agent_chat.mode_plan") : t("agent_chat.mode_build")}
</button>
)}
+ {/*
+ No folder chip on the Jarvis surface. Someone talking to Jarvis is
+ not pointing it at a checkout: the chip belongs to the IDE's chat,
+ and here it only ever showed the leaf of the default path — on
+ Windows the account name, which reads like a setting nobody chose.
+ The folder itself stays: a CLI seat needs a directory to start in,
+ and the surface brings its own (`surface_kits.py`) instead of the
+ home directory (maintainer, 2026-08-25).
+ */}
+ {surface !== "jarvis" && (
+ <button
+ type="button"
+ onClick={() => void onPickFolder()}
+ title={
+ draft.cwd ? `${t("agent_chat.surface_agent_hint")}: ${draft.cwd}` : t("agent_chat.folder")
+ }
+ aria-label={t("agent_chat.folder")}
+ data-testid="composer-folder"
+ className="inline-flex h-7 max-w-[160px] items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ >
+ <FolderOpen className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="hidden truncate font-mono text-[11px] 2xl:inline">{folderLeaf(draft.cwd)}</span>
+ </button>
+ )}
+ <span className="flex-1" />
+ {/*
+ Dropping and pasting are the primary paths; this is for the people
+ who do neither — and for a browser tab, where a drag out of Explorer
+ may carry nothing the page can read.
+ */}
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="sr-only"
+ tabIndex={-1}
+ onChange={(event) => {
+ const picked = Array.from(event.currentTarget.files ?? []);
+ event.currentTarget.value = "";
+ if (picked.length > 0) files.attachFiles(picked);
+ }}
+ />
<button
type="button"
- onClick={() => void onPickFolder()}
- title={
- draft.cwd
- ? `${t(surface === "jarvis" ? "agent_chat.folder_hint" : "agent_chat.surface_agent_hint")}: ${draft.cwd}`
- : t("agent_chat.folder")
- }
- aria-label={t("agent_chat.folder")}
- data-testid="composer-folder"
- className="inline-flex h-7 max-w-[160px] items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ data-testid="composer-attach"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={!connected}
+ aria-label={t("agent_chat.attach")}
+ title={t("agent_chat.attach_hint")}
+ className="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-transparent text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:opacity-50"
>
- <FolderOpen className="h-3.5 w-3.5 shrink-0" aria-hidden />
- <span className="hidden truncate font-mono text-[11px] 2xl:inline">{folderLeaf(draft.cwd)}</span>
+ <Paperclip className="h-4 w-4" />
</button>
- <span className="flex-1" />
<button
type="button"
data-jarvis-dictation-trigger
@@ -525,6 +629,15 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
</button>
</div>
)}
+ {attachError && (
+ <div
+ className="px-1 text-xs text-destructive"
+ role="alert"
+ data-testid="composer-attach-error"
+ >
+ {attachError}
+ </div>
+ )}
{lastError && (
<div className="px-1 text-xs text-destructive" role="alert" data-testid="composer-error">
{lastError}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
new file mode 100644
index 0000000000..28cd05cc03
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
@@ -0,0 +1,92 @@
+import { FileText, ImageIcon, Loader2, X } from "lucide-react";
+
+import type { ChatAttachment } from "@/lib/agentChatApi";
+import { fill, useT } from "@/i18n";
+
+/**
+ * The files waiting to go in with the next message.
+ *
+ * Each chip says what was actually LEARNED from the file, not merely that one
+ * is attached. That distinction is the whole feature: "screenshot.png" tells
+ * the person nothing about whether the model will be able to see it, while
+ * "described" and "not described" are the two outcomes they need to tell apart
+ * BEFORE pressing Send — and the second happens for real, on any install whose
+ * providers cannot see images.
+ *
+ * A near-twin of the Agentic IDE's terminal strip
+ * (components/agentic/PromptAttachments) and deliberately not shared with it:
+ * that one is hardcoded English, which is right inside a terminal composer
+ * whose every other label is too, and wrong in a chat that speaks the app's
+ * language everywhere else.
+ */
+export function ChatAttachmentStrip({
+ attachments,
+ analyzing,
+ onRemove,
+}: {
+ attachments: ChatAttachment[];
+ analyzing: number;
+ onRemove: (name: string) => void;
+}) {
+ const t = useT();
+ if (attachments.length === 0 && analyzing === 0) return null;
+ return (
+ <div
+ data-testid="chat-attachments"
+ className="flex max-h-20 shrink-0 flex-wrap items-center gap-1.5 overflow-y-auto px-1 scrollbar-jarvis"
+ >
+ {attachments.map((item) => {
+ const read = item.described_by !== "none" && item.detail.length > 0;
+ return (
+ <span
+ key={item.name}
+ data-testid={`chat-attachment-${item.name}`}
+ title={
+ read
+ ? `${item.detail.slice(0, 400)}${item.detail.length > 400 ? "…" : ""}`
+ : item.note || item.name
+ }
+ className={
+ "flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] " +
+ (read
+ ? "border-primary/40 bg-primary/10 text-foreground"
+ : "border-border text-muted-foreground")
+ }
+ >
+ {item.kind === "image" ? (
+ <ImageIcon className="h-3 w-3 shrink-0" aria-hidden />
+ ) : (
+ <FileText className="h-3 w-3 shrink-0" aria-hidden />
+ )}
+ <span className="max-w-[12rem] truncate font-mono">{item.name}</span>
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ {read
+ ? item.described_by === "vision"
+ ? t("agent_chat.attach_described")
+ : t("agent_chat.attach_text_read")
+ : t("agent_chat.attach_not_described")}
+ </span>
+ <button
+ type="button"
+ aria-label={fill(t("agent_chat.attach_remove"), { name: item.name })}
+ data-testid={`chat-attachment-remove-${item.name}`}
+ onClick={() => onRemove(item.name)}
+ className="shrink-0 rounded text-muted-foreground transition-colors hover:text-destructive"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ );
+ })}
+ {analyzing > 0 && (
+ <span
+ data-testid="chat-attachment-working"
+ className="flex items-center gap-1.5 rounded-md border border-dashed border-border px-2 py-1 text-[11px] text-muted-foreground"
+ >
+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
+ {t("agent_chat.attach_working")}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
new file mode 100644
index 0000000000..c34c6d8132
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
@@ -0,0 +1,302 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { AgentComposer } from "@/components/agentchat/AgentComposer";
+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";
+import { EMPTY_TIMELINE, reduceEvent } from "@/components/agentchat/reduce";
+import { useFileDropGuard } from "@/hooks/useFileDropGuard";
+import { useAgentChatStore } from "@/store/agentChat";
+import { useEventStore } from "@/store/events";
+import type { AgentChatCatalog } from "@/lib/agentChatApi";
+
+/**
+ * Files in the chat composer — the drop, the paste, and what travels with the
+ * message.
+ *
+ * The two chats (the front page and the Agentic IDE's chat mode) share this
+ * one composer, so everything asserted here holds for both. What is under test
+ * is that a file reaches the backend at all and that its CONTENTS ride along
+ * with the sentence: a chat can be answered by a coding CLI or a text-only
+ * model, and a bare path leaves those with a filename and a pronoun.
+ */
+
+const CATALOG: AgentChatCatalog = {
+ default_cwd: "C:\\work",
+ shell: "pwsh",
+ providers: [
+ {
+ id: "claude-api",
+ label: "Anthropic Claude",
+ family: "claude",
+ runner: "claude-cli",
+ models_source: "curated",
+ curated_models: [{ id: "claude-opus-5", label: "Claude Opus 5" }],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: ["low", "high"],
+ default_effort: "high",
+ permission_modes: [{ id: "default", label: "Ask before acting", description: "" }],
+ default_permission_mode: "default",
+ cli_installed: true,
+ },
+ ],
+};
+
+const ATTACHMENT = {
+ name: "shot.png",
+ reference: '".jarvis/drops/shot.png"',
+ kind: "image" as const,
+ detail: "A composer with no attach button.",
+ described_by: "vision" as const,
+ note: "",
+};
+
+function seed(overrides: Record<string, unknown> = {}) {
+ useAgentChatStore.setState({
+ catalog: CATALOG,
+ connections: [{ jarvis: "claude-api", key_set: true, is_active_brain: true }],
+ catalogError: null,
+ backendOutdated: false,
+ liveModels: {},
+ sessions: [],
+ activeSessionId: "s-1",
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ draft: {
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ permissionMode: "default",
+ buildMode: "default",
+ cwd: "C:\\work",
+ },
+ busy: false,
+ lastError: null,
+ loadCatalog: async () => {},
+ loadSessions: async () => {},
+ loadModels: async () => {},
+ ...overrides,
+ });
+}
+
+function composer() {
+ return render(
+ <AgentChatStoreProvider store={useAgentChatStore}>
+ <AgentComposer />
+ </AgentChatStoreProvider>,
+ );
+}
+
+/** A DataTransfer stand-in: jsdom's own carries neither files nor types. */
+function transfer(files: File[]) {
+ return {
+ files,
+ items: files.map((file) => ({ kind: "file", type: file.type, getAsFile: () => file })),
+ types: files.length ? ["Files"] : [],
+ getData: () => "",
+ dropEffect: "none",
+ };
+}
+
+describe("chat composer attachments", () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ window.localStorage.clear();
+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
+ seed();
+ fetchMock = vi.fn(async (url: string) => {
+ if (String(url).includes("/api/agent-chat/attachments")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ attachments: [ATTACHMENT], cwd: "C:\\work" }),
+ } as Response;
+ }
+ return { ok: true, status: 200, json: async () => ({ turn_id: "t-1" }) } as Response;
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("takes a pasted image and shows what was read from it", async () => {
+ composer();
+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
+ const png = new File([new Uint8Array([1, 2, 3])], "image.png", { type: "image/png" });
+
+ await act(async () => {
+ fireEvent.paste(box, { clipboardData: transfer([png]) });
+ });
+
+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
+ // The chip says the model could SEE it — that is the outcome a person has
+ // to be able to read before pressing Send.
+ expect(screen.getByTestId("chat-attachment-shot.png").textContent).toContain("described");
+
+ const [url, init] = fetchMock.mock.calls.find(([u]) =>
+ String(u).includes("/attachments"),
+ ) as [string, RequestInit];
+ expect(url).toContain("/api/agent-chat/attachments");
+ expect((init.body as FormData).get("session_id")).toBe("s-1");
+ });
+
+ it("leaves a pasted TEXT alone so ordinary copy-paste keeps working", async () => {
+ composer();
+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
+
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", { value: transfer([]) });
+ await act(async () => {
+ box.dispatchEvent(event);
+ });
+
+ // Not claimed, not prevented: the browser inserts the text itself.
+ expect(event.defaultPrevented).toBe(false);
+ expect(fetchMock.mock.calls.some(([u]) => String(u).includes("/attachments"))).toBe(false);
+ });
+
+ it("takes a dropped file and arms the drop overlay while the drag is over", async () => {
+ composer();
+ const card = screen.getByTestId("agent-composer");
+ const png = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });
+
+ fireEvent.dragEnter(card, { dataTransfer: transfer([png]) });
+ expect(screen.getByTestId("composer-drop-overlay")).toBeDefined();
+
+ await act(async () => {
+ fireEvent.drop(card, { dataTransfer: transfer([png]) });
+ });
+
+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
+ expect(screen.queryByTestId("composer-drop-overlay")).toBeNull();
+ });
+
+ it("sends the attachments with the sentence and then holds none", async () => {
+ const send = vi.fn(async () => {});
+ seed({ send });
+ composer();
+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
+ const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });
+
+ await act(async () => {
+ fireEvent.paste(box, { clipboardData: transfer([png]) });
+ });
+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
+
+ fireEvent.change(box, { target: { value: "what is wrong here" } });
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("composer-send"));
+ });
+
+ expect(send).toHaveBeenCalledWith("what is wrong here", [ATTACHMENT]);
+ // Cleared on send: the next message must not silently re-send the picture.
+ expect(screen.queryByTestId("chat-attachment-shot.png")).toBeNull();
+ });
+
+ it("lets a picture alone be the whole message", async () => {
+ const send = vi.fn(async () => {});
+ seed({ send });
+ composer();
+ const box = document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;
+ const png = new File([new Uint8Array([1])], "image.png", { type: "image/png" });
+
+ await act(async () => {
+ fireEvent.paste(box, { clipboardData: transfer([png]) });
+ });
+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("composer-send"));
+ });
+ expect(send).toHaveBeenCalledWith("", [ATTACHMENT]);
+ });
+});
+
+describe("the timeline's receipt for a message that carried files", () => {
+ it("shows the sentence that was typed, not the composed prompt", () => {
+ const tl = reduceEvent(EMPTY_TIMELINE, {
+ seq: 1,
+ ts_ms: 10,
+ kind: "user_message",
+ payload: {
+ text: "what is wrong here\n\n<attachment name=\"shot.png\">…</attachment>",
+ typed: "what is wrong here",
+ attachments: [{ name: "shot.png", kind: "image", described_by: "vision" }],
+ },
+ });
+ const item = tl.items[0];
+ expect(item.type).toBe("user");
+ if (item.type !== "user") return;
+ expect(item.text).toBe("what is wrong here");
+ expect(item.attachments).toEqual([
+ { name: "shot.png", kind: "image", describedBy: "vision" },
+ ]);
+ });
+
+ it("leaves an ordinary message exactly as it was", () => {
+ const tl = reduceEvent(EMPTY_TIMELINE, {
+ seq: 1,
+ ts_ms: 10,
+ kind: "user_message",
+ payload: { text: "hello" },
+ });
+ const item = tl.items[0];
+ if (item.type !== "user") throw new Error("expected a user item");
+ expect(item.text).toBe("hello");
+ expect(item.attachments).toEqual([]);
+ });
+});
+
+describe("the app-wide file drop guard", () => {
+ function Guarded() {
+ useFileDropGuard();
+ return <div data-testid="page">nothing here takes files</div>;
+ }
+
+ afterEach(cleanup);
+
+ /** A drop event carrying `types`, with `preventDefault` observable. */
+ function dropEvent(types: string[]) {
+ const event = new Event("drop", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "dataTransfer", {
+ value: { ...transfer([]), types },
+ });
+ const prevent = vi.spyOn(event, "preventDefault");
+ return { event, prevent };
+ }
+
+ it("swallows a file dropped on chrome that has no drop target", () => {
+ render(<Guarded />);
+ const { event, prevent } = dropEvent(["Files"]);
+ window.dispatchEvent(event);
+ // Prevented = the browser will NOT navigate away to the file, which inside
+ // the desktop shell would take the whole app with it.
+ expect(prevent).toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it("keeps its hands off a drop a real target already claimed", () => {
+ render(<Guarded />);
+ const { event, prevent } = dropEvent(["Files"]);
+ event.preventDefault(); // what a drop zone does, below window
+ prevent.mockClear();
+ window.dispatchEvent(event);
+ // The guard saw `defaultPrevented` and stood down — it never touches an
+ // event a target is already handling.
+ expect(prevent).not.toHaveBeenCalled();
+ });
+
+ it("leaves dragged text and links to the browser", () => {
+ render(<Guarded />);
+ const { event, prevent } = dropEvent(["text/plain"]);
+ window.dispatchEvent(event);
+ expect(prevent).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
index 2332c9206c..3bcb5d13ec 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -61,10 +61,29 @@ export type TurnStatus = "running" | "done" | "cancelled" | "error";
export interface UserItem {
type: "user";
id: string;
+ /**
+ * What the person WROTE.
+ *
+ * Not always what the turn received: a message with attached files carries
+ * their contents too (the backend composes it — jarvis/agent_chat/
+ * attachments.py), and showing a page of extracted PDF back to the person
+ * who typed one sentence would bury their own words. The full prompt stays
+ * in the event log, which is what the API runner rebuilds history from.
+ */
text: string;
+ /** Files that went in with this message; empty on an ordinary one. */
+ attachments: UserAttachment[];
tsMs: number;
}
+/** One file's receipt in the timeline — enough to say what was sent, no more. */
+export interface UserAttachment {
+ name: string;
+ kind: string;
+ /** `vision` / `extraction` / `none` — whether the model could read it. */
+ describedBy: string;
+}
+
export interface TurnItem {
type: "turn";
id: string;
@@ -117,6 +136,19 @@ export const EMPTY_TIMELINE: Timeline = {
sessionPatch: null,
};
+/** The attachment receipts off one `user_message`, tolerant of any shape. */
+function userAttachments(raw: unknown): UserAttachment[] {
+ if (!Array.isArray(raw)) return [];
+ const out: UserAttachment[] = [];
+ for (const entry of raw) {
+ if (!entry || typeof entry !== "object") continue;
+ const row = entry as Record<string, unknown>;
+ const name = str(row.name);
+ if (name) out.push({ name, kind: str(row.kind), describedBy: str(row.described_by) });
+ }
+ return out;
+}
+
function str(v: unknown, fallback = ""): string {
return typeof v === "string" ? v : fallback;
}
@@ -194,7 +226,15 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
...base,
items: [
...base.items,
- { type: "user", id: `u-${seq || ev.ts_ms}`, text: str(p.text), tsMs: ev.ts_ms },
+ {
+ type: "user",
+ id: `u-${seq || ev.ts_ms}`,
+ // `typed` is present only when the message carried files, and it
+ // is the person's own sentence; `text` is the composed prompt.
+ text: str(p.typed) || str(p.text),
+ attachments: userAttachments(p.attachments),
+ tsMs: ev.ts_ms,
+ },
],
};
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
new file mode 100644
index 0000000000..822455c7be
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
@@ -0,0 +1,166 @@
+/**
+ * Files waiting to go in with the next chat message — the drop, the paste and
+ * the paperclip.
+ *
+ * The Agentic IDE's terminal composer has taken files since 2026-08
+ * (components/agentic/PromptAttachments). The two CHATS — the front page and
+ * the IDE's chat mode, which share one composer — never did: a dropped
+ * screenshot landed on a bare `<textarea>`, where the browser's own default is
+ * to NAVIGATE to the file, replacing the whole app with the picture. A gesture
+ * that works one click away and destroys the view here reads as the app being
+ * broken, not as two surfaces with different features (maintainer, 2026-08-24).
+ *
+ * The pieces are deliberately the terminal path's own — the same drag tracking
+ * (`usePaneFileDrag`), the same payload extraction (`paneDrop`), the same
+ * desktop-shell path resolution (`waitForNativeDrop`) — so the two surfaces
+ * cannot drift into disagreeing about what a drop is. Only the endpoint
+ * differs: a chat has no pane to type a path into, so the files are HELD here
+ * and travel with the sentence when it is sent.
+ */
+import { useCallback, useState } from "react";
+
+import {
+ extractPaneDrop,
+ extractPasteFiles,
+ isEmptyPayload,
+ nameClipboardFile,
+ type PaneDropPayload,
+} from "@/components/agentic/paneDrop";
+import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";
+import { waitForNativeDrop } from "@/lib/nativeDrop";
+import { attachChatFiles, type AgentChatSurface, type ChatAttachment } from "@/lib/agentChatApi";
+
+export interface ChatAttachments {
+ /** What will travel with the next message. */
+ attachments: ChatAttachment[];
+ /** How many files are being read right now — 0 when nothing is in flight. */
+ analyzing: number;
+ /** True while a file drag hovers the composer; drives the drop styling. */
+ dragging: boolean;
+ /** Spread onto the element that should accept drops. */
+ dragHandlers: ReturnType<typeof usePaneFileDrag>["handlers"];
+ /** Attach files chosen by hand (the paperclip) or read off the clipboard. */
+ attachFiles: (files: File[]) => void;
+ /** Put on the text box: claims a pasted IMAGE, never a pasted text. */
+ onPaste: (event: React.ClipboardEvent) => void;
+ remove: (name: string) => void;
+ clear: () => void;
+}
+
+/**
+ * Hold files for one chat's next message.
+ *
+ * `onProblem` is where the caller puts its own error line — this hook does not
+ * decide how a surface reports things. It DOES decide how bad the news is: a
+ * drop that carried nothing usable is a warning about what was dragged, while
+ * an attach that threw is an error about the app, and collapsing the two
+ * buries the second.
+ */
+export function useChatAttachments(
+ target: {
+ sessionId: string | null;
+ cwd: string;
+ provider: string;
+ surface: AgentChatSurface;
+ },
+ onProblem: (message: string, severity: "warning" | "error") => void,
+): ChatAttachments {
+ const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
+ const [analyzing, setAnalyzing] = useState(0);
+ const { sessionId, cwd, provider, surface } = target;
+
+ const attach = useCallback(
+ async (payload: PaneDropPayload) => {
+ if (isEmptyPayload(payload)) return;
+ setAnalyzing((n) => n + 1);
+ try {
+ const found = await attachChatFiles({
+ files: payload.files,
+ paths: payload.paths,
+ sessionId,
+ cwd,
+ provider,
+ surface,
+ });
+ if (found.length === 0) {
+ onProblem("That drop carried nothing this chat could use.", "warning");
+ return;
+ }
+ // Keyed by name so the same file attached twice is held once — a
+ // repeated reference has the model read it again for nothing.
+ setAttachments((prev) => [
+ ...prev,
+ ...found.filter((item) => !prev.some((held) => held.name === item.name)),
+ ]);
+ } catch (e) {
+ onProblem((e as Error).message, "error");
+ } finally {
+ setAnalyzing((n) => Math.max(0, n - 1));
+ }
+ },
+ [sessionId, cwd, provider, surface, onProblem],
+ );
+
+ const { dragging, handlers: dragHandlers } = usePaneFileDrag(
+ useCallback(
+ (dt: DataTransfer) => {
+ // Both reads happen BEFORE any await, and they have to: a DataTransfer
+ // empties the moment this handler returns, and the desktop shell only
+ // answers a listener that was already in place when the drop happened.
+ const payload = extractPaneDrop(dt);
+ void waitForNativeDrop().then((detail) => {
+ if (!detail?.paths.length) return void attach(payload);
+ // Inside the desktop shell the host knows where the file really
+ // lies. Prefer that over uploading its bytes — same file, no copy —
+ // and drop the byte copies the shell just accounted for so nothing
+ // is attached twice.
+ const named = new Set(detail.names.map((n) => n.toLowerCase()));
+ return void attach({
+ paths: Array.from(new Set([...payload.paths, ...detail.paths])),
+ files: payload.files.filter((f) => !named.has(f.name.toLowerCase())),
+ });
+ });
+ },
+ [attach],
+ ),
+ );
+
+ const attachFiles = useCallback(
+ (files: File[]) => {
+ if (files.length > 0) void attach({ paths: [], files });
+ },
+ [attach],
+ );
+
+ const onPaste = useCallback(
+ (event: React.ClipboardEvent) => {
+ // Text paste belongs to the browser and must keep working — this only
+ // claims what a text box would otherwise DISCARD: an image on the
+ // clipboard, which is what PrintScreen and Ctrl+V produce.
+ const files = extractPasteFiles(event.clipboardData).map((f) =>
+ nameClipboardFile(f, "chat"),
+ );
+ if (files.length === 0) return;
+ event.preventDefault();
+ void attach({ paths: [], files });
+ },
+ [attach],
+ );
+
+ const remove = useCallback((name: string) => {
+ setAttachments((prev) => prev.filter((a) => a.name !== name));
+ }, []);
+
+ const clear = useCallback(() => setAttachments([]), []);
+
+ return {
+ attachments,
+ analyzing,
+ dragging,
+ dragHandlers,
+ attachFiles,
+ onPaste,
+ remove,
+ clear,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx
new file mode 100644
index 0000000000..a016ae70c3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.test.tsx
@@ -0,0 +1,112 @@
+import { act, cleanup, fireEvent, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { usePasteRescue } from "@/components/agentchat/usePasteRescue";
+
+/**
+ * Ctrl+V where the embedded browser never sends a `paste` event.
+ *
+ * The behaviour that matters is the NEGATIVE one: in a browser that pastes
+ * normally this hook must do nothing at all, or every paste lands twice. So
+ * both halves are pinned — the rescue fires when the event is missing, and
+ * stays out of the way when it is not.
+ */
+
+function Field({ onRescued }: { onRescued?: () => void }) {
+ const rescue = usePasteRescue();
+ return (
+ <textarea
+ data-testid="field"
+ defaultValue=""
+ onKeyDown={(e) => rescue.onKeyDown(e)}
+ onPaste={() => {
+ rescue.onPaste();
+ onRescued?.();
+ }}
+ />
+ );
+}
+
+describe("usePasteRescue", () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (String(url).includes("/api/clipboard/text") && (init?.method ?? "GET") === "GET") {
+ return { ok: true, status: 200, json: async () => ({ text: "from the clipboard" }) } as Response;
+ }
+ return { ok: false, status: 404, json: async () => ({}) } as Response;
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("puts the clipboard text in when no paste event follows the keystroke", async () => {
+ const { getByTestId } = render(<Field />);
+ const field = getByTestId("field") as HTMLTextAreaElement;
+ field.focus();
+
+ fireEvent.keyDown(field, { key: "v", ctrlKey: true });
+ // No `paste` event — this is the embedded browser that swallows it.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+
+ expect(fetchMock).toHaveBeenCalled();
+ expect(field.value).toBe("from the clipboard");
+ });
+
+ it("does nothing at all when the browser delivers the paste itself", async () => {
+ const { getByTestId } = render(<Field />);
+ const field = getByTestId("field") as HTMLTextAreaElement;
+ field.focus();
+
+ fireEvent.keyDown(field, { key: "v", ctrlKey: true });
+ fireEvent.paste(field, { clipboardData: { items: [], files: [], types: [] } });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+
+ // Never read the clipboard, never inserted: a second insertion here is
+ // exactly the double paste this timing exists to avoid.
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(field.value).toBe("");
+ });
+
+ it("ignores every keystroke that is not Ctrl/Cmd+V", async () => {
+ const { getByTestId } = render(<Field />);
+ const field = getByTestId("field") as HTMLTextAreaElement;
+
+ fireEvent.keyDown(field, { key: "v" });
+ fireEvent.keyDown(field, { key: "c", ctrlKey: true });
+ fireEvent.keyDown(field, { key: "v", ctrlKey: true, altKey: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("leaves an empty clipboard alone rather than reporting a failure", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ text: "" }) }) as Response),
+ );
+ const { getByTestId } = render(<Field />);
+ const field = getByTestId("field") as HTMLTextAreaElement;
+ field.focus();
+
+ fireEvent.keyDown(field, { key: "v", ctrlKey: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+ expect(field.value).toBe("");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts
new file mode 100644
index 0000000000..7675cf2089
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/usePasteRescue.ts
@@ -0,0 +1,85 @@
+import { useCallback, useEffect, useRef } from "react";
+
+import { robustPaste } from "@/lib/clipboard";
+import { captureEditSnapshot, pasteInto } from "@/lib/editActions";
+
+/**
+ * Make Ctrl+V put text in the box even where the embedded browser never sends
+ * a `paste` event.
+ *
+ * In a real browser this hook does nothing at all, and that is the design. A
+ * `<textarea>` pastes on its own; nothing here competes with it.
+ *
+ * The desktop shell is the reason it exists. Its WebView already withholds
+ * `clipboard-read` — measured in 2026-07, `navigator.clipboard.readText()`
+ * inside it never settles, resolved or rejected, which is why the right-click
+ * menu reads the clipboard through the host process instead (lib/clipboard).
+ * A build that also declines to deliver the `paste` event leaves Ctrl+V doing
+ * nothing whatsoever in a text box, with no error anywhere to explain it.
+ *
+ * ## How it can tell the difference
+ *
+ * A real paste delivers its event in the SAME task as the keystroke. So the
+ * keystroke arms a one-shot timer and the `paste` event disarms it; if the
+ * timer still fires, no paste was delivered and the text is fetched through
+ * the host route and inserted at the caret that was saved when the key went
+ * down. The window is deliberately short — long enough to outlast a busy main
+ * thread, far shorter than a person's next keystroke — because the failure
+ * mode to avoid is pasting twice.
+ *
+ * `pasteInto` goes through `insertText`, so the caret, the undo history and
+ * React's controlled value all survive (lib/editActions).
+ */
+
+/**
+ * How long a real `paste` has to arrive before the keystroke counts as
+ * unanswered. Browsers deliver it synchronously; this allows for a main thread
+ * busy with a streaming turn.
+ */
+const RESCUE_AFTER_MS = 150;
+
+export interface PasteRescue {
+ /** Call from the field's `onKeyDown`, before anything else. */
+ onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
+ /** Call from the field's `onPaste` — this is what proves the event arrives. */
+ onPaste: () => void;
+}
+
+export function usePasteRescue(): PasteRescue {
+ const timerRef = useRef<number | undefined>(undefined);
+
+ const disarm = useCallback(() => {
+ if (timerRef.current !== undefined) {
+ window.clearTimeout(timerRef.current);
+ timerRef.current = undefined;
+ }
+ }, []);
+
+ // A component unmounting mid-window must not paste into a field that is gone.
+ useEffect(() => disarm, [disarm]);
+
+ const onKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLElement>) => {
+ const key = event.key.toLowerCase();
+ if (key !== "v" || !(event.ctrlKey || event.metaKey) || event.altKey) return;
+ // Captured now: by the time the timer fires the caret may have moved,
+ // and the position the text belongs at is this one.
+ const snapshot = captureEditSnapshot(event.currentTarget);
+ if (!snapshot.editable) return;
+ disarm();
+ timerRef.current = window.setTimeout(() => {
+ timerRef.current = undefined;
+ void (async () => {
+ const text = await robustPaste();
+ // Null = no route could read the clipboard; empty = nothing on it.
+ // Neither is an error worth a message: the person pressed a key and
+ // the box stayed as it was, which is what an empty clipboard means.
+ if (text) pasteInto(snapshot, text);
+ })();
+ }, RESCUE_AFTER_MS);
+ },
+ [disarm],
+ );
+
+ return { onKeyDown, onPaste: disarm };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts b/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts
new file mode 100644
index 0000000000..4ba0c51d9e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useFileDropGuard.ts
@@ -0,0 +1,51 @@
+import { useEffect } from "react";
+
+/**
+ * Stop a missed file drop from replacing the app with the file.
+ *
+ * A browser's default action for a file dropped anywhere in a page is to
+ * NAVIGATE to it. Inside the desktop shell there is no address bar and no Back
+ * button, so a screenshot dropped two centimetres beside the composer does not
+ * merely fail — it takes the whole window: every open chat, every terminal in
+ * the grid, gone until the app is restarted. The person who did it has no way
+ * to read that as "you missed", because nothing about a picture filling the
+ * window says a drop was refused.
+ *
+ * So every drop that no drop zone claimed is swallowed here, and nothing else
+ * happens: no toast, no highlight. A drop on empty chrome SHOULD do nothing —
+ * this only makes "nothing" true.
+ *
+ * ## Why this cannot break a real drop target
+ *
+ * The listeners run in the BUBBLE phase on `window`, which is after React has
+ * delivered the event to its own tree (React 18 attaches at the root
+ * container, below `window`). A target that took the drop has already called
+ * `preventDefault()` by then, and `defaultPrevented` is how this tells the two
+ * apart. A handler that did NOT call it was not going to receive the file
+ * anyway — that is what the default action being navigation means.
+ *
+ * `dragover` needs the same treatment: without a `preventDefault()` there the
+ * browser refuses the drop before `drop` ever fires, so guarding only `drop`
+ * would leave the cursor showing 🚫 over the whole app. Guarding both keeps
+ * the page's own targets in charge of the cursor — they preventDefault first,
+ * and this one only claims what they left.
+ */
+export function useFileDropGuard(): void {
+ useEffect(() => {
+ const carriesFiles = (event: DragEvent): boolean => {
+ const types = event.dataTransfer?.types;
+ return types ? Array.from(types).includes("Files") : false;
+ };
+ const swallow = (event: DragEvent) => {
+ if (event.defaultPrevented) return; // a real target took it
+ if (!carriesFiles(event)) return; // dragged text/links are the browser's
+ event.preventDefault();
+ };
+ window.addEventListener("dragover", swallow);
+ window.addEventListener("drop", swallow);
+ return () => {
+ window.removeEventListener("dragover", swallow);
+ window.removeEventListener("drop", swallow);
+ };
+ }, []);
+}
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 6ff1694bed..20f739b74c 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -52,13 +52,12 @@ export interface AgentChatCatalog {
/**
* Where a session lives: the front page's typed chat (`jarvis` — the same
- * assistant as the microphone, on a keyboard), a coding session listed by
- * the Agentic IDE (`agent`), or the Local models section's setup assistant
- * (`local-models`). Each surface asks the backend for its own list and
- * catalog, so they never mix in a sidebar. Mirrors `SURFACES` in
+ * assistant as the microphone, on a keyboard) or a coding session listed by
+ * the Agentic IDE (`agent`). Each surface asks the backend for its own list
+ * and catalog, so they never mix in a sidebar. Mirrors `SURFACES` in
* `jarvis/agent_chat/store.py` (a parity test reads this union).
*/
-export type AgentChatSurface = "jarvis" | "agent" | "local-models";
+export type AgentChatSurface = "jarvis" | "agent";
export interface AgentChatSession {
session_id: string;
@@ -229,17 +228,76 @@ export async function fetchAgentChatSession(
export async function sendAgentChatMessage(
sessionId: string,
text: string,
+ attachments: ChatAttachment[] = [],
): Promise<{ turn_id: string }> {
return json(
await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ text }),
+ body: JSON.stringify({ text, attachments }),
}),
"send-failed",
);
}
+/**
+ * One file going in with the next message, and what was READ from it.
+ *
+ * `detail` is the whole point: a description written by a model that could see
+ * the image, or a document's extracted text. A chat can be answered by a coding
+ * CLI or a text-only model, neither of which can open the file itself, so the
+ * contents have to travel with the sentence.
+ *
+ * Structurally the same row the Agentic IDE's terminals hand back
+ * (`DropAttachment` in agenticIdeApi) — same backend analysis, same wire shape.
+ */
+export interface ChatAttachment {
+ name: string;
+ /** How the agent should refer to the file — `@path` or a quoted path. */
+ reference: string;
+ kind: "image" | "text" | "pdf" | "other";
+ /** The description or extracted text. Empty when neither could be produced. */
+ detail: string;
+ /** Which layer produced `detail`. */
+ described_by: "vision" | "extraction" | "none";
+ /** Why `detail` is empty or shortened. Empty on the happy path. */
+ note: string;
+}
+
+/**
+ * Hand dropped, pasted or picked files to the backend and get them READ.
+ *
+ * Nothing is sent to the agent here — the composer holds the result while the
+ * person finishes the sentence, then posts both together.
+ *
+ * `paths` are real locations the browser managed to supply (an Explorer drag,
+ * or the desktop shell resolving the drop); `files` are the bytes for
+ * everything with no path at all. Sending both is normal and the backend
+ * de-duplicates, because a drag can carry the path AND the bytes.
+ */
+export async function attachChatFiles(payload: {
+ files?: File[];
+ paths?: string[];
+ sessionId?: string | null;
+ cwd?: string;
+ provider?: string;
+ surface?: AgentChatSurface;
+}): Promise<ChatAttachment[]> {
+ const form = new FormData();
+ for (const file of payload.files ?? []) form.append("files", file, file.name);
+ if (payload.paths?.length) form.append("paths", payload.paths.join("\n"));
+ if (payload.sessionId) form.append("session_id", payload.sessionId);
+ if (payload.cwd) form.append("cwd", payload.cwd);
+ if (payload.provider) form.append("provider", payload.provider);
+ if (payload.surface) form.append("surface", payload.surface);
+
+ const data = await json<{ attachments?: ChatAttachment[] }>(
+ await fetch("/api/agent-chat/attachments", { method: "POST", body: form }),
+ "attach-failed",
+ );
+ return Array.isArray(data.attachments) ? data.attachments : [];
+}
+
export async function cancelAgentChatTurn(sessionId: string): Promise<void> {
await json(
await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/cancel`, {
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index d126397400..5e4a47f94f 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -19,6 +19,7 @@ import {
type AgentChatSurface,
type AgentConnectionRow,
type ApprovalDecision,
+ type ChatAttachment,
type CuratedModel,
type PatchSessionInput,
} from "@/lib/agentChatApi";
@@ -117,7 +118,8 @@ export interface AgentChatStore {
newChat: () => void;
openSession: (sessionId: string) => void;
removeSession: (sessionId: string) => Promise<void>;
- send: (text: string) => Promise<void>;
+ /** Send the sentence, with whatever files the composer is holding for it. */
+ send: (text: string, attachments?: ChatAttachment[]) => Promise<void>;
cancel: () => Promise<void>;
decide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
/** Tests and the socket: fold one event into the active timeline. */
@@ -497,9 +499,11 @@ export function createAgentChatStore(surface: AgentChatSurface) {
void get().loadSessions();
},
- send: async (text) => {
+ send: async (text, attachments = []) => {
const content = text.trim();
- if (!content) return;
+ // A message may be files alone — dropping a screenshot and pressing
+ // Enter is a complete gesture — but never nothing at all.
+ if (!content && attachments.length === 0) return;
const st = get();
set({ busy: true, lastError: null });
try {
@@ -523,7 +527,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {
});
connect(sid, 0);
}
- await sendAgentChatMessage(sid, content);
+ await sendAgentChatMessage(sid, content, attachments);
void get().loadSessions();
} catch (err) {
set({ lastError: errorText(err) });
diff --git a/tests/unit/agent_chat/test_chat_attachments.py b/tests/unit/agent_chat/test_chat_attachments.py
new file mode 100644
index 0000000000..a910f5a59b
--- /dev/null
+++ b/tests/unit/agent_chat/test_chat_attachments.py
@@ -0,0 +1,257 @@
+"""Files dropped, pasted or picked into a chat composer.
+
+Covers the whole path the composer uses: the attach route stores the bytes and
+returns what was read from them, and the message that follows carries those
+contents into the turn while the timeline still shows the person's own
+sentence.
+
+The vision layer is faked throughout. What is under test is the wiring — that a
+chat can take a file at all, which is what it could not do — not whether a
+model describes a picture well.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat import attachments as chat_attachments
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agentic_ide import drop_analysis
+from jarvis.ui.web.agent_chat_routes import router
+
+# A one-pixel PNG — real bytes, so the store and the mime guess behave.
+PNG = bytes.fromhex(
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
+ "890000000a49444154789c6360000002000100" + "05fe02fe" + "0000000049454e44ae426082"
+)
+
+
+def _app(tmp_path: Path) -> FastAPI:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = None
+ app.state.agent_chat_factory = lambda: AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ return app
+
+
+def described(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every image comes back described, without a provider being involved."""
+
+ async def fake_analyze(items, **_kwargs): # noqa: ANN001, ANN202
+ return [
+ drop_analysis.DropAnalysis(
+ name=item.name,
+ reference=reference,
+ kind="image",
+ detail="A screenshot of a chat composer with no attach button.",
+ described_by=drop_analysis.BY_VISION,
+ )
+ for item, reference in items
+ ]
+
+ monkeypatch.setattr(drop_analysis, "analyze", fake_analyze)
+
+
+# ---------------------------------------------------------------- the route
+
+
+def test_attach_stores_the_bytes_and_returns_what_was_read(tmp_path: Path, described) -> None:
+ with TestClient(_app(tmp_path)) as client:
+ res = client.post(
+ "/api/agent-chat/attachments",
+ files=[("files", ("shot.png", PNG, "image/png"))],
+ data={"cwd": str(tmp_path), "surface": "jarvis"},
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+
+ (row,) = body["attachments"]
+ assert row["name"].endswith(".png")
+ assert row["described_by"] == "vision"
+ assert "composer" in row["detail"]
+ # The copy landed in the chat's own folder, where the agent can open it.
+ copies = list((tmp_path / ".jarvis" / "drops").glob("*.png"))
+ assert len(copies) == 1
+ assert copies[0].read_bytes() == PNG
+
+
+def test_attach_falls_back_to_the_surface_folder_when_the_cwd_is_gone(
+ tmp_path: Path, described
+) -> None:
+ """A remembered folder that no longer exists must not refuse the file."""
+ with TestClient(_app(tmp_path)) as client:
+ res = client.post(
+ "/api/agent-chat/attachments",
+ files=[("files", ("shot.png", PNG, "image/png"))],
+ data={"cwd": str(tmp_path / "moved-away"), "surface": "agent"},
+ )
+ assert res.status_code == 200, res.text
+ assert res.json()["cwd"] == str(tmp_path)
+
+
+def test_attach_refuses_an_empty_drop(tmp_path: Path) -> None:
+ with TestClient(_app(tmp_path)) as client:
+ res = client.post(
+ "/api/agent-chat/attachments",
+ data={"cwd": str(tmp_path), "paths": " \n "},
+ )
+ assert res.status_code == 422
+ assert "nothing" in res.json()["detail"].lower()
+
+
+def test_a_path_inside_the_folder_is_referenced_where_it_lies(
+ tmp_path: Path, described
+) -> None:
+ """Nothing is copied for a file the agent can already open."""
+ existing = tmp_path / "notes.png"
+ existing.write_bytes(PNG)
+
+ with TestClient(_app(tmp_path)) as client:
+ res = client.post(
+ "/api/agent-chat/attachments",
+ data={"cwd": str(tmp_path), "paths": str(existing)},
+ )
+ assert res.status_code == 200, res.text
+ (row,) = res.json()["attachments"]
+ assert "notes.png" in row["reference"]
+ assert not (tmp_path / ".jarvis" / "drops").exists()
+
+
+# ------------------------------------------------------------- composition
+
+
+def test_compose_leaves_an_ordinary_message_alone() -> None:
+ assert chat_attachments.compose("what is this", []) == "what is this"
+ assert chat_attachments.compose(" spaced ", None) == "spaced"
+
+
+def test_compose_carries_the_contents_into_the_message() -> None:
+ item = drop_analysis.DropAnalysis(
+ name="shot.png",
+ reference='"shot.png"',
+ kind="image",
+ detail="A red error banner over the login form.",
+ described_by=drop_analysis.BY_VISION,
+ )
+ out = chat_attachments.compose("fix this", [item])
+
+ assert out.startswith("fix this")
+ # The description is what makes the drop useful to a model that cannot open
+ # the file, so it must be IN the message, not merely referenced.
+ assert "A red error banner over the login form." in out
+ assert "shot.png" in out
+
+
+def test_to_analysis_survives_a_malformed_row() -> None:
+ """The rows come back from a browser, so no shape may be assumed.
+
+ A message somebody is waiting to send must not 500 over a stray field:
+ anything that is not an object is dropped, and a row with a missing or
+ mistyped field degrades to a named, empty-detail attachment.
+ """
+ rows = [
+ {"name": "ok.png", "kind": "image", "detail": "d", "described_by": "vision"},
+ {"kind": "image"}, # no name — kept under a placeholder, not dropped
+ "not a dict", # not an object at all — dropped
+ {"name": "odd.txt", "detail": 42}, # wrong type — degrades to empty
+ ]
+ out = chat_attachments.to_analysis(rows) # type: ignore[arg-type]
+ assert [item.name for item in out] == ["ok.png", "file", "odd.txt"]
+ assert out[2].detail == ""
+
+
+# ------------------------------------------------------ the message it rides
+
+
+def test_a_message_with_files_shows_the_sentence_and_sends_the_contents(
+ tmp_path: Path,
+) -> None:
+ """The event log holds both halves, and each is used for its own job."""
+ svc = AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ session = svc.store.create_session(
+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)
+ )
+
+ async def run() -> None:
+ # No runner is reachable for "fakeprov" here, so the turn fails after
+ # the user message is persisted — which is the part under test.
+ await svc.send(
+ session.session_id,
+ "what is wrong here",
+ [
+ {
+ "name": "shot.png",
+ "reference": '"shot.png"',
+ "kind": "image",
+ "detail": "A red error banner.",
+ "described_by": "vision",
+ "note": "",
+ }
+ ],
+ )
+ await svc.cancel(session.session_id)
+
+ asyncio.run(run())
+
+ events = svc.store.list_events(session.session_id)
+ user = next(e for e in events if e["kind"] == "user_message")
+ payload = user["payload"]
+ # What the person typed — the timeline shows this.
+ assert payload["typed"] == "what is wrong here"
+ # What the turn received — history rebuilds from this.
+ assert "A red error banner." in payload["text"]
+ assert payload["text"].startswith("what is wrong here")
+ # The receipt the timeline draws under the message.
+ assert payload["attachments"] == [
+ {"name": "shot.png", "kind": "image", "described_by": "vision", "note": ""}
+ ]
+
+
+def test_files_alone_are_a_complete_message(tmp_path: Path) -> None:
+ """Dropping a picture and pressing Enter says enough."""
+ svc = AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ session = svc.store.create_session(
+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)
+ )
+
+ async def run() -> None:
+ await svc.send(
+ session.session_id,
+ "",
+ [{"name": "shot.png", "reference": "x", "kind": "image", "detail": "A chart."}],
+ )
+ await svc.cancel(session.session_id)
+
+ asyncio.run(run())
+ user = next(
+ e for e in svc.store.list_events(session.session_id) if e["kind"] == "user_message"
+ )
+ assert "A chart." in user["payload"]["text"]
+
+
+def test_an_empty_message_with_nothing_attached_is_still_refused(tmp_path: Path) -> None:
+ svc = AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ session = svc.store.create_session(
+ provider="fakeprov", model="", effort="", cwd=str(tmp_path)
+ )
+
+ async def run() -> None:
+ with pytest.raises(ValueError):
+ await svc.send(session.session_id, " ", [])
+
+ asyncio.run(run())