Skip to content

Build and run agents you can see, understand and trust.

feat(webui): render Write and Edit tool diffs (#1856)

Premsenaae9819017d6c
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.json
index 659fddf82..340d0349d 100644
--- a/examples/web_ui/frontend/package.json
+++ b/examples/web_ui/frontend/package.json
@@ -11,7 +11,7 @@
"preview": "vite preview"
},
"dependencies": {
- "@agentscope-ai/agentscope": "^0.0.9",
+ "@agentscope-ai/agentscope": "^0.0.11",
"@fontsource-variable/geist": "^5.2.8",
"@tailwindcss/vite": "^4.3.0",
"class-variance-authority": "^0.7.1",
@@ -29,6 +29,7 @@
"radix-ui": "^1.4.3",
"react": "^19.2.6",
"react-day-picker": "^10.0.1",
+ "react-diff-view": "^3.3.3",
"react-dom": "^19.2.6",
"react-i18next": "^17.0.8",
"react-markdown": "^10.1.0",
@@ -40,6 +41,7 @@
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.0",
"tw-animate-css": "^1.4.0",
+ "unidiff": "^1.0.4",
"vaul": "^1.1.2"
},
"devDependencies": {
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx
index 8d8bda5ac..6b01dba24 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/DefaultRenderer.tsx
@@ -1,9 +1,16 @@
import type { ToolCallBlock, ToolResultBlock } from '@agentscope-ai/agentscope/message';
+import { ChevronRight } from 'lucide-react';
import * as mime from 'mime-types';
import type { ReactNode } from 'react';
import { CornerLine, ToolStateIcon } from './_shared';
import type { TFunction, ToolCallWithResult } from './types';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@/components/ui/collapsible.tsx';
function processToolInput(input: string): string {
try {
@@ -101,21 +108,27 @@ export function defaultRenderGroup(
const args = resolvers.renderCallArgs(call);
const resultContent = result ? resolvers.renderResult(call, result) : null;
return (
- <div key={call.id} className="flex flex-col w-full max-w-full text-sm">
- <div className="flex flex-row gap-x-2 w-full max-w-full items-center">
- <ToolStateIcon states={[result?.state]} />
- <span className="truncate">
- <strong className="truncate text-primary">{displayName}</strong>
- {args && <>({args})</>}
- </span>
- </div>
+ <Collapsible key={call.id} className="flex flex-col w-full max-w-full text-sm">
+ <CollapsibleTrigger asChild>
+ <Button
+ variant={'ghost'}
+ className="group hover:bg-transparent data-[state=open]:bg-transparent justify-start px-0 gap-2 active:!translate-y-0"
+ >
+ <ToolStateIcon states={[result?.state]} />
+ <strong className="shrink-0 text-primary">{displayName}</strong>
+ {args && <span className="truncate min-w-0 text-left">{args}</span>}
+ {resultContent && (
+ <ChevronRight className="size-3 shrink-0 group-data-[state=open]:rotate-90" />
+ )}
+ </Button>
+ </CollapsibleTrigger>
{resultContent && (
- <div className="flex flex-row gap-x-2 pl-6 max-w-full">
+ <CollapsibleContent className="flex flex-row gap-x-2 pl-6 max-w-full">
<CornerLine />
{resultContent}
- </div>
+ </CollapsibleContent>
)}
- </div>
+ </Collapsible>
);
})}
</>
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/DiffPreview.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/DiffPreview.tsx
new file mode 100644
index 000000000..c222f95cb
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/DiffPreview.tsx
@@ -0,0 +1,204 @@
+import { ChevronDown, MoreHorizontal, Minus, Plus } from 'lucide-react';
+import type { ReactElement } from 'react';
+import { useMemo, useState } from 'react';
+import { Decoration, Diff, Hunk, parseDiff } from 'react-diff-view';
+import type { ChangeData, DiffType, GutterOptions, HunkData } from 'react-diff-view';
+
+import 'react-diff-view/style/index.css';
+
+const MAX_VISIBLE_DIFF_LINES = 18;
+
+interface DiffPreviewProps {
+ /**
+ * Pre-computed unified-diff text (produced by the backend Edit / Write
+ * tools and delivered via ``ToolResultBlock.metadata.diff``). It carries
+ * absolute file line numbers and naturally handles multi-hunk diffs from
+ * ``replace_all``. The component renders nothing if this is empty.
+ */
+ unifiedDiff: string;
+}
+
+function hunkLineCount(hunk: HunkData): number {
+ return hunk.changes.length;
+}
+
+function getVisibleHunks(hunks: HunkData[], expanded: boolean): HunkData[] {
+ if (expanded) return hunks;
+
+ let visibleLineCount = 0;
+ const visibleHunks: HunkData[] = [];
+
+ for (const hunk of hunks) {
+ const remaining = MAX_VISIBLE_DIFF_LINES - visibleLineCount;
+ if (remaining <= 0) break;
+ const hunkLines = hunkLineCount(hunk);
+ if (hunkLines <= remaining) {
+ visibleHunks.push(hunk);
+ visibleLineCount += hunkLines;
+ continue;
+ }
+ // Hunk doesn't fit in the remaining budget. If we haven't shown
+ // anything yet (typical for new-file / full-rewrite diffs that
+ // produce a single very large hunk), include a truncated slice so
+ // the user still sees the start of the change. Otherwise stop so
+ // we never overshoot ``MAX_VISIBLE_DIFF_LINES``.
+ if (visibleHunks.length === 0) {
+ visibleHunks.push(truncateHunkChanges(hunk, remaining));
+ }
+ break;
+ }
+
+ return visibleHunks;
+}
+
+/**
+ * Build a new ``HunkData`` containing only the first ``maxLines`` changes of
+ * ``hunk``. ``oldLines`` / ``newLines`` are recomputed from the slice so
+ * react-diff-view's line-number accounting stays internally consistent.
+ */
+function truncateHunkChanges(hunk: HunkData, maxLines: number): HunkData {
+ if (hunk.changes.length <= maxLines) return hunk;
+ const changes = hunk.changes.slice(0, maxLines);
+ let oldLines = 0;
+ let newLines = 0;
+ for (const change of changes) {
+ if (change.type === 'normal') {
+ oldLines += 1;
+ newLines += 1;
+ } else if (change.type === 'delete') {
+ oldLines += 1;
+ } else if (change.type === 'insert') {
+ newLines += 1;
+ }
+ }
+ return { ...hunk, changes, oldLines, newLines };
+}
+
+function countHiddenLines(allHunks: HunkData[], visibleHunks: HunkData[]): number {
+ const total = allHunks.reduce((sum, hunk) => sum + hunkLineCount(hunk), 0);
+ const visible = visibleHunks.reduce((sum, hunk) => sum + hunkLineCount(hunk), 0);
+ return Math.max(0, total - visible);
+}
+
+function getLineClassName({ changes }: { changes: Array<{ type: string }> }): string {
+ if (changes.some((change) => change.type === 'insert')) {
+ return 'bg-emerald-500/10';
+ }
+ if (changes.some((change) => change.type === 'delete')) {
+ return 'bg-red-500/10';
+ }
+ return 'bg-transparent';
+}
+
+// Pick the line number we want to display in the single visible gutter column.
+// - normal rows show the new-side line number (mirrors GitHub's unified view)
+// - insert / delete rows only have one `lineNumber` field, so use it directly
+function getDisplayedLineNumber(change: ChangeData): number | undefined {
+ if (change.type === 'normal') return change.newLineNumber;
+ return change.lineNumber;
+}
+
+// Render only the "new" side of each row. The "old" side <col> is removed
+// from the table layout via `visibility: collapse` (see arbitrary variants
+// on the table className below), so the unified diff effectively renders
+// as a single gutter column showing `<line-number> +/-`.
+function renderGutter({ change, side }: GutterOptions) {
+ if (side === 'old') return null;
+
+ let marker = null;
+ if (change.type === 'insert') {
+ marker = <Plus className="size-2.5 text-emerald-600 dark:text-emerald-400" />;
+ } else if (change.type === 'delete') {
+ marker = <Minus className="size-2.5 text-red-600 dark:text-red-400" />;
+ }
+
+ return (
+ <span className="inline-flex w-full items-center justify-between tabular-nums">
+ <span>{getDisplayedLineNumber(change)}</span>
+ {marker}
+ </span>
+ );
+}
+
+// Lines between two consecutive hunks that the unified diff omitted.
+// ``hunk.oldStart`` is 1-based and ``oldLines`` is the count of old-side
+// lines covered (including context). So the next hunk's ``oldStart`` minus
+// the end of the previous hunk gives the gap.
+function gapLinesBetween(prev: HunkData, next: HunkData): number {
+ return next.oldStart - (prev.oldStart + prev.oldLines);
+}
+
+export function DiffPreview({ unifiedDiff }: DiffPreviewProps) {
+ const [expanded, setExpanded] = useState(false);
+ const diffFile = useMemo(
+ () => parseDiff(unifiedDiff, { nearbySequences: 'zip' })[0],
+ [unifiedDiff],
+ );
+
+ if (!diffFile || diffFile.hunks.length === 0) {
+ return <div className="text-xs text-muted-foreground">No textual changes detected.</div>;
+ }
+
+ const visibleHunks = getVisibleHunks(diffFile.hunks, expanded);
+ const hiddenLines = countHiddenLines(diffFile.hunks, visibleHunks);
+
+ return (
+ <Diff
+ diffType={diffFile.type as DiffType}
+ hunks={visibleHunks}
+ viewType="unified"
+ renderGutter={renderGutter}
+ className="w-full border-collapse font-mono text-xs leading-5 [&>colgroup>col:first-child]:!w-0 [&>colgroup>col:first-child]:[visibility:collapse] [&_td.diff-gutter:first-of-type]:!p-0 [&_td.diff-gutter:first-of-type]:!border-r-0 [&_td.diff-gutter:first-of-type]:!w-0"
+ hunkClassName="align-top"
+ lineClassName="align-top"
+ gutterClassName="select-none border-r border-border px-2 text-right text-muted-foreground"
+ codeClassName="whitespace-pre-wrap break-all px-3"
+ generateLineClassName={getLineClassName}
+ >
+ {(hunks) => {
+ const children: ReactElement[] = [];
+
+ hunks.forEach((hunk, idx) => {
+ if (idx > 0) {
+ // Insert an ellipsis decoration between hunks so it's
+ // visually obvious there are skipped lines between
+ // e.g. an edit at line 20 and another at line 70.
+ const gap = gapLinesBetween(hunks[idx - 1], hunk);
+ children.push(
+ <Decoration key={`gap-${hunk.oldStart}-${hunk.newStart}`}>
+ <div className="flex items-center gap-2 border-y border-dashed border-border bg-muted/30 px-3 py-1 text-[10px] text-muted-foreground select-none">
+ <MoreHorizontal className="h-3 w-3" />
+ <span className="tabular-nums">
+ {gap > 0
+ ? `${gap} unchanged line${gap === 1 ? '' : 's'}`
+ : 'unchanged lines'}
+ </span>
+ </div>
+ </Decoration>,
+ );
+ }
+ children.push(
+ <Hunk key={`hunk-${hunk.oldStart}-${hunk.newStart}`} hunk={hunk} />,
+ );
+ });
+
+ if (hiddenLines > 0) {
+ children.push(
+ <Decoration key="collapsed-diff-lines">
+ <button
+ type="button"
+ className="flex w-full items-center justify-center gap-1 border-t border-border bg-muted/50 px-3 py-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ onClick={() => setExpanded(true)}
+ >
+ <ChevronDown className="h-3.5 w-3.5" />
+ {hiddenLines} more lines (click to expand)
+ </button>
+ </Decoration>,
+ );
+ }
+
+ return children;
+ }}
+ </Diff>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx
index d4433b454..54286e12b 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx
@@ -1,30 +1,73 @@
+import unidiff from 'unidiff';
+
import {
defaultGetDisplayName,
defaultRenderCallArgs,
defaultRenderGroup,
defaultRenderResult,
} from './DefaultRenderer';
+import { DiffPreview } from './DiffPreview';
import type { ToolRenderer } from './types';
+import {
+ countDiffStats,
+ DiffStats,
+ getFilePath,
+ getResultDiff,
+ parseInput,
+ tryGetFileName,
+} from '@/components/chat/tool-renderers/_shared.tsx';
-function parseInput(input: string): Record<string, unknown> {
- try {
- return JSON.parse(input);
- } catch {
- return {};
- }
+/**
+ * Count the real inserted / deleted lines between ``oldText`` and ``newText``
+ * by computing a unified diff and tallying the leading ``+`` / ``-`` markers.
+ * This is the per-occurrence diff size — for ``replace_all`` the backend
+ * reports the totalled counts via ``result.metadata`` (see ``countDiffStats``).
+ */
+function countLineChanges(
+ oldText: string,
+ newText: string,
+): { insertions: number; deletions: number } {
+ const diffText = unidiff.diffAsText(oldText, newText, { context: 0 });
+ return countDiffStats(diffText);
}
-function getFilePath(input: string): string {
- const { file_path } = parseInput(input) as { file_path?: string };
- return file_path || input;
+function renderEditDiff(result: { metadata?: Record<string, unknown> }) {
+ // The post-execution diff is always produced by the backend Edit tool
+ // (with absolute line numbers and one hunk per replaced occurrence).
+ // If it's missing we deliberately render nothing — falling back to a
+ // client-side diff of ``old_string`` / ``new_string`` would silently
+ // produce misleading line numbers and miss the other replace_all
+ // occurrences.
+ const unifiedDiff = getResultDiff(result);
+ if (!unifiedDiff) return null;
+ return <DiffPreview unifiedDiff={unifiedDiff} />;
}
-// TODO: render old_string / new_string as a side-by-side or unified diff
-// inside `renderGroup` once a diff component is available.
export const EditRenderer: ToolRenderer = {
getDisplayName: (call) => call.name,
- renderCallArgs: (call) => getFilePath(call.input),
+ renderCallArgs: (call) => {
+ // While the tool-call JSON is still streaming, ``call.input`` is a
+ // partial dict and parsing yields the wrong file name / empty
+ // strings. Return an empty fragment (not ``null``) so the index.ts
+ // ``?? defaultRenderCallArgs`` fallback doesn't dump the raw JSON.
+ const fileName = tryGetFileName(call.input);
+ if (!fileName) return <></>;
+ const input = parseInput(call.input);
+ const oldString = typeof input.old_string === 'string' ? input.old_string : '';
+ const newString = typeof input.new_string === 'string' ? input.new_string : '';
+ // Use the real per-occurrence insert/delete counts rather than the
+ // raw line counts of old_string / new_string (which over-count when
+ // most lines are unchanged context).
+ const { insertions, deletions } = countLineChanges(oldString, newString);
+
+ return (
+ <div className="flex items-center gap-2 font-normal">
+ {fileName}
+ <DiffStats insertions={insertions} deletions={deletions} />
+ </div>
+ );
+ },
renderConfirmBody: (call) => (
<div className="w-full max-w-full overflow-hidden text-ellipsis truncate">
@@ -36,9 +79,29 @@ export const EditRenderer: ToolRenderer = {
defaultRenderGroup(calls, t, {
getDisplayName: (call) =>
EditRenderer.getDisplayName?.(call, t) ?? defaultGetDisplayName(call),
- renderCallArgs: (call) =>
- EditRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call),
+ renderCallArgs: (call) => {
+ // When the backend has provided the post-execution unified diff
+ // (handles replace_all correctly), prefer its insert/delete
+ // counts over the per-occurrence client-side estimate.
+ const enriched = calls.find((c) => c.call.id === call.id);
+ const resultDiff = enriched?.result
+ ? getResultDiff(enriched.result as { metadata?: Record<string, unknown> })
+ : undefined;
+ if (resultDiff) {
+ const fileName = tryGetFileName(call.input);
+ if (!fileName) return null;
+ const { insertions, deletions } = countDiffStats(resultDiff);
+ return (
+ <div className="flex items-center gap-2 font-normal">
+ {fileName}
+ <DiffStats insertions={insertions} deletions={deletions} />
+ </div>
+ );
+ }
+ return EditRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call);
+ },
renderResult: (call, result) =>
+ (result.state === 'success' ? renderEditDiff(result) : null) ??
EditRenderer.renderResult?.(call, result, t) ??
defaultRenderResult(call, result, t),
}),
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx
index 66c4f0841..e74376c07 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/ReadRenderer.tsx
@@ -1,25 +1,14 @@
/* eslint-disable react-refresh/only-export-components -- renderer constant is co-located with its inline component by design */
import type { ToolResultBlock } from '@agentscope-ai/agentscope/message';
+import { ChevronRight } from 'lucide-react';
import { useState } from 'react';
-import { CornerLine, ToolStateIcon } from './_shared';
+import { CornerLine, getFilePath, ToolStateIcon } from './_shared';
import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';
+import { Button } from '@/components/ui/button.tsx';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { formatNumber } from '@/utils/common';
-function parseInput(input: string): Record<string, unknown> {
- try {
- return JSON.parse(input);
- } catch {
- return {};
- }
-}
-
-function getFilePath(input: string): string {
- const { file_path } = parseInput(input) as { file_path?: string };
- return file_path || input;
-}
-
/** Count lines in a tool result's output string, including text content from
* non-text blocks. Returns 0 when the result is missing or empty. */
function countResultLines(result?: ToolResultBlock): number {
@@ -60,16 +49,18 @@ function ReadGroup({ calls, t }: { calls: ToolCallWithResult[]; t: TFunction })
return (
<Collapsible open={open} onOpenChange={setOpen} className="flex flex-col w-full ">
- <CollapsibleTrigger className="flex flex-row gap-x-2 w-full max-w-full items-center cursor-pointer text-left">
- <ToolStateIcon states={calls.map((c) => c.result?.state)} />
- <span className="text-sm flex-1 min-w-0 truncate">
- <strong className="text-primary">{name} </strong>
- {t('tool.read.fileCount', { count: calls.length })}
- {!open && <span className="text-muted-foreground"> ...</span>}
- </span>
- {/*<ChevronRight*/}
- {/* className={`size-4 shrink-0 transition-transform ${open ? 'rotate-90' : ''}`}*/}
- {/*/>*/}
+ <CollapsibleTrigger asChild>
+ <Button
+ variant={'ghost'}
+ className="group hover:bg-transparent data-[state=open]:bg-transparent justify-start px-0 gap-2 active:!translate-y-0"
+ >
+ <ToolStateIcon states={calls.map((c) => c.result?.state)} />
+ <span className="flex items-center text-sm truncate gap-1">
+ <strong className="text-primary">{name}</strong>
+ {t('tool.read.fileCount', { count: calls.length })}
+ </span>
+ <ChevronRight className="size-3 group-data-[state=open]:rotate-90" />
+ </Button>
</CollapsibleTrigger>
<CollapsibleContent className="pl-6 pt-2 flex flex-col gap-y-2 text-sm">
{groupByConsecutivePath(calls).map((group, gIdx) => (
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx
index a2e2e7cb5..a5d63b31a 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/WriteRenderer.tsx
@@ -4,25 +4,33 @@ import {
defaultRenderGroup,
defaultRenderResult,
} from './DefaultRenderer';
+import { DiffPreview } from './DiffPreview';
import type { ToolRenderer } from './types';
-
-function parseInput(input: string): Record<string, unknown> {
- try {
- return JSON.parse(input);
- } catch {
- return {};
- }
-}
-
-function getFilePath(input: string): string {
- const { file_path } = parseInput(input) as { file_path?: string };
- return file_path || input;
-}
+import {
+ countDiffStats,
+ DiffStats,
+ getFilePath,
+ getResultDiff,
+ tryGetFileName,
+} from '@/components/chat/tool-renderers/_shared.tsx';
export const WriteRenderer: ToolRenderer = {
getDisplayName: (call) => call.name,
- renderCallArgs: (call) => getFilePath(call.input),
+ renderCallArgs: (call) => {
+ // While the tool-call JSON is still streaming, ``call.input`` is a
+ // partial dict (e.g. ``{"file_path": "foo", "content": "...``) and
+ // parsing yields the wrong file name or none at all. Render an empty
+ // fragment (not ``null``) so the index.ts ``?? defaultRenderCallArgs``
+ // fallback doesn't kick in and dump the raw JSON string.
+ const fileName = tryGetFileName(call.input);
+ if (!fileName) return <></>;
+ // Pre-execution we only know the new ``content`` (not the previous
+ // file body), so any ``+N`` count would be misleading on overwrites.
+ // The post-execution renderGroup override below adds ``+N -M`` once
+ // ``metadata.diff`` arrives.
+ return <div className="flex items-center gap-2 font-normal">{fileName}</div>;
+ },
renderConfirmBody: (call) => (
<div className="w-full max-w-full overflow-hidden text-ellipsis truncate">
@@ -30,12 +38,54 @@ export const WriteRenderer: ToolRenderer = {
</div>
),
+ renderResult: (call, result, t) => {
+ if (result.state === 'success') {
+ // The backend Write tool always attaches a unified diff in
+ // ``metadata.diff`` (correctly representing both new-file
+ // creation against /dev/null and overwrites of existing files
+ // with absolute line numbers). If it's missing we fall through
+ // rather than render a misleading client-side diff.
+ const unifiedDiff = getResultDiff(result as { metadata?: Record<string, unknown> });
+ if (unifiedDiff) {
+ return <DiffPreview unifiedDiff={unifiedDiff} />;
+ }
+ return undefined;
+ }
+ if (call.state === 'asking' || !result || result.state === 'running') {
+ return t('common.running');
+ }
+ if (result.state === 'interrupted') {
+ return t('common.interrupted');
+ }
+ return undefined;
+ },
+
renderGroup: (calls, t) =>
defaultRenderGroup(calls, t, {
getDisplayName: (call) =>
WriteRenderer.getDisplayName?.(call, t) ?? defaultGetDisplayName(call),
- renderCallArgs: (call) =>
- WriteRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call),
+ renderCallArgs: (call) => {
+ // Once the backend has produced the post-execution unified
+ // diff, compute and show the real ``+N -M`` stats — this
+ // correctly accounts for overwrites of existing files
+ // (which the pre-execution renderCallArgs cannot know).
+ const enriched = calls.find((c) => c.call.id === call.id);
+ const resultDiff = enriched?.result
+ ? getResultDiff(enriched.result as { metadata?: Record<string, unknown> })
+ : undefined;
+ if (resultDiff) {
+ const fileName = tryGetFileName(call.input);
+ if (!fileName) return null;
+ const { insertions, deletions } = countDiffStats(resultDiff);
+ return (
+ <div className="flex items-center gap-2 font-normal">
+ {fileName}
+ <DiffStats insertions={insertions} deletions={deletions} />
+ </div>
+ );
+ }
+ return WriteRenderer.renderCallArgs?.(call, t) ?? defaultRenderCallArgs(call);
+ },
renderResult: (call, result) =>
WriteRenderer.renderResult?.(call, result, t) ??
defaultRenderResult(call, result, t),
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
index 2573beb6d..33b6d3a58 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
@@ -1,10 +1,11 @@
import type { ToolResultBlock } from '@agentscope-ai/agentscope/message';
-import { Circle } from 'lucide-react';
+import { Circle, Minus, Plus } from 'lucide-react';
import type { ReactNode } from 'react';
import type { ToolCallWithResult } from './types';
import lineCornerSvg from '@/assets/images/line-corner.svg';
import lineVerticalSvg from '@/assets/images/line-vertical.svg';
+import { formatNumber } from '@/utils/common.ts';
/**
* Pick the connector image for an item at `index` of `total`:
@@ -104,3 +105,103 @@ export function ToolCallGroupList({
</div>
);
}
+
+/**
+ * Parse the input arguments from the given string.
+ * @param input
+ * @returns The JSON Record or empty object if parsing fails.
+ */
+export function parseInput(input: string): Record<string, unknown> {
+ try {
+ return JSON.parse(input);
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Get the filepath from the input arguments
+ * @param input
+ * @returns The filepath from the input string
+ */
+export function getFilePath(input: string): string {
+ const { file_path } = parseInput(input) as { file_path?: string };
+ return file_path || input;
+}
+
+/**
+ * Get the filename
+ * @param input
+ * @returns The filename from the input string, considering different OS path separators.
+ */
+export function getFileName(input: string): string {
+ const filePath = getFilePath(input);
+ const segments = filePath.split(/[/\\]+/).filter(Boolean);
+ return segments.length > 0 ? segments[segments.length - 1] : filePath;
+}
+
+/**
+ * Like ``getFileName`` but returns ``undefined`` when the input is not yet
+ * a fully parseable JSON object with a non-empty ``file_path`` field. Use
+ * this in ``renderCallArgs`` so partial JSON streamed during tool-call
+ * generation doesn't render a garbled file name (e.g. a fragment of the
+ * ``content`` field being mistaken for the path).
+ */
+export function tryGetFileName(input: string): string | undefined {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(input);
+ } catch {
+ return undefined;
+ }
+ if (!parsed || typeof parsed !== 'object') return undefined;
+ const filePath = (parsed as { file_path?: unknown }).file_path;
+ if (typeof filePath !== 'string' || filePath.length === 0) return undefined;
+ const segments = filePath.split(/[/\\]+/).filter(Boolean);
+ return segments.length > 0 ? segments[segments.length - 1] : filePath;
+}
+
+/**
+ * Tally inserted / deleted lines from a unified diff text. The leading
+ * ``+++`` / ``---`` lines (file headers) are excluded.
+ */
+export function countDiffStats(diffText: string): {
+ insertions: number;
+ deletions: number;
+} {
+ let insertions = 0;
+ let deletions = 0;
+ for (const line of diffText.split('\n')) {
+ if (line.startsWith('+') && !line.startsWith('+++')) insertions++;
+ else if (line.startsWith('-') && !line.startsWith('---')) deletions++;
+ }
+ return { insertions, deletions };
+}
+
+/**
+ * Extract the ``diff`` field from a ToolResultBlock metadata bag, returning
+ * ``undefined`` when missing or empty so callers can use it with ``??``.
+ */
+export function getResultDiff(result: { metadata?: Record<string, unknown> }): string | undefined {
+ const diff = result.metadata?.diff;
+ return typeof diff === 'string' && diff.length > 0 ? diff : undefined;
+}
+
+/**
+ * Compact ``+N -M`` badge used in tool call headers for Edit / Write to show
+ * how many lines were inserted and deleted.
+ */
+export function DiffStats({ insertions, deletions }: { insertions: number; deletions: number }) {
+ return (
+ <div className="flex items-center gap-0.5">
+ <div className="flex items-center text-emerald-600 dark:text-emerald-400">
+ <Plus className="size-2.5 stroke-2" />
+ {formatNumber(insertions)}
+ </div>
+ <div className="flex items-center text-red-600 dark:text-red-400">
+ <Minus className="size-2.5 stroke-2" />
+ {formatNumber(deletions)}
+ </div>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 18c8c8f70..e028c8e56 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -330,7 +330,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
/>
</div>
</div>
- <div className="flex flex-1 justify-center min-h-0 overflow-hidden relative [--chat-content-w:36rem]">
+ <div className="flex flex-1 justify-center min-h-0 overflow-hidden relative [--chat-content-w:48rem]">
<TaskPanel
className="absolute left-0 top-0 h-full max-w-[calc(50%-var(--chat-content-w)/2)]"
tasksContext={tasksContext}
diff --git a/examples/web_ui/frontend/src/types/unidiff.d.ts b/examples/web_ui/frontend/src/types/unidiff.d.ts
new file mode 100644
index 000000000..d273a81ed
--- /dev/null
+++ b/examples/web_ui/frontend/src/types/unidiff.d.ts
@@ -0,0 +1,20 @@
+declare module 'unidiff' {
+ interface DiffOptions {
+ aname?: string;
+ bname?: string;
+ context?: number;
+ pre_context?: number;
+ post_context?: number;
+ format?: 'unified';
+ }
+
+ const unidiff: {
+ diffAsText: (
+ oldText: string | string[],
+ newText: string | string[],
+ options?: DiffOptions,
+ ) => string;
+ };
+
+ export default unidiff;
+}
diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yaml
index f895ec6e6..b67ae5d0d 100644
--- a/examples/web_ui/pnpm-lock.yaml
+++ b/examples/web_ui/pnpm-lock.yaml
@@ -58,8 +58,8 @@ importers:
frontend:
dependencies:
'@agentscope-ai/agentscope':
- specifier: ^0.0.9
- version: 0.0.9
+ specifier: ^0.0.11
+ version: 0.0.11
'@fontsource-variable/geist':
specifier: ^5.2.8
version: 5.2.8
@@ -111,6 +111,9 @@ importers:
react-day-picker:
specifier: ^10.0.1
version: 10.0.1(@types/[email protected])([email protected])
+ react-diff-view:
+ specifier: ^3.3.3
+ version: 3.3.3([email protected])
react-dom:
specifier: ^19.2.6
version: 19.2.6([email protected])
@@ -144,6 +147,9 @@ importers:
tw-animate-css:
specifier: ^1.4.0
version: 1.4.0
+ unidiff:
+ specifier: ^1.0.4
+ version: 1.0.4
vaul:
specifier: ^1.1.2
@@ -199,8 +205,8 @@ importers:
packages:
- '@agentscope-ai/[email protected]':
- resolution: {integrity: sha512-FuELfct2hovIINATNPWEpYktyqe1SYoVb9TCJvQoXqQcj5upik0VJM+8+OBA2y79xWe+rTBO1lr0bhuSGcHrPA==}
+ '@agentscope-ai/[email protected]':
+ resolution: {integrity: sha512-ysPhVS/V+56Jggj+BnOCQpGQiTtvbhWQ/oCaECGT4HbYaSp/txHA4ytYxRttRowf789ummAOGplEBonfQqRkvw==}
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
@@ -2229,6 +2235,9 @@ packages:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
+ resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
+
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
@@ -2441,10 +2450,17 @@ packages:
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
+ resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}
+
resolution: {integrity: sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==}
+ engines: {node: '>=0.3.1'}
+
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
@@ -2835,6 +2851,9 @@ packages:
resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}
+ resolution: {integrity: sha512-YQJnY8aew65id8okGxKCksH3efDCJ9HzV7M9rsvd65habf39Pkh4cgYJ27AaoDMqo1X98pgNJhNMrm/kpV7UVQ==}
+
resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
engines: {node: '>= 6'}
@@ -3258,6 +3277,10 @@ packages:
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
+ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
+ hasBin: true
+
resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==}
@@ -3633,8 +3656,8 @@ packages:
resolution: {integrity: sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==}
engines: {node: '>=20'}
- resolution: {integrity: sha512-IGWPopZq6Rjoynjfb3NSLf/z2MTw7UiOsm9TAjPGAjUESH7Uq41Trg4QWehBEn58p74i+m7uoRPV2vXcpPXhyA==}
+ resolution: {integrity: sha512-09/gH+8jH0RgUwsgWHAaxsKGRT5zVZ95IaJUnqAWj6XejIBmnFRwq2WUIF37VtDEsmGrtPmvCs5+yBSeZGWvkA==}
peerDependencies:
ws: ^8.18.0
zod: ^3.25 || ^4.0
@@ -3822,6 +3845,11 @@ packages:
'@types/react':
optional: true
+ resolution: {integrity: sha512-CPveApk6n7ZbkW7T6PoptR7LWAvD9hohTHZ7WnKnu3GZkTfUB5rvg486apPo94iYVi4fZd3Nt+rtBZ5877exoQ==}
+ peerDependencies:
+ react: '>=16.14.0'
+
resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==}
peerDependencies:
@@ -4028,6 +4056,9 @@ packages:
resolution: {integrity: sha512-70fwnesNrY1GgeD7Kdzn+3SsYeyfibm8immsA5L68+OusoPTvYF01oWExl8/latKpMpvVXcbgdbbE6VFBJQ38w==}
hasBin: true
+ resolution: {integrity: sha512-pfVOw8QZIXpMbhBWvzBISicvToTiM5WBF1EeAUZDDSb5Dt29yl4AYbyywbJFSEsRUMr7gJaxqCdr4L3tQf9wVg==}
+
resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
@@ -4348,6 +4379,9 @@ packages:
resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-ynU0vsAXw0ir8roa+xPCUHmnJ5goc5BTM2Kuc3IJd8UwgaeRs7VSD5+eeaQL+xp1JtB92hu/Zy/Lgy7RZcr1pQ==}
+
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
@@ -4500,6 +4534,9 @@ packages:
resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==}
+
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
@@ -4598,7 +4635,7 @@ packages:
snapshots:
- '@agentscope-ai/[email protected]':
+ '@agentscope-ai/[email protected]':
dependencies:
'@cfworker/json-schema': 4.1.1
'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
@@ -4606,7 +4643,7 @@ snapshots:
jsonrepair: 3.14.0
mime-types: 3.0.2
ollama: 0.6.3
- openai: 6.41.0([email protected])
+ openai: 6.44.0([email protected])
string-format: 2.0.0
uuid: 13.0.2
zod: 4.4.3
@@ -6627,6 +6664,8 @@ snapshots:
dependencies:
clsx: 2.1.1
+
dependencies:
restore-cursor: 5.1.0
@@ -6788,8 +6827,12 @@ snapshots:
dependencies:
dequal: 2.0.3
+
+
@@ -7254,6 +7297,8 @@ snapshots:
dependencies:
resolve-pkg-maps: 1.0.0
+
dependencies:
is-glob: 4.0.3
@@ -7600,6 +7645,10 @@ snapshots:
+ dependencies:
+ js-tokens: 4.0.0
+
dependencies:
tslib: 2.8.1
@@ -8171,7 +8220,7 @@ snapshots:
powershell-utils: 0.1.0
wsl-utils: 0.3.1
optionalDependencies:
zod: 4.4.3
@@ -8400,6 +8449,16 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
+ dependencies:
+ classnames: 2.5.1
+ diff-match-patch: 1.0.5
+ gitdiff-parser: 0.3.1
+ lodash: 4.18.1
+ react: 19.2.6
+ shallow-equal: 3.1.0
+ warning: 4.0.3
+
dependencies:
react: 19.2.6
@@ -8704,6 +8763,8 @@ snapshots:
- supports-color
- typescript
+
dependencies:
'@img/colour': 1.1.0
@@ -9021,6 +9082,10 @@ snapshots:
+ dependencies:
+ diff: 5.2.2
+
dependencies:
'@types/unist': 3.0.3
@@ -9170,6 +9235,10 @@ snapshots:
+ dependencies:
+ loose-envify: 1.4.0
+
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index b3ff5ca16..586524fec 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -1057,6 +1057,7 @@ class Agent:
reply_id=self.state.reply_id,
tool_call_id=tool_result.id,
state=tool_result.state,
+ metadata=tool_result.metadata,
)
self._save_to_context([tool_result])
@@ -1456,6 +1457,7 @@ class Agent:
if isinstance(chunk.content, str)
else chunk.content,
state=chunk.state,
+ metadata=chunk.metadata,
)
# ========================================================
@@ -1524,6 +1526,7 @@ class Agent:
reply_id=self.state.reply_id,
tool_call_id=tool_call.id,
state=chunk.state,
+ metadata=chunk.metadata,
)
else:
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index ee52c97b6..e1d71c75d 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -360,6 +360,8 @@ class ToolResultEndEvent(EventBase):
"""ID of the corresponding tool call."""
state: ToolResultState
"""Final execution state of the tool call."""
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """Optional metadata attached to the tool result event."""
class ExceedMaxItersEvent(EventBase):
diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.py
index 1b5db757b..293af1879 100644
--- a/src/agentscope/message/_base.py
+++ b/src/agentscope/message/_base.py
@@ -416,6 +416,7 @@ class Msg(BaseModel):
else:
assert isinstance(block, ToolResultBlock)
block.state = event.state
+ block.metadata = event.metadata
# The paired ToolCallBlock's lifecycle ends with its
# result — flip it to FINISHED here so the SSE-rebuilt
# reply_msg matches ``agent.state.context``, which
diff --git a/src/agentscope/message/_block.py b/src/agentscope/message/_block.py
index 39b4cc57b..86242ab55 100644
--- a/src/agentscope/message/_block.py
+++ b/src/agentscope/message/_block.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""The content blocks of messages."""
from enum import StrEnum
-from typing import Literal, List, TypeAlias
+from typing import Literal, List, TypeAlias, Any
from pydantic import BaseModel, Field, AnyUrl, field_serializer, ConfigDict
from .._utils._common import _generate_id
@@ -184,6 +184,8 @@ class ToolResultBlock(BaseModel):
text and multimodal blocks."""
state: ToolResultState = ToolResultState.RUNNING
"""The execution state of the tool."""
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """The metadata of the tool result block."""
ContentBlock: TypeAlias = (
diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.py
index 863a71996..f57f12f98 100644
--- a/src/agentscope/tool/_builtin/_edit.py
+++ b/src/agentscope/tool/_builtin/_edit.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""The edit tool in agentscope."""
+import difflib
import fnmatch
import os
from typing import Any, List
@@ -382,6 +383,21 @@ Usage:
replacement_msg = (
f"all {occurrences} occurrences" if replace_all else "1 occurrence"
)
+
+ # Build a unified diff of the change with absolute line numbers so the
+ # web UI can render it with real line numbers and proper inter-hunk
+ # gaps. The diff is kept in ``metadata`` only (not in the textual
+ # output) so it does not bloat the LLM context.
+ diff_text = "".join(
+ difflib.unified_diff(
+ content.splitlines(keepends=True),
+ updated_content.splitlines(keepends=True),
+ fromfile=f"a/{file_path}",
+ tofile=f"b/{file_path}",
+ n=3,
+ ),
+ )
+
return ToolChunk(
content=[
TextBlock(
@@ -391,4 +407,9 @@ Usage:
],
state=ToolResultState.RUNNING,
is_last=True,
+ metadata={
+ "diff": diff_text,
+ "file_path": file_path,
+ "occurrences": occurrences if replace_all else 1,
+ },
)
diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.py
index d7060df82..7215c4b5a 100644
--- a/src/agentscope/tool/_builtin/_write.py
+++ b/src/agentscope/tool/_builtin/_write.py
@@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
"""The write tool in agentscope."""
+import difflib
import fnmatch
import os
+from pathlib import Path
from typing import Any, List
from .._base import ToolBase, ToolMiddlewareBase
@@ -259,6 +261,30 @@ Usage:
is_last=True,
)
+ # Capture the pre-write content (if any) so we can compute a unified
+ # diff for the web UI. For brand-new files this stays as an empty
+ # string, which produces a clean "new file" diff (``--- /dev/null``).
+ # Track ``file_existed`` separately from ``previous_content`` because
+ # an *existing* empty file overwrite is not the same as creating a
+ # new file — the diff header must reflect that.
+ file_existed = await self._backend.file_exists(file_path)
+ previous_content = ""
+ if file_existed:
+ try:
+ previous_content = (
+ await self._backend.read_file(file_path)
+ ).decode("utf-8")
+ except Exception: # pylint: disable=broad-except
+ # Binary or unreadable file — fall back to empty so we still
+ # render a best-effort "add" diff in the UI.
+ previous_content = ""
+
+ # Create parent directories if they don't exist
+ parent_dir = Path(file_path).parent
+ await self._backend.exec_shell(
+ ["mkdir", "-p", str(parent_dir)],
+ )
+
# Write content to file (backend handles parent dir creation)
await self._backend.write_file(
file_path,
@@ -268,6 +294,21 @@ Usage:
# Count lines in content
line_count = len(content.split("\n"))
+ # Build the unified diff between previous and new content. When the
+ # file is brand new, ``unified_diff`` over an empty old side naturally
+ # produces a single "all add" hunk starting at line 1.
+ diff_text = "".join(
+ difflib.unified_diff(
+ previous_content.splitlines(keepends=True),
+ content.splitlines(keepends=True),
+ fromfile=(
+ "/dev/null" if not file_existed else f"a/{file_path}"
+ ),
+ tofile=f"b/{file_path}",
+ n=3,
+ ),
+ )
+
# Return success message
return ToolChunk(
content=[
@@ -278,4 +319,9 @@ Usage:
],
state=ToolResultState.RUNNING,
is_last=True,
+ metadata={
+ "diff": diff_text,
+ "file_path": file_path,
+ "occurrences": 1,
+ },
)
diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.py
index f13c67cf3..759323da3 100644
--- a/tests/agent_basic_test.py
+++ b/tests/agent_basic_test.py
@@ -795,6 +795,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
],
"name": "mock_sequential_tool",
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -808,6 +809,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
],
"name": "mock_sequential_tool",
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -1034,6 +1036,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
],
"name": "mock_concurrent_tool",
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1047,6 +1050,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
],
"name": "mock_concurrent_tool",
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -1170,11 +1174,12 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "TOOL_RESULT_END",
"tool_call_id": tool_call_id_1,
"state": "success",
+ "metadata": {},
},
]
# Expected concurrent events (order may vary)
- expected_concurrent = [
+ expected_concurrent: list[dict[str, Any]] = [
{
"type": "TOOL_RESULT_START",
"tool_call_id": tool_call_id_2,
@@ -1204,6 +1209,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"type": "TOOL_RESULT_END",
"tool_call_id": tool_call_id_3,
"state": "success",
+ "metadata": {},
},
]
@@ -1317,6 +1323,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"text": "Sequential result: seq1",
},
],
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1330,6 +1337,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"text": "Concurrent result: conc1",
},
],
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1343,6 +1351,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
"text": "Concurrent result: conc2",
},
],
+ "metadata": {},
},
{
"type": "text",
diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.py
index 3f261af53..72752fdd5 100644
--- a/tests/event_to_message_test.py
+++ b/tests/event_to_message_test.py
@@ -135,6 +135,7 @@ def _trb(tc_id: str, name: str, output: Any, state: str) -> dict:
"name": name,
"output": output,
"state": state,
+ "metadata": {},
}
diff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.py
index 8bb381faa..498553794 100644
--- a/tests/hitl_external_execution_test.py
+++ b/tests/hitl_external_execution_test.py
@@ -453,6 +453,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -738,6 +739,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -751,6 +753,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "error",
+ "metadata": {},
},
{
"type": "text",
@@ -1037,6 +1040,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1050,6 +1054,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -1305,6 +1310,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1318,6 +1324,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.py
index e8820a503..2e6e2d5ce 100644
--- a/tests/hitl_user_confirmation_test.py
+++ b/tests/hitl_user_confirmation_test.py
@@ -455,6 +455,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -788,6 +789,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -801,6 +803,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
@@ -1138,6 +1141,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "tool_result",
@@ -1151,6 +1155,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
index 6ac7631e3..198a7dc4c 100644
--- a/tests/workspace_local_test.py
+++ b/tests/workspace_local_test.py
@@ -932,6 +932,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):
},
],
"state": "success",
+ "metadata": {},
},
{
"type": "text",