Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions computer-use-best-practices/computer_use/tools/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ def _insert(self, target: Path, insert_line: int | None, new: str | None) -> Too
insert_line = max(0, min(insert_line, len(lines)))
if new and not new.endswith("\n"):
new += "\n"
if new and insert_line > 0 and not lines[insert_line - 1].endswith("\n"):
lines[insert_line - 1] += "\n"
lines.insert(insert_line, new)
target.write_text("".join(lines), encoding="utf-8")
return ToolResult(output=f"inserted after line {insert_line} in {self._rel(target)}")
Expand Down
19 changes: 19 additions & 0 deletions computer-use-best-practices/tests/test_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,22 @@ def test_shell_shares_scratch_dir() -> None:
view = editor.execute(command="view", path="frombash.txt")
assert view.output is not None
assert "written-by-bash" in view.output


@pytest.mark.parametrize(
"before,line,expected",
[
("first", 1, "first\nsecond\n"),
("first\n", 1, "first\nsecond\n"),
("first", 0, "second\nfirst"),
("", 0, "second\n"),
],
)
def test_insert_preserves_line_boundary(
tool: EditorTool, tmp_path: Path, before: str, line: int, expected: str
) -> None:
path = tmp_path / "boundary.txt"
path.write_text(before, encoding="utf-8")
result = tool.execute(command="insert", path="boundary.txt", insert_line=line, new_str="second")
assert not result.is_error
assert path.read_text(encoding="utf-8") == expected