Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat: editor cross-file search + replace/undo + ⌘F in-file find (#713)
Call White1fb2bb3096fb
diff --git a/core/file_browser_service.py b/core/file_browser_service.pyindex b9b38fed9..88711be5a 100644--- a/core/file_browser_service.py+++ b/core/file_browser_service.py@@ -2,14 +2,18 @@ from __future__ import annotationsimport ctypesimport errno+import fnmatch+import hashlibimport loggingimport mimetypesimport os+import reimport shutilimport statimport sysimport tempfileimport threading+import timeimport uuidfrom dataclasses import dataclassfrom pathlib import Path@@ -902,3 +906,443 @@ def delete_path(raw_path: str, *, recursive: bool = False) -> dict[str, Any]:raise FileBrowserError("fs_error", str(exc), 400) from excreturn _run_mutation("delete", target, _delete, recursive=recursive)+++# ---------------------------------------------------------------------------+# Cross-file search + replace+#+# Search walks an absolute root directory (the folder open in the editor) and+# scans text files line-by-line. Matching is unified through a single compiled+# regex so search, replace, and the UI preview all agree on what a "match" is.+# Replace is per-line (same semantics as search/preview) and snapshots the+# original text so the whole batch can be undone with one click.+# ---------------------------------------------------------------------------++SEARCH_MAX_FILE_BYTES = 2 * 1024 * 1024+SEARCH_MAX_MATCHES = 1000+SEARCH_MAX_FILES = 200+SEARCH_LINE_PREVIEW_CHARS = 400+SEARCH_PREVIEW_CONTEXT = 60+_BINARY_SNIFF_BYTES = 8192++# Directories never worth searching — VCS metadata, dependency/build output,+# caches. Pruned during the walk so we never descend into huge noise trees.+SEARCH_SKIP_DIRS = frozenset(+ {+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__",+ ".mypy_cache", ".pytest_cache", ".ruff_cache", ".cache", "dist", "build",+ ".next", ".turbo", ".parcel-cache", ".gradle", "target", ".idea", ".tox",+ }+)++_UNDO_TTL_SECONDS = 600.0+_UNDO_MAX_TOKENS = 32+_UNDO_MAX_BYTES = 64 * 1024 * 1024+_UNDO_STORE: dict[str, dict[str, Any]] = {}+_UNDO_LOCK = threading.Lock()+++def _is_word_char(ch: str) -> bool:+ return re.match(r"\w", ch) is not None+++def _compile_search_matcher(query: str, *, regex: bool, case_sensitive: bool, whole_word: bool) -> "re.Pattern[str]":+ if not isinstance(query, str) or query == "":+ raise FileBrowserError("invalid_query", "Search query is required", 400)+ pattern = query if regex else re.escape(query)+ if whole_word:+ # Guard an edge with \b only when the query's edge char is itself a word char. A symbol query+ # like "C++" or "foo()" ends in a non-word char, and \b needs a word/non-word transition, so+ # a both-sides \b would make it never match. (For regex queries the edge is taken from the raw+ # query text — a heuristic, but it fixes the common literal symbol case.)+ prefix = r"\b" if _is_word_char(query[0]) else ""+ suffix = r"\b" if _is_word_char(query[-1]) else ""+ pattern = f"{prefix}(?:{pattern}){suffix}"+ flags = 0 if case_sensitive else re.IGNORECASE+ try:+ return re.compile(pattern, flags)+ except re.error as exc:+ raise FileBrowserError("invalid_regex", f"Invalid regular expression: {exc}", 400) from exc+++def _split_globs(raw: str | None) -> list[str]:+ if not raw:+ return []+ return [piece.strip() for piece in str(raw).replace("\n", ",").split(",") if piece.strip()]+++def _match_globs(rel_posix: str, patterns: list[str]) -> bool:+ name = rel_posix.rsplit("/", 1)[-1]+ for pat in patterns:+ # A leading `**/` should also match at the root: fnmatch's `**/` needs a real slash, so+ # `**/*.py` would miss root `foo.py` and `**/dist/**` would miss root `dist/a.ts`. Also try+ # the pattern with the `**/` prefix stripped.+ forms = [pat, pat[3:]] if pat.startswith("**/") else [pat]+ if any(fnmatch.fnmatch(rel_posix, form) for form in forms) or fnmatch.fnmatch(name, pat):+ return True+ return False+++def _read_file_text(path: Path, *, lossy: bool) -> tuple[str | None, float | None]:+ """Read a regular text file for search/replace; returns (text, mtime) or (None, None) to skip.++ Skips directories, oversized files, and binaries (NUL in the first chunk). ``lossy`` controls+ undecodable bytes: search previews tolerate replacement characters; replace must not, so it+ returns None and leaves the file alone. The mtime is captured from the stat taken BEFORE the+ read, so it corresponds to (at most) the content returned — search hands that mtime back as the+ replace baseline, and a change during the read window then fails the later mtime check.+ """+ # The rest of the file browser treats symlinks as no-follow / non-editable; mirror that here so+ # search/replace can't follow a link out of the opened root (e.g. a planted+ # ``secret -> ~/.ssh/id_rsa``) and surface or rewrite content outside the tree.+ if path.is_symlink():+ return None, None+ try:+ st = path.stat()+ except OSError:+ return None, None+ if not stat.S_ISREG(st.st_mode) or st.st_size > SEARCH_MAX_FILE_BYTES:+ return None, None+ mtime = _mtime_seconds(st)+ try:+ with open(path, "rb") as handle:+ head = handle.read(_BINARY_SNIFF_BYTES)+ if b"\x00" in head:+ return None, None+ # Bound the read to the size limit even if the file grew since the stat above (TOCTOU, or+ # a growing special file), so one read can't pull unbounded bytes into memory. For+ # replace, a file that grew also fails the later mtime check, so no truncated write lands.+ data = head + handle.read(max(0, SEARCH_MAX_FILE_BYTES - len(head)))+ except OSError:+ return None, None+ try:+ return data.decode("utf-8"), mtime+ except UnicodeDecodeError:+ if not lossy:+ return None, None+ return data.decode("utf-8", errors="replace"), mtime+++def _iter_search_files(root: Path, include: list[str], exclude: list[str]):+ """Yield (path, rel_posix) for every candidate file under ``root``."""+ exclude_names = [pat for pat in exclude if "/" not in pat]+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):+ dirnames[:] = sorted(+ d for d in dirnames if d not in SEARCH_SKIP_DIRS and not _match_globs(d, exclude_names)+ )+ base = Path(dirpath)+ for name in sorted(filenames):+ fpath = base / name+ rel = fpath.relative_to(root).as_posix()+ if include and not _match_globs(rel, include):+ continue+ if exclude and _match_globs(rel, exclude):+ continue+ yield fpath, rel+++def _utf16_len(s: str) -> int:+ # Python indexes strings by code point; the React preview (String.slice) and Monaco columns+ # count UTF-16 code units. Convert so a non-BMP char (emoji, etc.) before a match doesn't shift+ # the highlight / jump selection.+ return len(s.encode("utf-16-le")) // 2+++def _preview_for_match(line: str, start: int, end: int) -> tuple[str, int, int]:+ """Build a preview snippet that always contains the match, with UTF-16 col/end into it.++ Short lines are returned whole. For a long line (e.g. minified code) the snippet is windowed+ around the match — otherwise a hit past the first 400 chars would be sliced off and the row+ would show no highlight. A leading '…' marks a left-truncated window.+ """+ if len(line) <= SEARCH_LINE_PREVIEW_CHARS:+ col = _utf16_len(line[:start])+ return line, col, col + _utf16_len(line[start:end])+ win_start = max(0, start - SEARCH_PREVIEW_CONTEXT)+ snippet = line[win_start : win_start + SEARCH_LINE_PREVIEW_CHARS]+ prefix = "…" if win_start > 0 else ""+ text = prefix + snippet+ rel_start = len(prefix) + (start - win_start)+ rel_end = len(prefix) + min(end - win_start, len(snippet))+ return text, _utf16_len(text[:rel_start]), _utf16_len(text[:rel_end])+++def _scan_lines(text: str, matcher: "re.Pattern[str]", remaining: int) -> tuple[list[dict[str, Any]], bool]:+ matches: list[dict[str, Any]] = []+ for line_no, raw_line in enumerate(text.split("\n"), start=1):+ # Drop a trailing CR so line-end anchors ('foo$') and previews behave on CRLF files; the CR+ # sits after any match, so offsets are unaffected.+ line = raw_line[:-1] if raw_line.endswith("\r") else raw_line+ for m in matcher.finditer(line):+ # Check the cap BEFORE recording: returning True only once we see a match BEYOND the+ # limit means a result set with exactly `remaining` matches isn't falsely flagged+ # truncated (which would needlessly disable Replace All).+ if len(matches) >= remaining:+ return matches, True+ # col/end are FULL-LINE UTF-16 offsets — the editor jump selects against the whole line.+ # preview_col/preview_end index into the (possibly windowed) preview `text` for the row+ # highlight; the two differ once a long line is truncated.+ full_col = _utf16_len(line[: m.start()])+ full_end = full_col + _utf16_len(line[m.start() : m.end()])+ preview, preview_col, preview_end = _preview_for_match(line, m.start(), m.end())+ matches.append(+ {+ "line": line_no,+ "col": full_col,+ "end": full_end,+ "text": preview,+ "preview_col": preview_col,+ "preview_end": preview_end,+ "line_truncated": len(line) > SEARCH_LINE_PREVIEW_CHARS,+ }+ )+ return matches, False+++def search(+ raw_root: str,+ query: str,+ *,+ regex: bool = False,+ case_sensitive: bool = False,+ whole_word: bool = False,+ include: str = "",+ exclude: str = "",+ max_matches: int = SEARCH_MAX_MATCHES,+ max_files: int = SEARCH_MAX_FILES,+) -> dict[str, Any]:+ root = _require_directory(raw_root)+ matcher = _compile_search_matcher(query, regex=regex, case_sensitive=case_sensitive, whole_word=whole_word)+ include_globs = _split_globs(include)+ exclude_globs = _split_globs(exclude)++ results: list[dict[str, Any]] = []+ total_matches = 0+ truncated = False+ reason: str | None = None+ for fpath, rel in _iter_search_files(root, include_globs, exclude_globs):+ text, file_mtime = _read_file_text(fpath, lossy=True)+ if text is None:+ continue+ file_matches, overflowed = _scan_lines(text, matcher, max_matches - total_matches)+ if not file_matches:+ # `remaining` was already 0 and this file still holds a match → a genuine hidden match.+ if overflowed:+ truncated = True+ reason = "matches"+ break+ continue+ if len(results) >= max_files:+ # This matching file is the (max_files + 1)th — more files match than we display.+ truncated = True+ reason = "files"+ break+ results.append({"path": str(fpath), "rel": rel, "mtime": file_mtime, "match_count": len(file_matches), "matches": file_matches})+ total_matches += len(file_matches)+ if overflowed:+ truncated = True+ reason = "matches"+ break+ return {+ "root": str(root),+ "query": query,+ "results": results,+ "total_matches": total_matches,+ "total_files": len(results),+ "truncated": truncated,+ "truncated_reason": reason,+ }+++def _apply_replacement(text: str, matcher: "re.Pattern[str]", replacement: str, *, regex: bool) -> tuple[str, int]:+ # Per-line replace so the count and behavior match the per-line search/preview.+ # Literal mode treats the replacement verbatim (a lambda avoids backref expansion);+ # regex mode keeps Python's \1-style backreferences.+ repl: Any = replacement if regex else (lambda _m: replacement)+ out: list[str] = []+ total = 0+ for raw_line in text.split("\n"):+ # Match the same CR-stripped content search did, then re-attach the terminator so CRLF files+ # keep their line endings.+ cr = "\r" if raw_line.endswith("\r") else ""+ core = raw_line[: -len(cr)] if cr else raw_line+ try:+ new_core, count = matcher.subn(repl, core)+ except (re.error, IndexError) as exc:+ # A bad replacement template (out-of-range \1 or unknown named group \g<x>) raises+ # re.error or IndexError; surface a clean 400 instead of a 500.+ raise FileBrowserError("invalid_regex", f"Invalid replacement: {exc}", 400) from exc+ out.append(new_core + cr)+ total += count+ return "\n".join(out), total+++def _store_undo(token: str, files: dict[str, Any]) -> None:+ now = time.monotonic()+ size = sum(len(snap["original"].encode("utf-8")) for snap in files.values())+ with _UNDO_LOCK:+ for stale in [key for key, value in _UNDO_STORE.items() if now - value["created"] > _UNDO_TTL_SECONDS]:+ _UNDO_STORE.pop(stale, None)+ # Bound the store by BOTH token count and total snapshot bytes so a few large Replace All+ # batches can't pin unbounded memory. Evict oldest-first until the new entry fits; a single+ # batch larger than the budget still gets stored (it's the user's latest, undoable action)+ # but evicts everything else.+ def total_bytes() -> int:+ return sum(value["bytes"] for value in _UNDO_STORE.values())++ while _UNDO_STORE and (len(_UNDO_STORE) >= _UNDO_MAX_TOKENS or total_bytes() + size > _UNDO_MAX_BYTES):+ oldest = min(_UNDO_STORE, key=lambda key: _UNDO_STORE[key]["created"])+ _UNDO_STORE.pop(oldest, None)+ _UNDO_STORE[token] = {"created": now, "files": files, "bytes": size}+++def replace(+ raw_root: str,+ query: str,+ replacement: str,+ *,+ regex: bool = False,+ case_sensitive: bool = False,+ whole_word: bool = False,+ include: str = "",+ exclude: str = "",+ paths: list[str] | None = None,+ expected_mtimes: dict[str, float] | None = None,+ max_files: int = SEARCH_MAX_FILES,+) -> dict[str, Any]:+ if not isinstance(replacement, str):+ raise FileBrowserError("invalid_content", "Replacement must be text", 400)+ root = _require_directory(raw_root)+ matcher = _compile_search_matcher(query, regex=regex, case_sensitive=case_sensitive, whole_word=whole_word)++ pre_skipped: list[dict[str, Any]] = []+ # `paths is not None` (not truthiness) marks explicit mode: an empty list means "replace none of+ # the shown files" (a no-op), never "walk and rewrite the whole root".+ if paths is not None:+ candidates: list[tuple[Path, str]] = []+ for raw in paths:+ try:+ resolved = _require_regular_file(raw)+ except FileBrowserError as exc:+ # A displayed file deleted/renamed/replaced since the search must be reported as+ # skipped, not abort the whole batch (the other shown files should still apply).+ pre_skipped.append({"path": raw, "rel": raw, "reason": exc.code})+ continue+ # Search skips symlinks; an explicit path that is now a symlink (e.g. swapped in for a+ # shown file after the search) must not be followed, or replace could write through it to+ # a target outside the root.+ if _expanded_absolute_path(raw).is_symlink():+ pre_skipped.append({"path": raw, "rel": raw, "reason": "symlink"})+ continue+ if resolved != root and root not in resolved.parents:+ raise FileBrowserError("invalid_path", "Path is outside the search root", 400)+ candidates.append((resolved, resolved.relative_to(root).as_posix()))+ else:+ # Lazy: iterate the walk and stop at the file cap (the loop breaks) rather than+ # materializing every candidate under the root up front.+ candidates = _iter_search_files(root, _split_globs(include), _split_globs(exclude))++ # In paths mode the caller is replacing the exact files shown in the search results, so a file+ # we now can't process (vanished, or not strict-UTF-8 while search saw it via a lossy decode of+ # an ASCII match) is reported as skipped rather than silently dropped. In walk mode a None just+ # means "not a candidate", so stay quiet.+ explicit = paths is not None+ changed: list[dict[str, Any]] = []+ skipped: list[dict[str, Any]] = list(pre_skipped)+ snapshots: dict[str, Any] = {}+ total = 0+ truncated = False+ for fpath, rel in candidates:+ if len(changed) >= max_files:+ # Stop after the file cap, but tell the caller the batch was bounded so the UI doesn't+ # claim the whole root was rewritten.+ truncated = True+ break+ # Capture the mtime BEFORE reading, and hand it to write_file as expected_mtime. A+ # concurrent edit landing after this read makes the on-disk mtime diverge, so write_file+ # raises a conflict instead of overwriting the other writer with a replacement computed+ # from stale bytes.+ try:+ before_mtime = _mtime_seconds(fpath.stat())+ except OSError:+ if explicit:+ skipped.append({"path": str(fpath), "rel": rel, "reason": "missing"})+ continue+ # Reject a file that changed between the search the user previewed and this replace, so the+ # batch never rewrites matches they never saw (expected_mtimes carries the search-time mtime).+ if explicit and expected_mtimes is not None:+ expected = expected_mtimes.get(str(fpath))+ if expected is not None and abs(before_mtime - float(expected)) > 1e-6:+ skipped.append({"path": str(fpath), "rel": rel, "reason": "modified"})+ continue+ text, _ = _read_file_text(fpath, lossy=False)+ if text is None:+ if explicit:+ skipped.append({"path": str(fpath), "rel": rel, "reason": "unreadable"})+ continue+ new_text, count = _apply_replacement(text, matcher, replacement, regex=regex)+ if count == 0 or new_text == text:+ continue+ try:+ write_file(str(fpath), new_text, expected_mtime=before_mtime)+ except FileBrowserError as exc:+ # One file failing (read-only, vanished, concurrent edit) must NOT abort the whole batch+ # and strip undo from the files already replaced. Record it and keep going; the token+ # below still covers every file that did change.+ skipped.append({"path": str(fpath), "rel": rel, "reason": exc.code})+ continue+ snapshots[str(fpath)] = {+ "original": text,+ "after_sha": hashlib.sha256(new_text.encode("utf-8")).hexdigest(),+ }+ changed.append({"path": str(fpath), "rel": rel, "replacements": count})+ total += count++ token: str | None = None+ if snapshots:+ token = uuid.uuid4().hex+ _store_undo(token, snapshots)+ return {+ "changed": changed,+ "skipped": skipped,+ "total_replacements": total,+ "files_changed": len(changed),+ "truncated": truncated,+ "undo_token": token,+ }+++def undo_replace(token: str) -> dict[str, Any]:+ with _UNDO_LOCK:+ entry = _UNDO_STORE.pop(token, None)+ if not entry or time.monotonic() - entry["created"] > _UNDO_TTL_SECONDS:+ raise FileBrowserError("undo_unavailable", "Nothing to undo — it expired or was already undone", 404)++ restored: list[str] = []+ skipped: list[dict[str, str]] = []+ for path, snap in entry["files"].items():+ target = Path(path)+ # Read the mtime from the SAME window as the bytes we verify, and hand it to write_file as+ # expected_mtime. Otherwise a re-stat after hashing opens a race where an edit landing+ # between the hash check and the write would be silently clobbered by the restore.+ try:+ before_mtime = _mtime_seconds(target.stat())+ current = target.read_bytes()+ except FileNotFoundError:+ skipped.append({"path": path, "reason": "missing"})+ continue+ except OSError:+ skipped.append({"path": path, "reason": "unreadable"})+ continue+ # Only revert files still holding exactly what the replace wrote — never+ # clobber edits the user (or anything else) made after the replace.+ if hashlib.sha256(current).hexdigest() != snap["after_sha"]:+ skipped.append({"path": path, "reason": "modified"})+ continue+ try:+ write_file(path, snap["original"], expected_mtime=before_mtime)+ except FileBrowserError:+ skipped.append({"path": path, "reason": "write_failed"})+ continue+ restored.append(path)+ return {"restored": restored, "skipped": skipped}diff --git a/docs/plans/editor-search.md b/docs/plans/editor-search.mdnew file mode 100644index 000000000..cc79f4352--- /dev/null+++ b/docs/plans/editor-search.md@@ -0,0 +1,100 @@+# Editor Search (in-file + cross-file) — implementation plan++Phase 3 of the windowed-apps polish batch. Design approved in `design.pen`+frame **`Apps · Editor Search (Dark)`** (`mIK0C`). Two surfaces:++1. **In-file find (⌘F)** — reuse Monaco's built-in find/replace widget. No new+ UI. Work: make ⌘F reach the focused editor (not swallowed by the window /+ browser) and ensure the widget follows the dark theme.+2. **Cross-file search** — new VS Code-style Search view in the editor's+ activity bar (⇧⌘F): query + replace, `Aa`/whole-word/`.*` toggles,+ include/exclude globs, results grouped by file, click-to-jump + highlight,+ replace with preview + one-click undo.++## Locked decisions (2026-06-29)++- **Caps:** truncate at **1000 matches OR 200 files**; response carries a+ `truncated` flag and the UI shows a "结果已截断" notice.+- **Regex:** ship in v1 (toggle alongside plain text).+- **Replace:** preview (inline old→new over the existing results, client-side)+ **and** one-click undo of the whole replace batch.++## Backend — `core/file_browser_service.py` (+ routes in `vibe/ui_server.py`)++Reuse the existing absolute-path safety (`resolve_safe_path` / `_resolve_existing_path`),+`FileBrowserError`, and the atomic temp+rename `write_file` path.++### `search(root, query, *, regex, case_sensitive, whole_word, include, exclude, max_matches=1000, max_files=200)`+- `root` is an existing absolute directory (the folder open in the editor).+- Walk `root` (os.walk, dirs sorted, follow no symlinks). Always skip a small+ default set of noise dirs (`.git`, `node_modules`, `.venv`, `dist`,+ `__pycache__`, etc.) **and** anything matched by `exclude` globs; if `include`+ globs are given, a file must match one. Globs are matched against the path+ relative to `root` (fnmatch, `**` supported via `Path.match`-style or manual).+- Per candidate file: skip if > `SEARCH_MAX_FILE_BYTES` (2 MiB) or binary+ (NUL byte in first 8 KiB). Read text (utf-8, errors="replace"), scan lines.+ - Literal mode: `str.find` loop (respect case + whole-word via boundary+ check). Regex mode: `re.compile` once (case flag); `whole_word` wraps in+ `\b…\b`. Invalid regex → `FileBrowserError("invalid_regex", …, 400)`.+ - Each match: `{line, col, end, text}` where `text` is the (length-capped,+ ~400 char) source line for preview; column/offsets are 0-based within the+ raw line so the UI can render + the editor can select.+- Stop cleanly at the caps; set `truncated=True` and stop walking. Return+ `{root, results:[{path, rel, matches:[…], match_count}], total_matches,+ total_files, truncated, truncated_reason}`.++### `replace(root, query, replacement, *, regex, case_sensitive, whole_word, include, exclude, paths=None)`+- Re-derives matches with the **same** matcher as `search` (single source of+ truth — one private `_compile_matcher()` / `_iter_file_matches()` helper used+ by both). `paths` optionally restricts to a chosen subset (UI "replace in this+ file"); default = all matched files.+- For each file: compute the new content (regex `pattern.sub` with backrefs, or+ literal replace honoring case/whole-word), write atomically. Snapshot the+ original bytes first.+- Returns `{changed:[{path, replacements}], total_replacements, files_changed,+ undo_token}`. Token keys an in-memory, single-use, TTL-bounded snapshot store+ (`_UNDO_STORE`, cap N tokens, ~10 min TTL).++### `undo(token)`+- Restores each snapshotted file **iff** it is unchanged since the replace+ (compare current bytes hash to the post-replace hash we recorded); skips ++ reports any file modified meanwhile. Consumes the token. Returns+ `{restored, skipped}`.++### Routes (mirror existing `/api/files/*` shape, `_dispatch_native_ui_request` + `to_thread`)+- `GET /api/files/search` (query params; GET so it's cancel-friendly/cacheable)+- `POST /api/files/search/replace`+- `POST /api/files/search/undo`++## Frontend — `ui/src/components/workbench/`++- **`lib/filesApi.ts`**: add `searchFiles`, `replaceInFiles`, `undoReplace`.+- **In-file find:** ensure the editor's `⌘F`/`⌘⌥F` reach Monaco+ (`editor.getAction('actions.find')`) — Monaco already renders + themes the+ widget (we set `dark` on it). Add a window-level key guard only if something+ swallows it.+- **Search view:** new `EditorSearchView.tsx` rendered in the editor's left+ panel when the activity-bar **search** icon is active (state lifted into+ `EditorApp`). Reuse `ui/src/components/ui` primitives + the dark tokens from+ the design. Results list virtualated-lite (cap already bounds size). Click a+ match → open file in a tab + reveal/select the range in Monaco.+- **Replace preview:** when a replacement is typed, render each result line as+ old (strikethrough) → new inline (client-side, no extra call). Replace-all →+ `replaceInFiles`; show a toast/inline bar "已替换 N 处,可撤销" with an Undo+ action calling `undoReplace(token)`.+- **Shortcuts:** `⌘F` in-file find; `⇧⌘F` open Search view + focus input.+- **i18n:** all strings via `ui/src/i18n/{en,zh}.json`.++## Evidence++- Unit (`tests/test_file_search.py`): matcher (literal/regex/case/whole-word),+ include/exclude + default skips, binary/large skip, caps + truncation flag,+ replace correctness + atomicity, undo restore + skip-when-modified + token+ single-use.+- Build: `npm run build`. Manual: Incus regression — search real repo, jump,+ replace + undo, ⌘F.++## Status+- [ ] Backend search + replace + undo + routes + tests+- [ ] Frontend filesApi + Search view + ⌘F/⇧⌘F + replace preview/undo + i18n+- [ ] Build + deploy + verify + Codex + PRdiff --git a/tests/test_file_search.py b/tests/test_file_search.pynew file mode 100644index 000000000..0fd4b62d0--- /dev/null+++ b/tests/test_file_search.py@@ -0,0 +1,349 @@+from __future__ import annotations++from pathlib import Path++import pytest++from core import file_browser_service as fbs+from core.file_browser_service import FileBrowserError+++def _write(root: Path, rel: str, text: str) -> Path:+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return path+++def _rels(result: dict) -> set[str]:+ return {entry["rel"] for entry in result["results"]}+++def test_search_literal_groups_by_file_with_positions(tmp_path):+ _write(tmp_path, "a.txt", "alpha onResize beta\nno hit here\nonResize again\n")+ _write(tmp_path, "sub/b.txt", "leading onResize trailing\n")++ result = fbs.search(str(tmp_path), "onResize")++ assert _rels(result) == {"a.txt", "sub/b.txt"}+ assert result["total_matches"] == 3+ assert result["total_files"] == 2+ assert result["truncated"] is False+ a = next(e for e in result["results"] if e["rel"] == "a.txt")+ first = a["matches"][0]+ assert first["line"] == 1+ assert first["col"] == 6+ assert first["end"] == 14+ assert first["text"] == "alpha onResize beta"+++def test_search_case_sensitivity(tmp_path):+ _write(tmp_path, "a.txt", "Cat cat CAT\n")+ assert fbs.search(str(tmp_path), "cat")["total_matches"] == 3+ assert fbs.search(str(tmp_path), "cat", case_sensitive=True)["total_matches"] == 1+++def test_search_whole_word(tmp_path):+ _write(tmp_path, "a.txt", "cat category scatter cat\n")+ assert fbs.search(str(tmp_path), "cat", whole_word=True)["total_matches"] == 2+++def test_search_regex_and_invalid_regex(tmp_path):+ _write(tmp_path, "a.txt", "x1 x22 x333\n")+ assert fbs.search(str(tmp_path), r"x\d+", regex=True)["total_matches"] == 3+ with pytest.raises(FileBrowserError) as exc:+ fbs.search(str(tmp_path), "x(", regex=True)+ assert exc.value.code == "invalid_regex"+++def test_search_empty_query_rejected(tmp_path):+ _write(tmp_path, "a.txt", "anything\n")+ with pytest.raises(FileBrowserError) as exc:+ fbs.search(str(tmp_path), "")+ assert exc.value.code == "invalid_query"+++def test_whole_word_matches_symbol_query(tmp_path):+ # A symbol ending in a non-word char (C++) must still match under Whole Word — the old both-sides+ # \b made it never match.+ _write(tmp_path, "a.txt", "use C++ here\nand Cxx too\n")+ res = fbs.search(str(tmp_path), "C++", whole_word=True)+ assert res["total_matches"] == 1+++def test_include_globstar_matches_root_level(tmp_path):+ _write(tmp_path, "foo.py", "needle\n")+ _write(tmp_path, "sub/bar.py", "needle\n")+ _write(tmp_path, "baz.txt", "needle\n")+ assert _rels(fbs.search(str(tmp_path), "needle", include="**/*.py")) == {"foo.py", "sub/bar.py"}+++def test_exclude_globstar_matches_root_level(tmp_path):+ _write(tmp_path, "keep.txt", "needle\n")+ _write(tmp_path, "generated/a.ts", "needle\n")+ assert _rels(fbs.search(str(tmp_path), "needle", exclude="**/generated/**")) == {"keep.txt"}+++def test_search_include_exclude_globs(tmp_path):+ _write(tmp_path, "keep.py", "needle\n")+ _write(tmp_path, "skip.txt", "needle\n")+ _write(tmp_path, "vendor/dep.py", "needle\n")++ assert _rels(fbs.search(str(tmp_path), "needle", include="*.py")) == {"keep.py", "vendor/dep.py"}+ assert _rels(fbs.search(str(tmp_path), "needle", exclude="vendor/**")) == {"keep.py", "skip.txt"}+++def test_search_prunes_default_noise_dirs(tmp_path):+ _write(tmp_path, "src.py", "needle\n")+ _write(tmp_path, "node_modules/pkg/index.js", "needle\n")+ _write(tmp_path, ".git/config", "needle\n")+ assert _rels(fbs.search(str(tmp_path), "needle")) == {"src.py"}+++def test_search_skips_binary_and_oversized(tmp_path, monkeypatch):+ (tmp_path / "bin.dat").write_bytes(b"needle\x00needle")+ _write(tmp_path, "big.txt", "needle\n" + "x" * 100)+ _write(tmp_path, "small.txt", "needle\n")+ monkeypatch.setattr(fbs, "SEARCH_MAX_FILE_BYTES", 16)+ assert _rels(fbs.search(str(tmp_path), "needle")) == {"small.txt"}+++def test_search_truncates_on_match_cap(tmp_path):+ _write(tmp_path, "a.txt", "hit\n" * 50)+ result = fbs.search(str(tmp_path), "hit", max_matches=10)+ assert result["total_matches"] == 10+ assert result["truncated"] is True+ assert result["truncated_reason"] == "matches"+++def test_search_truncates_on_file_cap(tmp_path):+ for i in range(5):+ _write(tmp_path, f"f{i}.txt", "hit\n")+ result = fbs.search(str(tmp_path), "hit", max_files=2)+ assert result["truncated"] is True+ assert result["truncated_reason"] == "files"+ assert result["total_files"] == 2+++def test_replace_literal_then_undo_roundtrip(tmp_path):+ a = _write(tmp_path, "a.txt", "onResize here\nonResize there\n")+ b = _write(tmp_path, "b.txt", "no match\n")++ result = fbs.replace(str(tmp_path), "onResize", "onWindowResize")+ assert result["total_replacements"] == 2+ assert result["files_changed"] == 1+ assert a.read_text() == "onWindowResize here\nonWindowResize there\n"+ assert b.read_text() == "no match\n"++ token = result["undo_token"]+ assert token+ undo = fbs.undo_replace(token)+ assert undo["restored"] == [str(a)]+ assert a.read_text() == "onResize here\nonResize there\n"++ # token is single-use+ with pytest.raises(FileBrowserError) as exc:+ fbs.undo_replace(token)+ assert exc.value.code == "undo_unavailable"+++def test_replace_regex_uses_backrefs_literal_does_not(tmp_path):+ a = _write(tmp_path, "a.txt", "value=42\n")+ fbs.replace(str(tmp_path), r"value=(\d+)", r"v(\1)", regex=True)+ assert a.read_text() == "v(42)\n"++ b = _write(tmp_path, "b.txt", "value=42\n")+ fbs.replace(str(tmp_path), "value=42", r"x\1y")+ assert b.read_text() == r"x\1y" + "\n"+++def test_undo_skips_files_modified_after_replace(tmp_path):+ a = _write(tmp_path, "a.txt", "onResize\n")+ result = fbs.replace(str(tmp_path), "onResize", "renamed")+ a.write_text("user edited this after replace\n", encoding="utf-8")++ undo = fbs.undo_replace(result["undo_token"])+ assert undo["restored"] == []+ assert undo["skipped"] == [{"path": str(a), "reason": "modified"}]+ assert a.read_text() == "user edited this after replace\n"+++def test_search_skips_symlink_files(tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ (root / "real.txt").write_text("needle here\n", encoding="utf-8")+ outside = tmp_path / "secret.txt"+ outside.write_text("needle secret\n", encoding="utf-8")+ (root / "link.txt").symlink_to(outside)+ # The symlink must not be followed — only the real in-root file surfaces, and the outside+ # target's contents are never exposed under the root.+ assert _rels(fbs.search(str(root), "needle")) == {"real.txt"}+++def test_search_returns_utf16_offsets(tmp_path):+ # 😀 is one code point but two UTF-16 code units; col/end must be UTF-16 so the JS preview+ # slice and Monaco selection line up.+ _write(tmp_path, "e.txt", "😀 onResize\n")+ m = fbs.search(str(tmp_path), "onResize")["results"][0]["matches"][0]+ assert (m["col"], m["end"]) == (3, 11)+++def test_replace_partial_failure_preserves_undo(tmp_path, monkeypatch):+ a = _write(tmp_path, "a.txt", "x\n")+ b = _write(tmp_path, "b.txt", "x\n")+ real_write = fbs.write_file++ def flaky(path, content, **kwargs):+ if path.endswith("b.txt"):+ raise FileBrowserError("permission_denied", "denied", 403)+ return real_write(path, content, **kwargs)++ monkeypatch.setattr(fbs, "write_file", flaky)+ res = fbs.replace(str(tmp_path), "x", "y")+ # b.txt failing must not abort the batch or strip undo from a.txt.+ assert res["files_changed"] == 1+ assert [s["reason"] for s in res["skipped"]] == ["permission_denied"]+ assert res["undo_token"]+ assert a.read_text() == "y\n"+ assert b.read_text() == "x\n"+ fbs.undo_replace(res["undo_token"])+ assert a.read_text() == "x\n"+++def test_replace_reports_undecodable_shown_file_as_skipped(tmp_path):+ good = _write(tmp_path, "good.txt", "hit\n")+ bad = tmp_path / "bad.txt"+ # ASCII 'hit' (so lossy search would surface it) but invalid UTF-8, so strict replace can't read it.+ bad.write_bytes(b"hit \xff\xfe nope\n")+ res = fbs.replace(str(tmp_path), "hit", "x", paths=[str(good), str(bad)])+ assert res["files_changed"] == 1+ assert [s["reason"] for s in res["skipped"]] == ["unreadable"]+ assert good.read_text() == "x\n"+ assert bad.read_bytes() == b"hit \xff\xfe nope\n"+++def test_search_not_truncated_at_exact_match_cap(tmp_path):+ _write(tmp_path, "a.txt", "hit\n" * 5)+ res = fbs.search(str(tmp_path), "hit", max_matches=5)+ assert res["total_matches"] == 5+ assert res["truncated"] is False # exactly the cap, no hidden 6th match+++def test_search_not_truncated_at_exact_file_cap(tmp_path):+ for i in range(2):+ _write(tmp_path, f"f{i}.txt", "hit\n")+ res = fbs.search(str(tmp_path), "hit", max_files=2)+ assert res["total_files"] == 2+ assert res["truncated"] is False # exactly the cap, no hidden 3rd file+++def test_replace_truncates_on_file_cap(tmp_path):+ for i in range(4):+ _write(tmp_path, f"f{i}.txt", "hit\n")+ res = fbs.replace(str(tmp_path), "hit", "x", max_files=2)+ assert res["files_changed"] == 2+ assert res["truncated"] is True+++def test_search_windows_preview_around_long_line_match(tmp_path):+ needle = "TARGET"+ line = "x" * 1000 + needle + "y" * 50+ _write(tmp_path, "long.txt", line + "\n")+ m = fbs.search(str(tmp_path), needle)["results"][0]["matches"][0]+ assert m["line_truncated"] is True+ # col/end are full-line offsets (the editor jump target), unaffected by the preview window.+ assert (m["col"], m["end"]) == (1000, 1006)+ # The windowed preview still contains the hit at its preview offsets.+ assert m["text"][m["preview_col"] : m["preview_end"]] == needle+ assert len(m["text"]) <= fbs.SEARCH_LINE_PREVIEW_CHARS + 1 # +1 for the leading ellipsis+++def test_replace_bad_regex_template_is_clean_error(tmp_path):+ a = _write(tmp_path, "a.txt", "abc\n")+ # An invalid replacement template (unknown named group / out-of-range backref) must surface a+ # clean invalid_regex error, not leak IndexError/re.error as a 500.+ for bad in (r"\g<nope>", r"\9"):+ with pytest.raises(FileBrowserError) as exc:+ fbs.replace(str(tmp_path), "(a)", bad, regex=True, paths=[str(a)])+ assert exc.value.code == "invalid_regex"+ assert a.read_text() == "abc\n"+++def test_replace_skips_vanished_explicit_path(tmp_path):+ a = _write(tmp_path, "a.txt", "hit\n")+ gone = str(tmp_path / "gone.txt") # never created+ res = fbs.replace(str(tmp_path), "hit", "x", paths=[str(a), gone])+ assert res["files_changed"] == 1+ assert any(s["reason"] == "not_found" for s in res["skipped"])+ assert a.read_text() == "x\n"+++def test_replace_skips_files_modified_since_search(tmp_path):+ a = _write(tmp_path, "a.txt", "hit\n")+ # A search-time mtime that no longer matches the file → treated as changed-since, left untouched.+ res = fbs.replace(str(tmp_path), "hit", "x", paths=[str(a)], expected_mtimes={str(a): 1.0})+ assert res["files_changed"] == 0+ assert [s["reason"] for s in res["skipped"]] == ["modified"]+ assert a.read_text() == "hit\n"+++def test_replace_applies_when_search_mtime_matches(tmp_path):+ a = _write(tmp_path, "a.txt", "hit\n")+ mt = fbs.search(str(tmp_path), "hit")["results"][0]["mtime"]+ assert mt is not None+ res = fbs.replace(str(tmp_path), "hit", "x", paths=[str(a)], expected_mtimes={str(a): mt})+ assert res["files_changed"] == 1+ assert a.read_text() == "x\n"+++def test_replace_skips_symlinked_explicit_path(tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ real = root / "a.txt"+ real.write_text("hit\n", encoding="utf-8")+ outside = tmp_path / "secret.txt"+ outside.write_text("hit\n", encoding="utf-8")+ (root / "link.txt").symlink_to(outside)+ res = fbs.replace(str(root), "hit", "x", paths=[str(real), str(root / "link.txt")])+ assert res["files_changed"] == 1+ assert any(s["reason"] == "symlink" for s in res["skipped"])+ assert real.read_text() == "x\n"+ assert outside.read_text() == "hit\n" # symlink target never followed/written+++def test_replace_empty_paths_is_noop(tmp_path):+ a = _write(tmp_path, "a.txt", "hit\n")+ res = fbs.replace(str(tmp_path), "hit", "x", paths=[])+ # An explicit empty selection must replace nothing — never fall through to a whole-tree walk.+ assert res["files_changed"] == 0+ assert res["undo_token"] is None+ assert a.read_text() == "hit\n"+++def test_search_and_replace_handle_crlf_line_end(tmp_path):+ p = tmp_path / "win.txt"+ p.write_bytes(b"foo\r\nbar\r\n")+ # A line-end anchor matches despite the CRLF terminator...+ assert fbs.search(str(tmp_path), "foo$", regex=True)["total_matches"] == 1+ # ...and replace preserves the CRLF endings.+ fbs.replace(str(tmp_path), "foo$", "FOO", regex=True, paths=[str(p)])+ assert p.read_bytes() == b"FOO\r\nbar\r\n"+++def test_undo_store_bounded_by_bytes(tmp_path, monkeypatch):+ monkeypatch.setattr(fbs, "_UNDO_MAX_BYTES", 10)+ a = _write(tmp_path, "a.txt", "hit hit\n")+ r1 = fbs.replace(str(tmp_path), "hit", "x", paths=[str(a)])+ b = _write(tmp_path, "b.txt", "hit\n")+ r2 = fbs.replace(str(tmp_path), "hit", "y", paths=[str(b)])+ # Storing r2 pushes total snapshot bytes over the budget, so r1's snapshot is evicted.+ with pytest.raises(FileBrowserError) as exc:+ fbs.undo_replace(r1["undo_token"])+ assert exc.value.code == "undo_unavailable"+ assert fbs.undo_replace(r2["undo_token"])["restored"] == [str(b)]+++def test_search_root_must_be_directory(tmp_path):+ f = _write(tmp_path, "a.txt", "x\n")+ with pytest.raises(FileBrowserError):+ fbs.search(str(f), "x")diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxindex c3ef46f09..4306c6159 100644--- a/ui/src/components/workbench/EditorApp.tsx+++ b/ui/src/components/workbench/EditorApp.tsx@@ -8,6 +8,7 @@ import { downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry }import { isEditableFile } from '../../lib/filePreview';import { FileTree } from './FileTree';import { FilePicker, type FilePickerMode } from './FilePicker';+import { EditorSearchView } from './EditorSearchView';const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));@@ -16,7 +17,7 @@ const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ defa// clobbering newer on-disk content. `path` is null for an unsaved "untitled" buffer (a VS// Code-style new file): it lives only in memory until the first save picks a location. Tabs are// keyed by a synthetic `id` (not the path) so an untitled tab survives becoming a saved file.-type Tab = { id: string; path: string | null; name: string; mtime: number | null };+type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number };// A pending file dialog, rendered as the in-window FilePicker overlay.type PickerState = {@@ -86,25 +87,62 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unconst [dirty, setDirty] = useState<Record<string, boolean>>({}); // keyed by tab idconst [cursor, setCursor] = useState<{ line: number; col: number } | null>(null);const [picker, setPicker] = useState<PickerState | null>(null);+ const [view, setView] = useState<'files' | 'search'>('files');+ // A pending Monaco jump (from a cross-file search result), scoped to one tab. The nonce makes a+ // repeat jump to the same spot re-fire even when the tab is already open.+ const [reveal, setReveal] = useState<{ tabId: string; line: number; column: number; endColumn: number; nonce: number } | null>(null);+ const [searchFocus, setSearchFocus] = useState(0);const tabSeq = useRef(0);const untitledSeq = useRef(0);+ const revealSeq = useRef(0);+ // Latest tabs + dirty for async callbacks (reloadTabs) so a reload landing after an in-flight+ // replace never acts on a stale snapshot and clobbers a buffer the user just edited.+ const dirtyRef = useRef(dirty);+ const tabsRef = useRef(tabs);+ useEffect(() => {+ dirtyRef.current = dirty;+ tabsRef.current = tabs;+ });- const openFile = useCallback((path: string, name: string, mtime: number | null) => {- setRoot((r) => r ?? parentDir(path));- setCursor(null);- setTabs((ts) => {- // Dedup inside the updater so two concurrent opens of the same file (e.g. a fast double-click- // firing two fileMeta requests) can't both append a tab — both see the same current `ts`.- const existing = ts.find((x) => x.path === path);- if (existing) {- setActive(existing.id);+ const openFile = useCallback(+ (path: string, name: string, mtime: number | null, target?: { line: number; column: number; endColumn: number }) => {+ setRoot((r) => r ?? parentDir(path));+ if (!target) setCursor(null);+ setTabs((ts) => {+ // Dedup inside the updater so two concurrent opens of the same file (e.g. a fast double-click+ // firing two fileMeta requests) can't both append a tab — both see the same current `ts`.+ const existing = ts.find((x) => x.path === path);+ const id = existing ? existing.id : `t${++tabSeq.current}`;+ setActive(id);+ if (target) setReveal({ tabId: id, line: target.line, column: target.column, endColumn: target.endColumn, nonce: ++revealSeq.current });+ if (!existing) return [...ts, { id, path, name, mtime }];+ // Jumping to an already-open tab whose file changed on disk since it was opened (e.g. a+ // search hit in newer content): reload the clean buffer first so the revealed line matches+ // what the search showed. A dirty tab keeps its edits.+ if (mtime != null && existing.mtime !== mtime && !dirtyRef.current[existing.id]) {+ return ts.map((x) => (x.id === id ? { ...x, mtime, reload: (x.reload ?? 0) + 1 } : x));+ }return ts;+ });+ },+ [],+ );++ // Open (or focus) a file at a search match and select the range in Monaco. Fetch fresh metadata+ // for the save baseline + re-validation, mirroring the explorer's open path.+ const onJump = useCallback(+ async (path: string, line: number, col: number, endCol: number) => {+ const name = path.split('/').filter(Boolean).pop() || path;+ const target = { line, column: col, endColumn: endCol };+ try {+ const m = await fileMeta(path);+ openFile(path, name, m.mtime, target);+ } catch {+ openFile(path, name, null, target);}- const id = `t${++tabSeq.current}`;- setActive(id);- return [...ts, { id, path, name, mtime }];- });- }, []);+ },+ [openFile],+ );// The explorer tree emits a clicked entry. Gate it like the File Browser: only a regular,// supported, within-cap file opens in Monaco; a symlink (the backend refuses symlink writes),@@ -132,6 +170,29 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un[openFile],);+ // After a cross-file replace/undo rewrites files on disk, reload any open, non-dirty tab for a+ // changed file so it shows the new content with a fresh save baseline (a dirty tab keeps its+ // buffer — the mtime guard still catches a stale save). Refetch the mtime so the tab saves+ // against the post-replace revision, and bump `reload` to re-run the pane's read effect.+ const reloadTabs = useCallback(async (paths: string[]) => {+ const set = new Set(paths);+ const targets = tabsRef.current.filter((tb) => tb.path && set.has(tb.path));+ if (!targets.length) return;+ const metas = await Promise.all(+ targets.map(async (tb) => {+ try {+ return { id: tb.id, mtime: (await fileMeta(tb.path as string)).mtime };+ } catch {+ return { id: tb.id, mtime: null as number | null };+ }+ }),+ );+ const byId = new Map(metas.map((m) => [m.id, m.mtime]));+ // Re-check dirty at apply time (via ref): a tab the user edited while the request was in flight+ // must keep its unsaved buffer rather than be re-read from disk.+ setTabs((ts) => ts.map((tb) => (byId.has(tb.id) && !dirtyRef.current[tb.id] ? { ...tb, mtime: byId.get(tb.id) ?? tb.mtime, reload: (tb.reload ?? 0) + 1 } : tb)));+ }, []);+// Open the launch file (from the File Browser) once on mount.useEffect(() => {const p = typeof params?.path === 'string' ? params.path : null;@@ -217,12 +278,21 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unuseEffect(() => {if (!windowId) return;const onKey = (e: KeyboardEvent) => {- if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;- const k = e.key.toLowerCase();- if (k !== 'o' && k !== 'n') return;+ if (!(e.metaKey || e.ctrlKey) || e.altKey) return;// Only the frontmost editor window, and not while its own dialog is open. Scope by the window// manager's focused id (not DOM focus) so the shortcut keeps working after a dialog closes.if (picker || wm.focusedId !== windowId) return;+ const k = e.key.toLowerCase();+ // ⇧⌘F opens the cross-file Search view and focuses its query input. (Plain ⌘F is left to+ // Monaco's built-in in-file find widget when the editor has focus.)+ if (e.shiftKey) {+ if (k !== 'f') return;+ e.preventDefault();+ setView('search');+ setSearchFocus((n) => n + 1);+ return;+ }+ if (k !== 'o' && k !== 'n') return;e.preventDefault();if (k === 'o') openFolder();else newFile();@@ -231,63 +301,88 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unreturn () => window.removeEventListener('keydown', onKey, true);}, [windowId, openFolder, newFile, picker, wm.focusedId]);- const ACTIVITY = [Files, Search, GitBranch, Bug, Blocks];const showWelcome = root == null && tabs.length === 0;const activeName = tabs.find((x) => x.id === active)?.name;return (<div className="relative flex h-full min-h-0 w-full flex-col bg-surface"><div className="flex min-h-0 flex-1">- {/* Activity bar */}+ {/* Activity bar — Files / Search switch the left panel; the rest are inert placeholders. */}<div className="flex w-12 shrink-0 flex-col items-center justify-between border-r border-border bg-surface-3 py-3"><div className="flex flex-col items-center gap-[18px]">- {ACTIVITY.map((Icon, i) => (- <Icon key={i} className={clsx('size-5', i === 0 ? 'text-foreground' : 'text-muted')} />+ {([+ { Icon: Files, key: 'files' as const, label: t('apps.editor.explorer') },+ { Icon: Search, key: 'search' as const, label: t('apps.editor.search.title') },+ ]).map(({ Icon, key, label }) => (+ <button+ key={key}+ type="button"+ onClick={() => {+ setView(key);+ if (key === 'search') setSearchFocus((n) => n + 1);+ }}+ aria-label={label}+ aria-pressed={view === key}+ title={label}+ className={clsx('relative grid h-6 w-12 place-items-center transition', view === key ? 'text-foreground' : 'text-muted hover:text-foreground')}+ >+ {view === key && <span className="absolute left-0 top-0 h-full w-0.5 bg-cyan" />}+ <Icon className="size-5" />+ </button>+ ))}+ {[GitBranch, Bug, Blocks].map((Icon, i) => (+ <Icon key={i} className="size-5 text-muted" />))}</div><Settings className="size-5 text-muted" /></div>- {/* Explorer — ALWAYS present (design w0qoC keeps it in the welcome state): an- empty "No folder opened + Open Folder" state when no folder, else the file tree. */}- <div className="flex w-[220px] shrink-0 flex-col overflow-hidden border-r border-border bg-surface-2">- <div className="flex items-center gap-0.5 px-3 pb-1 pt-2.5">- <span className="flex-1 truncate font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('apps.editor.explorer')}</span>- <button- type="button"- onClick={newFile}- title={`${t('apps.fileBrowser.newFile')} (⌘N)`}- aria-label={t('apps.fileBrowser.newFile')}- className="grid size-5 place-items-center rounded text-muted transition hover:bg-foreground/10 hover:text-foreground"- >- <FilePlus className="size-3.5" />- </button>- <button- type="button"- onClick={openFolder}- title={`${t('apps.editor.openFolder')} (⌘O)`}- aria-label={t('apps.editor.openFolder')}- className="grid size-5 place-items-center rounded text-muted transition hover:bg-foreground/10 hover:text-foreground"- >- <FolderOpen className="size-3.5" />- </button>- </div>- {root == null ? (- <div className="flex flex-col gap-2 px-3 py-2">- <div className="text-[12px] text-muted">{t('apps.editor.noFolder')}</div>- <button- type="button"- onClick={openFolder}- className="flex items-center justify-center gap-1.5 rounded-md border border-mint/40 bg-mint/[0.08] px-2.5 py-1.5 text-[12px] font-semibold text-mint transition hover:bg-mint/[0.14]"- >- <FolderOpen className="size-3.5" />- {t('apps.editor.openFolder')}- </button>- </div>+ {/* Left panel — Explorer (Files view) or the cross-file Search view. Explorer is ALWAYS+ present in Files view (design w0qoC keeps it in the welcome state). */}+ <div className={clsx('flex shrink-0 flex-col overflow-hidden border-r border-border bg-surface-2', view === 'search' ? 'w-[300px]' : 'w-[220px]')}>+ {view === 'search' ? (+ <EditorSearchView root={root} focusNonce={searchFocus} onOpenFolder={openFolder} onJump={onJump} onFilesChanged={reloadTabs} />) : (- <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">- <FileTree rootPath={root} rootName={root.split('/').filter(Boolean).pop() || root} activePath={tabs.find((x) => x.id === active)?.path ?? null} onOpenFile={onTreeOpen} />- </div>+ <>+ <div className="flex items-center gap-0.5 px-3 pb-1 pt-2.5">+ <span className="flex-1 truncate font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('apps.editor.explorer')}</span>+ <button+ type="button"+ onClick={newFile}+ title={`${t('apps.fileBrowser.newFile')} (⌘N)`}+ aria-label={t('apps.fileBrowser.newFile')}+ className="grid size-5 place-items-center rounded text-muted transition hover:bg-foreground/10 hover:text-foreground"+ >+ <FilePlus className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={openFolder}+ title={`${t('apps.editor.openFolder')} (⌘O)`}+ aria-label={t('apps.editor.openFolder')}+ className="grid size-5 place-items-center rounded text-muted transition hover:bg-foreground/10 hover:text-foreground"+ >+ <FolderOpen className="size-3.5" />+ </button>+ </div>+ {root == null ? (+ <div className="flex flex-col gap-2 px-3 py-2">+ <div className="text-[12px] text-muted">{t('apps.editor.noFolder')}</div>+ <button+ type="button"+ onClick={openFolder}+ className="flex items-center justify-center gap-1.5 rounded-md border border-mint/40 bg-mint/[0.08] px-2.5 py-1.5 text-[12px] font-semibold text-mint transition hover:bg-mint/[0.14]"+ >+ <FolderOpen className="size-3.5" />+ {t('apps.editor.openFolder')}+ </button>+ </div>+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">+ <FileTree rootPath={root} rootName={root.split('/').filter(Boolean).pop() || root} activePath={tabs.find((x) => x.id === active)?.path ?? null} onOpenFile={onTreeOpen} />+ </div>+ )}+ </>)}</div>@@ -348,6 +443,8 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unonDirtyChange={(d) => setDirty((prev) => (prev[tab.id] === d ? prev : { ...prev, [tab.id]: d }))}onCursor={active === tab.id ? (line, col) => setCursor({ line, col }) : undefined}onSaveAs={(textValue) => saveAs(tab.id, textValue)}+ reveal={reveal?.tabId === tab.id ? { line: reveal.line, column: reveal.column, endColumn: reveal.endColumn, nonce: reveal.nonce } : null}+ reloadNonce={tab.reload}/></Suspense></div>diff --git a/ui/src/components/workbench/EditorSearchView.tsx b/ui/src/components/workbench/EditorSearchView.tsxnew file mode 100644index 000000000..98191b066--- /dev/null+++ b/ui/src/components/workbench/EditorSearchView.tsx@@ -0,0 +1,449 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ CaseSensitive,+ ChevronDown,+ ChevronRight,+ CodeXml,+ CornerDownRight,+ FolderOpen,+ Loader2,+ Regex,+ ReplaceAll,+ Undo2,+ WholeWord,+} from 'lucide-react';+import clsx from 'clsx';++import {+ fileBrowserErrorMessage,+ replaceInFiles,+ searchFiles,+ undoReplace,+ type SearchFileResult,+ type SearchMatch,+ type SearchResponse,+} from '../../lib/filesApi';++type Props = {+ /** Absolute folder the search is rooted at (the editor's open folder), or null. */+ root: string | null;+ /** Bumped by ⇧⌘F / the activity-bar click to focus + select the query input. */+ focusNonce: number;+ onOpenFolder: () => void;+ onJump: (path: string, line: number, col: number, endCol: number) => void;+ /** Paths whose on-disk content just changed (replace / undo), so open tabs can reload. */+ onFilesChanged?: (paths: string[]) => void;+};++// Build a per-match replacement preview that mirrors what the backend will write, given the match's+// preview line and its start offset within it. Literal mode is exact (the whole match becomes the+// replacement; an empty replacement is a deletion). Regex mode is best-effort: it evaluates the+// pattern against the full preview line (so anchors / lookaround see surrounding context, not just+// the isolated hit) and computes the replacement for the occurrence at `start`, translating+// Python-style backrefs (\1) to JS ($1). It falls back to the raw string if the pattern isn't+// JS-compatible. (Truncated long lines and Python-only regex syntax remain approximations; the+// actual replace is always computed server-side.)+function makePreviewer(query: string, replacement: string, regex: boolean, caseSensitive: boolean): (line: string, start: number) => string {+ if (!regex) return () => replacement;+ const flags = caseSensitive ? '' : 'i';+ let valid = true;+ try {+ new RegExp(query, flags);+ } catch {+ valid = false;+ }+ const jsRepl = replacement.replace(/\$/g, '$$$$').replace(/\\(\d)/g, '$$$1');+ return (line: string, start: number) => {+ if (!valid) return replacement;+ try {+ const global = new RegExp(query, flags.includes('g') ? flags : `${flags}g`);+ let out = replacement;+ let found = false;+ line.replace(global, (matched: string, ...args: unknown[]) => {+ const offset = args[args.length - 2] as number;+ if (!found && offset === start) {+ found = true;+ out = matched.replace(new RegExp(query, flags), jsRepl);+ }+ return matched;+ });+ return out;+ } catch {+ return replacement;+ }+ };+}++// A small toggle button (Aa / whole-word / regex) inside the search field.+const Toggle: React.FC<{ on: boolean; label: string; onClick: () => void; children: React.ReactNode }> = ({ on, label, onClick, children }) => (+ <button+ type="button"+ aria-pressed={on}+ title={label}+ aria-label={label}+ onClick={onClick}+ className={clsx('grid size-5 place-items-center rounded transition', on ? 'bg-cyan-soft text-cyan' : 'text-muted hover:bg-foreground/10 hover:text-foreground')}+ >+ {children}+ </button>+);++export const EditorSearchView: React.FC<Props> = ({ root, focusNonce, onOpenFolder, onJump, onFilesChanged }) => {+ const { t } = useTranslation();+ const [query, setQuery] = useState('');+ const [replacement, setReplacement] = useState('');+ const [showReplace, setShowReplace] = useState(false);+ const [showScope, setShowScope] = useState(false);+ const [regex, setRegex] = useState(false);+ const [caseSensitive, setCaseSensitive] = useState(false);+ const [wholeWord, setWholeWord] = useState(false);+ const [include, setInclude] = useState('');+ const [exclude, setExclude] = useState('');+ const [data, setData] = useState<SearchResponse | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ const [undo, setUndo] = useState<{ token: string; files: number; total: number; skipped: number } | null>(null);+ const [busy, setBusy] = useState(false);+ const [refresh, setRefresh] = useState(0);+ // `resultKey` records which inputs the displayed `data` belongs to. `notice` reports an outcome+ // that isn't an undo bar (e.g. everything skipped, or a partial/no-op undo).+ const [resultKey, setResultKey] = useState('');+ const [notice, setNotice] = useState<string | null>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ // Identity of the current query + options. Replace All is enabled only when the shown results+ // match this, so a replace can never run against stale results from a previous query.+ const searchKey = useMemo(+ () => JSON.stringify({ root, query, regex, caseSensitive, wholeWord, include, exclude }),+ [root, query, regex, caseSensitive, wholeWord, include, exclude],+ );+ const resultsCurrent = resultKey === searchKey;++ useEffect(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ }, [focusNonce]);++ // Debounced search whenever the query, options, or scope change (or a replace/undo asks for a+ // refresh). An AbortController cancels the in-flight request so fast typing doesn't race.+ useEffect(() => {+ if (!root || !query) {+ setData(null);+ setError(null);+ setLoading(false);+ setResultKey('');+ return;+ }+ setLoading(true);+ const ctrl = new AbortController();+ const handle = window.setTimeout(() => {+ searchFiles(root, query, { regex, caseSensitive, wholeWord, include, exclude }, ctrl.signal)+ .then((res) => {+ setData(res);+ setResultKey(searchKey);+ setError(null);+ })+ .catch((e: unknown) => {+ if ((e as { name?: string }).name === 'AbortError') return;+ setError(fileBrowserErrorMessage(e, t, t('apps.editor.search.failed')));+ setData(null);+ })+ .finally(() => setLoading(false));+ }, 300);+ return () => {+ window.clearTimeout(handle);+ ctrl.abort();+ };+ }, [root, query, regex, caseSensitive, wholeWord, include, exclude, refresh, searchKey, t]);++ // Drop a stale outcome notice when the query/options change (but NOT on the post-replace refresh,+ // which keeps searchKey the same — so a "skipped" notice survives the results refresh).+ useEffect(() => {+ setNotice(null);+ }, [searchKey]);++ const toggleCollapse = useCallback((path: string) => {+ setCollapsed((prev) => {+ const next = new Set(prev);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ return next;+ });+ }, []);++ const doReplace = useCallback(async () => {+ // Only act when the shown results match the current query (resultsCurrent), aren't loading, and+ // aren't truncated — a truncated result set hides matches (even inside shown files), so replacing+ // could touch occurrences the user never previewed. They must narrow the search first.+ if (!root || !query || busy || loading || !data?.results.length || !resultsCurrent || data.truncated) return;+ setBusy(true);+ setError(null);+ setNotice(null);+ try {+ // Replace only the files currently shown — when a search is truncated this bounds the edit to+ // what the user actually previewed instead of rescanning the whole root.+ const paths = data.results.map((r) => r.path);+ // Carry the search-time mtime per file so the backend skips any file edited between the+ // preview and this click instead of rewriting matches the user never saw.+ const expectedMtimes: Record<string, number> = {};+ for (const r of data.results) if (r.mtime != null) expectedMtimes[r.path] = r.mtime;+ const res = await replaceInFiles(root, query, replacement, { regex, caseSensitive, wholeWord, include, exclude, paths, expectedMtimes });+ if (res.undo_token) {+ setUndo({ token: res.undo_token, files: res.files_changed, total: res.total_replacements, skipped: res.skipped?.length ?? 0 });+ } else {+ // Nothing was written. If every shown file was skipped (conflicts / write-protected), say so+ // instead of silently looking like a success.+ setUndo(null);+ if (res.skipped?.length) setNotice(t('apps.editor.search.allSkipped', { n: res.skipped.length }));+ }+ onFilesChanged?.(res.changed.map((c) => c.path));+ setRefresh((n) => n + 1);+ } catch (e: unknown) {+ setError(fileBrowserErrorMessage(e, t, t('apps.editor.search.replaceFailed')));+ } finally {+ setBusy(false);+ }+ }, [root, query, replacement, regex, caseSensitive, wholeWord, include, exclude, busy, loading, data, resultsCurrent, onFilesChanged, t]);++ const doUndo = useCallback(async () => {+ if (!undo || busy) return;+ setBusy(true);+ setError(null);+ setNotice(null);+ try {+ const res = await undoReplace(undo.token);+ onFilesChanged?.(res.restored);+ setUndo(null);+ // A partial/no-op undo (files modified or removed since the replace) must be surfaced, not+ // silently dismissed with the banner.+ if (res.skipped?.length) setNotice(t('apps.editor.search.undoSkipped', { n: res.skipped.length }));+ setRefresh((n) => n + 1);+ } catch (e: unknown) {+ setError(fileBrowserErrorMessage(e, t, t('apps.editor.search.undoFailed')));+ } finally {+ setBusy(false);+ }+ }, [undo, busy, onFilesChanged, t]);++ // Preview replacement closure shared by every match row (rebuilt only when the query/replacement+ // or matching options change).+ const previewer = useMemo(+ () => (showReplace ? makePreviewer(query, replacement, regex, caseSensitive) : null),+ [showReplace, query, replacement, regex, caseSensitive],+ );++ if (root == null) {+ return (+ <div className="flex flex-col gap-2 px-3 py-2.5">+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('apps.editor.search.title')}</span>+ <div className="text-[12px] text-muted">{t('apps.editor.search.needFolder')}</div>+ <button+ type="button"+ onClick={onOpenFolder}+ className="flex items-center justify-center gap-1.5 rounded-md border border-mint/40 bg-mint/[0.08] px-2.5 py-1.5 text-[12px] font-semibold text-mint transition hover:bg-mint/[0.14]"+ >+ <FolderOpen className="size-3.5" />+ {t('apps.editor.openFolder')}+ </button>+ </div>+ );+ }++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-col gap-1.5 px-3 pb-2 pt-2.5">+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('apps.editor.search.title')}</span>+ {/* Query row: chevron toggles the replace row; the field carries the Aa / word / regex toggles. */}+ <div className="flex items-start gap-1">+ <button+ type="button"+ onClick={() => setShowReplace((v) => !v)}+ aria-label={t('apps.editor.search.toggleReplace')}+ title={t('apps.editor.search.toggleReplace')}+ className="mt-1.5 grid size-4 place-items-center rounded text-muted transition hover:text-foreground"+ >+ {showReplace ? <ChevronDown className="size-3.5" /> : <ChevronRight className="size-3.5" />}+ </button>+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <div className="flex items-center gap-1 rounded-md border border-cyan bg-surface-3 px-2 py-1 focus-within:border-cyan">+ <input+ ref={inputRef}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t('apps.editor.search.placeholder')}+ spellCheck={false}+ className="min-w-0 flex-1 bg-transparent font-mono text-[12px] text-foreground placeholder:text-muted focus:outline-none"+ />+ <Toggle on={caseSensitive} label={t('apps.editor.search.caseSensitive')} onClick={() => setCaseSensitive((v) => !v)}>+ <CaseSensitive className="size-3.5" />+ </Toggle>+ <Toggle on={wholeWord} label={t('apps.editor.search.wholeWord')} onClick={() => setWholeWord((v) => !v)}>+ <WholeWord className="size-3.5" />+ </Toggle>+ <Toggle on={regex} label={t('apps.editor.search.regex')} onClick={() => setRegex((v) => !v)}>+ <Regex className="size-3.5" />+ </Toggle>+ </div>+ {showReplace && (+ <div className="flex items-center gap-1">+ <CornerDownRight className="size-3.5 shrink-0 text-muted" />+ <div className="flex min-w-0 flex-1 items-center gap-1 rounded-md border border-border bg-surface-3 px-2 py-1">+ <input+ value={replacement}+ onChange={(e) => setReplacement(e.target.value)}+ placeholder={t('apps.editor.search.replacePlaceholder')}+ spellCheck={false}+ className="min-w-0 flex-1 bg-transparent font-mono text-[12px] text-foreground placeholder:text-muted focus:outline-none"+ />+ <button+ type="button"+ onClick={() => void doReplace()}+ disabled={busy || loading || !data?.results.length || !resultsCurrent || data?.truncated}+ aria-label={t('apps.editor.search.replaceAll')}+ title={t('apps.editor.search.replaceAll')}+ className="grid size-5 place-items-center rounded text-muted transition hover:bg-foreground/10 hover:text-foreground disabled:opacity-40"+ >+ <ReplaceAll className="size-3.5" />+ </button>+ </div>+ </div>+ )}+ <button+ type="button"+ onClick={() => setShowScope((v) => !v)}+ className="self-start font-mono text-[10px] uppercase tracking-wide text-muted transition hover:text-foreground"+ >+ {showScope ? t('apps.editor.search.hideScope') : t('apps.editor.search.showScope')}+ </button>+ {showScope && (+ <div className="flex flex-col gap-1.5">+ <input+ value={include}+ onChange={(e) => setInclude(e.target.value)}+ placeholder={t('apps.editor.search.include')}+ spellCheck={false}+ className="rounded-md border border-border bg-surface-3 px-2 py-1 font-mono text-[11px] text-foreground placeholder:text-muted focus:border-cyan focus:outline-none"+ />+ <input+ value={exclude}+ onChange={(e) => setExclude(e.target.value)}+ placeholder={t('apps.editor.search.exclude')}+ spellCheck={false}+ className="rounded-md border border-border bg-surface-3 px-2 py-1 font-mono text-[11px] text-foreground placeholder:text-muted focus:border-cyan focus:outline-none"+ />+ </div>+ )}+ </div>+ </div>+ </div>++ {/* Summary / status strip */}+ <div className="flex min-h-[22px] items-center gap-2 px-3 text-[11px] text-muted">+ {loading ? (+ <span className="flex items-center gap-1.5">+ <Loader2 className="size-3 animate-spin" /> {t('apps.editor.search.searching')}+ </span>+ ) : error ? (+ <span className="text-destructive">{error}</span>+ ) : data ? (+ <span>{t('apps.editor.search.summary', { matches: data.total_matches, files: data.total_files })}</span>+ ) : query ? null : (+ <span>{t('apps.editor.search.hint')}</span>+ )}+ </div>++ {data?.truncated && !loading && (+ <div className="mx-3 mb-1 rounded border border-gold/30 bg-gold/[0.08] px-2 py-1 text-[11px] text-gold">+ {t(data.truncated_reason === 'files' ? 'apps.editor.search.truncatedFiles' : 'apps.editor.search.truncatedMatches')}+ </div>+ )}++ {undo && (+ <div className="mx-3 mb-1 flex items-center gap-2 rounded border border-mint/30 bg-mint/[0.08] px-2 py-1 text-[11px] text-mint">+ <span className="flex-1">+ {t('apps.editor.search.replaced', { total: undo.total, files: undo.files })}+ {undo.skipped > 0 ? ` ${t('apps.editor.search.replaceSkipped', { n: undo.skipped })}` : ''}+ </span>+ <button type="button" onClick={() => void doUndo()} disabled={busy} className="flex items-center gap-1 font-semibold transition hover:underline disabled:opacity-40">+ <Undo2 className="size-3" /> {t('apps.editor.search.undo')}+ </button>+ </div>+ )}++ {notice && <div className="mx-3 mb-1 rounded border border-gold/30 bg-gold/[0.08] px-2 py-1 text-[11px] text-gold">{notice}</div>}++ {/* Results tree */}+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">+ {data?.results.map((file) => (+ <FileGroup+ key={file.path}+ file={file}+ collapsed={collapsed.has(file.path)}+ previewer={previewer}+ onToggle={() => toggleCollapse(file.path)}+ onJump={onJump}+ />+ ))}+ </div>+ </div>+ );+};++const FileGroup: React.FC<{+ file: SearchFileResult;+ collapsed: boolean;+ previewer: ((line: string, start: number) => string) | null;+ onToggle: () => void;+ onJump: (path: string, line: number, col: number, endCol: number) => void;+}> = ({ file, collapsed, previewer, onToggle, onJump }) => {+ const dir = file.rel.includes('/') ? file.rel.slice(0, file.rel.lastIndexOf('/')) : '';+ const name = file.rel.slice(file.rel.lastIndexOf('/') + 1);+ return (+ <div className="flex flex-col">+ <button+ type="button"+ onClick={onToggle}+ className="flex items-center gap-1.5 rounded px-1.5 py-1 text-left transition hover:bg-foreground/[0.05]"+ >+ {collapsed ? <ChevronRight className="size-3 shrink-0 text-muted" /> : <ChevronDown className="size-3 shrink-0 text-muted" />}+ <CodeXml className="size-3.5 shrink-0 text-cyan" />+ <span className="shrink-0 text-[12.5px] font-semibold text-foreground">{name}</span>+ {dir && <span className="min-w-0 flex-1 truncate text-[11px] text-muted">{dir}</span>}+ <span className="ml-auto shrink-0 rounded-full bg-surface-3 px-1.5 font-mono text-[10px] text-muted">{file.match_count}</span>+ </button>+ {!collapsed && (+ <div className="flex flex-col gap-px pl-2.5">+ {file.matches.map((m, i) => (+ <MatchRow key={`${m.line}:${m.col}:${i}`} match={m} previewer={previewer} onClick={() => onJump(file.path, m.line, m.col, m.end)} />+ ))}+ </div>+ )}+ </div>+ );+};++const MatchRow: React.FC<{ match: SearchMatch; previewer: ((line: string, start: number) => string) | null; onClick: () => void }> = ({ match, previewer, onClick }) => {+ const pre = match.text.slice(0, match.preview_col);+ const hit = match.text.slice(match.preview_col, match.preview_end);+ const post = match.text.slice(match.preview_end);+ const replaced = previewer ? previewer(match.text, match.preview_col) : null;+ return (+ <button type="button" onClick={onClick} className="flex items-center gap-2 rounded px-1.5 py-0.5 text-left transition hover:bg-cyan-soft">+ <span className="w-7 shrink-0 text-right font-mono text-[11px] tabular-nums text-muted">{match.line}</span>+ <span className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted">+ {pre}+ {replaced != null ? (+ <>+ <span className="rounded-sm bg-destructive/20 text-destructive line-through">{hit}</span>+ {replaced && <span className="rounded-sm bg-mint/20 text-mint">{replaced}</span>}+ </>+ ) : (+ <span className="rounded-sm bg-gold/25 font-semibold text-foreground">{hit}</span>+ )}+ {post}+ </span>+ </button>+ );+};diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsxindex 0a5cbe676..88d8348c8 100644--- a/ui/src/components/workbench/FileEditorPane.tsx+++ b/ui/src/components/workbench/FileEditorPane.tsx@@ -99,7 +99,11 @@ export const FileEditorPane: React.FC<{* save-as picker + write, then re-points this pane at the chosen path.*/onSaveAs?: (text: string) => void;-}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onDirtyChange, chromeless = false, onCursor, onSaveAs }) => {+ /** Jump to + select a match (cross-file search result click). Forwarded to Monaco. */+ reveal?: { line: number; column: number; endColumn: number; nonce: number } | null;+ /** Bumped to force a re-read from disk (e.g. after a cross-file replace rewrote this file). */+ reloadNonce?: number;+}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onDirtyChange, chromeless = false, onCursor, onSaveAs, reveal, reloadNonce }) => {const { t } = useTranslation();const { resolvedTheme } = useTheme();const [text, setText] = useState<string | null>(null);@@ -138,7 +142,7 @@ export const FileEditorPane: React.FC<{return () => {cancelled = true;};- }, [path, filename, mtime]);+ }, [path, filename, mtime, reloadNonce]);const dirty = !readOnly && text !== null && text !== original;useEffect(() => {@@ -243,6 +247,7 @@ export const FileEditorPane: React.FC<{onChange={(value) => setText(value)}onSave={() => void save()}onCursorChange={onCursor}+ reveal={reveal}/></Suspense>)}diff --git a/ui/src/components/workbench/MonacoEditor.tsx b/ui/src/components/workbench/MonacoEditor.tsxindex aeb3972de..0de29bec6 100644--- a/ui/src/components/workbench/MonacoEditor.tsx+++ b/ui/src/components/workbench/MonacoEditor.tsx@@ -102,9 +102,25 @@ export interface MonacoEditorProps {onSave?: () => void;/** Live 1-based cursor position, for an IDE status bar (`Ln x, Col y`). */onCursorChange?: (line: number, column: number) => void;+ /**+ * Jump to + select a match (from cross-file search). `line` is 1-based; `column`/`endColumn`+ * are 0-based offsets within the line (the search backend's convention). `nonce` makes a+ * repeated jump to the same spot re-fire.+ */+ reveal?: { line: number; column: number; endColumn: number; nonce: number } | null;+}++function applyReveal(editor: monaco.editor.IStandaloneCodeEditor, reveal: { line: number; column: number; endColumn: number }) {+ const line = Math.max(1, reveal.line);+ const startColumn = Math.max(1, reveal.column + 1);+ const endColumn = Math.max(startColumn, reveal.endColumn + 1);+ const range = { startLineNumber: line, startColumn, endLineNumber: line, endColumn };+ editor.revealRangeInCenter(range);+ editor.setSelection(range);+ editor.focus();}-export default function MonacoEditor({ value, language, path, readOnly, dark = true, onChange, onSave, onCursorChange }: MonacoEditorProps) {+export default function MonacoEditor({ value, language, path, readOnly, dark = true, onChange, onSave, onCursorChange, reveal }: MonacoEditorProps) {const { t } = useTranslation();const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);// Keep the latest callbacks in refs: the ⌘S command + cursor listener are bound@@ -112,9 +128,13 @@ export default function MonacoEditor({ value, language, path, readOnly, dark = t// closures rather than capture the first render's.const onSaveRef = useRef(onSave);const onCursorRef = useRef(onCursorChange);+ // Hold the latest reveal so handleMount can apply one that arrived before the editor existed+ // (opening a not-yet-open file from a search result mounts the editor with reveal already set).+ const revealRef = useRef(reveal);useEffect(() => {onSaveRef.current = onSave;onCursorRef.current = onCursorChange;+ revealRef.current = reveal;});const handleMount: OnMount = (editor) => {@@ -123,7 +143,14 @@ export default function MonacoEditor({ value, language, path, readOnly, dark = tconst pos = editor.getPosition();if (pos) onCursorRef.current?.(pos.lineNumber, pos.column);editor.onDidChangeCursorPosition((e) => onCursorRef.current?.(e.position.lineNumber, e.position.column));+ if (revealRef.current) applyReveal(editor, revealRef.current);};++ // Already-open file: a new reveal (its nonce changes) jumps + selects the match in place.+ useEffect(() => {+ if (editorRef.current && reveal) applyReveal(editorRef.current, reveal);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [reveal?.nonce]);const handleChange: OnChange = (next) => onChange?.(next ?? '');// Accessory actions operate on the live editor instance.diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex cea533fa0..12e2c7ea3 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -627,7 +627,35 @@"confirmDiscardClose": "Discard unsaved changes and close this window?","selectAll": "Select all","copyAll": "Copy all",- "untitled": "Untitled-{{n}}"+ "untitled": "Untitled-{{n}}",+ "search": {+ "title": "Search",+ "placeholder": "Search",+ "replacePlaceholder": "Replace",+ "caseSensitive": "Match Case",+ "wholeWord": "Match Whole Word",+ "regex": "Use Regular Expression",+ "toggleReplace": "Toggle Replace",+ "replaceAll": "Replace All",+ "showScope": "Files to include / exclude",+ "hideScope": "Hide include / exclude",+ "include": "files to include (e.g. ui/src/**)",+ "exclude": "files to exclude (e.g. **/dist/**)",+ "searching": "Searching…",+ "summary": "{{matches}} results in {{files}} files",+ "hint": "Type to search across this folder",+ "needFolder": "Open a folder to search across its files.",+ "truncatedMatches": "Showing the first 1000 matches — narrow your search to see the rest.",+ "truncatedFiles": "Showing the first 200 files — narrow your search to see the rest.",+ "replaced": "Replaced {{total}} occurrences in {{files}} files.",+ "replaceSkipped": "({{n}} files skipped)",+ "allSkipped": "No files changed — {{n}} skipped (conflicts or write-protected).",+ "undoSkipped": "Undo left {{n}} file(s) unchanged (modified since the replace).",+ "undo": "Undo",+ "failed": "Search failed",+ "replaceFailed": "Replace failed",+ "undoFailed": "Undo failed"+ }},"dock": {"newInstanceHint": "⌘-click for a new window",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c4c9a68a6..d2a18d5b0 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -627,7 +627,35 @@"confirmDiscardClose": "放弃未保存的更改并关闭此窗口?","selectAll": "全选","copyAll": "全部复制",- "untitled": "未命名-{{n}}"+ "untitled": "未命名-{{n}}",+ "search": {+ "title": "搜索",+ "placeholder": "搜索",+ "replacePlaceholder": "替换",+ "caseSensitive": "区分大小写",+ "wholeWord": "全字匹配",+ "regex": "使用正则表达式",+ "toggleReplace": "切换替换",+ "replaceAll": "全部替换",+ "showScope": "包含 / 排除文件",+ "hideScope": "隐藏包含 / 排除",+ "include": "包含的文件(如 ui/src/**)",+ "exclude": "排除的文件(如 **/dist/**)",+ "searching": "搜索中…",+ "summary": "在 {{files}} 个文件中找到 {{matches}} 处",+ "hint": "输入关键字,在该文件夹内搜索",+ "needFolder": "请先打开一个文件夹,再进行跨文件搜索。",+ "truncatedMatches": "仅显示前 1000 处匹配 —— 缩小搜索范围以查看其余结果。",+ "truncatedFiles": "仅显示前 200 个文件 —— 缩小搜索范围以查看其余结果。",+ "replaced": "已在 {{files}} 个文件中替换 {{total}} 处。",+ "replaceSkipped": "(跳过 {{n}} 个文件)",+ "allSkipped": "未改动任何文件 —— 跳过 {{n}} 个(冲突或只读)。",+ "undoSkipped": "撤销时有 {{n}} 个文件未还原(替换后又被改动)。",+ "undo": "撤销",+ "failed": "搜索失败",+ "replaceFailed": "替换失败",+ "undoFailed": "撤销失败"+ }},"dock": {"newInstanceHint": "⌘ 点击可新建窗口",diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.tsindex 1cef3f1f5..f2c582962 100644--- a/ui/src/lib/filesApi.ts+++ b/ui/src/lib/filesApi.ts@@ -217,6 +217,77 @@ export async function deletePath(path: string, recursive = false): Promise<{ ok:);}+// Cross-file search + replace (backend: file_browser_service.search/replace/undo_replace).+// col/end are full-line UTF-16 offsets (the editor jump target); preview_col/preview_end index+// into `text` (the possibly windowed preview) for the row highlight.+export type SearchMatch = { line: number; col: number; end: number; preview_col: number; preview_end: number; text: string; line_truncated: boolean };+export type SearchFileResult = { path: string; rel: string; mtime: number | null; match_count: number; matches: SearchMatch[] };+export type SearchResponse = {+ root: string;+ query: string;+ results: SearchFileResult[];+ total_matches: number;+ total_files: number;+ truncated: boolean;+ truncated_reason: 'matches' | 'files' | null;+};+export type SearchOptions = { regex?: boolean; caseSensitive?: boolean; wholeWord?: boolean; include?: string; exclude?: string };+export type ReplaceResponse = {+ changed: { path: string; rel: string; replacements: number }[];+ skipped: { path: string; rel: string; reason: string }[];+ total_replacements: number;+ files_changed: number;+ truncated: boolean;+ undo_token: string | null;+};+export type UndoResponse = { restored: string[]; skipped: { path: string; reason: string }[] };++export async function searchFiles(root: string, query: string, opts: SearchOptions = {}, signal?: AbortSignal): Promise<SearchResponse> {+ const params = new URLSearchParams({ root, query });+ if (opts.regex) params.set('regex', '1');+ if (opts.caseSensitive) params.set('case', '1');+ if (opts.wholeWord) params.set('word', '1');+ if (opts.include) params.set('include', opts.include);+ if (opts.exclude) params.set('exclude', opts.exclude);+ return parse<SearchResponse>(await apiFetch(`/api/files/search?${params.toString()}`, { signal }));+}++export async function replaceInFiles(+ root: string,+ query: string,+ replacement: string,+ opts: SearchOptions & { paths?: string[]; expectedMtimes?: Record<string, number> } = {},+): Promise<ReplaceResponse> {+ return parse<ReplaceResponse>(+ await apiFetch('/api/files/search/replace', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ root,+ query,+ replacement,+ regex: opts.regex || undefined,+ case: opts.caseSensitive || undefined,+ word: opts.wholeWord || undefined,+ include: opts.include || undefined,+ exclude: opts.exclude || undefined,+ paths: opts.paths,+ expected_mtimes: opts.expectedMtimes,+ }),+ }),+ );+}++export async function undoReplace(token: string): Promise<UndoResponse> {+ return parse<UndoResponse>(+ await apiFetch('/api/files/search/undo', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token }),+ }),+ );+}+export async function systemFavorites(): Promise<Favorite[]> {const data = await parse<{ ok: true; favorites: Favorite[] }>(await apiFetch('/api/browse/favorites'));return data.favorites || [];diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 9ac1ea4d8..265303fdf 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5494,6 +5494,73 @@ async def files_delete(starlette_request: FastAPIRequest):return await _dispatch_native_ui_request(starlette_request, handler)[email protected]("/api/files/search", include_in_schema=False)+async def files_search(starlette_request: FastAPIRequest):+ async def handler():+ from core import file_browser_service++ args = request.args+ try:+ return jsonify(+ await asyncio.to_thread(+ file_browser_service.search,+ args.get("root") or "",+ args.get("query") or "",+ regex=args.get("regex") == "1",+ case_sensitive=args.get("case") == "1",+ whole_word=args.get("word") == "1",+ include=args.get("include") or "",+ exclude=args.get("exclude") or "",+ )+ )+ except Exception as exc:+ return _file_browser_error_response(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++[email protected]("/api/files/search/replace", include_in_schema=False)+async def files_search_replace(starlette_request: FastAPIRequest):+ async def handler():+ from core import file_browser_service++ payload = request.json or {}+ try:+ return jsonify(+ await asyncio.to_thread(+ file_browser_service.replace,+ payload.get("root") or "",+ payload.get("query") or "",+ payload.get("replacement") or "",+ regex=_parse_explicit_bool(payload.get("regex")),+ case_sensitive=_parse_explicit_bool(payload.get("case")),+ whole_word=_parse_explicit_bool(payload.get("word")),+ include=payload.get("include") or "",+ exclude=payload.get("exclude") or "",+ paths=payload.get("paths"),+ expected_mtimes=payload.get("expected_mtimes"),+ )+ )+ except Exception as exc:+ return _file_browser_error_response(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++[email protected]("/api/files/search/undo", include_in_schema=False)+async def files_search_undo(starlette_request: FastAPIRequest):+ async def handler():+ from core import file_browser_service++ payload = request.json or {}+ try:+ return jsonify(await asyncio.to_thread(file_browser_service.undo_replace, payload.get("token") or ""))+ except Exception as exc:+ return _file_browser_error_response(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++# Content types the media proxy is willing to serve ``inline``. Anything else —# text/html, image/svg+xml, xml, application/octet-stream, unknown — is forced to# ``attachment`` so a preview-open of agent-produced ACTIVE content can't execute