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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): byte-exact file read, save, create, rename and delete for a code editor
rubenluetke10-beep7cc6feece2d7
diff --git a/jarvis/agentic_ide/file_editing.py b/jarvis/agentic_ide/file_editing.pynew file mode 100644index 0000000000..856d97e787--- /dev/null+++ b/jarvis/agentic_ide/file_editing.py@@ -0,0 +1,378 @@+"""Read and write workspace files for the Agentic IDE's code editor.++The explorer's preview path (``documents.extract``) normalises whitespace and is+fine for reading a document, but an editor must round-trip a file byte for byte:+indentation, line endings, a UTF-8 byte-order mark and a trailing newline all+survive a load and a save unchanged. Everything here therefore works on the raw+bytes and only decodes them at the edge.++Safety rules every function follows:++* **Contained.** A caller-supplied relative path is resolved (symlinks+ included) and refused unless it stays inside the workspace folder. Paths that+ do not exist yet (a new file, a rename target) are checked the same way.+* **Never inside ``.git``.** Editing git's own database through the editor+ corrupts a checkout; those paths are refused outright.+* **Optimistic concurrency.** A read returns a ``version`` (a content hash).+ A save names the version it was based on; if a coding agent changed the file+ in the meantime the save is refused with :class:`EditConflict` instead of+ silently overwriting the agent's work.+* **Atomic saves.** New bytes go to a temporary file in the same directory and+ replace the target with ``os.replace``, so a crash mid-save never leaves a+ half-written file. The original file mode is kept.+"""++from __future__ import annotations++import hashlib+import os+import shutil+import stat+import subprocess+import tempfile+from dataclasses import dataclass+from pathlib import Path, PurePosixPath++from loguru import logger++from jarvis.core.path_safety import UnsafePathError, contained_path+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++from .folders import _SKIP_DIRS++__all__ = [+ "MAX_EDITABLE_BYTES",+ "EditConflict",+ "EditError",+ "TextFile",+ "TrashUnavailable",+ "create_entry",+ "delete_entry",+ "list_files",+ "read_text_file",+ "rename_entry",+ "write_text_file",+]++#: Larger files open read-only in the explorer; a browser editor holding tens of+#: megabytes of text stalls the whole window.+MAX_EDITABLE_BYTES = 5 * 1024 * 1024++#: Bytes sniffed for a NUL to tell a binary file from text.+_BINARY_SNIFF_BYTES = 8192++_UTF8_BOM = b"\xef\xbb\xbf"++_ENCODINGS = ("utf-8", "utf-8-sig")+++class EditError(ValueError):+ """A request the editor cannot carry out; the message is safe to show."""+++class EditConflict(EditError):+ """The file changed on disk since the editor loaded it."""++ def __init__(self, message: str, current_version: str | None) -> None:+ super().__init__(message)+ self.current_version = current_version+++@dataclass(frozen=True, slots=True)+class TextFile:+ """One file as the editor sees it."""++ path: str+ text: str | None+ version: str+ size: int+ encoding: str+ eol: str+ binary: bool+ too_large: bool+++def _version_of(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _normalise_relative(path: str) -> str:+ """A POSIX relative path, or :class:`EditError` for anything else."""+ value = (path or "").strip().replace("\\", "/")+ if not value or any(ord(char) < 32 for char in value):+ raise EditError("Give a file path inside the workspace.")+ pure = PurePosixPath(value)+ if pure.is_absolute() or (len(value) > 1 and value[1] == ":"):+ raise EditError("Use a path relative to the workspace folder.")+ parts = [part for part in pure.parts if part not in ("", ".")]+ if not parts or any(part == ".." for part in parts):+ raise EditError("That path leaves the workspace folder.")+ if any(part.lower() == ".git" for part in parts):+ raise EditError("Files inside .git cannot be edited here.")+ return "/".join(parts)+++def _resolve(root: str | os.PathLike[str], path: str) -> tuple[str, Path]:+ """The normalised relative path and its contained absolute location."""+ relative = _normalise_relative(path)+ try:+ target = contained_path(root, relative)+ except UnsafePathError as exc:+ raise EditError("That path leaves the workspace folder.") from exc+ if target == Path(os.path.realpath(os.fspath(root))):+ raise EditError("Give a file path inside the workspace.")+ return relative, target+++def _resolve_entry(root: str | os.PathLike[str], path: str) -> tuple[str, Path]:+ """Like :func:`_resolve`, but the last component is taken literally.++ Rename and delete act on the directory entry itself: a symlink is renamed+ or removed, never the file it points at, and a case-only rename keeps the+ spelling the user typed (resolving would return the on-disk spelling).+ Only the parent folder is resolved and must stay inside the workspace.+ """+ relative = _normalise_relative(path)+ parent, _, name = relative.rpartition("/")+ try:+ folder = contained_path(root, parent or ".")+ except UnsafePathError as exc:+ raise EditError("That path leaves the workspace folder.") from exc+ return relative, folder / name+++def _detect_eol(text: str) -> str:+ crlf = text.count("\r\n")+ lf = text.count("\n") - crlf+ return "\r\n" if crlf > lf else "\n"+++def read_text_file(root: str | os.PathLike[str], path: str) -> TextFile:+ """Load one workspace file for editing, untouched."""+ relative, target = _resolve(root, path)+ if not target.is_file():+ raise EditError("That file does not exist.")+ size = target.stat().st_size+ if size > MAX_EDITABLE_BYTES:+ return TextFile(relative, None, "", size, "utf-8", "\n", False, True)+ data = target.read_bytes()+ version = _version_of(data)+ if b"\x00" in data[:_BINARY_SNIFF_BYTES]:+ return TextFile(relative, None, version, size, "utf-8", "\n", True, False)+ encoding = "utf-8-sig" if data.startswith(_UTF8_BOM) else "utf-8"+ try:+ text = data.decode(encoding)+ except UnicodeDecodeError:+ return TextFile(relative, None, version, size, encoding, "\n", True, False)+ return TextFile(relative, text, version, size, encoding, _detect_eol(text), False, False)+++def _atomic_write(target: Path, data: bytes) -> None:+ """Replace ``target`` with ``data`` in one step, keeping its file mode."""+ mode: int | None = None+ try:+ mode = stat.S_IMODE(target.stat().st_mode)+ except FileNotFoundError:+ mode = None+ handle, temp_name = tempfile.mkstemp(+ prefix=f".{target.name}.", suffix=".jarvis-save", dir=target.parent+ )+ temp = Path(temp_name)+ try:+ with os.fdopen(handle, "wb") as stream:+ stream.write(data)+ stream.flush()+ os.fsync(stream.fileno())+ if mode is not None:+ os.chmod(temp, mode)+ os.replace(temp, target)+ finally:+ # After a successful replace the temp name is gone; otherwise clean up.+ if temp.exists():+ try:+ temp.unlink()+ except OSError as exc:+ logger.warning("Could not remove editor temp file {}: {}", temp, exc)+++def write_text_file(+ root: str | os.PathLike[str],+ path: str,+ text: str,+ *,+ expected_version: str | None,+ encoding: str = "utf-8",+ create: bool = False,+) -> TextFile:+ """Save editor text over a workspace file.++ ``expected_version`` is the version the editor loaded. ``None`` means the+ editor believes the file is new: that is only allowed with ``create=True``+ and refused when a file already sits there.+ """+ relative, target = _resolve(root, path)+ if encoding not in _ENCODINGS:+ raise EditError("Only UTF-8 files can be saved from the editor.")+ data = text.encode("utf-8")+ if encoding == "utf-8-sig":+ data = _UTF8_BOM + data+ if len(data) > MAX_EDITABLE_BYTES:+ raise EditError("That file is too large to save from the editor.")+ if target.is_dir():+ raise EditError("A folder already has that name.")+ if target.exists():+ current = _version_of(target.read_bytes())+ if expected_version is None or expected_version != current:+ raise EditConflict("The file changed on disk since it was opened.", current)+ elif not create and expected_version is not None:+ raise EditConflict("The file was deleted since it was opened.", None)+ if not target.parent.is_dir():+ raise EditError("The folder for that file does not exist.")+ _atomic_write(target, data)+ return TextFile(+ relative,+ None,+ _version_of(data),+ len(data),+ encoding,+ _detect_eol(text),+ False,+ False,+ )+++def create_entry(root: str | os.PathLike[str], path: str, *, directory: bool) -> str:+ """Create an empty file or a folder (with missing parents)."""+ relative, target = _resolve(root, path)+ if target.exists():+ raise EditError("Something with that name already exists.")+ if directory:+ target.mkdir(parents=True)+ else:+ target.parent.mkdir(parents=True, exist_ok=True)+ # "x" fails instead of truncating if a file appears in between.+ with target.open("xb"):+ pass+ return relative+++def rename_entry(root: str | os.PathLike[str], source: str, destination: str) -> str:+ """Rename or move a file or folder inside the workspace."""+ _, source_path = _resolve_entry(root, source)+ relative, target = _resolve_entry(root, destination)+ if not (source_path.is_symlink() or source_path.exists()):+ raise EditError("That file or folder no longer exists.")+ # On a case-insensitive disk "readme.md" -> "README.md" names the same+ # entry; that is a rename, not a collision.+ same_entry = target.exists() and os.path.samefile(source_path, target)+ if (target.exists() or target.is_symlink()) and not same_entry:+ raise EditError("Something with that name already exists.")+ source_key = os.path.normcase(str(source_path))+ if not source_path.is_symlink() and source_path.is_dir():+ if os.path.normcase(os.path.realpath(target)).startswith(source_key + os.sep):+ raise EditError("A folder cannot be moved into itself.")+ if not target.parent.is_dir():+ raise EditError("The destination folder does not exist.")+ os.replace(source_path, target)+ return relative+++#: Quick Open lists at most this many paths; a home directory opened as a+#: workspace must not stall the editor.+MAX_LISTED_FILES = 50_000+_LIST_TIMEOUT_S = 15.0+++def _git_listed_files(base: Path) -> list[str] | None:+ """Tracked plus untracked-but-not-ignored files, or None outside a checkout."""+ try:+ result = subprocess.run(+ [+ "git",+ "-c",+ "core.quotePath=false",+ "ls-files",+ "-z",+ "--cached",+ "--others",+ "--exclude-standard",+ ],+ cwd=str(base),+ capture_output=True,+ timeout=_LIST_TIMEOUT_S,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return None+ if result.returncode != 0:+ return None+ paths = result.stdout.decode("utf-8", errors="replace").split("\0")+ # ls-files lists a file deleted in the working tree until it is staged.+ return sorted({path for path in paths if path and (base / path).is_file()})+++def _walked_files(base: Path) -> tuple[list[str], bool]:+ found: list[str] = []+ for current, dirs, files in os.walk(base):+ dirs[:] = sorted(name for name in dirs if name not in _SKIP_DIRS)+ rel_dir = Path(current).relative_to(base).as_posix()+ for name in sorted(files):+ found.append(name if rel_dir == "." else f"{rel_dir}/{name}")+ if len(found) >= MAX_LISTED_FILES:+ return found, True+ return found, False+++def list_files(root: str | os.PathLike[str]) -> tuple[list[str], bool]:+ """Every file path in the workspace for Quick Open, and whether it was cut."""+ base = Path(os.path.realpath(os.fspath(root)))+ listed = _git_listed_files(base)+ if listed is None:+ return _walked_files(base)+ return listed[:MAX_LISTED_FILES], len(listed) > MAX_LISTED_FILES+++class TrashUnavailable(EditError):+ """No system trash on this machine; only a permanent delete is possible."""+++def _move_to_trash(target: Path) -> bool:+ """Send ``target`` to the system trash; False when this machine has none.++ ``send2trash`` covers the Windows Recycle Bin, the macOS Trash and the+ freedesktop trash on Linux. It is optional: a headless server without it+ (or without a trash folder) gets an honest "permanent delete?" question+ from the editor instead of a silent permanent delete.+ """+ try:+ from send2trash import send2trash # type: ignore[import-not-found]+ except ImportError:+ return False+ try:+ send2trash(str(target))+ except OSError as exc:+ logger.info("Editor delete: system trash refused {}: {}", target.name, exc)+ return False+ return True+++def delete_entry(root: str | os.PathLike[str], path: str, *, permanent: bool = False) -> bool:+ """Delete a file or a folder with everything in it.++ Goes to the system trash unless ``permanent`` is set; returns whether it+ did. Raises :class:`TrashUnavailable` when there is no trash and the caller+ has not agreed to a permanent delete.+ """+ _, target = _resolve_entry(root, path)+ if not (target.is_symlink() or target.exists()):+ raise EditError("That file or folder no longer exists.")+ if not permanent:+ if _move_to_trash(target):+ return True+ raise TrashUnavailable("This computer has no trash to move it to.")+ if target.is_symlink() or target.is_file():+ target.unlink()+ else:+ shutil.rmtree(target)+ return Falsediff --git a/jarvis/agentic_ide/git_changes.py b/jarvis/agentic_ide/git_changes.pyindex b3d88c453c..7b0628101d 100644--- a/jarvis/agentic_ide/git_changes.py+++ b/jarvis/agentic_ide/git_changes.py@@ -297,6 +297,20 @@ def _parse_unified(text: str) -> tuple[list[DiffHunk], int, int, bool, bool]:return hunks, added, removed, False, truncated+def head_text(folder: str | Path, path: str) -> str | None:+ """One file's text as of the last commit; None when git has no copy of it."""+ rel = normalize_workspace_path(folder, path)+ root = Path(folder).expanduser()+ if not _has_head(root):+ return None+ # "./" makes git read the path relative to the workspace folder, which may+ # sit below the repository root.+ result = _git(["show", f"HEAD:./{rel}"], root)+ if result is None or result.returncode != 0:+ return None+ return result.stdout++def file_diff(folder: str | Path, path: str) -> FileDiff:"""How one file differs from the last commit; an untracked file is all new."""rel = normalize_workspace_path(folder, path)diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex e9f797d719..11f4c968a6 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -84,6 +84,7 @@ from jarvis.agentic_ide import (change_authors,drop_analysis,drops,+ file_editing,git_changes,layout_tree,native_picker,@@ -954,6 +955,57 @@ class WorkspaceFilePreviewResponse(BaseModel):hex_preview: str | None = None+class WorkspaceTextFileResponse(BaseModel):+ """One workspace file loaded byte-exact for the code editor."""++ workspace_id: str+ path: str+ text: str | None = Field(+ default=None, description="Exact file text; null when binary or too large."+ )+ version: str = Field(description="Content hash; send it back on save to detect conflicts.")+ size: int+ encoding: Literal["utf-8", "utf-8-sig"]+ eol: Literal["\n", "\r\n"]+ binary: bool = False+ too_large: bool = False+++class SaveWorkspaceFileRequest(BaseModel):+ """Editor text to write over one workspace file."""++ path: str = Field(min_length=1, max_length=4096)+ text: str+ expected_version: str | None = Field(+ default=None,+ max_length=128,+ description="Version the editor loaded; null only when creating a new file.",+ )+ encoding: Literal["utf-8", "utf-8-sig"] = "utf-8"+ create: bool = False+++class WorkspaceEntryRequest(BaseModel):+ """Create one file or folder inside a workspace."""++ path: str = Field(min_length=1, max_length=4096)+ kind: Literal["file", "directory"] = "file"+++class MoveWorkspaceEntryRequest(BaseModel):+ """Rename or move one file or folder inside a workspace."""++ source: str = Field(min_length=1, max_length=4096)+ destination: str = Field(min_length=1, max_length=4096)+++class DeleteWorkspaceEntryRequest(BaseModel):+ """Delete one file or folder; it goes to the system trash unless permanent."""++ path: str = Field(min_length=1, max_length=4096)+ permanent: bool = False++class SearchResponse(BaseModel):query: strentries: list[FolderItem]@@ -1910,6 +1962,171 @@ async def get_workspace_file_preview(workspace_id: str, path: str) -> WorkspaceF)+def _workspace_folder(workspace_id: str) -> str:+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="That workspace is not open.")+ return str(session.folder)+++def _text_file_response(workspace_id: str, loaded: file_editing.TextFile) -> dict[str, object]:+ return {"workspace_id": workspace_id, **asdict(loaded)}+++ "/workspaces/{workspace_id}/text-file",+ response_model=WorkspaceTextFileResponse,+ summary="Load one workspace file for the code editor",+)+async def get_workspace_text_file(workspace_id: str, path: str) -> dict[str, object]:+ """The file's exact text plus the version a later save must name.++ Unlike ``/file-preview`` nothing is normalised: indentation, line endings+ and a byte-order mark come back as they are on disk.+ """+ folder = _workspace_folder(workspace_id)+ try:+ loaded = await asyncio.to_thread(file_editing.read_text_file, folder, path)+ except file_editing.EditError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except OSError as exc:+ raise HTTPException(status_code=404, detail="That workspace file is unavailable.") from exc+ return _text_file_response(workspace_id, loaded)+++ "/workspaces/{workspace_id}/text-file",+ response_model=WorkspaceTextFileResponse,+ summary="Save editor text over one workspace file",+)+async def save_workspace_text_file(+ workspace_id: str, req: SaveWorkspaceFileRequest+) -> dict[str, object]:+ """Write the editor's text atomically.++ Answers 409 with ``current_version`` when the file changed on disk since+ the editor loaded it, so an agent's edit is never silently overwritten.+ """+ folder = _workspace_folder(workspace_id)+ try:+ saved = await asyncio.to_thread(+ file_editing.write_text_file,+ folder,+ req.path,+ req.text,+ expected_version=req.expected_version,+ encoding=req.encoding,+ create=req.create,+ )+ except file_editing.EditConflict as exc:+ raise HTTPException(+ status_code=409,+ detail={"message": str(exc), "current_version": exc.current_version},+ ) from exc+ except file_editing.EditError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except OSError as exc:+ log.warning("Agentic IDE editor: save failed for %s: %s", req.path, exc)+ raise HTTPException(status_code=500, detail="The file could not be saved.") from exc+ return _text_file_response(workspace_id, saved)+++ "/workspaces/{workspace_id}/head-text",+ summary="A workspace file's text at the last commit",+)+async def get_workspace_head_text(workspace_id: str, path: str) -> dict[str, object]:+ """The committed text the editor's diff view compares against.++ ``text`` is null for a file git does not know (new, or not a repository).+ """+ folder = _workspace_folder(workspace_id)+ try:+ text = await asyncio.to_thread(git_changes.head_text, folder, path)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"workspace_id": workspace_id, "path": path.replace("\\", "/"), "text": text}+++ "/workspaces/{workspace_id}/file-list",+ summary="Every file path in a workspace, for Quick Open",+)+async def get_workspace_file_list(workspace_id: str) -> dict[str, object]:+ """Tracked and untracked (not ignored) files; a bounded walk outside git."""+ folder = _workspace_folder(workspace_id)+ try:+ paths, truncated = await asyncio.to_thread(file_editing.list_files, folder)+ except OSError as exc:+ raise HTTPException(status_code=404, detail="Workspace folder not found.") from exc+ return {"workspace_id": workspace_id, "paths": paths, "truncated": truncated}+++ "/workspaces/{workspace_id}/entries",+ summary="Create a file or folder in a workspace",+)+async def create_workspace_entry(+ workspace_id: str, req: WorkspaceEntryRequest+) -> dict[str, object]:+ folder = _workspace_folder(workspace_id)+ try:+ created = await asyncio.to_thread(+ file_editing.create_entry, folder, req.path, directory=req.kind == "directory"+ )+ except file_editing.EditError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except OSError as exc:+ log.warning("Agentic IDE editor: create failed for %s: %s", req.path, exc)+ raise HTTPException(status_code=500, detail="It could not be created.") from exc+ return {"workspace_id": workspace_id, "path": created, "kind": req.kind}+++ "/workspaces/{workspace_id}/entries/move",+ summary="Rename or move a file or folder in a workspace",+)+async def move_workspace_entry(+ workspace_id: str, req: MoveWorkspaceEntryRequest+) -> dict[str, object]:+ folder = _workspace_folder(workspace_id)+ try:+ moved = await asyncio.to_thread(+ file_editing.rename_entry, folder, req.source, req.destination+ )+ except file_editing.EditError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except OSError as exc:+ log.warning("Agentic IDE editor: rename failed for %s: %s", req.source, exc)+ raise HTTPException(status_code=500, detail="It could not be renamed.") from exc+ return {"workspace_id": workspace_id, "path": moved}+++ "/workspaces/{workspace_id}/entries/delete",+ summary="Delete a file or folder in a workspace",+)+async def delete_workspace_entry(+ workspace_id: str, req: DeleteWorkspaceEntryRequest+) -> dict[str, object]:+ """Move to the system trash; 409 ``trash_unavailable`` asks for a permanent delete."""+ folder = _workspace_folder(workspace_id)+ try:+ trashed = await asyncio.to_thread(+ file_editing.delete_entry, folder, req.path, permanent=req.permanent+ )+ except file_editing.TrashUnavailable as exc:+ raise HTTPException(+ status_code=409, detail={"message": str(exc), "trash_unavailable": True}+ ) from exc+ except file_editing.EditError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except OSError as exc:+ log.warning("Agentic IDE editor: delete failed for %s: %s", req.path, exc)+ raise HTTPException(status_code=500, detail="It could not be deleted.") from exc+ return {"workspace_id": workspace_id, "path": req.path, "trashed": trashed}++@router.post("/terminal-target/open",summary="Open a file or folder linked in an Agentic-IDE terminal",diff --git a/tests/unit/agentic_ide/test_file_editing.py b/tests/unit/agentic_ide/test_file_editing.pynew file mode 100644index 0000000000..43baa70591--- /dev/null+++ b/tests/unit/agentic_ide/test_file_editing.py@@ -0,0 +1,258 @@+"""The code editor round-trips workspace files byte for byte and never clobbers an agent's edit."""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.agentic_ide import file_editing+from jarvis.agentic_ide.file_editing import (+ EditConflict,+ EditError,+ TrashUnavailable,+ create_entry,+ delete_entry,+ list_files,+ read_text_file,+ rename_entry,+ write_text_file,+)+from jarvis.ui.web import agentic_ide_routes as routes+++def test_read_keeps_indentation_crlf_and_bom(tmp_path: Path) -> None:+ raw = b"\xef\xbb\xbfdef f():\r\n\t\treturn 1\r\n\r\n\r\n"+ (tmp_path / "a.py").write_bytes(raw)++ loaded = read_text_file(tmp_path, "a.py")++ assert loaded.text == "def f():\r\n\t\treturn 1\r\n\r\n\r\n"+ assert loaded.encoding == "utf-8-sig"+ assert loaded.eol == "\r\n"+ assert not loaded.binary+++def test_save_round_trips_bytes_and_returns_new_version(tmp_path: Path) -> None:+ raw = b"\xef\xbb\xbfline one\r\nline two\r\n"+ (tmp_path / "a.txt").write_bytes(raw)+ loaded = read_text_file(tmp_path, "a.txt")++ saved = write_text_file(+ tmp_path,+ "a.txt",+ loaded.text + "line three\r\n",+ expected_version=loaded.version,+ encoding=loaded.encoding,+ )++ assert (tmp_path / "a.txt").read_bytes() == raw + b"line three\r\n"+ assert saved.version == read_text_file(tmp_path, "a.txt").version+ assert saved.version != loaded.version+++def test_save_refuses_when_the_file_changed_on_disk(tmp_path: Path) -> None:+ (tmp_path / "a.txt").write_text("mine\n", encoding="utf-8")+ loaded = read_text_file(tmp_path, "a.txt")+ (tmp_path / "a.txt").write_text("the agent's\n", encoding="utf-8")++ with pytest.raises(EditConflict) as caught:+ write_text_file(tmp_path, "a.txt", "mine, edited\n", expected_version=loaded.version)++ assert caught.value.current_version == read_text_file(tmp_path, "a.txt").version+ assert (tmp_path / "a.txt").read_text(encoding="utf-8") == "the agent's\n"+++def test_save_without_version_never_overwrites_an_existing_file(tmp_path: Path) -> None:+ (tmp_path / "a.txt").write_text("keep\n", encoding="utf-8")++ with pytest.raises(EditConflict):+ write_text_file(tmp_path, "a.txt", "gone\n", expected_version=None, create=True)++ created = write_text_file(tmp_path, "b.txt", "new\n", expected_version=None, create=True)+ assert created.path == "b.txt"+ assert (tmp_path / "b.txt").read_text(encoding="utf-8") == "new\n"+++def test_binary_and_large_files_are_not_loaded_as_text(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ (tmp_path / "x.bin").write_bytes(b"\x89PNG\x00\x00data")+ (tmp_path / "big.txt").write_text("a" * 64, encoding="utf-8")+ monkeypatch.setattr(file_editing, "MAX_EDITABLE_BYTES", 32)++ assert read_text_file(tmp_path, "x.bin").binary is True+ assert read_text_file(tmp_path, "x.bin").text is None+ big = read_text_file(tmp_path, "big.txt")+ assert big.too_large is True and big.text is None++[email protected]("path", ["../outside.txt", "/etc/passwd", "C:/x.txt", ".git/config", ""])+def test_paths_outside_the_workspace_or_inside_git_are_refused(tmp_path: Path, path: str) -> None:+ with pytest.raises(EditError):+ write_text_file(tmp_path, path, "x", expected_version=None, create=True)+++def test_symlink_escape_is_refused(tmp_path: Path) -> None:+ root = tmp_path / "root"+ root.mkdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ try:+ os.symlink(outside, root / "link", target_is_directory=True)+ except (OSError, NotImplementedError):+ pytest.skip("this machine cannot create symlinks")++ with pytest.raises(EditError):+ create_entry(root, "link/evil.txt", directory=False)+ assert not (outside / "evil.txt").exists()+++def test_create_rename_and_permanent_delete(tmp_path: Path) -> None:+ assert create_entry(tmp_path, "src/pkg", directory=True) == "src/pkg"+ assert create_entry(tmp_path, "src/pkg/mod.py", directory=False) == "src/pkg/mod.py"+ with pytest.raises(EditError):+ create_entry(tmp_path, "src/pkg/mod.py", directory=False)++ assert rename_entry(tmp_path, "src/pkg/mod.py", "src/pkg/main.py") == "src/pkg/main.py"+ assert (tmp_path / "src/pkg/main.py").is_file()+ with pytest.raises(EditError):+ rename_entry(tmp_path, "src", "src/pkg/inner")++ assert delete_entry(tmp_path, "src", permanent=True) is False+ assert not (tmp_path / "src").exists()+++def test_delete_without_trash_asks_for_a_permanent_delete(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ (tmp_path / "a.txt").write_text("x", encoding="utf-8")+ monkeypatch.setattr(file_editing, "_move_to_trash", lambda target: False)++ with pytest.raises(TrashUnavailable):+ delete_entry(tmp_path, "a.txt")+ assert (tmp_path / "a.txt").exists()+++def test_case_only_rename_is_allowed(tmp_path: Path) -> None:+ (tmp_path / "readme.md").write_text("x", encoding="utf-8")++ assert rename_entry(tmp_path, "readme.md", "README.md") == "README.md"+ assert [entry.name for entry in tmp_path.iterdir()] == ["README.md"]+++def test_list_files_walks_outside_git_and_skips_dependency_folders(tmp_path: Path) -> None:+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "a.py").write_text("", encoding="utf-8")+ (tmp_path / "node_modules").mkdir()+ (tmp_path / "node_modules" / "dep.js").write_text("", encoding="utf-8")++ paths, truncated = list_files(tmp_path)++ assert "src/a.py" in paths+ assert not any(path.startswith("node_modules/") for path in paths)+ assert truncated is False+++def test_list_files_in_git_honours_gitignore(tmp_path: Path) -> None:+ try:+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True, capture_output=True)+ except (FileNotFoundError, subprocess.CalledProcessError):+ pytest.skip("git is not available")+ (tmp_path / ".gitignore").write_text("build/\n", encoding="utf-8")+ (tmp_path / "build").mkdir()+ (tmp_path / "build" / "out.js").write_text("", encoding="utf-8")+ (tmp_path / "main.py").write_text("", encoding="utf-8")++ paths, _ = list_files(tmp_path)++ assert paths == [".gitignore", "main.py"]+++def workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ root = tmp_path / "project"+ root.mkdir()+ session = SimpleNamespace(folder=str(root))+ registry = SimpleNamespace(+ get=lambda workspace_id: session if workspace_id == "workspace-1" else None+ )+ monkeypatch.setattr(routes, "get_registry", lambda: registry)+ return root+++async def test_routes_load_save_and_report_conflicts(workspace: Path) -> None:+ (workspace / "main.py").write_bytes(b"x = 1\r\n")++ loaded = await routes.get_workspace_text_file("workspace-1", "main.py")+ assert loaded["text"] == "x = 1\r\n"+ assert loaded["eol"] == "\r\n"+ routes.WorkspaceTextFileResponse(**loaded)++ saved = await routes.save_workspace_text_file(+ "workspace-1",+ routes.SaveWorkspaceFileRequest(+ path="main.py", text="x = 2\r\n", expected_version=loaded["version"]+ ),+ )+ assert (workspace / "main.py").read_bytes() == b"x = 2\r\n"++ with pytest.raises(HTTPException) as caught:+ await routes.save_workspace_text_file(+ "workspace-1",+ routes.SaveWorkspaceFileRequest(+ path="main.py", text="stale\n", expected_version=loaded["version"]+ ),+ )+ assert caught.value.status_code == 409+ assert caught.value.detail["current_version"] == saved["version"]+++async def test_routes_reject_unknown_workspace_and_escapes(workspace: Path) -> None:+ with pytest.raises(HTTPException) as unknown:+ await routes.get_workspace_text_file("nope", "main.py")+ assert unknown.value.status_code == 404++ with pytest.raises(HTTPException) as escape:+ await routes.create_workspace_entry(+ "workspace-1", routes.WorkspaceEntryRequest(path="../evil.txt")+ )+ assert escape.value.status_code == 409+ assert not (workspace.parent / "evil.txt").exists()+++async def test_delete_route_reports_missing_trash(+ workspace: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ (workspace / "a.txt").write_text("x", encoding="utf-8")+ monkeypatch.setattr(file_editing, "_move_to_trash", lambda target: False)++ with pytest.raises(HTTPException) as caught:+ await routes.delete_workspace_entry(+ "workspace-1", routes.DeleteWorkspaceEntryRequest(path="a.txt")+ )+ assert caught.value.status_code == 409+ assert caught.value.detail["trash_unavailable"] is True++ answer = await routes.delete_workspace_entry(+ "workspace-1", routes.DeleteWorkspaceEntryRequest(path="a.txt", permanent=True)+ )+ assert answer["trashed"] is False+ assert not (workspace / "a.txt").exists()++[email protected](sys.platform == "win32", reason="POSIX file modes")+def test_save_keeps_the_file_mode(tmp_path: Path) -> None:+ script = tmp_path / "run.sh"+ script.write_text("echo hi\n", encoding="utf-8")+ script.chmod(0o755)+ loaded = read_text_file(tmp_path, "run.sh")++ write_text_file(tmp_path, "run.sh", "echo bye\n", expected_version=loaded.version)++ assert script.stat().st_mode & 0o777 == 0o755