From 624a64a152a882ec41ba133508589dea47cdf6dc Mon Sep 17 00:00:00 2001 From: Hyeonsang Cho Date: Tue, 24 Nov 2026 12:21:33 +0900 Subject: [PATCH] fix(sandbox): show virtual paths in local grep match lines (#8556) * fix(sandbox): show virtual paths in local grep match lines LocalSandbox.write_file stores host paths in code files so a script runs under a host interpreter. grep translated the match path back to a virtual path but returned the matched line as stored, so every grep hit in such a file showed the host path, including the user's home directory and the thread directory. find_grep_matches gains a display_line hook that rewrites a matched line before it is shortened, and LocalSandbox passes its reverse path resolution for both the mount walk and the regular walk. The pattern still matches the stored text. * fix(sandbox): keep grep line paths spelled as stored The output path scanner stops at punctuation such as ':' and '(' that can belong to one filename. Reverse resolution canonicalized the cut-off prefix, so an unrelated symlink there (cache -> data) turned a stored reference to cache:old.txt into data:old.txt, a file that does not exist. Matched grep lines now replace each mount's host root with its virtual path and keep the tail verbatim, which is what the line says. Bash output and read_file keep their existing reverse resolution. --- .../deerflow/sandbox/local/local_sandbox.py | 17 +++++ .../harness/deerflow/sandbox/search.py | 9 ++- ...est_local_sandbox_virtual_path_contract.py | 70 +++++++++++++++++++ docs/guide/sandbox.md | 2 +- 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py b/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py index a40a05e022..fcbdd3c752 100644 --- a/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py +++ b/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py @@ -1488,6 +1488,21 @@ class LocalSandbox(Sandbox): raise type(e)(e.errno, e.strerror, filename, getattr(e, "winerror", None), filename2) from None return [self._reverse_resolve_path(match) for match in matches], truncated + def _grep_line_with_virtual_paths(self, line: str) -> str: + """Show the mount roots in a matched line as virtual paths, spelled as stored. + + write_file stores host paths in code files. Matched lines show virtual + paths for every file, as bash output does: the record of agent-written + files that read_file consults does not survive a restart. The output + scanner stops at punctuation such as ``:`` that can belong to one + filename (``cache:old.txt``), so the tail is kept verbatim instead of + canonicalized: following an unrelated symlink at the cut-off prefix + (``cache -> data``) would name a different file (``data:old.txt``). + """ + for mapping in self._mappings_by_local_specificity: + line = replace_output_path_matches(line, self._resolved_local_paths[mapping], mapping.container_path, separator_agnostic=True) + return line + def grep( self, path: str, @@ -1513,6 +1528,7 @@ class LocalSandbox(Sandbox): max_results=max_results - len(results) + 1, relative_prefix=child, user_data=user_data, + display_line=self._grep_line_with_virtual_paths, ) results.extend(GrepMatch(path=f"{path.rstrip('/')}/{child}/{Path(match.path).relative_to(root).as_posix()}", line_number=match.line_number, line=match.line) for match in matches) if len(results) > max_results: @@ -1527,6 +1543,7 @@ class LocalSandbox(Sandbox): case_sensitive=case_sensitive, max_results=max_results, user_data=user_data, + display_line=self._grep_line_with_virtual_paths, ) except OSError as e: if e.filename is None: diff --git a/backend/packages/harness/deerflow/sandbox/search.py b/backend/packages/harness/deerflow/sandbox/search.py index 70bb77e50f..592d89dd9e 100644 --- a/backend/packages/harness/deerflow/sandbox/search.py +++ b/backend/packages/harness/deerflow/sandbox/search.py @@ -310,7 +310,14 @@ def find_grep_matches( line_summary_length: int = DEFAULT_LINE_SUMMARY_LENGTH, relative_prefix: str = "", user_data: bool = False, + display_line: Callable[[str], str] | None = None, ) -> tuple[list[GrepMatch], bool]: + """Search text files under ``root``. + + ``display_line`` rewrites a matched line for the caller before it is + shortened to ``line_summary_length``; the pattern still matches the stored + text. Rewriting after shortening could leave a cut-off fragment behind. + """ matches: list[GrepMatch] = [] truncated = False root = root.resolve() @@ -391,7 +398,7 @@ def find_grep_matches( GrepMatch( path=str(file_path), line_number=line_number, - line=truncate_line(line, line_summary_length), + line=truncate_line(display_line(line) if display_line is not None else line, line_summary_length), ) ) if len(matches) >= max_results: diff --git a/backend/tests/test_local_sandbox_virtual_path_contract.py b/backend/tests/test_local_sandbox_virtual_path_contract.py index 51239a79cf..4875e6340d 100644 --- a/backend/tests/test_local_sandbox_virtual_path_contract.py +++ b/backend/tests/test_local_sandbox_virtual_path_contract.py @@ -17,6 +17,7 @@ shim required. from __future__ import annotations +import os from pathlib import Path from types import SimpleNamespace from unittest.mock import patch @@ -24,7 +25,9 @@ from unittest.mock import patch import pytest from deerflow.config.sandbox_config import SandboxConfig +from deerflow.sandbox.local.local_sandbox import LocalSandbox from deerflow.sandbox.local.local_sandbox_provider import LocalSandboxProvider +from deerflow.sandbox.search import truncate_line def _build_config(skills_dir: Path) -> SimpleNamespace: @@ -128,6 +131,73 @@ def test_grep_with_virtual_path(provider): assert matches[0].path.endswith("/mnt/user-data/workspace/findme.txt") +def _host_dir(sbx, container_path: str) -> str: + return os.path.realpath(next(m.local_path for m in sbx.path_mappings if m.container_path == container_path)) + + +def test_grep_lines_show_virtual_paths_that_write_file_stored_as_host_paths(provider): + sbx = provider.get(provider.acquire("alpha")) + host_workspace = _host_dir(sbx, "/mnt/user-data/workspace") + sbx.write_file("/mnt/user-data/workspace/run.py", 'DATA = "/mnt/user-data/workspace/data.csv"\n') + # Pin the scenario: a code file stores the host path on disk. + assert host_workspace in (Path(host_workspace) / "run.py").read_text() + + # A fresh sandbox over the same mounts stands in for a Gateway restart or an + # LRU eviction, which forgets which files write_file wrote. + restarted = LocalSandbox(sbx.id, path_mappings=sbx.path_mappings) + for sandbox in (sbx, restarted): + matches, _ = sandbox.grep("/mnt/user-data/workspace", "DATA =") + assert [(m.path, m.line) for m in matches] == [("/mnt/user-data/workspace/run.py", 'DATA = "/mnt/user-data/workspace/data.csv"')] + + +@pytest.mark.skipif(os.name != "posix", reason="filenames with ':' and a symlink fixture need POSIX") +def test_grep_lines_keep_filenames_that_the_path_scanner_cuts_at_punctuation(provider): + sbx = provider.get(provider.acquire("alpha")) + host_workspace = Path(_host_dir(sbx, "/mnt/user-data/workspace")) + (host_workspace / "data").mkdir() + (host_workspace / "cache:old.txt").write_text("old") + (host_workspace / "report(1).txt").write_text("report") + # Unrelated links at the prefixes the output scanner stops at. + (host_workspace / "cache").symlink_to("data") + (host_workspace / "report").symlink_to("data") + sbx.write_file("/mnt/user-data/workspace/run.py", 'OLD = "/mnt/user-data/workspace/cache:old.txt"\n') + # Pin the scenario: the stored script names the existing file. + assert f'"{host_workspace}/cache:old.txt"' in (host_workspace / "run.py").read_text() + (host_workspace / "notes.sh").write_text(f"cat {host_workspace}/report(1).txt\n") + + old, _ = sbx.grep("/mnt/user-data/workspace", "OLD =") + report, _ = sbx.grep("/mnt/user-data/workspace", "cat ") + + assert [m.line for m in old] == ['OLD = "/mnt/user-data/workspace/cache:old.txt"'] + assert [m.line for m in report] == ["cat /mnt/user-data/workspace/report(1).txt"] + + +def test_grep_line_is_shortened_after_host_paths_become_virtual(provider): + sbx = provider.get(provider.acquire("alpha")) + host_workspace = _host_dir(sbx, "/mnt/user-data/workspace") + # The host path straddles the summary cut; shortening first would keep a + # fragment of it that no longer matches a mount. + shown = f'{"#" * 150} "/mnt/user-data/workspace/data.csv" {"y" * 60}' + sbx.write_file("/mnt/user-data/workspace/long.py", shown + "\n") + assert host_workspace in (Path(host_workspace) / "long.py").read_text() + + matches, _ = sbx.grep("/mnt/user-data/workspace", "data.csv", literal=True) + + assert [m.line for m in matches] == [truncate_line(shown)] + + +def test_grep_lines_under_skill_category_mounts_show_virtual_paths(provider): + sbx = provider.get(provider.acquire("alpha")) + host_workspace = _host_dir(sbx, "/mnt/user-data/workspace") + skill_dir = Path(_host_dir(sbx, "/mnt/skills/public")) / "demo" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text(f"input: {host_workspace}/data.csv\n") + + matches, _ = sbx.grep("/mnt/skills", "input:") + + assert [(m.path, m.line) for m in matches] == [("/mnt/skills/public/demo/SKILL.md", "input: /mnt/user-data/workspace/data.csv")] + + def test_execute_command_lists_aggregate_user_data_root(provider): """``ls /mnt/user-data`` (the parent prefix itself) must list the three subdirs — matching the AIO container's natural filesystem view.""" diff --git a/docs/guide/sandbox.md b/docs/guide/sandbox.md index 24dbc51319..6792d080df 100644 --- a/docs/guide/sandbox.md +++ b/docs/guide/sandbox.md @@ -355,7 +355,7 @@ Ranged `read_file` calls count lines the same way on every sandbox provider: a l Concurrent reads and writes to the same file share a gate across synchronous and asynchronous tool calls. Async callers waiting for that gate do not occupy worker threads needed to finish the current read or write. Cancelling a waiting call leaves the current operation running; a call that already started file inspection still waits for that work to finish before releasing its gate. The built-in `grep` tool searches either one text file or all matching text files below a directory, so an agent can search an uploaded document directly without first broadening the request to the entire uploads directory. -On the local sandbox, `grep(literal=True)` also searches long lines in minified text or single-line JSON, within the existing file-size limit. Case-insensitive literal matching avoids repeated-prefix rescans while preserving Unicode case behavior. Regex searches retain their long-line safety guard. +On the local sandbox, `grep(literal=True)` also searches long lines in minified text or single-line JSON, within the existing file-size limit. Case-insensitive literal matching avoids repeated-prefix rescans while preserving Unicode case behavior. Regex searches retain their long-line safety guard. Matched lines show `/mnt/...` virtual paths where `write_file` stored host paths in a code file, spelled as stored and before the line is shortened; the pattern still matches the stored text. Across sandbox providers, returned previews show only the beginning of each matched line (200 characters by default), so a match later in a long line may not appear in the preview. Use the reported path and line number to inspect the source. The `truncated` flag concerns match-count limits, not preview length. E2B's `glob` filter preserves spaces, quotes, and dollar signs in filename patterns, while wildcard matching and root-relative directory scoping remain unchanged.