Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(local-system): report computer-tool failures as failures, and refuse ambiguous edits (#18539)

Arvin Xu51b7420c955b
diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.ts
index 43c174fbb25..4c8c72cbfdc 100644
--- a/apps/cli/src/tools/index.test.ts
+++ b/apps/cli/src/tools/index.test.ts
@@ -197,8 +197,9 @@ describe('executeToolCall', () => {
JSON.stringify({ shell_id: 'nonexistent' }),
);
- // The runtime envelopes a failed lookup as success:true with the failure in state
- expect(result.success).toBe(true);
+ // A lookup against an unknown shell is a failed call, and `success` is what
+ // the tool_end event and `usage.tools.byTool[].errors` read.
+ expect(result.success).toBe(false);
expect((result.state as { success: boolean }).success).toBe(false);
});
@@ -220,7 +221,7 @@ describe('executeToolCall', () => {
JSON.stringify({ shell_id: 'nonexistent' }),
);
- expect(result.success).toBe(true);
+ expect(result.success).toBe(false);
expect((result.state as { success: boolean }).success).toBe(false);
});
});
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 842daebd01a..8497cefdaa9 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -943,8 +943,8 @@ describe('LocalFileCtr', () => {
});
describe('handleEditFile', () => {
- it('should replace first occurrence successfully', async () => {
- const originalContent = 'Hello world\nHello again\nGoodbye world';
+ it('should replace a unique occurrence successfully', async () => {
+ const originalContent = 'Hello world\nGreetings again\nGoodbye world';
vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);
@@ -962,11 +962,32 @@ describe('LocalFileCtr', () => {
expect(result.diffText).toContain('diff --git a/test/file.txt b/test/file.txt');
expect(mockFsPromises.writeFile).toHaveBeenCalledWith(
'/test/file.txt',
- 'Hi world\nHello again\nGoodbye world',
+ 'Hi world\nGreetings again\nGoodbye world',
'utf8',
);
});
+ // Editing an arbitrary one of several matches is worse than not editing:
+ // the caller was told "replaced 1 occurrence(s)" either way, so a wrong
+ // target went unnoticed.
+ it('should refuse an ambiguous old_string instead of editing the first match', async () => {
+ const originalContent = 'Hello world\nHello again\nGoodbye world';
+ vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
+
+ const result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.txt',
+ old_string: 'Hello',
+ new_string: 'Hi',
+ replace_all: false,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.replacements).toBe(0);
+ expect(result.error).toContain('not unique');
+ expect(result.error).toContain('L1, L2');
+ expect(mockFsPromises.writeFile).not.toHaveBeenCalled();
+ });
+
it('should replace all occurrences when replace_all is true', async () => {
const originalContent = 'Hello world\nHello again\nHello there';
vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
@@ -1020,7 +1041,9 @@ describe('LocalFileCtr', () => {
});
expect(result.success).toBe(false);
- expect(result.error).toBe('The specified old_string was not found in the file');
+ // The message now names the file and why the match failed.
+ expect(result.error).toContain('The specified old_string was not found in /test/file.txt');
+ expect(result.error).toContain('None of it appears in the file');
expect(result.replacements).toBe(0);
expect(mockFsPromises.writeFile).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 14e2d9c5650..72cd2407ec1 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -449,11 +449,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
success?: boolean;
};
- // `response.success` is the delivery envelope only: the device-side
- // ComputerRuntime reports service failures (spawn error, shell lost,
- // missing params) as `success: true` with `state.success: false` and no
- // exitCode (`errorOutput`) — without this check they'd fall through to
- // the still-running branch below and read as a successful run.
+ // `response.success` is the delivery envelope. Device-side service
+ // failures (spawn error, shell lost, missing params) now come back with
+ // `success: false`, but desktop builds predating that fix report them as
+ // `success: true` with `state.success: false` and no exitCode — and a
+ // device runs whatever version the user has installed. Keep testing both
+ // or those runs fall through to the still-running branch below and read
+ // as a successful run.
if (!response.success || state.success === false) {
return fail(
state.stderr ||
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 929649d0dd7..9815fb0c9c4 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -128,10 +128,11 @@
"lobe-agent.updateTodos.updated": "To-do list updated",
"lobe-knowledge-base.readKnowledge.meta.chars": "Character Count",
"lobe-knowledge-base.readKnowledge.meta.lines": "Line Count",
+ "localFiles.editFile.ambiguous": "This text appears {{times}} times in the file. The edit will be refused — it needs enough surrounding context to identify one occurrence, or \"replace all\".",
"localFiles.editFile.newString": "Replace with",
"localFiles.editFile.oldString": "Find",
"localFiles.editFile.replaceAll": "Replace all occurrences",
- "localFiles.editFile.replaceFirst": "Replace first occurrence only",
+ "localFiles.editFile.replaceFirst": "Replace the single occurrence",
"localFiles.file": "File",
"localFiles.folder": "Folder",
"localFiles.globFiles.pattern": "Pattern",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 6920920ef42..00dd168d133 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -128,10 +128,11 @@
"lobe-agent.updateTodos.updated": "待办事项已更新",
"lobe-knowledge-base.readKnowledge.meta.chars": "字符数",
"lobe-knowledge-base.readKnowledge.meta.lines": "行数",
+ "localFiles.editFile.ambiguous": "这段文本在文件中出现了 {{times}} 次。此次编辑会被拒绝 —— 需要带上足够的上下文来唯一定位一处,或改用「替换全部」。",
"localFiles.editFile.newString": "替换为",
"localFiles.editFile.oldString": "查找",
"localFiles.editFile.replaceAll": "替换全部匹配项",
- "localFiles.editFile.replaceFirst": "仅替换第一个匹配项",
+ "localFiles.editFile.replaceFirst": "替换该唯一匹配项",
"localFiles.file": "文件",
"localFiles.folder": "文件夹",
"localFiles.globFiles.pattern": "模式",
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
index 79e918f2064..3b17d4f7427 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
@@ -1,6 +1,7 @@
import type { EditLocalFileParams } from '@lobechat/electron-client-ipc';
import type { BuiltinInterventionProps } from '@lobechat/types';
import { CodeDiff, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { Alert } from '@lobehub/ui/base-ui';
import { ChevronRight } from 'lucide-react';
import path from 'path-browserify-esm';
import { memo, useMemo } from 'react';
@@ -26,18 +27,31 @@ const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ arg
},
);
- // Generate new content by applying the replacement
- const { oldContent, newContent } = useMemo(() => {
- if (!fileData?.content) return { newContent: '', oldContent: '' };
+ // Generate new content by applying the replacement.
+ //
+ // A single-occurrence edit whose old_string matches more than once is
+ // refused by the runtime, so previewing `String.replace`'s first-match result
+ // would show the user a concrete diff to approve that can never be applied.
+ // Count the matches and say so instead.
+ const { oldContent, newContent, matchCount } = useMemo(() => {
+ if (!fileData?.content) return { matchCount: 0, newContent: '', oldContent: '' };
const oldContent = fileData.content;
+ const matchCount = args.old_string ? oldContent.split(args.old_string).length - 1 : 0;
+
+ if (!args.replace_all && matchCount > 1) {
+ return { matchCount, newContent: oldContent, oldContent };
+ }
+
const newContent = args.replace_all
? oldContent.replaceAll(args.old_string, args.new_string)
: oldContent.replace(args.old_string, args.new_string);
- return { newContent, oldContent };
+ return { matchCount, newContent, oldContent };
}, [fileData?.content, args.old_string, args.new_string, args.replace_all]);
+ const isAmbiguous = !args.replace_all && matchCount > 1;
+
return (
<Flexbox gap={12}>
<OutOfScopeWarning paths={[args.file_path]} />
@@ -51,20 +65,30 @@ const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ arg
<Skeleton active paragraph={{ rows: 3 }} />
) : (
<Flexbox gap={8}>
- <Text type="secondary">
- {args.replace_all
- ? t('localFiles.editFile.replaceAll')
- : t('localFiles.editFile.replaceFirst')}
- </Text>
- {oldContent && (
- <CodeDiff
- fileName={args.file_path}
- newContent={newContent}
- oldContent={oldContent}
- showHeader={false}
- variant="borderless"
- viewMode="split"
+ {isAmbiguous ? (
+ <Alert
+ showIcon
+ description={t('localFiles.editFile.ambiguous', { times: matchCount })}
+ type="warning"
/>
+ ) : (
+ <>
+ <Text type="secondary">
+ {args.replace_all
+ ? t('localFiles.editFile.replaceAll')
+ : t('localFiles.editFile.replaceFirst')}
+ </Text>
+ {oldContent && (
+ <CodeDiff
+ fileName={args.file_path}
+ newContent={newContent}
+ oldContent={oldContent}
+ showHeader={false}
+ variant="borderless"
+ viewMode="split"
+ />
+ )}
+ </>
)}
</Flexbox>
)}
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.test.ts b/packages/builtin-tool-local-system/src/client/executor/index.test.ts
index bfdec1fac0b..3fcb1f736de 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.test.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.test.ts
@@ -109,7 +109,10 @@ describe('LocalSystemExecutor', () => {
pattern: '**/*Financial*Statement*',
});
- expect(result.success).toBe(true);
+ // The failure is reported as one: `success` feeds the tool_end event and
+ // `usage.tools.byTool[].errors`, so a permission-denied glob must not
+ // count as a successful call.
+ expect(result.success).toBe(false);
expect(result.content).toBeTruthy();
expect(result.content).toContain('EACCES');
expect(result.state).toEqual({
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index be450029f4b..9779dcbd909 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -190,7 +190,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
defaultTimeoutMs: 30_000,
description:
- 'Perform exact string replacements in files. Must read the file first before editing.',
+ 'Perform exact string replacements in files. Must read the file first before editing. old_string must match exactly once unless replace_all is set.',
humanIntervention: {
dynamic: {
default: 'never',
@@ -210,7 +210,8 @@ export const LocalSystemManifest: BuiltinToolManifest = {
type: 'string',
},
old_string: {
- description: 'The exact text to replace',
+ description:
+ 'The exact text to replace. Must be unique in the file — include surrounding lines to disambiguate — unless replace_all is true',
type: 'string',
},
replace_all: {
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 10317e00ede..845b8ee0597 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -73,7 +73,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'file_path': The absolute path to the file to modify.
- 'old_string': The exact text to replace.
- 'new_string': The replacement text.
- - 'replace_all' (Optional): Replace all occurrences.
+ - 'replace_all' (Optional): Replace all occurrences. Without it, 'old_string' must match exactly once — include surrounding lines to make it unique, or the edit is refused rather than applied to an arbitrary match.
- For executing shell commands: Use 'runCommand'. Provide the following parameters:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index ceb2f4fe449..ccd768c5cf5 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -72,7 +72,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'file_path': The absolute path to the file to modify.
- 'old_string': The exact text to replace.
- 'new_string': The replacement text.
- - 'replace_all' (Optional): Replace all occurrences.
+ - 'replace_all' (Optional): Replace all occurrences. Without it, 'old_string' must match exactly once — include surrounding lines to make it unique, or the edit is refused rather than applied to an arbitrary match.
- For executing shell commands: Use 'runCommand'. Provide the following parameters:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.ts
index 4ae4771c5d9..f75712441a5 100644
--- a/packages/local-file-shell/src/file/__tests__/file.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts
@@ -216,9 +216,9 @@ describe('file operations', () => {
// ─── editLocalFile ───
describe('editLocalFile', () => {
- it('should replace first occurrence by default', async () => {
+ it('should replace the single occurrence by default', async () => {
const filePath = path.join(tmpDir, 'edit.txt');
- await writeFile(filePath, 'hello world\nhello again');
+ await writeFile(filePath, 'hello world\ngoodbye again');
const result = await editLocalFile({
file_path: filePath,
@@ -228,12 +228,63 @@ describe('file operations', () => {
expect(result.success).toBe(true);
expect(result.replacements).toBe(1);
- expect(fs.readFileSync(filePath, 'utf8')).toBe('hi world\nhello again');
+ expect(fs.readFileSync(filePath, 'utf8')).toBe('hi world\ngoodbye again');
expect(result.diffText).toBeDefined();
expect(result.linesAdded).toBeDefined();
expect(result.linesDeleted).toBeDefined();
});
+ // Picking the first of several matches silently resolves an ambiguity the
+ // caller never sees: the tool used to report "replaced 1 occurrence(s)"
+ // while the edit may have landed on the wrong one.
+ it('refuses an ambiguous old_string instead of editing an arbitrary match', async () => {
+ const filePath = path.join(tmpDir, 'ambiguous.txt');
+ await writeFile(filePath, 'hello world\nhello again');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'hi',
+ old_string: 'hello',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.replacements).toBe(0);
+ expect(result.error).toContain('not unique');
+ expect(result.error).toContain('L1, L2');
+ expect(result.error).toContain('replace_all');
+ // The file must be untouched.
+ expect(fs.readFileSync(filePath, 'utf8')).toBe('hello world\nhello again');
+ });
+
+ it('reports at most five match locations for a heavily repeated old_string', async () => {
+ const filePath = path.join(tmpDir, 'many.txt');
+ await writeFile(filePath, Array.from({ length: 9 }, () => 'dup').join('\n'));
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'x',
+ old_string: 'dup',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('L1, L2, L3, L4, L5, …');
+ });
+
+ it('still allows an ambiguous old_string when replace_all is set', async () => {
+ const filePath = path.join(tmpDir, 'ambiguous-all.txt');
+ await writeFile(filePath, 'hello world\nhello again');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'hi',
+ old_string: 'hello',
+ replace_all: true,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.replacements).toBe(2);
+ });
+
it('should replace all occurrences when replace_all is true', async () => {
const filePath = path.join(tmpDir, 'edit-all.txt');
await writeFile(filePath, 'hello world\nhello again');
@@ -262,6 +313,85 @@ describe('file operations', () => {
expect(result.success).toBe(false);
expect(result.replacements).toBe(0);
+ expect(result.error).toContain(filePath);
+ });
+
+ // A bare "not found" makes the agent spend a readFile + LLM round trip just
+ // to learn why. The content is already in hand here, so name the cause.
+ describe('not-found diagnosis', () => {
+ it('points at whitespace when the block matches apart from indentation', async () => {
+ const filePath = path.join(tmpDir, 'indent.txt');
+ await writeFile(filePath, 'function f() {\n return 1;\n}');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'function f() {\n return 2;\n}',
+ // Same block, re-indented to 2 spaces — the classic miss.
+ old_string: 'function f() {\n return 1;\n}',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('whitespace/indentation');
+ });
+
+ it('points at letter case when the block matches apart from case', async () => {
+ const filePath = path.join(tmpDir, 'case.txt');
+ await writeFile(filePath, 'const Enabled = true;');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'const enabled = false;',
+ old_string: 'const enabled = true;',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('letter case');
+ });
+
+ it('anchors on the first line when the block diverges partway', async () => {
+ const filePath = path.join(tmpDir, 'diverge.txt');
+ await writeFile(filePath, 'header\n## images\n- p01: current\nfooter');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: '## images\n- p01: next',
+ old_string: '## images\n- p01: stale',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('L2');
+ expect(result.error).toContain('diverges');
+ });
+
+ it('says the text is absent when nothing matches', async () => {
+ const filePath = path.join(tmpDir, 'absent.txt');
+ await writeFile(filePath, 'hello world');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'hi',
+ old_string: 'xyz',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('None of it appears in the file');
+ });
+
+ // The CRLF fallback runs before the diagnosis; a `\n` old_string against a
+ // CRLF file must still edit rather than report a whitespace mismatch.
+ it('still edits CRLF files instead of diagnosing them', async () => {
+ const filePath = path.join(tmpDir, 'crlf.txt');
+ await writeFile(filePath, 'alpha\r\nbeta\r\ngamma');
+
+ const result = await editLocalFile({
+ file_path: filePath,
+ new_string: 'beta\nBETA',
+ old_string: 'beta\ngamma',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.replacements).toBe(1);
+ });
});
it('should handle special regex characters in old_string with replace_all', async () => {
diff --git a/packages/local-file-shell/src/file/edit.ts b/packages/local-file-shell/src/file/edit.ts
index 093cb4e9944..69bb66849a2 100644
--- a/packages/local-file-shell/src/file/edit.ts
+++ b/packages/local-file-shell/src/file/edit.ts
@@ -5,6 +5,83 @@ import { createPatch } from 'diff';
import type { EditFileParams, EditFileResult } from '../types';
import { resolveAgainstCwd } from './expandTilde';
+/** Cap the diagnosis scan so a stray edit against a huge file stays cheap. */
+const DIAGNOSIS_MAX_BYTES = 2_000_000;
+
+const squashWhitespace = (s: string) => s.replaceAll(/\s+/g, ' ').trim();
+
+/**
+ * Explain *why* an `old_string` didn't match.
+ *
+ * A bare "not found" costs the agent a whole extra round trip — re-read the
+ * file, re-diff by eye, retry — and at a large context that round trip is
+ * ~30-60s of wall clock. Nearly every miss is one of a handful of causes
+ * (indentation copied wrong, the text drifted since the last read, the wrong
+ * file), and the file content needed to tell them apart is already in hand
+ * here. Naming the cause lets the model fix the call instead of investigating
+ * it.
+ */
+const diagnoseMissingSearch = (content: string, search: string): string | undefined => {
+ if (content.length > DIAGNOSIS_MAX_BYTES) return;
+
+ const lines = content.split('\n');
+ const firstSearchLine = search.split('\n')[0].trim();
+
+ // Same text, different whitespace — by far the most common cause: the model
+ // reproduced the block from memory and normalized the indentation.
+ const squashedSearch = squashWhitespace(search);
+ if (squashedSearch.length > 0 && squashWhitespace(content).includes(squashedSearch)) {
+ return 'A block matching it apart from whitespace/indentation IS present. Re-read the exact lines and copy their leading whitespace verbatim.';
+ }
+
+ // Same text, different case.
+ if (search.length > 0 && content.toLowerCase().includes(search.toLowerCase())) {
+ return 'A block matching it apart from letter case IS present. old_string is case-sensitive — copy the text exactly as it appears.';
+ }
+
+ // The block starts where expected but diverges partway: point at the anchor
+ // so the model re-reads that region rather than the whole file.
+ if (firstSearchLine.length > 0) {
+ const anchors: number[] = [];
+ for (const [index, line] of lines.entries()) {
+ if (line.trim() === firstSearchLine) anchors.push(index + 1);
+ if (anchors.length >= 5) break;
+ }
+ if (anchors.length > 0) {
+ const where = anchors.map((n) => `L${n}`).join(', ');
+ return `Its first line matches at ${where}, but the block diverges after that. Re-read from there and copy the current text.`;
+ }
+ }
+
+ return 'None of it appears in the file. The content may have changed since you last read it, or this may be the wrong file — read the file before retrying.';
+};
+
+/**
+ * Line numbers (1-indexed) of every non-overlapping occurrence of `search`,
+ * capped — the message only needs enough of them to be actionable.
+ */
+const findOccurrenceLines = (content: string, search: string, cap: number): number[] => {
+ const lines: number[] = [];
+ let from = 0;
+ let consumedLines = 0;
+ let consumedUpTo = 0;
+
+ while (lines.length < cap) {
+ const index = content.indexOf(search, from);
+ if (index === -1) break;
+
+ // Count newlines incrementally rather than slicing from 0 each time, so a
+ // string that occurs thousands of times stays linear in the file size.
+ for (let i = consumedUpTo; i < index; i++) if (content[i] === '\n') consumedLines++;
+ consumedUpTo = index;
+
+ lines.push(consumedLines + 1);
+ from = index + search.length;
+ }
+
+ return lines;
+};
+
export async function editLocalFile({
file_path: rawPath,
old_string,
@@ -34,13 +111,37 @@ export async function editLocalFile({
}
if (!content.includes(search)) {
+ const diagnosis = diagnoseMissingSearch(content, search);
return {
- error: 'The specified old_string was not found in the file',
+ error: [`The specified old_string was not found in ${filePath}`, diagnosis]
+ .filter(Boolean)
+ .join(' '),
replacements: 0,
success: false,
};
}
+ // A single-occurrence edit whose old_string matches in more than one place
+ // is ambiguous, and picking the first match silently resolves that
+ // ambiguity in a way the caller never sees: the tool reports "Successfully
+ // replaced 1 occurrence(s)" while the edit may well have landed on the
+ // wrong one. Refuse instead, and say what would make the call unambiguous.
+ if (!replace_all) {
+ const occurrenceLines = findOccurrenceLines(content, search, 6);
+ if (occurrenceLines.length > 1) {
+ const shown = occurrenceLines
+ .slice(0, 5)
+ .map((n) => `L${n}`)
+ .join(', ');
+ const more = occurrenceLines.length > 5 ? ', …' : '';
+ return {
+ error: `The specified old_string is not unique in ${filePath} — it matches at ${shown}${more}. Include enough surrounding context to identify the one you mean, or pass replace_all: true to change every occurrence.`,
+ replacements: 0,
+ success: false,
+ };
+ }
+ }
+
let newContent: string;
let replacements: number;
@@ -52,7 +153,11 @@ export async function editLocalFile({
} else {
const index = content.indexOf(search);
if (index === -1) {
- return { error: 'Old string not found', replacements: 0, success: false };
+ return {
+ error: `The specified old_string was not found in ${filePath}`,
+ replacements: 0,
+ success: false,
+ };
}
newContent = content.slice(0, index) + replace + content.slice(index + search.length);
replacements = 1;
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index 498da06ddde..f5c8f45a84d 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -137,7 +137,9 @@ export default {
'localFiles.editFile.newString': 'Replace with',
'localFiles.editFile.oldString': 'Find',
'localFiles.editFile.replaceAll': 'Replace all occurrences',
- 'localFiles.editFile.replaceFirst': 'Replace first occurrence only',
+ 'localFiles.editFile.ambiguous':
+ 'This text appears {{times}} times in the file. The edit will be refused — it needs enough surrounding context to identify one occurrence, or "replace all".',
+ 'localFiles.editFile.replaceFirst': 'Replace the single occurrence',
'localFiles.file': 'File',
'localFiles.folder': 'Folder',
'localFiles.globFiles.pattern': 'Pattern',
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 64f4deb4fc7..973aabd6edb 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -536,10 +536,37 @@ export abstract class ComputerRuntime {
(typeof state?.stderr === 'string' ? state.stderr : undefined) ||
(typeof state?.error === 'string' ? state.error : undefined) ||
'[UNKNOWN_EXEC_ERROR] Tool execution failed';
+
return {
content: errorText,
+ // `success` is what the tool_end event reports as `isSuccess`, what
+ // `UsageCounter.accumulateTool` counts into `usage.tools.byTool[].errors`,
+ // and what the trace inspector prints as ✓/✗. Reporting `true` on this
+ // path made every computer-tool failure — an old_string that isn't in the
+ // file, a shell that never spawned, an unreadable path — indistinguishable
+ // from a success in both the UI and the metrics: `errors` was
+ // structurally pinned at 0 for the whole family. (A command that spawns
+ // and exits non-zero does not come through here: `runCommand` reports it
+ // on the success path via `state.success` / `exitCode`, since plenty of
+ // tools exit non-zero by design.)
+ //
+ // `error` is what reaches `pluginError`. The Render components already
+ // branch on it (EditLocalFile shows an "Edit Failed" alert); with it
+ // unset a failed edit had neither a diff nor an error to draw and
+ // rendered as an empty card.
+ //
+ // What the model sees is unchanged: `ToolMessageReorder` prefers a
+ // non-empty `content` over `pluginError.message`, and `content` still
+ // carries the same text.
+ //
+ // Deliberately a fresh `{ message }` rather than forwarding
+ // `result.error`: `executeToolWithRetry` escalates on
+ // `error.kind === 'retry'`, and these failures were never retried while
+ // they claimed success. Flipping the flag should not quietly enrol them
+ // in the retry loop.
+ error: { message: errorText },
state,
- success: true,
+ success: false,
};
}
}
diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
index c5f7bf5fe5f..25f62f52ff4 100644
--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
@@ -23,7 +23,7 @@ const createService = (overrides: Partial<ILocalSystemService> = {}): ILocalSyst
});
describe('LocalSystemExecutionRuntime.editFile', () => {
- it('surfaces the underlying error message instead of UNKNOWN_EXEC_ERROR', async () => {
+ it('reports a failed edit as a failure, with the underlying message intact', async () => {
const service = createService({
editLocalFile: vi.fn().mockResolvedValue({
error: 'The specified old_string was not found in the file',
@@ -40,9 +40,43 @@ describe('LocalSystemExecutionRuntime.editFile', () => {
search: 'foo',
});
- expect(output.success).toBe(true);
+ // `success` drives the tool_end event, `usage.tools.byTool[].errors` and
+ // the trace inspector's ✓/✗ — an edit that changed nothing must not land
+ // in any of them as a success.
+ expect(output.success).toBe(false);
+ // …while `error` reaches `pluginError`, which the EditLocalFile renderer
+ // branches on to draw its "Edit Failed" alert.
+ expect((output.error as { message: string }).message).toBe(
+ 'The specified old_string was not found in the file',
+ );
+ // The model reads `content`; it must still carry the real reason.
expect(output.content).toBe('The specified old_string was not found in the file');
expect(output.content).not.toContain('UNKNOWN_EXEC_ERROR');
+ expect((output.state as { replacements: number }).replacements).toBe(0);
+ });
+
+ // `executeToolWithRetry` escalates on `error.kind === 'retry'`. These
+ // failures were never retried while they claimed success; flipping the flag
+ // must not quietly enrol them in the retry loop.
+ it('does not mark a failed edit as retryable', async () => {
+ const service = createService({
+ editLocalFile: vi.fn().mockResolvedValue({
+ error: { kind: 'retry', message: 'transient' },
+ replacements: 0,
+ success: false,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.editFile({
+ all: false,
+ path: 'C:/foo.ts',
+ replace: 'bar',
+ search: 'foo',
+ });
+
+ expect(output.success).toBe(false);
+ expect((output.error as { kind?: string }).kind).toBeUndefined();
});
it('returns a formatted success result on a successful edit', async () => {