Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): harden backups, search, Python lookups and Cmd+W from review

rubenluetke10-beepce49b6db319b
diff --git a/jarvis/agentic_ide/editor_backups.py b/jarvis/agentic_ide/editor_backups.py
index d814804d2b..2d60f95710 100644
--- a/jarvis/agentic_ide/editor_backups.py
+++ b/jarvis/agentic_ide/editor_backups.py
@@ -45,6 +45,10 @@ __all__ = [
#: More open tabs than this are not worth restoring; the oldest are dropped.
MAX_TABS = 60
+#: A backup nobody restored for this long belongs to a file long gone.
+MAX_BACKUP_AGE_S = 30 * 24 * 3600
+#: Backups restored per workspace at most; the newest win.
+MAX_BACKUPS = 100
_MODES = ("edit", "diff")
@@ -95,10 +99,16 @@ def save_tabs(
"""Remember the open tabs of one workspace, in order."""
clean: list[dict[str, Any]] = []
for tab in tabs[-MAX_TABS:]:
- path = _normalise_relative(str(tab.get("path", "")))
+ try:
+ path = _normalise_relative(str(tab.get("path", "")))
+ except EditError:
+ continue # one unusable tab must not cost the others their place
mode = tab.get("mode") if tab.get("mode") in _MODES else "edit"
clean.append({"path": path, "mode": mode, "preview": bool(tab.get("preview"))})
- active_path = _normalise_relative(active) if active else None
+ try:
+ active_path = _normalise_relative(active) if active else None
+ except EditError:
+ active_path = None
_write_json(_folder_dir(folder) / "tabs.json", {"tabs": clean, "active": active_path})
@@ -143,8 +153,17 @@ def load_state(folder: str | os.PathLike[str]) -> dict[str, Any]:
backups: list[dict[str, Any]] = []
backup_dir = root / "backups"
if backup_dir.is_dir():
+ cutoff = time.time() - MAX_BACKUP_AGE_S
for entry in sorted(backup_dir.glob("*.json")):
doc = _read_json(entry)
- if doc and isinstance(doc.get("path"), str) and isinstance(doc.get("text"), str):
- backups.append(doc)
- return {"tabs": tabs, "active": tabs_doc.get("active"), "backups": backups}
+ if not (doc and isinstance(doc.get("path"), str) and isinstance(doc.get("text"), str)):
+ continue
+ if float(doc.get("saved_at") or 0) < cutoff:
+ try:
+ entry.unlink()
+ except OSError as exc:
+ logger.warning("Editor backup: could not prune {}: {}", entry.name, exc)
+ continue
+ backups.append(doc)
+ backups.sort(key=lambda doc: float(doc.get("saved_at") or 0), reverse=True)
+ return {"tabs": tabs, "active": tabs_doc.get("active"), "backups": backups[:MAX_BACKUPS]}
diff --git a/jarvis/agentic_ide/file_search.py b/jarvis/agentic_ide/file_search.py
index 5bd291f28c..d12e550d82 100644
--- a/jarvis/agentic_ide/file_search.py
+++ b/jarvis/agentic_ide/file_search.py
@@ -43,6 +43,12 @@ MAX_MATCHES = 2000
MAX_SEARCH_BYTES = 1024 * 1024
#: Wall-clock budget for one search.
SEARCH_BUDGET_S = 8.0
+#: Lines longer than this are skipped by a regular-expression search: a
+#: backtracking pattern on a minified megabyte line could hold the server.
+MAX_REGEX_LINE = 4000
+#: One line, a line ending included (only CRLF, CR and LF end a line, as in
+#: the editor, so line numbers agree with what it shows).
+_LINE = re.compile(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+$")
_PREVIEW_CHARS = 240
@@ -62,9 +68,50 @@ class _FileHits:
matches: list[dict[str, object]] = field(default_factory=list)
+def _repeats(tree: object, inside_repeat: bool = False) -> bool:
+ r"""True when a variably repeated group contains an unbounded repeat.
+
+ ``(a+)+``, ``(\w*)*`` and ``(a|b+)*`` backtrack exponentially in Python's
+ ``re``, which has no timeout and holds the interpreter lock while it runs.
+ ``(\d{2})+`` or ``(?:x+)?`` are fine and pass.
+ """
+ from re import _constants as constants # noqa: PLC0415 — stdlib internals, parse only
+
+ for op, value in tree: # type: ignore[attr-defined]
+ if op in (constants.MAX_REPEAT, constants.MIN_REPEAT):
+ low, high, body = value
+ unbounded = high is constants.MAXREPEAT
+ variable = unbounded or (high > 1 and low != high)
+ if unbounded and inside_repeat:
+ return True
+ if _repeats(body, inside_repeat or variable):
+ return True
+ elif op is constants.SUBPATTERN:
+ if _repeats(value[-1], inside_repeat):
+ return True
+ elif op is constants.BRANCH:
+ if any(_repeats(branch, inside_repeat) for branch in value[1]):
+ return True
+ return False
+
+
+def _risky(pattern: str) -> bool:
+ try:
+ from re import _parser as parser # noqa: PLC0415 — stdlib internals, parse only
+
+ return _repeats(parser.parse(pattern))
+ except Exception: # noqa: BLE001 — an unparseable pattern fails in re.compile instead
+ return False
+
+
def _compile(options: SearchOptions) -> re.Pattern[str]:
if not options.query:
raise EditError("Type something to search for.")
+ if options.regex and _risky(options.query):
+ raise EditError(
+ "That expression repeats a repeated group, e.g. (a+)+; it could take minutes. "
+ "Simplify it, for example (a+) or a+."
+ )
pattern = options.query if options.regex else re.escape(options.query)
if options.whole_word:
pattern = rf"\b(?:{pattern})\b"
@@ -101,6 +148,9 @@ def _read_searchable(base: Path, path: str) -> str | None:
real = os.path.realpath(target)
if not real.startswith(f"{base}{os.sep}"):
return None
+ # Nor a link into git's own database, which the editor refuses as well.
+ if any(part.lower() == ".git" for part in Path(real[len(str(base)) + 1 :]).parts):
+ return None
try:
if target.stat().st_size > MAX_SEARCH_BYTES:
return None
@@ -145,8 +195,14 @@ def search_workspace(root: str | os.PathLike[str], options: SearchOptions) -> di
continue
searched += 1
hits: _FileHits | None = None
- for number, line in enumerate(text.splitlines(keepends=True), start=1):
- for match in pattern.finditer(line):
+ for number, found in enumerate(_LINE.finditer(text), start=1):
+ line = found.group(0)
+ if options.regex and len(line) > MAX_REGEX_LINE:
+ continue
+ if time.monotonic() > deadline:
+ truncated = True
+ break
+ for match in pattern.finditer(line.rstrip("\r\n")):
if match.end() == match.start():
continue # an empty match marks nothing
if hits is None:
@@ -197,6 +253,35 @@ def _template(replacement: str, *, regex: bool) -> str:
return re.sub(r"\$(\$|&|\d+)", group, replacement)
+def _replace_lines(
+ pattern: re.Pattern[str], template: str, text: str, *, regex: bool
+) -> tuple[str, int]:
+ """Replace line by line, exactly the matches the search listed.
+
+ A pattern then never spans a line break, ``^``/``$`` mean a line's start
+ and end, empty matches are left alone, and a line the search skipped for
+ its length is skipped here too.
+ """
+ count = 0
+
+ def one(match: re.Match[str]) -> str:
+ nonlocal count
+ if match.end() == match.start():
+ return match.group(0)
+ count += 1
+ return match.expand(template)
+
+ out: list[str] = []
+ for found in _LINE.finditer(text):
+ line = found.group(0)
+ body = line.rstrip("\r\n")
+ if regex and len(line) > MAX_REGEX_LINE:
+ out.append(line)
+ continue
+ out.append(pattern.sub(one, body) + line[len(body) :])
+ return "".join(out), count
+
+
def replace_in_files(
root: str | os.PathLike[str],
options: SearchOptions,
@@ -209,16 +294,26 @@ def replace_in_files(
writing, is reported back instead of being written.
"""
pattern = _compile(options)
+ template = _template(replacement, regex=options.regex)
replaced_files: list[str] = []
skipped: list[dict[str, str]] = []
total = 0
+ deadline = time.monotonic() + SEARCH_BUDGET_S * 2
+ seen: set[str] = set()
for path in paths:
+ key = os.path.normcase(path.replace("\\", "/"))
+ if key in seen:
+ continue # the same file twice would be replaced twice
+ seen.add(key)
+ if time.monotonic() > deadline:
+ skipped.append({"path": path, "reason": "out of time"})
+ continue
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)
+ new_text, count = _replace_lines(pattern, template, loaded.text, regex=options.regex)
if count == 0:
continue
write_text_file(
diff --git a/jarvis/agentic_ide/python_intel.py b/jarvis/agentic_ide/python_intel.py
index 2b90bae2c7..2048baad7e 100644
--- a/jarvis/agentic_ide/python_intel.py
+++ b/jarvis/agentic_ide/python_intel.py
@@ -2,9 +2,16 @@
Jedi reads the editor's live buffer together with the workspace on disk, so a
completion after ``from jarvis.core import `` lists that package's names and a
-definition can lead into another workspace file. It analyses statically —
-nothing in the workspace is imported or run — and its helper process for
-compiled modules starts without a console window on Windows.
+definition can lead into another workspace file. Workspace source is only
+parsed, never imported or run; compiled extensions found in the workspace are
+not loaded either (``load_unsafe_extensions=False``), so a cloned repository
+cannot run native code through a completion. Jedi's helper process for the
+interpreter's own compiled modules starts without a console window on Windows.
+
+Every request runs on one dedicated worker thread: jedi's caches are not
+thread-safe, and a burst of hovers must not occupy the shared thread pool that
+saves and searches use. When requests pile up, the newest ones get an empty
+answer at once instead of queueing behind stale ones.
Jedi is imported lazily: nothing here touches the boot path (AP-26), and a
machine without it answers with empty results instead of an error.
@@ -13,7 +20,10 @@ machine without it answers with empty results instead of an error.
from __future__ import annotations
import os
+import re
import threading
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
from pathlib import Path
from typing import Any
@@ -21,14 +31,41 @@ from loguru import logger
from .file_editing import EditError, _resolve
-__all__ = ["complete", "definitions", "hover"]
+__all__ = ["complete", "definitions", "hover", "submit"]
#: Completions returned for one request; Monaco filters further as you type.
MAX_COMPLETIONS = 300
_HOVER_DOC_CHARS = 4000
+#: Requests waiting or running before new ones are answered empty.
+MAX_PENDING = 3
+_LINE_BREAK = re.compile(r"\r\n|\r|\n")
+
_projects: dict[str, Any] = {}
_lock = threading.Lock()
+_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="python-intel")
+_pending = 0
+
+
+def submit(fn: Callable[..., Any], *args: Any, empty: Any) -> Future[Any]:
+ """Run one lookup on the worker thread, or answer ``empty`` when it is busy."""
+ global _pending
+ with _lock:
+ if _pending >= MAX_PENDING:
+ done: Future[Any] = Future()
+ done.set_result(empty)
+ return done
+ _pending += 1
+
+ def run() -> Any:
+ global _pending
+ try:
+ return fn(*args)
+ finally:
+ with _lock:
+ _pending -= 1
+
+ return _executor.submit(run)
def _jedi() -> Any | None:
@@ -50,15 +87,18 @@ def _script(root: str | os.PathLike[str], path: str, text: str) -> tuple[Any, Pa
with _lock:
project = _projects.get(key)
if project is None:
- # The workspace is the import root, so its own packages resolve.
- project = jedi.Project(path=str(base), added_sys_path=[str(base)])
+ # The workspace is the import root (smart_sys_path), so its own
+ # packages resolve; its compiled extensions are never loaded.
+ project = jedi.Project(path=str(base), load_unsafe_extensions=False)
_projects[key] = project
return jedi.Script(code=text, path=str(target), project=project), base
def _position(text: str, line: int, column: int) -> tuple[int, int]:
"""Monaco's 1-based line/column as jedi's 1-based line, 0-based column, clamped."""
- lines = text.splitlines() or [""]
+ # Only CRLF, CR and LF end a line, as in the editor (splitlines() would
+ # also split on form feeds and drop a trailing empty line).
+ lines = _LINE_BREAK.split(text)
line = max(1, min(line, len(lines)))
current = lines[line - 1] if line - 1 < len(lines) else ""
return line, max(0, min(column - 1, len(current)))
diff --git a/jarvis/ui/macos_editor_keys.py b/jarvis/ui/macos_editor_keys.py
index b6a51a16dd..fe378dc4c9 100644
--- a/jarvis/ui/macos_editor_keys.py
+++ b/jarvis/ui/macos_editor_keys.py
@@ -7,9 +7,12 @@ editor, Cmd+W means "close this tab" (as Ctrl+W does on Windows and Linux), and
closing the whole Jarvis window instead is the opposite of what was asked.
This module wraps the host's ``keyDown_`` so Cmd+W goes to the web content
-like any other key; every other shortcut keeps pywebview's handling. Cmd+Z is
-left alone on purpose: pywebview sends it to the native undo manager, which
-WebKit turns into an ``historyUndo`` input event the editor already honours.
+like any other key; every other shortcut keeps pywebview's handling. When no
+editor tab takes the shortcut, the page posts ``"close-window"`` to the
+``jarvisWindow`` script-message handler registered here, and the window
+closes as before. Cmd+Z is left alone on purpose: pywebview sends it to the
+native undo manager, which WebKit turns into an ``historyUndo`` input event
+the editor already honours.
macOS only. On every other platform, or when the pywebview/AppKit internals
are not what this expects, installing is a logged no-op — the shortcut then
@@ -25,10 +28,13 @@ from typing import Any
log = logging.getLogger(__name__)
-__all__ = ["install_macos_editor_keys", "page_owns_shortcut"]
+__all__ = ["MESSAGE_HANDLER", "install_macos_editor_keys", "page_owns_shortcut"]
#: Command shortcuts the page handles itself instead of the window.
_PAGE_KEYS = frozenset({"w"})
+#: Script-message handler the page uses to hand Cmd+W back to the window.
+MESSAGE_HANDLER = "jarvisWindow"
+_CLOSE_MESSAGE = "close-window"
def page_owns_shortcut(command: bool, characters: str) -> bool:
@@ -42,16 +48,46 @@ def install_macos_editor_keys() -> bool:
return False
try:
import AppKit # type: ignore[import-not-found, import-untyped] # noqa: N813, PLC0415
+ import objc # type: ignore[import-not-found, import-untyped] # noqa: PLC0415
import webview.platforms.cocoa as cocoa # type: ignore[import-untyped] # noqa: PLC0415
except Exception as exc: # noqa: BLE001 — optional desktop internals absent
log.warning("macos_editor_keys: WKWebView host unavailable (%s)", exc)
return False
- host_class = cocoa.BrowserView.WebKitHost
+ browser_class = cocoa.BrowserView
+ host_class = browser_class.WebKitHost
if getattr(host_class, "_jarvis_editor_keys_installed", False):
return True
try:
original_key_down = host_class.keyDown_
+ original_browser_init = browser_class.__init__
+ script_message_protocol = objc.protocolNamed("WKScriptMessageHandler")
+
+ class JarvisWindowMessageHandler( # type: ignore[call-arg] # noqa: D101
+ AppKit.NSObject,
+ protocols=[script_message_protocol],
+ ):
+ def userContentController_didReceiveScriptMessage_(
+ self, _controller: Any, message: Any
+ ) -> None:
+ try:
+ if str(message.body()) != _CLOSE_MESSAGE:
+ return
+ window = message.webView().window()
+ if window is not None:
+ window.performClose_(None)
+ except Exception: # noqa: BLE001 — never raise on AppKit's thread
+ log.exception("macos_editor_keys: close request failed")
+
+ def _patched_browser_init(self: Any, window: Any) -> None:
+ original_browser_init(self, window)
+ try:
+ handler = JarvisWindowMessageHandler.alloc().init()
+ controller = self.webview.configuration().userContentController()
+ controller.addScriptMessageHandler_name_(handler, MESSAGE_HANDLER)
+ self._jarvis_window_message_handler = handler
+ except Exception: # noqa: BLE001 — window creation must still succeed
+ log.exception("macos_editor_keys: close handler registration failed")
def _patched_key_down(self: Any, event: Any) -> Any:
try:
@@ -65,7 +101,9 @@ def install_macos_editor_keys() -> bool:
return original_key_down(self, event)
host_class.keyDown_ = _patched_key_down # type: ignore[method-assign]
+ browser_class.__init__ = _patched_browser_init # type: ignore[method-assign]
host_class._jarvis_editor_keys_original = original_key_down
+ browser_class._jarvis_editor_keys_original_init = original_browser_init # type: ignore[attr-defined]
host_class._jarvis_editor_keys_installed = True
except Exception as exc: # noqa: BLE001 — pywebview internals changed
log.warning("macos_editor_keys: could not route Cmd+W to the page (%s)", exc)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index c2978cccc5..b6224e2de6 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -2261,8 +2261,13 @@ async def python_intel(
"hover": python_intel_module.hover,
"definition": python_intel_module.definitions,
}[action]
+ empty: object = None if action == "hover" else []
try:
- result = await asyncio.to_thread(handler, folder, req.path, req.text, req.line, req.column)
+ result = await asyncio.wrap_future(
+ python_intel_module.submit(
+ handler, folder, req.path, req.text, req.line, req.column, empty=empty
+ )
+ )
except file_editing.EditError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"workspace_id": workspace_id, "result": result}
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index 8db5b83d2a..7ac2062199 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -25,6 +25,7 @@ import { ToastLayer } from "@/components/ToastLayer";
import { CommandActivityLayer } from "@/components/CommandActivityLayer";
import { AppshotEditorHost } from "@/components/appshot/AppshotEditorHost";
import { EditContextMenu } from "@/components/EditContextMenu";
+import { useMacWindowCloseFallback } from "@/lib/macWindowClose";
/*
Lazy on purpose. The overlay pulls in the dialog primitives, the keyboard
layout table and the keybind hook — none of which anything needs before
@@ -151,6 +152,7 @@ export default function App() {
return () => window.removeEventListener("keydown", onKeyDown, true);
}, [switcherEnabled, switcherCombo]);
+ useMacWindowCloseFallback();
useWebSocket();
useBrainStatus();
useVoiceStatus();
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
index 16edd0b2e1..1935df1231 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
@@ -180,8 +180,30 @@ function toast(message: string): void {
// ---- Hot exit: unsaved text survives closing the app ----------------------
/** How long typing has to pause before the unsaved text is backed up. */
-const BACKUP_DELAY_MS = 600;
+const BACKUP_DELAY_MS = 400;
+/**
+ * Browsers cap a keepalive request body (about 64 KB). A larger buffer is
+ * still sent while the window closes, without keepalive: best effort.
+ */
+const KEEPALIVE_MAX_CHARS = 60_000;
const backupTimers = new Map<string, number>();
+/**
+ * Backup writes and deletes of one file run strictly one after another. Sent
+ * independently, a PUT issued just before a save could land after the save's
+ * DELETE and bring a stale backup back after the next restart.
+ */
+const backupChains = new Map<string, Promise<void>>();
+
+function inOrder(fileKey: string, task: () => Promise<void>): void {
+ const previous = backupChains.get(fileKey) ?? Promise.resolve();
+ const next = previous.then(task, task).catch((error: unknown) => {
+ console.warn("Editor backup request failed:", (error as Error).message);
+ });
+ backupChains.set(fileKey, next);
+ void next.finally(() => {
+ if (backupChains.get(fileKey) === next) backupChains.delete(fileKey);
+ });
+}
/** Files that have a backup on the server, so a clean buffer knows to drop it. */
const backedUp = new Set<string>();
/** Backups from last run, laid over their file when it loads. */
@@ -199,11 +221,11 @@ function sendBackup(fileKey: string, keepalive = false): void {
if (!file || !entry) return;
if (file.dirty) {
backedUp.add(fileKey);
- void putEditorBackup(
- file.workspaceId,
- { path: file.path, text: entry.model.getValue(), base_version: file.version, encoding: file.encoding },
- keepalive,
- ).catch((error: unknown) => console.warn("Editor backup failed:", (error as Error).message));
+ const backup = { path: file.path, text: entry.model.getValue(), base_version: file.version, encoding: file.encoding };
+ const send = () => putEditorBackup(file.workspaceId, backup, keepalive && backup.text.length <= KEEPALIVE_MAX_CHARS);
+ // While the window closes there is no later turn to wait for: send now.
+ if (keepalive) void send().catch((error: unknown) => console.warn("Editor backup failed:", (error as Error).message));
+ else inOrder(fileKey, send);
} else {
forgetBackup(fileKey);
}
@@ -219,9 +241,8 @@ function forgetBackup(fileKey: string, file = store().files[fileKey]): void {
window.clearTimeout(backupTimers.get(fileKey));
backupTimers.delete(fileKey);
if (!backedUp.delete(fileKey) || !file) return;
- void deleteEditorBackup(file.workspaceId, file.path).catch((error: unknown) =>
- console.warn("Editor backup cleanup failed:", (error as Error).message),
- );
+ const { workspaceId, path } = file;
+ inOrder(fileKey, () => deleteEditorBackup(workspaceId, path));
}
/** Send every backup still waiting for its typing pause, now (the window is closing). */
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/lineDiff.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/lineDiff.ts
index 11363213c9..12d59cf48e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/lineDiff.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/lineDiff.ts
@@ -18,7 +18,9 @@ export interface GutterChange {
}
/** More differences than this and no markers are drawn. */
-export const MAX_EDIT_DISTANCE = 4000;
+export const MAX_EDIT_DISTANCE = 1000;
+/** Files longer than this (both sides together) get no markers. */
+export const MAX_DIFF_LINES = 20_000;
const splitLines = (text: string) => text.split(/\r\n|\r|\n/);
@@ -85,6 +87,7 @@ export function gutterChanges(base: string, current: string): GutterChange[] | n
if (base === current) return [];
const a = splitLines(base);
const b = splitLines(current);
+ if (a.length + b.length > MAX_DIFF_LINES) return null;
const steps = editScript(a, b);
if (!steps) return null;
const changes: GutterChange[] = [];
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
index bc5d36ae5c..2cc92a8c82 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/search/SearchPanel.tsx
@@ -54,7 +54,10 @@ export function SearchPanel() {
const [regex, setRegex] = useState(false);
const [include, setInclude] = useState("");
const [exclude, setExclude] = useState("");
+ // The answer and the search it answers: Replace all only acts on the
+ // result of exactly the search on screen.
const [result, setResult] = useState<SearchResult | null>(null);
+ const [resultKey, setResultKey] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
@@ -78,10 +81,12 @@ export function SearchPanel() {
return () => window.removeEventListener(SEARCH_FOCUS_EVENT, focus);
}, []);
+ const searchKey = JSON.stringify(search);
useEffect(() => {
setConfirming(false);
if (!workspaceId || !search.query) {
setResult(null);
+ setResultKey("");
setError("");
return;
}
@@ -91,6 +96,7 @@ export function SearchPanel() {
searchWorkspace(workspaceId, search, controller.signal)
.then((answer) => {
setResult(answer);
+ setResultKey(JSON.stringify(search));
setError("");
})
.catch((err: unknown) => {
@@ -111,8 +117,9 @@ export function SearchPanel() {
const open = (path: string, line: number, column: number, length: number) =>
useCodeEditorStore.getState().openFile(workspaceId, path, { line, column, length });
+ const replaceReady = !!result && resultKey === searchKey && !result.truncated && result.match_count > 0;
const runReplace = async () => {
- if (!result) return;
+ if (!result || !replaceReady) 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.
@@ -206,9 +213,9 @@ export function SearchPanel() {
<button
type="button"
data-testid="ide-search-replace-all"
- disabled={!result?.match_count || busy}
+ disabled={!replaceReady || busy}
+ title={result?.truncated ? t("ide_side_panel.search.replace_truncated") : t("ide_side_panel.search.replace_all")}
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",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index d513c04304..3714f72ec2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -6295,6 +6295,7 @@
"toggle_replace": "Ersetzen ein- oder ausblenden",
"replace_all": "Alle ersetzen",
"replace_confirm": "{count} in {files} Dateien ersetzen?",
+ "replace_truncated": "Es wird nur ein Teil der Treffer gezeigt; grenze die Suche ein, bis alle aufgelistet sind, um sie zu ersetzen.",
"filters": "Dateien ein- oder ausschließen",
"include": "Einschließen, z. B. *.py, src",
"exclude": "Ausschließen, z. B. tests, *.min.js",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 3c2f80244a..f61a353b60 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6295,6 +6295,7 @@
"toggle_replace": "Show or hide replace",
"replace_all": "Replace all",
"replace_confirm": "Replace {count} in {files} files?",
+ "replace_truncated": "Only part of the results is shown; narrow the search until all are listed to replace them.",
"filters": "Files to include or exclude",
"include": "Files to include, e.g. *.py, src",
"exclude": "Files to exclude, e.g. tests, *.min.js",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index f283edd56d..e630add672 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -6295,6 +6295,7 @@
"toggle_replace": "Mostrar u ocultar reemplazar",
"replace_all": "Reemplazar todo",
"replace_confirm": "¿Reemplazar {count} en {files} archivos?",
+ "replace_truncated": "Solo se muestra parte de los resultados; acota la búsqueda hasta ver todos para reemplazarlos.",
"filters": "Archivos a incluir o excluir",
"include": "Incluir, p. ej. *.py, src",
"exclude": "Excluir, p. ej. tests, *.min.js",
diff --git a/jarvis/ui/web/frontend/src/lib/macWindowClose.ts b/jarvis/ui/web/frontend/src/lib/macWindowClose.ts
new file mode 100644
index 0000000000..86cf3777cc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/macWindowClose.ts
@@ -0,0 +1,33 @@
+import { useEffect } from "react";
+
+/**
+ * macOS desktop app: Cmd+W reaches the page (jarvis/ui/macos_editor_keys.py)
+ * so the code editor can close a tab with it. When nothing in the page took
+ * the shortcut, hand it back to the native window, which closes as before.
+ *
+ * A no-op everywhere else: the message handler only exists in the macOS
+ * WKWebView host.
+ */
+interface WindowMessageHandler {
+ postMessage: (message: string) => void;
+}
+
+function nativeWindowHandler(): WindowMessageHandler | undefined {
+ const webkit = (window as unknown as { webkit?: { messageHandlers?: Record<string, WindowMessageHandler> } }).webkit;
+ return webkit?.messageHandlers?.jarvisWindow;
+}
+
+export function useMacWindowCloseFallback(): void {
+ useEffect(() => {
+ if (!nativeWindowHandler()) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
+ if (event.key.toLowerCase() !== "w" || event.defaultPrevented) return;
+ nativeWindowHandler()?.postMessage("close-window");
+ };
+ // Bubble phase: the editor's own capture-phase handler runs first and
+ // prevents the default when it closed a tab.
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+}
diff --git a/tests/unit/agentic_ide/test_editor_backups.py b/tests/unit/agentic_ide/test_editor_backups.py
index c1ab50465f..3ada602836 100644
--- a/tests/unit/agentic_ide/test_editor_backups.py
+++ b/tests/unit/agentic_ide/test_editor_backups.py
@@ -68,8 +68,19 @@ def test_a_damaged_backup_is_skipped_not_fatal(tmp_path: Path, store: Path) -> N
def test_paths_are_validated(tmp_path: Path) -> None:
with pytest.raises(EditError):
editor_backups.save_backup(tmp_path, "../x", "t", base_version=None, encoding="utf-8")
- with pytest.raises(EditError):
- editor_backups.save_tabs(tmp_path, [{"path": ".git/config"}], None)
+ # One unusable tab is dropped; the others are still remembered.
+ editor_backups.save_tabs(tmp_path, [{"path": ".git/config"}, {"path": "ok.py"}], ".git/x")
+ state = editor_backups.load_state(tmp_path)
+ assert [tab["path"] for tab in state["tabs"]] == ["ok.py"]
+ assert state["active"] is None
+
+
+def test_old_backups_are_pruned(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ editor_backups.save_backup(tmp_path, "old.py", "x", base_version=None, encoding="utf-8")
+ monkeypatch.setattr(editor_backups, "MAX_BACKUP_AGE_S", -1)
+ assert editor_backups.load_state(tmp_path)["backups"] == []
+ monkeypatch.setattr(editor_backups, "MAX_BACKUP_AGE_S", 3600)
+ assert editor_backups.load_state(tmp_path)["backups"] == [] # deleted, not just hidden
async def test_routes_store_and_return_state(
diff --git a/tests/unit/agentic_ide/test_file_search.py b/tests/unit/agentic_ide/test_file_search.py
index 7f2d69bc39..d50440bb71 100644
--- a/tests/unit/agentic_ide/test_file_search.py
+++ b/tests/unit/agentic_ide/test_file_search.py
@@ -120,3 +120,37 @@ def test_search_reads_legacy_encodings_like_the_editor(project: Path) -> None:
("legacy.txt", 2),
("legacy.txt", 3),
]
+
+
+def test_catastrophic_regex_is_refused_but_ordinary_repeats_pass(project: Path) -> None:
+ with pytest.raises(EditError, match="repeats a repeated group"):
+ search_workspace(project, SearchOptions("(a+)+$", regex=True))
+ assert (
+ search_workspace(project, SearchOptions(r"(\d{2})+|hel+o", regex=True))["match_count"] >= 1
+ )
+
+
+def test_replace_changes_exactly_what_search_listed(project: Path) -> None:
+ (project / "lines.txt").write_text("foo one\nfoo two\nbar\n", encoding="utf-8")
+
+ listed = search_workspace(project, SearchOptions("^foo", regex=True, include="lines.txt"))
+ answer = replace_in_files(
+ project, SearchOptions("^foo", regex=True), "baz", ["lines.txt", "lines.txt"]
+ )
+
+ assert listed["match_count"] == answer["replacements"] == 2
+ assert (project / "lines.txt").read_text("utf-8") == "baz one\nbaz two\nbar\n"
+ # An empty match marks nothing, so it replaces nothing either.
+ assert (
+ replace_in_files(project, SearchOptions("x*", regex=True), "!", ["lines.txt"])[
+ "replacements"
+ ]
+ == 0
+ )
+ assert (project / "lines.txt").read_text("utf-8") == "baz one\nbaz two\nbar\n"
+
+
+def test_line_numbers_count_only_real_line_breaks(project: Path) -> None:
+ (project / "ff.txt").write_text("a\x0cb\nneedle\n", encoding="utf-8")
+ hits = _hits(search_workspace(project, SearchOptions("needle")))
+ assert ("ff.txt", 2, 1) in hits
diff --git a/tests/unit/agentic_ide/test_python_intel.py b/tests/unit/agentic_ide/test_python_intel.py
index 44d4da7801..788ddec48b 100644
--- a/tests/unit/agentic_ide/test_python_intel.py
+++ b/tests/unit/agentic_ide/test_python_intel.py
@@ -58,3 +58,9 @@ async def test_route_answers_each_action(project: Path, monkeypatch: pytest.Monk
answer = await routes.python_intel("w1", "definition", request)
assert answer["result"] == [{"path": "pkg/util.py", "line": 1, "column": 5}]
+
+
+def test_a_busy_worker_answers_new_requests_empty(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(python_intel, "MAX_PENDING", 0)
+ future = python_intel.submit(lambda: ["never"], empty=[])
+ assert future.result(timeout=1) == []