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.

✨ feat: edit local file render & intervention (#10269)

Arvin Xu3785a7109af6
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 345d764f258..5f64be31ec5 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -52,6 +52,7 @@
"@typescript/native-preview": "7.0.0-dev.20250711.1",
"consola": "^3.4.2",
"cookie": "^1.0.2",
+ "diff": "^8.0.2",
"electron": "^38.7.0",
"electron-builder": "^26.0.12",
"electron-is": "^3.0.0",
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index e1cdad6fac9..ab678376b6e 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -18,6 +18,7 @@ import {
WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
import { SYSTEM_FILES_TO_IGNORE, loadFile } from '@lobechat/file-loaders';
+import { createPatch } from 'diff';
import { shell } from 'electron';
import fg from 'fast-glob';
import { Stats, constants } from 'node:fs';
@@ -94,26 +95,45 @@ export default class LocalFileCtr extends ControllerModule {
}
@ipcClientEvent('readLocalFile')
- async readFile({ path: filePath, loc }: LocalReadFileParams): Promise<LocalReadFileResult> {
- const effectiveLoc = loc ?? [0, 200];
- logger.debug('Starting to read file:', { filePath, loc: effectiveLoc });
+ async readFile({
+ path: filePath,
+ loc,
+ fullContent,
+ }: LocalReadFileParams): Promise<LocalReadFileResult> {
+ const effectiveLoc = fullContent ? undefined : (loc ?? [0, 200]);
+ logger.debug('Starting to read file:', { filePath, fullContent, loc: effectiveLoc });
try {
const fileDocument = await loadFile(filePath);
- const [startLine, endLine] = effectiveLoc;
const lines = fileDocument.content.split('\n');
const totalLineCount = lines.length;
const totalCharCount = fileDocument.content.length;
- // Adjust slice indices to be 0-based and inclusive/exclusive
- const selectedLines = lines.slice(startLine, endLine);
- const content = selectedLines.join('\n');
- const charCount = content.length;
- const lineCount = selectedLines.length;
+ let content: string;
+ let charCount: number;
+ let lineCount: number;
+ let actualLoc: [number, number];
+
+ if (effectiveLoc === undefined) {
+ // Return full content
+ content = fileDocument.content;
+ charCount = totalCharCount;
+ lineCount = totalLineCount;
+ actualLoc = [0, totalLineCount];
+ } else {
+ // Return specified range
+ const [startLine, endLine] = effectiveLoc;
+ const selectedLines = lines.slice(startLine, endLine);
+ content = selectedLines.join('\n');
+ charCount = content.length;
+ lineCount = selectedLines.length;
+ actualLoc = effectiveLoc;
+ }
logger.debug('File read successfully:', {
filePath,
+ fullContent,
selectedLineCount: lineCount,
totalCharCount,
totalLineCount,
@@ -128,7 +148,7 @@ export default class LocalFileCtr extends ControllerModule {
fileType: fileDocument.fileType,
filename: fileDocument.filename,
lineCount,
- loc: effectiveLoc,
+ loc: actualLoc,
// Line count for the selected range
modifiedTime: fileDocument.modifiedTime,
@@ -711,8 +731,32 @@ export default class LocalFileCtr extends ControllerModule {
// Write back to file
await writeFile(filePath, newContent, 'utf8');
- logger.info(`${logPrefix} File edited successfully`, { replacements });
+ // Generate diff for UI display
+ const patch = createPatch(filePath, content, newContent, '', '');
+ const diffText = `diff --git a${filePath} b${filePath}\n${patch}`;
+
+ // Calculate lines added and deleted from patch
+ const patchLines = patch.split('\n');
+ let linesAdded = 0;
+ let linesDeleted = 0;
+
+ for (const line of patchLines) {
+ if (line.startsWith('+') && !line.startsWith('+++')) {
+ linesAdded++;
+ } else if (line.startsWith('-') && !line.startsWith('---')) {
+ linesDeleted++;
+ }
+ }
+
+ logger.info(`${logPrefix} File edited successfully`, {
+ linesAdded,
+ linesDeleted,
+ replacements,
+ });
return {
+ diffText,
+ linesAdded,
+ linesDeleted,
replacements,
success: true,
};
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 511f57ba4fb..6ea5495742d 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -183,6 +183,26 @@ describe('LocalFileCtr', () => {
expect(result.totalLineCount).toBe(5);
});
+ it('should read full file content when fullContent is true', async () => {
+ const mockFileContent = 'line1\nline2\nline3\nline4\nline5';
+ vi.mocked(mockLoadFile).mockResolvedValue({
+ content: mockFileContent,
+ filename: 'test.txt',
+ fileType: 'txt',
+ createdTime: new Date('2024-01-01'),
+ modifiedTime: new Date('2024-01-02'),
+ });
+
+ const result = await localFileCtr.readFile({ path: '/test/file.txt', fullContent: true });
+
+ expect(result.content).toBe(mockFileContent);
+ expect(result.lineCount).toBe(5);
+ expect(result.charCount).toBe(mockFileContent.length);
+ expect(result.totalLineCount).toBe(5);
+ expect(result.totalCharCount).toBe(mockFileContent.length);
+ expect(result.loc).toEqual([0, 5]);
+ });
+
it('should handle file read error', async () => {
vi.mocked(mockLoadFile).mockRejectedValue(new Error('File not found'));
@@ -392,4 +412,137 @@ describe('LocalFileCtr', () => {
});
});
});
+
+ describe('handleEditFile', () => {
+ it('should replace first occurrence successfully', async () => {
+ const originalContent = 'Hello world\nHello again\nGoodbye world';
+ vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
+ vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);
+
+ const result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.txt',
+ old_string: 'Hello',
+ new_string: 'Hi',
+ replace_all: false,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.replacements).toBe(1);
+ 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\nHello again\nGoodbye world',
+ 'utf8',
+ );
+ });
+
+ 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 result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.txt',
+ old_string: 'Hello',
+ new_string: 'Hi',
+ replace_all: true,
+ });
+
+ expect(result.success).toBe(true);
+ 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',
+ );
+ });
+
+ 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);
+
+ const result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.js',
+ old_string: 'console.log("old");',
+ new_string: 'console.log("new");\n console.log("added");',
+ replace_all: false,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.replacements).toBe(1);
+ expect(result.linesAdded).toBe(2);
+ expect(result.linesDeleted).toBe(1);
+ });
+
+ it('should return error when old_string is not found', async () => {
+ const originalContent = 'Hello world';
+ vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
+
+ const result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.txt',
+ old_string: 'NonExistent',
+ new_string: 'New',
+ replace_all: false,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe('The specified old_string was not found in the file');
+ expect(result.replacements).toBe(0);
+ expect(mockFsPromises.writeFile).not.toHaveBeenCalled();
+ });
+
+ it('should handle file read error', async () => {
+ vi.mocked(mockFsPromises.readFile).mockRejectedValue(new Error('Permission denied'));
+
+ 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.error).toBe('Permission denied');
+ expect(result.replacements).toBe(0);
+ });
+
+ it('should handle file write error', async () => {
+ const originalContent = 'Hello world';
+ vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
+ vi.mocked(mockFsPromises.writeFile).mockRejectedValue(new Error('Disk full'));
+
+ 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.error).toBe('Disk full');
+ });
+
+ 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);
+
+ const result = await localFileCtr.handleEditFile({
+ file_path: '/test/file.txt',
+ old_string: 'line 2',
+ new_string: 'modified line 2',
+ replace_all: false,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.diffText).toContain('diff --git a/test/file.txt b/test/file.txt');
+ expect(result.diffText).toContain('-line 2');
+ expect(result.diffText).toContain('+modified line 2');
+ });
+ });
});
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 0a13aef47e6..1cf3ad8f427 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -15,6 +15,12 @@
"prompt": "Prompt"
},
"localFiles": {
+ "editFile": {
+ "newString": "Replace with",
+ "oldString": "Find",
+ "replaceAll": "Replace all occurrences",
+ "replaceFirst": "Replace first occurrence only"
+ },
"file": "File",
"folder": "Folder",
"moveFiles": {
@@ -34,7 +40,12 @@
"readFile": "Read File",
"readFileError": "Failed to read file, please check if the file path is correct",
"readFiles": "Read Files",
- "readFilesError": "Failed to read files, please check if the file path is correct"
+ "readFilesError": "Failed to read files, please check if the file path is correct",
+ "writeFile": {
+ "characters": "characters",
+ "preview": "Content Preview",
+ "truncated": "truncated"
+ }
},
"search": {
"createNewSearch": "Create a new search record",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 6026977c06d..f816360d11e 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -15,6 +15,12 @@
"prompt": "提示词"
},
"localFiles": {
+ "editFile": {
+ "newString": "替换为",
+ "oldString": "查找内容",
+ "replaceAll": "替换全部匹配项",
+ "replaceFirst": "仅替换第一个匹配项"
+ },
"file": "文件",
"folder": "文件夹",
"moveFiles": {
@@ -34,7 +40,12 @@
"readFile": "读取文件",
"readFileError": "读取文件失败,请检查文件路径是否正确",
"readFiles": "读取文件",
- "readFilesError": "读取文件失败,请检查文件路径是否正确"
+ "readFilesError": "读取文件失败,请检查文件路径是否正确",
+ "writeFile": {
+ "characters": "字符",
+ "preview": "内容预览",
+ "truncated": "已截断"
+ }
},
"search": {
"createNewSearch": "创建新的搜索记录",
diff --git a/package.json b/package.json
index d037e9f7091..b0cf1a1660e 100644
--- a/package.json
+++ b/package.json
@@ -258,6 +258,7 @@
"random-words": "^2.0.1",
"react": "19.2.0",
"react-confetti": "^6.4.0",
+ "react-diff-view": "^3.3.2",
"react-dom": "19.2.0",
"react-fast-marquee": "^1.6.5",
"react-hotkeys-hook": "^5.2.1",
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index f8b5eb90111..0485cd2f504 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -48,6 +48,7 @@ export interface RenameLocalFileResult {
}
export interface LocalReadFileParams {
+ fullContent?: boolean;
loc?: [number, number];
path: string;
}
@@ -217,7 +218,10 @@ export interface EditLocalFileParams {
}
export interface EditLocalFileResult {
+ diffText?: string;
error?: string;
+ linesAdded?: number;
+ linesDeleted?: number;
replacements: number;
success: boolean;
}
diff --git a/scripts/prebuild.mts b/scripts/prebuild.mts
index 5d6bf299ba7..6c84154b93d 100644
--- a/scripts/prebuild.mts
+++ b/scripts/prebuild.mts
@@ -20,11 +20,11 @@ const partialBuildPages = [
disabled: isDesktop,
paths: ['src/app/[variants]/(auth)'],
},
- {
- name: 'mobile',
- disabled: isDesktop,
- paths: ['src/app/[variants]/(main)/(mobile)'],
- },
+ // {
+ // name: 'mobile',
+ // disabled: isDesktop,
+ // paths: ['src/app/[variants]/(main)/(mobile)'],
+ // },
{
name: 'oauth',
disabled: isDesktop,
@@ -35,6 +35,16 @@ const partialBuildPages = [
disabled: isDesktop,
paths: ['src/app/(backend)/api/webhooks'],
},
+ {
+ name: 'market-auth',
+ disabled: isDesktop,
+ paths: ['src/app/market-auth-callback'],
+ },
+ {
+ name: 'pwa',
+ disabled: isDesktop,
+ paths: ['src/manifest.ts', 'src/sitemap.tsx', 'src/robots.tsx', 'src/sw'],
+ },
// no need for web
{
name: 'desktop-devtools',
diff --git a/src/app/[variants]/desktopRouter.config.tsx b/src/app/[variants]/desktopRouter.config.tsx
index 07eef4195f5..18fcbf45abf 100644
--- a/src/app/[variants]/desktopRouter.config.tsx
+++ b/src/app/[variants]/desktopRouter.config.tsx
@@ -7,7 +7,6 @@ import Loading from '@/components/Loading/BrandTextLoading';
import { useGlobalStore } from '@/store/global';
import type { Locales } from '@/types/locale';
-import DesktopChangelogLayout from './(main)/changelog/_layout/Desktop';
import DesktopMainLayout from './(main)/layouts/desktop';
import { idLoader, slugLoader } from './loaders/routeParams';
@@ -300,22 +299,6 @@ export const createDesktopRouter = (locale: Locales) =>
path: 'labs',
},
- // Changelog routes
- {
- children: [
- {
- index: true,
- lazy: () =>
- import('./(main)/changelog').then((m) => ({
- Component: m.DesktopPage,
- })),
- path: '*',
- },
- ],
- element: <DesktopChangelogLayout locale={locale} />,
- path: 'changelog',
- },
-
// Profile routes
{
children: [
diff --git a/src/app/[variants]/mobileRouter.config.tsx b/src/app/[variants]/mobileRouter.config.tsx
index fffac5dccc1..ef7c5b9d9f3 100644
--- a/src/app/[variants]/mobileRouter.config.tsx
+++ b/src/app/[variants]/mobileRouter.config.tsx
@@ -7,7 +7,6 @@ import Loading from '@/components/Loading/BrandTextLoading';
import { useGlobalStore } from '@/store/global';
import type { Locales } from '@/types/locale';
-import MobileChangelogLayout from './(main)/changelog/_layout/Mobile';
import { MobileMainLayout } from './(main)/layouts/mobile';
import { idLoader, slugLoader } from './loaders/routeParams';
@@ -287,21 +286,6 @@ export const createMobileRouter = (locale: Locales) =>
path: 'labs',
},
- // Changelog routes
- {
- children: [
- {
- index: true,
- lazy: () =>
- import('./(main)/changelog').then((m) => ({
- Component: m.MobilePage,
- })),
- },
- ],
- element: <MobileChangelogLayout locale={locale} />,
- path: 'changelog',
- },
-
// Profile routes
{
children: [
diff --git a/src/app/[variants]/page.tsx b/src/app/[variants]/page.tsx
index 49c1330309f..4327b24dfd9 100644
--- a/src/app/[variants]/page.tsx
+++ b/src/app/[variants]/page.tsx
@@ -1,7 +1,10 @@
import { DynamicLayoutProps } from '@/types/next';
import { RouteVariants } from '@/utils/server/routeVariants';
-export default async function Page(props: DynamicLayoutProps) {
+import DesktopRouter from './DesktopRouter';
+import MobileRouter from './MobileRouter';
+
+export default async (props: DynamicLayoutProps) => {
// Get isMobile from variants parameter on server side
const isMobile = await RouteVariants.getIsMobile(props);
const { locale } = await RouteVariants.getVariantsFromProps(props);
@@ -10,10 +13,8 @@ export default async function Page(props: DynamicLayoutProps) {
// Using native dynamic import ensures complete code splitting
// Mobile and Desktop bundles will be completely separate
if (isMobile) {
- const { default: MobileRouter } = await import('./MobileRouter');
return <MobileRouter locale={locale} />;
}
- const { default: DesktopRouter } = await import('./DesktopRouter');
return <DesktopRouter locale={locale} />;
-}
+};
diff --git a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
index e377949340c..7e83ebfbfee 100644
--- a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
@@ -11,7 +11,7 @@ import {
Trash2,
X,
} from 'lucide-react';
-import { CSSProperties, memo, useState } from 'react';
+import { CSSProperties, memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
@@ -97,7 +97,6 @@ const Inspectors = memo<InspectorProps>(
apiName,
id,
arguments: requestArgs,
- showRender,
result,
setShowRender,
showPluginRender,
@@ -109,6 +108,8 @@ const Inspectors = memo<InspectorProps>(
const { styles, theme } = useStyles();
const [showDebug, setShowDebug] = useState(false);
+ const [isPinned, setIsPinned] = useState(false);
+ const [isHovered, setIsHovered] = useState(false);
const [deleteAssistantMessage] = useChatStore((s) => [s.deleteAssistantMessage]);
@@ -121,7 +122,15 @@ const Inspectors = memo<InspectorProps>(
const isReject = intervention?.status === 'rejected';
const isTitleLoading = !hasResult && !isPending;
- const showCustomPluginRender = showRender && !isPending && !isReject;
+ // Compute actual render state based on pinned or hovered
+ const shouldShowRender = isPinned || isHovered;
+
+ // Sync with parent state
+ useEffect(() => {
+ setShowRender(shouldShowRender);
+ }, [shouldShowRender, setShowRender]);
+
+ const showCustomPluginRender = shouldShowRender && !isPending && !isReject;
return (
<Flexbox className={styles.container} gap={4}>
<Flexbox align={'center'} distribution={'space-between'} gap={8} horizontal>
@@ -131,7 +140,17 @@ const Inspectors = memo<InspectorProps>(
gap={8}
horizontal
onClick={() => {
- setShowRender(!showRender);
+ setIsPinned(!isPinned);
+ }}
+ onMouseEnter={() => {
+ if (!isPinned) {
+ setIsHovered(true);
+ }
+ }}
+ onMouseLeave={() => {
+ if (!isPinned) {
+ setIsHovered(false);
+ }
}}
paddingInline={4}
>
diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.ts
index c217b090093..0140bc82297 100644
--- a/src/locales/default/tool.ts
+++ b/src/locales/default/tool.ts
@@ -15,6 +15,12 @@ export default {
prompt: '提示词',
},
localFiles: {
+ editFile: {
+ newString: '替换为',
+ oldString: '查找内容',
+ replaceAll: '替换全部匹配项',
+ replaceFirst: '仅替换第一个匹配项',
+ },
file: '文件',
folder: '文件夹',
moveFiles: {
@@ -35,6 +41,11 @@ export default {
readFileError: '读取文件失败,请检查文件路径是否正确',
readFiles: '读取文件',
readFilesError: '读取文件失败,请检查文件路径是否正确',
+ writeFile: {
+ characters: '字符',
+ preview: '内容预览',
+ truncated: '已截断',
+ },
},
search: {
createNewSearch: '创建新的搜索记录',
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
index 951f56734f9..4875fa16ac9 100644
--- a/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
+++ b/src/store/chat/slices/builtinTool/actions/__tests__/localSystem.test.ts
@@ -50,18 +50,17 @@ describe('localFileSlice', () => {
describe('internal_triggerLocalFileToolCalling', () => {
it('should handle successful calling', async () => {
- const mockContent = { foo: 'bar' };
+ const mockContent = 'result content';
const mockState = { state: 'test' };
- const mockService = vi.fn().mockResolvedValue({ content: mockContent, state: mockState });
+ const mockService = vi
+ .fn()
+ .mockResolvedValue({ content: mockContent, state: mockState, success: true });
await store.internal_triggerLocalFileToolCalling('test-id', mockService);
expect(mockStore.toggleLocalFileLoading).toBeCalledWith('test-id', true);
expect(mockStore.optimisticUpdatePluginState).toBeCalledWith('test-id', mockState);
- expect(mockStore.optimisticUpdateMessageContent).toBeCalledWith(
- 'test-id',
- JSON.stringify(mockContent),
- );
+ expect(mockStore.optimisticUpdateMessageContent).toBeCalledWith('test-id', mockContent);
expect(mockStore.toggleLocalFileLoading).toBeCalledWith('test-id', false);
});
diff --git a/src/store/chat/slices/builtinTool/actions/localSystem.ts b/src/store/chat/slices/builtinTool/actions/localSystem.ts
index 51406667718..57674f57595 100644
--- a/src/store/chat/slices/builtinTool/actions/localSystem.ts
+++ b/src/store/chat/slices/builtinTool/actions/localSystem.ts
@@ -5,7 +5,6 @@ import {
GrepContentParams,
KillCommandParams,
ListLocalFileParams,
- LocalMoveFilesResultItem,
LocalReadFileParams,
LocalReadFilesParams,
LocalSearchFilesParams,
@@ -16,28 +15,14 @@ import {
} from '@lobechat/electron-client-ipc';
import { StateCreator } from 'zustand/vanilla';
-import { localFileService } from '@/services/electron/localFileService';
import { ChatStore } from '@/store/chat/store';
-import {
- EditLocalFileState,
- GetCommandOutputState,
- GlobFilesState,
- GrepContentState,
- KillCommandState,
- LocalFileListState,
- LocalFileSearchState,
- LocalMoveFilesState,
- LocalReadFileState,
- LocalReadFilesState,
- LocalRenameFileState,
- RunCommandState,
-} from '@/tools/local-system/type';
+import { LocalSystemExecutionRuntime } from '@/tools/local-system/ExecutionRuntime';
/* eslint-disable typescript-sort-keys/interface */
export interface LocalFileAction {
- internal_triggerLocalFileToolCalling: <T = any>(
+ internal_triggerLocalFileToolCalling: (
id: string,
- callingService: () => Promise<{ content: any; state?: T }>,
+ callingService: () => Promise<{ content: string; error?: any; state?: any; success: boolean }>,
) => Promise<boolean>;
// File Operations
@@ -63,6 +48,8 @@ export interface LocalFileAction {
}
/* eslint-enable typescript-sort-keys/interface */
+const runtime = new LocalSystemExecutionRuntime();
+
/* eslint-disable sort-keys-fix/sort-keys-fix */
export const localSystemSlice: StateCreator<
ChatStore,
@@ -72,148 +59,49 @@ export const localSystemSlice: StateCreator<
> = (set, get) => ({
// ==================== File Editing ====================
editLocalFile: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<EditLocalFileState>(id, async () => {
- const result = await localFileService.editLocalFile(params);
-
- const message = result.success
- ? `Successfully replaced ${result.replacements} occurrence(s) in ${params.file_path}`
- : `Edit failed: ${result.error}`;
-
- const state: EditLocalFileState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.editLocalFile(params);
});
},
writeLocalFile: async (id, params) => {
return get().internal_triggerLocalFileToolCalling(id, async () => {
- const result = await localFileService.writeFile(params);
-
- let content: { message: string; success: boolean };
-
- if (result.success) {
- content = {
- message: `成功写入文件 ${params.path}`,
- success: true,
- };
- } else {
- const errorMessage = result.error;
-
- content = { message: errorMessage || '写入文件失败', success: false };
- }
- return { content };
+ return await runtime.writeLocalFile(params);
});
},
moveLocalFiles: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalMoveFilesState>(id, async () => {
- const results: LocalMoveFilesResultItem[] = await localFileService.moveLocalFiles(params);
-
- // 检查所有文件是否成功移动以更新消息内容
- const allSucceeded = results.every((r) => r.success);
- const someFailed = results.some((r) => !r.success);
- const successCount = results.filter((r) => r.success).length;
- const failedCount = results.length - successCount;
-
- let message = '';
-
- if (allSucceeded) {
- message = `Successfully moved ${results.length} item(s).`;
- } else if (someFailed) {
- message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;
- } else {
- // 所有都失败了?
- message = `Failed to move all ${results.length} item(s).`;
- }
-
- const state: LocalMoveFilesState = { results, successCount, totalCount: results.length };
-
- return { content: { message, results }, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.moveLocalFiles(params);
});
},
renameLocalFile: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalRenameFileState>(id, async () => {
- const { path: currentPath, newName } = params;
-
- // Basic validation for newName (can be done here or backend, maybe better in backend)
- if (
- !newName ||
- newName.includes('/') ||
- newName.includes('\\') ||
- newName === '.' ||
- newName === '..' ||
- /["*/:<>?\\|]/.test(newName)
- ) {
- throw new Error(
- 'Invalid new name provided. It cannot be empty, contain path separators, or invalid characters.',
- );
- }
-
- const result = await localFileService.renameLocalFile({ newName, path: currentPath }); // Call the specific service
-
- let state: LocalRenameFileState;
- let content: { message: string; success: boolean };
-
- if (result.success) {
- state = { newPath: result.newPath!, oldPath: currentPath, success: true };
- // Simplified message
- content = {
- message: `Successfully renamed file ${currentPath} to ${newName}.`,
- success: true,
- };
- } else {
- const errorMessage = result.error;
- state = {
- error: errorMessage,
- newPath: '',
- oldPath: params.path,
- success: false,
- };
- content = { message: errorMessage, success: false };
- }
- return { content, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.renameLocalFile(params);
});
},
// ==================== Search & Find ====================
grepContent: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<GrepContentState>(id, async () => {
- const result = await localFileService.grepContent(params);
-
- const message = result.success
- ? `Found ${result.total_matches} matches in ${result.matches.length} locations`
- : 'Search failed';
-
- const state: GrepContentState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.grepContent(params);
});
},
globLocalFiles: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<GlobFilesState>(id, async () => {
- const result = await localFileService.globFiles(params);
-
- const message = result.success ? `Found ${result.total_files} files` : 'Glob search failed';
-
- const state: GlobFilesState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.globLocalFiles(params);
});
},
searchLocalFiles: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalFileSearchState>(id, async () => {
- const result = await localFileService.searchLocalFiles(params);
- const state: LocalFileSearchState = { searchResults: result };
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.searchLocalFiles(params);
});
},
listLocalFiles: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalFileListState>(id, async () => {
- const result = await localFileService.listLocalFiles(params);
- const state: LocalFileListState = { listResults: result };
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.listLocalFiles(params);
});
},
@@ -226,67 +114,31 @@ export const localSystemSlice: StateCreator<
},
readLocalFile: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalReadFileState>(id, async () => {
- const result = await localFileService.readLocalFile(params);
- const state: LocalReadFileState = { fileContent: result };
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.readLocalFile(params);
});
},
readLocalFiles: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<LocalReadFilesState>(id, async () => {
- const results = await localFileService.readLocalFiles(params);
- const state: LocalReadFilesState = { filesContent: results };
- return { content: results, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.readLocalFiles(params);
});
},
// ==================== Shell Commands ====================
runCommand: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<RunCommandState>(id, async () => {
- const result = await localFileService.runCommand(params);
-
- let message: string;
-
- if (result.success) {
- if (result.shell_id) {
- message = `Command started in background with shell_id: ${result.shell_id}`;
- } else {
- message = `Command completed successfully.`;
- }
- } else {
- message = `Command failed: ${result.error}`;
- }
-
- const state: RunCommandState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.runCommand(params);
});
},
killCommand: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<KillCommandState>(id, async () => {
- const result = await localFileService.killCommand(params);
-
- const message = result.success
- ? `Successfully killed shell: ${params.shell_id}`
- : `Failed to kill shell: ${result.error}`;
-
- const state: KillCommandState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.killCommand(params);
});
},
getCommandOutput: async (id, params) => {
- return get().internal_triggerLocalFileToolCalling<GetCommandOutputState>(id, async () => {
- const result = await localFileService.getCommandOutput(params);
-
- const message = result.success
- ? `Output retrieved. Running: ${result.running}`
- : `Failed: ${result.error}`;
-
- const state: GetCommandOutputState = { message, result };
-
- return { content: result, state };
+ return get().internal_triggerLocalFileToolCalling(id, async () => {
+ return await runtime.getCommandOutput(params);
});
},
@@ -305,11 +157,22 @@ export const localSystemSlice: StateCreator<
internal_triggerLocalFileToolCalling: async (id, callingService) => {
get().toggleLocalFileLoading(id, true);
try {
- const { state, content } = await callingService();
- if (state) {
- await get().optimisticUpdatePluginState(id, state as any);
+ const { state, content, success, error } = await callingService();
+
+ if (success) {
+ if (state) {
+ await get().optimisticUpdatePluginState(id, state);
+ }
+ await get().optimisticUpdateMessageContent(id, content);
+ } else {
+ await get().optimisticUpdateMessagePluginError(id, {
+ body: error,
+ message: error?.message || 'Operation failed',
+ type: 'PluginServerError',
+ });
+ // Still update content even if failed, to show error message
+ await get().optimisticUpdateMessageContent(id, content);
}
- await get().optimisticUpdateMessageContent(id, JSON.stringify(content));
} catch (error) {
await get().optimisticUpdateMessagePluginError(id, {
body: error,
diff --git a/src/tools/executionRuntimes.ts b/src/tools/executionRuntimes.ts
index b74aae9c177..de2b52cac22 100644
--- a/src/tools/executionRuntimes.ts
+++ b/src/tools/executionRuntimes.ts
@@ -1,6 +1,9 @@
+import { LocalSystemManifest } from './local-system';
+import { LocalSystemExecutionRuntime } from './local-system/ExecutionRuntime';
import { WebBrowsingManifest } from './web-browsing';
import { WebBrowsingExecutionRuntime } from './web-browsing/ExecutionRuntime';
export const BuiltinToolServerRuntimes: Record<string, any> = {
+ [LocalSystemManifest.identifier]: LocalSystemExecutionRuntime,
[WebBrowsingManifest.identifier]: WebBrowsingExecutionRuntime,
};
diff --git a/src/tools/local-system/ExecutionRuntime/index.ts b/src/tools/local-system/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..da4e9264e6f
--- /dev/null
+++ b/src/tools/local-system/ExecutionRuntime/index.ts
@@ -0,0 +1,407 @@
+import {
+ EditLocalFileParams,
+ EditLocalFileResult,
+ GetCommandOutputParams,
+ GetCommandOutputResult,
+ GlobFilesParams,
+ GlobFilesResult,
+ GrepContentParams,
+ GrepContentResult,
+ KillCommandParams,
+ KillCommandResult,
+ ListLocalFileParams,
+ LocalFileItem,
+ LocalMoveFilesResultItem,
+ LocalReadFileParams,
+ LocalReadFileResult,
+ LocalReadFilesParams,
+ LocalSearchFilesParams,
+ MoveLocalFilesParams,
+ RenameLocalFileParams,
+ RenameLocalFileResult,
+ RunCommandParams,
+ RunCommandResult,
+ WriteLocalFileParams,
+} from '@lobechat/electron-client-ipc';
+import { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import { localFileService } from '@/services/electron/localFileService';
+
+import {
+ EditLocalFileState,
+ GetCommandOutputState,
+ GlobFilesState,
+ GrepContentState,
+ KillCommandState,
+ LocalFileListState,
+ LocalFileSearchState,
+ LocalMoveFilesState,
+ LocalReadFileState,
+ LocalReadFilesState,
+ LocalRenameFileState,
+ RunCommandState,
+} from '../type';
+
+export class LocalSystemExecutionRuntime {
+ // ==================== File Operations ====================
+
+ async listLocalFiles(args: ListLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: LocalFileItem[] = await localFileService.listLocalFiles(args);
+
+ const state: LocalFileListState = { listResults: result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async readLocalFile(args: LocalReadFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: LocalReadFileResult = await localFileService.readLocalFile(args);
+
+ const state: LocalReadFileState = { fileContent: result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async readLocalFiles(args: LocalReadFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const results: LocalReadFileResult[] = await localFileService.readLocalFiles(args);
+
+ const state: LocalReadFilesState = { filesContent: results };
+
+ return {
+ content: JSON.stringify(results),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async searchLocalFiles(args: LocalSearchFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: LocalFileItem[] = await localFileService.searchLocalFiles(args);
+
+ const state: LocalFileSearchState = { searchResults: result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async moveLocalFiles(args: MoveLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const results: LocalMoveFilesResultItem[] = await localFileService.moveLocalFiles(args);
+
+ const allSucceeded = results.every((r) => r.success);
+ const someFailed = results.some((r) => !r.success);
+ const successCount = results.filter((r) => r.success).length;
+ const failedCount = results.length - successCount;
+
+ let message = '';
+
+ if (allSucceeded) {
+ message = `Successfully moved ${results.length} item(s).`;
+ } else if (someFailed) {
+ message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;
+ } else {
+ message = `Failed to move all ${results.length} item(s).`;
+ }
+
+ const state: LocalMoveFilesState = {
+ results,
+ successCount,
+ totalCount: results.length,
+ };
+
+ return {
+ content: JSON.stringify({ message, results }),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async renameLocalFile(args: RenameLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: RenameLocalFileResult = await localFileService.renameLocalFile(args);
+
+ if (!result.success) {
+ const state: LocalRenameFileState = {
+ error: result.error,
+ newPath: '',
+ oldPath: args.path,
+ success: false,
+ };
+
+ return {
+ content: JSON.stringify({ message: result.error, success: false }),
+ state,
+ success: false,
+ };
+ }
+
+ const state: LocalRenameFileState = {
+ newPath: result.newPath!,
+ oldPath: args.path,
+ success: true,
+ };
+
+ return {
+ content: JSON.stringify({
+ message: `Successfully renamed file ${args.path} to ${args.newName}.`,
+ success: true,
+ }),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async writeLocalFile(args: WriteLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await localFileService.writeFile(args);
+
+ if (!result.success) {
+ return {
+ content: JSON.stringify({
+ message: result.error || '写入文件失败',
+ success: false,
+ }),
+ error: result.error,
+ success: false,
+ };
+ }
+
+ return {
+ content: JSON.stringify({
+ message: `成功写入文件 ${args.path}`,
+ success: true,
+ }),
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async editLocalFile(args: EditLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: EditLocalFileResult = await localFileService.editLocalFile(args);
+
+ if (!result.success) {
+ return {
+ content: `Edit failed: ${result.error}`,
+ success: false,
+ };
+ }
+
+ const statsText =
+ result.linesAdded || result.linesDeleted
+ ? ` (+${result.linesAdded || 0} -${result.linesDeleted || 0})`
+ : '';
+ const message = `Successfully replaced ${result.replacements} occurrence(s) in ${args.file_path}${statsText}`;
+
+ const state: EditLocalFileState = {
+ diffText: result.diffText,
+ linesAdded: result.linesAdded,
+ linesDeleted: result.linesDeleted,
+ replacements: result.replacements,
+ };
+
+ return {
+ content: message,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Shell Commands ====================
+
+ async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: RunCommandResult = await localFileService.runCommand(args);
+
+ let message: string;
+
+ if (result.success) {
+ if (result.shell_id) {
+ message = `Command started in background with shell_id: ${result.shell_id}`;
+ } else {
+ message = `Command completed successfully.`;
+ }
+ } else {
+ message = `Command failed: ${result.error}`;
+ }
+
+ const state: RunCommandState = { message, result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async getCommandOutput(args: GetCommandOutputParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: GetCommandOutputResult = await localFileService.getCommandOutput(args);
+
+ const message = result.success
+ ? `Output retrieved. Running: ${result.running}`
+ : `Failed: ${result.error}`;
+
+ const state: GetCommandOutputState = { message, result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async killCommand(args: KillCommandParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: KillCommandResult = await localFileService.killCommand(args);
+
+ const message = result.success
+ ? `Successfully killed shell: ${args.shell_id}`
+ : `Failed to kill shell: ${result.error}`;
+
+ const state: KillCommandState = { message, result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Search & Find ====================
+
+ async grepContent(args: GrepContentParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: GrepContentResult = await localFileService.grepContent(args);
+
+ const message = result.success
+ ? `Found ${result.total_matches} matches in ${result.matches.length} locations`
+ : 'Search failed';
+
+ const state: GrepContentState = { message, result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ async globLocalFiles(args: GlobFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result: GlobFilesResult = await localFileService.globFiles(args);
+
+ const message = result.success ? `Found ${result.total_files} files` : 'Glob search failed';
+
+ const state: GlobFilesState = { message, result };
+
+ return {
+ content: JSON.stringify(result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return {
+ content: (error as Error).message,
+ error,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/src/tools/local-system/Intervention/EditLocalFile/index.tsx b/src/tools/local-system/Intervention/EditLocalFile/index.tsx
new file mode 100644
index 00000000000..d9e1a307f42
--- /dev/null
+++ b/src/tools/local-system/Intervention/EditLocalFile/index.tsx
@@ -0,0 +1,89 @@
+import { EditLocalFileParams } from '@lobechat/electron-client-ipc';
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Icon, Text } from '@lobehub/ui';
+import { Skeleton } from 'antd';
+import { createPatch } from 'diff';
+import { ChevronRight } from 'lucide-react';
+import path from 'path-browserify-esm';
+import React, { memo, useMemo } from 'react';
+import { Diff, Hunk, parseDiff } from 'react-diff-view';
+import 'react-diff-view/style/index.css';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import useSWR from 'swr';
+
+import { LocalFile, LocalFolder } from '@/features/LocalFile';
+import { localFileService } from '@/services/electron/localFileService';
+
+const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { base, dir } = path.parse(args.file_path);
+
+ // Fetch full file content
+ const { data: fileData, isLoading } = useSWR(
+ ['readLocalFile', args.file_path],
+ () => localFileService.readLocalFile({ fullContent: true, path: args.file_path }),
+ {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ },
+ );
+
+ // Generate diff from full file content
+ const files = useMemo(() => {
+ if (!fileData?.content) return [];
+
+ try {
+ const oldContent = fileData.content;
+
+ // Generate new content by applying the replacement
+ const newContent = args.replace_all
+ ? oldContent.replaceAll(args.old_string, args.new_string)
+ : oldContent.replace(args.old_string, args.new_string);
+
+ // Use createPatch to generate unified diff with full file content
+ const patch = createPatch(args.file_path, oldContent, newContent, '', '');
+
+ // Add git diff header for parseDiff compatibility
+ const diffText = `diff --git a${args.file_path} b${args.file_path}\n${patch}`;
+
+ return parseDiff(diffText);
+ } catch (error) {
+ console.error('Failed to generate diff:', error);
+ return [];
+ }
+ }, [fileData?.content, args.file_path, args.old_string, args.new_string, args.replace_all]);
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal>
+ <LocalFolder path={dir} />
+ <Icon icon={ChevronRight} />
+ <LocalFile name={base} path={args.file_path} />
+ </Flexbox>
+
+ {isLoading ? (
+ <Skeleton active paragraph={{ rows: 3 }} />
+ ) : (
+ <Flexbox gap={8}>
+ <Text type="secondary">
+ {args.replace_all
+ ? t('localFiles.editFile.replaceAll')
+ : t('localFiles.editFile.replaceFirst')}
+ </Text>
+ {files.map((file, index) => (
+ <div key={`${file.oldPath}-${index}`} style={{ fontSize: '12px' }}>
+ <Diff diffType={file.type} hunks={file.hunks} viewType="split">
+ {(hunks) => hunks.map((hunk) => <Hunk hunk={hunk} key={hunk.content} />)}
+ </Diff>
+ </div>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+EditLocalFile.displayName = 'EditLocalFileIntervention';
+
+export default EditLocalFile;
diff --git a/src/tools/local-system/Intervention/WriteFile/index.tsx b/src/tools/local-system/Intervention/WriteFile/index.tsx
new file mode 100644
index 00000000000..d6347692320
--- /dev/null
+++ b/src/tools/local-system/Intervention/WriteFile/index.tsx
@@ -0,0 +1,72 @@
+import { WriteLocalFileParams } from '@lobechat/electron-client-ipc';
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Highlighter, Icon, Text } from '@lobehub/ui';
+import { ChevronRight } from 'lucide-react';
+import path from 'path-browserify-esm';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { LocalFile, LocalFolder } from '@/features/LocalFile';
+
+const WriteFile = memo<BuiltinInterventionProps<WriteLocalFileParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { base, dir, ext } = path.parse(args.path);
+
+ // Detect language from file extension
+ const language = useMemo(() => {
+ const extMap: Record<string, string> = {
+ css: 'css',
+ html: 'html',
+ js: 'javascript',
+ json: 'json',
+ jsx: 'jsx',
+ md: 'markdown',
+ py: 'python',
+ sh: 'bash',
+ ts: 'typescript',
+ tsx: 'tsx',
+ txt: 'text',
+ xml: 'xml',
+ yaml: 'yaml',
+ yml: 'yaml',
+ };
+ return extMap[ext.replace('.', '')] || 'text';
+ }, [ext]);
+
+ const contentLength = args.content?.length || 0;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal>
+ <LocalFolder path={dir} />
+ <Icon icon={ChevronRight} />
+ <LocalFile name={base} path={args.path} />
+ </Flexbox>
+
+ <Flexbox gap={4}>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text type="secondary">{t('localFiles.writeFile.preview')}</Text>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {contentLength.toLocaleString()} {t('localFiles.writeFile.characters')}
+ </Text>
+ </Flexbox>
+
+ {args.content && (
+ <Highlighter
+ language={language}
+ showLanguage={false}
+ style={{ maxHeight: 400, overflow: 'auto', padding: '8px' }}
+ variant={'outlined'}
+ >
+ {args.content}
+ </Highlighter>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+WriteFile.displayName = 'WriteFileIntervention';
+
+export default WriteFile;
diff --git a/src/tools/local-system/Intervention/index.ts b/src/tools/local-system/Intervention/index.ts
index 3c4a0437335..28183923f4c 100644
--- a/src/tools/local-system/Intervention/index.ts
+++ b/src/tools/local-system/Intervention/index.ts
@@ -1,11 +1,15 @@
import { LocalSystemApiName } from '../index';
+import EditLocalFile from './EditLocalFile';
import MoveLocalFiles from './MoveLocalFiles';
import RunCommand from './RunCommand';
+import WriteFile from './WriteFile';
/**
* Local System Intervention Components Registry
*/
export const LocalSystemInterventions = {
+ [LocalSystemApiName.editLocalFile]: EditLocalFile,
[LocalSystemApiName.moveLocalFiles]: MoveLocalFiles,
[LocalSystemApiName.runCommand]: RunCommand,
+ [LocalSystemApiName.writeLocalFile]: WriteFile,
};
diff --git a/src/tools/local-system/Render/EditLocalFile/index.tsx b/src/tools/local-system/Render/EditLocalFile/index.tsx
new file mode 100644
index 00000000000..5c96d04e9ad
--- /dev/null
+++ b/src/tools/local-system/Render/EditLocalFile/index.tsx
@@ -0,0 +1,67 @@
+import { EditLocalFileParams } from '@lobechat/electron-client-ipc';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Alert, Icon } from '@lobehub/ui';
+import { Skeleton } from 'antd';
+import { ChevronRight } from 'lucide-react';
+import path from 'path-browserify-esm';
+import React, { memo, useMemo } from 'react';
+import { Diff, Hunk, parseDiff } from 'react-diff-view';
+import 'react-diff-view/style/index.css';
+import { Flexbox } from 'react-layout-kit';
+
+import { LocalFile, LocalFolder } from '@/features/LocalFile';
+
+import { EditLocalFileState } from '../../type';
+
+const EditLocalFile = memo<BuiltinRenderProps<EditLocalFileParams, EditLocalFileState>>(
+ ({ args, pluginState, pluginError }) => {
+ const { base, dir } = path.parse(args.file_path);
+
+ // Parse diff for react-diff-view
+ const files = useMemo(() => {
+ const diffText = pluginState?.diffText;
+ if (!diffText) return [];
+
+ try {
+ return parseDiff(diffText);
+ } catch (error) {
+ console.error('Failed to parse diff:', error);
+ return [];
+ }
+ }, [pluginState?.diffText]);
+
+ if (!args) return <Skeleton active />;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal>
+ <LocalFolder path={dir} />
+ <Icon icon={ChevronRight} />
+ <LocalFile name={base} path={args.file_path} />
+ </Flexbox>
+ {pluginError ? (
+ <Alert
+ description={pluginError.message || 'Unknown error occurred'}
+ message="Edit Failed"
+ showIcon
+ type="error"
+ />
+ ) : (
+ <Flexbox gap={12}>
+ {files.map((file, index) => (
+ <div key={`${file.oldPath}-${index}`} style={{ fontSize: '12px' }}>
+ <Diff diffType={file.type} gutterType="default" hunks={file.hunks} viewType="split">
+ {(hunks) => hunks.map((hunk) => <Hunk hunk={hunk} key={hunk.content} />)}
+ </Diff>
+ </div>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+EditLocalFile.displayName = 'EditLocalFile';
+
+export default EditLocalFile;
diff --git a/src/tools/local-system/Render/ReadLocalFile/ReadFileView.tsx b/src/tools/local-system/Render/ReadLocalFile/ReadFileView.tsx
index c42ab635d62..748b4596baf 100644
--- a/src/tools/local-system/Render/ReadLocalFile/ReadFileView.tsx
+++ b/src/tools/local-system/Render/ReadLocalFile/ReadFileView.tsx
@@ -1,8 +1,8 @@
import { LocalReadFileResult } from '@lobechat/electron-client-ipc';
import { ActionIcon, Icon, Markdown, Text } from '@lobehub/ui';
import { createStyles } from 'antd-style';
-import { AlignLeft, Asterisk, ChevronDownIcon, ExternalLink, FolderOpen } from 'lucide-react';
-import React, { memo, useState } from 'react';
+import { AlignLeft, Asterisk, ExternalLink, FolderOpen } from 'lucide-react';
+import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
@@ -24,7 +24,6 @@ const useStyles = createStyles(({ css, token, cx }) => ({
container: css`
justify-content: space-between;
- height: 64px;
padding: 8px;
border-radius: ${token.borderRadiusLG}px;
@@ -79,11 +78,11 @@ const useStyles = createStyles(({ css, token, cx }) => ({
overflow: hidden;
- margin-block-start: 8px;
- padding: 8px;
+ padding-block: 0;
+ padding-inline: 8px;
border-radius: 8px;
- background: ${token.colorFillQuaternary};
+ background: ${token.colorBgContainer};
`,
previewText: css`
font-size: 12px;
@@ -102,11 +101,6 @@ const ReadFileView = memo<ReadFileViewProps>(
({ filename, path, fileType, charCount, content, totalLineCount, totalCharCount, loc }) => {
const { t } = useTranslation('tool');
const { styles } = useStyles();
- const [isExpanded, setIsExpanded] = useState(false);
-
- const handleToggleExpand = () => {
- setIsExpanded(!isExpanded);
- };
const handleOpenFile = (e: React.MouseEvent) => {
e.stopPropagation();
@@ -121,89 +115,70 @@ const ReadFileView = memo<ReadFileViewProps>(
const displayPath = useElectronStore(desktopStateSelectors.displayRelativePath(path));
return (
- <Flexbox className={styles.container}>
- <Flexbox
- align={'center'}
- className={styles.header}
- gap={12}
- horizontal
- justify={'space-between'}
- onClick={handleToggleExpand}
- >
- <Flexbox align={'center'} flex={1} gap={0} horizontal style={{ overflow: 'hidden' }}>
- <FileIcon fileName={filename} fileType={fileType} size={16} variant={'raw'} />
- <Flexbox horizontal>
- <Text className={styles.fileName} ellipsis>
- {filename}
- </Text>
- {/* Actions on Hover */}
- <Flexbox className={styles.actions} gap={2} horizontal style={{ marginLeft: 8 }}>
- <ActionIcon
- icon={ExternalLink}
- onClick={handleOpenFile}
- size="small"
- title={t('localFiles.openFile')}
- />
- <ActionIcon
- icon={FolderOpen}
- onClick={handleOpenFolder}
- size="small"
- title={t('localFiles.openFolder')}
- />
+ <Flexbox className={styles.container} gap={12}>
+ <Flexbox>
+ <Flexbox
+ align={'center'}
+ className={styles.header}
+ gap={12}
+ horizontal
+ justify={'space-between'}
+ >
+ <Flexbox align={'center'} flex={1} gap={0} horizontal style={{ overflow: 'hidden' }}>
+ <FileIcon fileName={filename} fileType={fileType} size={16} variant={'raw'} />
+ <Flexbox horizontal>
+ <Text className={styles.fileName} ellipsis>
+ {filename}
+ </Text>
+ {/* Actions on Hover */}
+ <Flexbox className={styles.actions} gap={2} horizontal style={{ marginLeft: 8 }}>
+ <ActionIcon
+ icon={ExternalLink}
+ onClick={handleOpenFile}
+ size="small"
+ title={t('localFiles.openFile')}
+ />
+ <ActionIcon
+ icon={FolderOpen}
+ onClick={handleOpenFolder}
+ size="small"
+ title={t('localFiles.openFolder')}
+ />
+ </Flexbox>
</Flexbox>
</Flexbox>
- </Flexbox>
- <Flexbox align={'center'} className={styles.meta} gap={8} horizontal>
- {isExpanded && (
+ <Flexbox align={'center'} className={styles.meta} gap={16} horizontal>
<Flexbox align={'center'} gap={4} horizontal>
<Icon icon={Asterisk} size={'small'} />
<span>
{charCount} / <span className={styles.lineCount}>{totalCharCount}</span>
</span>
</Flexbox>
- )}
- <Flexbox align={'center'} gap={4} horizontal>
- <Icon icon={AlignLeft} size={'small'} />
- {isExpanded ? (
+ <Flexbox align={'center'} gap={4} horizontal>
+ <Icon icon={AlignLeft} size={'small'} />
<span>
L{loc?.[0]}-{loc?.[1]} /{' '}
<span className={styles.lineCount}>{totalLineCount}</span>
</span>
- ) : (
- <span>
- L{loc?.[0]}-{loc?.[1]}
- </span>
- )}
+ </Flexbox>
</Flexbox>
- <ActionIcon
- active={isExpanded}
- icon={ChevronDownIcon}
- onClick={handleToggleExpand}
- size="small"
- style={{
- transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
- transition: 'transform 0.2s',
- }}
- />
</Flexbox>
+
+ {/* Path */}
+ <Text className={styles.path} ellipsis type={'secondary'}>
+ {displayPath}
+ </Text>
</Flexbox>
- {/* Path */}
- <Text className={styles.path} ellipsis type={'secondary'}>
- {displayPath}
- </Text>
-
- {isExpanded && (
- <Flexbox className={styles.previewBox} style={{ maxHeight: 240, overflow: 'auto' }}>
- {fileType === 'md' ? (
- <Markdown>{content}</Markdown>
- ) : (
- <div className={styles.previewText} style={{ width: '100%' }}>
- {content}
- </div>
- )}
- </Flexbox>
- )}
+ <Flexbox className={styles.previewBox} style={{ maxHeight: 240 }}>
+ {fileType === 'md' ? (
+ <Markdown style={{ overflow: 'auto' }}>{content}</Markdown>
+ ) : (
+ <div className={styles.previewText} style={{ width: '100%' }}>
+ {content}
+ </div>
+ )}
+ </Flexbox>
</Flexbox>
);
},
diff --git a/src/tools/local-system/Render/index.ts b/src/tools/local-system/Render/index.ts
index a0cb0ab33f8..4076cb4ba8a 100644
--- a/src/tools/local-system/Render/index.ts
+++ b/src/tools/local-system/Render/index.ts
@@ -1,4 +1,5 @@
import { LocalSystemApiName } from '../index';
+import EditLocalFile from './EditLocalFile';
import ListFiles from './ListFiles';
import MoveLocalFiles from './MoveLocalFiles';
import ReadLocalFile from './ReadLocalFile';
@@ -11,6 +12,7 @@ import WriteFile from './WriteFile';
* Local System Render Components Registry
*/
export const LocalSystemRenders = {
+ [LocalSystemApiName.editLocalFile]: EditLocalFile,
[LocalSystemApiName.listLocalFiles]: ListFiles,
[LocalSystemApiName.moveLocalFiles]: MoveLocalFiles,
[LocalSystemApiName.readLocalFile]: ReadLocalFile,
diff --git a/src/tools/local-system/index.ts b/src/tools/local-system/index.ts
index d53c664e4cc..ef150d7188d 100644
--- a/src/tools/local-system/index.ts
+++ b/src/tools/local-system/index.ts
@@ -206,6 +206,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Perform exact string replacements in files. Must read the file first before editing.',
+ humanIntervention: 'required',
name: LocalSystemApiName.editLocalFile,
parameters: {
properties: {
diff --git a/src/tools/local-system/type.ts b/src/tools/local-system/type.ts
index 1e6cc827f3b..30c2035cfd5 100644
--- a/src/tools/local-system/type.ts
+++ b/src/tools/local-system/type.ts
@@ -1,5 +1,4 @@
import {
- EditLocalFileResult,
GetCommandOutputResult,
GlobFilesResult,
GrepContentResult,
@@ -85,6 +84,8 @@ export interface GlobFilesState {
// Edit State
export interface EditLocalFileState {
- message: string;
- result: EditLocalFileResult;
+ diffText?: string;
+ linesAdded?: number;
+ linesDeleted?: number;
+ replacements: number;
}