π€― 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
β¨ feat(project-file): replicate desktop file operations to web via device RPC (#15885)
Arvin Xu91d684878f61
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 12d44c8b1c4..f61e3fec042 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -384,6 +384,73 @@ export const deviceRouter = router({}),),+ /**+ * Move files/folders within a directory on a remote device, via the device's+ * `moveLocalFiles` RPC. Powers the Files tree's drag-to-move in device mode.+ */+ moveProjectFiles: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ items: z.array(z.object({ newPath: z.string(), oldPath: z.string() })),+ workingDirectory: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.moveProjectFiles({+ deviceId: input.deviceId,+ items: input.items,+ userId: ctx.userId,+ workingDirectory: input.workingDirectory,+ }),+ ),++ /**+ * Rename a single file/folder in a directory on a remote device, via the+ * device's `renameLocalFile` RPC.+ */+ renameProjectFile: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ newName: z.string(),+ path: z.string(),+ workingDirectory: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.renameProjectFile({+ deviceId: input.deviceId,+ newName: input.newName,+ path: input.path,+ userId: ctx.userId,+ workingDirectory: input.workingDirectory,+ }),+ ),++ /**+ * Save edited content back to a file on a remote device, via the device's+ * `writeLocalFile` RPC. Powers remote save in the LocalFile editor.+ */+ writeProjectFile: deviceProcedure+ .input(+ z.object({+ content: z.string(),+ deviceId: z.string(),+ path: z.string(),+ workingDirectory: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.writeProjectFile({+ content: input.content,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workingDirectory: input.workingDirectory,+ }),+ ),+/*** Check whether a path exists on a remote device and is a directory, via the* device's `statPath` RPC. Lets a web client validate a manually-entereddiff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex 41c90dfd756..4a86db5c608 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -769,6 +769,148 @@ describe('DeviceGateway', () => {});});+ describe('file mutation containment', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ describe('writeProjectFile', () => {+ it('invokes the rpc when the path is inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.writeProjectFile({+ content: 'next',+ deviceId: 'dev-1',+ path: '/proj/src/App.tsx',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ { method: 'writeLocalFile', params: { content: 'next', path: '/proj/src/App.tsx' } },+ );+ });++ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: '/etc/passwd',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('rejects a `..` traversal that resolves outside the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: '/proj/../secrets.env',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('contains Windows device paths using Windows path semantics', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: 'C:\\Windows\\System32\\drivers\\etc\\hosts',+ userId: 'user-1',+ workingDirectory: 'C:\\proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('renameProjectFile', () => {+ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.renameProjectFile({+ deviceId: 'dev-1',+ newName: 'evil.ts',+ path: '/etc/hosts',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('moveProjectFiles', () => {+ it('throws when any item moves out of the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.moveProjectFiles({+ deviceId: 'dev-1',+ items: [+ { newPath: '/proj/b.ts', oldPath: '/proj/a.ts' },+ { newPath: '/tmp/exfil.ts', oldPath: '/proj/c.ts' },+ ],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('invokes the rpc when every item stays inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: [{ newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true }],+ success: true,+ });++ const proxy = new DeviceGateway();+ const result = await proxy.moveProjectFiles({+ deviceId: 'dev-1',+ items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual([+ { newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true },+ ]);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'moveLocalFiles',+ params: { items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }] },+ },+ );+ });+ });+ });+describe('getClient (lazy initialization)', () => {it('should return null when URL is missing', async () => {mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 851e012bcb8..a7e8cafc9cb 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1,3 +1,5 @@+import path from 'node:path';+import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';import {type DeviceMessageApiResult,@@ -26,7 +28,11 @@ import type {DeviceGitWorktreeListItem,DeviceListProjectSkillsResult,DeviceLocalFilePreviewResult,+ DeviceMoveProjectFileItem,+ DeviceMoveProjectFileResultItem,DeviceProjectFileIndexResult,+ DeviceRenameProjectFileResult,+ DeviceWriteProjectFileResult,ProjectSkillMeta,WorkspaceInitResult,} from '@lobechat/types';@@ -36,6 +42,42 @@ import { gatewayEnv } from '@/envs/gateway';const log = debug('lobe-server:device-gateway');+/**+ * Is `target` the same as, or nested inside, `root`?+ *+ * The device's working directory may be a POSIX path (`/Users/β¦`) or a Windows+ * path (`C:\β¦`) while this check runs on the cloud server (POSIX). We pick the+ * path flavour from the root's shape so a Windows device path is still resolved+ * with Windows semantics rather than being mangled by `path.posix`.+ */+const isPathWithinRoot = (root: string, target: string): boolean => {+ const p = /^[A-Z]:[/\\]/i.test(root) ? path.win32 : path.posix;+ if (!p.isAbsolute(root) || !p.isAbsolute(target)) return false;+ const relative = p.relative(p.resolve(root), p.resolve(target));+ return relative === '' || (!relative.startsWith('..') && !p.isAbsolute(relative));+};++/**+ * Guard the web/remote file mutations (move / rename / write) against escaping+ * the project root. These routes accept absolute paths straight from an+ * untrusted browser session, so before forwarding them to a device we confirm+ * every path stays inside the workspace the UI is operating in β otherwise a+ * caller could bypass the Files tree and mutate arbitrary locations on the+ * device. Mirrors the read path's `workspaceRoot` containment check.+ */+const assertPathsWithinWorkspace = (+ workspaceRoot: string,+ candidates: Array<string | undefined>,+): void => {+ if (!workspaceRoot) throw new Error('A workspace root is required for file mutations');++ for (const candidate of candidates) {+ if (!candidate || !isPathWithinRoot(workspaceRoot, candidate)) {+ throw new Error(`Path is outside the approved workspace: ${candidate ?? '(empty)'}`);+ }+ }+};+export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };export class DeviceGateway {@@ -683,6 +725,108 @@ export class DeviceGateway {}}+ /**+ * Move one or more files/folders within a directory on a remote device, via+ * the device's `moveLocalFiles` RPC. Powers the Files tree's move in device+ * mode. Unlike the read RPCs this is a user-initiated mutation, so a missing+ * gateway / offline device / failed call throws rather than degrading to+ * `undefined` β the UI surfaces the error instead of silently no-op'ing.+ */+ async moveProjectFiles(params: {+ deviceId: string;+ items: DeviceMoveProjectFileItem[];+ timeout?: number;+ userId: string;+ workingDirectory: string;+ }): Promise<DeviceMoveProjectFileResultItem[]> {+ const { userId, deviceId, items, workingDirectory, timeout = 30_000 } = params;+ const client = this.getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(+ workingDirectory,+ items.flatMap((item) => [item.oldPath, item.newPath]),+ );++ const result = await client.invokeRpc<DeviceMoveProjectFileResultItem[]>(+ { deviceId, timeout, userId },+ { method: 'moveLocalFiles', params: { items } },+ );++ if (!result.success || !result.data) {+ log('moveProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Move failed');+ }++ return result.data;+ }++ /**+ * Rename a single file/folder in a directory on a remote device, via the+ * device's `renameLocalFile` RPC. Like `moveProjectFiles`, a transport failure+ * throws rather than degrading silently.+ */+ async renameProjectFile(params: {+ deviceId: string;+ newName: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ }): Promise<DeviceRenameProjectFileResult> {+ const { userId, deviceId, path, newName, workingDirectory, timeout = 30_000 } = params;+ const client = this.getClient();+ if (!client) throw new Error('Device gateway not configured');++ // The rename stays in the same directory (the device rejects separators in+ // `newName`), so containing the source path also contains the target.+ assertPathsWithinWorkspace(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceRenameProjectFileResult>(+ { deviceId, timeout, userId },+ { method: 'renameLocalFile', params: { newName, path } },+ );++ if (!result.success || !result.data) {+ log('renameProjectFile: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Rename failed');+ }++ return result.data;+ }++ /**+ * Save edited content back to a file on a remote device, via the device's+ * `writeLocalFile` RPC. Powers remote save in the LocalFile editor. Like the+ * other file mutations, a transport failure throws rather than degrading.+ */+ async writeProjectFile(params: {+ content: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ }): Promise<DeviceWriteProjectFileResult> {+ const { userId, deviceId, path, content, workingDirectory, timeout = 30_000 } = params;+ const client = this.getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceWriteProjectFileResult>(+ { deviceId, timeout, userId },+ { method: 'writeLocalFile', params: { content, path } },+ );++ if (!result.success || !result.data) {+ log('writeProjectFile: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Write failed');+ }++ return result.data;+ }+/*** Check whether a path exists on the device and is a directory, via the same* generic `invokeRpc` channel as `gitInfo`. Lets a web / remote clientdiff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 8b34fc569d9..7ac3f590774 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';@@ -85,4 +85,47 @@ describe('executeDeviceRpc', () => {const result = await executeDeviceRpc('listGitBranches', { path: root }, makeDeps());expect(Array.isArray(result)).toBe(true);});++ it('routes moveLocalFiles to the shared local-file-shell impl', async () => {+ const oldPath = path.join(root, 'move-src.txt');+ const newPath = path.join(root, 'move-dst.txt');+ await writeFile(oldPath, 'hello');++ const result = (await executeDeviceRpc(+ 'moveLocalFiles',+ { items: [{ newPath, oldPath }] },+ makeDeps(),+ )) as { newPath?: string; success: boolean }[];++ expect(result).toHaveLength(1);+ expect(result[0].success).toBe(true);+ expect(result[0].newPath).toBe(newPath);+ });++ it('routes renameLocalFile to the shared local-file-shell impl', async () => {+ const filePath = path.join(root, 'rename-src.txt');+ await writeFile(filePath, 'hello');++ const result = (await executeDeviceRpc(+ 'renameLocalFile',+ { newName: 'rename-dst.txt', path: filePath },+ makeDeps(),+ )) as { newPath: string; success: boolean };++ expect(result.success).toBe(true);+ expect(result.newPath).toBe(path.join(root, 'rename-dst.txt'));+ });++ it('routes writeLocalFile to the shared local-file-shell impl', async () => {+ const filePath = path.join(root, 'write-target.txt');++ const result = (await executeDeviceRpc(+ 'writeLocalFile',+ { content: 'remote edit', path: filePath },+ makeDeps(),+ )) as { success: boolean };++ expect(result.success).toBe(true);+ expect(await readFile(filePath, 'utf8')).toBe('remote edit');+ });});diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex b5e6f3962e0..9504c2c9586 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -10,10 +10,13 @@ import {getLinkedPullRequest,listGitBranches,listGitRemoteBranches,+ moveLocalFiles,pullGitBranch,pushGitBranch,renameGitBranch,+ renameLocalFile,revertGitFile,+ writeLocalFile,} from '@lobechat/local-file-shell';import type {@@ -37,6 +40,9 @@ export const DEVICE_RPC_METHODS = ['statPath','getProjectFileIndex','getLocalFilePreview',+ 'moveLocalFiles',+ 'renameLocalFile',+ 'writeLocalFile','getGitBranch','getLinkedPullRequest','getGitWorkingTreeStatus',@@ -93,6 +99,18 @@ export const executeDeviceRpc = async (return deps.getLocalFilePreview(params as LocalFilePreviewUrlParams);}+ case 'moveLocalFiles': {+ return moveLocalFiles(params as { items: { newPath: string; oldPath: string }[] });+ }++ case 'renameLocalFile': {+ return renameLocalFile(params as { newName: string; path: string });+ }++ case 'writeLocalFile': {+ return writeLocalFile(params as { content: string; path: string });+ }+case 'getGitBranch': {return getGitBranch((params as { path: string }).path);}diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 3a9d7adab8f..1cc3923c4b0 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -367,6 +367,40 @@ export interface DeviceLocalFilePreviewResult {success: boolean;}+/** One file/folder to move within a directory on a remote device. Mirrors `MoveLocalFileParams`. */+export interface DeviceMoveProjectFileItem {+ newPath: string;+ oldPath: string;+}++/**+ * Per-item result of the `moveLocalFiles` device RPC. The move is batched and+ * each item succeeds or fails independently. Mirrors the desktop+ * `LocalMoveFilesResultItem`.+ */+export interface DeviceMoveProjectFileResultItem {+ error?: string;+ newPath?: string;+ sourcePath: string;+ success: boolean;+}++/** Result of the `renameLocalFile` device RPC. Mirrors the desktop `RenameLocalFileResult`. */+export interface DeviceRenameProjectFileResult {+ error?: string;+ newPath: string;+ success: boolean;+}++/**+ * Result of the `writeLocalFile` device RPC β saving edited content back to a+ * file on a remote device. Mirrors the desktop `WriteFileResult`.+ */+export interface DeviceWriteProjectFileResult {+ error?: string;+ success: boolean;+}+/*** A single project skill (`.agents/skills` / `.claude/skills`) discovered on a* remote device, returned by the `listProjectSkills` device RPC. Mirrors thediff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 5d1542ff482..6190dc28c02 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -24,6 +24,7 @@ import { localFileKeys } from '@/libs/swr/keys';import { type LocalFilePreview, projectFileService } from '@/services/projectFile';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';+import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';import {parseSkillMarkdownFrontmatter,parseSkillMarkdownFrontmatterFields,@@ -165,7 +166,13 @@ const TextPreviewPane = memo<TextPreviewPaneProps>([contentType, filePath],);const canRender = isMarkdown || isHtml;- const buffer = useChatStore(chatPortalSelectors.localFileBuffer(filePath));+ // Edit buffers are scoped by tab identity (device + working directory + path)+ // so the same path opened on two devices/workspaces keeps independent edits.+ const tabId = useMemo(+ () => createLocalFileTabId({ deviceId, filePath, workingDirectory }),+ [deviceId, filePath, workingDirectory],+ );+ const buffer = useChatStore(chatPortalSelectors.localFileBuffer(tabId));const setLocalFileBuffer = useChatStore((s) => s.setLocalFileBuffer);const saveLocalFile = useChatStore((s) => s.saveLocalFile);@@ -176,29 +183,38 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(if (readOnly) return;if (next === content) {- setLocalFileBuffer(filePath, undefined);+ setLocalFileBuffer(tabId, undefined);} else {- setLocalFileBuffer(filePath, next);+ setLocalFileBuffer(tabId, next);}},- [content, filePath, readOnly, setLocalFileBuffer],+ [content, tabId, readOnly, setLocalFileBuffer],);const handleSave = useCallback(async () => {if (readOnly) return;try {- const saved = await saveLocalFile(filePath);+ const saved = await saveLocalFile({ deviceId, filePath, workingDirectory });if (saved === undefined) return;// Update SWR cache BEFORE clearing the buffer, otherwise React will// briefly render with buffer cleared but content still stale, causing// CodeMirror to setValue and reset the cursor.onSaved?.(saved);- setLocalFileBuffer(filePath, undefined);+ setLocalFileBuffer(tabId, undefined);} catch {/* swallow β surfacing handled elsewhere if needed */}- }, [filePath, onSaved, readOnly, saveLocalFile, setLocalFileBuffer]);+ }, [+ deviceId,+ filePath,+ onSaved,+ readOnly,+ saveLocalFile,+ setLocalFileBuffer,+ tabId,+ workingDirectory,+ ]);const { body, frontmatter } = useMemo(() => (isMarkdown ? parseSkillMarkdownFrontmatter(editingValue) : { body: editingValue }),@@ -407,7 +423,9 @@ const ActiveFileView = memo<ActiveFileViewProps>(deviceId={deviceId}ext={ext}filePath={filePath}- readOnly={!!deviceId}+ // Remote files are now editable: saveLocalFile routes the write to the+ // device over RPC (writeProjectFile) just as local files go through IPC.+ readOnly={false}reloading={isValidating}workingDirectory={workingDirectory}onReload={handleReload}diff --git a/src/features/Portal/LocalFile/TabStrip.tsx b/src/features/Portal/LocalFile/TabStrip.tsxindex 95ba3bb7e14..82a4eb0177a 100644--- a/src/features/Portal/LocalFile/TabStrip.tsx+++ b/src/features/Portal/LocalFile/TabStrip.tsx@@ -161,8 +161,9 @@ const TabStrip = memo(() => {const closeRightLocalFileTabs = useChatStore((s) => s.closeRightLocalFileTabs);const confirmClose = useCallback(- (filePath: string, perform: () => void) => {- if (!(filePath in dirtyContents)) {+ (id: string, filePath: string, perform: () => void) => {+ // Edit buffers are keyed by tab identity, not bare file path.+ if (!(id in dirtyContents)) {perform();return;}@@ -222,7 +223,7 @@ const TabStrip = memo(() => {onClick: () => {const filePath =openLocalFiles.find((file) => getLocalFileTabId(file) === id)?.filePath ?? id;- confirmClose(filePath, () => closeLocalFileTab(id));+ confirmClose(id, filePath, () => closeLocalFileTab(id));},},],@@ -281,11 +282,11 @@ const TabStrip = memo(() => {<buttonaria-label={`Close ${filename}`}className={styles.tabClose}- data-dirty={filePath in dirtyContents ? 'true' : 'false'}+ data-dirty={id in dirtyContents ? 'true' : 'false'}type="button"onClick={(e) => {e.stopPropagation();- confirmClose(filePath, () => closeLocalFileTab(id));+ confirmClose(id, filePath, () => closeLocalFileTab(id));}}><span className={'cm-tab-close-x'}>diff --git a/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx b/src/routes/(main)/settings/provider/detail/default/CustomProviderDetail.tsxsimilarity index 87%rename from src/routes/(main)/settings/provider/detail/default/ClientMode.tsxrename to src/routes/(main)/settings/provider/detail/default/CustomProviderDetail.tsxindex 1c1b53fade7..ce1c1427296 100644--- a/src/routes/(main)/settings/provider/detail/default/ClientMode.tsx+++ b/src/routes/(main)/settings/provider/detail/default/CustomProviderDetail.tsx@@ -12,7 +12,7 @@ import { useAiInfraStore } from '@/store/aiInfra';import ModelList from '../../features/ModelList';import ProviderConfig from '../../features/ProviderConfig';-const ClientMode = memo<{ id: string }>(({ id }) => {+const CustomProviderDetail = memo<{ id: string }>(({ id }) => {const useFetchAiProviderItem = useAiInfraStore((s) => s.useFetchAiProviderItem);useFetchAiProviderItem(id);@@ -20,7 +20,7 @@ const ClientMode = memo<{ id: string }>(({ id }) => {aiProviderService.getAiProviderById(id),);- if (isLoading || !data || !data.id) return <Loading debugId="Provider > ClientMode" />;+ if (isLoading || !data || !data.id) return <Loading debugId="Provider > CustomProviderDetail" />;return (<Flexbox gap={24} paddingBlock={8}>@@ -30,4 +30,4 @@ const ClientMode = memo<{ id: string }>(({ id }) => {);});-export default ClientMode;+export default CustomProviderDetail;diff --git a/src/routes/(main)/settings/provider/detail/default/ProviderDetialPage.tsx b/src/routes/(main)/settings/provider/detail/default/ProviderDetialPage.tsxindex 3b00c36391a..bf3b16e93b8 100644--- a/src/routes/(main)/settings/provider/detail/default/ProviderDetialPage.tsx+++ b/src/routes/(main)/settings/provider/detail/default/ProviderDetialPage.tsx@@ -1,6 +1,6 @@import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';-import ClientMode from './ClientMode';+import CustomProviderDetail from './CustomProviderDetail';import ProviderDetail from './index';const ProviderDetialPage = (props: { id?: string | null }) => {@@ -11,7 +11,7 @@ const ProviderDetialPage = (props: { id?: string | null }) => {if (!!builtinProviderCard) return <ProviderDetail source={'builtin'} {...builtinProviderCard} />;if (id) {- return <ClientMode id={id} />;+ return <CustomProviderDetail id={id} />;}return null;};diff --git a/src/services/projectFile.ts b/src/services/projectFile.tsindex 664471b53c6..404853aab4e 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -1,6 +1,9 @@import type {LocalFilePreviewUrlParams,+ LocalMoveFilesResultItem,+ MoveLocalFileParams,ProjectFileIndexResult,+ RenameLocalFileResult,} from '@lobechat/electron-client-ipc';import type { DeviceLocalFilePreview } from '@lobechat/types';@@ -84,6 +87,63 @@ class ProjectFileService {return localFileService.getLocalFilePreview(params);}++ /**+ * Move one or more files/folders within a project working directory. Batched:+ * each item succeeds or fails independently.+ */+ async moveProjectFiles({+ deviceId,+ items,+ workingDirectory,+ }: {+ deviceId?: string;+ items: MoveLocalFileParams[];+ workingDirectory: string;+ }): Promise<LocalMoveFilesResultItem[]> {+ return deviceId+ ? lambdaClient.device.moveProjectFiles.mutate({ deviceId, items, workingDirectory })+ : localFileService.moveLocalFiles({ items });+ }++ /** Rename a single file/folder in a project working directory. */+ async renameProjectFile({+ deviceId,+ newName,+ path,+ workingDirectory,+ }: {+ deviceId?: string;+ newName: string;+ path: string;+ workingDirectory: string;+ }): Promise<RenameLocalFileResult> {+ return deviceId+ ? lambdaClient.device.renameProjectFile.mutate({ deviceId, newName, path, workingDirectory })+ : localFileService.renameLocalFile({ newName, path });+ }++ /**+ * Save edited content back to a file in a project working directory. The+ * remote RPC and local IPC both report fs failures (permission denied, etc.)+ * as `{ success: false, error }` β callers must inspect `success` before+ * treating the save as complete.+ */+ async writeProjectFile({+ content,+ deviceId,+ path,+ workingDirectory,+ }: {+ content: string;+ deviceId?: string;+ path: string;+ workingDirectory: string;+ }): Promise<{ error?: string; success: boolean }> {+ return deviceId+ ? lambdaClient.device.writeProjectFile.mutate({ content, deviceId, path, workingDirectory })+ : localFileService.writeFile({ content, path });+ }}export const projectFileService = new ProjectFileService();diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.tsindex 7a6a76eff7f..a9d23b8c3d0 100644--- a/src/store/chat/slices/portal/action.test.ts+++ b/src/store/chat/slices/portal/action.test.ts@@ -1,6 +1,7 @@import { act, renderHook } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';+import { projectFileService } from '@/services/projectFile';import { useChatStore } from '@/store/chat';import { createLocalFileScopeKey, createLocalFileTabId } from './helpers';@@ -625,6 +626,7 @@ describe('chatDockSlice', () => {it('should not clear local dirty buffer when closing a remote tab with the same file path', () => {const { result } = renderHook(() => useChatStore());+ const localId = localFileTabId({ filePath: '/path/a.ts', workingDirectory: '/path' });const remoteId = localFileTabId({deviceId: 'device-1',filePath: '/path/a.ts',@@ -633,12 +635,15 @@ describe('chatDockSlice', () => {act(() => {result.current.openLocalFile({ filePath: '/path/a.ts', workingDirectory: '/path' });- result.current.setLocalFileBuffer('/path/a.ts', 'dirty content');+ // Buffers are keyed by tab identity, so the local and remote tabs holding+ // the same absolute path each own an independent buffer.+ result.current.setLocalFileBuffer(localId, 'dirty content');result.current.openLocalFile({deviceId: 'device-1',filePath: '/path/a.ts',workingDirectory: '/remote/path',});+ result.current.setLocalFileBuffer(remoteId, 'remote edits');});act(() => {@@ -646,7 +651,81 @@ describe('chatDockSlice', () => {});expect(result.current.openLocalFiles).toHaveLength(1);- expect(result.current.dirtyLocalFileContents['/path/a.ts']).toBe('dirty content');+ // Closing the remote tab drops only its buffer; the local tab's stays.+ expect(result.current.dirtyLocalFileContents[remoteId]).toBeUndefined();+ expect(result.current.dirtyLocalFileContents[localId]).toBe('dirty content');+ });+ });++ describe('saveLocalFile', () => {+ const target = {+ deviceId: 'device-1',+ filePath: '/remote/proj/a.ts',+ workingDirectory: '/remote/proj',+ };++ it('reads the buffer for the matching tab and writes through the chokepoint', async () => {+ const { result } = renderHook(() => useChatStore());+ const writeSpy = vi+ .spyOn(projectFileService, 'writeProjectFile')+ .mockResolvedValue({ success: true });++ act(() => {+ result.current.setLocalFileBuffer(localFileTabId(target), 'edited');+ });++ let saved: string | undefined;+ await act(async () => {+ saved = await result.current.saveLocalFile(target);+ });++ expect(saved).toBe('edited');+ expect(writeSpy).toHaveBeenCalledWith({+ content: 'edited',+ deviceId: 'device-1',+ path: '/remote/proj/a.ts',+ workingDirectory: '/remote/proj',+ });+ writeSpy.mockRestore();+ });++ it('does not read another tab/device buffer for the same path', async () => {+ const { result } = renderHook(() => useChatStore());+ const writeSpy = vi+ .spyOn(projectFileService, 'writeProjectFile')+ .mockResolvedValue({ success: true });++ act(() => {+ // A different device holds an edit buffer at the same absolute path.+ result.current.setLocalFileBuffer(+ localFileTabId({ ...target, deviceId: 'device-2' }),+ 'other device edits',+ );+ });++ let saved: string | undefined;+ await act(async () => {+ saved = await result.current.saveLocalFile(target);+ });++ // device-1 has no buffer, so the save is a no-op and never writes.+ expect(saved).toBeUndefined();+ expect(writeSpy).not.toHaveBeenCalled();+ writeSpy.mockRestore();+ });++ it('throws when the write reports failure so the buffer stays dirty', async () => {+ const { result } = renderHook(() => useChatStore());+ const writeSpy = vi+ .spyOn(projectFileService, 'writeProjectFile')+ .mockResolvedValue({ error: 'EACCES', success: false });++ act(() => {+ result.current.setLocalFileBuffer(localFileTabId(target), 'edited');+ });++ await expect(result.current.saveLocalFile(target)).rejects.toThrow('EACCES');+ writeSpy.mockRestore();});});diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex 385a0362109..fd21be4c6c2 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -1,4 +1,4 @@-import { localFileService } from '@/services/electron/localFileService';+import { projectFileService } from '@/services/projectFile';import { type ChatStore } from '@/store/chat/store';import { type StoreSetter } from '@/store/types';import { type PortalArtifact } from '@/types/artifact';@@ -248,12 +248,12 @@ export class ChatPortalActionImpl {openLocalFiles,});+ // Edit buffers are keyed by tab identity, so each tab owns its buffer β drop+ // this tab's unsaved content (the close was confirmed) without touching the+ // buffer of any other tab that happens to share the same absolute path.let nextDirty = dirtyLocalFileContents;- const shouldClearDirty =- !target.deviceId &&- !nextFiles.some((file) => !file.deviceId && file.filePath === target.filePath);- if (shouldClearDirty && target.filePath in dirtyLocalFileContents) {- const { [target.filePath]: _, ...rest } = dirtyLocalFileContents;+ if (targetId in dirtyLocalFileContents) {+ const { [targetId]: _, ...rest } = dirtyLocalFileContents;nextDirty = rest;}@@ -523,28 +523,47 @@ export class ChatPortalActionImpl {);};- setLocalFileBuffer = (filePath: string, content: string | undefined): void => {+ setLocalFileBuffer = (tabId: string, content: string | undefined): void => {const { dirtyLocalFileContents } = this.#get();if (content === undefined) {- if (!(filePath in dirtyLocalFileContents)) return;+ if (!(tabId in dirtyLocalFileContents)) return;- const { [filePath]: _, ...rest } = dirtyLocalFileContents;+ const { [tabId]: _, ...rest } = dirtyLocalFileContents;this.#set({ dirtyLocalFileContents: rest }, false, 'setLocalFileBuffer/clear');return;}- if (dirtyLocalFileContents[filePath] === content) return;+ if (dirtyLocalFileContents[tabId] === content) return;this.#set(- { dirtyLocalFileContents: { ...dirtyLocalFileContents, [filePath]: content } },+ { dirtyLocalFileContents: { ...dirtyLocalFileContents, [tabId]: content } },false,'setLocalFileBuffer',);};- saveLocalFile = async (filePath: string): Promise<string | undefined> => {+ saveLocalFile = async ({+ deviceId,+ filePath,+ workingDirectory,+ }: OpenLocalFileParams): Promise<string | undefined> => {const { dirtyLocalFileContents } = this.#get();- const buffer = dirtyLocalFileContents[filePath];+ // Edit buffers are scoped by tab identity (device + working directory ++ // path), so the same absolute path opened on two devices/workspaces keeps+ // independent unsaved content.+ const tabId = createLocalFileTabId({ deviceId, filePath, workingDirectory });+ const buffer = dirtyLocalFileContents[tabId];if (buffer === undefined) return undefined;- await localFileService.writeFile({ content: buffer, path: filePath });+ // deviceId routes the write to the remote device over RPC; local desktop+ // (no deviceId) goes straight to Electron IPC. The chokepoint hides the split.+ const result = await projectFileService.writeProjectFile({+ content: buffer,+ deviceId,+ path: filePath,+ workingDirectory,+ });+ // The remote RPC / local IPC report fs failures (permission denied, etc.) as+ // `{ success: false }` rather than rejecting β treat that as a failed save so+ // the caller keeps the buffer dirty instead of marking it clean.+ if (!result.success) throw new Error(result.error || 'Failed to save file');return buffer;};diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 6e506ea299d..4480d025244 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -186,15 +186,17 @@ const currentLocalFile = (s: ChatStoreState): OpenLocalFileEntry | undefined =>const localFilePath = (s: ChatStoreState) => currentLocalFile(s)?.filePath;const localFileWorkingDirectory = (s: ChatStoreState) => currentLocalFile(s)?.workingDirectory;+// Edit buffers are keyed by tab identity (device + working directory + path),+// so callers pass the tab id rather than a bare file path.const localFileBuffer =- (filePath: string | undefined) =>+ (tabId: string | undefined) =>(s: ChatStoreState): string | undefined =>- filePath ? s.dirtyLocalFileContents[filePath] : undefined;+ tabId ? s.dirtyLocalFileContents[tabId] : undefined;const isLocalFileDirty =- (filePath: string | undefined) =>+ (tabId: string | undefined) =>(s: ChatStoreState): boolean =>- !!filePath && filePath in s.dirtyLocalFileContents;+ !!tabId && tabId in s.dirtyLocalFileContents;const dirtyLocalFileContents = (s: ChatStoreState): Record<string, string> =>s.dirtyLocalFileContents;