Skip to content

Your lightweight open-source personal agent.

fix(webui): keep edit diffs visible and distinguish file creation (#6049)

chengyongrued022e447fd6
diff --git a/nanobot/utils/file_edit_events.py b/nanobot/utils/file_edit_events.py
index 0b7287c4a..1db2135b5 100644
--- a/nanobot/utils/file_edit_events.py
+++ b/nanobot/utils/file_edit_events.py
@@ -504,7 +504,11 @@ def build_file_edit_end_event(
deleted=deleted,
approximate=False,
binary=binary,
- operation="delete" if tracker.before.exists and not after.exists else None,
+ operation=(
+ "delete" if tracker.before.exists and not after.exists
+ else "create" if not tracker.before.exists and after.exists
+ else None
+ ),
)
if diff_payload is not None:
payload["diff"] = diff_payload
diff --git a/tests/utils/test_file_edit_events.py b/tests/utils/test_file_edit_events.py
index 6eb251b03..ef6342f36 100644
--- a/tests/utils/test_file_edit_events.py
+++ b/tests/utils/test_file_edit_events.py
@@ -166,6 +166,35 @@ def test_write_file_start_tracks_snapshot_and_end_emits_exact_diff(tmp_path: Pat
assert "+extra" in diff_text
[email protected](("before", "content", "operation"), [
+ (None, "", "create"),
+ (None, "hello\n", "create"),
+ ("", "hello\n", None),
+])
+async def test_file_creation_is_distinct_from_editing_an_empty_file(
+ tmp_path: Path, before: str | None, content: str, operation: str | None,
+) -> None:
+ target = tmp_path / "new.txt"
+ if before is not None:
+ target.write_text(before, encoding="utf-8")
+ tool = _edit_tool(tmp_path)
+ params = {"path": "new.txt", "old_text": "", "new_text": content}
+ [tracker] = prepare_file_edit_trackers(
+ call_id="call-create", tool_name="edit_file", tool=tool, workspace=tmp_path,
+ params=params,
+ )
+ await tool.execute(**params)
+ assert target.read_text(encoding="utf-8") == content
+ event = build_file_edit_end_event(tracker)
+ assert event.get("operation") == operation
+ assert (event["added"], event["deleted"]) == (int(bool(content)), 0)
+ if content:
+ assert "+hello" in event["diff"]["text"]
+ else:
+ assert "diff" not in event
+
+
def test_unified_diff_payload_truncates_large_diffs() -> None:
before = "\n".join(f"old {i}" for i in range(12))
after = "\n".join(f"new {i}" for i in range(12))
diff --git a/webui/src/components/thread/AgentActivityCluster.tsx b/webui/src/components/thread/AgentActivityCluster.tsx
index b1e4d66be..957bcd918 100644
--- a/webui/src/components/thread/AgentActivityCluster.tsx
+++ b/webui/src/components/thread/AgentActivityCluster.tsx
@@ -179,7 +179,7 @@ export function AgentActivityCluster(props: AgentActivityClusterProps) {
() => summarizeFileEditsByMessage(messages, props.isTurnStreaming),
[messages, props.isTurnStreaming],
);
- if (props.expanded !== undefined || displayMode === "summary" || !editsByMessage.size) {
+ if (displayMode === "summary" || !editsByMessage.size) {
return <FoldedAgentActivity {...props} />;
}
@@ -192,6 +192,7 @@ export function AgentActivityCluster(props: AgentActivityClusterProps) {
items.push(
<FoldedAgentActivity
{...props}
+ detailsId={undefined}
key={pending[0]?.id ?? "tail-status"}
messages={pending}
isTurnStreaming={last && props.isTurnStreaming}
@@ -225,7 +226,7 @@ export function AgentActivityCluster(props: AgentActivityClusterProps) {
}
flush(true);
return (
- <div className={cn("flex w-full flex-col gap-0.5", props.hasBodyBelow && "mb-2")}>
+ <div id={props.detailsId} className={cn("flex w-full flex-col gap-0.5", props.hasBodyBelow && "mb-2")}>
{items}
</div>
);
diff --git a/webui/src/components/thread/activity/FileEditRow.tsx b/webui/src/components/thread/activity/FileEditRow.tsx
index 48147c508..8f22051b6 100644
--- a/webui/src/components/thread/activity/FileEditRow.tsx
+++ b/webui/src/components/thread/activity/FileEditRow.tsx
@@ -155,6 +155,7 @@ function fileEditAction(
const deleting = edit.operation === "delete";
if (failed) return t(`message.agentActivity.${deleting ? "deleteFileFailed" : "editFileFailedShort"}`);
if (editing) return t(`message.agentActivity.${deleting ? "deletingFile" : "editingFileShort"}`);
+ if (edit.operation === "create") return t("message.agentActivity.createdFile");
return t(`message.agentActivity.${deleting ? "deletedFile" : "editedFileShort"}`);
}
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 6757d38e0..846a6eaaa 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -2245,6 +2245,7 @@
"deletingFile": "Deleting",
"editingFileShort": "Editing",
"deletedFile": "Deleted",
+ "createdFile": "Created",
"editedFileShort": "Edited"
},
"collapseActivity": "Collapse activity details",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 8cd0fad72..17cfb13d6 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1922,7 +1922,7 @@
"copiedReply": "Copiado",
"turnLatencyTitle": "Tiempo de respuesta (extremo a extremo)",
"fileEditViewDiff": "Ver diferencias",
- "fileEditViewLargeDiff": "Ver diferencias grandes",
+ "fileEditViewLargeDiff": "Ver diferencias",
"fileEditDiffLineCount": "{{count}} líneas",
"fileEditUnchangedLinesHidden": "{{count}} líneas sin cambios ocultas",
"fileEditShowMoreLines": "Mostrar {{count}} líneas más",
@@ -2074,6 +2074,7 @@
"deletingFile": "Eliminando",
"editingFileShort": "Editando",
"deletedFile": "Eliminado",
+ "createdFile": "Creado",
"editedFileShort": "Editado"
},
"collapseActivity": "Contraer detalles de actividad",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 925561c77..e9c872cf3 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1921,7 +1921,7 @@
"copiedReply": "Copié",
"turnLatencyTitle": "Temps de réponse (de bout en bout)",
"fileEditViewDiff": "Voir les différences",
- "fileEditViewLargeDiff": "Voir les grandes différences",
+ "fileEditViewLargeDiff": "Voir les différences",
"fileEditDiffLineCount": "{{count}} lignes",
"fileEditUnchangedLinesHidden": "{{count}} lignes inchangées masquées",
"fileEditShowMoreLines": "Afficher {{count}} lignes de plus",
@@ -2073,6 +2073,7 @@
"deletingFile": "Suppression",
"editingFileShort": "Modification",
"deletedFile": "Supprimé",
+ "createdFile": "Créé",
"editedFileShort": "Modifié"
},
"collapseActivity": "Réduire les détails de l’activité",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index f530eb33d..b0ee5ab07 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1921,7 +1921,7 @@
"copiedReply": "Disalin",
"turnLatencyTitle": "Waktu respons (ujung ke ujung)",
"fileEditViewDiff": "Lihat perbedaan",
- "fileEditViewLargeDiff": "Lihat perbedaan besar",
+ "fileEditViewLargeDiff": "Lihat perbedaan",
"fileEditDiffLineCount": "{{count}} baris",
"fileEditUnchangedLinesHidden": "{{count}} baris tidak berubah disembunyikan",
"fileEditShowMoreLines": "Tampilkan {{count}} baris lagi",
@@ -2073,6 +2073,7 @@
"deletingFile": "Menghapus",
"editingFileShort": "Mengedit",
"deletedFile": "Dihapus",
+ "createdFile": "Dibuat",
"editedFileShort": "Diedit"
},
"collapseActivity": "Ciutkan detail aktivitas",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index a3ae48202..8e09bff7c 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -2072,8 +2072,9 @@
"editFileFailedShort": "編集できませんでした",
"deletingFile": "削除中",
"editingFileShort": "編集中",
- "deletedFile": "削除しました",
- "editedFileShort": "編集しました"
+ "deletedFile": "削除",
+ "createdFile": "作成",
+ "editedFileShort": "編集"
},
"collapseActivity": "アクティビティの詳細を折りたたむ",
"activityShow": "処理過程を表示",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index fc02707a3..cce1250c2 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1921,13 +1921,13 @@
"copiedReply": "복사됨",
"turnLatencyTitle": "응답 시간(엔드투엔드)",
"fileEditViewDiff": "변경 사항 보기",
- "fileEditViewLargeDiff": "큰 변경 사항 보기",
+ "fileEditViewLargeDiff": "변경 사항 보기",
"fileEditDiffLineCount": "{{count}}줄",
"fileEditUnchangedLinesHidden": "변경되지 않은 {{count}}줄 숨김",
"fileEditShowMoreLines": "{{count}}줄 더 보기",
- "fileEditShowFewerLines": "줄 줄이기",
+ "fileEditShowFewerLines": "간략히 보기",
"fileEditOpenFile": "파일 열기",
- "fileEditDiffTruncated": "변경 사항이 잘렸습니다. 전체 변경은 파일을 열어 확인하세요.",
+ "fileEditDiffTruncated": "변경 사항의 일부만 표시됩니다. 전체 내용은 파일을 열어 확인하세요.",
"usage": {
"context": "최근 컨텍스트: {{tokens}}{{capacity}} 토큰",
"requests": "모델 요청 {{count}}회",
@@ -2073,6 +2073,7 @@
"deletingFile": "삭제 중",
"editingFileShort": "편집 중",
"deletedFile": "삭제 완료",
+ "createdFile": "생성 완료",
"editedFileShort": "편집 완료"
},
"collapseActivity": "활동 세부 정보 접기",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index e892181bc..7ccd4dbb3 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -2059,6 +2059,7 @@
"deletingFile": "Excluindo",
"editingFileShort": "Editando",
"deletedFile": "Excluído",
+ "createdFile": "Criado",
"editedFileShort": "Editado"
},
"collapseActivity": "Recolher detalhes da atividade",
@@ -2101,7 +2102,7 @@
"copiedReply": "Copiado",
"turnLatencyTitle": "Tempo de resposta (ponta a ponta)",
"fileEditViewDiff": "Ver diferenças",
- "fileEditViewLargeDiff": "Ver diferenças grandes",
+ "fileEditViewLargeDiff": "Ver diferenças",
"fileEditDiffLineCount": "{{count}} linhas",
"fileEditUnchangedLinesHidden": "{{count}} linhas inalteradas ocultas",
"fileEditShowMoreLines": "Mostrar mais {{count}} linhas",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index f8145935b..fe979e7af 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1920,14 +1920,14 @@
"copyReply": "Sao chép",
"copiedReply": "Đã sao chép",
"turnLatencyTitle": "Thời gian phản hồi (end-to-end)",
- "fileEditViewDiff": "Xem khác biệt",
- "fileEditViewLargeDiff": "Xem khác biệt lớn",
+ "fileEditViewDiff": "Xem thay đổi",
+ "fileEditViewLargeDiff": "Xem thay đổi",
"fileEditDiffLineCount": "{{count}} dòng",
"fileEditUnchangedLinesHidden": "Đã ẩn {{count}} dòng không đổi",
"fileEditShowMoreLines": "Hiển thị thêm {{count}} dòng",
"fileEditShowFewerLines": "Hiển thị ít dòng hơn",
"fileEditOpenFile": "Mở tệp",
- "fileEditDiffTruncated": "Khác biệt đã bị cắt bớt. Mở tệp để xem toàn bộ thay đổi.",
+ "fileEditDiffTruncated": "Chỉ hiển thị một phần thay đổi. Mở tệp để xem nội dung đầy đủ.",
"usage": {
"context": "Ngữ cảnh gần nhất: {{tokens}}{{capacity}} token",
"requests": "{{count}} yêu cầu mô hình",
@@ -2073,6 +2073,7 @@
"deletingFile": "Đang xóa",
"editingFileShort": "Đang chỉnh sửa",
"deletedFile": "Đã xóa",
+ "createdFile": "Đã tạo",
"editedFileShort": "Đã chỉnh sửa"
},
"collapseActivity": "Thu gọn chi tiết hoạt động",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index f033e8663..7e79dc51d 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -2121,13 +2121,13 @@
"foundFiles": "文件查找完成",
"findFilesFailed": "文件查找失败",
"listingFiles": "正在列出文件",
- "listedFiles": "已列出文件",
+ "listedFiles": "列出文件",
"listFilesFailed": "无法列出文件",
"readingSource": "正在读取资料",
"readSource": "资料读取完成",
"readSourceFailed": "资料读取失败",
"readingFile": "正在读取文件",
- "readFile": "已读取文件",
+ "readFile": "读取文件",
"readFileFailed": "无法读取文件",
"searchingMemory": "正在搜索记忆",
"searchedMemory": "记忆搜索完成",
@@ -2189,10 +2189,10 @@
"readFailed": "无法读取",
"privateAddress": "私有地址",
"writingFile": "正在写入文件",
- "wroteFile": "已写入文件",
+ "wroteFile": "写入文件",
"writeFileFailed": "无法写入文件",
"editingFile": "正在编辑文件",
- "editedFile": "已编辑文件",
+ "editedFile": "编辑文件",
"editFileFailed": "无法编辑文件",
"working": "正在处理",
"completedStep": "已完成步骤",
@@ -2243,8 +2243,9 @@
"editFileFailedShort": "无法编辑",
"deletingFile": "正在删除",
"editingFileShort": "正在编辑",
- "deletedFile": "已删除",
- "editedFileShort": "已编辑"
+ "deletedFile": "删除",
+ "createdFile": "创建",
+ "editedFileShort": "编辑"
},
"activityWorkedFor": "已处理 {{duration}}",
"collapseActivity": "收起处理过程",
@@ -2274,7 +2275,7 @@
"fileAttachment": "文件附件",
"attachmentUnavailable": "附件不可用",
"dataTable": "数据表",
- "fileEditPreparing": "正在准备文件编辑…",
+ "fileEditPreparing": "准备编辑文件…",
"openLink": "打开链接:{{label}}",
"openAttachment": "打开 {{name}}",
"skill": "技能:{{name}}",
@@ -2287,13 +2288,13 @@
"copiedReply": "已复制",
"turnLatencyTitle": "本轮耗时(端到端)",
"fileEditViewDiff": "查看差异",
- "fileEditViewLargeDiff": "查看大型差异",
+ "fileEditViewLargeDiff": "展开差异",
"fileEditDiffLineCount": "{{count}} 行",
"fileEditUnchangedLinesHidden": "已隐藏 {{count}} 行未修改内容",
"fileEditShowMoreLines": "显示剩余 {{count}} 行",
"fileEditShowFewerLines": "收起部分行",
"fileEditOpenFile": "打开文件",
- "fileEditDiffTruncated": "差异内容已截断。打开文件可查看完整更改。",
+ "fileEditDiffTruncated": "仅显示部分差异,打开文件可查看完整内容。",
"usage": {
"context": "当前上下文:{{tokens}}{{capacity}}",
"requests": "本轮 {{count}} 次模型调用",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index c823c2256..aa52f8d29 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1910,7 +1910,7 @@
"fileAttachment": "檔案附件",
"attachmentUnavailable": "附件無法使用",
"dataTable": "資料表",
- "fileEditPreparing": "正在準備檔案編輯…",
+ "fileEditPreparing": "準備編輯檔案…",
"openLink": "開啟連結:{{label}}",
"openAttachment": "開啟 {{name}}",
"skill": "技能:{{name}}",
@@ -1920,13 +1920,13 @@
"copiedReply": "已複製",
"turnLatencyTitle": "本輪耗時(端到端)",
"fileEditViewDiff": "檢視差異",
- "fileEditViewLargeDiff": "檢視大型差異",
+ "fileEditViewLargeDiff": "展開差異",
"fileEditDiffLineCount": "{{count}} 行",
"fileEditUnchangedLinesHidden": "已隱藏 {{count}} 行未修改內容",
"fileEditShowMoreLines": "顯示其餘 {{count}} 行",
"fileEditShowFewerLines": "收起部分行",
"fileEditOpenFile": "開啟檔案",
- "fileEditDiffTruncated": "差異內容已截斷。請開啟檔案以檢視完整變更。",
+ "fileEditDiffTruncated": "僅顯示部分差異,請開啟檔案查看完整內容。",
"usage": {
"context": "目前上下文:{{tokens}}{{capacity}} tokens",
"requests": "{{count}} 次模型請求",
@@ -1949,13 +1949,13 @@
"foundFiles": "檔案搜尋完成",
"findFilesFailed": "檔案搜尋失敗",
"listingFiles": "正在列出檔案",
- "listedFiles": "已列出檔案",
+ "listedFiles": "列出檔案",
"listFilesFailed": "無法列出檔案",
"readingSource": "正在讀取資料",
"readSource": "資料讀取完成",
"readSourceFailed": "資料讀取失敗",
"readingFile": "正在讀取檔案",
- "readFile": "已讀取檔案",
+ "readFile": "讀取檔案",
"readFileFailed": "無法讀取檔案",
"searchingMemory": "正在搜尋記憶",
"searchedMemory": "記憶搜尋完成",
@@ -2017,10 +2017,10 @@
"readFailed": "無法讀取",
"privateAddress": "私人位址",
"writingFile": "正在寫入檔案",
- "wroteFile": "已寫入檔案",
+ "wroteFile": "寫入檔案",
"writeFileFailed": "無法寫入檔案",
"editingFile": "正在編輯檔案",
- "editedFile": "已編輯檔案",
+ "editedFile": "編輯檔案",
"editFileFailed": "無法編輯檔案",
"working": "正在處理",
"completedStep": "已完成步驟",
@@ -2071,8 +2071,9 @@
"editFileFailedShort": "無法編輯",
"deletingFile": "正在刪除",
"editingFileShort": "正在編輯",
- "deletedFile": "已刪除",
- "editedFileShort": "已編輯"
+ "deletedFile": "刪除",
+ "createdFile": "建立",
+ "editedFileShort": "編輯"
},
"cliActivityRunningOne": "正在使用 {{name}}",
"cliActivityRanOne": "已使用 {{name}}",
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 5140e2e0b..584be199e 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -389,7 +389,7 @@ export interface UIFileEdit {
deleted: number;
approximate?: boolean;
status: "editing" | "done" | "error";
- operation?: "edit" | "delete" | string;
+ operation?: "create" | "edit" | "delete" | string;
binary?: boolean;
error?: string;
pending?: boolean;
diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsx
index c95d2fc9f..b1340f366 100644
--- a/webui/src/tests/agent-activity-cluster.test.tsx
+++ b/webui/src/tests/agent-activity-cluster.test.tsx
@@ -156,7 +156,7 @@ describe("AgentActivityCluster", () => {
expect(screen.getByText(`正在读取文件 ${path}`)).toBeInTheDocument();
expect(screen.getByText("正在使用 Blender · --json --background scene.blend")).toBeInTheDocument();
expect(screen.getByText("正在打开 example.com · Browserbase")).toBeInTheDocument();
- expect(screen.getByText("已编辑")).toBeInTheDocument();
+ expect(screen.getByText("编辑")).toBeInTheDocument();
expect(screen.getByTestId("activity-file-reference")).toHaveTextContent(path);
await act(async () => setAppLanguage("ja"));
@@ -166,7 +166,7 @@ describe("AgentActivityCluster", () => {
expect(screen.getByText("Blender を使用中 · --json --background scene.blend")).toBeInTheDocument();
expect(screen.getByText("example.com · 開いています · Browserbase")).toBeInTheDocument();
expect(screen.getByTestId("activity-file-reference").closest('[data-testid="activity-step"]'))
- .toHaveTextContent(`${path} · 編集しました`);
+ .toHaveTextContent(`${path} · 編集`);
});
it("loads deferred trace details only after completed activity is expanded", async () => {
@@ -661,6 +661,7 @@ describe("AgentActivityCluster", () => {
expect(screen.getByTestId("file-edit-diff")).toBeInTheDocument();
expect(screen.getByText("return <Old />;")).toBeInTheDocument();
expect(screen.getByText("return <New />;")).toBeInTheDocument();
+ expect(screen.getByText("Edited")).toBeInTheDocument();
expect(screen.getByTestId("activity-file-reference")).toHaveTextContent("src/app.tsx");
expect(screen.getAllByTestId("activity-diff-pair")).toHaveLength(1);
@@ -668,6 +669,7 @@ describe("AgentActivityCluster", () => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, fileEditDisplayMode: "summary" });
});
expect(screen.queryByTestId("file-edit-diff")).not.toBeInTheDocument();
+ expect(screen.getByText("Edited")).toBeInTheDocument();
act(() => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, fileEditDisplayMode: "diff" });
@@ -937,6 +939,39 @@ describe("AgentActivityCluster", () => {
}
});
+ it.each([false, true])("labels created files with or without text diffs (hasDiff: %s)", (hasDiff) => {
+ localStorage.setItem(
+ "nanobot-webui.settings-preferences",
+ JSON.stringify({ fileEditDisplayMode: "diff" }),
+ );
+ try {
+ render(
+ <AgentActivityCluster
+ messages={[{
+ id: "create", role: "tool", kind: "trace", content: "edit_file()", createdAt: 1,
+ traces: ["edit_file()"],
+ fileEdits: [{
+ call_id: "call-create", tool: "edit_file", path: "tmp.txt", phase: "end",
+ added: hasDiff ? 1 : 0, deleted: 0, status: "done", operation: "create",
+ ...(hasDiff ? { diff: unifiedFileDiff([
+ "--- tmp.txt", "+++ tmp.txt", "@@ -0,0 +1 @@", "+hello",
+ ]) } : {}),
+ }],
+ }]}
+ isTurnStreaming={false}
+ hasBodyBelow={false}
+ />,
+ );
+ expect(screen.getByText("Created")).toBeInTheDocument();
+ expect(screen.getByLabelText("Created tmp.txt")).toBeInTheDocument();
+ expect(screen.queryByText("Edited")).not.toBeInTheDocument();
+ expect(screen.getByTestId("activity-file-reference")).toHaveTextContent("tmp.txt");
+ expect(!!screen.queryByTestId("file-edit-diff")).toBe(hasDiff);
+ } finally {
+ localStorage.removeItem("nanobot-webui.settings-preferences");
+ }
+ });
+
it("labels whole-file deletes as deleted instead of edited", () => {
render(
<AgentActivityCluster
diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsx
index 044501122..cbe2650cc 100644
--- a/webui/src/tests/thread-messages.test.tsx
+++ b/webui/src/tests/thread-messages.test.tsx
@@ -52,6 +52,71 @@ function openMessageBlockMenu(root: ParentNode): {
}
describe("ThreadMessages", () => {
+ it.each(["diff", "collapsed_diff"] as const)(
+ "keeps completed %s edits visible when answer activity is toggled",
+ (fileEditDisplayMode) => {
+ localStorage.setItem(
+ "nanobot-webui.settings-preferences",
+ JSON.stringify({ fileEditDisplayMode }),
+ );
+ const messages: UIMessage[] = [
+ { id: "user", role: "user", content: "edit the file", createdAt: 1 },
+ { id: "before", role: "assistant", content: "", reasoning: "Before edit", createdAt: 2 },
+ {
+ id: "edit", role: "tool", kind: "trace", content: "edit_file()", createdAt: 3,
+ traces: ["edit_file()"],
+ fileEdits: [{
+ call_id: "edit-call", tool: "edit_file", path: "src/app.tsx", phase: "end",
+ added: 1, deleted: 1, status: "done",
+ diff: {
+ format: "unified", context: 3, truncated: false,
+ text: "--- a/src/app.tsx\n+++ b/src/app.tsx\n@@ -1 +1 @@\n-old\n+new\n",
+ },
+ }],
+ },
+ { id: "after", role: "assistant", content: "", reasoning: "After edit", createdAt: 4 },
+ { id: "answer", role: "assistant", content: "File updated", latencyMs: 5_000, createdAt: 5 },
+ ];
+ try {
+ const { container, rerender } = render(<ThreadMessages messages={messages} isStreaming />);
+ rerender(<ThreadMessages messages={messages} isStreaming={false} />);
+ if (fileEditDisplayMode === "collapsed_diff") {
+ fireEvent.click(screen.getByTestId("file-edit-diff-toggle"));
+ }
+ const assertIndependentDiff = () => {
+ const diff = screen.getByTestId("file-edit-diff");
+ expect(diff).toBeVisible();
+ expect(screen.getByText("Edited")).toBeInTheDocument();
+ expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-content"]'))
+ .toBeNull();
+ expect(screen.getByText("File updated")).toBeVisible();
+ return diff;
+ };
+ assertIndependentDiff();
+ openAssistantBlockMenu(container);
+ const disclosure = screen.getByRole("button", { name: "Worked for 5s", exact: true });
+ expect(disclosure).toHaveAttribute("aria-expanded", "false");
+ const detailsId = disclosure.getAttribute("aria-controls")!;
+ expect(container.querySelectorAll(`[id="${detailsId}"]`)).toHaveLength(1);
+ fireEvent.click(disclosure);
+ const diff = assertIndependentDiff();
+ expect(screen.getByText("Before edit").compareDocumentPosition(diff)
+ & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(diff.compareDocumentPosition(screen.getByText("After edit"))
+ & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ fireEvent.click(screen.getAllByRole("button", { name: /Worked for 5s.*Collapse activity/ })[0]);
+ assertIndependentDiff();
+ expect(screen.getByText("Before edit").closest('[aria-hidden="true"][inert]')).not.toBeNull();
+ expect(screen.getByText("After edit").closest('[aria-hidden="true"][inert]')).not.toBeNull();
+
+ rerender(<ThreadMessages messages={[messages[0], messages[2], messages[4]]} isStreaming={false} />);
+ assertIndependentDiff();
+ } finally {
+ localStorage.removeItem("nanobot-webui.settings-preferences");
+ }
+ },
+ );
+
it.each([0, -13_000, -14_000, -15_000, 15_000])(
"keeps the optimistic timer through acknowledgement and output with %i ms server clock skew",
(clockSkewMs) => {