π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(local-system): stop parallel editFile calls on one file from dropping edits (#19966)
Arvin Xu9afe09fe84b4
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.tsindex 0f024bcad21..05de75731d4 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -1,7 +1,7 @@import path from 'node:path';import { zipSync } from 'fflate';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type App } from '@/core/App';@@ -42,6 +42,7 @@ vi.mock('electron', () => ({// Mock node:fs/promises and node:fsvi.mock('node:fs/promises', () => ({access: vi.fn(),+ chmod: vi.fn(),mkdir: vi.fn(),readFile: vi.fn(),readdir: vi.fn(),@@ -122,6 +123,37 @@ describe('LocalFileCtr', () => {localFileCtr = new LocalFileCtr(mockApp);});+ /**+ * Back the fs mock with an in-memory disk. editLocalFile / writeLocalFile+ * write a sibling temp file, rename it over the target and read the target+ * back before reporting success, so a write has to be visible to later reads.+ * Returns the disk so a test can assert what actually landed at a path.+ */+ const useDisk = (files: Record<string, string> = {}) => {+ const disk = new Map(Object.entries(files));+ vi.mocked(mockFsPromises.readFile).mockImplementation(async (filePath: string) => {+ if (!disk.has(filePath)) throw new Error(`ENOENT: ${filePath}`);+ return disk.get(filePath);+ });+ vi.mocked(mockFsPromises.writeFile).mockImplementation(+ async (filePath: string, content: string) => {+ disk.set(filePath, content);+ },+ );+ vi.mocked(mockFsPromises.rename).mockImplementation(async (from: string, to: string) => {+ disk.set(to, disk.get(from)!);+ disk.delete(from);+ });+ return disk;+ };++ afterEach(() => {+ // clearAllMocks keeps implementations; drop the disk so it cannot leak.+ for (const fn of ['readFile', 'writeFile', 'rename'] as const) {+ vi.mocked(mockFsPromises[fn]).mockReset();+ }+ });+describe('handleOpenLocalFile', () => {it('should open file successfully', async () => {vi.mocked(mockShell.openPath).mockResolvedValue('');@@ -575,7 +607,7 @@ describe('LocalFileCtr', () => {describe('handleWriteFile', () => {it('should write file successfully', async () => {vi.mocked(mockFsPromises.mkdir).mockResolvedValue(undefined);- vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);+ const disk = useDisk();const result = await localFileCtr.handleWriteFile({path: '/test/file.txt',@@ -583,6 +615,7 @@ describe('LocalFileCtr', () => {});expect(result).toEqual({ success: true });+ expect(disk.get('/test/file.txt')).toBe('test content');});it('should return error when path is empty', async () => {@@ -972,9 +1005,7 @@ describe('LocalFileCtr', () => {describe('handleEditFile', () => {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);+ const disk = useDisk({ '/test/file.txt': 'Hello world\nGreetings again\nGoodbye world' });const result = await localFileCtr.handleEditFile({file_path: '/test/file.txt',@@ -988,11 +1019,7 @@ describe('LocalFileCtr', () => {expect(result.linesAdded).toBe(1);expect(result.linesDeleted).toBe(1);expect(result.diffText).toContain('diff --git a/test/file.txt b/test/file.txt');- expect(mockFsPromises.writeFile).toHaveBeenCalledWith(- '/test/file.txt',- 'Hi world\nGreetings again\nGoodbye world',- 'utf8',- );+ expect(disk.get('/test/file.txt')).toBe('Hi world\nGreetings again\nGoodbye world');});// Editing an arbitrary one of several matches is worse than not editing:@@ -1017,9 +1044,7 @@ describe('LocalFileCtr', () => {});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);- vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);+ const disk = useDisk({ '/test/file.txt': 'Hello world\nHello again\nHello there' });const result = await localFileCtr.handleEditFile({file_path: '/test/file.txt',@@ -1032,17 +1057,11 @@ describe('LocalFileCtr', () => {expect(result.replacements).toBe(3);expect(result.linesAdded).toBe(3);expect(result.linesDeleted).toBe(3);- expect(mockFsPromises.writeFile).toHaveBeenCalledWith(- '/test/file.txt',- 'Hi world\nHi again\nHi there',- 'utf8',- );+ expect(disk.get('/test/file.txt')).toBe('Hi world\nHi again\nHi there');});it('should handle multiline replacement correctly', async () => {- const originalContent = 'function test() {\n console.log("old");\n}';- vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);- vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);+ useDisk({ '/test/file.js': 'function test() {\n console.log("old");\n}' });const result = await localFileCtr.handleEditFile({file_path: '/test/file.js',@@ -1108,9 +1127,7 @@ describe('LocalFileCtr', () => {});it('should generate correct diff format', async () => {- const originalContent = 'line 1\nline 2\nline 3';- vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);- vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);+ useDisk({ '/test/file.txt': 'line 1\nline 2\nline 3' });const result = await localFileCtr.handleEditFile({file_path: '/test/file.txt',diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex ea06ed018cf..4b244dbb4dd 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -1141,6 +1141,109 @@ describe('tool executors', () => {});});+ describe('serialized batch calls', () => {+ // Several editFile calls to one path in a batch reached the device at once;+ // each read the same snapshot and the last write dropped the others while+ // every call reported success. Calls naming the same resource through+ // `serializeBy` queue in emission order; other paths stay concurrent.+ const manifestMap = {+ 'lobe-local-system': {+ api: [+ { name: 'editFile', serializeBy: 'file_path' },+ { name: 'writeFile', serializeBy: 'path' },+ { name: 'readFile' },+ ],+ identifier: 'lobe-local-system',+ },+ };++ const fileCall = (id: string, apiName: string, args: Record<string, unknown>) => ({+ apiName,+ arguments: JSON.stringify(args),+ id,+ identifier: 'lobe-local-system',+ type: 'builtin' as const,+ });++ const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>+ vi.fn().mockImplementation(async (tool: { id: string }) => {+ timeline.push(`start:${tool.id}`);+ await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));+ timeline.push(`end:${tool.id}`);+ return {+ attempts: 1,+ result: { content: `done ${tool.id}`, executionTime: 1, state: {}, success: true },+ };+ });++ beforeEach(() => {+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));+ });++ it('runs edits and writes to one path one after another, in emission order', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'edit-1': 30, 'edit-2': 10, 'write-1': 0 },+ timeline,+ );++ const result = await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ fileCall('edit-1', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),+ fileCall('edit-2', 'editFile', { file_path: '/repo/a.ts', old_string: 'y' }),+ fileCall('write-1', 'writeFile', { content: 'z', path: '/repo/a.ts' }),+ ],+ },+ type: 'call_tools_batch',+ },+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline).toEqual([+ 'start:edit-1',+ 'end:edit-1',+ 'start:edit-2',+ 'end:edit-2',+ 'start:write-1',+ 'end:write-1',+ ]);+ expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);+ });++ it('keeps edits to different paths and unmarked reads concurrent', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'edit-a': 30, 'edit-b': 0, 'read-a': 0 },+ timeline,+ );++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ fileCall('edit-a', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),+ fileCall('edit-b', 'editFile', { file_path: '/repo/b.ts', old_string: 'x' }),+ fileCall('read-a', 'readFile', { path: '/repo/a.ts' }),+ ],+ },+ type: 'call_tools_batch',+ },+ createState({ toolManifestMap: manifestMap }),+ );++ // All three start before the slow edit to a.ts finishes.+ expect(timeline.slice(0, 3).sort()).toEqual(['start:edit-a', 'start:edit-b', 'start:read-a']);+ });+ });+describe('ordered batch calls', () => {// A model that posts a long report as several `sendMessage` calls emits// them in reading order, but `Promise.all` handed every call to thediff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 6953cb1c1fa..a9d00f8674a 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -131,26 +131,66 @@ const buildEffectiveManifestMap = (state: AgentState): Record<string, any> => ({});/**- * Split a batch into the calls whose API is marked `ordered` (kept in emission- * order) and the rest. The flag lives on the manifest API entry, so it is read- * from the same effective map the run context exposes to executors.+ * Resource an API call mutates, read from the argument its manifest names in+ * `serializeBy`. Undefined when the API declares none or the argument is not a+ * non-empty string.*/-const partitionOrderedCalls = (+const readSerializeKey = (tool: ChatToolPayload, argName: string): string | undefined => {+ try {+ const value = JSON.parse(tool.arguments || '{}')?.[argName];+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;+ } catch {+ return undefined;+ }+};++/**+ * Split a batch into lanes. Calls within a lane run one after another in+ * emission order; lanes run concurrently. The flags live on the manifest API+ * entry, so they are read from the same effective map the run context exposes+ * to executors.+ *+ * - every call to an API marked `ordered` shares one lane;+ * - calls to one tool that name the same resource through `serializeBy` (the+ * same file path) share a lane, across that tool's APIs;+ * - everything else gets a lane of its own.+ */+const planBatchLanes = (state: AgentState,toolsCalling: ChatToolPayload[],-): { ordered: ChatToolPayload[]; unordered: ChatToolPayload[] } => {+): ChatToolPayload[][] => {const manifestMap = buildEffectiveManifestMap(state);const ordered: ChatToolPayload[] = [];- const unordered: ChatToolPayload[] = [];+ const serialized = new Map<string, ChatToolPayload[]>();+ const lanes: ChatToolPayload[][] = [ordered];for (const tool of toolsCalling) {const apis = manifestMap[tool.identifier]?.api as- Array<{ name?: string; ordered?: boolean }> | undefined;+ Array<{ name?: string; ordered?: boolean; serializeBy?: string }> | undefined;const api = apis?.find((item) => item.name === tool.apiName);- (api?.ordered === true ? ordered : unordered).push(tool);++ if (api?.ordered === true) {+ ordered.push(tool);+ continue;+ }++ const resource = api?.serializeBy ? readSerializeKey(tool, api.serializeBy) : undefined;+ if (resource === undefined) {+ lanes.push([tool]);+ continue;+ }++ const key = `${tool.identifier}\u0000${resource}`;+ const lane = serialized.get(key);+ if (lane) lane.push(tool);+ else {+ const created = [tool];+ serialized.set(key, created);+ lanes.push(created);+ }}- return { ordered, unordered };+ return lanes.filter((lane) => lane.length > 0);};const resolveCallIndex = (state: AgentState, toolName: string) => {@@ -1002,15 +1042,17 @@ export const callToolsBatch =// Calls to an API marked `ordered` (posting successive chat messages) run// one after another in the order the model emitted them: handing them to// the platform concurrently let the channel keep whichever request landed- // first, so a report emitted as nine sends arrived shuffled. The chain runs- // alongside the unordered calls so a read-only sibling never waits on it.- const { ordered, unordered } = partitionOrderedCalls(state, toolsToExecute);- await Promise.all([- ...unordered.map((tool) => runOne(tool)),- (async () => {- for (const tool of ordered) await runOne(tool);- })(),- ]);+ // first, so a report emitted as nine sends arrived shuffled. Calls that+ // mutate the same resource (`serializeBy`, e.g. several edits to one file)+ // queue the same way: devices that apply them concurrently read one+ // snapshot and keep only the last write, while each call reports success.+ // Each chain runs alongside everything else, so a read-only sibling never+ // waits on it.+ await Promise.all(+ planBatchLanes(state, toolsToExecute).map(async (lane) => {+ for (const tool of lane) await runOne(tool);+ }),+ );// Client tools in a mixed batch never entered `toolsToExecute` β they were// waiting for the pause below to hand them to the client. Once the operationdiff --git a/packages/builtin-tool-cloud-sandbox/src/manifest.ts b/packages/builtin-tool-cloud-sandbox/src/manifest.tsindex 5178886b358..4fb1dd1f8d5 100644--- a/packages/builtin-tool-cloud-sandbox/src/manifest.ts+++ b/packages/builtin-tool-cloud-sandbox/src/manifest.ts@@ -154,6 +154,9 @@ export const CloudSandboxManifest: BuiltinToolManifest = {required: ['path', 'content'],type: 'object',},+ // Queues with editFile on the same path: parallel read-modify-writes of+ // one file would otherwise drop all but the last edit.+ serializeBy: 'path',},{description:@@ -182,6 +185,7 @@ export const CloudSandboxManifest: BuiltinToolManifest = {required: ['path', 'search', 'replace'],type: 'object',},+ serializeBy: 'path',},{defaultTimeoutMs: 120_000,diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.tsindex 9d265d32b5b..e9a5184caf2 100644--- a/packages/builtin-tool-local-system/src/manifest.ts+++ b/packages/builtin-tool-local-system/src/manifest.ts@@ -191,6 +191,9 @@ export const LocalSystemManifest: BuiltinToolManifest = {required: ['path', 'content'],type: 'object',},+ // Queues with editFile on the same path: parallel read-modify-writes of+ // one file would otherwise drop all but the last edit.+ serializeBy: 'path',},{defaultTimeoutMs: 30_000,@@ -227,6 +230,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {required: ['file_path', 'old_string', 'new_string'],type: 'object',},+ serializeBy: 'file_path',},{defaultTimeoutMs: 60_000,diff --git a/packages/local-file-shell/src/file/__tests__/edit.concurrent.test.ts b/packages/local-file-shell/src/file/__tests__/edit.concurrent.test.tsnew file mode 100644index 00000000000..80b7ea1cc7c--- /dev/null+++ b/packages/local-file-shell/src/file/__tests__/edit.concurrent.test.ts@@ -0,0 +1,119 @@+import { chmod, lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { editLocalFile } from '../edit';+import { writeLocalFile } from '../write';++// call_tools_batch runs unordered tool calls with Promise.all and the desktop+// gateway handles each tool_call_request without a queue, so parallel editFile+// calls on one path reach editLocalFile concurrently.+describe('editLocalFile β concurrent edits to the same file', () => {+ let dir: string;+ let file: string;+ const base =+ Array.from({ length: 2000 }, (_, i) => `第${i}θ‘γδΈζζ£ζγ anchor_${i}_end`).join('\n') ++ '\n';++ beforeEach(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'edit-concurrent-'));+ file = path.join(dir, 'doc.md');+ });++ afterEach(async () => {+ await rm(dir, { force: true, recursive: true });+ });++ it('applies every edit that reports success', async () => {+ for (let trial = 0; trial < 20; trial++) {+ await writeFile(file, base, 'utf8');++ const results = await Promise.all([+ editLocalFile({+ file_path: file,+ new_string: 'anchor_600_end<E0>' + 'γζγ'.repeat(7) + 'x</E0>',+ old_string: 'anchor_600_end',+ }),+ editLocalFile({+ file_path: file,+ new_string: 'anchor_1300_end<E1>' + 'γζγ'.repeat(40) + 'xx</E1>',+ old_string: 'anchor_1300_end',+ }),+ ]);+ const onDisk = await readFile(file, 'utf8');++ expect(results.map((r) => r.success)).toEqual([true, true]);+ expect(onDisk).toContain('</E0>');+ expect(onDisk).toContain('</E1>');+ expect(onDisk).not.toContain('οΏ½');+ expect(onDisk.match(/anchor_1999_end/g)).toHaveLength(1);+ }+ // 20 serialized trials; the default 5s is too tight on a loaded CI runner.+ }, 30_000);++ it('queues a writeFile and an editFile to one path instead of interleaving them', async () => {+ for (let trial = 0; trial < 20; trial++) {+ await writeFile(file, base, 'utf8');++ const [write, edit] = await Promise.all([+ writeLocalFile({ content: base.replace('anchor_5_end', 'anchor_5_end<W/>'), path: file }),+ editLocalFile({+ file_path: file,+ new_string: 'anchor_1900_end<E/>',+ old_string: 'anchor_1900_end',+ }),+ ]);+ const onDisk = await readFile(file, 'utf8');++ // The write lands first (emission order), then the edit applies on top of it.+ expect([write.success, edit.success]).toEqual([true, true]);+ expect(onDisk).toContain('<W/>');+ expect(onDisk).toContain('<E/>');+ }+ }, 30_000);++ it('never shows a concurrent reader an empty or half-written file', async () => {+ // Large enough that a truncate-then-write takes several event-loop turns.+ const large =+ Array.from({ length: 30_000 }, (_, i) => `第${i}θ‘γδΈζζ£ζγ anchor_${i}_end`).join('\n') ++ '\n';+ await writeFile(file, large, 'utf8');+ const edits = Array.from({ length: 10 }, (_, i) =>+ editLocalFile({+ file_path: file,+ new_string: `anchor_${i * 100}_end<E${i}/>\n`,+ old_string: `anchor_${i * 100}_end\n`,+ }),+ );+ const reads: string[] = [];+ let settled = false;+ const reader = (async () => {+ while (!settled) reads.push(await readFile(file, 'utf8'));+ })();++ const results = await Promise.all(edits);+ settled = true;+ await reader;++ expect(results.every((r) => r.success)).toBe(true);+ // Every snapshot a reader saw was a complete file, never an empty or half-written one.+ expect(reads.length).toBeGreaterThan(0);+ for (const snapshot of reads) expect(snapshot.endsWith('anchor_29999_end\n')).toBe(true);+ }, 30_000);++ it('keeps a symlink and the file mode when replacing the content', async () => {+ const target = path.join(dir, 'target.sh');+ await writeFile(target, 'echo old\n', 'utf8');+ await chmod(target, 0o755);+ await symlink(target, file);++ const result = await editLocalFile({ file_path: file, new_string: 'new', old_string: 'old' });++ expect(result.success).toBe(true);+ expect((await lstat(file)).isSymbolicLink()).toBe(true);+ expect(await readFile(target, 'utf8')).toBe('echo new\n');+ expect((await stat(target)).mode & 0o777).toBe(0o755);+ });+});diff --git a/packages/local-file-shell/src/file/atomicWrite.ts b/packages/local-file-shell/src/file/atomicWrite.tsnew file mode 100644index 00000000000..df7960bc178--- /dev/null+++ b/packages/local-file-shell/src/file/atomicWrite.ts@@ -0,0 +1,104 @@+import { randomBytes } from 'node:crypto';+import { chmod, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';+import path from 'node:path';++/**+ * Per-path write queue for this process.+ *+ * The runtime can hand several edits to the same file to the device at once+ * (a tool batch runs its calls concurrently and the gateway handles every+ * request on its own), and a read β replace β write that is not serialized+ * lets one call overwrite another's change while both report success. Every+ * mutation of a file in this package runs through here, so two calls on one+ * path always see each other's result.+ */+const pathQueues = new Map<string, Promise<unknown>>();++/**+ * Case-insensitive file systems (the default on Windows and macOS) map+ * `Foo.ts` and `foo.ts` to one file. Folding case there only ever+ * over-serializes on a case-sensitive volume, which is harmless.+ */+const lockKey = (filePath: string) => {+ const resolved = path.resolve(filePath);+ return process.platform === 'win32' || process.platform === 'darwin'+ ? resolved.toLowerCase()+ : resolved;+};++export const withFileLock = async <T>(filePath: string, task: () => Promise<T>): Promise<T> => {+ const key = lockKey(filePath);+ const previous = pathQueues.get(key) ?? Promise.resolve();+ const current = previous.then(task, task);+ // The queue tail must never reject, or the next caller would inherit it.+ const tail = current.catch(() => {});+ pathQueues.set(key, tail);++ try {+ return await current;+ } finally {+ // Drop the entry once nothing is queued behind this call, so the map does+ // not grow with every file ever touched.+ if (pathQueues.get(key) === tail) pathQueues.delete(key);+ }+};++/** Errors a rename over an existing file can hit on Windows when something else holds it open. */+const RENAME_BLOCKED_CODES = new Set(['EACCES', 'EBUSY', 'EPERM']);++/**+ * Write `content` so no reader ever sees a half-written file: write a sibling+ * temp file, then rename it over the target. `writeFile` in place truncates+ * first and writes from offset 0, so two overlapping writes (or a read in the+ * middle of one) produce an empty file, a duplicated tail, or a UTF-8+ * sequence cut in half.+ *+ * Symlinks are followed so the link itself is kept, and the target's mode is+ * carried over. When the rename is refused (another process holding the file+ * open on Windows), fall back to an in-place write β still serialized by+ * {@link withFileLock}, and still checked by {@link verifyWrittenContent}.+ */+export const writeFileAtomic = async (filePath: string, content: string): Promise<void> => {+ let target = filePath;+ let mode: number | undefined;+ try {+ // Adopt the resolved path only once both lookups succeed, so a failure+ // part-way never leaves `target` pointing somewhere other than the file.+ const resolved = await realpath(filePath);+ const { mode: resolvedMode } = await stat(resolved);+ target = resolved;+ mode = resolvedMode;+ } catch {+ // New file: nothing to follow or preserve.+ }++ const tempPath = path.join(+ path.dirname(target),+ `.${path.basename(target)}.${randomBytes(6).toString('hex')}.tmp`,+ );++ try {+ await writeFile(tempPath, content, 'utf8');+ if (mode !== undefined) await chmod(tempPath, mode);+ await rename(tempPath, target);+ } catch (error) {+ await rm(tempPath, { force: true });+ if (!RENAME_BLOCKED_CODES.has((error as NodeJS.ErrnoException).code ?? '')) throw error;+ await writeFile(target, content, 'utf8');+ }+};++/**+ * Read the file back and confirm it holds exactly what was written, so a+ * success result reflects the disk rather than the in-memory replacement.+ * Returns an error message when it does not.+ */+export const verifyWrittenContent = async (+ filePath: string,+ expected: string,+): Promise<string | undefined> => {+ const actual = await readFile(filePath, 'utf8');+ if (actual === expected) return;++ return `The write to ${filePath} did not persist: reading it back returned ${Buffer.byteLength(actual, 'utf8')} bytes instead of the expected ${Buffer.byteLength(expected, 'utf8')}. Another process may have modified the file β read it again before retrying.`;+};diff --git a/packages/local-file-shell/src/file/edit.ts b/packages/local-file-shell/src/file/edit.tsindex 69bb66849a2..5296be5b1d9 100644--- a/packages/local-file-shell/src/file/edit.ts+++ b/packages/local-file-shell/src/file/edit.ts@@ -1,8 +1,9 @@-import { readFile, writeFile } from 'node:fs/promises';+import { readFile } from 'node:fs/promises';import { createPatch } from 'diff';import type { EditFileParams, EditFileResult } from '../types';+import { verifyWrittenContent, withFileLock, writeFileAtomic } from './atomicWrite';import { resolveAgainstCwd } from './expandTilde';/** Cap the diagnosis scan so a stray edit against a huge file stays cheap. */@@ -82,14 +83,10 @@ const findOccurrenceLines = (content: string, search: string, cap: number): numbreturn lines;};-export async function editLocalFile({- file_path: rawPath,- old_string,- new_string,- replace_all = false,- cwd,-}: EditFileParams): Promise<EditFileResult> {- const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;+const applyEdit = async (+ filePath: string,+ { old_string, new_string, replace_all = false }: EditFileParams,+): Promise<EditFileResult> => {try {const content = await readFile(filePath, 'utf8');@@ -163,7 +160,10 @@ export async function editLocalFile({replacements = 1;}- await writeFile(filePath, newContent, 'utf8');+ await writeFileAtomic(filePath, newContent);++ const writeError = await verifyWrittenContent(filePath, newContent);+ if (writeError) return { error: writeError, replacements: 0, success: false };const patch = createPatch(filePath, content, newContent, '', '');const diffText = `diff --git a${filePath} b${filePath}\n${patch}`;@@ -181,4 +181,12 @@ export async function editLocalFile({} catch (error) {return { error: (error as Error).message, replacements: 0, success: false };}+};++export async function editLocalFile(params: EditFileParams): Promise<EditFileResult> {+ const filePath = resolveAgainstCwd(params.file_path, params.cwd) ?? params.file_path;++ // Serialize the whole read β replace β write per path: parallel edits to one+ // file otherwise read the same snapshot and the last write drops the rest.+ return withFileLock(filePath, () => applyEdit(filePath, params));}diff --git a/packages/local-file-shell/src/file/write.ts b/packages/local-file-shell/src/file/write.tsindex c0aefa300b8..5f6c4eca715 100644--- a/packages/local-file-shell/src/file/write.ts+++ b/packages/local-file-shell/src/file/write.ts@@ -1,7 +1,8 @@-import { mkdir, writeFile } from 'node:fs/promises';+import { mkdir } from 'node:fs/promises';import path from 'node:path';import type { WriteFileParams, WriteFileResult } from '../types';+import { verifyWrittenContent, withFileLock, writeFileAtomic } from './atomicWrite';import { resolveAgainstCwd } from './expandTilde';export async function writeLocalFile({@@ -14,12 +15,20 @@ export async function writeLocalFile({const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;- try {- const dirname = path.dirname(filePath);- await mkdir(dirname, { recursive: true });- await writeFile(filePath, content, 'utf8');- return { success: true };- } catch (error) {- return { error: `Failed to write file: ${(error as Error).message}`, success: false };- }+ // Shares the per-path queue with editLocalFile, so a write and an edit to the+ // same file in one batch cannot interleave.+ return withFileLock(filePath, async () => {+ try {+ const dirname = path.dirname(filePath);+ await mkdir(dirname, { recursive: true });+ await writeFileAtomic(filePath, content);++ const writeError = await verifyWrittenContent(filePath, content);+ if (writeError) return { error: writeError, success: false };++ return { success: true };+ } catch (error) {+ return { error: `Failed to write file: ${(error as Error).message}`, success: false };+ }+ });}diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex cf7d6d7a78a..494a502be99 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -220,6 +220,17 @@ export interface LobeChatPluginApi {* @default 'collapsed'*/renderDisplayControl?: RenderDisplayControl;+ /**+ * Name of the argument that identifies the resource this API mutates (e.g.+ * a file path). Within one tool batch, calls to the same tool whose argument+ * holds the same value run one after another in emission order β across+ * APIs of that tool, so a `writeFile` and an `editFile` on one path queue+ * together. Calls on different values stay concurrent.+ *+ * Framework-only config like `ordered`: it never reaches the LLM-facing+ * tool spec.+ */+ serializeBy?: string;url?: string;/*** Declarative Work-registration config. When present, the tool-execution@@ -237,6 +248,7 @@ export const LobeChatPluginApiSchema = z.object({ordered: z.boolean().optional(),parameters: z.record(z.string(), z.any()),renderDisplayControl: RenderDisplayControlSchema.optional(),+ serializeBy: z.string().optional(),url: z.string().optional(),work: PluginApiWorkConfigSchema.optional(),});