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): search and replace in all workspace files

rubenluetke10-beep38e87cc9a439
diff --git a/jarvis/agentic_ide/file_search.py b/jarvis/agentic_ide/file_search.py
new file mode 100644
index 0000000000..03e09132d7
--- /dev/null
+++ b/jarvis/agentic_ide/file_search.py
@@ -0,0 +1,238 @@
+"""Search (and replace) text across a workspace for the code editor.
+
+The editor's "Search" tab asks for every line in the workspace that matches a
+query: plain text or a regular expression, optionally case-sensitive or whole
+word, narrowed by include/exclude globs. Replace runs the same match over a
+chosen set of files and writes them atomically.
+
+Bounded on purpose. A workspace may be a home directory: the file list comes
+from :func:`file_editing.list_files` (git's view when there is one, so ignored
+build output is skipped), large and binary files are skipped, and both the
+number of matches and the time spent are capped. A capped answer says so
+(``truncated``) instead of running on.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import os
+import re
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from .file_editing import (
+ EditConflict,
+ EditError,
+ list_files,
+ read_text_file,
+ write_text_file,
+)
+
+__all__ = [
+ "MAX_MATCHES",
+ "SearchOptions",
+ "replace_in_files",
+ "search_workspace",
+]
+
+#: Matches returned for one query; enough to scan, few enough to render.
+MAX_MATCHES = 2000
+#: Files bigger than this are not searched (minified bundles, data dumps).
+MAX_SEARCH_BYTES = 1024 * 1024
+#: Wall-clock budget for one search.
+SEARCH_BUDGET_S = 8.0
+_PREVIEW_CHARS = 240
+_BINARY_SNIFF_BYTES = 8192
+
+
+@dataclass(frozen=True, slots=True)
+class SearchOptions:
+ query: str
+ regex: bool = False
+ case_sensitive: bool = False
+ whole_word: bool = False
+ include: str = ""
+ exclude: str = ""
+
+
+@dataclass(slots=True)
+class _FileHits:
+ path: str
+ matches: list[dict[str, object]] = field(default_factory=list)
+
+
+def _compile(options: SearchOptions) -> re.Pattern[str]:
+ if not options.query:
+ raise EditError("Type something to search for.")
+ pattern = options.query if options.regex else re.escape(options.query)
+ if options.whole_word:
+ pattern = rf"\b(?:{pattern})\b"
+ try:
+ return re.compile(pattern, 0 if options.case_sensitive else re.IGNORECASE)
+ except re.error as exc:
+ raise EditError(f"That regular expression is not valid: {exc}") from exc
+
+
+def _globs(raw: str) -> list[str]:
+ return [part.strip().replace("\\", "/") for part in raw.split(",") if part.strip()]
+
+
+def _glob_match(path: str, pattern: str) -> bool:
+ """``*.py``, ``src/**``, ``docs`` — matched like the editor's search box."""
+ name = path.rsplit("/", 1)[-1]
+ if fnmatch.fnmatch(path, pattern) or ("/" not in pattern and fnmatch.fnmatch(name, pattern)):
+ return True
+ # A folder name or folder glob covers everything below it.
+ folder = pattern.rstrip("/").removesuffix("/**")
+ return path.startswith(f"{folder}/") or fnmatch.fnmatch(path, f"{folder}/*")
+
+
+def _selected(path: str, include: list[str], exclude: list[str]) -> bool:
+ if include and not any(_glob_match(path, pattern) for pattern in include):
+ return False
+ return not any(_glob_match(path, pattern) for pattern in exclude)
+
+
+def _read_searchable(base: Path, path: str) -> str | None:
+ target = base / path
+ # A symlink that leads out of the workspace is not searched: the search
+ # must not become a way to read files the editor itself refuses to open.
+ real = os.path.realpath(target)
+ if not real.startswith(f"{base}{os.sep}"):
+ return None
+ try:
+ if target.stat().st_size > MAX_SEARCH_BYTES:
+ return None
+ data = target.read_bytes()
+ except OSError:
+ return None
+ if b"\x00" in data[:_BINARY_SNIFF_BYTES]:
+ return None
+ return data.decode("utf-8", errors="replace")
+
+
+def _preview(line: str, start: int, end: int) -> tuple[str, int]:
+ """The line around a match, trimmed; returns the text and the match offset in it."""
+ stripped = line.rstrip("\r\n")
+ if len(stripped) <= _PREVIEW_CHARS:
+ return stripped, start
+ left = max(0, start - 60)
+ cut = stripped[left : left + _PREVIEW_CHARS]
+ return ("…" if left else "") + cut, start - left + (1 if left else 0)
+
+
+def search_workspace(root: str | os.PathLike[str], options: SearchOptions) -> dict[str, object]:
+ """Every matching line in the workspace, grouped by file."""
+ pattern = _compile(options)
+ include, exclude = _globs(options.include), _globs(options.exclude)
+ base = Path(os.path.realpath(os.fspath(root)))
+ paths, listing_cut = list_files(base)
+ deadline = time.monotonic() + SEARCH_BUDGET_S
+ results: list[_FileHits] = []
+ total = 0
+ searched = 0
+ truncated = listing_cut
+ for path in paths:
+ if not _selected(path, include, exclude):
+ continue
+ if time.monotonic() > deadline:
+ truncated = True
+ break
+ text = _read_searchable(base, path)
+ if text is None:
+ continue
+ searched += 1
+ hits: _FileHits | None = None
+ for number, line in enumerate(text.splitlines(keepends=True), start=1):
+ for match in pattern.finditer(line):
+ if match.end() == match.start():
+ continue # an empty match marks nothing
+ if hits is None:
+ hits = _FileHits(path)
+ results.append(hits)
+ preview, offset = _preview(line, match.start(), match.end())
+ hits.matches.append(
+ {
+ "line": number,
+ "column": match.start() + 1,
+ "length": match.end() - match.start(),
+ "preview": preview,
+ "preview_start": offset,
+ }
+ )
+ total += 1
+ if total >= MAX_MATCHES:
+ truncated = True
+ break
+ if total >= MAX_MATCHES:
+ break
+ if total >= MAX_MATCHES:
+ break
+ return {
+ "results": [{"path": hits.path, "matches": hits.matches} for hits in results],
+ "match_count": total,
+ "file_count": len(results),
+ "searched_files": searched,
+ "truncated": truncated,
+ }
+
+
+def _template(replacement: str, *, regex: bool) -> str:
+ r"""The replacement as :func:`re.sub` reads it.
+
+ Plain text is taken literally. A regex replacement accepts the editor's
+ ``$1`` / ``$&`` group syntax (``$$`` for a dollar) besides Python's ``\1``.
+ """
+ if not regex:
+ return replacement.replace("\\", "\\\\")
+
+ def group(match: re.Match[str]) -> str:
+ ref = match.group(1)
+ if ref == "$":
+ return "$"
+ return r"\g<0>" if ref == "&" else rf"\g<{ref}>"
+
+ return re.sub(r"\$(\$|&|\d+)", group, replacement)
+
+
+def replace_in_files(
+ root: str | os.PathLike[str],
+ options: SearchOptions,
+ replacement: str,
+ paths: list[str],
+) -> dict[str, object]:
+ """Replace every match in the given files; each file is written atomically.
+
+ A file that cannot be read as text, or that changed between reading and
+ writing, is reported back instead of being written.
+ """
+ pattern = _compile(options)
+ replaced_files: list[str] = []
+ skipped: list[dict[str, str]] = []
+ total = 0
+ for path in paths:
+ try:
+ loaded = read_text_file(root, path)
+ if loaded.text is None:
+ skipped.append({"path": path, "reason": "not a text file"})
+ continue
+ new_text, count = pattern.subn(_template(replacement, regex=options.regex), loaded.text)
+ if count == 0:
+ continue
+ write_text_file(
+ root,
+ loaded.path,
+ new_text,
+ expected_version=loaded.version,
+ encoding=loaded.encoding,
+ )
+ except EditConflict:
+ skipped.append({"path": path, "reason": "changed while replacing"})
+ continue
+ except (EditError, re.error) as exc:
+ skipped.append({"path": path, "reason": str(exc)})
+ continue
+ replaced_files.append(loaded.path)
+ total += count
+ return {"replaced_files": replaced_files, "replacements": total, "skipped": skipped}
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index dc9d7f1739..5888dac476 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -86,6 +86,7 @@ from jarvis.agentic_ide import (
drops,
editor_backups,
file_editing,
+ file_search,
git_changes,
layout_tree,
native_picker,
@@ -1022,6 +1023,17 @@ class EditorBackupRequest(BaseModel):
encoding: str = Field(default="utf-8", max_length=40)
+class ReplaceInFilesRequest(BaseModel):
+ """Replace every match of a search in the given files."""
+
+ query: str = Field(min_length=1, max_length=1000)
+ replacement: str = Field(max_length=10_000)
+ regex: bool = False
+ case_sensitive: bool = False
+ whole_word: bool = False
+ paths: list[str] = Field(min_length=1, max_length=5000)
+
+
class DeleteWorkspaceEntryRequest(BaseModel):
"""Delete one file or folder; it goes to the system trash unless permanent."""
@@ -2149,6 +2161,60 @@ async def move_workspace_entry(
return {"workspace_id": workspace_id, "path": moved}
+ "/workspaces/{workspace_id}/search",
+ summary="Search the text of every file in a workspace",
+)
+async def search_workspace_files(
+ workspace_id: str,
+ q: Annotated[str, Query(min_length=1, max_length=1000)],
+ regex: bool = False,
+ case: bool = False,
+ word: bool = False,
+ include: Annotated[str, Query(max_length=1000)] = "",
+ exclude: Annotated[str, Query(max_length=1000)] = "",
+) -> dict[str, object]:
+ """Matching lines grouped by file; bounded in matches and time (``truncated``)."""
+ folder = _workspace_folder(workspace_id)
+ options = file_search.SearchOptions(
+ query=q,
+ regex=regex,
+ case_sensitive=case,
+ whole_word=word,
+ include=include,
+ exclude=exclude,
+ )
+ try:
+ answer = await asyncio.to_thread(file_search.search_workspace, folder, options)
+ except file_editing.EditError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"workspace_id": workspace_id, **answer}
+
+
+ "/workspaces/{workspace_id}/search/replace",
+ summary="Replace a search's matches in chosen files",
+)
+async def replace_in_workspace_files(
+ workspace_id: str, req: ReplaceInFilesRequest
+) -> dict[str, object]:
+ """Each file is rewritten atomically; files that changed meanwhile are skipped."""
+ folder = _workspace_folder(workspace_id)
+ options = file_search.SearchOptions(
+ query=req.query,
+ regex=req.regex,
+ case_sensitive=req.case_sensitive,
+ whole_word=req.whole_word,
+ )
+ try:
+ answer = await asyncio.to_thread(
+ file_search.replace_in_files, folder, options, req.replacement, req.paths
+ )
+ except file_editing.EditError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"workspace_id": workspace_id, **answer}
+
+
@router.get(
"/workspaces/{workspace_id}/editor-state",
summary="The code editor's open tabs and unsaved text to restore",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
index b4dd14577d..fc9f8aa400 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
@@ -28,6 +28,8 @@ import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components
import { checkDisk, discardFile, languageName, revertFile, saveAll, saveFile } from "./editorModels";
import { QuickOpen } from "./QuickOpen";
import { restoreWorkspace } from "./editorPersistence";
+import { SEARCH_FOCUS_EVENT } from "@/components/agentic/sidePanel/search/SearchPanel";
+import { useIdeSidePanelStore } from "@/store/ideSidePanel";
import { renderKindOf } from "./fileKinds";
const EditorSurface = lazy(() => import("./EditorSurface"));
@@ -141,6 +143,14 @@ export function CodeEditorStage({
state.setQuickOpen(true);
return;
}
+ if (key === "f" && event.shiftKey) {
+ // Search in all files lives in the side panel, like the explorer.
+ event.preventDefault();
+ event.stopPropagation();
+ useIdeSidePanelStore.getState().openTab("search");
+ window.setTimeout(() => window.dispatchEvent(new Event(SEARCH_FOCUS_EVENT)), 0);
+ return;
+ }
const host = stage.current;
if (!state.visible || !host) return;
if (target && target !== document.body && !host.contains(target)) return;
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
index a77137fbca..9dabc62312 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
@@ -158,7 +158,11 @@ export default function EditorSurface({
if (!editor || editor.getModel() !== modelOf(tab.fileKey)) return;
handledReveal.current = reveal.nonce;
const position = { lineNumber: reveal.line, column: reveal.column };
- editor.setPosition(position);
+ if (reveal.length > 0) {
+ editor.setSelection(new monaco.Selection(reveal.line, reveal.column, reveal.line, reveal.column + reveal.length));
+ } else {
+ editor.setPosition(position);
+ }
editor.revealPositionInCenter(position);
editor.focus();
}, [reveal, ready, tab.fileKey, tab.mode, tab.key]);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
index f722bd4c03..bd840d7912 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
@@ -187,3 +187,67 @@ export async function putEditorBackup(
export async function deleteEditorBackup(workspaceId: string, path: string): Promise<void> {
await send(`${base(workspaceId)}/editor-state/backup?${query(path)}`, { method: "DELETE" });
}
+
+export interface SearchMatch {
+ line: number;
+ column: number;
+ length: number;
+ /** The line around the match, possibly trimmed. */
+ preview: string;
+ /** Where the match starts inside `preview`. */
+ preview_start: number;
+}
+
+export interface SearchResult {
+ results: { path: string; matches: SearchMatch[] }[];
+ match_count: number;
+ file_count: number;
+ searched_files: number;
+ truncated: boolean;
+}
+
+export interface SearchQuery {
+ query: string;
+ regex: boolean;
+ caseSensitive: boolean;
+ wholeWord: boolean;
+ include: string;
+ exclude: string;
+}
+
+export function searchWorkspace(workspaceId: string, search: SearchQuery, signal?: AbortSignal): Promise<SearchResult> {
+ const params = new URLSearchParams({
+ q: search.query,
+ regex: String(search.regex),
+ case: String(search.caseSensitive),
+ word: String(search.wholeWord),
+ include: search.include,
+ exclude: search.exclude,
+ });
+ return send<SearchResult>(`${base(workspaceId)}/search?${params.toString()}`, { signal });
+}
+
+export interface ReplaceResult {
+ replaced_files: string[];
+ replacements: number;
+ skipped: { path: string; reason: string }[];
+}
+
+export function replaceInFiles(
+ workspaceId: string,
+ search: SearchQuery,
+ replacement: string,
+ paths: string[],
+): Promise<ReplaceResult> {
+ return send<ReplaceResult>(
+ `${base(workspaceId)}/search/replace`,
+ json("POST", {
+ query: search.query,
+ replacement,
+ regex: search.regex,
+ case_sensitive: search.caseSensitive,
+ whole_word: search.wholeWord,
+ paths,
+ }),
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.test.tsx
new file mode 100644
index 0000000000..eb62e32d14
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.test.tsx
@@ -0,0 +1,80 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useCodeEditorStore } from "@/store/codeEditor";
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+import { SearchPanel } from "./SearchPanel";
+
+const RESULT = {
+ results: [
+ {
+ path: "src/app.py",
+ matches: [{ line: 2, column: 12, length: 5, preview: " return 'Hello'", preview_start: 12 }],
+ },
+ ],
+ match_count: 1,
+ file_count: 1,
+ searched_files: 3,
+ truncated: false,
+};
+
+const calls: { url: string; body: string }[] = [];
+
+beforeEach(() => {
+ calls.length = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ calls.push({ url, body: String(init?.body ?? "") });
+ const body = url.includes("/search/replace")
+ ? { replaced_files: ["src/app.py"], replacements: 1, skipped: [] }
+ : RESULT;
+ return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
+ }),
+ );
+ useEventStore.setState({ activeSection: "agentic-ide" });
+ useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });
+ useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, visible: false, reveal: null, closed: [] });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("SearchPanel", () => {
+ it("searches with the chosen options and opens a match selected in the editor", async () => {
+ render(<SearchPanel />);
+ fireEvent.change(screen.getByTestId("ide-search-input"), { target: { value: "hello" } });
+ fireEvent.click(screen.getByLabelText("Match case"));
+
+ const match = await screen.findByTestId("ide-search-match");
+ const url = calls.find((call) => call.url.includes("/search?"))!.url;
+ expect(url).toContain("q=hello");
+ expect(url).toContain("case=true");
+ expect(match.querySelector("mark")?.textContent).toBe("Hello");
+
+ fireEvent.click(match);
+ expect(useCodeEditorStore.getState().tabs).toMatchObject([{ path: "src/app.py" }]);
+ expect(useCodeEditorStore.getState().reveal).toMatchObject({ line: 2, column: 12, length: 5 });
+ });
+
+ it("replaces only after a confirming second click, and leaves unsaved files out", async () => {
+ useCodeEditorStore.getState().openFile("w1", "src/other.py");
+ render(<SearchPanel />);
+ fireEvent.change(screen.getByTestId("ide-search-input"), { target: { value: "hello" } });
+ await screen.findByTestId("ide-search-match");
+ fireEvent.click(screen.getByLabelText("Show or hide replace"));
+ fireEvent.change(screen.getByTestId("ide-search-replace"), { target: { value: "Hi" } });
+
+ fireEvent.click(screen.getByTestId("ide-search-replace-all"));
+ expect(calls.some((call) => call.url.includes("/search/replace"))).toBe(false);
+ fireEvent.click(screen.getByTestId("ide-search-replace-all"));
+
+ await waitFor(() => expect(calls.some((call) => call.url.includes("/search/replace"))).toBe(true));
+ const sent = JSON.parse(calls.find((call) => call.url.includes("/search/replace"))!.body);
+ expect(sent).toMatchObject({ query: "hello", replacement: "Hi", paths: ["src/app.py"] });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.tsx
new file mode 100644
index 0000000000..bc5d36ae5c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.tsx
@@ -0,0 +1,321 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { CaseSensitive, ChevronDown, ChevronRight, Loader2, MoreHorizontal, Regex, Replace, WholeWord } from "lucide-react";
+
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { useCodeEditorStore, type EditorFile } from "@/store/codeEditor";
+import { useIdeChatStore } from "@/store/ideChat";
+import { replaceInFiles, searchWorkspace, type SearchQuery, type SearchResult } from "@/components/agentic/editor/editorApi";
+import { checkDisk } from "@/components/agentic/editor/editorModels";
+import { forgetFileList } from "@/components/agentic/editor/QuickOpen";
+import { FileTypeIcon } from "../explorer/FileTypeIcon";
+
+/** Typing pauses this long before the search runs. */
+const SEARCH_DELAY_MS = 350;
+
+/** Ask the Search tab to take the keyboard (Ctrl+Shift+F). */
+export const SEARCH_FOCUS_EVENT = "jarvis:editor-search-focus";
+
+const baseName = (path: string) => path.split("/").pop() ?? path;
+const folderOf = (path: string) => path.split("/").slice(0, -1).join("/");
+
+function Toggle({ on, label, onClick, children }: { on: boolean; label: string; onClick: () => void; children: ReactNode }) {
+ return (
+ <button
+ type="button"
+ aria-pressed={on}
+ aria-label={label}
+ title={label}
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ on && "bg-primary/15 text-foreground ring-1 ring-inset ring-primary/40",
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+/**
+ * Search in every file of the workspace (Ctrl+Shift+F), with optional
+ * replace. A result opens the file in the code editor with the match selected.
+ */
+export function SearchPanel() {
+ const t = useT();
+ const workspace = useIdeChatStore((state) => state.workspace);
+ const workspaceId = workspace?.id ?? null;
+ const [query, setQuery] = useState("");
+ const [replacement, setReplacement] = useState("");
+ const [showReplace, setShowReplace] = useState(false);
+ const [showFilters, setShowFilters] = useState(false);
+ const [caseSensitive, setCaseSensitive] = useState(false);
+ const [wholeWord, setWholeWord] = useState(false);
+ const [regex, setRegex] = useState(false);
+ const [include, setInclude] = useState("");
+ const [exclude, setExclude] = useState("");
+ const [result, setResult] = useState<SearchResult | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
+ const [confirming, setConfirming] = useState(false);
+ const [notice, setNotice] = useState("");
+ const [nonce, setNonce] = useState(0);
+ const input = useRef<HTMLInputElement>(null);
+
+ const search: SearchQuery = useMemo(
+ () => ({ query, regex, caseSensitive, wholeWord, include, exclude }),
+ [query, regex, caseSensitive, wholeWord, include, exclude],
+ );
+
+ useEffect(() => {
+ input.current?.focus();
+ const focus = () => {
+ input.current?.focus();
+ input.current?.select();
+ };
+ window.addEventListener(SEARCH_FOCUS_EVENT, focus);
+ return () => window.removeEventListener(SEARCH_FOCUS_EVENT, focus);
+ }, []);
+
+ useEffect(() => {
+ setConfirming(false);
+ if (!workspaceId || !search.query) {
+ setResult(null);
+ setError("");
+ return;
+ }
+ const controller = new AbortController();
+ const timer = window.setTimeout(() => {
+ setBusy(true);
+ searchWorkspace(workspaceId, search, controller.signal)
+ .then((answer) => {
+ setResult(answer);
+ setError("");
+ })
+ .catch((err: unknown) => {
+ if ((err as Error).name !== "AbortError") setError((err as Error).message);
+ })
+ .finally(() => setBusy(false));
+ }, SEARCH_DELAY_MS);
+ return () => {
+ window.clearTimeout(timer);
+ controller.abort();
+ };
+ }, [workspaceId, search, nonce]);
+
+ if (!workspace || !workspaceId) {
+ return <p className="px-4 py-3 text-sm text-muted-foreground">{t("ide_side_panel.explorer.no_workspace")}</p>;
+ }
+
+ const open = (path: string, line: number, column: number, length: number) =>
+ useCodeEditorStore.getState().openFile(workspaceId, path, { line, column, length });
+
+ const runReplace = async () => {
+ if (!result) return;
+ setConfirming(false);
+ // A file with unsaved edits in the editor is left alone: replacing on
+ // disk under it would only turn into a conflict.
+ const files = Object.values(useCodeEditorStore.getState().files) as EditorFile[];
+ const dirty = new Set(files.filter((file) => file.workspaceId === workspaceId && file.dirty).map((file) => file.path));
+ const paths = result.results.map((entry) => entry.path).filter((path) => !dirty.has(path));
+ const skippedDirty = result.results.length - paths.length;
+ if (paths.length === 0) {
+ setNotice(fill(t("ide_side_panel.search.skipped_dirty"), { count: skippedDirty }));
+ return;
+ }
+ setBusy(true);
+ try {
+ const answer = await replaceInFiles(workspaceId, search, replacement, paths);
+ let message = fill(t("ide_side_panel.search.replaced"), {
+ count: answer.replacements,
+ files: answer.replaced_files.length,
+ });
+ if (skippedDirty) message += ` ${fill(t("ide_side_panel.search.skipped_dirty"), { count: skippedDirty })}`;
+ if (answer.skipped.length) message += ` ${fill(t("ide_side_panel.search.skipped_other"), { count: answer.skipped.length })}`;
+ setNotice(message);
+ forgetFileList(workspaceId);
+ // Open buffers follow the files they show.
+ const state = useCodeEditorStore.getState();
+ for (const path of answer.replaced_files) {
+ const key = Object.keys(state.files).find((fileKey) => state.files[fileKey].workspaceId === workspaceId && state.files[fileKey].path === path);
+ if (key) void checkDisk(key);
+ }
+ setNonce((value) => value + 1);
+ } catch (err) {
+ setNotice((err as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const fieldClass =
+ "flex h-8 min-w-0 flex-1 items-center gap-1 rounded-lg border border-border/60 bg-background/50 pl-2.5 pr-1 focus-within:border-ring";
+ const textClass = "min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground";
+
+ return (
+ <section data-testid="ide-search" aria-label={t("ide_side_panel.tabs.search")} className="flex h-full min-h-0 flex-col">
+ <div className="shrink-0 space-y-1.5 border-b border-border/60 px-3 pb-2.5 pt-3">
+ <div className="flex items-start gap-1">
+ <button
+ type="button"
+ aria-expanded={showReplace}
+ aria-label={t("ide_side_panel.search.toggle_replace")}
+ title={t("ide_side_panel.search.toggle_replace")}
+ onClick={() => setShowReplace((value) => !value)}
+ className="mt-1 inline-flex h-6 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ {showReplace ? <ChevronDown className="h-3.5 w-3.5" aria-hidden /> : <ChevronRight className="h-3.5 w-3.5" aria-hidden />}
+ </button>
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <label className={fieldClass}>
+ <input
+ ref={input}
+ data-testid="ide-search-input"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") setNonce((value) => value + 1);
+ }}
+ placeholder={t("ide_side_panel.search.placeholder")}
+ aria-label={t("ide_side_panel.search.placeholder")}
+ className={textClass}
+ />
+ <Toggle on={caseSensitive} label={t("ide_side_panel.search.match_case")} onClick={() => setCaseSensitive((v) => !v)}>
+ <CaseSensitive className="h-4 w-4" aria-hidden />
+ </Toggle>
+ <Toggle on={wholeWord} label={t("ide_side_panel.search.whole_word")} onClick={() => setWholeWord((v) => !v)}>
+ <WholeWord className="h-4 w-4" aria-hidden />
+ </Toggle>
+ <Toggle on={regex} label={t("ide_side_panel.search.regex")} onClick={() => setRegex((v) => !v)}>
+ <Regex className="h-4 w-4" aria-hidden />
+ </Toggle>
+ </label>
+ {showReplace && (
+ <div className="flex items-center gap-1">
+ <label className={fieldClass}>
+ <input
+ data-testid="ide-search-replace"
+ value={replacement}
+ onChange={(event) => setReplacement(event.target.value)}
+ placeholder={t("ide_side_panel.search.replace_placeholder")}
+ aria-label={t("ide_side_panel.search.replace_placeholder")}
+ className={textClass}
+ />
+ </label>
+ <button
+ type="button"
+ data-testid="ide-search-replace-all"
+ disabled={!result?.match_count || busy}
+ onClick={() => (confirming ? void runReplace() : setConfirming(true))}
+ title={t("ide_side_panel.search.replace_all")}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1 rounded-lg border px-2 text-xs disabled:opacity-40",
+ confirming ? "border-destructive/60 bg-destructive/10 text-destructive" : "border-border/60 text-foreground hover:bg-secondary",
+ )}
+ >
+ <Replace className="h-3.5 w-3.5" aria-hidden />
+ {confirming
+ ? fill(t("ide_side_panel.search.replace_confirm"), { count: result?.match_count ?? 0, files: result?.file_count ?? 0 })
+ : t("ide_side_panel.search.replace_all")}
+ </button>
+ </div>
+ )}
+ </div>
+ <button
+ type="button"
+ aria-expanded={showFilters}
+ aria-label={t("ide_side_panel.search.filters")}
+ title={t("ide_side_panel.search.filters")}
+ onClick={() => setShowFilters((value) => !value)}
+ className="mt-1 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ <MoreHorizontal className="h-4 w-4" aria-hidden />
+ </button>
+ </div>
+ {showFilters && (
+ <div className="space-y-1.5 pl-6 pr-7">
+ <label className={fieldClass}>
+ <input value={include} onChange={(event) => setInclude(event.target.value)} placeholder={t("ide_side_panel.search.include")} aria-label={t("ide_side_panel.search.include")} className={textClass} />
+ </label>
+ <label className={fieldClass}>
+ <input value={exclude} onChange={(event) => setExclude(event.target.value)} placeholder={t("ide_side_panel.search.exclude")} aria-label={t("ide_side_panel.search.exclude")} className={textClass} />
+ </label>
+ </div>
+ )}
+ {(result || busy || error || notice) && (
+ <p className="flex items-center gap-1.5 pl-6 text-[11px] text-muted-foreground" role="status">
+ {busy && <Loader2 className="h-3 w-3 animate-spin" aria-hidden />}
+ {error ? (
+ <span className="text-destructive">{error}</span>
+ ) : notice ? (
+ <span>{notice}</span>
+ ) : result ? (
+ <span>
+ {result.match_count === 0
+ ? t("ide_side_panel.search.no_results")
+ : fill(t("ide_side_panel.search.summary"), { count: result.match_count, files: result.file_count })}
+ {result.truncated && ` ${t("ide_side_panel.search.truncated")}`}
+ </span>
+ ) : (
+ <span>{t("ide_side_panel.search.searching")}</span>
+ )}
+ </p>
+ )}
+ </div>
+
+ <ul data-testid="ide-search-results" className="scrollbar-jarvis min-h-0 flex-1 overflow-y-auto py-1">
+ {result?.results.map((file) => {
+ const closed = collapsed.has(file.path);
+ return (
+ <li key={file.path}>
+ <button
+ type="button"
+ onClick={() =>
+ setCollapsed((current) => {
+ const next = new Set(current);
+ if (next.has(file.path)) next.delete(file.path);
+ else next.add(file.path);
+ return next;
+ })
+ }
+ title={file.path}
+ className="flex h-7 w-full items-center gap-1.5 px-2 text-left text-[13px] hover:bg-muted/60"
+ >
+ <ChevronRight className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", !closed && "rotate-90")} aria-hidden />
+ <FileTypeIcon path={file.path} />
+ <span className="shrink-0 text-foreground">{baseName(file.path)}</span>
+ <span className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">{folderOf(file.path)}</span>
+ <span className="shrink-0 rounded-full bg-secondary px-1.5 text-[10px] tabular-nums text-muted-foreground">{file.matches.length}</span>
+ </button>
+ {!closed && (
+ <ul>
+ {file.matches.map((match) => (
+ <li key={`${match.line}:${match.column}`}>
+ <button
+ type="button"
+ data-testid="ide-search-match"
+ onClick={() => open(file.path, match.line, match.column, match.length)}
+ title={`${file.path}:${match.line}`}
+ className="flex h-6 w-full items-center gap-2 pl-9 pr-2 text-left font-mono text-[12px] hover:bg-muted/60"
+ >
+ <span className="min-w-0 flex-1 truncate whitespace-pre text-muted-foreground">
+ {match.preview.slice(0, match.preview_start).trimStart()}
+ <mark className="rounded-sm bg-warning/30 text-foreground">
+ {match.preview.slice(match.preview_start, match.preview_start + match.length)}
+ </mark>
+ {match.preview.slice(match.preview_start + match.length)}
+ </span>
+ <span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/70">{match.line}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx
index e998c3248b..67014da051 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx
@@ -1,10 +1,11 @@
import type { ReactNode } from "react";
-import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, type LucideIcon } from "lucide-react";
+import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, Search, type LucideIcon } from "lucide-react";
import type { SidePanelTabId } from "@/store/ideSidePanel";
import { AgentsOverview } from "./AgentsOverview";
import { ExplorerPanel } from "./explorer/ExplorerPanel";
import { GitOverviewTab } from "./git/GitOverviewTab";
import { OfficeTab } from "./OfficeTab";
+import { SearchPanel } from "./search/SearchPanel";
import { SkillsTab } from "./skills/SkillsTab";
import { SubscriptionsTab } from "./subscriptions/SubscriptionsTab";
@@ -43,6 +44,12 @@ export const SIDE_PANEL_TABS: readonly SidePanelTabDef[] = [
icon: FolderTree,
render: () => <ExplorerPanel view="files" />,
},
+ {
+ id: "search",
+ labelKey: "ide_side_panel.tabs.search",
+ icon: Search,
+ render: () => <SearchPanel />,
+ },
{
id: "git",
labelKey: "ide_side_panel.tabs.git",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index c547722770..20e1a15ab3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -6277,12 +6277,33 @@
"busy_saving": "Eine Datei darin wird noch gespeichert. Versuche es gleich noch einmal.",
"cancel": "Abbrechen"
},
+ "search": {
+ "placeholder": "In allen Dateien suchen",
+ "replace_placeholder": "Ersetzen durch",
+ "match_case": "Groß-/Kleinschreibung beachten",
+ "whole_word": "Nur ganzes Wort",
+ "regex": "Regulärer Ausdruck",
+ "toggle_replace": "Ersetzen ein- oder ausblenden",
+ "replace_all": "Alle ersetzen",
+ "replace_confirm": "{count} in {files} Dateien ersetzen?",
+ "filters": "Dateien ein- oder ausschließen",
+ "include": "Einschließen, z. B. *.py, src",
+ "exclude": "Ausschließen, z. B. tests, *.min.js",
+ "summary": "{count} Treffer in {files} Dateien",
+ "no_results": "Keine Treffer.",
+ "searching": "Suche läuft…",
+ "truncated": "Nur die ersten Treffer werden gezeigt; grenze die Suche ein.",
+ "replaced": "{count} in {files} Dateien ersetzt.",
+ "skipped_dirty": "{count} Dateien mit ungespeicherten Änderungen wurden ausgelassen; speichere sie zuerst.",
+ "skipped_other": "{count} Dateien ließen sich nicht ändern."
+ },
"tabs": {
"git": "Git",
"skills": "Skills",
"agents": "Agents",
"files": "Ordner",
"changes": "Änderungen",
+ "search": "Suche",
"subscriptions": "Abos",
"office": "Jarvis Verse"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index edf07804ec..81f90eb686 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6277,12 +6277,33 @@
"busy_saving": "A file in there is still saving. Try again in a moment.",
"cancel": "Cancel"
},
+ "search": {
+ "placeholder": "Search in all files",
+ "replace_placeholder": "Replace with",
+ "match_case": "Match case",
+ "whole_word": "Whole word",
+ "regex": "Regular expression",
+ "toggle_replace": "Show or hide replace",
+ "replace_all": "Replace all",
+ "replace_confirm": "Replace {count} in {files} files?",
+ "filters": "Files to include or exclude",
+ "include": "Files to include, e.g. *.py, src",
+ "exclude": "Files to exclude, e.g. tests, *.min.js",
+ "summary": "{count} results in {files} files",
+ "no_results": "No results.",
+ "searching": "Searching…",
+ "truncated": "Only the first results are shown; narrow the search.",
+ "replaced": "Replaced {count} in {files} files.",
+ "skipped_dirty": "{count} files with unsaved changes were left out; save them first.",
+ "skipped_other": "{count} files could not be changed."
+ },
"tabs": {
"git": "Git",
"skills": "Skills",
"agents": "Agents",
"files": "Folder",
"changes": "Changes",
+ "search": "Search",
"subscriptions": "Subscriptions",
"office": "Jarvis Verse"
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 178cf0c073..60d6996513 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -6277,12 +6277,33 @@
"busy_saving": "Un archivo de ahí aún se está guardando. Inténtalo de nuevo en un momento.",
"cancel": "Cancelar"
},
+ "search": {
+ "placeholder": "Buscar en todos los archivos",
+ "replace_placeholder": "Reemplazar por",
+ "match_case": "Coincidir mayúsculas y minúsculas",
+ "whole_word": "Palabra completa",
+ "regex": "Expresión regular",
+ "toggle_replace": "Mostrar u ocultar reemplazar",
+ "replace_all": "Reemplazar todo",
+ "replace_confirm": "¿Reemplazar {count} en {files} archivos?",
+ "filters": "Archivos a incluir o excluir",
+ "include": "Incluir, p. ej. *.py, src",
+ "exclude": "Excluir, p. ej. tests, *.min.js",
+ "summary": "{count} resultados en {files} archivos",
+ "no_results": "Sin resultados.",
+ "searching": "Buscando…",
+ "truncated": "Solo se muestran los primeros resultados; acota la búsqueda.",
+ "replaced": "{count} reemplazos en {files} archivos.",
+ "skipped_dirty": "Se omitieron {count} archivos con cambios sin guardar; guárdalos primero.",
+ "skipped_other": "{count} archivos no se pudieron cambiar."
+ },
"tabs": {
"git": "Git",
"skills": "Skills",
"agents": "Agentes",
"files": "Carpeta",
"changes": "Cambios",
+ "search": "Buscar",
"subscriptions": "Suscripciones",
"office": "Jarvis Verse"
},
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.ts
index 1a2d324e9a..f4a834ae07 100644
--- a/jarvis/ui/web/frontend/src/store/codeEditor.ts
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts
@@ -62,6 +62,8 @@ export interface RevealRequest {
fileKey: string;
line: number;
column: number;
+ /** Characters to select from the column on (a search match); 0 = just place the cursor. */
+ length: number;
nonce: number;
}
@@ -77,6 +79,7 @@ export interface OpenOptions {
preview?: boolean;
line?: number;
column?: number;
+ length?: number;
}
interface CodeEditorState {
@@ -190,7 +193,9 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
}
const files = state.files[fileKey] ? state.files : { ...state.files, [fileKey]: newFile(workspaceId, path) };
const reveal =
- options.line != null ? { fileKey, line: options.line, column: options.column ?? 1, nonce: ++revealNonce } : state.reveal;
+ options.line != null
+ ? { fileKey, line: options.line, column: options.column ?? 1, length: options.length ?? 0, nonce: ++revealNonce }
+ : state.reveal;
return {
tabs,
files: prune(files, tabs),
diff --git a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts b/jarvis/ui/web/frontend/src/store/ideSidePanel.ts
index 744885833a..4916e4937f 100644
--- a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts
+++ b/jarvis/ui/web/frontend/src/store/ideSidePanel.ts
@@ -10,7 +10,7 @@ import { create } from "zustand";
*/
/** Every function the panel can show. A new one is a new id plus a registry entry. */
-export type SidePanelTabId = "agents" | "changes" | "files" | "git" | "skills" | "subscriptions" | "office" | `terminal:${string}`;
+export type SidePanelTabId = "agents" | "changes" | "files" | "search" | "git" | "skills" | "subscriptions" | "office" | `terminal:${string}`;
export interface SidePanelTerminal {
id: `terminal:${string}`;
@@ -21,7 +21,7 @@ export interface SidePanelTerminal {
export const MAX_TERMINAL_TABS = 16;
-export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["agents", "changes", "files", "git", "skills", "subscriptions", "office"];
+export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["agents", "changes", "files", "search", "git", "skills", "subscriptions", "office"];
/**
* DOM id of the panel host, for the toggle's `aria-controls`.
diff --git a/tests/unit/agentic_ide/test_file_search.py b/tests/unit/agentic_ide/test_file_search.py
new file mode 100644
index 0000000000..d71b99e7b2
--- /dev/null
+++ b/tests/unit/agentic_ide/test_file_search.py
@@ -0,0 +1,108 @@
+"""Search and replace across a workspace for the code editor."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import file_search
+from jarvis.agentic_ide.file_editing import EditError
+from jarvis.agentic_ide.file_search import SearchOptions, replace_in_files, search_workspace
+
+
+def project(tmp_path: Path) -> Path:
+ root = tmp_path / "project"
+ (root / "src").mkdir(parents=True)
+ (root / "docs").mkdir()
+ (root / "node_modules").mkdir()
+ (root / "src" / "app.py").write_text(
+ "def greet():\n return 'Hello'\n# hello again\n", "utf-8"
+ )
+ (root / "src" / "util.ts").write_text("export const hello = 1;\n", encoding="utf-8")
+ (root / "docs" / "guide.md").write_text("Say Hello to the editor.\n", encoding="utf-8")
+ (root / "node_modules" / "dep.js").write_text("hello\n", encoding="utf-8")
+ (root / "logo.bin").write_bytes(b"\x00hello")
+ return root
+
+
+def _hits(answer: dict[str, object]) -> list[tuple[str, int, int]]:
+ return [
+ (result["path"], match["line"], match["column"])
+ for result in answer["results"] # type: ignore[union-attr]
+ for match in result["matches"]
+ ]
+
+
+def test_plain_search_is_case_insensitive_and_skips_binaries_and_deps(project: Path) -> None:
+ answer = search_workspace(project, SearchOptions("hello"))
+
+ assert sorted(_hits(answer)) == [
+ ("docs/guide.md", 1, 5),
+ ("src/app.py", 2, 13),
+ ("src/app.py", 3, 3),
+ ("src/util.ts", 1, 14),
+ ]
+ assert answer["match_count"] == 4
+ assert answer["truncated"] is False
+
+
+def test_case_word_and_regex_options(project: Path) -> None:
+ assert len(_hits(search_workspace(project, SearchOptions("Hello", case_sensitive=True)))) == 2
+ assert _hits(search_workspace(project, SearchOptions("greet", whole_word=True))) == [
+ ("src/app.py", 1, 5)
+ ]
+ regex = search_workspace(project, SearchOptions(r"def \w+\(", regex=True))
+ assert _hits(regex) == [("src/app.py", 1, 1)]
+ with pytest.raises(EditError):
+ search_workspace(project, SearchOptions("(", regex=True))
+
+
+def test_include_and_exclude_globs(project: Path) -> None:
+ only_py = search_workspace(project, SearchOptions("hello", include="*.py"))
+ assert {path for path, _, _ in _hits(only_py)} == {"src/app.py"}
+ no_src = search_workspace(project, SearchOptions("hello", exclude="src"))
+ assert {path for path, _, _ in _hits(no_src)} == {"docs/guide.md"}
+
+
+def test_search_stops_at_the_match_cap(project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(file_search, "MAX_MATCHES", 2)
+ answer = search_workspace(project, SearchOptions("hello"))
+ assert answer["match_count"] == 2
+ assert answer["truncated"] is True
+
+
+def test_symlinked_files_outside_the_workspace_are_not_searched(
+ project: Path, tmp_path: Path
+) -> None:
+ secret = tmp_path / "secret.txt"
+ secret.write_text("hello secret\n", encoding="utf-8")
+ try:
+ os.symlink(secret, project / "leak.txt")
+ except (OSError, NotImplementedError):
+ pytest.skip("this machine cannot create symlinks")
+ assert "leak.txt" not in {
+ path for path, _, _ in _hits(search_workspace(project, SearchOptions("secret")))
+ }
+
+
+def test_replace_plain_and_regex_groups(project: Path) -> None:
+ answer = replace_in_files(project, SearchOptions("hello"), "Hi", ["src/app.py", "src/util.ts"])
+ assert answer["replacements"] == 3
+ assert (project / "src" / "app.py").read_text(
+ "utf-8"
+ ) == "def greet():\n return 'Hi'\n# Hi again\n"
+
+ replace_in_files(
+ project, SearchOptions(r"const (\w+)", regex=True), "let $1_value", ["src/util.ts"]
+ )
+ assert (project / "src" / "util.ts").read_text("utf-8") == "export let Hi_value = 1;\n"
+
+
+def test_replace_keeps_crlf_and_reports_unreadable_files(project: Path) -> None:
+ (project / "win.txt").write_bytes(b"one\r\ntwo\r\n")
+ answer = replace_in_files(project, SearchOptions("two"), "2", ["win.txt", "logo.bin"])
+ assert (project / "win.txt").read_bytes() == b"one\r\n2\r\n"
+ assert answer["skipped"] == [{"path": "logo.bin", "reason": "not a text file"}]