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(agentic-ide): drop and paste files onto a terminal pane

Ruben Lütkebe6170eb49d1
diff --git a/jarvis/agentic_ide/drops.py b/jarvis/agentic_ide/drops.py
new file mode 100644
index 0000000000..a58f7177b3
--- /dev/null
+++ b/jarvis/agentic_ide/drops.py
@@ -0,0 +1,259 @@
+"""Files dropped or pasted onto a terminal pane.
+
+A native terminal takes a dragged file and writes its PATH into the prompt.
+A browser cannot: for security it hands a web page the file's BYTES and never
+its location. That is the whole reason dropping a screenshot onto an agent pane
+did nothing — the pane had no drop handler, and a handler alone would not have
+been enough, because what the coding agent needs is a path it can open.
+
+So a drop takes one of two routes, and the caller picks by what it actually has:
+
+1. **The path came along.** Dragging out of Explorer or Finder usually puts the
+ real path in the drag payload (``text/uri-list``). Nothing is copied — the
+ path is typed straight into the agent. This is the common case for "look at
+ this file in my project".
+2. **Only bytes.** A screenshot pasted from the clipboard, an image dragged off
+ a web page, a file from a sandboxed source. Those are written into the
+ workspace here, and the path of the written copy is what the agent gets.
+
+Why the copies land INSIDE the workspace rather than in a temp directory: a
+coding agent's file access is scoped, and how it treats an absolute path from
+somewhere else varies by agent, by version, and by the user's permission
+settings. Betting on that would make the feature work on the maintainer's
+machine and prompt-or-fail on someone else's. A path inside the folder the user
+opened needs no permission from anyone.
+
+The drop directory hides itself from git by carrying its own ``.gitignore`` with
+``*`` in it — so a dropped screenshot never shows up in the user's `git status`
+and we never touch their repository configuration to achieve that.
+"""
+from __future__ import annotations
+
+import os
+import re
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+from loguru import logger
+
+#: Where copies of pasted/dropped bytes land, relative to the workspace root.
+DROP_DIRNAME = ".jarvis/drops"
+
+#: Per-file cap. A screenshot is ~1-5 MB; 25 MB covers a screen recording still
+#: or a large PDF without letting an accidental drop of a video eat the disk.
+MAX_FILE_BYTES = 25 * 1024 * 1024
+
+#: Total cap for one drop, so dragging a whole folder of images is bounded.
+MAX_TOTAL_BYTES = 100 * 1024 * 1024
+
+#: How many files one drop may carry.
+MAX_FILES = 20
+
+#: Dropped copies older than this are swept when a new drop arrives. Long enough
+#: that yesterday's screenshot is still there if the agent is still working on
+#: it, short enough that the folder does not grow without bound.
+KEEP_SECONDS = 7 * 24 * 3600
+
+# A dropped name is attacker-adjacent input (it can come from a web page), and it
+# also has to survive Windows. Keep letters, digits and the safe punctuation;
+# everything else becomes an underscore.
+_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+")
+
+# Windows refuses these as file names regardless of extension.
+_RESERVED = frozenset(
+ {
+ "con", "prn", "aux", "nul",
+ *(f"com{i}" for i in range(1, 10)),
+ *(f"lpt{i}" for i in range(1, 10)),
+ }
+)
+
+
+@dataclass(frozen=True, slots=True)
+class StoredDrop:
+ """One file written into the workspace's drop directory."""
+
+ relative_path: str
+ """Repo-relative, forward-slashed — what gets typed into the agent."""
+
+ absolute_path: str
+ name: str
+ size: int
+
+
+class DropError(RuntimeError):
+ """A drop the module refuses, with a user-facing English message."""
+
+
+def safe_name(raw: str) -> str:
+ """A file name safe to write on any of the three platforms.
+
+ Path separators are stripped rather than escaped: a dropped ``name`` may
+ contain ``../`` (it is not a trusted value), and the only correct reading of
+ that is "this is part of the name", never "walk up a directory".
+ """
+ base = os.path.basename((raw or "").replace("\\", "/")).strip()
+ cleaned = _UNSAFE.sub("_", base).strip("._-")
+ if not cleaned:
+ cleaned = "file"
+ stem, dot, ext = cleaned.rpartition(".")
+ if dot and stem.lower() in _RESERVED:
+ cleaned = f"{stem}_{dot}{ext}"
+ elif not dot and cleaned.lower() in _RESERVED:
+ cleaned = f"{cleaned}_"
+ # Windows caps a path component at 255; leave room for the timestamp prefix.
+ return cleaned[:120]
+
+
+def drop_dir(workspace: str | Path) -> Path:
+ """The workspace's drop directory, created and self-ignoring."""
+ target = Path(workspace).expanduser() / DROP_DIRNAME
+ target.mkdir(parents=True, exist_ok=True)
+ # The directory hides its whole contents from git without the user ever
+ # having to edit their own .gitignore. Written once; harmless to rewrite.
+ marker = target.parent / ".gitignore"
+ if not marker.exists():
+ try:
+ marker.write_text("*\n", encoding="utf-8")
+ except OSError as exc: # noqa: BLE001 - cosmetic, never fatal
+ logger.debug("Agentic IDE: drop dir gitignore not written: {}", exc)
+ return target
+
+
+def sweep(workspace: str | Path, *, keep_seconds: int = KEEP_SECONDS) -> int:
+ """Delete drop copies older than ``keep_seconds``. Returns how many went."""
+ try:
+ target = Path(workspace).expanduser() / DROP_DIRNAME
+ if not target.is_dir():
+ return 0
+ cutoff = time.time() - max(0, keep_seconds)
+ removed = 0
+ with os.scandir(target) as it:
+ for item in it:
+ try:
+ if item.is_file(follow_symlinks=False) and item.stat().st_mtime < cutoff:
+ os.unlink(item.path)
+ removed += 1
+ except OSError:
+ continue
+ return removed
+ except OSError:
+ return 0
+
+
+def store(
+ workspace: str | Path,
+ files: list[tuple[str, bytes]],
+) -> list[StoredDrop]:
+ """Write ``(name, data)`` pairs into the workspace drop directory.
+
+ Raises ``DropError`` on an empty drop, too many files, or a size overrun —
+ the caller turns that into an HTTP error the user actually reads.
+ """
+ if not files:
+ raise DropError("That drop carried no file.")
+ if len(files) > MAX_FILES:
+ raise DropError(f"Too many files at once (max {MAX_FILES}).")
+
+ total = sum(len(data) for _n, data in files)
+ if total > MAX_TOTAL_BYTES:
+ raise DropError(
+ f"That drop is too large (max {MAX_TOTAL_BYTES // (1024 * 1024)} MB in total)."
+ )
+ for name, data in files:
+ if len(data) > MAX_FILE_BYTES:
+ raise DropError(
+ f"{name!r} is too large (max {MAX_FILE_BYTES // (1024 * 1024)} MB per file)."
+ )
+
+ root = Path(workspace).expanduser()
+ target = drop_dir(root)
+ sweep(root)
+
+ stored: list[StoredDrop] = []
+ # One timestamp for the whole drop, so files dropped together sort together.
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ for index, (name, data) in enumerate(files):
+ if not data:
+ continue
+ base = safe_name(name)
+ # A second drop of the same screenshot must not overwrite the first —
+ # the agent may still be working on it.
+ suffix = "" if len(files) == 1 else f"-{index + 1}"
+ candidate = target / f"{stamp}{suffix}-{base}"
+ counter = 2
+ while candidate.exists():
+ candidate = target / f"{stamp}{suffix}-{counter}-{base}"
+ counter += 1
+ try:
+ candidate.write_bytes(data)
+ except OSError as exc:
+ raise DropError(f"Could not save {base}: {exc}") from exc
+ stored.append(
+ StoredDrop(
+ relative_path=candidate.relative_to(root).as_posix(),
+ absolute_path=str(candidate),
+ name=base,
+ size=len(data),
+ )
+ )
+
+ if not stored:
+ raise DropError("Every dropped file was empty.")
+ logger.info(
+ "Agentic IDE: stored {} dropped file(s) in {}", len(stored), target
+ )
+ return stored
+
+
+def reference(path: str, *, agent: str) -> str:
+ """How ``path`` should be written so ``agent`` picks the file up.
+
+ Claude Code resolves ``@path`` into the file's contents — verified live, the
+ file-picker popup does not eat an injected reference. Codex has no such
+ syntax, so it gets a quoted path and reads it because the sentence asks it
+ to. Quoting matters on both: workspace paths contain spaces far more often
+ than people expect ("Personal Jarvis").
+ """
+ posix = path.replace("\\", "/")
+ if agent == "claude":
+ # An @reference containing a space would end at the space, so a path
+ # that needs quoting is passed plainly instead of half-referenced.
+ return f"@{posix}" if " " not in posix else f'"{posix}"'
+ return f'"{posix}"'
+
+
+def within_workspace(path: str, workspace: str | Path) -> str | None:
+ """``path`` as a workspace-relative posix path, or ``None`` if it is outside.
+
+ Used for the fast route: a file dragged out of Explorer already lives
+ somewhere, and when that somewhere is inside the open workspace there is
+ nothing to copy — the agent can open it where it is.
+ """
+ try:
+ root = Path(workspace).expanduser().resolve()
+ candidate = Path(path).expanduser().resolve()
+ except (OSError, ValueError):
+ return None
+ try:
+ return candidate.relative_to(root).as_posix()
+ except ValueError:
+ return None
+
+
+__all__ = [
+ "DROP_DIRNAME",
+ "KEEP_SECONDS",
+ "MAX_FILES",
+ "MAX_FILE_BYTES",
+ "MAX_TOTAL_BYTES",
+ "DropError",
+ "StoredDrop",
+ "drop_dir",
+ "reference",
+ "safe_name",
+ "store",
+ "sweep",
+ "within_workspace",
+]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index d2512b8a7a..2f9e334284 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -12,8 +12,11 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``POST /session`` → open a workspace (folder + terminals)
* ``DELETE /session`` → close it and stop every agent
* ``PUT /mode`` → focused coding mode on/off
+* ``POST /terminals`` → open one more pane (split)
+* ``POST /terminals/batch`` → open N more panes at once
* ``GET /terminals/{name}/report`` → what one named terminal is doing
* ``POST /terminals/{name}/prompt`` → type a prompt into it and press Enter
+* ``POST /terminals/{name}/attach`` → drop/paste files onto a pane
* ``WS /pty/{name}`` → the pane's live terminal stream
``{name}`` accepts the call-sign ("mika", "Mika") or a spoken phrase containing
@@ -26,7 +29,16 @@ import logging
from dataclasses import asdict
from pathlib import Path
-from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from fastapi import (
+ APIRouter,
+ File,
+ Form,
+ HTTPException,
+ Request,
+ UploadFile,
+ WebSocket,
+ WebSocketDisconnect,
+)
from pydantic import BaseModel, Field
from jarvis.agentic_ide import recents
@@ -40,6 +52,7 @@ from jarvis.agentic_ide.session import (
SessionError,
agent_argv,
get_registry,
+ terminals_added_event,
)
from .surface_security import credentials_valid
@@ -90,6 +103,21 @@ class AddTerminalRequest(BaseModel):
)
+class AddTerminalsRequest(BaseModel):
+ """Open several panes at once (the spoken "five more terminals")."""
+
+ count: int = Field(
+ default=1,
+ ge=1,
+ le=MAX_TERMINALS,
+ description="How many terminals to open, capped by the workspace maximum.",
+ )
+ agent: str | None = Field(
+ default=None,
+ description="Coding agent to run in all of them; defaults to the last pane's.",
+ )
+
+
class ModeRequest(BaseModel):
enabled: bool = Field(
description="True narrows Jarvis to this workspace; False returns to normal."
@@ -434,6 +462,48 @@ async def add_terminal(req: AddTerminalRequest) -> dict:
return {"ok": True, "terminal": term.to_dict(), "state": get_registry().state()}
[email protected]("/terminals/batch", summary="Open several terminals at once")
+async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:
+ """Open ``count`` more terminals in the running workspace.
+
+ The batch behind a spoken "open five more Claude Code terminals", and the
+ same call the CLI makes. Placement, call-signs and the agent default are the
+ single-terminal endpoint's — this only repeats it and reports honestly when
+ the workspace cap cut the request short.
+
+ ``capped`` is true when fewer panes were opened than asked for. A client MUST
+ surface that: five requested with three opened is not a plain success.
+ """
+ registry = get_registry()
+ try:
+ created, capped = await registry.add_terminals(req.count, agent=req.agent)
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+ # Tell every connected client, so a workspace view that is already open shows
+ # the new panes instead of a stale grid. Best-effort: the panes exist whether
+ # or not a bus is attached (it is not, in tests).
+ session = registry.session
+ bus = getattr(request.app.state, "bus", None)
+ if session is not None and bus is not None and created:
+ try:
+ await bus.publish(
+ terminals_added_event(
+ session, created, source_layer="agentic_ide_routes"
+ )
+ )
+ except Exception as exc: # noqa: BLE001 - notification is not the work
+ log.debug("AgenticIdeTerminalsAdded publish failed: %s", exc)
+
+ return {
+ "ok": True,
+ "requested": req.count,
+ "capped": capped,
+ "terminals": [t.to_dict() for t in created],
+ "state": registry.state(),
+ }
+
+
@router.delete(
"/terminals/{name}",
summary="Close one terminal",
@@ -457,6 +527,132 @@ async def terminal_report(name: str, lines: int = 40) -> dict:
raise HTTPException(status_code=404, detail=str(exc)) from exc
[email protected]("/terminals/{name}/attach", summary="Drop or paste files onto a terminal")
+async def terminal_attach(
+ name: str,
+ files: list[UploadFile] | None = File(default=None), # noqa: B008
+ paths: str | None = Form(default=None), # noqa: B008
+ submit: bool = Form(default=False), # noqa: B008
+ note: str | None = Form(default=None), # noqa: B008
+) -> dict:
+ """Put dropped or pasted files in front of the agent in terminal ``name``.
+
+ Two inputs, either or both:
+
+ * ``paths`` — newline-separated real paths the browser DID manage to hand
+ over (an Explorer/Finder drag usually carries them). Nothing is copied;
+ one inside the workspace is referenced where it lies, one outside is
+ copied in, because an agent's access to unrelated parts of the disk is
+ neither guaranteed nor silent.
+ * ``files`` — raw bytes, for everything with no path at all: a screenshot
+ pasted from the clipboard, an image dragged off a web page.
+
+ The resulting references are TYPED into the pane, not submitted, so the user
+ can add a sentence before pressing Enter — which is what someone dropping a
+ screenshot almost always wants to do. ``submit=true`` sends it as-is.
+ """
+ from jarvis.agentic_ide import drops
+
+ registry = get_registry()
+ session = registry.session
+ if session is None:
+ raise HTTPException(
+ status_code=409, detail="No Agentic-IDE session is running."
+ )
+ term = session.find(name)
+ if term is None:
+ known = ", ".join(t.name for t in session.terminals) or "none"
+ raise HTTPException(
+ status_code=404, detail=f"No terminal called {name!r}. Running: {known}."
+ )
+
+ references: list[str] = []
+ stored_names: list[str] = []
+ copied = 0
+
+ # 1. Paths that came with the drag. A path already inside the workspace is
+ # used as it lies; anything else is copied in.
+ to_copy: list[tuple[str, bytes]] = []
+ for raw in (paths or "").splitlines():
+ candidate = raw.strip()
+ if not candidate:
+ continue
+ inside = drops.within_workspace(candidate, session.folder)
+ if inside is not None:
+ references.append(drops.reference(inside, agent=term.agent))
+ stored_names.append(Path(inside).name)
+ continue
+ # expanduser() is string/env work, not a filesystem call; 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("Agentic IDE attach: unreadable dropped path %r (%s)", candidate, exc)
+ continue
+ to_copy.append((resolved.name, data))
+
+ # 2. Bytes the browser handed over directly.
+ total = 0
+ for upload in files or []:
+ data = await upload.read()
+ total += len(data)
+ if total > drops.MAX_TOTAL_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ f"That drop is too large (max "
+ f"{drops.MAX_TOTAL_BYTES // (1024 * 1024)} MB in total)."
+ ),
+ )
+ if data:
+ to_copy.append((upload.filename or "file", data))
+
+ if to_copy:
+ try:
+ stored = await asyncio.to_thread(drops.store, session.folder, to_copy)
+ except drops.DropError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ copied = len(stored)
+ for item in stored:
+ references.append(drops.reference(item.relative_path, agent=term.agent))
+ stored_names.append(item.name)
+
+ if not references:
+ raise HTTPException(
+ status_code=422,
+ detail="That drop carried nothing this pane could use.",
+ )
+
+ payload = " ".join(references)
+ if note and note.strip():
+ payload = f"{payload} {note.strip()}"
+
+ try:
+ if submit:
+ await registry.send_prompt(term.name, payload)
+ else:
+ # Typed, not submitted: the user still wants to say what to DO with
+ # the file. A leading space keeps it off whatever they already typed.
+ if not registry.write(term.key, f"{payload} "):
+ raise HTTPException(
+ status_code=409,
+ detail=f"{term.name} is not accepting input right now.",
+ )
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+ return {
+ "ok": True,
+ "terminal": term.name,
+ "references": references,
+ "files": stored_names,
+ "copied": copied,
+ "submitted": bool(submit),
+ }
+
+
@router.post("/terminals/{name}/prompt", summary="Send a prompt to one terminal")
async def terminal_prompt(name: str, req: PromptRequest) -> dict:
"""Type ``prompt`` into the terminal called ``name`` and press Enter.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index ffd751849f..8117bc4cb5 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -427,6 +427,7 @@ export function AgenticGrid({
}
onSplit={(direction, agent) => void split(term.name, direction, agent)}
onClose={() => setPendingClose(term.name)}
+ onAttachError={(message) => pushToast("error", message)}
restartToken={restartTokens[term.name] ?? 0}
onRestart={() => restartPane(term.name)}
/>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index ddb8095d2f..1147de8443 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -38,7 +38,7 @@
* redrawing on every keystroke that is both slow and subtly misaligned. The
* canvas renderer draws on a grid, which is what a terminal actually is.
*/
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
@@ -52,6 +52,7 @@ import {
Loader2,
Maximize2,
Minimize2,
+ Paperclip,
Rows2,
RotateCcw,
X,
@@ -62,6 +63,14 @@ import {
themeFor,
type TerminalAppearance,
} from "./terminalThemes";
+import {
+ extractPaneDrop,
+ extractPasteFiles,
+ isEmptyPayload,
+ nameClipboardFile,
+ type PaneDropPayload,
+} from "./paneDrop";
+import { attachToTerminal } from "@/lib/agenticIdeApi";
export type PaneStatus = "connecting" | "live" | "exited" | "error";
@@ -106,6 +115,8 @@ interface AgenticTerminalProps {
onClose?: () => void;
/** Disable the split buttons — the workspace is at its terminal limit. */
splitDisabled?: boolean;
+ /** A dropped or pasted file could not be attached — the grid surfaces it. */
+ onAttachError?: (message: string) => void;
/** Called when the user asks a dead pane to start a fresh agent. */
onRestart?: () => void;
/**
@@ -142,6 +153,7 @@ export function AgenticTerminal({
agents,
onClose,
splitDisabled = false,
+ onAttachError,
onRestart,
restartToken = 0,
}: AgenticTerminalProps) {
@@ -387,16 +399,92 @@ export function AgenticTerminal({
resizeRef.current?.();
}, [fontSize]);
+ /*
+ * Drag a file onto the pane, or paste a screenshot into it.
+ *
+ * A native terminal writes a dragged file's PATH into the prompt; a browser
+ * cannot, because it never tells a web page where a file lives. So the drop is
+ * read synchronously (a DataTransfer empties the instant this handler
+ * returns — see ./paneDrop), handed to the backend, and what comes back is
+ * already typed into the agent's input.
+ *
+ * Deliberately typed and NOT submitted: someone dropping a screenshot wants to
+ * say what to do with it. The reference appears, the cursor sits after it.
+ */
+ const [dragging, setDragging] = useState(false);
+ const [attaching, setAttaching] = useState(false);
+ const dragDepth = useRef(0);
+
+ const attach = useCallback(
+ async (payload: PaneDropPayload) => {
+ if (isEmptyPayload(payload)) {
+ onAttachError?.("That drop carried no file this pane could use.");
+ return;
+ }
+ setAttaching(true);
+ try {
+ await attachToTerminal(name, payload);
+ termRef.current?.focus();
+ } catch (e) {
+ onAttachError?.((e as Error).message);
+ } finally {
+ setAttaching(false);
+ }
+ },
+ [name, onAttachError],
+ );
+
+ // Clipboard images only — text paste stays with xterm, which already does it
+ // right, and intercepting it would break ordinary copy-paste into the agent.
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const onPaste = (event: ClipboardEvent) => {
+ const images = extractPasteFiles(event.clipboardData).map((f) =>
+ nameClipboardFile(f, name),
+ );
+ if (images.length === 0) return;
+ event.preventDefault();
+ void attach({ paths: [], files: images });
+ };
+ container.addEventListener("paste", onPaste);
+ return () => container.removeEventListener("paste", onPaste);
+ }, [attach, name]);
+
const chrome = PANE_CHROME[appearance];
return (
<div
onMouseDown={onFocus}
+ onDragEnter={(e) => {
+ e.preventDefault();
+ // Counted, not a boolean: dragging across the xterm canvas fires
+ // enter/leave for every child element, and a boolean flickers.
+ dragDepth.current += 1;
+ setDragging(true);
+ }}
+ onDragOver={(e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ }}
+ onDragLeave={() => {
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
+ if (dragDepth.current === 0) setDragging(false);
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ dragDepth.current = 0;
+ setDragging(false);
+ onFocus?.();
+ // Read BEFORE any await — the DataTransfer is gone after this returns.
+ void attach(extractPaneDrop(e.dataTransfer));
+ }}
className={cn(
"relative flex h-full w-full flex-col overflow-hidden rounded-xl border transition-shadow",
focused
? "border-primary/60 shadow-[0_0_0_1px_hsl(var(--primary)/0.35),0_8px_24px_-12px_rgba(0,0,0,0.5)]"
: "shadow-[0_4px_16px_-10px_rgba(0,0,0,0.4)]",
+ dragging && "border-primary shadow-[0_0_0_2px_hsl(var(--primary)/0.5)]",
)}
style={{
background: chrome.shell,
@@ -419,6 +507,25 @@ export function AgenticTerminal({
splitDisabled={splitDisabled}
/>
<div ref={containerRef} className="flex-1 overflow-hidden px-2 pb-1 pt-1" />
+ {(dragging || attaching) && (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-background/70 backdrop-blur-[2px]">
+ <div className="flex items-center gap-2 rounded-xl border border-primary/50 bg-card px-4 py-2.5 text-sm shadow-lg">
+ {attaching ? (
+ <>
+ <Loader2 className="h-4 w-4 animate-spin text-primary" />
+ <span>Attaching to {name}…</span>
+ </>
+ ) : (
+ <>
+ <Paperclip className="h-4 w-4 text-primary" />
+ <span>
+ Drop to put it in front of <strong>{name}</strong>
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ )}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts
new file mode 100644
index 0000000000..8beb1cc689
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+import {
+ extractPaneDrop,
+ extractPasteFiles,
+ isEmptyPayload,
+ nameClipboardFile,
+} from "./paneDrop";
+
+/** Minimal DataTransfer stand-in — jsdom has no real one. */
+function dt(opts: {
+ uriList?: string;
+ text?: string;
+ files?: File[];
+}): DataTransfer {
+ return {
+ getData: (type: string) =>
+ type === "text/uri-list" ? (opts.uriList ?? "") : (opts.text ?? ""),
+ files: opts.files ?? [],
+ items: (opts.files ?? []).map((file) => ({
+ kind: "file" as const,
+ type: file.type,
+ getAsFile: () => file,
+ })),
+ } as unknown as DataTransfer;
+}
+
+function file(name: string, type = "image/png", size = 4): File {
+ return new File([new Uint8Array(size)], name, { type });
+}
+
+describe("reading a drop onto a terminal pane", () => {
+ it("takes the real path Explorer and Finder hand over", () => {
+ const payload = extractPaneDrop(dt({ uriList: "file:///C:/work/shot.png\r\n" }));
+ expect(payload.paths).toEqual(["C:/work/shot.png"]);
+ });
+
+ it("takes a POSIX path the same way", () => {
+ expect(extractPaneDrop(dt({ text: "/home/ruben/shot.png" })).paths).toEqual([
+ "/home/ruben/shot.png",
+ ]);
+ });
+
+ it("takes a UNC path", () => {
+ expect(extractPaneDrop(dt({ text: "\\\\nas\\share\\shot.png" })).paths).toEqual([
+ "\\\\nas\\share\\shot.png",
+ ]);
+ });
+
+ it("keeps the bytes when there is no path — a pasted screenshot has none", () => {
+ const payload = extractPaneDrop(dt({ files: [file("image.png")] }));
+ expect(payload.paths).toEqual([]);
+ expect(payload.files.map((f) => f.name)).toEqual(["image.png"]);
+ });
+
+ it("does not send the same file twice when both a path and bytes arrive", () => {
+ // A normal Explorer drag produces exactly this: a path AND a File object.
+ const payload = extractPaneDrop(
+ dt({ uriList: "file:///C:/work/shot.png", files: [file("shot.png")] }),
+ );
+ expect(payload.paths).toEqual(["C:/work/shot.png"]);
+ expect(payload.files).toEqual([]);
+ });
+
+ it("ignores dragged prose, which also arrives as text/plain", () => {
+ // Dragging a selected sentence must not have the backend try to read it
+ // off the disk.
+ const payload = extractPaneDrop(dt({ text: "please look at the wake code" }));
+ expect(isEmptyPayload(payload)).toBe(true);
+ });
+
+ it("ignores a dropped directory, which arrives as an empty type-less entry", () => {
+ const payload = extractPaneDrop(dt({ files: [file("src", "", 0)] }));
+ expect(payload.files).toEqual([]);
+ });
+
+ it("reads several dropped files at once", () => {
+ const payload = extractPaneDrop(
+ dt({ uriList: "file:///C:/a.png\r\nfile:///C:/b.png" }),
+ );
+ expect(payload.paths).toEqual(["C:/a.png", "C:/b.png"]);
+ });
+
+ it("survives a drop with nothing in it", () => {
+ expect(isEmptyPayload(extractPaneDrop(null))).toBe(true);
+ expect(isEmptyPayload(extractPaneDrop(dt({})))).toBe(true);
+ });
+});
+
+describe("reading a paste", () => {
+ it("picks up a clipboard image", () => {
+ expect(extractPasteFiles(dt({ files: [file("image.png")] })).length).toBe(1);
+ });
+
+ it("leaves a text paste to xterm", () => {
+ // No files on the clipboard → nothing for us; xterm handles the text.
+ expect(extractPasteFiles(dt({ text: "some text" }))).toEqual([]);
+ });
+
+ it("renames the generic clipboard name so screenshots stay distinguishable", () => {
+ const renamed = nameClipboardFile(file("image.png"), "Kai");
+ expect(renamed.name).toMatch(/^kai-paste-\d{8}-\d{6}\.png$/);
+ });
+
+ it("keeps a name the user actually chose", () => {
+ expect(nameClipboardFile(file("design-review.png"), "Kai").name).toBe(
+ "design-review.png",
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts
new file mode 100644
index 0000000000..c256a84c54
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts
@@ -0,0 +1,141 @@
+/**
+ * Reading a drop or a paste that lands on a terminal pane.
+ *
+ * A browser hands a web page two very different things depending on where the
+ * drag came from, and the difference decides whether anything has to be copied:
+ *
+ * * **A real path.** Explorer and Finder put the file's location in
+ * `text/uri-list` (and usually `text/plain`). Nothing needs copying — the
+ * agent can open the file where it lies.
+ * * **Only bytes.** A screenshot pasted from the clipboard, an image dragged
+ * off a web page, anything from a sandboxed source. There is no path to be
+ * had — that is a deliberate browser restriction, not something to work
+ * around — so those bytes have to be written somewhere the agent can reach.
+ *
+ * Both are collected here and sent together; the backend copies only what it
+ * has to.
+ *
+ * The hard constraint that shapes this file: **a DataTransfer is emptied the
+ * moment the event handler returns.** Reading it after an `await` yields an
+ * empty list — a bug that reads as "dropping sometimes does nothing". So every
+ * extraction below is synchronous, and the async work happens afterwards on
+ * what was already pulled out.
+ */
+
+export interface PaneDropPayload {
+ /** Real filesystem paths the drag carried, if any. */
+ paths: string[];
+ /** Raw files, for everything the browser gave no path for. */
+ files: File[];
+}
+
+/** True when this payload has nothing worth sending. */
+export function isEmptyPayload(payload: PaneDropPayload): boolean {
+ return payload.paths.length === 0 && payload.files.length === 0;
+}
+
+/**
+ * A `file://` URI as a native path; anything else unchanged.
+ *
+ * Windows URIs carry a leading slash before the drive letter
+ * (`file:///C:/x` → `C:/x`), which is why this cannot be a plain `slice(7)`.
+ */
+function unwrapFileUri(value: string): string {
+ if (!/^file:/i.test(value)) return value;
+ let path: string;
+ try {
+ path = decodeURIComponent(new URL(value).pathname);
+ } catch {
+ return value;
+ }
+ if (path.length > 2 && path[0] === "/" && path[2] === ":") path = path.slice(1);
+ return path;
+}
+
+/**
+ * Does this string look like a filesystem path rather than dragged prose?
+ *
+ * Dragging selected TEXT also fills `text/plain`, and sending that as a path
+ * would have the backend try to read a sentence off the disk. A path is
+ * single-line and either absolute (`/x`, `C:\x`, `\\server\share`) or a
+ * `file://` URI — a relative-looking fragment is far more likely to be text.
+ */
+function looksLikePath(value: string): boolean {
+ const trimmed = value.trim();
+ if (!trimmed || /[\r\n]/.test(trimmed)) return false;
+ if (/^file:/i.test(trimmed)) return true;
+ if (/^[a-zA-Z]:[\\/]/.test(trimmed)) return true;
+ if (trimmed.startsWith("\\\\")) return true;
+ return trimmed.startsWith("/");
+}
+
+/**
+ * Everything usable in a drop, pulled out synchronously.
+ *
+ * Files and paths are matched up by NAME so a single drag does not produce
+ * both a path and a byte copy of the same file: when Explorer gives us the
+ * path, the `File` object beside it is redundant.
+ */
+export function extractPaneDrop(dt: DataTransfer | null): PaneDropPayload {
+ const out: PaneDropPayload = { paths: [], files: [] };
+ if (!dt) return out;
+
+ const raw = dt.getData("text/uri-list") || dt.getData("text/plain") || "";
+ for (const line of raw.split(/[\r\n]+/)) {
+ const candidate = line.trim();
+ if (!candidate || candidate.startsWith("#")) continue;
+ const unwrapped = unwrapFileUri(candidate);
+ if (looksLikePath(unwrapped)) out.paths.push(unwrapped);
+ }
+
+ const named = new Set(
+ out.paths.map((p) => p.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? ""),
+ );
+ for (const file of Array.from(dt.files ?? [])) {
+ // A directory dropped into a pane arrives as a zero-byte, type-less entry;
+ // there is nothing to attach and copying it would produce an empty file.
+ if (file.size === 0 && !file.type) continue;
+ if (named.has(file.name.toLowerCase())) continue;
+ out.files.push(file);
+ }
+
+ return out;
+}
+
+/**
+ * Files worth attaching from a paste.
+ *
+ * Text paste is left entirely alone — xterm already handles that, and grabbing
+ * it here would break ordinary copy-paste into the agent. This only picks up
+ * the case xterm cannot express: an IMAGE on the clipboard, which is exactly
+ * what pressing PrintScreen and Ctrl+V produces.
+ */
+export function extractPasteFiles(data: DataTransfer | null): File[] {
+ if (!data) return [];
+ const files: File[] = [];
+ for (const item of Array.from(data.items ?? [])) {
+ if (item.kind !== "file") continue;
+ const file = item.getAsFile();
+ if (file && file.size > 0) files.push(file);
+ }
+ return files;
+}
+
+/**
+ * A clipboard image arrives named `image.png` — every screenshot would land
+ * under the same name and the user could not tell them apart in the agent's
+ * output. Give it the pane and a timestamp instead.
+ */
+export function nameClipboardFile(file: File, paneName: string): File {
+ const generic = !file.name || /^image\.[a-z0-9]+$/i.test(file.name);
+ if (!generic) return file;
+ const ext = (file.type.split("/")[1] || "png").replace(/[^a-z0-9]/gi, "");
+ const stamp = new Date()
+ .toISOString()
+ .replace(/[-:]/g, "")
+ .replace(/\..+$/, "")
+ .replace("T", "-");
+ return new File([file], `${paneName.toLowerCase()}-paste-${stamp}.${ext}`, {
+ type: file.type,
+ });
+}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 64d1b3a454..89e0894291 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -251,6 +251,43 @@ export async function setFocusMode(enabled: boolean): Promise<boolean> {
return body.focus_mode;
}
+export interface AttachResult {
+ terminal: string;
+ /** What was typed into the pane — `@path` for Claude Code, a quoted path otherwise. */
+ references: string[];
+ /** File names now in front of the agent. */
+ files: string[];
+ /** How many had to be copied into the workspace (the rest were already there). */
+ copied: number;
+ submitted: boolean;
+}
+
+/**
+ * Put dropped or pasted files in front of the agent in one pane.
+ *
+ * Two inputs because a browser gives you one or the other, never reliably both:
+ * `paths` are the real locations an Explorer/Finder drag usually carries, and
+ * `files` are raw bytes for everything else (a pasted screenshot has no path at
+ * all). Sending both lets the backend skip copying whatever already exists.
+ */
+export async function attachToTerminal(
+ name: string,
+ payload: { files?: File[]; paths?: string[]; note?: string; submit?: boolean },
+): Promise<AttachResult> {
+ 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.note) form.append("note", payload.note);
+ if (payload.submit) form.append("submit", "true");
+
+ const res = await fetch(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/attach`,
+ { method: "POST", body: form },
+ );
+ if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as AttachResult;
+}
+
export interface PromptResult {
terminal: string;
/** What was actually typed into the agent. */
diff --git a/tests/unit/agentic_ide/test_drops.py b/tests/unit/agentic_ide/test_drops.py
new file mode 100644
index 0000000000..13d9bf7e43
--- /dev/null
+++ b/tests/unit/agentic_ide/test_drops.py
@@ -0,0 +1,141 @@
+"""Guards for files dropped or pasted onto a terminal pane.
+
+The interesting cases are all about untrusted input and about not making a mess
+of the user's repository: a dropped name can come from a web page (so it can
+contain ``../`` or a Windows-reserved word), a second drop of the same
+screenshot must not overwrite the first while the agent is still reading it,
+and none of this may show up in the user's ``git status``.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import drops
+
+
+def workspace(tmp_path: Path) -> Path:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "main.py").write_text("x")
+ return tmp_path
+
+
+def test_a_dropped_file_lands_in_the_workspace(workspace: Path) -> None:
+ stored = drops.store(workspace, [("shot.png", b"\x89PNG-data")])
+ assert len(stored) == 1
+ item = stored[0]
+ assert item.relative_path.startswith(f"{drops.DROP_DIRNAME}/")
+ assert item.relative_path.endswith("shot.png")
+ # The path handed to the agent must actually resolve.
+ assert (workspace / item.relative_path).read_bytes() == b"\x89PNG-data"
+
+
+def test_the_drop_directory_hides_itself_from_git(workspace: Path) -> None:
+ """A dropped screenshot must never appear in the user's `git status`."""
+ drops.store(workspace, [("shot.png", b"data")])
+ ignore = workspace / ".jarvis" / ".gitignore"
+ assert ignore.is_file()
+ assert ignore.read_text(encoding="utf-8").strip() == "*"
+
+
+ ("raw", "forbidden"),
+ [
+ ("../../etc/passwd", ".."),
+ ("..\\..\\windows\\system32\\cfg", ".."),
+ ("/absolute/evil.png", "/"),
+ ("C:\\Windows\\evil.png", ":"),
+ ],
+)
+def test_a_hostile_name_cannot_escape_the_drop_directory(
+ workspace: Path, raw: str, forbidden: str
+) -> None:
+ """A dropped name is untrusted input — it names a file, never a location."""
+ stored = drops.store(workspace, [(raw, b"data")])
+ written = Path(stored[0].absolute_path).resolve()
+ assert written.parent == (workspace / drops.DROP_DIRNAME).resolve()
+ assert forbidden not in Path(stored[0].relative_path).name
+
+
+def test_windows_reserved_names_are_made_writable(workspace: Path) -> None:
+ """`con.txt` cannot be created on Windows regardless of extension."""
+ stored = drops.store(workspace, [("con.txt", b"data")])
+ assert Path(stored[0].relative_path).name.lower() != "con.txt"
+ assert Path(stored[0].absolute_path).is_file()
+
+
+def test_two_drops_of_the_same_name_keep_both(workspace: Path) -> None:
+ """The agent may still be reading the first one."""
+ first = drops.store(workspace, [("shot.png", b"one")])
+ second = drops.store(workspace, [("shot.png", b"two")])
+ assert first[0].absolute_path != second[0].absolute_path
+ assert Path(first[0].absolute_path).read_bytes() == b"one"
+ assert Path(second[0].absolute_path).read_bytes() == b"two"
+
+
+def test_oversized_drops_are_refused_with_a_readable_message(
+ workspace: Path,
+) -> None:
+ big = b"x" * (drops.MAX_FILE_BYTES + 1)
+ with pytest.raises(drops.DropError, match="too large"):
+ drops.store(workspace, [("huge.bin", big)])
+
+ with pytest.raises(drops.DropError, match="Too many files"):
+ drops.store(workspace, [(f"f{i}.txt", b"x") for i in range(drops.MAX_FILES + 1)])
+
+ with pytest.raises(drops.DropError, match="no file"):
+ drops.store(workspace, [])
+
+
+def test_empty_files_are_skipped_not_written(workspace: Path) -> None:
+ stored = drops.store(workspace, [("empty.txt", b""), ("real.txt", b"x")])
+ assert len(stored) == 1
+ assert stored[0].name == "real.txt"
+
+
+def test_a_file_already_in_the_workspace_needs_no_copy(workspace: Path) -> None:
+ inside = workspace / "src" / "main.py"
+ assert drops.within_workspace(str(inside), workspace) == "src/main.py"
+
+
+def test_a_file_outside_the_workspace_is_recognised_as_outside(
+ workspace: Path, tmp_path: Path
+) -> None:
+ outside = tmp_path.parent / "elsewhere.png"
+ assert drops.within_workspace(str(outside), workspace) is None
+
+
+ ("agent", "path", "expected"),
+ [
+ ("claude", ".jarvis/drops/shot.png", "@.jarvis/drops/shot.png"),
+ ("codex", ".jarvis/drops/shot.png", '".jarvis/drops/shot.png"'),
+ # A space would end an @reference early, so it is quoted plainly instead
+ # of shipping a half-reference the agent resolves to the wrong file.
+ ("claude", "my docs/shot.png", '"my docs/shot.png"'),
+ ],
+)
+def test_reference_syntax_matches_the_agent(
+ agent: str, path: str, expected: str
+) -> None:
+ assert drops.reference(path, agent=agent) == expected
+
+
+def test_sweep_removes_only_stale_copies(workspace: Path) -> None:
+ import os
+ import time
+
+ stored = drops.store(workspace, [("old.png", b"x"), ("new.png", b"y")])
+ old = Path(stored[0].absolute_path)
+ stale = time.time() - (drops.KEEP_SECONDS + 60)
+ os.utime(old, (stale, stale))
+
+ assert drops.sweep(workspace) == 1
+ assert not old.exists()
+ assert Path(stored[1].absolute_path).exists()
+
+
+def test_sweep_on_a_folder_with_no_drops_is_harmless(tmp_path: Path) -> None:
+ assert drops.sweep(tmp_path) == 0
diff --git a/tests/unit/agentic_ide/test_prompt_composer.py b/tests/unit/agentic_ide/test_prompt_composer.py
index 6a7187f373..dbe6cb5d78 100644
--- a/tests/unit/agentic_ide/test_prompt_composer.py
+++ b/tests/unit/agentic_ide/test_prompt_composer.py
@@ -32,6 +32,26 @@ class _Session:
profile: _Profile = field(default_factory=_Profile)
+class _Writer:
+ """Stands in for a resolved quality-tier Brain.
+
+ Every test here patches ``_llm_compose``, so this only has to exist — the
+ point is that ``compose`` found a model it considers good enough and did
+ not take the honest-degradation exit.
+ """
+
+
[email protected](autouse=True)
+def _writer_available(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A quality-tier writer is reachable unless a test says otherwise.
+
+ Without this the composer would resolve the real provider chain, which on a
+ machine with no keys returns None and sends every test down the
+ deterministic path.
+ """
+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: _Writer())
+
+
@pytest.fixture()
def workspace(tmp_path: Path) -> _Session:
(tmp_path / "jarvis" / "plugins" / "wake").mkdir(parents=True)
@@ -149,20 +169,25 @@ async def test_a_fenced_or_quoted_answer_is_unwrapped(
assert result.text == "Review the wake word detection."
-async def test_use_llm_false_sends_the_text_through(workspace: _Session) -> None:
- """The typed prompt bar must not have its wording rewritten behind the user."""
+async def test_use_llm_false_keeps_the_users_own_wording(workspace: _Session) -> None:
+ """The typed prompt bar must not have its wording rewritten behind the user.
+
+ Asserted on the WORDS surviving rather than on the exact string: the prompt
+ carries a markdown skeleton around them, and what must not happen is the
+ instruction being rephrased, not the skeleton existing.
+ """
_prime(workspace)
result = await prompt_composer.compose(
"run the tests", session=workspace, terminal_name="Kai", use_llm=False
)
assert result.composed_by == "raw"
- assert result.text.startswith("run the tests")
+ assert "run the tests" in result.text
async def test_an_index_that_is_not_ready_yet_does_not_block(
workspace: _Session, monkeypatch: pytest.MonkeyPatch
) -> None:
- """A workspace whose walk is still running ships without references."""
+ """A workspace whose walk is still running ships without file references."""
file_index.reset_cache()
async def _echo(**kwargs: object) -> str:
@@ -173,4 +198,6 @@ async def test_an_index_that_is_not_ready_yet_does_not_block(
result = await prompt_composer.compose(
"review the vosk wake provider", session=workspace, terminal_name="Kai"
)
- assert result.text == "Review the wake word detection."
+ # The instruction goes out; with no index there is nothing to attach.
+ assert "wake" in result.text.lower()
+ assert result.files == []