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.

fix(ide): accept dropped files of any size instead of capping at 25 MB

rubenluetke10-beep6f2b32d527bd
diff --git a/jarvis/agent_chat/attachments.py b/jarvis/agent_chat/attachments.py
index bc84f8a635..4b55c2a463 100644
--- a/jarvis/agent_chat/attachments.py
+++ b/jarvis/agent_chat/attachments.py
@@ -33,24 +33,22 @@ from __future__ import annotations
import asyncio
import logging
+from collections.abc import Sequence
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from jarvis.agentic_ide.drops import DropSource
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."""
@@ -59,7 +57,7 @@ async def ingest(
cwd: str | Path,
*,
paths: list[str] | None = None,
- uploads: list[tuple[str, bytes]] | None = None,
+ uploads: Sequence[tuple[str, DropSource]] | None = None,
provider: str = "",
) -> list[Any]:
"""Store what was dropped in ``cwd`` and read what is in it.
@@ -68,7 +66,8 @@ async def ingest(
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 web page. An upload may also be an open binary file (the web server's
+ spooled copy), so a large one streams to disk instead of into memory.
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
@@ -89,7 +88,7 @@ async def ingest(
# (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]] = []
+ to_copy: list[tuple[str, DropSource]] = []
for raw in paths or []:
candidate = (raw or "").strip()
@@ -100,45 +99,43 @@ async def ingest(
reference = drops.reference(inside, agent=provider)
references.append(reference)
try:
- body = await asyncio.to_thread((folder / inside).read_bytes)
+ body = await asyncio.to_thread(drops.read_for_analysis, folder / inside)
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))
+ if body is not None:
+ 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).
+ # expanduser() is string work; the stat itself goes to a worker thread
+ # (a dropped file may live on a slow network share). The copy streams
+ # from the path, so a large recording is never held in memory.
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)
+ if not await asyncio.to_thread(resolved.is_file):
+ log.info("chat attach: unreadable dropped path %r", candidate)
continue
- to_copy.append((resolved.name, data))
+ to_copy.append((resolved.name, resolved))
- 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))
+ for name, source in uploads or []:
+ to_copy.append((name or "file", source))
# ``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]
+ sizes = await asyncio.to_thread(lambda: [drops.size_of(src) for _n, src in to_copy])
+ to_copy = [pair for pair, size in zip(to_copy, sizes, strict=True) if size != 0]
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):
+ for item, (_original, source) in zip(stored, to_copy, strict=True):
reference = drops.reference(item.relative_path, agent=provider)
references.append(reference)
- readable.append((item.name, data, reference))
+ # A file too large to analyse still ships; it goes undescribed.
+ body = await asyncio.to_thread(drops.read_for_analysis, source)
+ if body is not None:
+ readable.append((item.name, body, reference))
if not references:
raise AttachmentError("That attachment carried nothing this chat could use.")
diff --git a/jarvis/agentic_ide/drops.py b/jarvis/agentic_ide/drops.py
index f9eef9dbfb..86b5394a96 100644
--- a/jarvis/agentic_ide/drops.py
+++ b/jarvis/agentic_ide/drops.py
@@ -23,6 +23,12 @@ 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.
+There is no size cap. A screen recording is exactly the kind of file someone
+drops on an agent, and refusing it is worse than any cost of storing it. What
+keeps a big drop safe instead is how it is handled: a copy streams to disk in
+chunks (never the whole file in memory), and a drop that would leave the disk
+nearly full is refused with a message saying exactly that.
+
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.
@@ -31,21 +37,29 @@ from __future__ import annotations
import os
import re
+import shutil
import time
from dataclasses import dataclass
from pathlib import Path
+from typing import BinaryIO, TypeAlias
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
+#: Free space a drop must leave behind. Filling the disk to the last byte breaks
+#: far more than the drop (the agent, the app's own database, the OS), so a drop
+#: that would cross this line is refused instead.
+DISK_RESERVE_BYTES = 512 * 1024 * 1024
+
+#: Largest file whose bytes are read back for an analysis (image description,
+#: text/PDF extraction). A bigger file is still stored and referenced - the
+#: agent opens it itself - it just carries no description.
+MAX_ANALYSIS_BYTES = 25 * 1024 * 1024
-#: Total cap for one drop, so dragging a whole folder of images is bounded.
-MAX_TOTAL_BYTES = 100 * 1024 * 1024
+#: Chunk size for streaming a copy to disk.
+_COPY_CHUNK = 1024 * 1024
#: How many files one drop may carry.
MAX_FILES = 20
@@ -86,6 +100,77 @@ class DropError(RuntimeError):
"""A drop the module refuses, with a user-facing English message."""
+#: What one dropped file can be: bytes already in memory, a path on disk to
+#: copy from, or an open binary file (an upload the web server spooled to disk).
+DropSource: TypeAlias = bytes | Path | BinaryIO
+
+
+def size_of(source: DropSource) -> int:
+ """Byte size of ``source`` without reading it. -1 if it cannot be told."""
+ if isinstance(source, (bytes, bytearray)):
+ return len(source)
+ if isinstance(source, Path):
+ try:
+ return source.stat().st_size
+ except OSError:
+ return -1
+ try:
+ here = source.tell()
+ end = source.seek(0, os.SEEK_END)
+ source.seek(here)
+ return int(end)
+ except (OSError, ValueError, AttributeError):
+ return -1
+
+
+def read_for_analysis(source: DropSource, *, limit: int = MAX_ANALYSIS_BYTES) -> bytes | None:
+ """The bytes of ``source`` for an analysis, or ``None`` when it is too big.
+
+ Only called for files an analysis will actually look at, so a large video
+ dropped next to a screenshot is never pulled into memory.
+ """
+ size = size_of(source)
+ if size < 0 or size > limit:
+ return None
+ if isinstance(source, (bytes, bytearray)):
+ return bytes(source)
+ if isinstance(source, Path):
+ return source.read_bytes()
+ source.seek(0)
+ return source.read()
+
+
+def _write(source: DropSource, target: Path) -> None:
+ """Write ``source`` to ``target``, streaming anything not already in memory."""
+ if isinstance(source, (bytes, bytearray)):
+ target.write_bytes(source)
+ return
+ if isinstance(source, Path):
+ shutil.copyfile(source, target)
+ return
+ source.seek(0)
+ with target.open("wb") as out:
+ shutil.copyfileobj(source, out, _COPY_CHUNK)
+
+
+def _ensure_room(target: Path, needed: int) -> None:
+ """Refuse a drop that would leave the disk nearly full."""
+ try:
+ free = shutil.disk_usage(target).free
+ except OSError as exc:
+ # Unknown free space is not a reason to refuse: the write itself fails
+ # loudly (and cleans up) if the disk really is full.
+ logger.debug("Agentic IDE: free-space check skipped: {}", exc)
+ return
+ if needed + DISK_RESERVE_BYTES > free:
+ need_mb = -(-needed // (1024 * 1024))
+ free_mb = free // (1024 * 1024)
+ raise DropError(
+ f"Not enough free disk space for that drop ({need_mb} MB needed, "
+ f"{free_mb} MB free)."
+ )
+
+
def safe_name(raw: str) -> str:
"""A file name safe to write on any of the three platforms.
@@ -144,41 +229,35 @@ def sweep(workspace: str | Path, *, keep_seconds: int = KEEP_SECONDS) -> int:
def store(
workspace: str | Path,
- files: list[tuple[str, bytes]],
+ files: list[tuple[str, DropSource]],
) -> list[StoredDrop]:
- """Write ``(name, data)`` pairs into the workspace drop directory.
+ """Write ``(name, source)`` 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.
+ Each source is bytes, a path to copy from, or an open binary file; anything
+ not already in memory is streamed. Raises ``DropError`` on an empty drop,
+ too many files, or too little free disk space - 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)."
- )
+ sizes = [size_of(source) for _name, source in files]
root = Path(workspace).expanduser()
target = drop_dir(root)
sweep(root)
+ _ensure_room(target, sum(size for size in sizes if size > 0))
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:
+ for index, ((name, source), size) in enumerate(zip(files, sizes, strict=True)):
+ if size == 0:
continue
base = safe_name(name)
- # A second drop of the same screenshot must not overwrite the first —
+ # 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}"
@@ -187,15 +266,21 @@ def store(
candidate = target / f"{stamp}{suffix}-{counter}-{base}"
counter += 1
try:
- candidate.write_bytes(data)
+ _write(source, candidate)
+ written = candidate.stat().st_size
except OSError as exc:
+ # A half-written video is worse than none: the agent would open it.
+ candidate.unlink(missing_ok=True)
raise DropError(f"Could not save {base}: {exc}") from exc
+ if written == 0:
+ candidate.unlink(missing_ok=True)
+ continue
stored.append(
StoredDrop(
relative_path=candidate.relative_to(root).as_posix(),
absolute_path=str(candidate),
name=base,
- size=len(data),
+ size=written,
)
)
@@ -271,15 +356,18 @@ def within_workspace(path: str, workspace: str | Path) -> str | None:
__all__ = [
"DROP_DIRNAME",
"KEEP_SECONDS",
+ "DISK_RESERVE_BYTES",
+ "MAX_ANALYSIS_BYTES",
"MAX_FILES",
- "MAX_FILE_BYTES",
- "MAX_TOTAL_BYTES",
"DropError",
+ "DropSource",
"StoredDrop",
"dereference",
"drop_dir",
+ "read_for_analysis",
"reference",
"safe_name",
+ "size_of",
"store",
"sweep",
"within_workspace",
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index b21fdeaac6..018b9bdc66 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -898,9 +898,9 @@ async def attach_files(
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()))
+ # The spooled upload file itself, not its bytes: a screen recording streams
+ # to disk instead of being read into memory whole.
+ uploads = [(upload.filename or "file", upload.file) for upload in files or []]
try:
found = await chat_attachments.ingest(
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index faf91703a4..09ff1288e2 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -3745,8 +3745,10 @@ async def terminal_attach(
readable: list[tuple[str, bytes, str]] = []
# 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]] = []
+ # used as it lies; anything else is copied in. Sources stay paths or
+ # open files rather than bytes, so a screen recording streams to disk
+ # instead of being held in memory whole.
+ to_copy: list[tuple[str, drops.DropSource]] = []
for raw in (paths or "").splitlines():
candidate = raw.strip()
if not candidate:
@@ -3761,45 +3763,36 @@ async def terminal_attach(
# here to be described. A failure is not fatal: the reference
# still ships, the file simply goes undescribed.
try:
- body = await asyncio.to_thread((Path(session.folder) / inside).read_bytes)
+ body = await asyncio.to_thread(
+ drops.read_for_analysis, Path(session.folder) / inside
+ )
except OSError as exc:
log.info("Agentic IDE attach: %r not readable for analysis (%s)", inside, exc)
else:
- readable.append((Path(inside).name, body, reference))
+ if body is not None:
+ readable.append((Path(inside).name, body, reference))
continue
- # expanduser() is string/env work, not a filesystem call; the read
+ # expanduser() is string/env work, not a filesystem call; the stat
# 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)
+ if not await asyncio.to_thread(resolved.is_file):
+ log.info("Agentic IDE attach: unreadable dropped path %r", candidate)
continue
- to_copy.append((resolved.name, data))
+ to_copy.append((resolved.name, resolved))
- # 2. Bytes the browser handed over directly.
- total = 0
+ # 2. Bytes the browser handed over directly. The web server has already
+ # spooled each upload to a temporary file; it is copied from there.
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))
+ to_copy.append((upload.filename or "file", upload.file))
# ``store`` silently skips empty entries, so they are dropped HERE instead —
# that keeps ``stored[i]`` paired with ``to_copy[i]`` positionally. Pairing
# by name would be wrong: two files that sanitize to the same name are
# stored as two distinct files but would collapse into one key, and one drop
# would be referenced twice while the other went missing.
- to_copy = [(name, data) for name, data in to_copy if data]
+ sizes = await asyncio.to_thread(lambda: [drops.size_of(src) for _n, src in to_copy])
+ to_copy = [pair for pair, size in zip(to_copy, sizes, strict=True) if size != 0]
if to_copy:
try:
@@ -3807,12 +3800,15 @@ async def terminal_attach(
except drops.DropError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
copied = len(stored)
- for item, (_original, data) in zip(stored, to_copy, strict=True):
+ for item, (_original, source) in zip(stored, to_copy, strict=True):
reference = drops.reference(item.relative_path, agent=term.agent)
references.append(reference)
stored_names.append(item.name)
if analyze:
- readable.append((item.name, data, reference))
+ # A file too large to analyse still ships; it goes undescribed.
+ body = await asyncio.to_thread(drops.read_for_analysis, source)
+ if body is not None:
+ readable.append((item.name, body, reference))
if not references:
raise HTTPException(
diff --git a/tests/unit/agentic_ide/test_drops.py b/tests/unit/agentic_ide/test_drops.py
index 13d9bf7e43..bd6dfcb598 100644
--- a/tests/unit/agentic_ide/test_drops.py
+++ b/tests/unit/agentic_ide/test_drops.py
@@ -8,6 +8,7 @@ and none of this may show up in the user's ``git status``.
"""
from __future__ import annotations
+import io
from pathlib import Path
import pytest
@@ -75,13 +76,42 @@ def test_two_drops_of_the_same_name_keep_both(workspace: Path) -> None:
assert Path(second[0].absolute_path).read_bytes() == b"two"
-def test_oversized_drops_are_refused_with_a_readable_message(
- workspace: Path,
+def test_a_large_file_is_not_refused_for_its_size(workspace: Path) -> None:
+ """A screen recording is exactly what people drop on an agent."""
+ big = b"x" * (drops.MAX_ANALYSIS_BYTES + 1)
+ [item] = drops.store(workspace, [("recording.mp4", big)])
+ assert item.size == len(big)
+ assert (workspace / item.relative_path).stat().st_size == len(big)
+
+
+def test_path_and_file_sources_stream_to_disk(workspace: Path, tmp_path: Path) -> None:
+ """A dragged path or a spooled upload is copied, not read into memory."""
+ outside = tmp_path.parent / f"{tmp_path.name}-outside.mp4"
+ outside.write_bytes(b"from-disk")
+ upload = io.BytesIO(b"from-upload")
+ upload.seek(4) # a caller may hand over a file mid-read
+ stored = drops.store(workspace, [("a.mp4", outside), ("b.mp4", upload)])
+ assert [(workspace / s.relative_path).read_bytes() for s in stored] == [
+ b"from-disk",
+ b"from-upload",
+ ]
+ outside.unlink()
+
+
+def test_analysis_reads_only_files_small_enough_to_describe() -> None:
+ assert drops.read_for_analysis(b"abc") == b"abc"
+ assert drops.read_for_analysis(io.BytesIO(b"abcd"), limit=3) is None
+
+
+def test_a_drop_that_would_fill_the_disk_is_refused(
+ workspace: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- big = b"x" * (drops.MAX_FILE_BYTES + 1)
- with pytest.raises(drops.DropError, match="too large"):
- drops.store(workspace, [("huge.bin", big)])
+ monkeypatch.setattr(drops, "DISK_RESERVE_BYTES", 1 << 62)
+ with pytest.raises(drops.DropError, match="free disk space"):
+ drops.store(workspace, [("recording.mp4", b"x")])
+
+def test_bad_drops_are_refused_with_a_readable_message(workspace: Path) -> None:
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)])