Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(webui): fix rendering errors in Read/Write/Edit tools caused by incomplete JSON during tool call streaming or interruption (#2075)
DavdGao4cb5832075e7
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.tsxindex 07a0d53b4..19e079294 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@@ -2,7 +2,7 @@ import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';import * as mime from 'mime-types';import type { ReactNode } from 'react';-import { toolArgClass, toolLabelClass } from './_shared';+import { getResultText, toolArgClass, toolLabelClass } from './_shared';import type { TFunction, ToolCallWithResult } from './types';export function defaultGetDisplayName(call: ToolCallBlock): string {@@ -40,10 +40,21 @@ export function defaultRenderBody(pair: ToolCallWithResult, t: TFunction): Reactconst { call, result } = pair;if (!result) return null;if (call.state === 'asking' || result.state === 'running') {- return <span>{t('common.running')} ...</span>;+ return (+ <div className="flex flex-col border rounded-sm bg-background">+ <div className="px-2 py-1 whitespace-nowrap overflow-x-auto">+ {t('common.running')}+ </div>+ </div>+ );}if (result.state === 'interrupted') {- return <span>{t('common.interrupted')}</span>;+ const result = getResultText(pair.result);+ return (+ <div className="flex flex-col border rounded-sm bg-background">+ <div className="px-2 py-1 whitespace-nowrap overflow-x-auto">{result}</div>+ </div>+ );}// TODO: render multimodal outputsdiff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/EditRenderer.tsxindex 3c404dce1..36e724b86 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@@ -7,12 +7,12 @@ import {countDiffStats,DiffStats,FramedFileBody,- getFilePath,getResultDiff,parseInput,toolArgClass,toolLabelClass,tryGetFileName,+ tryGetFilePath,} from '@/components/chat/tool-renderers/_shared.tsx';/**@@ -49,7 +49,7 @@ export const EditRenderer: ToolRenderer = {renderConfirmBody: (call) => (<div className="w-full max-w-full overflow-hidden text-ellipsis truncate">- <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ <div className="text-secondary-foreground">{tryGetFilePath(call.input)}</div></div>),@@ -69,7 +69,9 @@ export const EditRenderer: ToolRenderer = {},renderBody: (pair, t) => {- if (!pair.result) return null;+ // Until the call has actually run there's no file change to frame — the+ // input is still streaming in as partial JSON.+ if (!pair.result || pair.result.state === 'running') return undefined;if (pair.result.state === 'success') {// The backend Edit tool always attaches a unified diff (absolute line// numbers, one hunk per replaced occurrence). A client-side diff of@@ -78,12 +80,13 @@ export const EditRenderer: ToolRenderer = {const diff = getResultDiff(pair.result);if (diff) {return (- <FramedFileBody filePath={getFilePath(pair.call.input)}>+ <FramedFileBody filePath={tryGetFilePath(pair.call.input)}><DiffPreview unifiedDiff={diff} /></FramedFileBody>);}}+ // Errors / interruptions aren't file content, so drop the path frame.return defaultRenderBody(pair, 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.tsxindex df6f27ca9..dc7980ff9 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,12 +1,12 @@import {FramedFileBody,- getFilePath,- getFileName,getResultText,- parseInput,toolArgClass,toolLabelClass,+ tryGetFileName,+ tryGetFilePath,} from './_shared';+import { defaultRenderBody } from './DefaultRenderer';import { DiffPreview } from './DiffPreview';import type { ToolRenderer } from './types';@@ -44,18 +44,18 @@ export const ReadRenderer: ToolRenderer = {renderConfirmBody: (call) => (<div className="w-full max-w-full overflow-hidden text-ellipsis truncate">- <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ <div className="text-secondary-foreground">{tryGetFilePath(call.input)}</div></div>),renderHeader: (pair) => {- const fileName = getFileName(parseInput(pair.call.input).file_path as string);+ const fileName = tryGetFileName(pair.call.input);const readContent = getResultText(pair.result);const lines = readContent ? readContent.split('\n').length : 0;return (<><span className={toolLabelClass}>Read</span>- <span className={toolArgClass}>{fileName}</span>+ {fileName && <span className={toolArgClass}>{fileName}</span>}{pair.result?.state === 'success' && (<span className={toolLabelClass}>{lines} lines</span>)}@@ -63,19 +63,15 @@ export const ReadRenderer: ToolRenderer = {);},- renderBody: (pair) => {- if (!pair.result) return null;- const filePath = parseInput(pair.call.input).file_path as string;- const readContent = getResultText(pair.result);+ renderBody: (pair, t) => {+ // Until the call has actually run there's no file content to frame — the+ // input is still streaming in as partial JSON.+ if (!pair.result || pair.result.state === 'running') return undefined;+ // Errors / interruptions aren't file content, so drop the path frame.+ if (pair.result.state !== 'success') return defaultRenderBody(pair, t);return (- <FramedFileBody filePath={filePath}>- {pair.result.state === 'error' ? (- // Errors aren't file content, so show the raw message rather than- // forcing it through the diff renderer.- <div className="overflow-x-auto p-2 font-mono text-xs">{readContent}</div>- ) : (- <DiffPreview unifiedDiff={buildContextDiff(readContent)} />- )}+ <FramedFileBody filePath={tryGetFilePath(pair.call.input)}>+ <DiffPreview unifiedDiff={buildContextDiff(getResultText(pair.result))} /></FramedFileBody>);},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.tsxindex a989aa2fe..3d321bbc2 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@@ -5,11 +5,11 @@ import {countDiffStats,DiffStats,FramedFileBody,- getFilePath,getResultDiff,toolArgClass,toolLabelClass,tryGetFileName,+ tryGetFilePath,} from '@/components/chat/tool-renderers/_shared.tsx';export const WriteRenderer: ToolRenderer = {@@ -17,13 +17,12 @@ export const WriteRenderer: ToolRenderer = {renderConfirmBody: (call) => (<div className="w-full max-w-full overflow-hidden text-ellipsis truncate">- <div className="text-secondary-foreground">{getFilePath(call.input)}</div>+ <div className="text-secondary-foreground">{tryGetFilePath(call.input)}</div></div>),renderHeader: (pair) => {const fileName = tryGetFileName(pair.call.input);- if (!fileName) return <span className={toolLabelClass}>{pair.call.name}</span>;// Pre-execution we only know the new ``content`` (not the previous file// body), so any ``+N`` count would be misleading on overwrites. Show the// real ``+N -M`` only once the backend post-execution diff has arrived.@@ -32,14 +31,16 @@ export const WriteRenderer: ToolRenderer = {return (<><span className={toolLabelClass}>{pair.call.name}</span>- <span className={toolArgClass}>{fileName}</span>+ {fileName && <span className={toolArgClass}>{fileName}</span>}{stats && <DiffStats insertions={stats.insertions} deletions={stats.deletions} />}</>);},renderBody: (pair, t) => {- if (!pair.result) return null;+ // Until the call has actually run there's no file change to frame — the+ // input is still streaming in as partial JSON.+ if (!pair.result || pair.result.state === 'running') return undefined;if (pair.result.state === 'success') {// The backend Write tool always attaches a unified diff (new-file// creation against /dev/null or an overwrite with absolute line@@ -47,12 +48,13 @@ export const WriteRenderer: ToolRenderer = {const diff = getResultDiff(pair.result);if (diff) {return (- <FramedFileBody filePath={getFilePath(pair.call.input)}>+ <FramedFileBody filePath={tryGetFilePath(pair.call.input)}><DiffPreview unifiedDiff={diff} /></FramedFileBody>);}}+ // Errors / interruptions aren't file content, so drop the path frame.return defaultRenderBody(pair, 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.tsxindex e22ea2bdb..2695d20e6 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@@ -116,50 +116,36 @@ export function ToolCallRow({*/export function parseInput(input: string): Record<string, unknown> {try {- return JSON.parse(input);+ const parsed = JSON.parse(input);+ return parsed && typeof parsed === 'object' ? parsed : {};} catch {return {};}}/**- * Get the filepath from the input arguments+ * Get the filepath from the input arguments.* @param input- * @returns The filepath from the input string+ * @returns The filepath, or ``undefined`` when ``input`` isn't yet a complete+ * JSON object carrying a non-empty ``file_path`` — a tool call's arguments+ * stream in as partial JSON, and a fragment of ``content`` must never pass for+ * a path.*/-export function getFilePath(input: string): string {- const { file_path } = parseInput(input) as { file_path?: string };- return file_path || input;+export function tryGetFilePath(input: string): string | undefined {+ const { file_path } = parseInput(input) as { file_path?: unknown };+ return typeof file_path === 'string' && file_path.length > 0 ? file_path : undefined;}/**- * Get the filename+ * The basename of ``file_path``, or ``undefined`` while the tool-call JSON is+ * still streaming. Use this in ``renderHeader`` so a partial input renders no+ * file name rather than a garbled one.* @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 ``renderHeader`` 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).+ * @returns The filename, considering different OS path separators.*/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 filePath = tryGetFilePath(input);+ if (!filePath) return undefined;const segments = filePath.split(/[/\\]+/).filter(Boolean);return segments.length > 0 ? segments[segments.length - 1] : filePath;}@@ -195,11 +181,15 @@ export function getResultDiff(result: { metadata?: Record<string, unknown> }): s* bordered card with the file path as a header, a separator, then the tool's* own content (numbered source lines for Read, a diff for Edit / Write).*/-export function FramedFileBody({ filePath, children }: { filePath: string; children: ReactNode }) {+export function FramedFileBody({ filePath, children }: { filePath?: string; children: ReactNode }) {return (<div className="flex flex-col border rounded-sm bg-background">- <div className="px-2 py-1 whitespace-nowrap overflow-x-auto">{filePath}</div>- <Separator />+ {filePath && (+ <>+ <div className="px-2 py-1 whitespace-nowrap overflow-x-auto">{filePath}</div>+ <Separator />+ </>+ )}{children}</div>);@@ -212,18 +202,15 @@ export function FramedFileBody({ filePath, children }: { filePath: string; childexport function DiffStats({ insertions, deletions }: { insertions: number; deletions: number }) {return (<div className="flex items-center gap-0.5">- {insertions && (- <div className="flex items-center text-emerald-600 dark:text-emerald-400">- <Plus className="size-2.5 stroke-2" />- {formatNumber(insertions)}- </div>- )}- {deletions && (- <div className="flex items-center text-red-600 dark:text-red-400">- <Minus className="size-2.5 stroke-2" />- {formatNumber(deletions)}- </div>- )}+ <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>);}