refactor(tools): unify edit summaries with shared fast diffs

Return compact, workspace-relative summaries from edit_file and apply_patch.
Compute one RapidFuzz line alignment per file and reuse it for summary counts
and WebUI unified diffs, checking snapshots before reuse. Summarize batched
edits by their final file state.

Warn only when a recorded file version changed, without asking for a read
after an edit has already succeeded. Preserve existing edit errors.

Validate summary and activity reuse, repetitive files, diff formatting,
snapshot changes, file creation, and read-state behavior.
This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-15 11:25:01 +08:00
1 parent 3a725b35a7
commit 1c3c68262f
13 files changed
+346 -170

No files matched your search

+81
View File
@@ -1,10 +1,16 @@
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
import pytest
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.agent.tools.filesystem import EditFileTool, WriteFileTool
from nanobot.utils.file_edit_events import (
FileDiff,
FileEditResult,
build_file_edit_end_event,
build_file_edit_start_event,
build_unified_diff_payload,
@@ -39,6 +45,81 @@ def test_line_diff_stats_counts_new_file_crlf_lines_once() -> None:
assert line_diff_stats("", "a\r\nb\r\n") == (2, 0)
@pytest.mark.parametrize("position", [0, 3000, 6000])
@pytest.mark.parametrize(
("before_text", "after_text", "expected"),
[("old\n", "new\n", (1, 1)), ("", "new\n", (1, 0)), ("old\n", "", (0, 1))],
)
def test_line_diff_stats_small_edit_in_repeated_lines(
position: int, before_text: str, after_text: str, expected: tuple[int, int],
) -> None:
prefix = "same\n" * position
suffix = "same\n" * (6000 - position)
assert line_diff_stats(prefix + before_text + suffix, prefix + after_text + suffix) == expected
def test_sparse_edits_in_repeated_lines_have_compact_diff() -> None:
middle = "same,0\n" * 6000
before = "obsolete,1\n" + middle + "obsolete,2\n"
after = "current,1\n" + middle + "current,2\n"
assert line_diff_stats(before, after) == (2, 2)
payload = build_unified_diff_payload(before, after)
assert payload is not None and not payload["truncated"]
body = payload["text"].splitlines()[2:]
assert sum(line.startswith("@@") for line in body) == 2
assert sum(line.startswith("+") for line in body) == 2
assert sum(line.startswith("-") for line in body) == 2
assert body.count(" same,0") == 6
@pytest.mark.parametrize(("before", "after", "expected"), [
("", "new\n", "@@ -0,0 +1 @@\n+new"),
("old\n", "", "@@ -1 +0,0 @@\n-old"),
("keep\n", "keep\nnew\n", "@@ -1,0 +2 @@\n+new"),
("keep\nold\n", "keep\n", "@@ -2 +1,0 @@\n-old"),
])
def test_unified_diff_empty_ranges(before: str, after: str, expected: str) -> None:
payload = build_unified_diff_payload(before, after, context_lines=0)
assert payload is not None
assert payload["text"] == "--- before\n+++ after\n" + expected
@pytest.mark.parametrize("gap", [0, 5, 6, 7])
def test_unified_diff_groups_changes_by_context(gap: int) -> None:
middle = "".join(f"keep {i}\n" for i in range(gap))
payload = build_unified_diff_payload("old\n" + middle + "old\n", "new\n" + middle + "new\n")
assert payload is not None
assert payload["text"].count("@@ -") == (2 if gap > 6 else 1)
def test_file_edit_result_copies_and_serializes_only_observation(tmp_path: Path) -> None:
result = FileEditResult("Patch applied", {tmp_path: FileDiff.from_text("old", "new")})
assert type(deepcopy(result)) is str
assert json.loads(json.dumps({"content": result})) == {"content": "Patch applied"}
assert result.file_diffs
@pytest.mark.asyncio
@pytest.mark.parametrize("changed_state", ["before", "after"])
async def test_activity_recomputes_diff_when_snapshots_changed(tmp_path: Path, changed_state: str) -> None:
target = tmp_path / "notes.txt"
target.write_text("old\n", encoding="utf-8")
tool = _edit_tool(tmp_path)
params = {"path": "notes.txt", "old_text": "old", "new_text": "new"}
[tracker] = prepare_file_edit_trackers(
call_id="call-edit", tool_name="edit_file", tool=tool, workspace=tmp_path, params=params,
)
if changed_state == "before":
target.write_text("old\nexternal\n", encoding="utf-8")
result = await tool.execute(**params)
assert isinstance(result, FileEditResult)
if changed_state == "after":
target.write_text("new\nexternal\n", encoding="utf-8")
event = build_file_edit_end_event(tracker, diff=result.file_diffs[target.resolve()])
assert (event["added"], event["deleted"]) == (2, 1)
assert "+external" in event["diff"]["text"]
def test_write_file_start_tracks_snapshot_and_end_emits_exact_diff(tmp_path: Path) -> None:
target = tmp_path / "notes.txt"
target.write_text("old\nkeep\n", encoding="utf-8")