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(files): add basic file operations to the workspace Files tree (#20028)

Arvin Xu1e8c064e689d
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 5550ff0b1b2..5637587d1aa 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -461,6 +461,9 @@ export default class GatewayConnectionCtr extends ControllerModule {
getProjectFileIndex: (params) => this.localFileCtr.getProjectFileIndex(params),
listHeterogeneousAgentModels: (params) => this.heterogeneousAgentCtr.listModels(params),
searchProjectFiles: (params) => this.localFileCtr.searchProjectFiles(params),
+ // Remote "delete" goes to this machine's trash (`shell.trashItem`), same
+ // as the local Files tree, so it stays recoverable.
+ trashLocalFiles: (params) => this.localFileCtr.trashLocalFiles(params),
unenrollWorkspace: (params) => this.service.unenrollWorkspace(params),
// Skill-archive cache (`prepareSkillDirectory` RPC): reuse LocalFileCtr's
// deps so gateway-prepared skills share one cache with the renderer-IPC path.
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index b702f4b950c..684c8e729e4 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -18,6 +18,10 @@ import {
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
+ type CopyLocalFilesParams,
+ type CreateLocalDirectoryParams,
+ type CreateLocalEntryResult,
+ type CreateLocalFileParams,
type EditLocalFileParams,
type EditLocalFileResult,
type GlobFilesParams,
@@ -26,6 +30,7 @@ import {
type GrepContentResult,
type HashLocalFileParams,
type ListLocalFileParams,
+ type LocalCopyFilesResultItem,
type LocalFilePreviewResult,
type LocalFilePreviewUrlParams,
type LocalFilePreviewUrlResult,
@@ -62,6 +67,9 @@ import {
type WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
import {
+ copyLocalFiles,
+ createLocalDirectory,
+ createLocalFile,
editLocalFile,
expandTilde,
listLocalFiles,
@@ -616,6 +624,37 @@ export default class LocalFileCtr extends ControllerModule {
return writeLocalFile({ content, cwd, path: filePath });
}
+ /** Create a new file. Fails instead of overwriting when the path is taken. */
+ @IpcMethod()
+ async handleCreateFile({
+ path: filePath,
+ content,
+ cwd,
+ }: CreateLocalFileParams): Promise<CreateLocalEntryResult> {
+ logger.debug(`Creating file ${filePath}`);
+ return createLocalFile({ content, cwd, path: filePath });
+ }
+
+ /** Create a new folder. Fails instead of reusing it when the path is taken. */
+ @IpcMethod()
+ async handleCreateDirectory({
+ path: dirPath,
+ cwd,
+ }: CreateLocalDirectoryParams): Promise<CreateLocalEntryResult> {
+ logger.debug(`Creating directory ${dirPath}`);
+ return createLocalDirectory({ cwd, path: dirPath });
+ }
+
+ /**
+ * Copy files/folders, or duplicate them in place when an item has no
+ * `targetPath`. Never overwrites; each item reports its own outcome.
+ */
+ @IpcMethod()
+ async handleCopyFiles({ items, cwd }: CopyLocalFilesParams): Promise<LocalCopyFilesResultItem[]> {
+ logger.debug('Starting batch file copy:', { itemsCount: items?.length });
+ return copyLocalFiles({ cwd, items });
+ }
+
@IpcMethod()
async auditSafePaths({
paths,
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index ddada220170..09d83c35ea0 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -239,6 +239,11 @@ vi.mock('fflate', () => ({ unzipSync: vi.fn() }));
// ─── Mock Controllers ───
const mockLocalFileCtr = {
+ getSkillDirectoryDeps: vi.fn(() => ({})),
+ trashLocalFiles: vi.fn().mockResolvedValue({
+ items: [{ path: '/proj/a.txt', success: true }],
+ success: true,
+ }),
handleEditFile: vi.fn().mockResolvedValue({ success: true }),
handleGlobFiles: vi.fn().mockResolvedValue({ files: [] }),
handleGrepContent: vi.fn().mockResolvedValue({ matches: [] }),
@@ -924,6 +929,18 @@ describe('GatewayConnectionCtr', () => {
});
});
+ describe('device RPC host deps', () => {
+ it('hands the device-control dispatcher an OS-trash handler backed by LocalFileCtr', async () => {
+ const deps = (ctr as any).deviceControlDeps;
+
+ await expect(deps.trashLocalFiles({ paths: ['/proj/a.txt'] })).resolves.toEqual({
+ items: [{ path: '/proj/a.txt', success: true }],
+ success: true,
+ });
+ expect(mockLocalFileCtr.trashLocalFiles).toHaveBeenCalledWith({ paths: ['/proj/a.txt'] });
+ });
+ });
+
describe('message API routing', () => {
async function connectAndOpen() {
ctr.afterFirstFrame();
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 05de75731d4..bc848a1f120 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -43,6 +43,8 @@ vi.mock('electron', () => ({
vi.mock('node:fs/promises', () => ({
access: vi.fn(),
chmod: vi.fn(),
+ cp: vi.fn(),
+ lstat: vi.fn(),
mkdir: vi.fn(),
readFile: vi.fn(),
readdir: vi.fn(),
@@ -148,8 +150,9 @@ describe('LocalFileCtr', () => {
};
afterEach(() => {
- // clearAllMocks keeps implementations; drop the disk so it cannot leak.
- for (const fn of ['readFile', 'writeFile', 'rename'] as const) {
+ // clearAllMocks keeps implementations; drop the disk and the per-test
+ // existence probes so they cannot leak into later tests.
+ for (const fn of ['readFile', 'writeFile', 'rename', 'lstat', 'cp', 'mkdir'] as const) {
vi.mocked(mockFsPromises[fn]).mockReset();
}
});
@@ -649,6 +652,125 @@ describe('LocalFileCtr', () => {
});
});
+ describe('handleMoveFiles', () => {
+ it('should refuse to move onto an existing entry', async () => {
+ vi.mocked(mockFsPromises.access).mockResolvedValue(undefined);
+ vi.mocked(mockFsPromises.lstat).mockImplementation(async (target: string) => ({
+ dev: 1,
+ ino: target === '/p/a.txt' ? 10 : 20,
+ }));
+
+ const result = await localFileCtr.handleMoveFiles({
+ items: [{ newPath: '/p/sub/a.txt', oldPath: '/p/a.txt' }],
+ });
+
+ expect(result).toEqual([
+ {
+ error: 'An item already exists at the target path: /p/sub/a.txt.',
+ newPath: undefined,
+ sourcePath: '/p/a.txt',
+ success: false,
+ },
+ ]);
+ expect(mockFsPromises.rename).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('handleCreateFile', () => {
+ it('creates the file exclusively so an existing one is never overwritten', async () => {
+ vi.mocked(mockFsPromises.mkdir).mockResolvedValue(undefined);
+ vi.mocked(mockFsPromises.writeFile).mockResolvedValue(undefined);
+
+ const result = await localFileCtr.handleCreateFile({ path: '/p/new.ts' });
+
+ expect(result).toEqual({ path: '/p/new.ts', success: true });
+ expect(mockFsPromises.writeFile).toHaveBeenCalledWith('/p/new.ts', '', { flag: 'wx' });
+ });
+
+ it('reports an existing file as an error', async () => {
+ vi.mocked(mockFsPromises.mkdir).mockResolvedValue(undefined);
+ vi.mocked(mockFsPromises.writeFile).mockRejectedValue(
+ Object.assign(new Error('exists'), { code: 'EEXIST' }),
+ );
+
+ const result = await localFileCtr.handleCreateFile({ content: 'x', path: '/p/taken.ts' });
+
+ expect(result).toEqual({
+ error: 'An item already exists at /p/taken.ts.',
+ path: '/p/taken.ts',
+ success: false,
+ });
+ });
+ });
+
+ describe('handleCreateDirectory', () => {
+ it('creates the final folder non-recursively', async () => {
+ vi.mocked(mockFsPromises.mkdir).mockResolvedValue(undefined);
+
+ const result = await localFileCtr.handleCreateDirectory({ path: '/p/new-dir' });
+
+ expect(result).toEqual({ path: '/p/new-dir', success: true });
+ expect(mockFsPromises.mkdir).toHaveBeenCalledTimes(1);
+ expect(mockFsPromises.mkdir).toHaveBeenCalledWith('/p/new-dir', { recursive: false });
+ });
+
+ it('reports an existing folder as an error', async () => {
+ vi.mocked(mockFsPromises.mkdir).mockRejectedValueOnce(
+ Object.assign(new Error('exists'), { code: 'EEXIST' }),
+ );
+
+ const result = await localFileCtr.handleCreateDirectory({ path: '/p/src' });
+
+ expect(result).toEqual({
+ error: 'An item already exists at /p/src.',
+ path: '/p/src',
+ success: false,
+ });
+ });
+ });
+
+ describe('handleCopyFiles', () => {
+ const enoent = () => Object.assign(new Error('missing'), { code: 'ENOENT' });
+
+ it('duplicates in place under a Finder-style name when targetPath is omitted', async () => {
+ const existing = new Set(['/p/a.ts', '/p/a copy.ts']);
+ vi.mocked(mockFsPromises.lstat).mockImplementation(async (target: string) => {
+ if (!existing.has(target)) throw enoent();
+ return { isDirectory: () => false };
+ });
+ vi.mocked(mockFsPromises.cp).mockResolvedValue(undefined);
+
+ const result = await localFileCtr.handleCopyFiles({ items: [{ sourcePath: '/p/a.ts' }] });
+
+ expect(result).toEqual([
+ { sourcePath: '/p/a.ts', success: true, targetPath: '/p/a copy 2.ts' },
+ ]);
+ expect(mockFsPromises.cp).toHaveBeenCalledWith('/p/a.ts', '/p/a copy 2.ts', {
+ errorOnExist: true,
+ force: false,
+ recursive: true,
+ verbatimSymlinks: true,
+ });
+ });
+
+ it('refuses an explicit target that already exists without copying', async () => {
+ vi.mocked(mockFsPromises.lstat).mockResolvedValue({ isDirectory: () => true });
+
+ const result = await localFileCtr.handleCopyFiles({
+ items: [{ sourcePath: '/p/src', targetPath: '/p/dst' }],
+ });
+
+ expect(result).toEqual([
+ {
+ error: 'An item already exists at the target path: /p/dst.',
+ sourcePath: '/p/src',
+ success: false,
+ },
+ ]);
+ expect(mockFsPromises.cp).not.toHaveBeenCalled();
+ });
+ });
+
describe('auditSafePaths', () => {
it('should treat real temporary paths as safe', async () => {
vi.mocked(mockFsPromises.access).mockResolvedValue(undefined);
@@ -850,6 +972,22 @@ describe('LocalFileCtr', () => {
expect(result.error).toContain('File or directory not found');
});
+ it('should refuse to overwrite an existing sibling instead of renaming over it', async () => {
+ vi.mocked(mockFsPromises.lstat).mockImplementation(async (target: string) => ({
+ dev: 1,
+ ino: target === '/test/old.txt' ? 10 : 20,
+ }));
+
+ const result = await localFileCtr.handleRenameFile({
+ path: '/test/old.txt',
+ newName: 'taken.txt',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(mockFsPromises.rename).not.toHaveBeenCalled();
+ });
+
it('should handle file already exists error', async () => {
const error: any = new Error('File exists');
error.code = 'EEXIST';
diff --git a/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts
new file mode 100644
index 00000000000..274e08c16fd
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts
@@ -0,0 +1,119 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceRouter } from '../device';
+
+const mocks = vi.hoisted(() => ({
+ copyProjectFiles: vi.fn(),
+ createProjectDirectory: vi.fn(),
+ createProjectFile: vi.fn(),
+ findByDeviceId: vi.fn(),
+ moveProjectFiles: vi.fn(),
+ renameProjectFile: vi.fn(),
+ trashProjectFiles: vi.fn(),
+ writeProjectFile: vi.fn(),
+}));
+
+// The OSS role guard is a no-op stub; stand in for the cloud one so the test
+// can see which routes are write-gated. Like the real guard it only bites when
+// the request carries a workspace role below `member`.
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ const { trpc } = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ ...actual,
+ requireWorkspaceRoleWhenScoped: () =>
+ trpc.middleware(async (opts: any) => {
+ if (opts.ctx.workspaceRole === 'viewer') throw new TRPCError({ code: 'FORBIDDEN' });
+ return opts.next();
+ }),
+ };
+});
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: class {
+ findByDeviceId = mocks.findByDeviceId;
+ },
+}));
+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ deviceGateway: {
+ copyProjectFiles: mocks.copyProjectFiles,
+ createProjectDirectory: mocks.createProjectDirectory,
+ createProjectFile: mocks.createProjectFile,
+ moveProjectFiles: mocks.moveProjectFiles,
+ renameProjectFile: mocks.renameProjectFile,
+ trashProjectFiles: mocks.trashProjectFiles,
+ writeProjectFile: mocks.writeProjectFile,
+ },
+}));
+
+const caller = () => deviceRouter.createCaller({ userId: 'user-1' } as never);
+
+const base = { deviceId: 'dev-1', workingDirectory: '/Users/me/proj' };
+
+const routes = [
+ ['createProjectFile', { ...base, path: '/Users/me/proj/new.ts' }],
+ ['createProjectDirectory', { ...base, path: '/Users/me/proj/new-dir' }],
+ ['copyProjectFiles', { ...base, items: [{ sourcePath: '/Users/me/proj/a.ts' }] }],
+ ['trashProjectFiles', { ...base, paths: ['/Users/me/proj/a.ts'] }],
+] as const;
+
+describe('device project file mutations', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/Users/me/proj' }] });
+ for (const [route] of routes) mocks[route].mockResolvedValue({ success: true });
+ });
+
+ it.each(routes)(
+ '%s forwards to the gateway inside an approved workspace',
+ async (route, input) => {
+ await expect((caller()[route] as any)(input)).resolves.toEqual({ success: true });
+
+ const { workingDirectory, deviceId, ...rest } = input;
+ expect(mocks[route]).toHaveBeenCalledWith({
+ ...rest,
+ deviceId,
+ userId: 'user-1',
+ workingDirectory,
+ workspaceId: undefined,
+ });
+ },
+ );
+
+ it.each(routes)('%s rejects a workspace root the device never approved', async (route, input) => {
+ await expect(
+ (caller()[route] as any)({ ...input, workingDirectory: '/' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks[route]).not.toHaveBeenCalled();
+ });
+
+ it('rejects an empty trash batch before reaching the device', async () => {
+ await expect(caller().trashProjectFiles({ ...base, paths: [] })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(mocks.trashProjectFiles).not.toHaveBeenCalled();
+ });
+
+ const writeRoutes = [
+ ...routes,
+ [
+ 'moveProjectFiles',
+ { ...base, items: [{ newPath: '/Users/me/proj/b.ts', oldPath: '/Users/me/proj/a.ts' }] },
+ ],
+ ['renameProjectFile', { ...base, newName: 'b.ts', path: '/Users/me/proj/a.ts' }],
+ ['writeProjectFile', { ...base, content: 'x', path: '/Users/me/proj/a.ts' }],
+ ] as const;
+
+ it.each(writeRoutes)('%s refuses a read-only workspace viewer', async (route, input) => {
+ const viewer = deviceRouter.createCaller({
+ userId: 'user-1',
+ workspaceRole: 'viewer',
+ } as never);
+ await expect((viewer[route] as any)(input)).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks[route]).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 6574ba1a5c4..94f0703eeef 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -16,6 +16,7 @@ import { z } from 'zod';
import {
requireWorkspaceRole,
+ requireWorkspaceRoleWhenScoped,
type WorkspaceRole,
wsCompatProcedure,
wsProcedure,
@@ -186,6 +187,15 @@ const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(asy
return opts.next();
});
+/**
+ * `workspaceFileProcedure` for routes that change files on the device. In a
+ * shared workspace a read-only viewer may browse the tree but not alter it, so
+ * writes also need at least the `member` role; personal mode stays open.
+ */
+const workspaceFileWriteProcedure = workspaceFileProcedure.use(
+ requireWorkspaceRoleWhenScoped('member'),
+);
+
export const deviceRouter = router({
/**
* Probe whether a specific agent platform (openclaw / hermes) is available
@@ -945,7 +955,7 @@ 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: workspaceFileProcedure
+ moveProjectFiles: workspaceFileWriteProcedure
.input(
z.object({
items: z.array(z.object({ newPath: z.string(), oldPath: z.string() })),
@@ -965,7 +975,7 @@ export const deviceRouter = router({
* Rename a single file/folder in a directory on a remote device, via the
* device's `renameLocalFile` RPC.
*/
- renameProjectFile: workspaceFileProcedure
+ renameProjectFile: workspaceFileWriteProcedure
.input(
z.object({
newName: z.string(),
@@ -987,7 +997,7 @@ export const deviceRouter = router({
* 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: workspaceFileProcedure
+ writeProjectFile: workspaceFileWriteProcedure
.input(
z.object({
content: z.string(),
@@ -1005,6 +1015,82 @@ export const deviceRouter = router({
});
}),
+ /**
+ * Create a new file on a remote device, via the device's `createLocalFile`
+ * RPC. Fails instead of overwriting when the path is taken.
+ */
+ createProjectFile: workspaceFileWriteProcedure
+ .input(
+ z.object({
+ content: z.string().optional(),
+ path: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.createProjectFile({
+ content: input.content,
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ workingDirectory: input.workingDirectory,
+ });
+ }),
+
+ /**
+ * Create a new folder on a remote device, via the device's
+ * `createLocalDirectory` RPC. Fails when the path is taken.
+ */
+ createProjectDirectory: workspaceFileWriteProcedure
+ .input(z.object({ path: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.createProjectDirectory({
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ workingDirectory: input.workingDirectory,
+ });
+ }),
+
+ /**
+ * Copy files/folders on a remote device, via the device's `copyLocalFiles`
+ * RPC. An item without `targetPath` is duplicated in place.
+ */
+ copyProjectFiles: workspaceFileWriteProcedure
+ .input(
+ z.object({
+ items: z
+ .array(z.object({ sourcePath: z.string(), targetPath: z.string().optional() }))
+ .min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.copyProjectFiles({
+ deviceId: input.deviceId,
+ items: input.items,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ workingDirectory: input.workingDirectory,
+ });
+ }),
+
+ /**
+ * Move files/folders to a remote device's trash, via the device's
+ * `trashLocalFiles` RPC. Devices without a trash reject rather than delete.
+ */
+ trashProjectFiles: workspaceFileWriteProcedure
+ .input(z.object({ paths: z.array(z.string()).min(1) }))
+ .mutation(async ({ ctx, input }) => {
+ return deviceGateway.trashProjectFiles({
+ deviceId: input.deviceId,
+ paths: input.paths,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ 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-entered
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index 35bb036b0c3..5e922a9a752 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -1033,7 +1033,10 @@ describe('DeviceGateway', () => {
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' } },
+ {
+ method: 'writeLocalFile',
+ params: { content: 'next', path: '/proj/src/App.tsx', workspaceRoot: '/proj' },
+ },
);
});
@@ -1104,6 +1107,303 @@ describe('DeviceGateway', () => {
});
});
+ describe('createProjectFile', () => {
+ it('invokes createLocalFile when the path is inside the workspace', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ data: { path: '/proj/new.ts', success: true },
+ success: true,
+ });
+
+ const proxy = new DeviceGateway();
+ const result = await proxy.createProjectFile({
+ deviceId: 'dev-1',
+ path: '/proj/new.ts',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ });
+
+ expect(result).toEqual({ path: '/proj/new.ts', success: true });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
+ {
+ method: 'createLocalFile',
+ params: { content: undefined, path: '/proj/new.ts', workspaceRoot: '/proj' },
+ },
+ );
+ });
+
+ it('throws without invoking the rpc when the path escapes the workspace', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.createProjectFile({
+ deviceId: 'dev-1',
+ path: '/proj/../evil.sh',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a device that has not shipped the rpc yet as an error', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ error: 'Unknown device RPC method: createLocalFile',
+ success: false,
+ });
+
+ const proxy = new DeviceGateway();
+ await expect(
+ proxy.createProjectFile({
+ deviceId: 'dev-1',
+ path: '/proj/new.ts',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow('Unknown device RPC method: createLocalFile');
+ });
+ });
+
+ describe('createProjectDirectory', () => {
+ it('invokes createLocalDirectory when the path is inside the workspace', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ data: { path: '/proj/src/new', success: true },
+ success: true,
+ });
+
+ const proxy = new DeviceGateway();
+ await expect(
+ proxy.createProjectDirectory({
+ deviceId: 'dev-1',
+ path: '/proj/src/new',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).resolves.toEqual({ path: '/proj/src/new', success: true });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
+ {
+ method: 'createLocalDirectory',
+ params: { path: '/proj/src/new', workspaceRoot: '/proj' },
+ },
+ );
+ });
+
+ it('throws without invoking the rpc when the path escapes the workspace', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.createProjectDirectory({
+ deviceId: 'dev-1',
+ path: '/tmp/outside',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('copyProjectFiles', () => {
+ it('invokes copyLocalFiles when source and target stay inside the workspace', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ data: [{ sourcePath: '/proj/a.ts', success: true, targetPath: '/proj/a copy.ts' }],
+ success: true,
+ });
+
+ const proxy = new DeviceGateway();
+ const items = [
+ { sourcePath: '/proj/a.ts' },
+ { sourcePath: '/proj/b', targetPath: '/proj/c' },
+ ];
+ await proxy.copyProjectFiles({
+ deviceId: 'dev-1',
+ items,
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ });
+
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },
+ { method: 'copyLocalFiles', params: { items, workspaceRoot: '/proj' } },
+ );
+ });
+
+ it('throws when a source lies outside the workspace', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.copyProjectFiles({
+ deviceId: 'dev-1',
+ items: [{ sourcePath: '/Users/me/.ssh/id_rsa', targetPath: '/proj/key' }],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('throws when a target lies outside the workspace', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.copyProjectFiles({
+ deviceId: 'dev-1',
+ items: [{ sourcePath: '/proj/secrets.env', targetPath: '/tmp/exfil.env' }],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('refuses to duplicate the workspace root (the copy would land outside it)', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.copyProjectFiles({
+ deviceId: 'dev-1',
+ items: [{ sourcePath: '/proj' }],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/workspace root/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('trashProjectFiles', () => {
+ it('invokes trashLocalFiles when every path is inside the workspace', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ data: { items: [{ path: '/proj/a.ts', success: true }], success: true },
+ success: true,
+ });
+
+ const proxy = new DeviceGateway();
+ await expect(
+ proxy.trashProjectFiles({
+ deviceId: 'dev-1',
+ paths: ['/proj/a.ts'],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).resolves.toEqual({ items: [{ path: '/proj/a.ts', success: true }], success: true });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
+ { method: 'trashLocalFiles', params: { paths: ['/proj/a.ts'], workspaceRoot: '/proj' } },
+ );
+ });
+
+ it('throws when any path escapes the workspace', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.trashProjectFiles({
+ deviceId: 'dev-1',
+ paths: ['/proj/a.ts', '/Users/me/Documents'],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it.each(['/proj', '/proj/', '/proj/src/..'])(
+ 'refuses to trash the workspace root itself (%s)',
+ async (rootPath) => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.trashProjectFiles({
+ deviceId: 'dev-1',
+ paths: [rootPath],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/workspace root/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ },
+ );
+
+ it('surfaces a device without a trash as an error, not a delete', async () => {
+ configure();
+ mockClient.invokeRpc.mockResolvedValue({
+ error: 'This device does not support moving files to the trash',
+ success: false,
+ });
+
+ const proxy = new DeviceGateway();
+ await expect(
+ proxy.trashProjectFiles({
+ deviceId: 'dev-1',
+ paths: ['/proj/a.ts'],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow('This device does not support moving files to the trash');
+ expect(mockClient.invokeRpc).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('workspace root guard on rename / move', () => {
+ it('refuses to rename the workspace root itself', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.renameProjectFile({
+ deviceId: 'dev-1',
+ newName: 'renamed',
+ path: '/proj',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/workspace root/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('refuses to move the workspace root itself', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.moveProjectFiles({
+ deviceId: 'dev-1',
+ items: [{ newPath: '/proj/inner', oldPath: '/proj' }],
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/workspace root/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('contains Windows workspace roots with Windows semantics', async () => {
+ configure();
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.trashProjectFiles({
+ deviceId: 'dev-1',
+ paths: ['C:\\proj\\'],
+ userId: 'user-1',
+ workingDirectory: 'C:\\proj',
+ }),
+ ).rejects.toThrow(/workspace root/);
+ });
+ });
+
describe('moveProjectFiles', () => {
it('throws when any item moves out of the workspace', async () => {
configure();
@@ -1145,7 +1445,10 @@ describe('DeviceGateway', () => {
{ deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
{
method: 'moveLocalFiles',
- params: { items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }] },
+ params: {
+ items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],
+ workspaceRoot: '/proj',
+ },
},
);
});
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index cbe7c8bf4c4..eee3fdad5fe 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -20,6 +20,9 @@ import type {
DeviceAppUpdateState,
DeviceAppUpdateStateResult,
DeviceCopyAssetForPublishResult,
+ DeviceCopyProjectFileItem,
+ DeviceCopyProjectFileResultItem,
+ DeviceCreateProjectEntryResult,
DeviceDirectoryBrowseResult,
DeviceExternalAssetForPublishResult,
DeviceGitAddWorktreeResult,
@@ -53,6 +56,7 @@ import type {
DeviceProjectFileIndexResult,
DeviceProjectFileSearchResult,
DeviceRenameProjectFileResult,
+ DeviceTrashProjectFilesResult,
DeviceUnavailableErrorData,
DeviceWriteProjectFileResult,
HeterogeneousAgentModelCatalog,
@@ -102,6 +106,27 @@ const assertPathsWithinWorkspace = (
}
};
+/**
+ * Refuse to trash / rename / move / duplicate the workspace root itself. It
+ * passes the containment check (a root is "within" itself), but removing or
+ * renaming it pulls the whole Files tree out from under the UI, and a duplicate
+ * of the root would land in its parent — outside the workspace.
+ */
+const assertNotWorkspaceRoot = (
+ workspaceRoot: string,
+ candidates: Array<string | undefined>,
+): void => {
+ for (const candidate of candidates) {
+ if (
+ candidate &&
+ isAbsolute(candidate) &&
+ relative(resolve(workspaceRoot), resolve(candidate)) === ''
+ ) {
+ throw new Error(`This operation is not allowed on the workspace root: ${candidate}`);
+ }
+ }
+};
+
export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };
interface AppUpdateRpcParams {
@@ -1493,10 +1518,14 @@ export class DeviceGateway {
workingDirectory,
items.flatMap((item) => [item.oldPath, item.newPath]),
);
+ assertNotWorkspaceRoot(
+ workingDirectory,
+ items.map((item) => item.oldPath),
+ );
const result = await client.invokeRpc<DeviceMoveProjectFileResultItem[]>(
{ deviceId, timeout, userId, workspaceId },
- { method: 'moveLocalFiles', params: { items } },
+ { method: 'moveLocalFiles', params: { items, workspaceRoot: workingDirectory } },
);
if (!result.success || !result.data) {
@@ -1536,10 +1565,11 @@ export class DeviceGateway {
// 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]);
+ assertNotWorkspaceRoot(workingDirectory, [path]);
const result = await client.invokeRpc<DeviceRenameProjectFileResult>(
{ deviceId, timeout, userId, workspaceId },
- { method: 'renameLocalFile', params: { newName, path } },
+ { method: 'renameLocalFile', params: { newName, path, workspaceRoot: workingDirectory } },
);
if (!result.success || !result.data) {
@@ -1580,7 +1610,7 @@ export class DeviceGateway {
const result = await client.invokeRpc<DeviceWriteProjectFileResult>(
{ deviceId, timeout, userId, workspaceId },
- { method: 'writeLocalFile', params: { content, path } },
+ { method: 'writeLocalFile', params: { content, path, workspaceRoot: workingDirectory } },
);
if (!result.success || !result.data) {
@@ -1591,6 +1621,153 @@ export class DeviceGateway {
return result.data;
}
+ /**
+ * Create a new, empty (or seeded) file on a remote device via the device's
+ * `createLocalFile` RPC. Never overwrites: an existing entry comes back as
+ * `{ success: false, error }`. A transport failure throws.
+ */
+ async createProjectFile(params: {
+ content?: string;
+ deviceId: string;
+ path: string;
+ timeout?: number;
+ userId: string;
+ workingDirectory: string;
+ workspaceId?: string;
+ }): Promise<DeviceCreateProjectEntryResult> {
+ const {
+ userId,
+ deviceId,
+ path,
+ content,
+ workingDirectory,
+ timeout = 30_000,
+ workspaceId,
+ } = params;
+ const client = this.getClient();
+ if (!client) throw new Error('Device gateway not configured');
+
+ assertPathsWithinWorkspace(workingDirectory, [path]);
+
+ const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'createLocalFile', params: { content, path, workspaceRoot: workingDirectory } },
+ );
+
+ if (!result.success || !result.data) {
+ log('createProjectFile: failed for deviceId=%s — %s', deviceId, result.error);
+ throw new Error(result.error || 'Create file failed');
+ }
+
+ return result.data;
+ }
+
+ /**
+ * Create a new folder on a remote device via the device's
+ * `createLocalDirectory` RPC. An existing entry fails instead of being reused.
+ */
+ async createProjectDirectory(params: {
+ deviceId: string;
+ path: string;
+ timeout?: number;
+ userId: string;
+ workingDirectory: string;
+ workspaceId?: string;
+ }): Promise<DeviceCreateProjectEntryResult> {
+ const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) throw new Error('Device gateway not configured');
+
+ assertPathsWithinWorkspace(workingDirectory, [path]);
+
+ const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'createLocalDirectory', params: { path, workspaceRoot: workingDirectory } },
+ );
+
+ if (!result.success || !result.data) {
+ log('createProjectDirectory: failed for deviceId=%s — %s', deviceId, result.error);
+ throw new Error(result.error || 'Create folder failed');
+ }
+
+ return result.data;
+ }
+
+ /**
+ * Copy (or, without `targetPath`, duplicate in place) files/folders on a
+ * remote device via the device's `copyLocalFiles` RPC. Both ends of every item
+ * must stay inside the workspace. A duplicate lands next to its source, so
+ * containing the source (and refusing the root itself) contains the copy.
+ */
+ async copyProjectFiles(params: {
+ deviceId: string;
+ items: DeviceCopyProjectFileItem[];
+ timeout?: number;
+ userId: string;
+ workingDirectory: string;
+ workspaceId?: string;
+ }): Promise<DeviceCopyProjectFileResultItem[]> {
+ const { userId, deviceId, items, workingDirectory, timeout = 60_000, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) throw new Error('Device gateway not configured');
+
+ assertPathsWithinWorkspace(
+ workingDirectory,
+ items.flatMap((item) =>
+ item.targetPath === undefined ? [item.sourcePath] : [item.sourcePath, item.targetPath],
+ ),
+ );
+ assertNotWorkspaceRoot(
+ workingDirectory,
+ items.map((item) => item.sourcePath),
+ );
+
+ const result = await client.invokeRpc<DeviceCopyProjectFileResultItem[]>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'copyLocalFiles', params: { items, workspaceRoot: workingDirectory } },
+ );
+
+ if (!result.success || !result.data) {
+ log('copyProjectFiles: failed for deviceId=%s — %s', deviceId, result.error);
+ throw new Error(result.error || 'Copy failed');
+ }
+
+ return result.data;
+ }
+
+ /**
+ * Move files/folders to the remote device's trash via its `trashLocalFiles`
+ * RPC. A device without a recoverable trash (the CLI daemon) rejects the RPC,
+ * which surfaces here as a thrown error — never as a permanent delete.
+ */
+ async trashProjectFiles(params: {
+ deviceId: string;
+ paths: string[];
+ timeout?: number;
+ userId: string;
+ workingDirectory: string;
+ workspaceId?: string;
+ }): Promise<DeviceTrashProjectFilesResult> {
+ const { userId, deviceId, paths, workingDirectory, timeout = 30_000, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) throw new Error('Device gateway not configured');
+
+ assertPathsWithinWorkspace(workingDirectory, paths);
+ assertNotWorkspaceRoot(workingDirectory, paths);
+
+ const result = await client.invokeRpc<DeviceTrashProjectFilesResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'trashLocalFiles', params: { paths, workspaceRoot: workingDirectory } },
+ );
+
+ if (!result.success || !result.data) {
+ log('trashProjectFiles: failed for deviceId=%s — %s', deviceId, result.error);
+ throw new Error(result.error || 'Move to trash 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 client
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 58e2d86a225..21e71924824 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2476,10 +2476,45 @@
"workingPanel.documents.saved": "All changes saved",
"workingPanel.documents.title": "Document",
"workingPanel.documents.unsaved": "Unsaved changes",
+ "workingPanel.files.actions.copy": "Copy",
+ "workingPanel.files.actions.cut": "Cut",
+ "workingPanel.files.actions.duplicate": "Duplicate",
+ "workingPanel.files.actions.more": "More",
+ "workingPanel.files.actions.moveToTrash": "Move to {{trash}}",
+ "workingPanel.files.actions.newFile": "New File…",
+ "workingPanel.files.actions.newFolder": "New Folder…",
+ "workingPanel.files.actions.openInSystem": "Open in System",
+ "workingPanel.files.actions.openInTerminal": "Open in Terminal",
+ "workingPanel.files.actions.paste": "Paste",
+ "workingPanel.files.actions.refresh": "Refresh",
+ "workingPanel.files.actions.rename": "Rename…",
"workingPanel.files.collapseAll": "Collapse Folders in Explorer",
"workingPanel.files.copyAbsolutePath": "Copy Path",
"workingPanel.files.copyRelativePath": "Copy Relative Path",
+ "workingPanel.files.delete.confirm": "Move to {{trash}}",
+ "workingPanel.files.delete.confirmTitle": "Move \"{{name}}\" to {{trash}}?",
+ "workingPanel.files.delete.confirmTitleMultiple": "Move {{count}} items to {{trash}}?",
+ "workingPanel.files.delete.dirtyWarning": "Includes uncommitted Git changes.",
+ "workingPanel.files.delete.fileDesc": "You can restore it from the {{trash}}.",
+ "workingPanel.files.delete.folderDesc": "\"{{name}}\" and everything in it will be moved to the {{trash}}. You can restore them from the {{trash}}.",
+ "workingPanel.files.delete.multipleDesc": "You can restore them from the {{trash}}.",
"workingPanel.files.empty": "No files in this workspace",
+ "workingPanel.files.feedback.createFailed": "Couldn't create \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.deleteFailed": "Couldn't delete \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.deviceOffline": "The device is offline. Try again after it reconnects.",
+ "workingPanel.files.feedback.duplicateFailed": "Couldn't duplicate \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.moveConflict": "\"{{name}}\" already exists in the destination folder",
+ "workingPanel.files.feedback.moveFailed": "Couldn't move \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.openFailed": "Couldn't open \"{{name}}\"",
+ "workingPanel.files.feedback.pasteFailed": "Couldn't paste \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.pasteIntoItself": "Can't paste \"{{name}}\" into itself",
+ "workingPanel.files.feedback.refreshFailed": "Couldn't refresh files",
+ "workingPanel.files.feedback.renameFailed": "Couldn't rename \"{{name}}\": {{reason}}",
+ "workingPanel.files.feedback.terminalFailed": "Couldn't open the terminal",
+ "workingPanel.files.feedback.trashUnsupported": "This device has no {{trash}} to move files to, so nothing was deleted. Delete it on the device itself.",
+ "workingPanel.files.feedback.trashed": "Moved \"{{name}}\" to {{trash}}",
+ "workingPanel.files.feedback.trashedCount": "Moved {{count}} items to {{trash}}",
+ "workingPanel.files.feedback.unsupportedOnDevice": "This device's app is out of date. Update it and try again.",
"workingPanel.files.filters.changedOnly": "Show Git Changes Only",
"workingPanel.files.filters.hideIgnored": "Exclude Ignored Files",
"workingPanel.files.filters.title": "Filter Files",
@@ -2490,7 +2525,16 @@
"workingPanel.files.showInReview": "Show in Review",
"workingPanel.files.showInSystem": "Reveal in Folder",
"workingPanel.files.title": "Files",
+ "workingPanel.files.trashName.linux": "Trash",
+ "workingPanel.files.trashName.mac": "Trash",
+ "workingPanel.files.trashName.windows": "Recycle Bin",
"workingPanel.files.truncatedNotice": "Some expanded folders are too large to list fully — only the first entries are shown",
+ "workingPanel.files.validation.empty": "A file or folder name must be provided",
+ "workingPanel.files.validation.exists": "\"{{name}}\" already exists here. Choose a different name.",
+ "workingPanel.files.validation.invalidChars": "Names can't contain < > : \" / \\ | ? * or control characters",
+ "workingPanel.files.validation.reserved": "\".\" and \"..\" can't be used as names",
+ "workingPanel.files.validation.tooLong": "Name is too long (255 bytes max)",
+ "workingPanel.files.validation.whitespace": "Names can't start or end with a space",
"workingPanel.files.views.changes": "Git Changes",
"workingPanel.files.views.project": "Project",
"workingPanel.files.views.title": "File View",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 63a99b61556..314e8a0d498 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2476,10 +2476,45 @@
"workingPanel.documents.saved": "已保存全部变更",
"workingPanel.documents.title": "文档",
"workingPanel.documents.unsaved": "有未保存的变更",
+ "workingPanel.files.actions.copy": "复制",
+ "workingPanel.files.actions.cut": "剪切",
+ "workingPanel.files.actions.duplicate": "创建副本",
+ "workingPanel.files.actions.more": "更多",
+ "workingPanel.files.actions.moveToTrash": "移到{{trash}}",
+ "workingPanel.files.actions.newFile": "新建文件…",
+ "workingPanel.files.actions.newFolder": "新建文件夹…",
+ "workingPanel.files.actions.openInSystem": "在系统中打开",
+ "workingPanel.files.actions.openInTerminal": "在终端中打开",
+ "workingPanel.files.actions.paste": "粘贴",
+ "workingPanel.files.actions.refresh": "刷新",
+ "workingPanel.files.actions.rename": "重命名…",
"workingPanel.files.collapseAll": "折叠资源管理器中的文件夹",
"workingPanel.files.copyAbsolutePath": "复制路径",
"workingPanel.files.copyRelativePath": "复制相对路径",
+ "workingPanel.files.delete.confirm": "移到{{trash}}",
+ "workingPanel.files.delete.confirmTitle": "将「{{name}}」移到{{trash}}?",
+ "workingPanel.files.delete.confirmTitleMultiple": "将 {{count}} 个项目移到{{trash}}?",
+ "workingPanel.files.delete.dirtyWarning": "其中包含未提交的 Git 改动。",
+ "workingPanel.files.delete.fileDesc": "可以从{{trash}}中恢复。",
+ "workingPanel.files.delete.folderDesc": "「{{name}}」及其中的全部内容都会被移到{{trash}},可从{{trash}}中恢复。",
+ "workingPanel.files.delete.multipleDesc": "可以从{{trash}}中恢复。",
"workingPanel.files.empty": "此工作区中没有文件",
+ "workingPanel.files.feedback.createFailed": "无法创建「{{name}}」:{{reason}}",
+ "workingPanel.files.feedback.deleteFailed": "无法删除「{{name}}」:{{reason}}",
+ "workingPanel.files.feedback.deviceOffline": "设备已离线,重新连接后再试",
+ "workingPanel.files.feedback.duplicateFailed": "无法创建「{{name}}」的副本:{{reason}}",
+ "workingPanel.files.feedback.moveConflict": "目标文件夹中已存在「{{name}}」",
+ "workingPanel.files.feedback.moveFailed": "无法移动「{{name}}」:{{reason}}",
+ "workingPanel.files.feedback.openFailed": "无法打开「{{name}}」",
+ "workingPanel.files.feedback.pasteFailed": "无法粘贴「{{name}}」:{{reason}}",
+ "workingPanel.files.feedback.pasteIntoItself": "不能把「{{name}}」粘贴到它自己里面",
+ "workingPanel.files.feedback.refreshFailed": "刷新文件失败",
+ "workingPanel.files.feedback.renameFailed": "无法重命名「{{name}}」:{{reason}}",
+ "workingPanel.files.feedback.terminalFailed": "无法打开终端",
+ "workingPanel.files.feedback.trashUnsupported": "该设备没有可用的回收站,未删除任何文件。请在设备上直接删除",
+ "workingPanel.files.feedback.trashed": "已将「{{name}}」移到{{trash}}",
+ "workingPanel.files.feedback.trashedCount": "已将 {{count}} 个项目移到{{trash}}",
+ "workingPanel.files.feedback.unsupportedOnDevice": "该设备上的应用版本过旧,请更新后重试",
"workingPanel.files.filters.changedOnly": "仅显示 Git 变更",
"workingPanel.files.filters.hideIgnored": "不包含已忽略文件",
"workingPanel.files.filters.title": "筛选文件",
@@ -2490,7 +2525,16 @@
"workingPanel.files.showInReview": "在审查中查看",
"workingPanel.files.showInSystem": "在文件夹中显示",
"workingPanel.files.title": "文件",
+ "workingPanel.files.trashName.linux": "回收站",
+ "workingPanel.files.trashName.mac": "废纸篓",
+ "workingPanel.files.trashName.windows": "回收站",
"workingPanel.files.truncatedNotice": "部分展开的文件夹内容过多,仅显示前部分条目",
+ "workingPanel.files.validation.empty": "请输入文件或文件夹名称",
+ "workingPanel.files.validation.exists": "此位置已存在「{{name}}」,请换一个名称",
+ "workingPanel.files.validation.invalidChars": "名称不能包含 < > : \" / \\ | ? * 或控制字符",
+ "workingPanel.files.validation.reserved": "名称不能是「.」或「..」",
+ "workingPanel.files.validation.tooLong": "名称过长(最多 255 字节)",
+ "workingPanel.files.validation.whitespace": "名称首尾不能有空格",
"workingPanel.files.views.changes": "Git 变更",
"workingPanel.files.views.project": "项目",
"workingPanel.files.views.title": "文件视图",
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index d961b4d452f..bb9a23b9406 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -1,11 +1,17 @@
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readdir, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
-import { APP_UPDATE_UNSUPPORTED_MESSAGE, executeDeviceRpc } from '../dispatch';
+import {
+ APP_UPDATE_UNSUPPORTED_MESSAGE,
+ DEVICE_RPC_METHODS,
+ executeDeviceRpc,
+ TRASH_UNSUPPORTED_MESSAGE,
+} from '../dispatch';
import type { DeviceControlDeps } from '../types';
+import { WORKSPACE_ESCAPE_MESSAGE } from '../workspaceGuard';
let root: string;
let deviceHome: string;
@@ -303,6 +309,274 @@ describe('executeDeviceRpc', () => {
expect(await readFile(filePath, 'utf8')).toBe('remote edit');
});
+ it('refuses to overwrite an existing target when routing moveLocalFiles', async () => {
+ const oldPath = path.join(root, 'move-clash-src.txt');
+ const newPath = path.join(root, 'move-clash-dst.txt');
+ await writeFile(oldPath, 'incoming');
+ await writeFile(newPath, 'keep me');
+
+ const [result] = (await executeDeviceRpc(
+ 'moveLocalFiles',
+ { items: [{ newPath, oldPath }] },
+ makeDeps(),
+ )) as { error?: string; success: boolean }[];
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(await readFile(newPath, 'utf8')).toBe('keep me');
+ });
+
+ it('refuses to overwrite an existing sibling when routing renameLocalFile', async () => {
+ const filePath = path.join(root, 'rename-clash-src.txt');
+ await writeFile(filePath, 'incoming');
+ await writeFile(path.join(root, 'rename-clash-dst.txt'), 'keep me');
+
+ const result = (await executeDeviceRpc(
+ 'renameLocalFile',
+ { newName: 'rename-clash-dst.txt', path: filePath },
+ makeDeps(),
+ )) as { error?: string; success: boolean };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(await readFile(path.join(root, 'rename-clash-dst.txt'), 'utf8')).toBe('keep me');
+ });
+
+ describe('file tree mutations', () => {
+ it('exposes create / mkdir / copy / trash as device RPC methods', () => {
+ expect(DEVICE_RPC_METHODS).toEqual(
+ expect.arrayContaining([
+ 'createLocalFile',
+ 'createLocalDirectory',
+ 'copyLocalFiles',
+ 'trashLocalFiles',
+ ]),
+ );
+ });
+
+ it('routes createLocalFile and refuses an existing file', async () => {
+ const filePath = path.join(root, 'created.ts');
+
+ await expect(
+ executeDeviceRpc('createLocalFile', { path: filePath, workspaceRoot: root }, makeDeps()),
+ ).resolves.toEqual({ path: filePath, success: true });
+ await expect(
+ executeDeviceRpc(
+ 'createLocalFile',
+ { content: 'x', path: filePath, workspaceRoot: root },
+ makeDeps(),
+ ),
+ ).resolves.toMatchObject({
+ error: expect.stringContaining('already exists'),
+ success: false,
+ });
+ expect(await readFile(filePath, 'utf8')).toBe('');
+ });
+
+ it('routes createLocalDirectory and refuses an existing folder', async () => {
+ const dirPath = path.join(root, 'created-dir');
+
+ await expect(
+ executeDeviceRpc(
+ 'createLocalDirectory',
+ { path: dirPath, workspaceRoot: root },
+ makeDeps(),
+ ),
+ ).resolves.toEqual({ path: dirPath, success: true });
+ expect((await stat(dirPath)).isDirectory()).toBe(true);
+ await expect(
+ executeDeviceRpc(
+ 'createLocalDirectory',
+ { path: dirPath, workspaceRoot: root },
+ makeDeps(),
+ ),
+ ).resolves.toMatchObject({
+ error: expect.stringContaining('already exists'),
+ success: false,
+ });
+ });
+
+ it('routes copyLocalFiles, duplicating in place when targetPath is omitted', async () => {
+ const src = path.join(root, 'dup.md');
+ await writeFile(src, 'dup');
+
+ const result = await executeDeviceRpc(
+ 'copyLocalFiles',
+ { items: [{ sourcePath: src }], workspaceRoot: root },
+ makeDeps(),
+ );
+
+ expect(result).toEqual([
+ { sourcePath: src, success: true, targetPath: path.join(root, 'dup copy.md') },
+ ]);
+ expect(await readFile(path.join(root, 'dup copy.md'), 'utf8')).toBe('dup');
+ });
+
+ it('routes trashLocalFiles to the host trash handler', async () => {
+ const target = path.join(root, 'a.txt');
+ const trashLocalFiles = vi.fn(async () => ({
+ items: [{ path: target, success: true }],
+ success: true,
+ }));
+
+ await expect(
+ executeDeviceRpc(
+ 'trashLocalFiles',
+ { paths: [target], workspaceRoot: root },
+ {
+ ...makeDeps(),
+ trashLocalFiles,
+ },
+ ),
+ ).resolves.toEqual({ items: [{ path: target, success: true }], success: true });
+ expect(trashLocalFiles).toHaveBeenCalledWith({ paths: [target] });
+ });
+
+ it('rejects trashLocalFiles on a host without a trash instead of hard-deleting', async () => {
+ const filePath = path.join(root, 'must-survive.txt');
+ await writeFile(filePath, 'still here');
+
+ await expect(
+ executeDeviceRpc('trashLocalFiles', { paths: [filePath], workspaceRoot: root }, makeDeps()),
+ ).rejects.toThrow(TRASH_UNSUPPORTED_MESSAGE);
+ expect(await readFile(filePath, 'utf8')).toBe('still here');
+ });
+
+ describe('workspace containment through symlinks', () => {
+ let workspace: string;
+ let outside: string;
+
+ beforeAll(async () => {
+ workspace = await mkdtemp(path.join(tmpdir(), 'device-control-ws-'));
+ outside = await mkdtemp(path.join(tmpdir(), 'device-control-outside-'));
+ await writeFile(path.join(outside, 'secret.txt'), 'secret');
+ // `<workspace>/link` passes a lexical "inside the root" check but
+ // points at a folder outside the workspace.
+ await symlink(outside, path.join(workspace, 'link'));
+ });
+
+ afterAll(async () => {
+ await rm(workspace, { force: true, recursive: true });
+ await rm(outside, { force: true, recursive: true });
+ });
+
+ it('refuses to create through a symlinked folder that leaves the workspace', async () => {
+ const escaped = path.join(workspace, 'link', 'planted.txt');
+
+ await expect(
+ executeDeviceRpc(
+ 'createLocalFile',
+ { path: escaped, workspaceRoot: workspace },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ await expect(
+ executeDeviceRpc(
+ 'createLocalDirectory',
+ { path: path.join(workspace, 'link', 'planted-dir'), workspaceRoot: workspace },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ await expect(readdir(outside)).resolves.toEqual(['secret.txt']);
+ });
+
+ it('refuses to copy a file out through the symlink', async () => {
+ await writeFile(path.join(workspace, 'inside.txt'), 'inside');
+
+ await expect(
+ executeDeviceRpc(
+ 'copyLocalFiles',
+ {
+ items: [
+ {
+ sourcePath: path.join(workspace, 'inside.txt'),
+ targetPath: path.join(workspace, 'link', 'copied.txt'),
+ },
+ ],
+ workspaceRoot: workspace,
+ },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ await expect(readdir(outside)).resolves.toEqual(['secret.txt']);
+ });
+
+ it('refuses to trash a file reached through the symlink', async () => {
+ const trashLocalFiles = vi.fn();
+
+ await expect(
+ executeDeviceRpc(
+ 'trashLocalFiles',
+ { paths: [path.join(workspace, 'link', 'secret.txt')], workspaceRoot: workspace },
+ { ...makeDeps(), trashLocalFiles },
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ expect(trashLocalFiles).not.toHaveBeenCalled();
+ });
+
+ it('still lets the symlink entry itself be trashed', async () => {
+ const trashLocalFiles = vi.fn(async () => ({ items: [], success: true }));
+ const link = path.join(workspace, 'link');
+
+ await executeDeviceRpc(
+ 'trashLocalFiles',
+ { paths: [link], workspaceRoot: workspace },
+ { ...makeDeps(), trashLocalFiles },
+ );
+ expect(trashLocalFiles).toHaveBeenCalledWith({ paths: [link] });
+ });
+
+ it('applies the same check to move / rename / write once the root is sent', async () => {
+ await writeFile(path.join(workspace, 'movable.txt'), 'm');
+
+ await expect(
+ executeDeviceRpc(
+ 'moveLocalFiles',
+ {
+ items: [
+ {
+ newPath: path.join(workspace, 'link', 'moved.txt'),
+ oldPath: path.join(workspace, 'movable.txt'),
+ },
+ ],
+ workspaceRoot: workspace,
+ },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ await expect(
+ executeDeviceRpc(
+ 'renameLocalFile',
+ {
+ newName: 'renamed.txt',
+ path: path.join(workspace, 'link', 'secret.txt'),
+ workspaceRoot: workspace,
+ },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ await expect(
+ executeDeviceRpc(
+ 'writeLocalFile',
+ {
+ content: 'overwritten',
+ path: path.join(workspace, 'link', 'secret.txt'),
+ workspaceRoot: workspace,
+ },
+ makeDeps(),
+ ),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ expect(await readFile(path.join(outside, 'secret.txt'), 'utf8')).toBe('secret');
+ });
+
+ it('refuses create / copy / trash that arrive without a workspace root', async () => {
+ await expect(
+ executeDeviceRpc('createLocalFile', { path: path.join(workspace, 'x.txt') }, makeDeps()),
+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);
+ });
+ });
+ });
+
it('routes listGitWorktrees through the shared git dispatcher', async () => {
// Not a git repo → the shared local-file-shell impl returns an empty list.
const result = await executeDeviceRpc('listGitWorktrees', { path: root }, makeDeps());
diff --git a/packages/device-control/src/__tests__/projectFileIndex.test.ts b/packages/device-control/src/__tests__/projectFileIndex.test.ts
index 8ff34bc9db0..a97d97e6f43 100644
--- a/packages/device-control/src/__tests__/projectFileIndex.test.ts
+++ b/packages/device-control/src/__tests__/projectFileIndex.test.ts
@@ -87,6 +87,28 @@ describe('defaultGetProjectFileIndex', () => {
);
});
+ it('keeps empty untracked folders visible as expandable directories', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-index-empty-dir-'));
+ cleanup.push(dir);
+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });
+ await mkdir(path.join(dir, 'src', 'utils'), { recursive: true });
+ await mkdir(path.join(dir, 'drafts', 'deeper'), { recursive: true });
+ await mkdir(path.join(dir, 'notes'), { recursive: true });
+ await writeFile(path.join(dir, 'src', 'app.ts'), 'export {};\n');
+ await writeFile(path.join(dir, 'notes', 'today.md'), '# today\n');
+
+ const result = await defaultGetProjectFileIndex({ scope: dir });
+ const byPath = new Map(result.entries.map((entry) => [entry.relativePath, entry]));
+
+ expect(byPath.get('src/utils/')).toMatchObject({ collapsed: true, isDirectory: true });
+ expect(byPath.get('src/utils/')?.gitIgnored).toBeUndefined();
+ expect(byPath.get('drafts/')).toMatchObject({ collapsed: true, isDirectory: true });
+ // Folders that hold files are listed through those files, not collapsed.
+ expect(byPath.get('notes/')?.collapsed).toBeUndefined();
+ expect(byPath.get('src/')?.collapsed).toBeUndefined();
+ expect(byPath.has('notes/today.md')).toBe(true);
+ });
+
it('flags a collapsed ignored directory so its children can be fetched on expand', async () => {
const dir = await mkdtemp(path.join(tmpdir(), 'dc-index-collapsed-'));
cleanup.push(dir);
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 81c202dd68c..b25c8bd89f3 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -1,4 +1,11 @@
-import { moveLocalFiles, renameLocalFile, writeLocalFile } from '@lobechat/local-file-shell/file';
+import {
+ copyLocalFiles,
+ createLocalDirectory,
+ createLocalFile,
+ moveLocalFiles,
+ renameLocalFile,
+ writeLocalFile,
+} from '@lobechat/local-file-shell/file';
import {
addGitWorktree,
checkoutGitBranch,
@@ -24,6 +31,11 @@ import {
revertGitFile,
runPullRequestAction,
} from '@lobechat/local-file-shell/git';
+import type {
+ CopyFilesParams,
+ CreateDirectoryParams,
+ CreateFileParams,
+} from '@lobechat/local-file-shell/types';
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
@@ -46,9 +58,11 @@ import type {
ProjectDirectoryListParams,
ProjectFileIndexParams,
ProjectFileSearchParams,
+ TrashLocalFilesParams,
UnenrollWorkspaceParams,
} from './types';
import { browseDirectory, initWorkspace, listProjectSkills, statPath } from './workspace';
+import { assertEntriesWithinWorkspace, WORKSPACE_ESCAPE_MESSAGE } from './workspaceGuard';
/**
* Every method name the device-control RPC dispatcher understands. Mirrors the
@@ -77,6 +91,10 @@ export const DEVICE_RPC_METHODS = [
'moveLocalFiles',
'renameLocalFile',
'writeLocalFile',
+ 'createLocalFile',
+ 'createLocalDirectory',
+ 'copyLocalFiles',
+ 'trashLocalFiles',
'getGitBranch',
'getLinkedPullRequest',
'getPullRequestDetail',
@@ -110,6 +128,30 @@ export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];
/** Why a client without the app-update handlers rejects those RPCs. */
export const APP_UPDATE_UNSUPPORTED_MESSAGE = 'This device client does not support remote updates';
+/** Why a client without a recoverable trash (the CLI daemon) rejects `trashLocalFiles`. */
+export const TRASH_UNSUPPORTED_MESSAGE = 'This device does not support moving files to the trash';
+
+/** File-mutation params carry the approved workspace root they must stay inside. */
+type WorkspaceScoped<T> = T & { workspaceRoot?: string };
+
+/**
+ * The file-tree mutations (create / mkdir / copy / trash) always arrive with
+ * the workspace root, so a request without one is refused rather than run
+ * unchecked.
+ */
+const guardMutation = async (workspaceRoot: string | undefined, targets: string[]) => {
+ if (!workspaceRoot) throw new Error(`${WORKSPACE_ESCAPE_MESSAGE}: missing workspace root`);
+ await assertEntriesWithinWorkspace(workspaceRoot, targets);
+};
+
+/**
+ * move / rename / write predate the root being sent; a server that still omits
+ * it keeps working, and every server that sends it gets the device-side check.
+ */
+const guardLegacyMutation = async (workspaceRoot: string | undefined, targets: string[]) => {
+ if (workspaceRoot) await assertEntriesWithinWorkspace(workspaceRoot, targets);
+};
+
/**
* Dispatch a generic server-internal device RPC by method name. This is the
* single device-control entry point shared by the desktop main process
@@ -214,15 +256,64 @@ export const executeDeviceRpc = async (
}
case 'moveLocalFiles': {
- return moveLocalFiles(params as { items: { newPath: string; oldPath: string }[] });
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<{
+ items: { newPath: string; oldPath: string }[];
+ }>;
+ await guardLegacyMutation(
+ workspaceRoot,
+ rest.items.flatMap((item) => [item.oldPath, item.newPath]),
+ );
+ return moveLocalFiles(rest);
}
case 'renameLocalFile': {
- return renameLocalFile(params as { newName: string; path: string });
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<{
+ newName: string;
+ path: string;
+ }>;
+ await guardLegacyMutation(workspaceRoot, [rest.path]);
+ return renameLocalFile(rest);
}
case 'writeLocalFile': {
- return writeLocalFile(params as { content: string; path: string });
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<{
+ content: string;
+ path: string;
+ }>;
+ await guardLegacyMutation(workspaceRoot, [rest.path]);
+ return writeLocalFile(rest);
+ }
+
+ case 'createLocalFile': {
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<CreateFileParams>;
+ await guardMutation(workspaceRoot, [rest.path]);
+ return createLocalFile(rest);
+ }
+
+ case 'createLocalDirectory': {
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<CreateDirectoryParams>;
+ await guardMutation(workspaceRoot, [rest.path]);
+ return createLocalDirectory(rest);
+ }
+
+ case 'copyLocalFiles': {
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<CopyFilesParams>;
+ await guardMutation(
+ workspaceRoot,
+ rest.items.flatMap((item) =>
+ item.targetPath === undefined ? [item.sourcePath] : [item.sourcePath, item.targetPath],
+ ),
+ );
+ return copyLocalFiles(rest);
+ }
+
+ // Never falls back to a hard delete: a host without a recoverable trash
+ // refuses, so a remote "delete" can always be undone.
+ case 'trashLocalFiles': {
+ const { workspaceRoot, ...rest } = params as WorkspaceScoped<TrashLocalFilesParams>;
+ if (!deps.trashLocalFiles) throw new Error(TRASH_UNSUPPORTED_MESSAGE);
+ await guardMutation(workspaceRoot, rest.paths);
+ return deps.trashLocalFiles(rest);
}
case 'getGitBranch': {
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 10a14fbae4d..11d4be6902b 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -4,6 +4,7 @@ export {
DEVICE_RPC_METHODS,
type DeviceRpcMethod,
executeDeviceRpc,
+ TRASH_UNSUPPORTED_MESSAGE,
} from './dispatch';
export {
defaultCopyAssetForPublish,
diff --git a/packages/device-control/src/projectFileIndex.ts b/packages/device-control/src/projectFileIndex.ts
index 0151932b170..9172cedf578 100644
--- a/packages/device-control/src/projectFileIndex.ts
+++ b/packages/device-control/src/projectFileIndex.ts
@@ -73,6 +73,7 @@ const buildEntries = (
files: string[],
root: string,
ignoredPaths: string[] = [],
+ emptyDirectoryPaths: string[] = [],
): ProjectFileIndexEntry[] => {
const seen = new Set<string>();
const fileEntries = files
@@ -107,11 +108,90 @@ const buildEntries = (
return true;
});
+ // Git tracks no directories, so an empty (or empty-only) untracked folder —
+ // one the user just created — never shows up among the files. Surface it as
+ // a collapsed directory so it stays visible and expands on demand.
+ const emptyDirectoryEntries = emptyDirectoryPaths
+ .map((relativePath) =>
+ createProjectFileEntry(
+ root,
+ path.resolve(root, relativePath.replace(/\/$/, '')),
+ true,
+ false,
+ true,
+ ),
+ )
+ .filter((entry) => {
+ if (seen.has(entry.path)) return false;
+ seen.add(entry.path);
+ return true;
+ });
+
return clearCollapsedOnIndexedDirectories(
- addMissingParentDirectories([...fileEntries, ...ignoredEntries], root),
+ addMissingParentDirectories(
+ [...fileEntries, ...ignoredEntries, ...emptyDirectoryEntries],
+ root,
+ ),
);
};
+// Upper bound on directories visited while looking for empty folders inside
+// untracked directories, so a huge untracked tree can't stall the index.
+const EMPTY_DIRECTORY_SCAN_LIMIT = 2000;
+
+/**
+ * Untracked folders that hold none of the indexed files: empty folders, or
+ * folders of empty folders. Git lists no directories, and
+ * `git ls-files --others --directory` reports an untracked folder that has
+ * files only as that folder, so empty folders nested inside it are found by a
+ * bounded walk that skips ignored folders.
+ */
+const findEmptyUntrackedDirectories = async (
+ root: string,
+ untrackedDirectoryOutput: string,
+ files: string[],
+ ignoredPaths: string[],
+): Promise<string[]> => {
+ const reported = untrackedDirectoryOutput
+ .split('\n')
+ .map((item) => item.trim())
+ .filter((item) => item.endsWith('/'));
+ if (reported.length === 0) return [];
+
+ const directoriesWithFiles = new Set<string>();
+ for (const file of files) {
+ let parent = getParentRelativePath(file);
+ while (parent && !directoriesWithFiles.has(parent)) {
+ directoriesWithFiles.add(parent);
+ parent = getParentRelativePath(parent);
+ }
+ }
+ const ignored = new Set(ignoredPaths.filter((item) => item.endsWith('/')));
+
+ const empty: string[] = [];
+ const queue = reported.filter((directory) => {
+ if (directoriesWithFiles.has(directory)) return true;
+ empty.push(directory);
+ return false;
+ });
+ let visited = 0;
+ while (queue.length > 0 && visited < EMPTY_DIRECTORY_SCAN_LIMIT) {
+ const directory = queue.shift()!;
+ visited += 1;
+ const children = await readdir(path.resolve(root, directory), { withFileTypes: true }).catch(
+ () => [],
+ );
+ for (const child of children) {
+ if (!child.isDirectory()) continue;
+ const relativePath = `${directory}${child.name}/`;
+ if (ignored.has(relativePath) || child.name === '.git') continue;
+ if (directoriesWithFiles.has(relativePath)) queue.push(relativePath);
+ else empty.push(relativePath);
+ }
+ }
+ return empty;
+};
+
/**
* A directory Git collapsed can still have indexed descendants — a nested
* `.gitignore` re-including part of the subtree, for example. Those rows are
@@ -245,44 +325,80 @@ export const defaultGetProjectFileIndex = async (
rootResult?.stdout && !exitCode ? rootResult.stdout.trim() || requestedScope : requestedScope;
if (rootResult?.stdout && !exitCode) {
- const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([
- execFileAsync(
- 'git',
- ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
- { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
- ),
- execFileAsync(
- 'git',
- ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--others', '--exclude-standard'],
- { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
- ).catch(() => ({ stdout: '' })),
- execFileAsync(
- 'git',
- [
- '-C',
- root,
- '-c',
- 'core.quotepath=false',
- 'ls-files',
- '--others',
- '--ignored',
- '--exclude-standard',
- '--directory',
- ],
- { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
- ).catch(() => ({ stdout: '' })),
- ]);
-
- const files = [...trackedResult.stdout.split('\n'), ...untrackedResult.stdout.split('\n')]
+ const [trackedResult, untrackedResult, ignoredResult, untrackedDirectoryResult] =
+ await Promise.all([
+ execFileAsync(
+ 'git',
+ ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ),
+ execFileAsync(
+ 'git',
+ [
+ '-C',
+ root,
+ '-c',
+ 'core.quotepath=false',
+ 'ls-files',
+ '--others',
+ '--exclude-standard',
+ ],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ).catch(() => ({ stdout: '' })),
+ execFileAsync(
+ 'git',
+ [
+ '-C',
+ root,
+ '-c',
+ 'core.quotepath=false',
+ 'ls-files',
+ '--others',
+ '--ignored',
+ '--exclude-standard',
+ '--directory',
+ ],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ).catch(() => ({ stdout: '' })),
+ execFileAsync(
+ 'git',
+ [
+ '-C',
+ root,
+ '-c',
+ 'core.quotepath=false',
+ 'ls-files',
+ '--others',
+ '--exclude-standard',
+ '--directory',
+ ],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ).catch(() => ({ stdout: '' })),
+ ]);
+
+ const fileRelativePaths = [
+ ...trackedResult.stdout.split('\n'),
+ ...untrackedResult.stdout.split('\n'),
+ ]
.map((item) => item.trim())
- .filter(Boolean)
- .map((relativePath) => path.resolve(root, relativePath));
+ .filter(Boolean);
+ const files = fileRelativePaths.map((relativePath) => path.resolve(root, relativePath));
const ignoredPaths = ignoredResult.stdout
.split('\n')
.map((item) => item.trim())
.filter(Boolean);
- const entries = buildEntries(files, root, ignoredPaths);
+ const entries = buildEntries(
+ files,
+ root,
+ ignoredPaths,
+ await findEmptyUntrackedDirectories(
+ root,
+ untrackedDirectoryResult.stdout,
+ fileRelativePaths,
+ ignoredPaths,
+ ),
+ );
return {
entries,
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 2abe2b50210..749f87727b0 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -272,6 +272,26 @@ export interface WorkspaceScanDeps {
* - The CLI uses the portable defaults exported from this package
* (`defaultGetLocalFilePreview`, `defaultGetProjectFileIndex`).
*/
+// ─── Trash ───
+
+/** Mirrors `@lobechat/electron-client-ipc` `TrashLocalFilesParams`. */
+export interface TrashLocalFilesParams {
+ paths: string[];
+}
+
+export interface TrashLocalFilesResultItem {
+ error?: string;
+ /** The path as it was requested, so the caller can reconcile its own rows. */
+ path: string;
+ success: boolean;
+}
+
+/** Per-path outcome in request order; `success` is true only when every path was trashed. */
+export interface TrashLocalFilesResult {
+ items: TrashLocalFilesResultItem[];
+ success: boolean;
+}
+
export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps {
/**
* Start an app update check on this client; an available update downloads
@@ -314,6 +334,13 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps
) => Promise<ExternalAssetForPublishResult>;
/** Search project files without shipping the whole index to the caller. */
searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;
+ /**
+ * Move files/folders to the OS trash. Optional: only a host with a desktop
+ * shell (Electron `shell.trashItem`) has a recoverable trash, so the CLI omits
+ * it and the dispatcher fails the RPC with {@link TRASH_UNSUPPORTED_MESSAGE}
+ * rather than degrading to a permanent delete.
+ */
+ trashLocalFiles?: (params: TrashLocalFilesParams) => Promise<TrashLocalFilesResult>;
/**
* Drop this machine's enrollment in a workspace pool: close the
* workspace-principal connection and clear any persisted auto-reconnect
diff --git a/packages/device-control/src/workspaceGuard.ts b/packages/device-control/src/workspaceGuard.ts
new file mode 100644
index 00000000000..4c62e690d10
--- /dev/null
+++ b/packages/device-control/src/workspaceGuard.ts
@@ -0,0 +1,65 @@
+import { realpath } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+export const WORKSPACE_ESCAPE_MESSAGE = 'Path is outside the approved workspace';
+
+const expandHomePath = (target: string): string => {
+ if (target === '~') return homedir();
+ if (target.startsWith('~/') || target.startsWith('~\\')) {
+ return path.join(homedir(), target.slice(2));
+ }
+ return target;
+};
+
+// A path that does not exist yet (a file about to be created, nested folders
+// `a/b` created on the way) resolves through its nearest existing ancestor,
+// with the missing tail re-appended.
+const realpathForCreate = async (target: string): Promise<string> => {
+ const missing: string[] = [];
+ let current = path.resolve(target);
+ for (;;) {
+ try {
+ return path.join(await realpath(current), ...missing);
+ } catch {
+ const parent = path.dirname(current);
+ if (parent === current) return path.join(current, ...missing);
+ missing.unshift(path.basename(current));
+ current = parent;
+ }
+ }
+};
+
+/**
+ * Where an entry really lives: its parent folder resolved through symlinks, its
+ * own name kept as-is. Resolving the parent stops a path that walks *through* a
+ * symlinked folder (`<root>/link/secret` with `link → /etc`) from escaping,
+ * while the entry itself may still be a symlink — renaming, copying or trashing
+ * the link acts on the link, never on what it points to.
+ */
+const resolveEntry = async (target: string, realRoot: string): Promise<string> => {
+ const absolute = path.resolve(realRoot, expandHomePath(target));
+ const realParent = await realpathForCreate(path.dirname(absolute));
+ return path.join(realParent, path.basename(absolute));
+};
+
+/**
+ * Device-side containment for file mutations. The server's check is lexical
+ * (it cannot see the device's filesystem), so the device re-checks every path
+ * against the real workspace root before touching disk. Entries must sit
+ * strictly inside the root: the root itself is never a mutation target.
+ */
+export const assertEntriesWithinWorkspace = async (
+ workspaceRoot: string,
+ targets: string[],
+): Promise<void> => {
+ const realRoot = await realpathForCreate(expandHomePath(workspaceRoot));
+ const prefix = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;
+
+ for (const target of targets) {
+ const entry = await resolveEntry(target, realRoot);
+ if (!entry.startsWith(prefix)) {
+ throw new Error(`${WORKSPACE_ESCAPE_MESSAGE}: ${target}`);
+ }
+ }
+};
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index e95ae53e7f8..f4d26ca4006 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -88,6 +88,47 @@ export interface RenameLocalFileResult {
success: boolean;
}
+export interface CreateLocalFileParams {
+ /** Initial content. Defaults to an empty file. */
+ content?: string;
+ /** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
+ path: string;
+}
+
+export interface CreateLocalDirectoryParams {
+ /** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
+ path: string;
+}
+
+/** Result of creating a file or folder. Never overwrites: an existing entry fails. */
+export interface CreateLocalEntryResult {
+ error?: string;
+ path: string;
+ success: boolean;
+}
+
+export interface CopyLocalFileItem {
+ sourcePath: string;
+ /** Omit to duplicate next to the source as `name copy.ext` / `name copy 2.ext`. */
+ targetPath?: string;
+}
+
+export interface CopyLocalFilesParams {
+ /** Working directory each item's relative paths resolve against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
+ items: CopyLocalFileItem[];
+}
+
+export interface LocalCopyFilesResultItem {
+ error?: string;
+ sourcePath: string;
+ success: boolean;
+ /** The path the copy was written to, when it succeeded. */
+ targetPath?: string;
+}
+
export interface HashLocalFileParams {
path: string;
}
diff --git a/packages/local-file-shell/src/file/__tests__/createCopy.test.ts b/packages/local-file-shell/src/file/__tests__/createCopy.test.ts
new file mode 100644
index 00000000000..65421ff1529
--- /dev/null
+++ b/packages/local-file-shell/src/file/__tests__/createCopy.test.ts
@@ -0,0 +1,248 @@
+import fs from 'node:fs';
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { copyLocalFiles, createLocalDirectory, createLocalFile, getCopyName } from '../index';
+
+let tmpDir: string;
+
+beforeEach(async () => {
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'local-file-shell-create-copy-'));
+});
+
+afterEach(async () => {
+ await rm(tmpDir, { force: true, recursive: true });
+});
+
+describe('createLocalFile', () => {
+ it('creates an empty file by default', async () => {
+ const filePath = path.join(tmpDir, 'new.ts');
+
+ const result = await createLocalFile({ path: filePath });
+
+ expect(result).toEqual({ path: filePath, success: true });
+ expect(await readFile(filePath, 'utf8')).toBe('');
+ });
+
+ it('creates missing parent folders and writes initial content', async () => {
+ const filePath = path.join(tmpDir, 'a', 'b', 'c.md');
+
+ const result = await createLocalFile({ content: '# hi', path: filePath });
+
+ expect(result.success).toBe(true);
+ expect(await readFile(filePath, 'utf8')).toBe('# hi');
+ });
+
+ it('resolves a relative path against cwd', async () => {
+ const result = await createLocalFile({ cwd: tmpDir, path: 'rel.txt' });
+
+ expect(result).toEqual({ path: path.join(tmpDir, 'rel.txt'), success: true });
+ });
+
+ it('refuses to overwrite an existing file', async () => {
+ const filePath = path.join(tmpDir, 'taken.txt');
+ await writeFile(filePath, 'keep me');
+
+ const result = await createLocalFile({ content: 'new', path: filePath });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(await readFile(filePath, 'utf8')).toBe('keep me');
+ });
+
+ it('refuses when a folder already sits at the path', async () => {
+ const dirPath = path.join(tmpDir, 'folder');
+ await mkdir(dirPath);
+
+ const result = await createLocalFile({ path: dirPath });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ });
+
+ it('rejects an empty path', async () => {
+ expect(await createLocalFile({ path: '' })).toEqual({
+ error: 'Path cannot be empty',
+ path: '',
+ success: false,
+ });
+ });
+});
+
+describe('createLocalDirectory', () => {
+ it('creates a folder', async () => {
+ const dirPath = path.join(tmpDir, 'x');
+
+ const result = await createLocalDirectory({ path: dirPath });
+
+ expect(result).toEqual({ path: dirPath, success: true });
+ expect(fs.statSync(dirPath).isDirectory()).toBe(true);
+ });
+
+ it('does not create missing parent folders', async () => {
+ const dirPath = path.join(tmpDir, 'missing', 'child');
+
+ const result = await createLocalDirectory({ path: dirPath });
+
+ expect(result).toEqual({
+ error: `The parent folder of ${dirPath} does not exist.`,
+ path: dirPath,
+ success: false,
+ });
+ expect(fs.existsSync(path.join(tmpDir, 'missing'))).toBe(false);
+ });
+
+ it('refuses when the folder already exists', async () => {
+ const dirPath = path.join(tmpDir, 'exists');
+ await mkdir(dirPath);
+ await writeFile(path.join(dirPath, 'inside.txt'), 'keep');
+
+ const result = await createLocalDirectory({ path: dirPath });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(fs.readdirSync(dirPath)).toEqual(['inside.txt']);
+ });
+
+ it('refuses when a file already sits at the path', async () => {
+ const filePath = path.join(tmpDir, 'file');
+ await writeFile(filePath, 'x');
+
+ const result = await createLocalDirectory({ path: filePath });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ });
+});
+
+describe('getCopyName', () => {
+ it.each([
+ ['report.pdf', false, 1, 'report copy.pdf'],
+ ['report.pdf', false, 2, 'report copy 2.pdf'],
+ ['report copy.pdf', false, 2, 'report copy 2.pdf'],
+ ['report copy 3.pdf', false, 4, 'report copy 4.pdf'],
+ ['.env', false, 1, '.env copy'],
+ ['Makefile', false, 1, 'Makefile copy'],
+ ['v1.2', true, 1, 'v1.2 copy'],
+ ['src', true, 3, 'src copy 3'],
+ ])('%s (dir=%s, attempt %i) → %s', (name, isDirectory, attempt, expected) => {
+ expect(getCopyName(name, isDirectory, attempt)).toBe(expected);
+ });
+});
+
+describe('copyLocalFiles', () => {
+ it('copies a file to an explicit target', async () => {
+ const src = path.join(tmpDir, 'a.txt');
+ const dst = path.join(tmpDir, 'sub', 'b.txt');
+ await writeFile(src, 'hello');
+
+ const result = await copyLocalFiles({ items: [{ sourcePath: src, targetPath: dst }] });
+
+ expect(result).toEqual([{ sourcePath: src, success: true, targetPath: dst }]);
+ expect(await readFile(dst, 'utf8')).toBe('hello');
+ expect(await readFile(src, 'utf8')).toBe('hello');
+ });
+
+ it('copies a folder recursively and keeps relative symlinks verbatim', async () => {
+ const src = path.join(tmpDir, 'pkg');
+ await mkdir(path.join(src, 'nested'), { recursive: true });
+ await writeFile(path.join(src, 'nested', 'deep.txt'), 'deep');
+ await symlink('nested/deep.txt', path.join(src, 'link.txt'));
+ const dst = path.join(tmpDir, 'pkg-2');
+
+ const result = await copyLocalFiles({ items: [{ sourcePath: src, targetPath: dst }] });
+
+ expect(result[0].success).toBe(true);
+ expect(await readFile(path.join(dst, 'nested', 'deep.txt'), 'utf8')).toBe('deep');
+ expect(fs.readlinkSync(path.join(dst, 'link.txt'))).toBe('nested/deep.txt');
+ });
+
+ it('refuses to overwrite an existing target file', async () => {
+ const src = path.join(tmpDir, 'a.txt');
+ const dst = path.join(tmpDir, 'b.txt');
+ await writeFile(src, 'incoming');
+ await writeFile(dst, 'keep me');
+
+ const [result] = await copyLocalFiles({ items: [{ sourcePath: src, targetPath: dst }] });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(await readFile(dst, 'utf8')).toBe('keep me');
+ });
+
+ it('refuses to merge a folder into an existing folder', async () => {
+ const src = path.join(tmpDir, 'src');
+ const dst = path.join(tmpDir, 'dst');
+ await mkdir(src);
+ await writeFile(path.join(src, 'new.txt'), 'new');
+ await mkdir(dst);
+
+ const [result] = await copyLocalFiles({ items: [{ sourcePath: src, targetPath: dst }] });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(fs.readdirSync(dst)).toEqual([]);
+ });
+
+ it('duplicates next to the source with Finder-style names when targetPath is omitted', async () => {
+ const src = path.join(tmpDir, 'notes.md');
+ await writeFile(src, 'n');
+
+ const first = await copyLocalFiles({ items: [{ sourcePath: src }] });
+ const second = await copyLocalFiles({ items: [{ sourcePath: src }] });
+ const ofCopy = await copyLocalFiles({ items: [{ sourcePath: first[0].targetPath! }] });
+
+ expect(first[0].targetPath).toBe(path.join(tmpDir, 'notes copy.md'));
+ expect(second[0].targetPath).toBe(path.join(tmpDir, 'notes copy 2.md'));
+ expect(ofCopy[0].targetPath).toBe(path.join(tmpDir, 'notes copy 3.md'));
+ expect(await readFile(path.join(tmpDir, 'notes copy 2.md'), 'utf8')).toBe('n');
+ });
+
+ it('duplicates a folder without splitting a dotted name', async () => {
+ const src = path.join(tmpDir, 'v1.2');
+ await mkdir(src);
+ await writeFile(path.join(src, 'x.txt'), 'x');
+
+ const [result] = await copyLocalFiles({ items: [{ sourcePath: src }] });
+
+ expect(result.targetPath).toBe(path.join(tmpDir, 'v1.2 copy'));
+ expect(await readFile(path.join(tmpDir, 'v1.2 copy', 'x.txt'), 'utf8')).toBe('x');
+ });
+
+ it('refuses to copy a folder into itself', async () => {
+ const src = path.join(tmpDir, 'loop');
+ await mkdir(src);
+
+ const [result] = await copyLocalFiles({
+ items: [{ sourcePath: src, targetPath: path.join(src, 'inner') }],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('into itself');
+ });
+
+ it('reports each item independently', async () => {
+ const ok = path.join(tmpDir, 'ok.txt');
+ await writeFile(ok, 'ok');
+ const missing = path.join(tmpDir, 'missing.txt');
+
+ const result = await copyLocalFiles({
+ items: [
+ { sourcePath: missing },
+ { sourcePath: ok, targetPath: path.join(tmpDir, 'ok2.txt') },
+ ],
+ });
+
+ expect(result).toEqual([
+ { error: `Source path not found: ${missing}.`, sourcePath: missing, success: false },
+ { sourcePath: ok, success: true, targetPath: path.join(tmpDir, 'ok2.txt') },
+ ]);
+ });
+
+ it('returns an empty list for no items', async () => {
+ expect(await copyLocalFiles({ items: [] })).toEqual([]);
+ });
+});
diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.ts
index e64879132c6..c1d3e062e6c 100644
--- a/packages/local-file-shell/src/file/__tests__/file.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts
@@ -658,6 +658,33 @@ describe('file operations', () => {
expect(result).toEqual([]);
});
+ it('should refuse to overwrite an existing target file', async () => {
+ const src = path.join(tmpDir, 'src.txt');
+ const dst = path.join(tmpDir, 'dst.txt');
+ await writeFile(src, 'incoming');
+ await writeFile(dst, 'keep me');
+
+ const result = await moveLocalFiles({ items: [{ newPath: dst, oldPath: src }] });
+
+ expect(result[0].success).toBe(false);
+ expect(result[0].error).toContain('already exists');
+ expect(fs.readFileSync(dst, 'utf8')).toBe('keep me');
+ expect(fs.readFileSync(src, 'utf8')).toBe('incoming');
+ });
+
+ it('should refuse to move onto an existing directory', async () => {
+ const src = path.join(tmpDir, 'src-dir');
+ const dst = path.join(tmpDir, 'dst-dir');
+ await mkdir(src);
+ await mkdir(dst);
+
+ const result = await moveLocalFiles({ items: [{ newPath: dst, oldPath: src }] });
+
+ expect(result[0].success).toBe(false);
+ expect(result[0].error).toContain('already exists');
+ expect(fs.existsSync(src)).toBe(true);
+ });
+
it('should create target directory if missing', async () => {
const src = path.join(tmpDir, 'src.txt');
const dst = path.join(tmpDir, 'new', 'dir', 'dst.txt');
@@ -708,6 +735,31 @@ describe('file operations', () => {
expect(result.success).toBe(true);
});
+ it('should refuse to overwrite an existing sibling', async () => {
+ const filePath = path.join(tmpDir, 'old.txt');
+ const taken = path.join(tmpDir, 'taken.txt');
+ await writeFile(filePath, 'incoming');
+ await writeFile(taken, 'keep me');
+
+ const result = await renameLocalFile({ newName: 'taken.txt', path: filePath });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('already exists');
+ expect(fs.readFileSync(taken, 'utf8')).toBe('keep me');
+ expect(fs.readFileSync(filePath, 'utf8')).toBe('incoming');
+ });
+
+ it('should allow a case-only rename', async () => {
+ const filePath = path.join(tmpDir, 'readme.md');
+ await writeFile(filePath, 'content');
+
+ const result = await renameLocalFile({ newName: 'README.md', path: filePath });
+
+ expect(result.success).toBe(true);
+ expect(fs.readdirSync(tmpDir)).toContain('README.md');
+ expect(fs.readdirSync(tmpDir)).not.toContain('readme.md');
+ });
+
it('should return error for non-existent file', async () => {
const result = await renameLocalFile({
newName: 'new.txt',
diff --git a/packages/local-file-shell/src/file/copy.ts b/packages/local-file-shell/src/file/copy.ts
new file mode 100644
index 00000000000..38d3badff78
--- /dev/null
+++ b/packages/local-file-shell/src/file/copy.ts
@@ -0,0 +1,105 @@
+import { cp } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { CopyFileResultItem, CopyFilesParams } from '../types';
+import { lstatIfExists } from './existingEntry';
+import { resolveAgainstCwd } from './expandTilde';
+
+/** Upper bound on `name copy N` probes; a folder with more duplicates than this is pathological. */
+const MAX_COPY_NAME_ATTEMPTS = 1000;
+
+/**
+ * Finder's duplicate naming: `report.pdf` → `report copy.pdf` → `report copy 2.pdf`.
+ * Duplicating a copy keeps counting from the original stem instead of stacking
+ * (`report copy.pdf` → `report copy 2.pdf`, not `report copy copy.pdf`).
+ * Folders and dotfiles keep their whole name as the stem.
+ */
+export const getCopyName = (name: string, isDirectory: boolean, attempt: number): string => {
+ const ext = isDirectory ? '' : path.extname(name);
+ const base = ext ? name.slice(0, -ext.length) : name;
+ const stem = base.replace(/ copy(?: \d+)?$/, '') || base;
+ const suffix = attempt <= 1 ? ' copy' : ` copy ${attempt}`;
+ return `${stem}${suffix}${ext}`;
+};
+
+const findFreeCopyPath = async (sourcePath: string, isDirectory: boolean): Promise<string> => {
+ const dir = path.dirname(sourcePath);
+ const name = path.basename(sourcePath);
+
+ for (let attempt = 1; attempt <= MAX_COPY_NAME_ATTEMPTS; attempt++) {
+ const candidate = path.join(dir, getCopyName(name, isDirectory, attempt));
+ if (!(await lstatIfExists(candidate))) return candidate;
+ }
+
+ throw new Error(`Could not find a free name to duplicate ${sourcePath}.`);
+};
+
+const describeCopyError = (error: unknown, sourcePath: string, targetPath: string): string => {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EEXIST' || code === 'ERR_FS_CP_EEXIST')
+ return `An item already exists at the target path: ${targetPath}.`;
+ if (code === 'ERR_FS_CP_EINVAL') return `Cannot copy ${sourcePath} into itself.`;
+ if (code === 'EPERM' || code === 'EACCES')
+ return `Permission denied to copy ${sourcePath} to ${targetPath}.`;
+ if (code === 'ENOENT') return `Source path not found: ${sourcePath}.`;
+ return (error as Error).message;
+};
+
+/**
+ * Copy files/folders (folders recursively). Never overwrites — an existing
+ * target fails that item — and each item succeeds or fails independently, so
+ * the caller can reconcile a partially applied batch.
+ *
+ * An item without `targetPath` is duplicated next to its source under the first
+ * free Finder-style name (see {@link getCopyName}).
+ */
+export async function copyLocalFiles({
+ cwd,
+ items,
+}: CopyFilesParams): Promise<CopyFileResultItem[]> {
+ const results: CopyFileResultItem[] = [];
+ if (!items || items.length === 0) return results;
+
+ for (const item of items) {
+ const sourcePath = resolveAgainstCwd(item.sourcePath, cwd) ?? item.sourcePath;
+ const resultItem: CopyFileResultItem = { sourcePath, success: false };
+ results.push(resultItem);
+
+ if (!sourcePath) {
+ resultItem.error = 'sourcePath is required for each item.';
+ continue;
+ }
+
+ let targetPath = resolveAgainstCwd(item.targetPath, cwd);
+ try {
+ const sourceStats = await lstatIfExists(sourcePath);
+ if (!sourceStats) {
+ resultItem.error = `Source path not found: ${sourcePath}.`;
+ continue;
+ }
+
+ targetPath ??= await findFreeCopyPath(sourcePath, sourceStats.isDirectory());
+
+ // `errorOnExist` alone only guards files: copying a folder onto an
+ // existing folder would merge into it and fail halfway through. Refuse
+ // up front so a conflict never leaves a partial copy behind.
+ if (await lstatIfExists(targetPath)) {
+ resultItem.error = `An item already exists at the target path: ${targetPath}.`;
+ continue;
+ }
+
+ await cp(sourcePath, targetPath, {
+ errorOnExist: true,
+ force: false,
+ recursive: true,
+ verbatimSymlinks: true,
+ });
+ resultItem.success = true;
+ resultItem.targetPath = targetPath;
+ } catch (error) {
+ resultItem.error = describeCopyError(error, sourcePath, targetPath ?? '');
+ }
+ }
+
+ return results;
+}
diff --git a/packages/local-file-shell/src/file/create.ts b/packages/local-file-shell/src/file/create.ts
new file mode 100644
index 00000000000..df573542693
--- /dev/null
+++ b/packages/local-file-shell/src/file/create.ts
@@ -0,0 +1,59 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { CreateDirectoryParams, CreateEntryResult, CreateFileParams } from '../types';
+import { resolveAgainstCwd } from './expandTilde';
+
+const describeCreateError = (error: unknown, targetPath: string): string => {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EEXIST') return `An item already exists at ${targetPath}.`;
+ if (code === 'EPERM' || code === 'EACCES') return `Permission denied to create ${targetPath}.`;
+ if (code === 'ENOTDIR') return `A parent of ${targetPath} is a file, not a folder.`;
+ if (code === 'ENOENT') return `The parent folder of ${targetPath} does not exist.`;
+ return (error as Error).message;
+};
+
+/**
+ * Create a new file. Unlike {@link writeLocalFile} this never overwrites: the
+ * final path is opened with `wx`, so an existing file or folder fails the call.
+ * Missing parent folders are created, so `a/b/c.ts` works in one step.
+ */
+export async function createLocalFile({
+ content = '',
+ cwd,
+ path: rawPath,
+}: CreateFileParams): Promise<CreateEntryResult> {
+ if (!rawPath) return { error: 'Path cannot be empty', path: '', success: false };
+
+ const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
+
+ try {
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, content, { flag: 'wx' });
+ return { path: filePath, success: true };
+ } catch (error) {
+ return { error: describeCreateError(error, filePath), path: filePath, success: false };
+ }
+}
+
+/**
+ * Create a new folder with a plain, non-recursive `mkdir`: an existing entry
+ * at the path fails the call instead of being silently accepted, and a missing
+ * parent fails too rather than conjuring a chain of folders the user never
+ * asked for.
+ */
+export async function createLocalDirectory({
+ cwd,
+ path: rawPath,
+}: CreateDirectoryParams): Promise<CreateEntryResult> {
+ if (!rawPath) return { error: 'Path cannot be empty', path: '', success: false };
+
+ const dirPath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
+
+ try {
+ await mkdir(dirPath, { recursive: false });
+ return { path: dirPath, success: true };
+ } catch (error) {
+ return { error: describeCreateError(error, dirPath), path: dirPath, success: false };
+ }
+}
diff --git a/packages/local-file-shell/src/file/existingEntry.ts b/packages/local-file-shell/src/file/existingEntry.ts
new file mode 100644
index 00000000000..d14d6e5dc6c
--- /dev/null
+++ b/packages/local-file-shell/src/file/existingEntry.ts
@@ -0,0 +1,32 @@
+import type { Stats } from 'node:fs';
+import { lstat } from 'node:fs/promises';
+
+/** `lstat` that reports a missing path as `undefined` instead of throwing. */
+export const lstatIfExists = async (target: string): Promise<Stats | undefined> => {
+ try {
+ return await lstat(target);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT' || code === 'ENOTDIR') return undefined;
+ throw error;
+ }
+};
+
+/**
+ * Whether `target` is already taken by an entry other than `source`.
+ *
+ * `fs.rename` silently replaces an existing file on POSIX, so move and rename
+ * check this first and refuse instead of destroying the user's file. A
+ * case-only rename (`a.ts` → `A.ts`) on a case-insensitive disk resolves both
+ * names to the same entry, which must stay allowed — hence the inode compare
+ * rather than a bare existence check.
+ */
+export const isTakenByAnotherEntry = async (source: string, target: string): Promise<boolean> => {
+ const targetStats = await lstatIfExists(target);
+ if (!targetStats) return false;
+
+ const sourceStats = await lstatIfExists(source);
+ if (!sourceStats) return true;
+
+ return sourceStats.ino !== targetStats.ino || sourceStats.dev !== targetStats.dev;
+};
diff --git a/packages/local-file-shell/src/file/index.ts b/packages/local-file-shell/src/file/index.ts
index 1801a35bd98..6cdf0c6379b 100644
--- a/packages/local-file-shell/src/file/index.ts
+++ b/packages/local-file-shell/src/file/index.ts
@@ -1,3 +1,5 @@
+export { copyLocalFiles, getCopyName } from './copy';
+export { createLocalDirectory, createLocalFile } from './create';
export { editLocalFile } from './edit';
export { expandTilde, resolveAgainstCwd } from './expandTilde';
export { globLocalFiles } from './glob';
diff --git a/packages/local-file-shell/src/file/move.ts b/packages/local-file-shell/src/file/move.ts
index 38222191e7c..1eb7c147fd2 100644
--- a/packages/local-file-shell/src/file/move.ts
+++ b/packages/local-file-shell/src/file/move.ts
@@ -3,9 +3,13 @@ import { access, mkdir, rename } from 'node:fs/promises';
import path from 'node:path';
import type { MoveFileResultItem, MoveFilesParams } from '../types';
+import { isTakenByAnotherEntry } from './existingEntry';
import { resolveAgainstCwd } from './expandTilde';
-export async function moveLocalFiles({ items, cwd }: MoveFilesParams): Promise<MoveFileResultItem[]> {
+export async function moveLocalFiles({
+ items,
+ cwd,
+}: MoveFilesParams): Promise<MoveFileResultItem[]> {
const results: MoveFileResultItem[] = [];
if (!items || items.length === 0) {
@@ -50,6 +54,13 @@ export async function moveLocalFiles({ items, cwd }: MoveFilesParams): Promise<M
continue;
}
+ // `fs.rename` replaces an existing file on POSIX; refuse instead.
+ if (await isTakenByAnotherEntry(sourcePath, newPath)) {
+ resultItem.error = `An item already exists at the target path: ${newPath}.`;
+ results.push(resultItem);
+ continue;
+ }
+
// Ensure target directory exists
const targetDir = path.dirname(newPath);
await mkdir(targetDir, { recursive: true });
diff --git a/packages/local-file-shell/src/file/rename.ts b/packages/local-file-shell/src/file/rename.ts
index e5aa1ba6f18..68ad25d275b 100644
--- a/packages/local-file-shell/src/file/rename.ts
+++ b/packages/local-file-shell/src/file/rename.ts
@@ -2,6 +2,7 @@ import { rename } from 'node:fs/promises';
import path from 'node:path';
import type { RenameFileParams, RenameFileResult } from '../types';
+import { isTakenByAnotherEntry } from './existingEntry';
import { expandTilde } from './expandTilde';
export async function renameLocalFile({
@@ -47,6 +48,15 @@ export async function renameLocalFile({
}
try {
+ // `fs.rename` replaces an existing file on POSIX; refuse instead.
+ if (await isTakenByAnotherEntry(currentPath, newPath)) {
+ return {
+ error: `Cannot rename: an item with the name '${newName}' already exists at this location.`,
+ newPath: '',
+ success: false,
+ };
+ }
+
await rename(currentPath, newPath);
return { newPath, success: true };
} catch (error) {
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index c270fc2d0d9..9456882282e 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -311,6 +311,51 @@ export interface RenameFileResult {
success: boolean;
}
+export interface CreateFileParams {
+ /** Initial content. Defaults to an empty file. */
+ content?: string;
+ /** Working directory a relative `path` resolves against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
+ path: string;
+}
+
+export interface CreateDirectoryParams {
+ /** Working directory a relative `path` resolves against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
+ path: string;
+}
+
+/** Result of creating one new file or directory. Never overwrites: an existing entry fails. */
+export interface CreateEntryResult {
+ error?: string;
+ /** The resolved absolute path of the entry that was (or would have been) created. */
+ path: string;
+ success: boolean;
+}
+
+export interface CopyFileItem {
+ sourcePath: string;
+ /**
+ * Where the copy lands. Omit it to duplicate next to the source under a
+ * Finder-style free name (`name copy.ext`, `name copy 2.ext`, …).
+ */
+ targetPath?: string;
+}
+
+export interface CopyFilesParams {
+ /** Working directory each item's relative paths resolve against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
+ items: CopyFileItem[];
+}
+
+export interface CopyFileResultItem {
+ error?: string;
+ sourcePath: string;
+ success: boolean;
+ /** The path the copy was written to, when it succeeded. */
+ targetPath?: string;
+}
+
export interface GrepContentParams {
'-A'?: number;
'-B'?: number;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 53193fc1af3..e7d4a49d8af 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2955,6 +2955,56 @@ export default {
'workingPanel.skills.title': 'Skills',
'workingPanel.files.copyAbsolutePath': 'Copy Path',
'workingPanel.files.copyRelativePath': 'Copy Relative Path',
+ 'workingPanel.files.actions.copy': 'Copy',
+ 'workingPanel.files.actions.cut': 'Cut',
+ 'workingPanel.files.actions.duplicate': 'Duplicate',
+ 'workingPanel.files.actions.more': 'More',
+ 'workingPanel.files.actions.moveToTrash': 'Move to {{trash}}',
+ 'workingPanel.files.actions.newFile': 'New File…',
+ 'workingPanel.files.actions.newFolder': 'New Folder…',
+ 'workingPanel.files.actions.openInSystem': 'Open in System',
+ 'workingPanel.files.actions.openInTerminal': 'Open in Terminal',
+ 'workingPanel.files.actions.paste': 'Paste',
+ 'workingPanel.files.actions.refresh': 'Refresh',
+ 'workingPanel.files.actions.rename': 'Rename…',
+ 'workingPanel.files.delete.confirm': 'Move to {{trash}}',
+ 'workingPanel.files.delete.confirmTitle': 'Move "{{name}}" to {{trash}}?',
+ 'workingPanel.files.delete.confirmTitleMultiple': 'Move {{count}} items to {{trash}}?',
+ 'workingPanel.files.delete.dirtyWarning': 'Includes uncommitted Git changes.',
+ 'workingPanel.files.delete.fileDesc': 'You can restore it from the {{trash}}.',
+ 'workingPanel.files.delete.folderDesc':
+ '"{{name}}" and everything in it will be moved to the {{trash}}. You can restore them from the {{trash}}.',
+ 'workingPanel.files.delete.multipleDesc': 'You can restore them from the {{trash}}.',
+ 'workingPanel.files.feedback.createFailed': 'Couldn\'t create "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.deleteFailed': 'Couldn\'t delete "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.deviceOffline':
+ 'The device is offline. Try again after it reconnects.',
+ 'workingPanel.files.feedback.duplicateFailed': 'Couldn\'t duplicate "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.moveConflict': '"{{name}}" already exists in the destination folder',
+ 'workingPanel.files.feedback.moveFailed': 'Couldn\'t move "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.openFailed': 'Couldn\'t open "{{name}}"',
+ 'workingPanel.files.feedback.pasteFailed': 'Couldn\'t paste "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.pasteIntoItself': 'Can\'t paste "{{name}}" into itself',
+ 'workingPanel.files.feedback.refreshFailed': "Couldn't refresh files",
+ 'workingPanel.files.feedback.renameFailed': 'Couldn\'t rename "{{name}}": {{reason}}',
+ 'workingPanel.files.feedback.terminalFailed': "Couldn't open the terminal",
+ 'workingPanel.files.feedback.trashUnsupported':
+ 'This device has no {{trash}} to move files to, so nothing was deleted. Delete it on the device itself.',
+ 'workingPanel.files.feedback.trashed': 'Moved "{{name}}" to {{trash}}',
+ 'workingPanel.files.feedback.trashedCount': 'Moved {{count}} items to {{trash}}',
+ 'workingPanel.files.feedback.unsupportedOnDevice':
+ "This device's app is out of date. Update it and try again.",
+ 'workingPanel.files.trashName.linux': 'Trash',
+ 'workingPanel.files.trashName.mac': 'Trash',
+ 'workingPanel.files.trashName.windows': 'Recycle Bin',
+ 'workingPanel.files.validation.empty': 'A file or folder name must be provided',
+ 'workingPanel.files.validation.exists':
+ '"{{name}}" already exists here. Choose a different name.',
+ 'workingPanel.files.validation.invalidChars':
+ 'Names can\'t contain < > : " / \\ | ? * or control characters',
+ 'workingPanel.files.validation.reserved': '"." and ".." can\'t be used as names',
+ 'workingPanel.files.validation.tooLong': 'Name is too long (255 bytes max)',
+ 'workingPanel.files.validation.whitespace': "Names can't start or end with a space",
'workingPanel.files.collapseAll': 'Collapse Folders in Explorer',
'workingPanel.files.empty': 'No files in this workspace',
'workingPanel.files.filters.changedOnly': 'Show Git Changes Only',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 695b3b1f6bc..9b38aaa40c6 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -885,6 +885,40 @@ export interface DeviceWriteProjectFileResult {
success: boolean;
}
+/**
+ * Result of the `createLocalFile` / `createLocalDirectory` device RPCs. Neither
+ * overwrites: an existing entry fails with `error`. Mirrors the desktop
+ * `CreateLocalEntryResult`.
+ */
+export interface DeviceCreateProjectEntryResult {
+ error?: string;
+ path: string;
+ success: boolean;
+}
+
+/**
+ * One item of a `copyLocalFiles` device RPC. Omitting `targetPath` duplicates
+ * the source next to itself under a Finder-style free name (`name copy.ext`).
+ */
+export interface DeviceCopyProjectFileItem {
+ sourcePath: string;
+ targetPath?: string;
+}
+
+/** Per-item result of the `copyLocalFiles` device RPC. Mirrors `LocalCopyFilesResultItem`. */
+export interface DeviceCopyProjectFileResultItem {
+ error?: string;
+ sourcePath: string;
+ success: boolean;
+ targetPath?: string;
+}
+
+/** Result of the `trashLocalFiles` device RPC. Mirrors the desktop `TrashLocalFilesResult`. */
+export interface DeviceTrashProjectFilesResult {
+ items: { error?: string; path: string; success: boolean }[];
+ success: boolean;
+}
+
/**
* A single project skill (`.agents/skills` / `.claude/skills`) discovered on a
* remote device, returned by the `listProjectSkills` device RPC. Mirrors the
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index 3f7001df9f8..a398e12dee0 100644
--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode as ReactNodeType, Ref } from 'react';
import { useImperativeHandle } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -13,8 +13,12 @@ import Files from '../index';
const handleSpies = {
focus: vi.fn(),
+ getSelectedIds: vi.fn((): string[] => []),
+ resync: vi.fn(),
select: vi.fn(),
setExpanded: vi.fn(),
+ startCreating: vi.fn(),
+ startRenaming: vi.fn(),
};
const explorerTreeProps = vi.hoisted(() => ({
@@ -30,6 +34,20 @@ const gitFilesMock = vi.hoisted(() => ({
const openLocalFileMock = vi.hoisted(() => vi.fn());
const searchProjectFilesMock = vi.hoisted(() => vi.fn());
const listProjectDirectoryMock = vi.hoisted(() => vi.fn());
+const fileOpsMock = vi.hoisted(() => ({
+ copyProjectFiles: vi.fn(),
+ createProjectDirectory: vi.fn(),
+ createProjectFile: vi.fn(),
+ moveProjectFiles: vi.fn(),
+ refreshProjectFiles: vi.fn(),
+ renameProjectFile: vi.fn(),
+ trashProjectFiles: vi.fn(),
+}));
+const uiSpies = vi.hoisted(() => ({
+ confirmModal: vi.fn(),
+ toastError: vi.fn(),
+ toastSuccess: vi.fn(),
+}));
const projectFilesMock = vi.hoisted(() => {
const baseEntries = [
{ isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
@@ -120,11 +138,14 @@ vi.mock('@/features/ExplorerTree', () => {
explorerTreeProps.current = props;
useImperativeHandle(ref, () => ({
focus: handleSpies.focus,
- getSelectedIds: vi.fn(() => []),
+ getFocusedId: vi.fn(() => null),
+ getSelectedIds: handleSpies.getSelectedIds,
deselect: vi.fn(),
+ resync: handleSpies.resync,
select: handleSpies.select,
setExpanded: handleSpies.setExpanded,
- startRenaming: vi.fn(),
+ startCreating: handleSpies.startCreating,
+ startRenaming: handleSpies.startRenaming,
}));
return <div data-testid="explorer-tree" />;
};
@@ -164,9 +185,21 @@ vi.mock('../useProjectFiles', () => ({
vi.mock('@/services/projectFile', () => ({
projectFileService: {
+ copyProjectFiles: fileOpsMock.copyProjectFiles,
+ createProjectDirectory: fileOpsMock.createProjectDirectory,
+ createProjectFile: fileOpsMock.createProjectFile,
listProjectDirectory: listProjectDirectoryMock,
+ moveProjectFiles: fileOpsMock.moveProjectFiles,
+ renameProjectFile: fileOpsMock.renameProjectFile,
searchProjectFiles: searchProjectFilesMock,
+ trashProjectFiles: fileOpsMock.trashProjectFiles,
},
+ refreshProjectFiles: fileOpsMock.refreshProjectFiles,
+}));
+
+vi.mock('@/utils/platform', () => ({
+ getPlatform: () => 'Mac OS',
+ isMacOS: () => true,
}));
vi.mock('@/store/chat', () => ({
@@ -187,12 +220,15 @@ vi.mock('antd', async (importOriginal) => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string) => key,
+ t: (key: string, options?: Record<string, unknown>) =>
+ options ? `${key} ${JSON.stringify(options)}` : key,
}),
}));
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
+ confirmModal: uiSpies.confirmModal,
+ toast: { error: uiSpies.toastError, success: uiSpies.toastSuccess },
ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
<button title={title} type={'button'} onClick={onClick} />
),
@@ -273,6 +309,16 @@ beforeEach(() => {
handleSpies.focus.mockClear();
handleSpies.select.mockClear();
handleSpies.setExpanded.mockClear();
+ handleSpies.getSelectedIds.mockReset();
+ handleSpies.getSelectedIds.mockReturnValue([]);
+ handleSpies.resync.mockClear();
+ handleSpies.startCreating.mockClear();
+ handleSpies.startRenaming.mockClear();
+ for (const mock of Object.values(fileOpsMock)) mock.mockReset();
+ fileOpsMock.refreshProjectFiles.mockResolvedValue(undefined);
+ uiSpies.confirmModal.mockReset();
+ uiSpies.toastError.mockReset();
+ uiSpies.toastSuccess.mockReset();
messageSpy.warning.mockClear();
openLocalFileMock.mockClear();
listProjectDirectoryMock.mockReset();
@@ -436,26 +482,81 @@ describe('Files — reveal request integration', () => {
expect(getContextMenuItems(dirtyNode).map((item) => item.key)).toEqual([
'open',
- 'divider-reveal',
+ 'divider-show-in-system',
'show-in-system',
'show-in-review',
- 'divider-copy',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
'copy-absolute-path',
'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
]);
expect(getContextMenuItems(cleanFolderNode).map((item) => item.key)).toEqual([
- 'open',
- 'divider-reveal',
+ 'new-file',
+ 'new-folder',
+ 'divider-open-in-system',
+ 'open-in-system',
'show-in-system',
- 'divider-copy',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
'copy-absolute-path',
'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
]);
expect(getContextMenuItems(ignoredNode).map((item) => item.key)).not.toContain(
'show-in-review',
);
});
+ it('keeps create and refresh inside the trailing "…" menu', async () => {
+ render(<Files workingDirectory="/repo" />);
+
+ // Neither "New" nor refresh is its own header button; both sit in "…".
+ expect(screen.queryByTitle('workingPanel.files.actions.refresh')).toBeNull();
+ expect(screen.queryByTitle('workingPanel.files.actions.new')).toBeNull();
+ const more = screen.getByTitle('workingPanel.files.actions.more').parentElement!;
+ expect(within(more).getByText('workingPanel.files.actions.newFile')).toBeTruthy();
+ expect(within(more).getByText('workingPanel.files.actions.newFolder')).toBeTruthy();
+ expect(within(more).getByText('workingPanel.files.actions.refresh')).toBeTruthy();
+
+ fireEvent.click(screen.getByText('workingPanel.files.actions.refresh'));
+ await waitFor(() =>
+ expect(fileOpsMock.refreshProjectFiles).toHaveBeenCalledWith(undefined, '/repo'),
+ );
+
+ fireEvent.click(screen.getByText('workingPanel.files.actions.newFolder'));
+ expect(handleSpies.startCreating).toHaveBeenCalledWith('\0project-root', 'folder');
+ });
+
+ it('hands every tree operation to ExplorerTree', () => {
+ render(<Files workingDirectory="/repo" />);
+ for (const prop of [
+ 'canDrag',
+ 'canDrop',
+ 'canRename',
+ 'getBlankContextMenuItems',
+ 'onCommitCreate',
+ 'onCommitRename',
+ 'onMove',
+ 'onTreeKeyDown',
+ 'validateName',
+ ]) {
+ expect(explorerTreeProps.current?.[prop]).toBeTypeOf('function');
+ }
+ });
+
it('does not offer a publish action in the open-source build', () => {
const previousLab = useUserStore.getState().preference.lab;
useUserStore.setState({
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/useCollapsedDirectoryChildren.test.ts b/src/features/Conversation/WorkingSidebar/Files/__tests__/useCollapsedDirectoryChildren.test.ts
new file mode 100644
index 00000000000..03f8d5f8944
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/useCollapsedDirectoryChildren.test.ts
@@ -0,0 +1,84 @@
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { projectFileService } from '@/services/projectFile';
+
+import {
+ selectCollapsedChildren,
+ useCollapsedDirectoryChildren,
+} from '../useCollapsedDirectoryChildren';
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { listProjectDirectory: vi.fn() },
+}));
+
+const ROOT = '/repo';
+
+const dir = (relativePath: string, collapsed = false): ProjectFileIndexEntry => ({
+ collapsed: collapsed || undefined,
+ isDirectory: true,
+ name: relativePath.replace(/\/$/, '').split('/').pop()!,
+ path: `${ROOT}/${relativePath.replace(/\/$/, '')}`,
+ relativePath,
+});
+
+const file = (relativePath: string): ProjectFileIndexEntry => ({
+ isDirectory: false,
+ name: relativePath.split('/').pop()!,
+ path: `${ROOT}/${relativePath}`,
+ relativePath,
+});
+
+const listDirectory = vi.mocked(projectFileService.listProjectDirectory);
+
+describe('selectCollapsedChildren', () => {
+ it('keeps children of collapsed directories, including nested listed ones', () => {
+ const entries = [dir('node_modules/', true)];
+ const children = [dir('node_modules/pkg/', true), file('node_modules/pkg/index.js')];
+
+ expect(selectCollapsedChildren(entries, children)).toEqual(children);
+ });
+
+ it('drops children the index already lists or whose parent is no longer collapsed', () => {
+ const entries = [dir('src/'), dir('src/hooks/'), file('src/hooks/index.ts')];
+ const children = [file('src/hooks/index.ts'), file('src/hooks/stale.ts')];
+
+ expect(selectCollapsedChildren(entries, children)).toEqual([]);
+ });
+});
+
+describe('useCollapsedDirectoryChildren', () => {
+ beforeEach(() => {
+ listDirectory.mockReset();
+ });
+
+ it('does not duplicate a file pasted into a new empty folder once the index lists it', async () => {
+ // A new empty folder is indexed as collapsed, so expanding it lists it on demand.
+ listDirectory.mockResolvedValueOnce({ entries: [], truncated: false } as any);
+ const { result, rerender } = renderHook(
+ ({ entries }) =>
+ useCollapsedDirectoryChildren({
+ entries,
+ expandedIds: ['src/', 'src/hooks/'],
+ projectRoot: ROOT,
+ }),
+ { initialProps: { entries: [dir('src/'), dir('src/hooks/', true)] } },
+ );
+ await waitFor(() => expect(listDirectory).toHaveBeenCalledTimes(1));
+
+ // Paste writes src/hooks/index.ts: the listing is re-read, and the refreshed
+ // index now lists the folder (no longer collapsed) together with the file.
+ listDirectory.mockResolvedValueOnce({
+ entries: [file('src/hooks/index.ts')],
+ truncated: false,
+ } as any);
+ act(() => result.current.invalidate());
+ await waitFor(() => expect(listDirectory).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current.children).toHaveLength(1));
+
+ rerender({ entries: [dir('src/'), dir('src/hooks/'), file('src/hooks/index.ts')] });
+
+ expect(result.current.children).toEqual([]);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileClipboard.ts b/src/features/Conversation/WorkingSidebar/Files/fileClipboard.ts
new file mode 100644
index 00000000000..f13af3f2735
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileClipboard.ts
@@ -0,0 +1,34 @@
+import { create } from 'zustand';
+
+export interface FileClipboardItem {
+ isDirectory: boolean;
+ name: string;
+ path: string;
+}
+
+export interface FileClipboard {
+ items: FileClipboardItem[];
+ mode: 'copy' | 'cut';
+ /** Device + project root the items were taken from; paste only works in the same scope. */
+ scopeKey: string;
+}
+
+interface FileClipboardStore {
+ clear: () => void;
+ clipboard?: FileClipboard;
+ set: (clipboard: FileClipboard) => void;
+}
+
+export const getFileClipboardScopeKey = (deviceId: string | undefined, root: string) =>
+ `${deviceId ?? 'local'}\0${root}`;
+
+/**
+ * In-app clipboard for the Files tree's copy / cut / paste. Kept outside the
+ * panel so it survives switching sidebar tabs, and scoped per device + project
+ * so a path is never pasted onto a different machine.
+ */
+export const useFileClipboardStore = create<FileClipboardStore>()((set) => ({
+ clear: () => set({ clipboard: undefined }),
+ clipboard: undefined,
+ set: (clipboard) => set({ clipboard }),
+}));
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.test.ts
new file mode 100644
index 00000000000..1b1324c0f25
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.test.ts
@@ -0,0 +1,207 @@
+import type { TFunction } from 'i18next';
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildFileContextMenu, type FileMenuEnv, type FileMenuTarget } from './fileContextMenu';
+
+const t = ((key: string, options?: Record<string, unknown>) =>
+ options?.trash ? `${key}(${options.trash})` : key) as unknown as TFunction<'chat'>;
+
+const localEnv: FileMenuEnv = {
+ canPaste: true,
+ canPublish: false,
+ canUseTerminal: true,
+ isRemote: false,
+ trashName: 'Trash',
+};
+const remoteEnv: FileMenuEnv = { ...localEnv, canUseTerminal: false, isRemote: true };
+
+const file: FileMenuTarget = { isDeleted: false, isDirty: false, kind: 'file' };
+const folder: FileMenuTarget = { isDeleted: false, isDirty: false, kind: 'folder' };
+const root: FileMenuTarget = { kind: 'root' };
+
+const keys = (target: FileMenuTarget, env: FileMenuEnv) =>
+ buildFileContextMenu(target, env, vi.fn(), t).map((item) => item?.key);
+
+describe('buildFileContextMenu', () => {
+ it('gives every entry both a web icon and a native SF Symbol', () => {
+ const targets: FileMenuTarget[] = [
+ file,
+ folder,
+ root,
+ { isDeleted: false, isDirty: true, kind: 'file' },
+ { isDeleted: true, isDirty: true, kind: 'file' },
+ ];
+ for (const env of [localEnv, remoteEnv, { ...localEnv, canPublish: true }]) {
+ for (const target of targets) {
+ const entries = buildFileContextMenu(target, env, vi.fn(), t).filter(
+ (item) => item && item.type !== 'divider',
+ );
+ expect(entries.length).toBeGreaterThan(0);
+ for (const entry of entries) {
+ expect(entry, String(entry?.key)).toHaveProperty('icon');
+ expect((entry as { icon?: unknown }).icon, String(entry?.key)).toBeTruthy();
+ expect((entry as { sfSymbol?: string }).sfSymbol, String(entry?.key)).toBeTruthy();
+ }
+ }
+ }
+ });
+
+ it('builds the local file menu', () => {
+ expect(keys(file, localEnv)).toEqual([
+ 'open',
+ 'divider-show-in-system',
+ 'show-in-system',
+ 'open-in-terminal',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
+ ]);
+ });
+
+ it('builds the local folder menu with create entries and "Open in System"', () => {
+ const items = buildFileContextMenu(folder, localEnv, vi.fn(), t);
+ expect(items.map((item) => item?.key)).toEqual([
+ 'new-file',
+ 'new-folder',
+ 'divider-open-in-system',
+ 'open-in-system',
+ 'show-in-system',
+ 'open-in-terminal',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
+ ]);
+ // A folder no longer says "Open File".
+ expect(items.find((item) => item?.key === 'open-in-system')).toMatchObject({
+ label: 'workingPanel.files.actions.openInSystem',
+ });
+ expect(items.map((item) => item?.key)).not.toContain('open');
+ });
+
+ it('builds the root / blank-area menu', () => {
+ expect(keys(root, localEnv)).toEqual([
+ 'new-file',
+ 'new-folder',
+ 'divider-paste',
+ 'paste',
+ 'divider-refresh',
+ 'refresh',
+ 'collapse-all',
+ 'divider-show-in-system',
+ 'show-in-system',
+ 'open-in-terminal',
+ 'copy-absolute-path',
+ ]);
+ });
+
+ it('keeps every file operation on a remote device but drops OS-level entries', () => {
+ expect(keys(file, remoteEnv)).toEqual([
+ 'open',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
+ ]);
+ expect(keys(folder, remoteEnv)).toEqual([
+ 'new-file',
+ 'new-folder',
+ 'divider-cut',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ 'divider-rename',
+ 'rename',
+ 'trash',
+ ]);
+ expect(keys(root, remoteEnv)).toEqual([
+ 'new-file',
+ 'new-folder',
+ 'divider-paste',
+ 'paste',
+ 'divider-refresh',
+ 'refresh',
+ 'collapse-all',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ ]);
+ });
+
+ it('hides the terminal entry when the in-app terminal is unavailable', () => {
+ expect(keys(folder, { ...localEnv, canUseTerminal: false })).not.toContain('open-in-terminal');
+ });
+
+ it('offers publish and review only when they apply', () => {
+ expect(keys({ ...file, isDirty: true }, { ...localEnv, canPublish: true })).toEqual(
+ expect.arrayContaining(['publish', 'show-in-review']),
+ );
+ expect(keys(file, localEnv)).not.toContain('show-in-review');
+ });
+
+ it('leaves only path and review entries on a row git reports deleted', () => {
+ expect(keys({ isDeleted: true, isDirty: true, kind: 'file' }, localEnv)).toEqual([
+ 'show-in-review',
+ 'divider-copy-absolute-path',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ ]);
+ });
+
+ it('disables paste when the clipboard is empty and names the platform trash', () => {
+ const items = buildFileContextMenu(file, { ...localEnv, canPaste: false }, vi.fn(), t);
+ expect(items.find((item) => item?.key === 'paste')).toMatchObject({ disabled: true });
+ expect(items.find((item) => item?.key === 'trash')).toMatchObject({
+ danger: true,
+ label: 'workingPanel.files.actions.moveToTrash(Trash)',
+ });
+ });
+
+ it('runs the matching action on click', () => {
+ const run = vi.fn();
+ const items = buildFileContextMenu(folder, localEnv, run, t);
+ for (const item of items) {
+ if (item && 'onClick' in item && item.onClick) (item.onClick as () => void)();
+ }
+ expect(run.mock.calls.map(([action]) => action)).toEqual([
+ 'newFile',
+ 'newFolder',
+ 'openInSystem',
+ 'revealInSystem',
+ 'openInTerminal',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'duplicate',
+ 'copyPath',
+ 'copyRelativePath',
+ 'rename',
+ 'trash',
+ ]);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx
new file mode 100644
index 00000000000..344bf485103
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx
@@ -0,0 +1,225 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
+import type { TFunction } from 'i18next';
+import type { LucideIcon } from 'lucide-react';
+import {
+ AppWindowIcon,
+ ClipboardPasteIcon,
+ CopyIcon,
+ CopyPlusIcon,
+ FilePlusIcon,
+ FileTextIcon,
+ FolderPlusIcon,
+ FolderSearchIcon,
+ FoldVerticalIcon,
+ GitCompareArrowsIcon,
+ LinkIcon,
+ PenLineIcon,
+ RotateCwIcon,
+ ScissorsIcon,
+ Share2Icon,
+ SquareTerminalIcon,
+ Trash2Icon,
+} from 'lucide-react';
+
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
+
+/** What was right-clicked: a file or folder row, or the project root / blank area. */
+export type FileMenuTarget =
+ | { kind: 'root' }
+ | {
+ /** Git reports it deleted: the path no longer exists on disk. */
+ isDeleted: boolean;
+ isDirty: boolean;
+ kind: 'file' | 'folder';
+ };
+
+export interface FileMenuEnv {
+ /** Paste has something to paste in this scope. */
+ canPaste: boolean;
+ /** Publish is offered for this file (cloud, HTML only). */
+ canPublish: boolean;
+ /** The in-app terminal is available (desktop, local workspace). */
+ canUseTerminal: boolean;
+ isRemote: boolean;
+ /** Platform name of the trash, already localized ("Trash" / "Recycle Bin"). */
+ trashName: string;
+}
+
+export type FileMenuAction =
+ | 'collapseAll'
+ | 'copy'
+ | 'copyPath'
+ | 'copyRelativePath'
+ | 'cut'
+ | 'duplicate'
+ | 'newFile'
+ | 'newFolder'
+ | 'open'
+ | 'openInSystem'
+ | 'openInTerminal'
+ | 'paste'
+ | 'publish'
+ | 'refresh'
+ | 'rename'
+ | 'revealInSystem'
+ | 'showInReview'
+ | 'trash';
+
+type Item = Exclude<NativeContextMenuItem, null>;
+
+/**
+ * Every entry carries both glyphs: `sfSymbol` for the native macOS menu and a
+ * lucide `icon` for the web menu (and non-mac desktops), so the two stay alike.
+ */
+const ACTION_ICONS: Record<FileMenuAction, { icon: LucideIcon; sfSymbol: SFSymbol }> = {
+ collapseAll: { icon: FoldVerticalIcon, sfSymbol: 'rectangle.compress.vertical' },
+ copy: { icon: CopyIcon, sfSymbol: 'doc.on.doc' },
+ copyPath: { icon: LinkIcon, sfSymbol: 'link' },
+ copyRelativePath: { icon: LinkIcon, sfSymbol: 'link' },
+ cut: { icon: ScissorsIcon, sfSymbol: 'scissors' },
+ duplicate: { icon: CopyPlusIcon, sfSymbol: 'plus.square.on.square' },
+ newFile: { icon: FilePlusIcon, sfSymbol: 'doc.badge.plus' },
+ newFolder: { icon: FolderPlusIcon, sfSymbol: 'folder.badge.plus' },
+ open: { icon: FileTextIcon, sfSymbol: 'doc' },
+ openInSystem: { icon: AppWindowIcon, sfSymbol: 'arrow.up.forward.app' },
+ openInTerminal: { icon: SquareTerminalIcon, sfSymbol: 'terminal' },
+ paste: { icon: ClipboardPasteIcon, sfSymbol: 'doc.on.clipboard' },
+ publish: { icon: Share2Icon, sfSymbol: 'square.and.arrow.up' },
+ refresh: { icon: RotateCwIcon, sfSymbol: 'arrow.clockwise' },
+ rename: { icon: PenLineIcon, sfSymbol: 'pencil' },
+ revealInSystem: { icon: FolderSearchIcon, sfSymbol: 'folder' },
+ showInReview: { icon: GitCompareArrowsIcon, sfSymbol: 'arrow.triangle.branch' },
+ trash: { icon: Trash2Icon, sfSymbol: 'trash' },
+};
+
+const joinGroups = (groups: Item[][]): NativeContextMenuItem[] => {
+ const items: NativeContextMenuItem[] = [];
+ for (const group of groups) {
+ if (group.length === 0) continue;
+ if (items.length > 0) items.push({ key: `divider-${group[0].key}`, type: 'divider' });
+ items.push(...group);
+ }
+ return items;
+};
+
+/**
+ * Context menu of the Files tree, per target (file / folder / root and blank
+ * area) and per host (local desktop vs remote device). OS-level entries
+ * (reveal, open in system, terminal) only exist for a local workspace; a
+ * remote device keeps every file operation and reports at run time when its
+ * client can't perform one. Keys stay stable for tests and telemetry.
+ */
+export const buildFileContextMenu = (
+ target: FileMenuTarget,
+ env: FileMenuEnv,
+ run: (action: FileMenuAction) => void,
+ t: TFunction<'chat'>,
+): NativeContextMenuItem[] => {
+ const item = (key: string, action: FileMenuAction, label: string, extra?: Partial<Item>) => {
+ const { icon: IconComponent, sfSymbol } = ACTION_ICONS[action];
+ return {
+ icon: <IconComponent size={14} />,
+ key,
+ label,
+ onClick: () => run(action),
+ sfSymbol,
+ ...extra,
+ } as Item;
+ };
+ const local = !env.isRemote;
+
+ const copyPathItem = item(
+ 'copy-absolute-path',
+ 'copyPath',
+ t('workingPanel.files.copyAbsolutePath'),
+ );
+ const pasteItem = item('paste', 'paste', t('workingPanel.files.actions.paste'), {
+ disabled: !env.canPaste,
+ } as Partial<Item>);
+ const newItems = [
+ item('new-file', 'newFile', t('workingPanel.files.actions.newFile')),
+ item('new-folder', 'newFolder', t('workingPanel.files.actions.newFolder')),
+ ];
+
+ if (target.kind === 'root') {
+ return joinGroups([
+ newItems,
+ [pasteItem],
+ [
+ item('refresh', 'refresh', t('workingPanel.files.actions.refresh')),
+ item('collapse-all', 'collapseAll', t('workingPanel.files.collapseAll')),
+ ],
+ [
+ ...(local
+ ? [item('show-in-system', 'revealInSystem', t('workingPanel.files.showInSystem'))]
+ : []),
+ ...(local && env.canUseTerminal
+ ? [
+ item(
+ 'open-in-terminal',
+ 'openInTerminal',
+ t('workingPanel.files.actions.openInTerminal'),
+ ),
+ ]
+ : []),
+ copyPathItem,
+ ],
+ ]);
+ }
+
+ const isFolder = target.kind === 'folder';
+ const reviewItems = target.isDirty
+ ? [item('show-in-review', 'showInReview', t('workingPanel.files.showInReview'))]
+ : [];
+ const pathItems = [
+ copyPathItem,
+ item('copy-relative-path', 'copyRelativePath', t('workingPanel.files.copyRelativePath')),
+ ];
+
+ // Nothing exists on disk to open, move or delete: keep the path and review.
+ if (target.isDeleted) return joinGroups([reviewItems, pathItems]);
+
+ const openGroup = isFolder
+ ? newItems
+ : [
+ item('open', 'open', t('workingPanel.files.open')),
+ ...(env.canPublish
+ ? [item('publish', 'publish', t('workingPanel.localFile.publish.action'))]
+ : []),
+ ];
+ const systemGroup = [
+ ...(local && isFolder
+ ? [item('open-in-system', 'openInSystem', t('workingPanel.files.actions.openInSystem'))]
+ : []),
+ ...(local
+ ? [item('show-in-system', 'revealInSystem', t('workingPanel.files.showInSystem'))]
+ : []),
+ ...(local && env.canUseTerminal
+ ? [item('open-in-terminal', 'openInTerminal', t('workingPanel.files.actions.openInTerminal'))]
+ : []),
+ ...reviewItems,
+ ];
+
+ return joinGroups([
+ openGroup,
+ systemGroup,
+ [
+ item('cut', 'cut', t('workingPanel.files.actions.cut')),
+ item('copy', 'copy', t('workingPanel.files.actions.copy')),
+ pasteItem,
+ item('duplicate', 'duplicate', t('workingPanel.files.actions.duplicate')),
+ ],
+ pathItems,
+ [
+ item('rename', 'rename', t('workingPanel.files.actions.rename')),
+ item(
+ 'trash',
+ 'trash',
+ t('workingPanel.files.actions.moveToTrash', { trash: env.trashName }),
+ {
+ danger: true,
+ } as Partial<Item>,
+ ),
+ ],
+ ]);
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.test.ts
new file mode 100644
index 00000000000..02ef89ea59a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from 'vitest';
+
+import { getFreeCopyName, validateFileName } from './fileNameValidation';
+
+const siblings = [
+ { isDirectory: false, name: 'index.ts' },
+ { isDirectory: true, name: 'src' },
+];
+
+const create = (name: string, caseInsensitive = false) =>
+ validateFileName({ allowNested: true, caseInsensitive, name, siblings });
+const rename = (name: string, currentName = 'index.ts', caseInsensitive = false) =>
+ validateFileName({ allowNested: false, caseInsensitive, currentName, name, siblings });
+
+describe('validateFileName', () => {
+ it('accepts ordinary names and dotfiles', () => {
+ expect(create('notes.md')).toBeNull();
+ expect(create('.env.local')).toBeNull();
+ expect(rename('main.ts')).toBeNull();
+ });
+
+ it('rejects empty and whitespace-only names', () => {
+ expect(create('')).toBe('empty');
+ expect(create(' ')).toBe('empty');
+ expect(rename('')).toBe('empty');
+ });
+
+ it('rejects leading or trailing spaces instead of trimming them silently', () => {
+ expect(create(' notes.md')).toBe('whitespace');
+ expect(rename('main.ts ')).toBe('whitespace');
+ });
+
+ it('rejects the reserved . and .. names, also as a nested segment', () => {
+ expect(create('.')).toBe('reserved');
+ expect(rename('..')).toBe('reserved');
+ expect(create('a/../b.ts')).toBe('reserved');
+ });
+
+ it('rejects characters the file host refuses', () => {
+ for (const name of ['a<b', 'a>b', 'a:b', 'a"b', 'a|b', 'a?b', 'a*b', 'a\\b', 'a\u0001b']) {
+ expect(create(name)).toBe('invalidChars');
+ }
+ });
+
+ it('lets a new entry name a nested path but never a rename', () => {
+ expect(create('docs/guide/intro.md')).toBeNull();
+ expect(rename('docs/intro.md')).toBe('invalidChars');
+ expect(create('docs//intro.md')).toBe('empty');
+ expect(create('docs/')).toBe('empty');
+ });
+
+ it('rejects names over 255 UTF-8 bytes', () => {
+ expect(create('a'.repeat(255))).toBeNull();
+ expect(create('a'.repeat(256))).toBe('tooLong');
+ // 86 × 3-byte characters = 258 bytes
+ expect(create('文'.repeat(86))).toBe('tooLong');
+ });
+
+ it('rejects a name already taken in the folder', () => {
+ expect(create('index.ts')).toBe('exists');
+ expect(create('src')).toBe('exists');
+ expect(rename('src')).toBe('exists');
+ });
+
+ it('compares case-insensitively only where the file system does', () => {
+ expect(create('INDEX.ts', false)).toBeNull();
+ expect(create('INDEX.ts', true)).toBe('exists');
+ });
+
+ it('treats the current name and a case-only rename as no clash', () => {
+ expect(rename('index.ts')).toBeNull();
+ expect(rename('Index.ts', 'index.ts', true)).toBeNull();
+ });
+
+ it('allows a nested new entry inside an existing folder but not through a file', () => {
+ expect(create('src/new.ts')).toBeNull();
+ expect(create('index.ts/new.ts')).toBe('exists');
+ });
+});
+
+describe('getFreeCopyName', () => {
+ it('keeps the name when it is free', () => {
+ expect(getFreeCopyName('a.ts', false, siblings, false)).toBe('a.ts');
+ });
+
+ it('numbers copies Finder-style, before the extension', () => {
+ expect(getFreeCopyName('index.ts', false, siblings, false)).toBe('index copy.ts');
+ expect(
+ getFreeCopyName(
+ 'index.ts',
+ false,
+ [...siblings, { isDirectory: false, name: 'index copy.ts' }],
+ false,
+ ),
+ ).toBe('index copy 2.ts');
+ });
+
+ it('never splits a folder name at a dot', () => {
+ expect(getFreeCopyName('v1.2', true, [{ isDirectory: true, name: 'v1.2' }], false)).toBe(
+ 'v1.2 copy',
+ );
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.ts b/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.ts
new file mode 100644
index 00000000000..ce94d316451
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileNameValidation.ts
@@ -0,0 +1,97 @@
+export type FileNameError =
+ 'empty' | 'exists' | 'invalidChars' | 'reserved' | 'tooLong' | 'whitespace';
+
+export interface SiblingEntry {
+ isDirectory: boolean;
+ name: string;
+}
+
+export interface ValidateFileNameParams {
+ /**
+ * New entries may name a nested path (`a/b/c.ts`), which creates the missing
+ * folders on the way, as in VS Code. Renames never may.
+ */
+ allowNested: boolean;
+ /** macOS and Windows file systems ignore case, so `A.ts` collides with `a.ts`. */
+ caseInsensitive: boolean;
+ /** The entry's current name, when renaming it. */
+ currentName?: string;
+ name: string;
+ /** Entries already in the target folder. */
+ siblings: SiblingEntry[];
+}
+
+// Same set the file host refuses on rename, so a name that passes here is not
+// bounced by the server for its characters.
+// eslint-disable-next-line no-control-regex
+const INVALID_CHARS = /["*:<>?\\|\u0000-\u001F]/;
+const MAX_NAME_BYTES = 255;
+const textEncoder = new TextEncoder();
+
+const checkSegment = (segment: string): FileNameError | null => {
+ if (segment.trim() === '') return 'empty';
+ if (segment !== segment.trim()) return 'whitespace';
+ if (segment === '.' || segment === '..') return 'reserved';
+ if (INVALID_CHARS.test(segment)) return 'invalidChars';
+ if (textEncoder.encode(segment).length > MAX_NAME_BYTES) return 'tooLong';
+ return null;
+};
+
+/**
+ * Client-side check for a name typed into the Files tree (new file / folder,
+ * rename). Returns `null` for an acceptable name. Renaming to the current name
+ * is acceptable too: the tree treats it as a cancel.
+ */
+export const validateFileName = ({
+ allowNested,
+ caseInsensitive,
+ currentName,
+ name,
+ siblings,
+}: ValidateFileNameParams): FileNameError | null => {
+ if (currentName !== undefined && name === currentName) return null;
+ if (name.trim() === '') return 'empty';
+ if (name !== name.trim()) return 'whitespace';
+
+ if (name.includes('/') && !allowNested) return 'invalidChars';
+ const segments = allowNested ? name.split('/') : [name];
+ for (const segment of segments) {
+ const error = checkSegment(segment);
+ if (error) return error;
+ }
+
+ const fold = (value: string) => (caseInsensitive ? value.toLowerCase() : value);
+ const [first] = segments;
+ // A case-only rename (a.ts → A.ts) is the same entry, not a clash.
+ if (currentName !== undefined && fold(first) === fold(currentName)) return null;
+
+ const clash = siblings.find((sibling) => fold(sibling.name) === fold(first));
+ if (!clash) return null;
+ // `src/new.ts` may go into an existing `src` folder; anything else clashes.
+ if (segments.length > 1 && clash.isDirectory) return null;
+ return 'exists';
+};
+
+/**
+ * Finder-style free name for a copy landing in a folder that already holds
+ * `name`: `name copy.ext`, then `name copy 2.ext`, …
+ */
+export const getFreeCopyName = (
+ name: string,
+ isDirectory: boolean,
+ siblings: SiblingEntry[],
+ caseInsensitive: boolean,
+): string => {
+ const fold = (value: string) => (caseInsensitive ? value.toLowerCase() : value);
+ const taken = new Set(siblings.map((sibling) => fold(sibling.name)));
+ if (!taken.has(fold(name))) return name;
+
+ const dot = isDirectory ? -1 : name.lastIndexOf('.');
+ const stem = dot > 0 ? name.slice(0, dot) : name;
+ const ext = dot > 0 ? name.slice(dot) : '';
+ for (let index = 1; index < 10_000; index += 1) {
+ const candidate = `${stem} copy${index === 1 ? '' : ` ${index}`}${ext}`;
+ if (!taken.has(fold(candidate))) return candidate;
+ }
+ return `${stem} copy ${Date.now()}${ext}`;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.test.ts
new file mode 100644
index 00000000000..cef4ca4f9df
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyFileOpError } from './fileOpErrors';
+
+describe('classifyFileOpError', () => {
+ it('recognises a device without a trash', () => {
+ expect(
+ classifyFileOpError(new Error('This device does not support moving files to the trash')).kind,
+ ).toBe('trashUnsupported');
+ });
+
+ it('recognises a device client that predates the RPC', () => {
+ expect(classifyFileOpError(new Error('Unknown device RPC method: trashLocalFiles')).kind).toBe(
+ 'unsupported',
+ );
+ });
+
+ it('recognises an offline device', () => {
+ expect(classifyFileOpError(new Error('DEVICE_NOT_FOUND')).kind).toBe('offline');
+ expect(classifyFileOpError('Desktop offline').kind).toBe('offline');
+ });
+
+ it('passes any other host message through as the reason', () => {
+ expect(classifyFileOpError(new Error('EACCES: permission denied'))).toEqual({
+ kind: 'reason',
+ message: 'EACCES: permission denied',
+ });
+ expect(classifyFileOpError({ message: 'EEXIST' }).message).toBe('EEXIST');
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.ts b/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.ts
new file mode 100644
index 00000000000..d7d290bb4e8
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileOpErrors.ts
@@ -0,0 +1,33 @@
+export type FileOpErrorKind = 'offline' | 'reason' | 'trashUnsupported' | 'unsupported';
+
+export interface FileOpError {
+ kind: FileOpErrorKind;
+ /** The host's own message, used as the reason for `kind: 'reason'`. */
+ message: string;
+}
+
+// Mirrors TRASH_UNSUPPORTED_MESSAGE in @lobechat/device-control: a device
+// without a recoverable trash (the `lh connect` daemon) refuses to delete.
+const TRASH_UNSUPPORTED = 'does not support moving files to the trash';
+// A device whose client predates the RPC.
+const UNKNOWN_METHOD = 'Unknown device RPC method';
+const OFFLINE =
+ /DEVICE_NOT_FOUND|DEVICE_OFFLINE|device (?:is )?offline|desktop offline|not connected/i;
+
+const toMessage = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ if (error && typeof error === 'object' && 'message' in error) {
+ return String((error as { message: unknown }).message);
+ }
+ return String(error ?? '');
+};
+
+/** Sorts a failed file operation into the cases the Files panel words differently. */
+export const classifyFileOpError = (error: unknown): FileOpError => {
+ const message = toMessage(error);
+ if (message.includes(TRASH_UNSUPPORTED)) return { kind: 'trashUnsupported', message };
+ if (message.includes(UNKNOWN_METHOD)) return { kind: 'unsupported', message };
+ if (OFFLINE.test(message)) return { kind: 'offline', message };
+ return { kind: 'reason', message };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.test.ts
new file mode 100644
index 00000000000..845ecee29b1
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveFileTreeShortcut } from './fileTreeShortcuts';
+
+const key = (
+ k: string,
+ mods: Partial<Record<'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey', boolean>> = {},
+) => ({
+ altKey: false,
+ ctrlKey: false,
+ key: k,
+ metaKey: false,
+ shiftKey: false,
+ ...mods,
+});
+
+describe('resolveFileTreeShortcut', () => {
+ it('opens on Enter and deletes on Delete on every platform', () => {
+ for (const isMac of [true, false]) {
+ expect(resolveFileTreeShortcut(key('Enter'), isMac)).toBe('open');
+ expect(resolveFileTreeShortcut(key('Delete'), isMac)).toBe('delete');
+ }
+ });
+
+ it('deletes on ⌘⌫ on macOS only; a bare Backspace does nothing', () => {
+ expect(resolveFileTreeShortcut(key('Backspace', { metaKey: true }), true)).toBe('delete');
+ expect(resolveFileTreeShortcut(key('Backspace'), true)).toBeNull();
+ expect(resolveFileTreeShortcut(key('Backspace', { ctrlKey: true }), false)).toBeNull();
+ });
+
+ it('maps copy / cut / paste to ⌘ on macOS and Ctrl elsewhere', () => {
+ expect(resolveFileTreeShortcut(key('c', { metaKey: true }), true)).toBe('copy');
+ expect(resolveFileTreeShortcut(key('x', { metaKey: true }), true)).toBe('cut');
+ expect(resolveFileTreeShortcut(key('v', { metaKey: true }), true)).toBe('paste');
+ expect(resolveFileTreeShortcut(key('c', { ctrlKey: true }), false)).toBe('copy');
+ expect(resolveFileTreeShortcut(key('V', { ctrlKey: true }), false)).toBe('paste');
+ expect(resolveFileTreeShortcut(key('c', { ctrlKey: true }), true)).toBeNull();
+ expect(resolveFileTreeShortcut(key('c', { metaKey: true }), false)).toBeNull();
+ });
+
+ it('ignores F2 (the tree renames by itself) and modified or unrelated keys', () => {
+ expect(resolveFileTreeShortcut(key('F2'), true)).toBeNull();
+ expect(resolveFileTreeShortcut(key('Enter', { shiftKey: true }), true)).toBeNull();
+ expect(resolveFileTreeShortcut(key('c', { altKey: true, metaKey: true }), true)).toBeNull();
+ expect(resolveFileTreeShortcut(key('a'), true)).toBeNull();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.ts b/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.ts
new file mode 100644
index 00000000000..df52118dde4
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileTreeShortcuts.ts
@@ -0,0 +1,48 @@
+export type FileTreeShortcut = 'copy' | 'cut' | 'delete' | 'open' | 'paste';
+
+interface ShortcutKeyEvent {
+ altKey: boolean;
+ ctrlKey: boolean;
+ key: string;
+ metaKey: boolean;
+ shiftKey: boolean;
+}
+
+/**
+ * Maps a key press on a focused Files tree row to an operation. F2 (rename)
+ * and Escape are handled by the tree itself.
+ * - Enter opens, like a click (not rename: that is F2 here).
+ * - Delete, or ⌘⌫ on macOS, moves to the trash (after a confirmation).
+ * - ⌘C / ⌘X / ⌘V (Ctrl elsewhere) copy, cut and paste entries.
+ */
+export const resolveFileTreeShortcut = (
+ event: ShortcutKeyEvent,
+ isMac: boolean,
+): FileTreeShortcut | null => {
+ const mod = isMac ? event.metaKey : event.ctrlKey;
+ const otherMod = isMac ? event.ctrlKey : event.metaKey;
+ if (event.altKey || otherMod) return null;
+
+ if (!mod && !event.shiftKey) {
+ if (event.key === 'Enter') return 'open';
+ if (event.key === 'Delete') return 'delete';
+ return null;
+ }
+ if (!mod || event.shiftKey) return null;
+
+ if (isMac && event.key === 'Backspace') return 'delete';
+ switch (event.key.toLowerCase()) {
+ case 'c': {
+ return 'copy';
+ }
+ case 'x': {
+ return 'cut';
+ }
+ case 'v': {
+ return 'paste';
+ }
+ default: {
+ return null;
+ }
+ }
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileTreeStyle.ts b/src/features/Conversation/WorkingSidebar/Files/fileTreeStyle.ts
new file mode 100644
index 00000000000..0b52c6e1afb
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileTreeStyle.ts
@@ -0,0 +1,45 @@
+import { FOLDER_ICON_CSS } from '@/features/ExplorerTree';
+
+const IGNORED_FILE_OPACITY_CSS = `
+[data-item-git-status='ignored'] > :where(
+ [data-item-section='icon'],
+ [data-item-section='content'],
+ [data-item-section='decoration'],
+ [data-item-section='git']
+) {
+ opacity: 0.7;
+}`;
+
+// The selected fill already marks the current row. pierre still rings a row
+// that holds :focus-visible, and it grants that after programmatic focus too —
+// so a row we select and focus after create / duplicate / paste gets a stray
+// white outline. Drop the ring in every state; a row holding real keyboard
+// focus but not selected borrows the hover fill so arrowing stays visible.
+// Key the fill on :focus-visible, not data-item-focused: pierre keeps that
+// roving marker on a row (the root, initially) even while the tree is blurred,
+// which would leave a second, phantom highlight.
+const NO_FOCUS_RING_CSS = `
+[data-type='item'][data-item-focused='true']::before,
+[data-type='item']:focus-visible::before {
+ outline: none;
+}
+
+[data-type='item']:focus-visible:not([data-item-selected='true']) {
+ background-color: var(--trees-bg-muted);
+}`;
+
+// pierre sizes the name to its text and hides the flexible decoration spacer
+// while the rename input is open, so the git lane ("A", "M") slides in right
+// after the input, mid-row. Let the input take the spacer's place so the
+// status letter stays at the row's end, where every other row shows it.
+const RENAME_INPUT_FULL_WIDTH_CSS = `
+[data-item-section='content']:has([data-item-rename-input]) {
+ flex: 1 1 0;
+}`;
+
+export const FILE_TREE_UNSAFE_CSS = [
+ FOLDER_ICON_CSS,
+ NO_FOCUS_RING_CSS,
+ IGNORED_FILE_OPACITY_CSS,
+ RENAME_INPUT_FULL_WIDTH_CSS,
+].join('\n');
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index 9d453548a52..bdcf35df754 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -1,44 +1,40 @@
'use client';
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
-import { Center, copyToClipboard, Empty, Flexbox, Icon, stopPropagation } from '@lobehub/ui';
-import { ActionIcon, Button, DropdownMenu, Input, Spin, toast } from '@lobehub/ui/base-ui';
+import { Center, Empty, Flexbox, Icon, stopPropagation } from '@lobehub/ui';
+import { ActionIcon, Button, DropdownMenu, Input, Spin } from '@lobehub/ui/base-ui';
import type { GitStatusEntry } from '@pierre/trees';
import { createStaticStyles } from 'antd-style';
import {
CheckIcon,
ChevronDownIcon,
+ EllipsisIcon,
FileIcon,
+ FilePlusIcon,
+ FolderPlusIcon,
FolderTreeIcon,
FoldVerticalIcon,
GitCompareArrowsIcon,
ListFilterIcon,
+ RotateCwIcon,
SearchIcon,
XIcon,
} from 'lucide-react';
-import type { DragEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { startWorkspaceFileDrag } from '@/features/ChatInput/InputEditor/workspaceFileDragData';
import type { ExplorerTreeNode } from '@/features/ExplorerTree';
-import {
- ExplorerTree,
- FOLDER_ICON_CSS,
- getExplorerTreeStyleVars,
- HIDE_POINTER_FOCUS_RING_CSS,
-} from '@/features/ExplorerTree';
+import { ExplorerTree, getExplorerTreeStyleVars } from '@/features/ExplorerTree';
import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';
-import { usePublishWorkspaceHtmlFromFile } from '@/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile';
-import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
-import { localFileService } from '@/services/electron/localFileService';
import { projectFileService } from '@/services/projectFile';
-import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { filterProjectFileEntries, mergeMissingDeletedEntries } from './fileFilter';
+import { FILE_TREE_UNSAFE_CSS } from './fileTreeStyle';
import { isExcludedProjectFileEntry } from './fileVisibility';
+import { getAncestorIds, getParentRelativePath, PROJECT_ROOT_NODE_ID } from './treePaths';
import { useCollapsedDirectoryChildren } from './useCollapsedDirectoryChildren';
+import { useFileTreeActions } from './useFileTreeActions';
import { buildGitStatusEntries, useGitWorkingTreeFiles } from './useGitWorkingTreeFiles';
import { useProjectFiles } from './useProjectFiles';
@@ -95,26 +91,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
-
-const IGNORED_FILE_OPACITY_CSS = `
-[data-item-git-status='ignored'] > :where(
- [data-item-section='icon'],
- [data-item-section='content'],
- [data-item-section='decoration'],
- [data-item-section='git']
-) {
- opacity: 0.7;
-}`;
-const FILE_TREE_UNSAFE_CSS = [
- FOLDER_ICON_CSS,
- HIDE_POINTER_FOCUS_RING_CSS,
- IGNORED_FILE_OPACITY_CSS,
-].join('\n');
const FILE_SEARCH_DEBOUNCE_MS = 180;
const PROJECT_FILE_TREE_SEARCH_LIMIT = 200;
-// Relative file paths cannot contain NUL, so this synthetic id cannot collide with an indexed entry.
-const PROJECT_ROOT_NODE_ID = '\0project-root';
type FileViewMode = 'project' | 'changes';
@@ -123,13 +101,6 @@ const getProjectRootName = (root: string) => {
return normalizedRoot.split(/[\\/]/).pop() || root;
};
-const getParentRelativePath = (relativePath: string): string | null => {
- const cleaned = stripTrailingSlash(relativePath);
- const idx = cleaned.lastIndexOf('/');
- if (idx < 0) return null;
- return `${cleaned.slice(0, idx)}/`;
-};
-
const buildTreeNodes = (
entries: ProjectFileIndexEntry[],
rootName: string,
@@ -167,15 +138,6 @@ const buildIgnoredGitStatusEntries = (entries: ProjectFileIndexEntry[]): GitStat
const prefixGitStatusPaths = (entries: GitStatusEntry[], rootName: string): GitStatusEntry[] =>
entries.map((entry) => ({ ...entry, path: `${rootName}/${entry.path}` }));
-const getAncestorIds = (filePath: string): string[] => {
- const segments = filePath.split('/');
- const ancestors: string[] = [];
- for (let i = 1; i < segments.length; i++) {
- ancestors.push(segments.slice(0, i).join('/') + '/');
- }
- return ancestors;
-};
-
interface FilesSearchBarProps {
onClose: () => void;
onDebouncedChange: (query: string) => void;
@@ -231,7 +193,6 @@ FilesSearchBar.displayName = 'FilesSearchBar';
const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const { t } = useTranslation('chat');
- const isRemote = !!deviceId;
const { data, isLoading } = useProjectFiles(deviceId, workingDirectory);
const { data: gitFiles } = useGitWorkingTreeFiles(
deviceId,
@@ -261,7 +222,11 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
);
// The index delivers fully git-ignored folders as childless collapsed rows;
// their children stream in here as the user expands them.
- const { children: collapsedChildren, truncatedCount } = useCollapsedDirectoryChildren({
+ const {
+ children: collapsedChildren,
+ invalidate: invalidateCollapsedChildren,
+ truncatedCount,
+ } = useCollapsedDirectoryChildren({
deviceId,
entries,
expandedIds,
@@ -424,7 +389,6 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
}, [defaultExpandedIds, isFiltering]);
const revealRequest = useGlobalStore((s) => s.status.workingSidebarRevealRequest);
- const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);
useEffect(() => {
if (!revealRequest) return;
@@ -441,125 +405,59 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealRequest?.nonce, nodes]);
- const openLocalFile = useChatStore((s) => s.openLocalFile);
- const { canOfferFile, publishFile } = usePublishWorkspaceHtmlFromFile({
+ const clearDisplayFilter = useCallback(() => {
+ setSearchExpanded(false);
+ setDebouncedQuery('');
+ setViewMode('project');
+ setHideIgnored(false);
+ }, []);
+ const knownEntries = useMemo(
+ () => [...entries, ...collapsedChildren],
+ [collapsedChildren, entries],
+ );
+ const deletedPaths = useMemo(() => new Set(gitFiles?.deleted ?? []), [gitFiles?.deleted]);
+ const actions = useFileTreeActions({
+ deletedPaths,
deviceId,
- workingDirectory: projectRoot,
+ dirtyFilePaths,
+ expandedIds,
+ hasDisplayFilter,
+ invalidateCollapsedChildren,
+ knownEntries,
+ nodes,
+ onClearDisplayFilter: clearDisplayFilter,
+ onCollapseAll: handleCollapseAll,
+ projectRoot,
+ treeRef,
+ workingDirectory,
});
- const openNode = useCallback(
- (node: ExplorerTreeNode<ProjectFileIndexEntry>) => {
- if (!node.data) return;
- if (node.isFolder) {
- if (isRemote) return;
-
- void localFileService.openLocalFileOrFolder(node.data.path, true);
- return;
- }
- openLocalFile({ deviceId, filePath: node.data.path, workingDirectory: projectRoot });
- },
- [deviceId, isRemote, openLocalFile, projectRoot],
- );
-
- const handleNodeClick = useCallback(
- (node: ExplorerTreeNode<ProjectFileIndexEntry>) => {
- // Folders expand via the tree; files open in the preview panel.
- if (node.isFolder) return;
- openNode(node);
- },
- [openNode],
- );
-
- // Dragging a row into the chat input inserts a `<localFile />` mention instead
- // of uploading it. We stamp a custom MIME on dragstart; the input's
- // useWorkspaceFileDrop reads it. The panel has no onMove, so overriding the
- // drag effect here can't disturb any internal reorder behaviour.
- const handleNodeDragStart = useCallback(
- (node: ExplorerTreeNode<ProjectFileIndexEntry>, event: DragEvent<HTMLElement>) => {
- if (!node.data) return;
- startWorkspaceFileDrag(event, {
- isDirectory: !!node.isFolder,
- name: node.data.name,
- path: node.data.path,
- });
- },
- [],
- );
-
- const getContextMenuItems = useCallback(
- (node: ExplorerTreeNode<ProjectFileIndexEntry>): NativeContextMenuItem[] => {
- if (!node.data) return [];
-
- const { path, relativePath } = node.data;
- const isDirty = dirtyFilePaths.has(relativePath);
- const items: NativeContextMenuItem[] = [];
-
- if (!isRemote) {
- items.push({
- key: 'open',
- label: t('workingPanel.files.open'),
- onClick: () => openNode(node),
- });
- }
-
- if (canOfferFile(path, !!node.isFolder)) {
- items.push({
- key: 'publish',
- label: t('workingPanel.localFile.publish.action'),
- sfSymbol: 'square.and.arrow.up',
- onClick: () => {
- void publishFile(path);
- },
- });
- }
-
- if (!isRemote) {
- items.push(
- { key: 'divider-reveal', type: 'divider' as const },
- {
- key: 'show-in-system',
- label: t('workingPanel.files.showInSystem'),
- onClick: () => void localFileService.openFileFolder(path),
- },
- );
- }
-
- if (isDirty) {
- items.push({
- key: 'show-in-review',
- label: t('workingPanel.files.showInReview'),
- onClick: () => openWorkingSidebar('review'),
- });
- }
-
- if (items.length > 0) {
- items.push({ key: 'divider-copy', type: 'divider' as const });
- }
-
- items.push(
- {
- key: 'copy-absolute-path',
- label: t('workingPanel.files.copyAbsolutePath'),
- onClick: async () => {
- await copyToClipboard(path);
- toast.success(t('workingPanel.review.copied'));
- },
- sfSymbol: 'doc.on.doc',
- },
- {
- key: 'copy-relative-path',
- label: t('workingPanel.files.copyRelativePath'),
- onClick: async () => {
- await copyToClipboard(relativePath);
- toast.success(t('workingPanel.review.copied'));
- },
- sfSymbol: 'doc.on.doc',
- },
- );
-
- return items;
- },
- [canOfferFile, dirtyFilePaths, isRemote, openNode, openWorkingSidebar, publishFile, t],
+ // Tree-level actions live behind "…" so the header keeps room: creating at
+ // the project root, then refresh.
+ const moreItems = useMemo(
+ () => [
+ {
+ icon: <FilePlusIcon size={14} />,
+ key: 'new-file',
+ label: t('workingPanel.files.actions.newFile'),
+ onClick: () => actions.startCreateFromHeader('file'),
+ },
+ {
+ icon: <FolderPlusIcon size={14} />,
+ key: 'new-folder',
+ label: t('workingPanel.files.actions.newFolder'),
+ onClick: () => actions.startCreateFromHeader('folder'),
+ },
+ { key: 'divider-refresh', type: 'divider' as const },
+ {
+ disabled: actions.refreshing,
+ icon: <RotateCwIcon size={14} />,
+ key: 'refresh',
+ label: t('workingPanel.files.actions.refresh'),
+ onClick: () => void actions.refresh(),
+ },
+ ],
+ [actions, t],
);
const isEmpty = displayEntries.length === 0;
@@ -588,7 +486,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
<Button
icon={viewMode === 'project' ? FolderTreeIcon : GitCompareArrowsIcon}
size={'small'}
- style={{ maxWidth: 'calc(100% - 84px)' }}
+ style={{ maxWidth: 'calc(100% - 108px)' }}
title={t('workingPanel.files.views.title')}
type={'text'}
>
@@ -626,12 +524,20 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
title={t('workingPanel.files.collapseAll')}
onClick={handleCollapseAll}
/>
+ <DropdownMenu items={moreItems} placement={'bottomRight'}>
+ <ActionIcon
+ icon={EllipsisIcon}
+ loading={actions.refreshing}
+ size={'small'}
+ title={t('workingPanel.files.actions.more')}
+ />
+ </DropdownMenu>
</div>
{isEmpty && isFiltering && isSearching ? (
<Center flex={1}>
<Spin size="large" />
</Center>
- ) : isEmpty ? (
+ ) : isEmpty && !actions.pendingCreate ? (
<Center flex={1} gap={8} paddingBlock={24}>
<Empty
icon={FileIcon}
@@ -644,17 +550,26 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
<div className={styles.tree} style={treeStyleVars}>
<ExplorerTree<ProjectFileIndexEntry>
iconsColored
+ canDrag={actions.canDrag}
+ canDrop={actions.canDrop}
+ canRename={actions.canRename}
defaultExpandedIds={defaultExpandedIds}
- getContextMenuItems={getContextMenuItems}
+ getBlankContextMenuItems={actions.getBlankContextMenuItems}
+ getContextMenuItems={actions.getContextMenuItems}
gitStatus={gitStatus}
iconSet="complete"
nodes={nodes}
ref={treeRef}
style={{ height: '100%' }}
unsafeCSS={FILE_TREE_UNSAFE_CSS}
+ validateName={actions.validateName}
+ onCommitCreate={actions.onCommitCreate}
+ onCommitRename={actions.onCommitRename}
onExpandedChange={setExpandedIds}
- onNodeClick={handleNodeClick}
- onNodeDragStart={handleNodeDragStart}
+ onMove={actions.onMove}
+ onNodeClick={actions.handleNodeClick}
+ onNodeDragStart={actions.handleNodeDragStart}
+ onTreeKeyDown={actions.handleTreeKeyDown}
/>
</div>
)}
diff --git a/src/features/Conversation/WorkingSidebar/Files/treePaths.ts b/src/features/Conversation/WorkingSidebar/Files/treePaths.ts
new file mode 100644
index 00000000000..80ce0b6cd9d
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/treePaths.ts
@@ -0,0 +1,26 @@
+// Relative file paths cannot contain NUL, so this synthetic id cannot collide with an indexed entry.
+export const PROJECT_ROOT_NODE_ID = '\0project-root';
+
+export const stripTrailingSlash = (value: string) =>
+ value.endsWith('/') ? value.slice(0, -1) : value;
+
+/** Parent directory id (`src/`) of an entry id, or `null` for a top-level entry. */
+export const getParentRelativePath = (relativePath: string): string | null => {
+ const cleaned = stripTrailingSlash(relativePath);
+ const idx = cleaned.lastIndexOf('/');
+ if (idx < 0) return null;
+ return `${cleaned.slice(0, idx)}/`;
+};
+
+export const getAncestorIds = (filePath: string): string[] => {
+ const segments = stripTrailingSlash(filePath).split('/');
+ const ancestors: string[] = [];
+ for (let i = 1; i < segments.length; i++) {
+ ancestors.push(segments.slice(0, i).join('/') + '/');
+ }
+ return ancestors;
+};
+
+/** Tree id of an entry at `relativePath` (folders end with `/`). */
+export const toEntryId = (relativePath: string, isDirectory: boolean) =>
+ isDirectory ? `${stripTrailingSlash(relativePath)}/` : relativePath;
diff --git a/src/features/Conversation/WorkingSidebar/Files/useCollapsedDirectoryChildren.ts b/src/features/Conversation/WorkingSidebar/Files/useCollapsedDirectoryChildren.ts
index b127e69b9e6..3015f879bb5 100644
--- a/src/features/Conversation/WorkingSidebar/Files/useCollapsedDirectoryChildren.ts
+++ b/src/features/Conversation/WorkingSidebar/Files/useCollapsedDirectoryChildren.ts
@@ -1,9 +1,11 @@
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSingleton } from '@/hooks/useSingleton';
import { projectFileService } from '@/services/projectFile';
+import { getParentRelativePath } from './treePaths';
+
interface UseCollapsedDirectoryChildrenParams {
deviceId?: string;
/** Indexed entries; tells the hook which expanded rows the index collapsed. */
@@ -15,10 +17,50 @@ interface UseCollapsedDirectoryChildrenParams {
interface CollapsedDirectoryChildren {
children: ProjectFileIndexEntry[];
+ /**
+ * Forget every listing so expanded collapsed directories are read again —
+ * call it after a write, since the listings are not part of the SWR index.
+ */
+ invalidate: () => void;
/** Expanded directories whose on-disk listing exceeded the host-side cap. */
truncatedCount: number;
}
+/**
+ * Listed children the tree should still show: those whose parent is a
+ * collapsed directory (indexed, or itself a listed child still shown) and that
+ * the index does not list itself. A write can turn a collapsed folder into an
+ * indexed one — pasting into a new empty folder does — and its old listing
+ * must then yield to the index instead of duplicating its rows.
+ */
+export const selectCollapsedChildren = (
+ entries: ProjectFileIndexEntry[],
+ children: ProjectFileIndexEntry[],
+): ProjectFileIndexEntry[] => {
+ if (children.length === 0) return children;
+ const indexed = new Map(entries.map((entry) => [entry.relativePath, entry]));
+ const listed = new Map(children.map((child) => [child.relativePath, child]));
+ const visible = new Map<string, boolean>();
+
+ const isVisible = (child: ProjectFileIndexEntry): boolean => {
+ const cached = visible.get(child.relativePath);
+ if (cached !== undefined) return cached;
+ visible.set(child.relativePath, false);
+ const parentPath = getParentRelativePath(child.relativePath);
+ const indexedParent = parentPath ? indexed.get(parentPath) : undefined;
+ const listedParent = parentPath ? listed.get(parentPath) : undefined;
+ const result =
+ !indexed.has(child.relativePath) &&
+ (indexedParent
+ ? !!indexedParent.collapsed
+ : !!listedParent?.collapsed && isVisible(listedParent));
+ visible.set(child.relativePath, result);
+ return result;
+ };
+
+ return children.filter(isVisible);
+};
+
/**
* Children of collapsed (fully git-ignored) directories, fetched one level at a
* time as the user expands them. The project index deliberately omits these
@@ -48,6 +90,10 @@ export const useCollapsedDirectoryChildren = ({
}, [scopeKey]);
const children = loaded.scopeKey === scopeKey ? loaded.entries : [];
+ const visibleChildren = useMemo(
+ () => selectCollapsedChildren(entries, children),
+ [children, entries],
+ );
const truncatedCount = loaded.scopeKey === scopeKey ? loaded.truncatedDirs.length : 0;
useEffect(() => {
@@ -76,9 +122,15 @@ export const useCollapsedDirectoryChildren = ({
const base = previous.scopeKey === scopeKey ? previous.entries : [];
const baseTruncated = previous.scopeKey === scopeKey ? previous.truncatedDirs : [];
const freshPaths = new Set(result.entries.map((child) => child.relativePath));
+ // A re-read replaces the directory's listing, so drop children
+ // that are gone from disk along with the ones being refreshed.
return {
entries: [
- ...base.filter((child) => !freshPaths.has(child.relativePath)),
+ ...base.filter(
+ (child) =>
+ !freshPaths.has(child.relativePath) &&
+ getParentRelativePath(child.relativePath) !== id,
+ ),
...result.entries,
],
scopeKey,
@@ -97,5 +149,12 @@ export const useCollapsedDirectoryChildren = ({
}
}, [children, deviceId, entries, expandedIds, projectRoot, scopeKey]);
- return { children, truncatedCount };
+ const invalidate = useCallback(() => {
+ requested.clear();
+ // Keep what is shown until the re-read lands; a fresh array identity is
+ // what re-runs the fetch effect for every expanded collapsed directory.
+ setLoaded((previous) => ({ ...previous, entries: [...previous.entries] }));
+ }, [requested]);
+
+ return { children: visibleChildren, invalidate, truncatedCount };
};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts b/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts
new file mode 100644
index 00000000000..1ab77f7cba6
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts
@@ -0,0 +1,645 @@
+import { isDesktop } from '@lobechat/const';
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { basename, dirname, join, relative } from 'pathe';
+import type { RefObject } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type {
+ ExplorerTreeCanDropCtx,
+ ExplorerTreeCreateEvent,
+ ExplorerTreeEntryKind,
+ ExplorerTreeHandle,
+ ExplorerTreeMoveEvent,
+ ExplorerTreeNameCheck,
+ ExplorerTreeNode,
+} from '@/features/ExplorerTree';
+import { localFileService } from '@/services/electron/localFileService';
+import { projectFileService, refreshProjectFiles } from '@/services/projectFile';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+import { getPlatform } from '@/utils/platform';
+
+import { getFileClipboardScopeKey, useFileClipboardStore } from './fileClipboard';
+import { getFreeCopyName, type SiblingEntry, validateFileName } from './fileNameValidation';
+import { classifyFileOpError } from './fileOpErrors';
+import {
+ getAncestorIds,
+ getParentRelativePath,
+ PROJECT_ROOT_NODE_ID,
+ stripTrailingSlash,
+ toEntryId,
+} from './treePaths';
+
+type Node = ExplorerTreeNode<ProjectFileIndexEntry>;
+
+interface PendingSelection {
+ id: string;
+ open?: boolean;
+ rename?: boolean;
+}
+
+interface UseFileOperationsParams {
+ deviceId?: string;
+ dirtyFilePaths: Set<string>;
+ /** Folders expanded right now; a revealed entry's ancestors are added to them. */
+ expandedIds: string[];
+ /** Called after a write so lazily listed (git-ignored) folders are re-read too. */
+ invalidateCollapsedChildren: () => void;
+ /** Every entry the panel knows about, before display filters. */
+ knownEntries: ProjectFileIndexEntry[];
+ /** Ids currently in the tree; a pending selection is applied once its id shows up. */
+ nodeIds: Set<string>;
+ projectRoot: string;
+ treeRef: RefObject<ExplorerTreeHandle | null>;
+ /** Key the file index is cached under (the bound working directory). */
+ workingDirectory: string;
+}
+
+/** Folder a node stands for as a write target: `''` is the project root. */
+const dirRelOf = (node: Node | null): string =>
+ !node || node.id === PROJECT_ROOT_NODE_ID || !node.data ? '' : node.data.relativePath;
+
+/** Whether `dirRel` is the folder `entry` itself or lies inside it. */
+const isInside = (
+ entry: Pick<ProjectFileIndexEntry, 'isDirectory' | 'relativePath'>,
+ dirRel: string,
+) => entry.isDirectory && dirRel.startsWith(toEntryId(entry.relativePath, true));
+
+const getTrashNameKey = (isRemote: boolean) => {
+ if (isRemote) return 'linux';
+ const platform = getPlatform();
+ if (platform === 'Mac OS') return 'mac';
+ if (platform === 'Windows') return 'windows';
+ return 'linux';
+};
+
+/**
+ * Every write the Files tree offers — create, rename, move, duplicate, copy /
+ * cut / paste, trash — plus refresh and "open in terminal", for both the local
+ * desktop and a remote device (the transport is picked in projectFileService).
+ * After each write the file index, git overlay and lazily listed folders are
+ * re-read, and the resulting entry is selected once it shows up in the tree.
+ */
+export const useFileOperations = ({
+ deviceId,
+ dirtyFilePaths,
+ expandedIds,
+ invalidateCollapsedChildren,
+ knownEntries,
+ nodeIds,
+ projectRoot,
+ treeRef,
+ workingDirectory,
+}: UseFileOperationsParams) => {
+ const { t } = useTranslation('chat');
+ const isRemote = !!deviceId;
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const retargetLocalFiles = useChatStore((s) => s.retargetLocalFiles);
+ const closeLocalFilesAt = useChatStore((s) => s.closeLocalFilesAt);
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
+ const toggleTerminalPanel = useGlobalStore((s) => s.toggleTerminalPanel);
+ const [refreshing, setRefreshing] = useState(false);
+ const pendingSelectionRef = useRef<PendingSelection | null>(null);
+ const expandedIdsRef = useRef(expandedIds);
+ expandedIdsRef.current = expandedIds;
+
+ const scopeKey = getFileClipboardScopeKey(deviceId, projectRoot);
+ const clipboard = useFileClipboardStore((s) =>
+ s.clipboard?.scopeKey === scopeKey ? s.clipboard : undefined,
+ );
+ const setClipboard = useFileClipboardStore((s) => s.set);
+ const clearClipboard = useFileClipboardStore((s) => s.clear);
+
+ const trashName = t(`workingPanel.files.trashName.${getTrashNameKey(isRemote)}`);
+ // macOS / Windows disks ignore case; a remote device may be Linux, so be strict there.
+ const caseInsensitive = useMemo(() => {
+ if (isRemote) return false;
+ const platform = getPlatform();
+ return platform === 'Mac OS' || platform === 'Windows';
+ }, [isRemote]);
+
+ const siblingsOf = useCallback(
+ (dirRel: string): SiblingEntry[] => {
+ const parent = dirRel === '' ? null : dirRel;
+ return knownEntries
+ .filter((entry) => getParentRelativePath(entry.relativePath) === parent)
+ .map((entry) => ({ isDirectory: entry.isDirectory, name: entry.name }));
+ },
+ [knownEntries],
+ );
+
+ const toAbsolute = useCallback(
+ (rel: string) => (rel === '' ? projectRoot : join(projectRoot, stripTrailingSlash(rel))),
+ [projectRoot],
+ );
+ const toRelative = useCallback(
+ (absolutePath: string) => relative(projectRoot, absolutePath),
+ [projectRoot],
+ );
+
+ const reasonOf = useCallback(
+ (error: unknown) => {
+ const { kind, message } = classifyFileOpError(error);
+ switch (kind) {
+ case 'offline': {
+ return t('workingPanel.files.feedback.deviceOffline');
+ }
+ case 'unsupported': {
+ return t('workingPanel.files.feedback.unsupportedOnDevice');
+ }
+ case 'trashUnsupported': {
+ return t('workingPanel.files.feedback.trashUnsupported', { trash: trashName });
+ }
+ default: {
+ return message;
+ }
+ }
+ },
+ [t, trashName],
+ );
+
+ /** Re-read everything the tree shows, then select `selection` once it exists. */
+ const afterWrite = useCallback(
+ async (selection?: PendingSelection) => {
+ pendingSelectionRef.current = selection ?? null;
+ invalidateCollapsedChildren();
+ await refreshProjectFiles(deviceId, workingDirectory);
+ },
+ [deviceId, invalidateCollapsedChildren, workingDirectory],
+ );
+
+ // Apply a pending selection when the refreshed nodes contain it: expand its
+ // ancestors, select and focus it, then open or rename it as requested.
+ useEffect(() => {
+ const pending = pendingSelectionRef.current;
+ if (!pending || !nodeIds.has(pending.id)) return;
+ pendingSelectionRef.current = null;
+ const tree = treeRef.current;
+ if (!tree) return;
+ const ancestors = [PROJECT_ROOT_NODE_ID, ...getAncestorIds(pending.id)];
+ const self = pending.id.endsWith('/') ? [pending.id] : [];
+ tree.setExpanded([...new Set([...expandedIdsRef.current, ...ancestors, ...self])]);
+ // `select` adds to the selection, so drop whatever the write replaced.
+ for (const id of tree.getSelectedIds()) if (id !== pending.id) tree.deselect(id);
+ tree.select(pending.id);
+ tree.focus(pending.id);
+ if (pending.rename) tree.startRenaming(pending.id);
+ if (pending.open && !pending.id.endsWith('/')) {
+ openLocalFile({ deviceId, filePath: toAbsolute(pending.id), workingDirectory: projectRoot });
+ }
+ }, [deviceId, nodeIds, openLocalFile, projectRoot, toAbsolute, treeRef]);
+
+ const validateName = useCallback(
+ (check: ExplorerTreeNameCheck<ProjectFileIndexEntry>) => {
+ const error =
+ check.mode === 'create'
+ ? validateFileName({
+ allowNested: true,
+ caseInsensitive,
+ name: check.name,
+ siblings: siblingsOf(dirRelOf(check.parentNode)),
+ })
+ : validateFileName({
+ allowNested: false,
+ caseInsensitive,
+ currentName: check.node.name,
+ name: check.name,
+ siblings: siblingsOf(getParentRelativePath(check.node.id) ?? ''),
+ });
+ return error
+ ? t(`workingPanel.files.validation.${error}`, { name: check.name.split('/')[0] })
+ : null;
+ },
+ [caseInsensitive, siblingsOf, t],
+ );
+
+ const commitCreate = useCallback(
+ async ({ kind, name, parentNode }: ExplorerTreeCreateEvent<ProjectFileIndexEntry>) => {
+ const dirRel = dirRelOf(parentNode);
+ const path = join(toAbsolute(dirRel), name);
+ try {
+ const result =
+ kind === 'folder'
+ ? await projectFileService.createProjectDirectory({
+ deviceId,
+ path,
+ workingDirectory: projectRoot,
+ })
+ : await projectFileService.createProjectFile({
+ deviceId,
+ path,
+ workingDirectory: projectRoot,
+ });
+ if (!result.success) throw new Error(result.error || 'Unknown error');
+ } catch (error) {
+ toast.error(
+ t('workingPanel.files.feedback.createFailed', { name, reason: reasonOf(error) }),
+ );
+ await afterWrite();
+ return false;
+ }
+ await afterWrite({
+ id: toEntryId(
+ `${stripTrailingSlash(dirRel)}${dirRel ? '/' : ''}${name}`,
+ kind === 'folder',
+ ),
+ open: kind === 'file',
+ });
+ },
+ [afterWrite, deviceId, projectRoot, reasonOf, t, toAbsolute],
+ );
+
+ const commitRename = useCallback(
+ async (node: Node, newName: string) => {
+ if (!node.data) return false;
+ try {
+ const result = await projectFileService.renameProjectFile({
+ deviceId,
+ newName,
+ path: node.data.path,
+ workingDirectory: projectRoot,
+ });
+ if (!result.success) throw new Error(String(result.error || 'Unknown error'));
+ } catch (error) {
+ toast.error(
+ t('workingPanel.files.feedback.renameFailed', {
+ name: node.data.name,
+ reason: reasonOf(error),
+ }),
+ );
+ await afterWrite();
+ return false;
+ }
+ retargetLocalFiles(
+ [{ from: node.data.path, to: join(dirname(node.data.path), newName) }],
+ deviceId,
+ );
+ const parentRel = getParentRelativePath(node.id) ?? '';
+ await afterWrite({ id: toEntryId(`${parentRel}${newName}`, !!node.isFolder) });
+ },
+ [afterWrite, deviceId, projectRoot, reasonOf, retargetLocalFiles, t],
+ );
+
+ /** Moves entries into `targetDirRel`, skipping (and reporting) name clashes. */
+ const moveInto = useCallback(
+ async (entries: ProjectFileIndexEntry[], targetDirRel: string) => {
+ const fold = (value: string) => (caseInsensitive ? value.toLowerCase() : value);
+ const taken = new Set(siblingsOf(targetDirRel).map((sibling) => fold(sibling.name)));
+ const movable = entries.filter((entry) => {
+ if (getParentRelativePath(entry.relativePath) === (targetDirRel || null)) return false;
+ if (!taken.has(fold(entry.name))) return true;
+ toast.error(t('workingPanel.files.feedback.moveConflict', { name: entry.name }));
+ return false;
+ });
+ if (movable.length === 0) return entries.length === 0;
+
+ const targetDir = toAbsolute(targetDirRel);
+ let results;
+ try {
+ results = await projectFileService.moveProjectFiles({
+ deviceId,
+ items: movable.map((entry) => ({
+ newPath: join(targetDir, entry.name),
+ oldPath: entry.path,
+ })),
+ workingDirectory: projectRoot,
+ });
+ } catch (error) {
+ const reason = reasonOf(error);
+ for (const entry of movable) {
+ toast.error(t('workingPanel.files.feedback.moveFailed', { name: entry.name, reason }));
+ }
+ await afterWrite();
+ return false;
+ }
+ const failed = results.filter((result) => !result.success);
+ for (const result of failed) {
+ toast.error(
+ t('workingPanel.files.feedback.moveFailed', {
+ name: basename(result.sourcePath),
+ reason: reasonOf(result.error),
+ }),
+ );
+ }
+ retargetLocalFiles(
+ results.flatMap((result) =>
+ result.success && result.newPath ? [{ from: result.sourcePath, to: result.newPath }] : [],
+ ),
+ deviceId,
+ );
+ const moved = results.find((result) => result.success && result.newPath);
+ const movedEntry = moved && movable.find((entry) => entry.path === moved.sourcePath);
+ await afterWrite(
+ moved?.newPath && movedEntry
+ ? { id: toEntryId(toRelative(moved.newPath), movedEntry.isDirectory) }
+ : undefined,
+ );
+ return failed.length === 0;
+ },
+ [
+ afterWrite,
+ caseInsensitive,
+ deviceId,
+ projectRoot,
+ reasonOf,
+ retargetLocalFiles,
+ siblingsOf,
+ t,
+ toAbsolute,
+ toRelative,
+ ],
+ );
+
+ const canDrop = useCallback(
+ ({ sourceNodes, targetNode }: ExplorerTreeCanDropCtx<ProjectFileIndexEntry>) => {
+ const targetDirRel = dirRelOf(targetNode);
+ if (targetNode && !targetNode.isFolder) return false;
+ const fold = (value: string) => (caseInsensitive ? value.toLowerCase() : value);
+ const taken = new Set(siblingsOf(targetDirRel).map((sibling) => fold(sibling.name)));
+ return sourceNodes.every((node) => {
+ const entry = node.data;
+ if (!entry || node.id === PROJECT_ROOT_NODE_ID) return false;
+ if (isInside(entry, targetDirRel)) return false;
+ // Dropping back into its own folder is a no-op, not a clash.
+ if (getParentRelativePath(entry.relativePath) === (targetDirRel || null)) return true;
+ return !taken.has(fold(entry.name));
+ });
+ },
+ [caseInsensitive, siblingsOf],
+ );
+
+ const move = useCallback(
+ async ({ newParentId, sourceNodes }: ExplorerTreeMoveEvent<ProjectFileIndexEntry>) => {
+ const targetDirRel = newParentId && newParentId !== PROJECT_ROOT_NODE_ID ? newParentId : '';
+ const entries = sourceNodes.flatMap((node) => (node.data ? [node.data] : []));
+ if (entries.some((entry) => isInside(entry, targetDirRel))) return false;
+ return moveInto(entries, targetDirRel);
+ },
+ [moveInto],
+ );
+
+ const trash = useCallback(
+ (entries: ProjectFileIndexEntry[]) => {
+ if (entries.length === 0) return;
+ const [first] = entries;
+ const isDirty = entries.some((entry) =>
+ entry.isDirectory
+ ? [...dirtyFilePaths].some((path) => path.startsWith(toEntryId(entry.relativePath, true)))
+ : dirtyFilePaths.has(entry.relativePath),
+ );
+ const description =
+ entries.length > 1
+ ? t('workingPanel.files.delete.multipleDesc', { trash: trashName })
+ : first.isDirectory
+ ? t('workingPanel.files.delete.folderDesc', { name: first.name, trash: trashName })
+ : t('workingPanel.files.delete.fileDesc', { trash: trashName });
+
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: isDirty
+ ? `${description} ${t('workingPanel.files.delete.dirtyWarning')}`
+ : description,
+ okButtonProps: { danger: true },
+ okText: t('workingPanel.files.delete.confirm', { trash: trashName }),
+ onOk: async () => {
+ let items: { error?: string; path: string; success: boolean }[];
+ try {
+ const result = await projectFileService.trashProjectFiles({
+ deviceId,
+ paths: entries.map((entry) => entry.path),
+ workingDirectory: projectRoot,
+ });
+ items = result.items;
+ } catch (error) {
+ const reason = reasonOf(error);
+ toast.error(
+ t('workingPanel.files.feedback.deleteFailed', {
+ name: entries.length > 1 ? String(entries.length) : first.name,
+ reason,
+ }),
+ );
+ return;
+ }
+ const trashed = items.filter((item) => item.success);
+ closeLocalFilesAt(
+ trashed.map((item) => item.path),
+ deviceId,
+ );
+ if (trashed.length === 1) {
+ toast.success(
+ t('workingPanel.files.feedback.trashed', {
+ name: basename(trashed[0].path),
+ trash: trashName,
+ }),
+ );
+ } else if (trashed.length > 1) {
+ toast.success(
+ t('workingPanel.files.feedback.trashedCount', {
+ count: trashed.length,
+ trash: trashName,
+ }),
+ );
+ }
+ for (const item of items.filter((result) => !result.success)) {
+ toast.error(
+ t('workingPanel.files.feedback.deleteFailed', {
+ name: basename(item.path),
+ reason: reasonOf(item.error),
+ }),
+ );
+ }
+ const parentRel = getParentRelativePath(first.relativePath);
+ await afterWrite(parentRel ? { id: parentRel } : undefined);
+ },
+ title:
+ entries.length > 1
+ ? t('workingPanel.files.delete.confirmTitleMultiple', {
+ count: entries.length,
+ trash: trashName,
+ })
+ : t('workingPanel.files.delete.confirmTitle', { name: first.name, trash: trashName }),
+ });
+ },
+ [afterWrite, closeLocalFilesAt, deviceId, dirtyFilePaths, projectRoot, reasonOf, t, trashName],
+ );
+
+ const duplicate = useCallback(
+ async (entry: ProjectFileIndexEntry) => {
+ try {
+ const [result] = await projectFileService.copyProjectFiles({
+ deviceId,
+ items: [{ sourcePath: entry.path }],
+ workingDirectory: projectRoot,
+ });
+ if (!result?.success || !result.targetPath) {
+ throw new Error(result?.error || 'Unknown error');
+ }
+ await afterWrite({
+ id: toEntryId(toRelative(result.targetPath), entry.isDirectory),
+ rename: true,
+ });
+ } catch (error) {
+ toast.error(
+ t('workingPanel.files.feedback.duplicateFailed', {
+ name: entry.name,
+ reason: reasonOf(error),
+ }),
+ );
+ }
+ },
+ [afterWrite, deviceId, projectRoot, reasonOf, t, toRelative],
+ );
+
+ const putOnClipboard = useCallback(
+ (entries: ProjectFileIndexEntry[], mode: 'copy' | 'cut') => {
+ if (entries.length === 0) return;
+ setClipboard({
+ items: entries.map(({ isDirectory, name, path }) => ({ isDirectory, name, path })),
+ mode,
+ scopeKey,
+ });
+ },
+ [scopeKey, setClipboard],
+ );
+
+ const paste = useCallback(
+ async (targetDirRel: string) => {
+ if (!clipboard) return;
+ const entries = clipboard.items.map((item) => ({
+ ...item,
+ relativePath: toEntryId(toRelative(item.path), item.isDirectory),
+ }));
+ const intoItself = entries.find((entry) => isInside(entry, targetDirRel));
+ if (intoItself) {
+ toast.error(t('workingPanel.files.feedback.pasteIntoItself', { name: intoItself.name }));
+ return;
+ }
+
+ if (clipboard.mode === 'cut') {
+ if (await moveInto(entries, targetDirRel)) clearClipboard();
+ return;
+ }
+
+ const siblings = [...siblingsOf(targetDirRel)];
+ const targetDir = toAbsolute(targetDirRel);
+ const items = entries.map((entry) => {
+ const name = getFreeCopyName(entry.name, entry.isDirectory, siblings, caseInsensitive);
+ siblings.push({ isDirectory: entry.isDirectory, name });
+ return { sourcePath: entry.path, targetPath: join(targetDir, name) };
+ });
+ let results;
+ try {
+ results = await projectFileService.copyProjectFiles({
+ deviceId,
+ items,
+ workingDirectory: projectRoot,
+ });
+ } catch (error) {
+ const reason = reasonOf(error);
+ for (const entry of entries) {
+ toast.error(t('workingPanel.files.feedback.pasteFailed', { name: entry.name, reason }));
+ }
+ return;
+ }
+ for (const result of results.filter((item) => !item.success)) {
+ toast.error(
+ t('workingPanel.files.feedback.pasteFailed', {
+ name: basename(result.sourcePath),
+ reason: reasonOf(result.error),
+ }),
+ );
+ }
+ const copied = results.find((result) => result.success && result.targetPath);
+ const copiedEntry = copied && entries.find((entry) => entry.path === copied.sourcePath);
+ await afterWrite(
+ copied?.targetPath && copiedEntry
+ ? { id: toEntryId(toRelative(copied.targetPath), copiedEntry.isDirectory) }
+ : undefined,
+ );
+ },
+ [
+ afterWrite,
+ caseInsensitive,
+ clearClipboard,
+ clipboard,
+ deviceId,
+ moveInto,
+ projectRoot,
+ reasonOf,
+ siblingsOf,
+ t,
+ toAbsolute,
+ toRelative,
+ ],
+ );
+
+ const refresh = useCallback(async () => {
+ setRefreshing(true);
+ try {
+ await afterWrite();
+ } catch {
+ toast.error(t('workingPanel.files.feedback.refreshFailed'));
+ } finally {
+ setRefreshing(false);
+ }
+ }, [afterWrite, t]);
+
+ const openInSystem = useCallback(
+ async (entry: ProjectFileIndexEntry) => {
+ try {
+ const result = await localFileService.openLocalFileOrFolder(entry.path, true);
+ if (result && result.success === false) throw new Error(result.error);
+ } catch {
+ toast.error(t('workingPanel.files.feedback.openFailed', { name: entry.name }));
+ }
+ },
+ [t],
+ );
+
+ const canUseTerminal = isDesktop && !isRemote;
+ const openInTerminal = useCallback(
+ async (cwd: string) => {
+ // The terminal store pulls in xterm; load it only when a terminal is asked for.
+ const { useChatTerminalStore } = await import('@/features/ChatTerminal/store');
+ const topicKey = activeTopicId || (activeAgentId ? `agent:${activeAgentId}` : 'global');
+ await useChatTerminalStore.getState().createTab(topicKey, cwd);
+ if (useChatTerminalStore.getState().createErrors[topicKey]) {
+ toast.error(t('workingPanel.files.feedback.terminalFailed'));
+ return;
+ }
+ toggleTerminalPanel(true);
+ },
+ [activeAgentId, activeTopicId, t, toggleTerminalPanel],
+ );
+
+ const startCreate = useCallback(
+ (parentId: string, kind: ExplorerTreeEntryKind) =>
+ treeRef.current?.startCreating(parentId, kind),
+ [treeRef],
+ );
+
+ return {
+ canDrop,
+ canPaste: !!clipboard,
+ canUseTerminal,
+ clipboard,
+ commitCreate,
+ commitRename,
+ duplicate,
+ move,
+ openInSystem,
+ openInTerminal,
+ paste,
+ putOnClipboard,
+ refresh,
+ refreshing,
+ startCreate,
+ toAbsolute,
+ trash,
+ trashName,
+ validateName,
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts
new file mode 100644
index 00000000000..75b6088691a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts
@@ -0,0 +1,772 @@
+import { WORKSPACE_FILE_DRAG_MIME } from '@lobechat/const';
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ExplorerTreeHandle, ExplorerTreeNode } from '@/features/ExplorerTree';
+import { useGlobalStore } from '@/store/global';
+
+import { useFileClipboardStore } from './fileClipboard';
+import { PROJECT_ROOT_NODE_ID } from './treePaths';
+import { useFileTreeActions } from './useFileTreeActions';
+
+const service = vi.hoisted(() => ({
+ copyProjectFiles: vi.fn(),
+ createProjectDirectory: vi.fn(),
+ createProjectFile: vi.fn(),
+ moveProjectFiles: vi.fn(),
+ refreshProjectFiles: vi.fn(),
+ renameProjectFile: vi.fn(),
+ trashProjectFiles: vi.fn(),
+}));
+const ui = vi.hoisted(() => ({ confirmModal: vi.fn(), error: vi.fn(), success: vi.fn() }));
+const openLocalFile = vi.hoisted(() => vi.fn());
+const retargetLocalFiles = vi.hoisted(() => vi.fn());
+const closeLocalFilesAt = vi.hoisted(() => vi.fn());
+const terminal = vi.hoisted(() => ({
+ createErrors: {} as Record<string, string | undefined>,
+ createTab: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ isDesktop: true,
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: service,
+ refreshProjectFiles: service.refreshProjectFiles,
+}));
+
+vi.mock('@/features/ChatTerminal/store', () => ({
+ useChatTerminalStore: { getState: () => terminal },
+}));
+
+vi.mock('@/utils/platform', () => ({ getPlatform: () => 'Mac OS', isMacOS: () => true }));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({
+ activeAgentId: 'agt_1',
+ activeTopicId: 'tpc_1',
+ closeLocalFilesAt,
+ openLocalFile,
+ retargetLocalFiles,
+ }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options ? `${key} ${JSON.stringify(options)}` : key,
+ }),
+}));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ confirmModal: ui.confirmModal,
+ toast: { error: ui.error, success: ui.success },
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ copyToClipboard: vi.fn(),
+}));
+
+// ─── fixtures ─────────────────────────────────────────────────────────────────
+
+type Node = ExplorerTreeNode<ProjectFileIndexEntry>;
+
+const entry = (relativePath: string): ProjectFileIndexEntry => {
+ const isDirectory = relativePath.endsWith('/');
+ const clean = isDirectory ? relativePath.slice(0, -1) : relativePath;
+ return {
+ isDirectory,
+ name: clean.split('/').pop()!,
+ path: `/repo/${clean}`,
+ relativePath,
+ };
+};
+
+const baseEntries = ['src/', 'src/app.ts', 'root.ts'].map(entry);
+
+const toNodes = (entries: ProjectFileIndexEntry[]): Node[] => [
+ { id: PROJECT_ROOT_NODE_ID, isFolder: true, name: 'repo', parentId: null },
+ ...entries.map((item) => {
+ const parent = item.relativePath.replace(/[^/]+\/?$/, '');
+ return {
+ data: item,
+ id: item.relativePath,
+ isFolder: item.isDirectory,
+ name: item.name,
+ parentId: parent || PROJECT_ROOT_NODE_ID,
+ };
+ }),
+];
+
+const handle = {
+ deselect: vi.fn(),
+ focus: vi.fn(),
+ getFocusedId: vi.fn(() => null),
+ getSelectedIds: vi.fn((): string[] => []),
+ resync: vi.fn(),
+ select: vi.fn(),
+ setExpanded: vi.fn(),
+ startCreating: vi.fn(),
+ startRenaming: vi.fn(),
+} satisfies ExplorerTreeHandle;
+
+const setup = (overrides: Partial<Parameters<typeof useFileTreeActions>[0]> = {}) => {
+ const entries = [...baseEntries, entry('gone.ts')];
+ const params: Parameters<typeof useFileTreeActions>[0] = {
+ deletedPaths: new Set(['gone.ts']),
+ dirtyFilePaths: new Set(['src/app.ts']),
+ expandedIds: [PROJECT_ROOT_NODE_ID],
+ hasDisplayFilter: false,
+ invalidateCollapsedChildren: vi.fn(),
+ knownEntries: baseEntries,
+ nodes: toNodes(entries),
+ onClearDisplayFilter: vi.fn(),
+ onCollapseAll: vi.fn(),
+ projectRoot: '/repo',
+ treeRef: { current: handle },
+ workingDirectory: '/repo',
+ ...overrides,
+ };
+ const view = renderHook((props) => useFileTreeActions(props), { initialProps: params });
+ const node = (id: string) => params.nodes.find((item) => item.id === id)!;
+ const menu = (id: string) =>
+ view.result.current.getContextMenuItems(node(id)) as {
+ disabled?: boolean;
+ key: string;
+ onClick?: () => void;
+ }[];
+ const clickMenu = (id: string, key: string) =>
+ act(() => menu(id).find((item) => item.key === key)!.onClick!());
+ return { clickMenu, menu, node, params, view };
+};
+
+const keyEvent = (key: string, mods: Record<string, boolean> = {}) =>
+ ({ altKey: false, ctrlKey: false, key, metaKey: false, shiftKey: false, ...mods }) as never;
+
+beforeEach(() => {
+ for (const mock of Object.values(service)) mock.mockReset();
+ service.refreshProjectFiles.mockResolvedValue(undefined);
+ for (const mock of Object.values(handle)) mock.mockReset();
+ handle.getSelectedIds.mockReturnValue([]);
+ ui.confirmModal.mockReset();
+ ui.error.mockReset();
+ ui.success.mockReset();
+ openLocalFile.mockReset();
+ retargetLocalFiles.mockReset();
+ closeLocalFilesAt.mockReset();
+ terminal.createTab.mockReset();
+ terminal.createErrors = {};
+ useFileClipboardStore.setState({ clipboard: undefined });
+});
+
+// ─── tests ────────────────────────────────────────────────────────────────────
+
+describe('useFileTreeActions — create', () => {
+ it('creates a file under the target folder, invalidates lazy listings and refreshes', async () => {
+ service.createProjectFile.mockResolvedValue({ path: '/repo/src/new.ts', success: true });
+ const { node, params, view } = setup();
+
+ await act(() =>
+ view.result.current.onCommitCreate({
+ kind: 'file',
+ name: 'new.ts',
+ parentNode: node('src/'),
+ }),
+ );
+
+ expect(service.createProjectFile).toHaveBeenCalledWith({
+ deviceId: undefined,
+ path: '/repo/src/new.ts',
+ workingDirectory: '/repo',
+ });
+ expect(params.invalidateCollapsedChildren).toHaveBeenCalledTimes(1);
+ expect(service.refreshProjectFiles).toHaveBeenCalledWith(undefined, '/repo');
+ });
+
+ it('selects, reveals and opens the new file once the refreshed nodes contain it', async () => {
+ service.createProjectFile.mockResolvedValue({ path: '/repo/src/new.ts', success: true });
+ const { node, params, view } = setup();
+
+ await act(() =>
+ view.result.current.onCommitCreate({
+ kind: 'file',
+ name: 'new.ts',
+ parentNode: node('src/'),
+ }),
+ );
+ expect(openLocalFile).not.toHaveBeenCalled();
+
+ handle.getSelectedIds.mockReturnValue(['src/app.ts']);
+ view.rerender({ ...params, nodes: toNodes([...baseEntries, entry('src/new.ts')]) });
+
+ expect(handle.setExpanded).toHaveBeenCalledWith([PROJECT_ROOT_NODE_ID, 'src/']);
+ // The previous selection is replaced, not extended.
+ expect(handle.deselect).toHaveBeenCalledWith('src/app.ts');
+ expect(handle.select).toHaveBeenCalledWith('src/new.ts');
+ expect(handle.focus).toHaveBeenCalledWith('src/new.ts');
+ expect(openLocalFile).toHaveBeenCalledWith({
+ deviceId: undefined,
+ filePath: '/repo/src/new.ts',
+ workingDirectory: '/repo',
+ });
+ });
+
+ it('creates a folder through the device RPC on a remote device and expands it', async () => {
+ service.createProjectDirectory.mockResolvedValue({ path: '/repo/docs', success: true });
+ const { node, params, view } = setup({ deviceId: 'dev_1' });
+
+ await act(() =>
+ view.result.current.onCommitCreate({
+ kind: 'folder',
+ name: 'docs',
+ parentNode: node(PROJECT_ROOT_NODE_ID),
+ }),
+ );
+ expect(service.createProjectDirectory).toHaveBeenCalledWith({
+ deviceId: 'dev_1',
+ path: '/repo/docs',
+ workingDirectory: '/repo',
+ });
+ expect(service.refreshProjectFiles).toHaveBeenCalledWith('dev_1', '/repo');
+
+ view.rerender({ ...params, nodes: toNodes([...baseEntries, entry('docs/')]) });
+ expect(handle.setExpanded).toHaveBeenCalledWith([PROJECT_ROOT_NODE_ID, 'docs/']);
+ expect(openLocalFile).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed create with its reason, refreshes and tells the tree to roll back', async () => {
+ service.createProjectFile.mockResolvedValue({ error: 'EACCES', path: '', success: false });
+ const { node, view } = setup();
+
+ let result: unknown;
+ await act(async () => {
+ result = await view.result.current.onCommitCreate({
+ kind: 'file',
+ name: 'x.ts',
+ parentNode: node(PROJECT_ROOT_NODE_ID),
+ });
+ });
+
+ expect(result).toBe(false);
+ expect(ui.error).toHaveBeenCalledWith(
+ 'workingPanel.files.feedback.createFailed {"name":"x.ts","reason":"EACCES"}',
+ );
+ expect(service.refreshProjectFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens the inline input from the folder menu, the blank area and the header', () => {
+ const { clickMenu, view } = setup();
+
+ clickMenu('src/', 'new-file');
+ expect(handle.startCreating).toHaveBeenLastCalledWith('src/', 'file');
+
+ const blankItems = view.result.current.getBlankContextMenuItems() as {
+ key: string;
+ onClick: () => void;
+ }[];
+ act(() => blankItems.find((item) => item.key === 'new-folder')!.onClick());
+ expect(handle.startCreating).toHaveBeenLastCalledWith(PROJECT_ROOT_NODE_ID, 'folder');
+
+ handle.getSelectedIds.mockReturnValue(['src/app.ts']);
+ act(() => view.result.current.startCreateFromHeader('file'));
+ expect(handle.startCreating).toHaveBeenLastCalledWith('src/', 'file');
+
+ handle.getSelectedIds.mockReturnValue([]);
+ act(() => view.result.current.startCreateFromHeader('folder'));
+ expect(handle.startCreating).toHaveBeenLastCalledWith(PROJECT_ROOT_NODE_ID, 'folder');
+ });
+
+ it('drops display filters first and opens the input once the tree is unfiltered', async () => {
+ const { clickMenu, params, view } = setup({ hasDisplayFilter: true });
+
+ clickMenu('src/', 'new-folder');
+ expect(params.onClearDisplayFilter).toHaveBeenCalledTimes(1);
+ expect(handle.startCreating).not.toHaveBeenCalled();
+ expect(view.result.current.pendingCreate).toBe(true);
+
+ view.rerender({ ...params, hasDisplayFilter: false });
+ await waitFor(() => expect(handle.startCreating).toHaveBeenCalledWith('src/', 'folder'));
+ });
+});
+
+describe('useFileTreeActions — name validation', () => {
+ it('flags empty, invalid and taken names (case-insensitive on macOS)', () => {
+ const { node, view } = setup();
+ const validate = (name: string, parent = PROJECT_ROOT_NODE_ID) =>
+ view.result.current.validateName({
+ kind: 'file',
+ mode: 'create',
+ name,
+ parentNode: node(parent),
+ });
+
+ expect(validate('fresh.ts')).toBeNull();
+ expect(validate(' ')).toBe('workingPanel.files.validation.empty {"name":" "}');
+ expect(validate('a:b')).toContain('workingPanel.files.validation.invalidChars');
+ expect(validate('ROOT.ts')).toContain('workingPanel.files.validation.exists');
+ expect(validate('app.ts', 'src/')).toContain('workingPanel.files.validation.exists');
+ expect(validate('src/app2.ts')).toBeNull();
+ });
+
+ it('compares case-sensitively on a remote device', () => {
+ const { node, view } = setup({ deviceId: 'dev_1' });
+ expect(
+ view.result.current.validateName({
+ kind: 'file',
+ mode: 'create',
+ name: 'ROOT.ts',
+ parentNode: node(PROJECT_ROOT_NODE_ID),
+ }),
+ ).toBeNull();
+ });
+
+ it('refuses a slash in a rename but accepts the current name', () => {
+ const { node, view } = setup();
+ const validate = (name: string) =>
+ view.result.current.validateName({ mode: 'rename', name, node: node('root.ts') });
+
+ expect(validate('root.ts')).toBeNull();
+ expect(validate('a/b.ts')).toContain('validation.invalidChars');
+ expect(validate('src')).toContain('validation.exists');
+ });
+
+ it('does not rename or drag the project root or a row git reports deleted', () => {
+ const { node, view } = setup();
+ const { canDrag, canRename } = view.result.current;
+ expect(canRename(node(PROJECT_ROOT_NODE_ID))).toBe(false);
+ expect(canRename(node('gone.ts'))).toBe(false);
+ expect(canRename(node('root.ts'))).toBe(true);
+ expect(canDrag(node(PROJECT_ROOT_NODE_ID))).toBe(false);
+ expect(canDrag(node('gone.ts'))).toBe(false);
+ });
+});
+
+describe('useFileTreeActions — rename', () => {
+ it('renames through the service and refreshes', async () => {
+ service.renameProjectFile.mockResolvedValue({ newPath: '/repo/main.ts', success: true });
+ const { node, view } = setup();
+
+ await act(() => view.result.current.onCommitRename(node('root.ts'), 'main.ts'));
+
+ expect(service.renameProjectFile).toHaveBeenCalledWith({
+ deviceId: undefined,
+ newName: 'main.ts',
+ path: '/repo/root.ts',
+ workingDirectory: '/repo',
+ });
+ // An open tab of the renamed file follows it to the new path.
+ expect(retargetLocalFiles).toHaveBeenCalledWith(
+ [{ from: '/repo/root.ts', to: '/repo/main.ts' }],
+ undefined,
+ );
+ expect(service.refreshProjectFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it('rolls back and explains a failed rename', async () => {
+ service.renameProjectFile.mockRejectedValue(new Error('EBUSY'));
+ const { node, view } = setup();
+
+ let result: unknown;
+ await act(async () => {
+ result = await view.result.current.onCommitRename(node('root.ts'), 'main.ts');
+ });
+
+ expect(result).toBe(false);
+ expect(ui.error).toHaveBeenCalledWith(
+ 'workingPanel.files.feedback.renameFailed {"name":"root.ts","reason":"EBUSY"}',
+ );
+ });
+
+ it('starts inline rename from the menu', () => {
+ const { clickMenu } = setup();
+ clickMenu('src/', 'rename');
+ expect(handle.startRenaming).toHaveBeenCalledWith('src/');
+ });
+});
+
+describe('useFileTreeActions — move to trash', () => {
+ it('confirms, warns about uncommitted changes, trashes and refreshes', async () => {
+ service.trashProjectFiles.mockResolvedValue({
+ items: [{ path: '/repo/src/app.ts', success: true }],
+ success: true,
+ });
+ const { clickMenu } = setup();
+
+ clickMenu('src/app.ts', 'trash');
+
+ expect(ui.confirmModal).toHaveBeenCalledTimes(1);
+ const [config] = ui.confirmModal.mock.calls[0];
+ expect(config.title).toBe(
+ 'workingPanel.files.delete.confirmTitle {"name":"app.ts","trash":"workingPanel.files.trashName.mac"}',
+ );
+ expect(config.content).toContain('workingPanel.files.delete.fileDesc');
+ expect(config.content).toContain('workingPanel.files.delete.dirtyWarning');
+ expect(config.okButtonProps).toEqual({ danger: true });
+ expect(config.cancelText).toBe('cancel {"ns":"common"}');
+
+ await act(() => config.onOk());
+
+ expect(service.trashProjectFiles).toHaveBeenCalledWith({
+ deviceId: undefined,
+ paths: ['/repo/src/app.ts'],
+ workingDirectory: '/repo',
+ });
+ expect(ui.success).toHaveBeenCalledWith(
+ 'workingPanel.files.feedback.trashed {"name":"app.ts","trash":"workingPanel.files.trashName.mac"}',
+ );
+ expect(closeLocalFilesAt).toHaveBeenCalledWith(['/repo/src/app.ts'], undefined);
+ expect(service.refreshProjectFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it('warns about changes inside a folder and describes the recursive delete', () => {
+ const { clickMenu } = setup();
+ clickMenu('src/', 'trash');
+ const [config] = ui.confirmModal.mock.calls[0];
+ expect(config.content).toContain('workingPanel.files.delete.folderDesc');
+ expect(config.content).toContain('workingPanel.files.delete.dirtyWarning');
+ });
+
+ it('acts on the whole selection when the clicked row is part of it', async () => {
+ service.trashProjectFiles.mockResolvedValue({
+ items: [
+ { path: '/repo/root.ts', success: true },
+ { error: 'EPERM', path: '/repo/src', success: false },
+ ],
+ success: false,
+ });
+ handle.getSelectedIds.mockReturnValue(['root.ts', 'src/']);
+ const { clickMenu } = setup();
+
+ clickMenu('root.ts', 'trash');
+
+ const [config] = ui.confirmModal.mock.calls[0];
+ expect(config.title).toContain('delete.confirmTitleMultiple');
+ expect(config.title).toContain('"count":2');
+
+ await act(() => config.onOk());
+ expect(service.trashProjectFiles).toHaveBeenCalledWith(
+ expect.objectContaining({ paths: ['/repo/root.ts', '/repo/src'] }),
+ );
+ // Partial success: report what went to the trash, then each failure.
+ expect(ui.success).toHaveBeenCalledWith(expect.stringContaining('feedback.trashed'));
+ expect(ui.error).toHaveBeenCalledWith(
+ 'workingPanel.files.feedback.deleteFailed {"name":"src","reason":"EPERM"}',
+ );
+ });
+
+ it('fails clearly on a device without a trash instead of deleting', async () => {
+ service.trashProjectFiles.mockRejectedValue(
+ new Error('This device does not support moving files to the trash'),
+ );
+ const { clickMenu } = setup({ deviceId: 'dev_1' });
+
+ clickMenu('root.ts', 'trash');
+ await act(() => ui.confirmModal.mock.calls[0][0].onOk());
+
+ expect(ui.error).toHaveBeenCalledWith(
+ 'workingPanel.files.feedback.deleteFailed {"name":"root.ts","reason":"workingPanel.files.feedback.trashUnsupported {\\"trash\\":\\"workingPanel.files.trashName.linux\\"}"}',
+ );
+ expect(ui.success).not.toHaveBeenCalled();
+ });
+
+ it('reports an outdated or offline device', async () => {
+ const { clickMenu } = setup({ deviceId: 'dev_1' });
+
+ service.trashProjectFiles.mockRejectedValueOnce(new Error('Unknown device RPC method: x'));
+ clickMenu('root.ts', 'trash');
+ await act(() => ui.confirmModal.mock.calls[0][0].onOk());
+ expect(ui.error).toHaveBeenLastCalledWith(
+ expect.stringContaining('workingPanel.files.feedback.unsupportedOnDevice'),
+ );
+
+ service.trashProjectFiles.mockRejectedValueOnce(new Error('DEVICE_NOT_FOUND'));
+ clickMenu('root.ts', 'trash');
+ await act(() => ui.confirmModal.mock.calls[1][0].onOk());
+ expect(ui.error).toHaveBeenLastCalledWith(
+ expect.stringContaining('workingPanel.files.feedback.deviceOffline'),
+ );
+ });
+});
+
+describe('useFileTreeActions — keyboard', () => {
+ it('Delete and ⌘⌫ ask to trash the focused row; Enter opens a file', () => {
+ const { node, view } = setup();
+ const ctx = { focusedNode: node('root.ts'), selectedNodes: [] };
+
+ expect(view.result.current.handleTreeKeyDown(keyEvent('Delete'), ctx)).toBe(true);
+ expect(
+ view.result.current.handleTreeKeyDown(keyEvent('Backspace', { metaKey: true }), ctx),
+ ).toBe(true);
+ expect(ui.confirmModal).toHaveBeenCalledTimes(2);
+
+ expect(view.result.current.handleTreeKeyDown(keyEvent('Enter'), ctx)).toBe(true);
+ expect(openLocalFile).toHaveBeenCalledWith({
+ deviceId: undefined,
+ filePath: '/repo/root.ts',
+ workingDirectory: '/repo',
+ });
+ });
+
+ it('deletes the whole selection when the focused row is in it', () => {
+ const { node, view } = setup();
+ view.result.current.handleTreeKeyDown(keyEvent('Delete'), {
+ focusedNode: node('root.ts'),
+ selectedNodes: [node('root.ts'), node('src/app.ts')],
+ });
+ expect(ui.confirmModal.mock.calls[0][0].title).toContain('"count":2');
+ });
+
+ it('never deletes a row git reports deleted', () => {
+ const { node, view } = setup();
+ expect(
+ view.result.current.handleTreeKeyDown(keyEvent('Delete'), {
+ focusedNode: node('gone.ts'),
+ selectedNodes: [],
+ }),
+ ).toBe(false);
+ expect(ui.confirmModal).not.toHaveBeenCalled();
+ });
+
+ it('Enter toggles a folder and unrelated keys are left alone', () => {
+ const { node, view } = setup();
+ const ctx = { focusedNode: node('src/'), selectedNodes: [] };
+
+ expect(view.result.current.handleTreeKeyDown(keyEvent('Enter'), ctx)).toBe(true);
+ expect(handle.setExpanded).toHaveBeenCalledWith([PROJECT_ROOT_NODE_ID, 'src/']);
+ expect(view.result.current.handleTreeKeyDown(keyEvent('a'), ctx)).toBe(false);
+ });
+
+ it('⌘C then ⌘V pastes a Finder-style copy into the focused folder', async () => {
+ service.copyProjectFiles.mockResolvedValue([
+ { sourcePath: '/repo/src/app.ts', success: true, targetPath: '/repo/src/app copy.ts' },
+ ]);
+ const { node, view } = setup();
+
+ act(() => {
+ view.result.current.handleTreeKeyDown(keyEvent('c', { metaKey: true }), {
+ focusedNode: node('src/app.ts'),
+ selectedNodes: [],
+ });
+ });
+ await act(async () => {
+ view.result.current.handleTreeKeyDown(keyEvent('v', { metaKey: true }), {
+ focusedNode: node('src/'),
+ selectedNodes: [],
+ });
+ });
+
+ await waitFor(() =>
+ expect(service.copyProjectFiles).toHaveBeenCalledWith({
+ deviceId: undefined,
+ items: [{ sourcePath: '/repo/src/app.ts', targetPath: '/repo/src/app copy.ts' }],
+ workingDirectory: '/repo',
+ }),
+ );
+ expect(service.refreshProjectFiles).toHaveBeenCalled();
+ });
+
+ it('⌘V does nothing with an empty clipboard', () => {
+ const { node, view } = setup();
+ expect(
+ view.result.current.handleTreeKeyDown(keyEvent('v', { metaKey: true }), {
+ focusedNode: node('src/'),
+ selectedNodes: [],
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('useFileTreeActions — cut / paste, duplicate and move', () => {
+ it('cut + paste moves the entry and empties the clipboard', async () => {
+ service.moveProjectFiles.mockResolvedValue([
+ { newPath: '/repo/src/root.ts', sourcePath: '/repo/root.ts', success: true },
+ ]);
+ const { clickMenu, menu } = setup();
+
+ expect(menu('src/').find((item) => item.key === 'paste')?.disabled).toBe(true);
+ clickMenu('root.ts', 'cut');
+ expect(menu('src/').find((item) => item.key === 'paste')?.disabled).toBe(false);
+
+ clickMenu('src/', 'paste');
+
+ await waitFor(() =>
+ expect(service.moveProjectFiles).toHaveBeenCalledWith({
+ deviceId: undefined,
+ items: [{ newPath: '/repo/src/root.ts', oldPath: '/repo/root.ts' }],
+ workingDirectory: '/repo',
+ }),
+ );
+ await waitFor(() => expect(useFileClipboardStore.getState().clipboard).toBeUndefined());
+ expect(retargetLocalFiles).toHaveBeenCalledWith(
+ [{ from: '/repo/root.ts', to: '/repo/src/root.ts' }],
+ undefined,
+ );
+ });
+
+ it('keeps the clipboard scoped to its device and project', () => {
+ const local = setup();
+ local.clickMenu('root.ts', 'copy');
+ const remote = setup({ deviceId: 'dev_1' });
+ expect(remote.menu('src/').find((item) => item.key === 'paste')?.disabled).toBe(true);
+ });
+
+ it('refuses to paste a folder into itself', async () => {
+ const { clickMenu } = setup();
+ clickMenu('src/', 'copy');
+ clickMenu('src/', 'paste');
+
+ await waitFor(() =>
+ expect(ui.error).toHaveBeenCalledWith(expect.stringContaining('feedback.pasteIntoItself')),
+ );
+ expect(service.copyProjectFiles).not.toHaveBeenCalled();
+ });
+
+ it('duplicates next to the source and opens the copy for renaming', async () => {
+ service.copyProjectFiles.mockResolvedValue([
+ { sourcePath: '/repo/root.ts', success: true, targetPath: '/repo/root copy.ts' },
+ ]);
+ const { clickMenu, params, view } = setup();
+
+ clickMenu('root.ts', 'duplicate');
+
+ await waitFor(() =>
+ expect(service.copyProjectFiles).toHaveBeenCalledWith({
+ deviceId: undefined,
+ items: [{ sourcePath: '/repo/root.ts' }],
+ workingDirectory: '/repo',
+ }),
+ );
+ await waitFor(() => expect(service.refreshProjectFiles).toHaveBeenCalled());
+ view.rerender({ ...params, nodes: toNodes([...baseEntries, entry('root copy.ts')]) });
+ expect(handle.startRenaming).toHaveBeenCalledWith('root copy.ts');
+ });
+
+ it('moves dropped rows into the target folder and refuses clashes or self-nesting', async () => {
+ service.moveProjectFiles.mockResolvedValue([
+ { newPath: '/repo/src/root.ts', sourcePath: '/repo/root.ts', success: true },
+ ]);
+ const { node, view } = setup();
+ const canDrop = (sources: string[], target: string) =>
+ view.result.current.canDrop({
+ sourceIds: sources,
+ sourceNodes: sources.map(node),
+ targetId: target,
+ targetNode: node(target),
+ });
+
+ expect(canDrop(['root.ts'], 'src/')).toBe(true);
+ expect(canDrop(['src/'], 'src/')).toBe(false);
+ expect(canDrop([PROJECT_ROOT_NODE_ID], 'src/')).toBe(false);
+
+ await act(() =>
+ view.result.current.onMove({
+ newParentId: 'src/',
+ oldParentId: PROJECT_ROOT_NODE_ID,
+ sourceIds: ['root.ts'],
+ sourceNodes: [node('root.ts')],
+ targetId: 'src/',
+ targetNode: node('src/'),
+ }),
+ );
+ expect(service.moveProjectFiles).toHaveBeenCalledWith({
+ deviceId: undefined,
+ items: [{ newPath: '/repo/src/root.ts', oldPath: '/repo/root.ts' }],
+ workingDirectory: '/repo',
+ });
+ });
+
+ it('refuses a drop onto a same-named entry', () => {
+ const { node, view } = setup({
+ knownEntries: [...baseEntries, entry('src/root.ts')],
+ });
+ expect(
+ view.result.current.canDrop({
+ sourceIds: ['root.ts'],
+ sourceNodes: [node('root.ts')],
+ targetId: 'src/',
+ targetNode: node('src/'),
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps the chat-input drag payload while allowing in-tree moves', () => {
+ const { node, view } = setup();
+ const data = new Map<string, string>();
+ const dataTransfer = {
+ effectAllowed: 'all',
+ setData: (type: string, value: string) => data.set(type, value),
+ setDragImage: vi.fn(),
+ };
+ const row = document.createElement('div');
+ document.body.append(row);
+
+ view.result.current.handleNodeDragStart(node('root.ts'), {
+ currentTarget: row,
+ dataTransfer,
+ } as never);
+
+ expect(JSON.parse(data.get(WORKSPACE_FILE_DRAG_MIME)!)).toEqual({
+ isDirectory: false,
+ name: 'root.ts',
+ path: '/repo/root.ts',
+ });
+ expect(dataTransfer.effectAllowed).toBe('copyMove');
+ });
+});
+
+describe('useFileTreeActions — refresh, terminal and remote', () => {
+ it('refresh re-reads the index, git status and lazy listings', async () => {
+ const { params, view } = setup();
+ await act(() => view.result.current.refresh());
+ expect(service.refreshProjectFiles).toHaveBeenCalledWith(undefined, '/repo');
+ expect(params.invalidateCollapsedChildren).toHaveBeenCalled();
+ expect(view.result.current.refreshing).toBe(false);
+ });
+
+ it('opens a terminal tab in the folder and shows the panel', async () => {
+ const toggleTerminalPanel = vi.fn();
+ useGlobalStore.setState({ toggleTerminalPanel });
+ const { clickMenu } = setup();
+
+ clickMenu('src/app.ts', 'open-in-terminal');
+
+ await waitFor(() => expect(terminal.createTab).toHaveBeenCalledWith('tpc_1', '/repo/src'));
+ await waitFor(() => expect(toggleTerminalPanel).toHaveBeenCalledWith(true));
+ });
+
+ it('reports a terminal that failed to start', async () => {
+ const toggleTerminalPanel = vi.fn();
+ useGlobalStore.setState({ toggleTerminalPanel });
+ terminal.createTab.mockImplementation(async () => {
+ terminal.createErrors = { tpc_1: 'no pty' };
+ });
+ const { clickMenu } = setup();
+
+ clickMenu(PROJECT_ROOT_NODE_ID, 'open-in-terminal');
+
+ await waitFor(() =>
+ expect(ui.error).toHaveBeenCalledWith('workingPanel.files.feedback.terminalFailed'),
+ );
+ expect(terminal.createTab).toHaveBeenCalledWith('tpc_1', '/repo');
+ expect(toggleTerminalPanel).not.toHaveBeenCalled();
+ });
+
+ it('has no terminal or reveal entries on a remote device', () => {
+ const { view } = setup({ deviceId: 'dev_1' });
+ const keys = view.result.current.getBlankContextMenuItems().map((item) => item?.key);
+ expect(keys).not.toContain('open-in-terminal');
+ expect(keys).not.toContain('show-in-system');
+ expect(keys).toEqual(expect.arrayContaining(['new-file', 'new-folder', 'paste', 'refresh']));
+ });
+
+ it('uses the root menu for the project root row', () => {
+ const { menu } = setup();
+ expect(menu(PROJECT_ROOT_NODE_ID).map((item) => item?.key)).toContain('refresh');
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts
new file mode 100644
index 00000000000..661e88baaf9
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts
@@ -0,0 +1,394 @@
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+import { copyToClipboard } from '@lobehub/ui';
+import { toast } from '@lobehub/ui/base-ui';
+import type { DragEvent, KeyboardEvent, RefObject } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { startWorkspaceFileDrag } from '@/features/ChatInput/InputEditor/workspaceFileDragData';
+import type {
+ ExplorerTreeEntryKind,
+ ExplorerTreeHandle,
+ ExplorerTreeKeyDownCtx,
+ ExplorerTreeNode,
+} from '@/features/ExplorerTree';
+import { usePublishWorkspaceHtmlFromFile } from '@/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile';
+import { localFileService } from '@/services/electron/localFileService';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+import { isMacOS } from '@/utils/platform';
+
+import { buildFileContextMenu, type FileMenuAction, type FileMenuTarget } from './fileContextMenu';
+import { resolveFileTreeShortcut } from './fileTreeShortcuts';
+import { getParentRelativePath, PROJECT_ROOT_NODE_ID } from './treePaths';
+import { useFileOperations } from './useFileOperations';
+
+type Node = ExplorerTreeNode<ProjectFileIndexEntry>;
+
+interface UseFileTreeActionsParams {
+ /** Files git reports deleted; their rows no longer exist on disk. */
+ deletedPaths: Set<string>;
+ deviceId?: string;
+ dirtyFilePaths: Set<string>;
+ expandedIds: string[];
+ /** Search, the Git-changes view or a filter is narrowing the tree. */
+ hasDisplayFilter: boolean;
+ invalidateCollapsedChildren: () => void;
+ knownEntries: ProjectFileIndexEntry[];
+ nodes: Node[];
+ onClearDisplayFilter: () => void;
+ onCollapseAll: () => void;
+ projectRoot: string;
+ treeRef: RefObject<ExplorerTreeHandle | null>;
+ workingDirectory: string;
+}
+
+interface PendingCreate {
+ kind: ExplorerTreeEntryKind;
+ parentId: string;
+}
+
+const isDeletedNode = (node: Node, deletedPaths: Set<string>) =>
+ !!node.data && !node.isFolder && deletedPaths.has(node.data.relativePath);
+
+/** Folder a write lands in when aimed at `node`: itself, or a file's parent. */
+const targetFolderId = (node: Node | null | undefined): string => {
+ if (!node?.data) return PROJECT_ROOT_NODE_ID;
+ if (node.isFolder) return node.id;
+ return getParentRelativePath(node.id) ?? PROJECT_ROOT_NODE_ID;
+};
+
+const folderRel = (folderId: string) => (folderId === PROJECT_ROOT_NODE_ID ? '' : folderId);
+
+/**
+ * Everything the Files tree hands to ExplorerTree and its header: context
+ * menus for rows and the blank area, keyboard shortcuts, the header "New"
+ * menu and refresh, drag start/drop, and inline create / rename commits.
+ */
+export const useFileTreeActions = ({
+ deviceId,
+ deletedPaths,
+ dirtyFilePaths,
+ expandedIds,
+ hasDisplayFilter,
+ invalidateCollapsedChildren,
+ knownEntries,
+ nodes,
+ onClearDisplayFilter,
+ onCollapseAll,
+ projectRoot,
+ treeRef,
+ workingDirectory,
+}: UseFileTreeActionsParams) => {
+ const { t } = useTranslation('chat');
+ const isRemote = !!deviceId;
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);
+ const { canOfferFile, publishFile } = usePublishWorkspaceHtmlFromFile({
+ deviceId,
+ workingDirectory: projectRoot,
+ });
+ const nodeIds = useMemo(() => new Set(nodes.map((node) => node.id)), [nodes]);
+ const nodeById = useMemo(() => new Map(nodes.map((node) => [node.id, node])), [nodes]);
+
+ const ops = useFileOperations({
+ deviceId,
+ dirtyFilePaths,
+ expandedIds,
+ invalidateCollapsedChildren,
+ knownEntries,
+ nodeIds,
+ projectRoot,
+ treeRef,
+ workingDirectory,
+ });
+
+ // A new entry typed into a filtered tree would vanish from it, so creation
+ // first drops the filters and opens the input once the full tree is back.
+ const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
+ const startCreate = useCallback(
+ (parentId: string, kind: ExplorerTreeEntryKind) => {
+ if (hasDisplayFilter || !treeRef.current) {
+ onClearDisplayFilter();
+ setPendingCreate({ kind, parentId });
+ return;
+ }
+ ops.startCreate(parentId, kind);
+ },
+ [hasDisplayFilter, onClearDisplayFilter, ops, treeRef],
+ );
+ const startCreateRef = useRef(ops.startCreate);
+ startCreateRef.current = ops.startCreate;
+ useEffect(() => {
+ if (!pendingCreate || hasDisplayFilter) return;
+ const frame = requestAnimationFrame(() => {
+ if (!treeRef.current) return;
+ setPendingCreate(null);
+ startCreateRef.current(pendingCreate.parentId, pendingCreate.kind);
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [hasDisplayFilter, nodes, pendingCreate, treeRef]);
+
+ const openNode = useCallback(
+ (node: Node) => {
+ if (!node.data) return;
+ if (node.isFolder) {
+ if (!isRemote) void ops.openInSystem(node.data);
+ return;
+ }
+ openLocalFile({ deviceId, filePath: node.data.path, workingDirectory: projectRoot });
+ },
+ [deviceId, isRemote, openLocalFile, ops, projectRoot],
+ );
+
+ const handleNodeClick = useCallback(
+ (node: Node) => {
+ // Folders expand via the tree; files open in the preview panel.
+ if (node.isFolder) return;
+ openNode(node);
+ },
+ [openNode],
+ );
+
+ // Dragging a row into the chat input inserts a `<localFile />` mention; the
+ // tree itself moves rows on drop. The helper marks the drag copy-only for the
+ // input, so widen it to copyMove or the tree's own "move" drop is refused.
+ const handleNodeDragStart = useCallback((node: Node, event: DragEvent<HTMLElement>) => {
+ if (!node.data) return;
+ startWorkspaceFileDrag(event, {
+ isDirectory: !!node.isFolder,
+ name: node.data.name,
+ path: node.data.path,
+ });
+ event.dataTransfer.effectAllowed = 'copyMove';
+ }, []);
+
+ /** Right-click on a row inside a multi-selection acts on the whole selection. */
+ const entriesFor = useCallback(
+ (node: Node): ProjectFileIndexEntry[] => {
+ const selected = treeRef.current?.getSelectedIds() ?? [];
+ const ids = selected.includes(node.id) ? selected : [node.id];
+ return ids
+ .map((id) => nodeById.get(id))
+ .filter((item): item is Node => !!item?.data && !isDeletedNode(item, deletedPaths))
+ .map((item) => item.data!);
+ },
+ [deletedPaths, nodeById, treeRef],
+ );
+
+ const copyText = useCallback(
+ async (text: string) => {
+ await copyToClipboard(text);
+ toast.success(t('workingPanel.review.copied'));
+ },
+ [t],
+ );
+
+ const runAction = useCallback(
+ (action: FileMenuAction, node: Node | null) => {
+ const entry = node?.data;
+ const folderId = targetFolderId(node);
+ const folderPath = ops.toAbsolute(folderRel(folderId));
+ switch (action) {
+ case 'newFile':
+ case 'newFolder': {
+ startCreate(folderId, action === 'newFile' ? 'file' : 'folder');
+ return;
+ }
+ case 'open': {
+ if (node) openNode(node);
+ return;
+ }
+ case 'openInSystem': {
+ if (entry) void ops.openInSystem(entry);
+ return;
+ }
+ case 'publish': {
+ if (entry) void publishFile(entry.path);
+ return;
+ }
+ case 'revealInSystem': {
+ void localFileService.openFileFolder(entry?.path ?? projectRoot);
+ return;
+ }
+ case 'openInTerminal': {
+ void ops.openInTerminal(folderPath);
+ return;
+ }
+ case 'showInReview': {
+ openWorkingSidebar('review');
+ return;
+ }
+ case 'copy':
+ case 'cut': {
+ if (node) ops.putOnClipboard(entriesFor(node), action);
+ return;
+ }
+ case 'paste': {
+ void ops.paste(folderRel(folderId));
+ return;
+ }
+ case 'duplicate': {
+ if (entry) void ops.duplicate(entry);
+ return;
+ }
+ case 'copyPath': {
+ void copyText(entry?.path ?? projectRoot);
+ return;
+ }
+ case 'copyRelativePath': {
+ if (entry) void copyText(entry.relativePath);
+ return;
+ }
+ case 'rename': {
+ if (node) treeRef.current?.startRenaming(node.id);
+ return;
+ }
+ case 'trash': {
+ if (node) ops.trash(entriesFor(node));
+ return;
+ }
+ case 'refresh': {
+ void ops.refresh();
+ return;
+ }
+ case 'collapseAll': {
+ onCollapseAll();
+ return;
+ }
+ }
+ },
+ [
+ copyText,
+ entriesFor,
+ onCollapseAll,
+ openNode,
+ openWorkingSidebar,
+ ops,
+ projectRoot,
+ publishFile,
+ startCreate,
+ treeRef,
+ ],
+ );
+
+ const menuEnv = useCallback(
+ (canPublish: boolean) => ({
+ canPaste: ops.canPaste,
+ canPublish,
+ canUseTerminal: ops.canUseTerminal,
+ isRemote,
+ trashName: ops.trashName,
+ }),
+ [isRemote, ops.canPaste, ops.canUseTerminal, ops.trashName],
+ );
+
+ const getBlankContextMenuItems = useCallback(
+ () =>
+ buildFileContextMenu(
+ { kind: 'root' },
+ menuEnv(false),
+ (action) => runAction(action, null),
+ t,
+ ),
+ [menuEnv, runAction, t],
+ );
+
+ const getContextMenuItems = useCallback(
+ (node: Node) => {
+ if (!node.data) return getBlankContextMenuItems();
+ const target: FileMenuTarget = {
+ isDeleted: isDeletedNode(node, deletedPaths),
+ isDirty: dirtyFilePaths.has(node.data.relativePath),
+ kind: node.isFolder ? 'folder' : 'file',
+ };
+ return buildFileContextMenu(
+ target,
+ menuEnv(canOfferFile(node.data.path, !!node.isFolder)),
+ (action) => runAction(action, node),
+ t,
+ );
+ },
+ [canOfferFile, deletedPaths, dirtyFilePaths, getBlankContextMenuItems, menuEnv, runAction, t],
+ );
+
+ const isMac = useMemo(() => isMacOS(), []);
+ const handleTreeKeyDown = useCallback(
+ (
+ event: KeyboardEvent<HTMLElement>,
+ { focusedNode, selectedNodes }: ExplorerTreeKeyDownCtx<ProjectFileIndexEntry>,
+ ) => {
+ const shortcut = resolveFileTreeShortcut(event, isMac);
+ if (!shortcut) return false;
+ const targets =
+ focusedNode && !selectedNodes.some((node) => node.id === focusedNode.id)
+ ? [focusedNode]
+ : selectedNodes;
+ const entries = targets
+ .filter((node) => node.data && !isDeletedNode(node, deletedPaths))
+ .map((node) => node.data!);
+
+ switch (shortcut) {
+ case 'open': {
+ if (!focusedNode) return false;
+ if (!focusedNode.isFolder) {
+ openNode(focusedNode);
+ return true;
+ }
+ const expanded = expandedIds.includes(focusedNode.id);
+ treeRef.current?.setExpanded(
+ expanded
+ ? expandedIds.filter((id) => id !== focusedNode.id)
+ : [...expandedIds, focusedNode.id],
+ );
+ return true;
+ }
+ case 'delete': {
+ if (entries.length === 0) return false;
+ ops.trash(entries);
+ return true;
+ }
+ case 'copy':
+ case 'cut': {
+ if (entries.length === 0) return false;
+ ops.putOnClipboard(entries, shortcut);
+ return true;
+ }
+ case 'paste': {
+ if (!ops.canPaste) return false;
+ void ops.paste(folderRel(targetFolderId(focusedNode)));
+ return true;
+ }
+ }
+ },
+ [deletedPaths, expandedIds, isMac, openNode, ops, treeRef],
+ );
+
+ // Header "New" menu: into the selected folder, next to a selected file, or at the root.
+ const startCreateFromHeader = useCallback(
+ (kind: ExplorerTreeEntryKind) => {
+ const [selectedId] = treeRef.current?.getSelectedIds() ?? [];
+ startCreate(targetFolderId(selectedId ? nodeById.get(selectedId) : null), kind);
+ },
+ [nodeById, startCreate, treeRef],
+ );
+
+ return {
+ canDrag: (node: Node) => !!node.data && !isDeletedNode(node, deletedPaths),
+ canDrop: ops.canDrop,
+ canRename: (node: Node) => !!node.data && !isDeletedNode(node, deletedPaths),
+ getBlankContextMenuItems,
+ getContextMenuItems,
+ handleNodeClick,
+ handleNodeDragStart,
+ handleTreeKeyDown,
+ onCommitCreate: ops.commitCreate,
+ onCommitRename: ops.commitRename,
+ onMove: ops.move,
+ pendingCreate: !!pendingCreate,
+ refresh: ops.refresh,
+ refreshing: ops.refreshing,
+ startCreateFromHeader,
+ validateName: ops.validateName,
+ };
+};
diff --git a/src/features/ExplorerTree/documentTreeStyle.test.ts b/src/features/ExplorerTree/documentTreeStyle.test.ts
index 6ea3bece32a..f0c95e403a4 100644
--- a/src/features/ExplorerTree/documentTreeStyle.test.ts
+++ b/src/features/ExplorerTree/documentTreeStyle.test.ts
@@ -66,21 +66,27 @@ describe('code tree call sites', () => {
const read = (relativePath: string) =>
readFileSync(join(__dirname, '..', '..', '..', 'src', relativePath), 'utf8');
- const CODE_TREE_FILES = [
- 'features/Conversation/WorkingSidebar/Files/index.tsx',
- 'features/Conversation/WorkingSidebar/Review/FileTreeNav.tsx',
- ];
+ // A tree may keep its pierre CSS bundle in a sibling module; read those together.
+ const CODE_TREE_FILES: Record<string, string[]> = {
+ 'features/Conversation/WorkingSidebar/Files/index.tsx': [
+ 'features/Conversation/WorkingSidebar/Files/fileTreeStyle.ts',
+ ],
+ 'features/Conversation/WorkingSidebar/Review/FileTreeNav.tsx': [],
+ };
- it.each(CODE_TREE_FILES)('%s renders with FOLDER_ICON_CSS and no document tokens', (file) => {
- const source = read(file);
- expect(source).toContain('FOLDER_ICON_CSS');
- expect(source).not.toContain('DOCUMENT_TREE_ICON_CSS');
- expect(source).not.toContain('DOCUMENT_TREE_ROW_CSS');
- expect(source).not.toContain('DOCUMENT_TREE_LAYOUT');
- // They keep their own pre-existing 12px label and pierre's default 30px row
- // (no `itemHeight` prop) — that is what "文件的那个 tree 渲染保留原样" means.
- // The document tree's 14px / 36px must never reach them.
- expect(source).toContain('--trees-font-size-override: 12px');
- expect(source).not.toContain('itemHeight');
- });
+ it.each(Object.keys(CODE_TREE_FILES))(
+ '%s renders with FOLDER_ICON_CSS and no document tokens',
+ (file) => {
+ const source = [file, ...CODE_TREE_FILES[file]].map(read).join('\n');
+ expect(source).toContain('FOLDER_ICON_CSS');
+ expect(source).not.toContain('DOCUMENT_TREE_ICON_CSS');
+ expect(source).not.toContain('DOCUMENT_TREE_ROW_CSS');
+ expect(source).not.toContain('DOCUMENT_TREE_LAYOUT');
+ // They keep their own pre-existing 12px label and pierre's default 30px row
+ // (no `itemHeight` prop) — that is what "文件的那个 tree 渲染保留原样" means.
+ // The document tree's 14px / 36px must never reach them.
+ expect(source).toContain('--trees-font-size-override: 12px');
+ expect(source).not.toContain('itemHeight');
+ },
+ );
});
diff --git a/src/features/ExplorerTree/index.tsx b/src/features/ExplorerTree/index.tsx
index 2e2452f4dea..08541434841 100644
--- a/src/features/ExplorerTree/index.tsx
+++ b/src/features/ExplorerTree/index.tsx
@@ -11,8 +11,12 @@ export {
} from './folderIconStyle';
export type {
ExplorerTreeCanDropCtx,
+ ExplorerTreeCreateEvent,
+ ExplorerTreeEntryKind,
ExplorerTreeHandle,
+ ExplorerTreeKeyDownCtx,
ExplorerTreeMoveEvent,
+ ExplorerTreeNameCheck,
ExplorerTreeNode,
ExplorerTreeProps,
ExplorerTreeRowDecorationCtx,
diff --git a/src/features/ExplorerTree/types.ts b/src/features/ExplorerTree/types.ts
index 16e82b0ec49..1f0c774214f 100644
--- a/src/features/ExplorerTree/types.ts
+++ b/src/features/ExplorerTree/types.ts
@@ -1,5 +1,5 @@
import type { FileTreeRowDecoration, GitStatusEntry } from '@pierre/trees';
-import type { CSSProperties, DragEvent, MouseEvent, ReactNode } from 'react';
+import type { CSSProperties, DragEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';
import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
@@ -34,12 +34,48 @@ export interface ExplorerTreeRowDecorationCtx<TData = unknown> {
node: ExplorerTreeNode<TData>;
}
+export type ExplorerTreeEntryKind = 'file' | 'folder';
+
+/** What `validateName` is asked to check while an inline name input is open. */
+export type ExplorerTreeNameCheck<TData = unknown> =
+ | {
+ kind: ExplorerTreeEntryKind;
+ mode: 'create';
+ name: string;
+ /** `null` when the new entry lands at the top level of the tree. */
+ parentNode: ExplorerTreeNode<TData> | null;
+ }
+ | { mode: 'rename'; name: string; node: ExplorerTreeNode<TData> };
+
+export interface ExplorerTreeCreateEvent<TData = unknown> {
+ kind: ExplorerTreeEntryKind;
+ name: string;
+ parentNode: ExplorerTreeNode<TData> | null;
+}
+
+export interface ExplorerTreeKeyDownCtx<TData = unknown> {
+ focusedNode: ExplorerTreeNode<TData> | null;
+ selectedNodes: ExplorerTreeNode<TData>[];
+}
+
export interface ExplorerTreeHandle {
deselect: (id: string) => void;
focus: (id: string) => void;
+ getFocusedId: () => string | null;
getSelectedIds: () => string[];
+ /**
+ * Re-applies the current `nodes` to the tree model, dropping any optimistic
+ * rename / move / create the tree applied on its own.
+ */
+ resync: () => void;
select: (id: string, opts?: { additive?: boolean }) => void;
setExpanded: (ids: string[]) => void;
+ /**
+ * Inserts a placeholder row under `parentId` (`null` = top level) and opens
+ * the inline name input on it. Committing calls `onCommitCreate`; an empty
+ * name or Escape removes the placeholder.
+ */
+ startCreating: (parentId: string | null, kind: ExplorerTreeEntryKind) => void;
startRenaming: (id: string) => void;
}
@@ -56,6 +92,8 @@ export interface ExplorerTreeProps<TData = unknown> {
defaultSelectedIds?: string[];
density?: 'compact' | 'default' | 'relaxed' | number;
expandedIds?: string[];
+ /** Menu for a right click that lands on no row (the blank area under the rows). */
+ getBlankContextMenuItems?: () => NativeContextMenuItem[];
getContextMenuItems?: (node: ExplorerTreeNode<TData>) => NativeContextMenuItem[];
getRowDecoration?: (
ctx: ExplorerTreeRowDecorationCtx<TData>,
@@ -66,21 +104,45 @@ export interface ExplorerTreeProps<TData = unknown> {
iconSet?: 'minimal' | 'standard' | 'complete' | 'none';
itemHeight?: number;
nodes: ExplorerTreeNode<TData>[];
- onCommitRename?: (node: ExplorerTreeNode<TData>, newName: string) => void | Promise<void>;
+ /** Resolve `false` when creation failed so the optimistic row is dropped. */
+ onCommitCreate?: (
+ event: ExplorerTreeCreateEvent<TData>,
+ ) => boolean | void | Promise<boolean | void>;
+ /** Resolve `false` when the rename failed so the tree rolls the row back. */
+ onCommitRename?: (
+ node: ExplorerTreeNode<TData>,
+ newName: string,
+ ) => boolean | void | Promise<boolean | void>;
onExpandedChange?: (ids: string[]) => void;
onExternalDrop?: (event: {
nativeEvent: DragEvent<HTMLElement>;
targetId: string | null;
targetNode: ExplorerTreeNode<TData> | null;
}) => void;
- onMove?: (event: ExplorerTreeMoveEvent<TData>) => void | Promise<void>;
+ /** Resolve `false` when the move failed so the tree rolls the drop back. */
+ onMove?: (event: ExplorerTreeMoveEvent<TData>) => boolean | void | Promise<boolean | void>;
onNodeClick?: (node: ExplorerTreeNode<TData>, event: MouseEvent<HTMLElement>) => void;
onNodeDragStart?: (node: ExplorerTreeNode<TData>, event: DragEvent<HTMLElement>) => void;
onRenameError?: (error: unknown, node: ExplorerTreeNode<TData>) => void;
onSelectedChange?: (ids: string[]) => void;
+ /**
+ * Keys pressed on a tree row (never inside the rename or search input).
+ * Return `true` when handled; the event is then stopped so it can't reach
+ * page-level shortcuts.
+ */
+ onTreeKeyDown?: (
+ event: KeyboardEvent<HTMLElement>,
+ ctx: ExplorerTreeKeyDownCtx<TData>,
+ ) => boolean | void;
overscan?: number;
selectedIds?: string[];
style?: CSSProperties;
/** Raw CSS injected into the pierre/trees shadow DOM via FILE_TREE_UNSAFE_CSS_ATTRIBUTE. */
unsafeCSS?: string;
+ /**
+ * Checks a name typed into the inline input. Return a message to show it
+ * under the input and block the commit (Enter or blur); the input stays open
+ * with the user's text.
+ */
+ validateName?: (check: ExplorerTreeNameCheck<TData>) => string | null | undefined;
}
diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
index e3a19b79bb2..d1d3cc48f7e 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
@@ -1,5 +1,6 @@
import { AGENT_DOCUMENT_CATEGORY, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
+import type { RefObject } from 'react';
import { useRef } from 'react';
import { MemoryRouter } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
@@ -221,3 +222,183 @@ describe('DocumentExplorerTree menu ownership', () => {
expect(toNativeTemplate(items).template).toMatchSnapshot();
});
});
+
+// ─── inline create / rename, blank-area menu and keys ────────────────────────
+
+const inlineNodes: ExplorerTreeNode<{ path: string }>[] = [
+ { id: 'root', isFolder: true, name: 'repo', parentId: null },
+ { data: { path: 'src' }, id: 'src/', isFolder: true, name: 'src', parentId: 'root' },
+ { data: { path: 'a.ts' }, id: 'a.ts', isFolder: false, name: 'a.ts', parentId: 'root' },
+];
+
+const getHost = (container: HTMLElement) => container.querySelector('file-tree-container')!;
+
+const waitForRenameInput = (container: HTMLElement) =>
+ waitFor(() => {
+ const input = getHost(container).shadowRoot?.querySelector('[data-item-rename-input]');
+ expect(input).toBeInstanceOf(HTMLInputElement);
+ return input as HTMLInputElement;
+ });
+
+const renderTree = (props: Partial<Parameters<typeof ExplorerTree>[0]> = {}) => {
+ const ref: RefObject<ExplorerTreeHandle | null> = { current: null };
+ const view = render(
+ <ExplorerTree defaultExpandedIds={['root']} nodes={inlineNodes} ref={ref} {...props} />,
+ );
+ return { ...view, ref };
+};
+
+describe('ExplorerTree inline create', () => {
+ it('opens an empty inline input under the parent and commits the typed name', async () => {
+ const onCommitCreate = vi.fn();
+ const { container, ref } = renderTree({ onCommitCreate });
+
+ act(() => ref.current?.startCreating('src/', 'file'));
+ const input = await waitForRenameInput(container);
+ // The placeholder's own name never shows: the input starts empty.
+ await waitFor(() => expect(input.value).toBe(''));
+
+ fireEvent.input(input, { target: { value: 'notes/today.md' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ await waitFor(() =>
+ expect(onCommitCreate).toHaveBeenCalledWith({
+ kind: 'file',
+ name: 'notes/today.md',
+ parentNode: expect.objectContaining({ id: 'src/' }),
+ }),
+ );
+ });
+
+ it('drops the placeholder without committing when the name is left empty', async () => {
+ const onCommitCreate = vi.fn();
+ const { container, ref } = renderTree({ onCommitCreate });
+
+ act(() => ref.current?.startCreating('root', 'folder'));
+ const input = await waitForRenameInput(container);
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ await waitFor(() =>
+ expect(getHost(container).shadowRoot?.querySelector('[data-item-rename-input]')).toBeNull(),
+ );
+ expect(onCommitCreate).not.toHaveBeenCalled();
+ });
+
+ it('keeps the input open with a hint while validateName rejects the name', async () => {
+ const onCommitCreate = vi.fn();
+ const validateName = vi.fn((check: { name: string }) =>
+ check.name === 'a.ts' ? 'already exists' : null,
+ );
+ const { container, ref } = renderTree({ onCommitCreate, validateName });
+
+ act(() => ref.current?.startCreating('root', 'file'));
+ const input = await waitForRenameInput(container);
+ fireEvent.input(input, { target: { value: 'a.ts' } });
+
+ // Live hint while typing…
+ await waitFor(() =>
+ expect(document.body.querySelector('[role="alert"]')?.textContent).toBe('already exists'),
+ );
+ expect(validateName).toHaveBeenLastCalledWith(
+ expect.objectContaining({ kind: 'file', mode: 'create', name: 'a.ts' }),
+ );
+
+ // …and neither Enter nor blur commits it.
+ fireEvent.keyDown(input, { key: 'Enter' });
+ fireEvent.blur(input);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(onCommitCreate).not.toHaveBeenCalled();
+ expect(getHost(container).shadowRoot?.querySelector('[data-item-rename-input]')).toBe(input);
+ expect(input.value).toBe('a.ts');
+
+ // Fixing the name clears the hint and commits.
+ fireEvent.input(input, { target: { value: 'b.ts' } });
+ await waitFor(() => expect(document.body.querySelector('[role="alert"]')).toBeNull());
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() =>
+ expect(onCommitCreate).toHaveBeenCalledWith(expect.objectContaining({ name: 'b.ts' })),
+ );
+ });
+});
+
+describe('ExplorerTree inline rename validation', () => {
+ it('blocks a rename that validateName rejects and commits a valid one', async () => {
+ const onCommitRename = vi.fn();
+ const validateName = vi.fn((check: { name: string }) =>
+ check.name.includes(':') ? 'bad name' : null,
+ );
+ const { container, ref } = renderTree({ onCommitRename, validateName });
+
+ act(() => ref.current?.startRenaming('a.ts'));
+ const input = await waitForRenameInput(container);
+
+ fireEvent.input(input, { target: { value: 'a:b.ts' } });
+ fireEvent.blur(input);
+ expect(onCommitRename).not.toHaveBeenCalled();
+ expect(validateName).toHaveBeenLastCalledWith(
+ expect.objectContaining({ mode: 'rename', node: expect.objectContaining({ id: 'a.ts' }) }),
+ );
+
+ fireEvent.input(input, { target: { value: 'b.ts' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onCommitRename).toHaveBeenCalledWith(expect.objectContaining({ id: 'a.ts' }), 'b.ts');
+ });
+});
+
+describe('ExplorerTree blank area and keys', () => {
+ it('opens the blank-area menu for a right click that hits no row', () => {
+ showContextMenu.mockClear();
+ const getBlankContextMenuItems = vi.fn(() => [{ key: 'refresh', label: 'Refresh' }]);
+ const { container } = renderTree({ getBlankContextMenuItems });
+
+ fireEvent.contextMenu(getHost(container));
+
+ expect(getBlankContextMenuItems).toHaveBeenCalledTimes(1);
+ expect(showContextMenu).toHaveBeenCalledWith([
+ expect.objectContaining({ key: 'refresh', label: 'Refresh' }),
+ ]);
+ });
+
+ it('hands row keys to onTreeKeyDown and stops the ones it handles', () => {
+ const onTreeKeyDown = vi.fn((event: { key: string }, _ctx: unknown) => event.key === 'Delete');
+ const outer = vi.fn();
+ const { container } = render(
+ <div onKeyDown={outer}>
+ <ExplorerTree
+ defaultExpandedIds={['root']}
+ nodes={inlineNodes}
+ onTreeKeyDown={onTreeKeyDown}
+ />
+ </div>,
+ );
+
+ fireEvent.keyDown(getHost(container), { key: 'Delete' });
+ fireEvent.keyDown(getHost(container), { key: 'a' });
+
+ expect(onTreeKeyDown).toHaveBeenCalledTimes(2);
+ expect(onTreeKeyDown.mock.calls[0][1]).toEqual({
+ focusedNode: expect.objectContaining({ id: 'root' }),
+ selectedNodes: [],
+ });
+ // Delete was handled, so only the unhandled key reached the page.
+ expect(outer).toHaveBeenCalledTimes(1);
+ });
+
+ it('rolls an optimistic rename back when onCommitRename resolves false', async () => {
+ const onCommitRename = vi.fn(async () => false as const);
+ const { container, ref } = renderTree({ onCommitRename });
+
+ act(() => ref.current?.startRenaming('a.ts'));
+ const input = await waitForRenameInput(container);
+ fireEvent.input(input, { target: { value: 'b.ts' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ const rowPath = (path: string) =>
+ getHost(container).shadowRoot?.querySelector(`[data-item-path="${path}"]`);
+ await waitFor(() => expect(onCommitRename).toHaveBeenCalled());
+ await waitFor(() => {
+ expect(rowPath('repo/a.ts')).not.toBeNull();
+ expect(rowPath('repo/b.ts')).toBeNull();
+ });
+ });
+});
diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsx
index 20248cc1d6f..6486d601d5c 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx
@@ -8,7 +8,7 @@ import type {
} from '@pierre/trees';
import { FileTree as PierreFileTree, useFileTree, useFileTreeSelection } from '@pierre/trees/react';
import debug from 'debug';
-import type { DragEvent, ForwardedRef, MouseEvent } from 'react';
+import type { DragEvent, ForwardedRef, KeyboardEvent, MouseEvent } from 'react';
import {
forwardRef,
useCallback,
@@ -30,6 +30,9 @@ import type {
ExplorerTreeProps,
} from '../types';
import { openExplorerContextMenu } from './ContextMenu';
+import { getItemPathFromEventPath } from './eventPath';
+import NameInputHint from './NameInputHint';
+import { type PendingCreate, useInlineNameEdit } from './useInlineNameEdit';
const log = debug('lobe-explorer-tree');
@@ -59,8 +62,6 @@ const getItemSafely = (model: FileTreeModel, path: string): FileTreeItemHandle |
type ExplorerTreeHostEvent = DragEvent<HTMLElement> | MouseEvent<HTMLElement>;
-const isHTMLElement = (target: EventTarget): target is HTMLElement => target instanceof HTMLElement;
-
const getComposedPath = (event: ExplorerTreeHostEvent): EventTarget[] => {
const path = event.nativeEvent.composedPath();
if (path.length > 0) return path;
@@ -70,18 +71,7 @@ const getComposedPath = (event: ExplorerTreeHostEvent): EventTarget[] => {
);
};
-export const getItemPathFromEventPath = (path: EventTarget[]): string | null => {
- for (const target of path) {
- if (!isHTMLElement(target)) continue;
- const flattenedSegmentPath = target.getAttribute('data-item-flattened-subitem');
- if (flattenedSegmentPath) return flattenedSegmentPath;
- if (target.dataset.type !== 'item') continue;
- const path = target.dataset.itemPath;
- if (path) return path;
- }
-
- return null;
-};
+export { getItemPathFromEventPath } from './eventPath';
const getItemPathFromHostEvent = (event: ExplorerTreeHostEvent): string | null =>
getItemPathFromEventPath(getComposedPath(event));
@@ -110,6 +100,7 @@ function ExplorerTreeInner<TData>(
);
const suppressModelEventsRef = useRef(false);
const renamingRef = useRef(false);
+ const pendingCreateRef = useRef<PendingCreate | null>(null);
const initialOptions = useMemo((): FileTreeOptions => {
const initial = adapterRef.current;
@@ -188,7 +179,12 @@ function ExplorerTreeInner<TData>(
targetId,
targetNode: targetId ? (a.nodeById.get(targetId) ?? null) : null,
};
- void onMove(moveEvent);
+ void Promise.resolve(onMove(moveEvent)).then(
+ (result) => {
+ if (result === false) resyncRef.current();
+ },
+ () => resyncRef.current(),
+ );
},
},
icons: {
@@ -211,6 +207,7 @@ function ExplorerTreeInner<TData>(
renaming: {
canRename: (item) => {
const path = toCanonicalTreePath(item.path, item.isFolder);
+ if (pendingCreateRef.current?.path === path) return true;
const node = adapterRef.current.nodeById.get(adapterRef.current.idByPath.get(path) ?? '');
if (!node) return false;
const fn = propsRef.current.canRename;
@@ -229,12 +226,20 @@ function ExplorerTreeInner<TData>(
renamingNodeRef.current = node;
const newName = extractName(destinationPath);
const result = propsRef.current.onCommitRename?.(node, newName);
- if (result && typeof (result as Promise<void>).then === 'function') {
- (result as Promise<void>).finally(() => {
- renamingNodeRef.current = null;
- renamingRef.current = false;
- });
+ if (result && typeof (result as Promise<boolean | void>).then === 'function') {
+ (result as Promise<boolean | void>)
+ .then(
+ (value) => {
+ if (value === false) resyncRef.current();
+ },
+ () => resyncRef.current(),
+ )
+ .finally(() => {
+ renamingNodeRef.current = null;
+ renamingRef.current = false;
+ });
} else {
+ if (result === false) queueMicrotask(() => resyncRef.current());
renamingNodeRef.current = null;
renamingRef.current = false;
}
@@ -259,6 +264,43 @@ function ExplorerTreeInner<TData>(
const renamingNodeRef = useRef<ExplorerTreeNode<TData> | null>(null);
const { model } = useFileTree(initialOptions);
+ // Drops whatever the tree applied optimistically (rename, drop, new row) by
+ // re-applying the current nodes, keeping expansion, selection and focus.
+ const resync = useCallback(() => {
+ const a = adapterRef.current;
+ const expandedPaths: string[] = [];
+ for (const path of a.paths) {
+ if (asDirectory(getItemSafely(model, path))?.isExpanded()) expandedPaths.push(path);
+ }
+ const selectedPaths = model.getSelectedPaths().filter((path) => a.idByPath.has(path));
+ const focusedPath = model.getFocusedPath();
+ pendingCreateRef.current = null;
+ suppressModelEventsRef.current = true;
+ try {
+ for (const path of model.getSelectedPaths()) {
+ if (!a.idByPath.has(path)) getItemSafely(model, path)?.deselect();
+ }
+ model.resetPaths(a.paths, { initialExpandedPaths: expandedPaths });
+ for (const path of selectedPaths) getItemSafely(model, path)?.select();
+ if (focusedPath && a.idByPath.has(focusedPath)) model.focusPath(focusedPath);
+ } catch (error) {
+ log('resync failed, rebuilding the tree: %O', error);
+ requestTreeRebuild();
+ } finally {
+ suppressModelEventsRef.current = false;
+ }
+ }, [adapterRef, model, requestTreeRebuild]);
+ const resyncRef = useRef(resync);
+ resyncRef.current = resync;
+
+ const { hint, selectRenameStem, startCreating } = useInlineNameEdit({
+ adapterRef,
+ model,
+ pendingCreateRef,
+ propsRef,
+ resync,
+ });
+
// Observe selection changes so external consumers see updates without needing to pass a selection listener.
useFileTreeSelection(model);
@@ -465,7 +507,12 @@ function ExplorerTreeInner<TData>(
if (!path || !getItemSafely(model, path)) return;
model.focusPath(path);
},
+ getFocusedId: () => {
+ const path = model.getFocusedPath();
+ return path ? (adapterRef.current.idByPath.get(path) ?? null) : null;
+ },
getSelectedIds: () => remapPathsToIds(model.getSelectedPaths(), adapterRef.current.idByPath),
+ resync,
select: (id, opts) => {
const path = adapterRef.current.pathById.get(id);
if (!path) return;
@@ -485,21 +532,28 @@ function ExplorerTreeInner<TData>(
else if (!shouldExpand && dir.isExpanded()) dir.collapse();
}
},
+ startCreating,
startRenaming: (id) => {
const path = adapterRef.current.pathById.get(id);
if (!path || !getItemSafely(model, path)) return;
renamingRef.current = true;
- model.startRenaming(path);
+ if (model.startRenaming(path)) selectRenameStem(path.endsWith('/'));
},
}),
- [adapterRef, model],
+ [adapterRef, model, resync, selectRenameStem, startCreating],
);
const handleContextMenu = (event: MouseEvent<HTMLElement>) => {
const fn = propsRef.current.getContextMenuItems;
- if (!fn) return;
const itemPath = getItemPathFromHostEvent(event);
- if (!itemPath) return;
+ if (!itemPath) {
+ const blankItems = propsRef.current.getBlankContextMenuItems?.();
+ if (!blankItems || blankItems.length === 0) return;
+ event.preventDefault();
+ openExplorerContextMenu(blankItems);
+ return;
+ }
+ if (!fn) return;
const a = adapterRef.current;
const id = a.idByPath.get(itemPath);
if (!id) return;
@@ -552,17 +606,42 @@ function ExplorerTreeInner<TData>(
onNodeDragStart(node, event);
};
+ const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
+ const onTreeKeyDown = propsRef.current.onTreeKeyDown;
+ if (!onTreeKeyDown) return;
+ // Keys typed into the rename or search input belong to that input.
+ const [origin] = event.nativeEvent.composedPath();
+ if (origin instanceof HTMLInputElement || origin instanceof HTMLTextAreaElement) return;
+ const a = adapterRef.current;
+ const toNode = (path: string) => a.nodeById.get(a.idByPath.get(path) ?? '');
+ const focusedPath = model.getFocusedPath();
+ const handled = onTreeKeyDown(event, {
+ focusedNode: (focusedPath && toNode(focusedPath)) || null,
+ selectedNodes: model
+ .getSelectedPaths()
+ .map(toNode)
+ .filter((node): node is ExplorerTreeNode<TData> => !!node),
+ });
+ if (!handled) return;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
return (
- <PierreFileTree
- className={props.className}
- header={props.header}
- model={model}
- style={props.style}
- onClick={handleClick}
- onContextMenu={handleContextMenu}
- onDragStart={handleDragStart}
- onDropCapture={handleDropCapture}
- />
+ <>
+ <PierreFileTree
+ className={props.className}
+ header={props.header}
+ model={model}
+ style={props.style}
+ onClick={handleClick}
+ onContextMenu={handleContextMenu}
+ onDragStart={handleDragStart}
+ onDropCapture={handleDropCapture}
+ onKeyDown={handleKeyDown}
+ />
+ {hint && <NameInputHint hint={hint} />}
+ </>
);
}
diff --git a/src/features/ExplorerTree/view/NameInputHint.tsx b/src/features/ExplorerTree/view/NameInputHint.tsx
new file mode 100644
index 00000000000..66d2bec50db
--- /dev/null
+++ b/src/features/ExplorerTree/view/NameInputHint.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { createStaticStyles } from 'antd-style';
+
+import type { NameInputHintState } from './useInlineNameEdit';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ hint: css`
+ pointer-events: none;
+
+ position: fixed;
+ z-index: 1100;
+
+ padding-block: 4px;
+ padding-inline: 8px;
+ border: 1px solid ${cssVar.colorErrorBorder};
+ border-radius: 6px;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorError};
+
+ background: ${cssVar.colorErrorBg};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+}));
+
+/**
+ * One-line validation message pinned under the tree's inline name input.
+ * Rendered in place (not portalled to body) so it stays inside the theme root
+ * that defines the color tokens.
+ */
+const NameInputHint = ({ hint }: { hint: NameInputHintState }) => (
+ <div
+ className={styles.hint}
+ role={'alert'}
+ style={{ left: hint.left, minWidth: hint.width, top: hint.top + 2 }}
+ >
+ {hint.message}
+ </div>
+);
+
+export default NameInputHint;
diff --git a/src/features/ExplorerTree/view/eventPath.ts b/src/features/ExplorerTree/view/eventPath.ts
new file mode 100644
index 00000000000..3dab8e639bd
--- /dev/null
+++ b/src/features/ExplorerTree/view/eventPath.ts
@@ -0,0 +1,15 @@
+const isHTMLElement = (target: EventTarget): target is HTMLElement => target instanceof HTMLElement;
+
+/** Tree path of the row an event came from, read off the composed (shadow-piercing) path. */
+export const getItemPathFromEventPath = (path: EventTarget[]): string | null => {
+ for (const target of path) {
+ if (!isHTMLElement(target)) continue;
+ const flattenedSegmentPath = target.getAttribute('data-item-flattened-subitem');
+ if (flattenedSegmentPath) return flattenedSegmentPath;
+ if (target.dataset.type !== 'item') continue;
+ const path = target.dataset.itemPath;
+ if (path) return path;
+ }
+
+ return null;
+};
diff --git a/src/features/ExplorerTree/view/useInlineNameEdit.ts b/src/features/ExplorerTree/view/useInlineNameEdit.ts
new file mode 100644
index 00000000000..5b552996f07
--- /dev/null
+++ b/src/features/ExplorerTree/view/useInlineNameEdit.ts
@@ -0,0 +1,306 @@
+'use client';
+
+import type { useFileTree } from '@pierre/trees/react';
+import debug from 'debug';
+import type { RefObject } from 'react';
+import { useCallback, useEffect, useState } from 'react';
+
+import type { NormalizedTree } from '../adapter';
+import type {
+ ExplorerTreeEntryKind,
+ ExplorerTreeNameCheck,
+ ExplorerTreeNode,
+ ExplorerTreeProps,
+} from '../types';
+import { getItemPathFromEventPath } from './eventPath';
+
+const log = debug('lobe-explorer-tree:inline-edit');
+
+type FileTreeModel = ReturnType<typeof useFileTree>['model'];
+
+// Leaf name of the placeholder row a new entry is typed into. The input is
+// cleared before the user sees it, and a lone zero-width space can't collide
+// with a name anyone would type.
+const PLACEHOLDER_NAME = '​';
+const RENAME_INPUT_ATTRIBUTE = 'data-item-rename-input';
+
+export interface PendingCreate {
+ kind: ExplorerTreeEntryKind;
+ parentId: string | null;
+ /** Canonical tree path of the placeholder row. */
+ path: string;
+}
+
+export interface NameInputHintState {
+ left: number;
+ message: string;
+ top: number;
+ width: number;
+}
+
+const isRenameInput = (target: EventTarget | undefined): target is HTMLInputElement =>
+ target instanceof HTMLInputElement && target.hasAttribute(RENAME_INPUT_ATTRIBUTE);
+
+/** Pushes a value into the tree's controlled rename input the way typing would. */
+const setRenameInputValue = (input: HTMLInputElement, value: string) => {
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+};
+
+/** Select the name without its extension, as VS Code and Finder do. */
+const selectStem = (input: HTMLInputElement, isFolder: boolean) => {
+ const dot = isFolder ? -1 : input.value.lastIndexOf('.');
+ input.setSelectionRange(0, dot > 0 ? dot : input.value.length);
+};
+
+interface UseInlineNameEditParams<TData> {
+ adapterRef: RefObject<NormalizedTree<TData>>;
+ model: FileTreeModel;
+ pendingCreateRef: RefObject<PendingCreate | null>;
+ propsRef: RefObject<ExplorerTreeProps<TData>>;
+ resync: () => void;
+}
+
+/**
+ * Inline new-entry and rename input on top of @pierre/trees' rename row:
+ * - `startCreating` inserts a placeholder row and opens the input on it;
+ * - every commit (Enter or blur) runs `validateName` first and, when it fails,
+ * keeps the input open with a hint under it instead of committing;
+ * - a new entry is committed here (the tree's own rename refuses `a/b` names)
+ * and handed to `onCommitCreate`.
+ *
+ * The rename input lives in the tree's shadow DOM, so everything hooks native
+ * capture listeners, which run before the tree's own handlers.
+ */
+export const useInlineNameEdit = <TData>({
+ adapterRef,
+ model,
+ pendingCreateRef,
+ propsRef,
+ resync,
+}: UseInlineNameEditParams<TData>) => {
+ const [hint, setHint] = useState<NameInputHintState | null>(null);
+
+ const findRenameInput = useCallback((): HTMLInputElement | null => {
+ const input = model
+ .getFileTreeContainer()
+ ?.shadowRoot?.querySelector(`[${RENAME_INPUT_ATTRIBUTE}]`);
+ return input instanceof HTMLInputElement ? input : null;
+ }, [model]);
+
+ // The input mounts on the tree's next render, which can be a frame or two away.
+ const whenRenameInputMounts = useCallback(
+ (run: (input: HTMLInputElement) => void, attempts = 5) => {
+ requestAnimationFrame(() => {
+ const input = findRenameInput();
+ if (input) run(input);
+ else if (attempts > 1) whenRenameInputMounts(run, attempts - 1);
+ });
+ },
+ [findRenameInput],
+ );
+
+ const showHint = useCallback((message: string | null | undefined, input: HTMLInputElement) => {
+ if (!message) {
+ setHint(null);
+ return;
+ }
+ const rect = input.getBoundingClientRect();
+ setHint({ left: rect.left, message, top: rect.bottom, width: rect.width });
+ }, []);
+
+ const describeInput = useCallback(
+ (
+ input: HTMLInputElement,
+ eventPath: EventTarget[],
+ ): { check: ExplorerTreeNameCheck<TData>; pending?: PendingCreate } | null => {
+ const itemPath = getItemPathFromEventPath(eventPath);
+ if (!itemPath) return null;
+ const a = adapterRef.current;
+ const pending = pendingCreateRef.current;
+ if (pending && pending.path === itemPath) {
+ const parentNode = pending.parentId ? (a.nodeById.get(pending.parentId) ?? null) : null;
+ return {
+ check: { kind: pending.kind, mode: 'create', name: input.value, parentNode },
+ pending,
+ };
+ }
+ const id = a.idByPath.get(itemPath);
+ const node: ExplorerTreeNode<TData> | undefined = id ? a.nodeById.get(id) : undefined;
+ if (!node) return null;
+ return { check: { mode: 'rename', name: input.value, node } };
+ },
+ [adapterRef, pendingCreateRef],
+ );
+
+ useEffect(() => {
+ // The host element is attached after this effect first runs, so listen on
+ // the document (capture phase: still ahead of the tree's own handlers) and
+ // keep only events that come from this tree's rename input.
+ const fromThisTree = (event: Event) => {
+ const host = model.getFileTreeContainer();
+ return !!host && event.composedPath().includes(host);
+ };
+
+ const validate = (check: ExplorerTreeNameCheck<TData>) =>
+ propsRef.current.validateName?.(check) ?? null;
+
+ const handleInput = (event: Event) => {
+ if (!fromThisTree(event)) return;
+ const eventPath = event.composedPath();
+ const [target] = eventPath;
+ if (!isRenameInput(target)) return;
+ const described = describeInput(target, eventPath);
+ if (!described) return;
+ // An empty new-entry name only cancels, so it is not worth flagging.
+ if (described.pending && target.value === '') {
+ setHint(null);
+ return;
+ }
+ showHint(validate(described.check), target);
+ };
+
+ const commitCreate = (pending: PendingCreate, name: string, check: ExplorerTreeNameCheck) => {
+ const parentNode = check.mode === 'create' ? check.parentNode : null;
+ const parentPath = pending.parentId
+ ? (adapterRef.current.pathById.get(pending.parentId) ?? '')
+ : '';
+ const optimisticPath = `${parentPath}${name}${pending.kind === 'folder' ? '/' : ''}`;
+ // Runs after the tree has dropped the placeholder on its own commit.
+ setTimeout(() => {
+ try {
+ model.add(optimisticPath);
+ } catch (error) {
+ log('optimistic add of %s failed: %O', optimisticPath, error);
+ }
+ void Promise.resolve(
+ propsRef.current.onCommitCreate?.({
+ kind: pending.kind,
+ name,
+ parentNode: parentNode as ExplorerTreeNode<TData> | null,
+ }),
+ ).then(
+ (result) => {
+ if (result === false) resync();
+ },
+ () => resync(),
+ );
+ }, 0);
+ };
+
+ const handleCommitAttempt = (event: Event) => {
+ if (!fromThisTree(event)) return;
+ const eventPath = event.composedPath();
+ const [target] = eventPath;
+ if (!isRenameInput(target)) return;
+ const described = describeInput(target, eventPath);
+ if (!described) return;
+ const { check, pending } = described;
+
+ // Blank new-entry name: let the tree drop the placeholder.
+ if (pending && target.value.trim() === '') {
+ pendingCreateRef.current = null;
+ setHint(null);
+ return;
+ }
+
+ const error = validate(check);
+ if (error) {
+ event.preventDefault();
+ event.stopPropagation();
+ showHint(error, target);
+ return;
+ }
+ setHint(null);
+ if (!pending) return;
+
+ // Take the commit over from the tree: clearing the input makes its own
+ // commit remove the placeholder, and the entry is created from here.
+ pendingCreateRef.current = null;
+ const name = target.value;
+ setRenameInputValue(target, '');
+ commitCreate(pending, name, check);
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (!fromThisTree(event)) return;
+ const eventPath = event.composedPath();
+ const [target] = eventPath;
+ if (!isRenameInput(target)) {
+ // The tree opens the rename input on F2 by itself; trim the selection
+ // down to the stem once it is there.
+ if (event.key === 'F2') {
+ whenRenameInputMounts((input) => {
+ selectStem(input, getItemPathFromEventPath(eventPath)?.endsWith('/') ?? false);
+ });
+ }
+ return;
+ }
+ if (event.key === 'Escape') {
+ if (pendingCreateRef.current) pendingCreateRef.current = null;
+ setHint(null);
+ return;
+ }
+ if (event.key !== 'Enter' || event.isComposing) return;
+ handleCommitAttempt(event);
+ };
+
+ document.addEventListener('keydown', handleKeyDown, true);
+ document.addEventListener('blur', handleCommitAttempt, true);
+ document.addEventListener('input', handleInput, true);
+ return () => {
+ document.removeEventListener('keydown', handleKeyDown, true);
+ document.removeEventListener('blur', handleCommitAttempt, true);
+ document.removeEventListener('input', handleInput, true);
+ };
+ }, [
+ adapterRef,
+ describeInput,
+ model,
+ pendingCreateRef,
+ propsRef,
+ resync,
+ showHint,
+ whenRenameInputMounts,
+ ]);
+
+ const startCreating = useCallback(
+ (parentId: string | null, kind: ExplorerTreeEntryKind) => {
+ const parentPath = parentId == null ? '' : adapterRef.current.pathById.get(parentId);
+ if (parentPath === undefined) return;
+
+ const stale = pendingCreateRef.current;
+ pendingCreateRef.current = null;
+ if (stale) {
+ try {
+ model.remove(stale.path, { recursive: true });
+ } catch {
+ // Already gone with a data refresh.
+ }
+ }
+
+ const path = `${parentPath}${PLACEHOLDER_NAME}${kind === 'folder' ? '/' : ''}`;
+ try {
+ model.add(path);
+ } catch (error) {
+ log('cannot insert placeholder %s: %O', path, error);
+ return;
+ }
+ pendingCreateRef.current = { kind, parentId, path };
+ if (!model.startRenaming(path, { removeIfCanceled: true })) {
+ pendingCreateRef.current = null;
+ model.remove(path, { recursive: true });
+ return;
+ }
+ whenRenameInputMounts((input) => setRenameInputValue(input, ''));
+ },
+ [adapterRef, model, pendingCreateRef, whenRenameInputMounts],
+ );
+
+ const selectRenameStem = useCallback(
+ (isFolder: boolean) => whenRenameInputMounts((input) => selectStem(input, isFolder)),
+ [whenRenameInputMounts],
+ );
+
+ return { hint, selectRenameStem, startCreating };
+};
diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.ts
index 1ff161636ee..ea22cf54091 100644
--- a/src/services/electron/localFileService.test.ts
+++ b/src/services/electron/localFileService.test.ts
@@ -1,8 +1,14 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { localFileService } from './localFileService';
+
const mockLocalSystem = vi.hoisted(() => ({
getExternalAssetForPublishUrl: vi.fn(),
getLocalFilePreviewUrl: vi.fn(),
+ handleCopyFiles: vi.fn(),
+ handleCreateDirectory: vi.fn(),
+ handleCreateFile: vi.fn(),
+ trashLocalFiles: vi.fn(),
}));
vi.mock('@/utils/electron/ipc', () => ({
@@ -18,8 +24,6 @@ describe('localFileService', () => {
});
it('fetches text local-file preview from the preview URL', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
url: 'localfile://preview/index.html',
@@ -53,8 +57,6 @@ describe('localFileService', () => {
});
it('returns the entry directory as the HTML workspace resource base URL', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
url: 'localfile://preview-session/pages/index.html',
@@ -91,8 +93,6 @@ describe('localFileService', () => {
});
it('throws when the preview URL cannot be created', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
error: 'outside safe path',
success: false,
@@ -107,8 +107,6 @@ describe('localFileService', () => {
});
it('forwards image-only preview constraints to Electron', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
url: 'localfile://preview/image.png',
@@ -137,8 +135,6 @@ describe('localFileService', () => {
});
it('rejects non-image responses before reading the body for image-only previews', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
url: 'localfile://preview/.env',
@@ -165,8 +161,6 @@ describe('localFileService', () => {
});
it('reads local file bytes from the preview URL', async () => {
- const { localFileService } = await import('./localFileService');
-
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
url: 'localfile://preview/font.woff2',
@@ -195,7 +189,6 @@ describe('localFileService', () => {
});
it('uses the dedicated publish IPC channel for external bytes', async () => {
- const { localFileService } = await import('./localFileService');
mockLocalSystem.getExternalAssetForPublishUrl.mockResolvedValue({
success: true,
url: 'localfile://publish/font.woff2',
@@ -225,4 +218,41 @@ describe('localFileService', () => {
});
expect(mockLocalSystem.getLocalFilePreviewUrl).not.toHaveBeenCalled();
});
+
+ describe('file tree mutations', () => {
+ it('routes create / mkdir / copy / trash to their localSystem IPC methods', async () => {
+ mockLocalSystem.handleCreateFile.mockResolvedValue({ path: '/p/a.ts', success: true });
+ mockLocalSystem.handleCreateDirectory.mockResolvedValue({ path: '/p/dir', success: true });
+ mockLocalSystem.handleCopyFiles.mockResolvedValue([
+ { sourcePath: '/p/a.ts', success: true, targetPath: '/p/a copy.ts' },
+ ]);
+ mockLocalSystem.trashLocalFiles.mockResolvedValue({
+ items: [{ path: '/p/a.ts', success: true }],
+ success: true,
+ });
+
+ await expect(localFileService.createLocalFile({ path: '/p/a.ts' })).resolves.toEqual({
+ path: '/p/a.ts',
+ success: true,
+ });
+ await expect(localFileService.createLocalDirectory({ path: '/p/dir' })).resolves.toEqual({
+ path: '/p/dir',
+ success: true,
+ });
+ await expect(
+ localFileService.copyLocalFiles({ items: [{ sourcePath: '/p/a.ts' }] }),
+ ).resolves.toEqual([{ sourcePath: '/p/a.ts', success: true, targetPath: '/p/a copy.ts' }]);
+ await expect(localFileService.trashLocalFiles({ paths: ['/p/a.ts'] })).resolves.toEqual({
+ items: [{ path: '/p/a.ts', success: true }],
+ success: true,
+ });
+
+ expect(mockLocalSystem.handleCreateFile).toHaveBeenCalledWith({ path: '/p/a.ts' });
+ expect(mockLocalSystem.handleCreateDirectory).toHaveBeenCalledWith({ path: '/p/dir' });
+ expect(mockLocalSystem.handleCopyFiles).toHaveBeenCalledWith({
+ items: [{ sourcePath: '/p/a.ts' }],
+ });
+ expect(mockLocalSystem.trashLocalFiles).toHaveBeenCalledWith({ paths: ['/p/a.ts'] });
+ });
+ });
});
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 7f1445e63d5..d1b900a1cec 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -2,6 +2,10 @@ import { MARKDOWN_MIME_TYPES } from '@lobechat/const';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
+ type CopyLocalFilesParams,
+ type CreateLocalDirectoryParams,
+ type CreateLocalEntryResult,
+ type CreateLocalFileParams,
type DeviceSandboxCapabilityResult,
type DeviceSandboxInstallResult,
type EditLocalFileParams,
@@ -21,6 +25,7 @@ import {
type ListLocalFilesResult,
type ListProjectSkillsParams,
type ListProjectSkillsResult,
+ type LocalCopyFilesResultItem,
type LocalFileItem,
type LocalFilePreviewUrlParams,
type LocalFileStats,
@@ -48,6 +53,8 @@ import {
type RunCommandResult,
type ShowSaveDialogParams,
type ShowSaveDialogResult,
+ type TrashLocalFilesParams,
+ type TrashLocalFilesResult,
type WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
@@ -262,6 +269,26 @@ class LocalFileService {
return ensureElectronIpc().localSystem.handleWriteFile(params);
}
+ /** Create a new file; fails instead of overwriting an existing one. */
+ async createLocalFile(params: CreateLocalFileParams): Promise<CreateLocalEntryResult> {
+ return ensureElectronIpc().localSystem.handleCreateFile(params);
+ }
+
+ /** Create a new folder; fails when the path is already taken. */
+ async createLocalDirectory(params: CreateLocalDirectoryParams): Promise<CreateLocalEntryResult> {
+ return ensureElectronIpc().localSystem.handleCreateDirectory(params);
+ }
+
+ /** Copy files/folders, or duplicate in place when an item has no `targetPath`. */
+ async copyLocalFiles(params: CopyLocalFilesParams): Promise<LocalCopyFilesResultItem[]> {
+ return ensureElectronIpc().localSystem.handleCopyFiles(params);
+ }
+
+ /** Move files/folders to the OS trash (recoverable), reporting each path. */
+ async trashLocalFiles(params: TrashLocalFilesParams): Promise<TrashLocalFilesResult> {
+ return ensureElectronIpc().localSystem.trashLocalFiles(params);
+ }
+
async auditSafePaths(params: AuditSafePathsParams): Promise<AuditSafePathsResult> {
return ensureElectronIpc().localSystem.auditSafePaths(params);
}
diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.ts
index 55d50015158..71f498b3802 100644
--- a/src/services/projectFile.test.ts
+++ b/src/services/projectFile.test.ts
@@ -1,7 +1,17 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { localFileKeys } from '@/libs/swr/keys';
+
+import { projectFileService, refreshProjectFiles } from './projectFile';
+
const mockDeviceClient = vi.hoisted(() => ({
copyAssetForPublish: { mutate: vi.fn() },
+ copyProjectFiles: { mutate: vi.fn() },
+ createProjectDirectory: { mutate: vi.fn() },
+ createProjectFile: { mutate: vi.fn() },
+ moveProjectFiles: { mutate: vi.fn() },
+ renameProjectFile: { mutate: vi.fn() },
+ trashProjectFiles: { mutate: vi.fn() },
getLocalFilePreview: { query: vi.fn() },
getProjectFileIndex: { query: vi.fn() },
readExternalAssetForPublish: { query: vi.fn() },
@@ -10,12 +20,24 @@ const mockDeviceClient = vi.hoisted(() => ({
const mockLocalFileService = vi.hoisted(() => ({
copyAssetForPublish: vi.fn(),
+ copyLocalFiles: vi.fn(),
+ createLocalDirectory: vi.fn(),
+ createLocalFile: vi.fn(),
+ moveLocalFiles: vi.fn(),
+ renameLocalFile: vi.fn(),
+ trashLocalFiles: vi.fn(),
getLocalFilePreview: vi.fn(),
getProjectFileIndex: vi.fn(),
readExternalAssetForPublish: vi.fn(),
searchProjectFiles: vi.fn(),
}));
+const mockMutate = vi.hoisted(() => vi.fn());
+
+vi.mock('@/libs/swr', () => ({
+ mutate: mockMutate,
+}));
+
vi.mock('@lobechat/const', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
isDesktop: true,
@@ -38,8 +60,6 @@ describe('projectFileService', () => {
});
it('gets remote local-file preview through device RPC', async () => {
- const { projectFileService } = await import('./projectFile');
-
mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
preview: {
content: '<h1>Remote</h1>',
@@ -70,8 +90,6 @@ describe('projectFileService', () => {
});
it('forwards image-only preview constraints to remote device RPC', async () => {
- const { projectFileService } = await import('./projectFile');
-
mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
preview: {
base64: 'aW1hZ2U=',
@@ -98,8 +116,6 @@ describe('projectFileService', () => {
});
it('rejects non-image remote payloads for image-only previews', async () => {
- const { projectFileService } = await import('./projectFile');
-
mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
preview: {
content: 'SECRET=value',
@@ -120,8 +136,6 @@ describe('projectFileService', () => {
});
it('delegates desktop local-file preview to localFileService', async () => {
- const { projectFileService } = await import('./projectFile');
-
mockLocalFileService.getLocalFilePreview.mockResolvedValue({
content: '<h1>Local</h1>',
contentType: 'text/html',
@@ -146,7 +160,6 @@ describe('projectFileService', () => {
});
it('reads an external publish asset through the dedicated remote RPC', async () => {
- const { projectFileService } = await import('./projectFile');
mockDeviceClient.readExternalAssetForPublish.query.mockResolvedValue({
base64: 'AQID',
contentType: 'image/png',
@@ -170,7 +183,6 @@ describe('projectFileService', () => {
});
it('reads an external publish asset through the dedicated desktop service', async () => {
- const { projectFileService } = await import('./projectFile');
const result = { bytes: new Uint8Array([4]), contentType: 'font/woff2' };
mockLocalFileService.readExternalAssetForPublish.mockResolvedValue(result);
@@ -189,7 +201,6 @@ describe('projectFileService', () => {
});
it('copies a publish asset through the remote RPC or the desktop service', async () => {
- const { projectFileService } = await import('./projectFile');
const params = {
from: '/outside/logo.png',
to: '/repo/.lobe-artifacts/site/logo.png',
@@ -213,7 +224,6 @@ describe('projectFileService', () => {
});
it('searches remote project files through device RPC', async () => {
- const { projectFileService } = await import('./projectFile');
mockDeviceClient.searchProjectFiles.query.mockResolvedValue({
entries: [],
root: '/repo',
@@ -240,7 +250,6 @@ describe('projectFileService', () => {
});
it('searches local project files through localFileService', async () => {
- const { projectFileService } = await import('./projectFile');
mockLocalFileService.searchProjectFiles.mockResolvedValue({
entries: [],
root: '/repo',
@@ -263,4 +272,127 @@ describe('projectFileService', () => {
});
expect(mockDeviceClient.searchProjectFiles.query).not.toHaveBeenCalled();
});
+
+ describe('file tree mutations', () => {
+ const REMOTE = { deviceId: 'device-1', workingDirectory: '/repo' };
+ const LOCAL = { workingDirectory: '/repo' };
+
+ it('creates a file through the device RPC or local IPC', async () => {
+ mockDeviceClient.createProjectFile.mutate.mockResolvedValue({
+ path: '/repo/a.ts',
+ success: true,
+ });
+ mockLocalFileService.createLocalFile.mockResolvedValue({ path: '/repo/a.ts', success: true });
+
+ await projectFileService.createProjectFile({ ...REMOTE, path: '/repo/a.ts' });
+ await projectFileService.createProjectFile({ ...LOCAL, content: 'x', path: '/repo/a.ts' });
+
+ expect(mockDeviceClient.createProjectFile.mutate).toHaveBeenCalledWith({
+ content: undefined,
+ deviceId: 'device-1',
+ path: '/repo/a.ts',
+ workingDirectory: '/repo',
+ });
+ expect(mockLocalFileService.createLocalFile).toHaveBeenCalledWith({
+ content: 'x',
+ path: '/repo/a.ts',
+ });
+ });
+
+ it('creates a folder through the device RPC or local IPC', async () => {
+ await projectFileService.createProjectDirectory({ ...REMOTE, path: '/repo/dir' });
+ await projectFileService.createProjectDirectory({ ...LOCAL, path: '/repo/dir' });
+
+ expect(mockDeviceClient.createProjectDirectory.mutate).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ path: '/repo/dir',
+ workingDirectory: '/repo',
+ });
+ expect(mockLocalFileService.createLocalDirectory).toHaveBeenCalledWith({ path: '/repo/dir' });
+ });
+
+ it('copies through the device RPC or local IPC', async () => {
+ const items = [{ sourcePath: '/repo/a.ts' }];
+
+ await projectFileService.copyProjectFiles({ ...REMOTE, items });
+ await projectFileService.copyProjectFiles({ ...LOCAL, items });
+
+ expect(mockDeviceClient.copyProjectFiles.mutate).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ items,
+ workingDirectory: '/repo',
+ });
+ expect(mockLocalFileService.copyLocalFiles).toHaveBeenCalledWith({ items });
+ });
+
+ it('trashes through the device RPC or local IPC', async () => {
+ await projectFileService.trashProjectFiles({ ...REMOTE, paths: ['/repo/a.ts'] });
+ await projectFileService.trashProjectFiles({ ...LOCAL, paths: ['/repo/a.ts'] });
+
+ expect(mockDeviceClient.trashProjectFiles.mutate).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ paths: ['/repo/a.ts'],
+ workingDirectory: '/repo',
+ });
+ expect(mockLocalFileService.trashLocalFiles).toHaveBeenCalledWith({ paths: ['/repo/a.ts'] });
+ });
+
+ it('surfaces a remote device without a trash as a rejection', async () => {
+ mockDeviceClient.trashProjectFiles.mutate.mockRejectedValue(
+ new Error('This device does not support moving files to the trash'),
+ );
+
+ await expect(
+ projectFileService.trashProjectFiles({ ...REMOTE, paths: ['/repo/a.ts'] }),
+ ).rejects.toThrow('This device does not support moving files to the trash');
+ });
+
+ it.each([
+ ['local', LOCAL],
+ ['remote', REMOTE],
+ ])('refuses to trash, rename, move or duplicate the workspace root (%s)', async (_, target) => {
+ await expect(
+ projectFileService.trashProjectFiles({ ...target, paths: ['/repo/a.ts', '/repo/'] }),
+ ).rejects.toThrow(/workspace root/);
+ await expect(
+ projectFileService.renameProjectFile({ ...target, newName: 'x', path: '/repo' }),
+ ).rejects.toThrow(/workspace root/);
+ await expect(
+ projectFileService.moveProjectFiles({
+ ...target,
+ items: [{ newPath: '/repo/sub/repo', oldPath: '/repo' }],
+ }),
+ ).rejects.toThrow(/workspace root/);
+ await expect(
+ projectFileService.copyProjectFiles({ ...target, items: [{ sourcePath: '/repo' }] }),
+ ).rejects.toThrow(/workspace root/);
+
+ expect(mockLocalFileService.trashLocalFiles).not.toHaveBeenCalled();
+ expect(mockLocalFileService.renameLocalFile).not.toHaveBeenCalled();
+ expect(mockLocalFileService.moveLocalFiles).not.toHaveBeenCalled();
+ expect(mockLocalFileService.copyLocalFiles).not.toHaveBeenCalled();
+ expect(mockDeviceClient.trashProjectFiles.mutate).not.toHaveBeenCalled();
+ expect(mockDeviceClient.renameProjectFile.mutate).not.toHaveBeenCalled();
+ expect(mockDeviceClient.moveProjectFiles.mutate).not.toHaveBeenCalled();
+ expect(mockDeviceClient.copyProjectFiles.mutate).not.toHaveBeenCalled();
+ });
+
+ it('refreshProjectFiles revalidates the file index and the git overlay', async () => {
+ await refreshProjectFiles('device-1', '/repo');
+ await refreshProjectFiles(undefined, '/repo');
+
+ expect(mockMutate.mock.calls.map(([key]) => key)).toEqual([
+ localFileKeys.projectIndex('device-1', '/repo'),
+ localFileKeys.gitWorkingTreeFiles('device-1', '/repo'),
+ localFileKeys.projectIndex(undefined, '/repo'),
+ localFileKeys.gitWorkingTreeFiles(undefined, '/repo'),
+ ]);
+ expect(mockMutate.mock.calls[0][0]).toEqual(['localFile:projectIndex', 'device-1', '/repo']);
+ expect(mockMutate.mock.calls[3][0]).toEqual([
+ 'localFile:gitWorkingTreeFiles',
+ 'local',
+ '/repo',
+ ]);
+ });
+ });
});
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index ed33d6c03a6..f07946ec2bc 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -1,5 +1,8 @@
import { isDesktop } from '@lobechat/const';
import type {
+ CopyLocalFileItem,
+ CreateLocalEntryResult,
+ LocalCopyFilesResultItem,
LocalFilePreviewUrlParams,
LocalMoveFilesResultItem,
MoveLocalFileParams,
@@ -7,9 +10,13 @@ import type {
ProjectFileIndexResult,
ProjectFileSearchResult,
RenameLocalFileResult,
+ TrashLocalFilesResult,
} from '@lobechat/electron-client-ipc';
import type { DeviceLocalFilePreview } from '@lobechat/types';
+import { isAbsolute, relative, resolve } from 'pathe';
+import { mutate } from '@/libs/swr';
+import { localFileKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
import { type LocalFilePreview, localFileService } from '@/services/electron/localFileService';
@@ -52,6 +59,37 @@ const deserializeLocalFilePreview = (preview: DeviceLocalFilePreview): LocalFile
}
};
+/**
+ * Refuse to trash / rename / move / duplicate the workspace root itself: it
+ * would pull the whole tree out from under the UI (and a duplicate would land
+ * outside the workspace). Checked here for both transports so the local IPC
+ * path gets the same guard the device gateway enforces server-side.
+ */
+const assertNotWorkspaceRoot = (workingDirectory: string, paths: string[]): void => {
+ if (!workingDirectory) return;
+ for (const target of paths) {
+ if (isAbsolute(target) && relative(resolve(workingDirectory), resolve(target)) === '') {
+ throw new Error(`This operation is not allowed on the workspace root: ${target}`);
+ }
+ }
+};
+
+/**
+ * Revalidate everything the Files tree reads for a working directory — the
+ * file index and the git dirty-file overlay — after a file operation changed
+ * it. There is no file watcher, so without this a mutation only shows up on
+ * the next window focus.
+ */
+export const refreshProjectFiles = async (
+ deviceId: string | undefined,
+ dirPath: string,
+): Promise<void> => {
+ await Promise.all([
+ mutate(localFileKeys.projectIndex(deviceId, dirPath)),
+ mutate(localFileKeys.gitWorkingTreeFiles(deviceId, dirPath)),
+ ]);
+};
+
/**
* Project file chokepoint. Picks the transport per call from `deviceId`: a
* remote / web target goes through the device RPCs; the local desktop talks to
@@ -219,6 +257,11 @@ class ProjectFileService {
items: MoveLocalFileParams[];
workingDirectory: string;
}): Promise<LocalMoveFilesResultItem[]> {
+ assertNotWorkspaceRoot(
+ workingDirectory,
+ items.map((item) => item.oldPath),
+ );
+
return deviceId
? lambdaClient.device.moveProjectFiles.mutate({ deviceId, items, workingDirectory })
: localFileService.moveLocalFiles({ items });
@@ -236,6 +279,8 @@ class ProjectFileService {
path: string;
workingDirectory: string;
}): Promise<RenameLocalFileResult> {
+ assertNotWorkspaceRoot(workingDirectory, [path]);
+
return deviceId
? lambdaClient.device.renameProjectFile.mutate({ deviceId, newName, path, workingDirectory })
: localFileService.renameLocalFile({ newName, path });
@@ -262,6 +307,86 @@ class ProjectFileService {
? lambdaClient.device.writeProjectFile.mutate({ content, deviceId, path, workingDirectory })
: localFileService.writeFile({ content, path });
}
+
+ /**
+ * Create a new file in a project working directory (empty unless `content`
+ * is given). Never overwrites: an existing entry resolves `{ success: false }`.
+ */
+ async createProjectFile({
+ content,
+ deviceId,
+ path,
+ workingDirectory,
+ }: {
+ content?: string;
+ deviceId?: string;
+ path: string;
+ workingDirectory: string;
+ }): Promise<CreateLocalEntryResult> {
+ return deviceId
+ ? lambdaClient.device.createProjectFile.mutate({ content, deviceId, path, workingDirectory })
+ : localFileService.createLocalFile({ content, path });
+ }
+
+ /** Create a new folder in a project working directory. Fails when the path is taken. */
+ async createProjectDirectory({
+ deviceId,
+ path,
+ workingDirectory,
+ }: {
+ deviceId?: string;
+ path: string;
+ workingDirectory: string;
+ }): Promise<CreateLocalEntryResult> {
+ return deviceId
+ ? lambdaClient.device.createProjectDirectory.mutate({ deviceId, path, workingDirectory })
+ : localFileService.createLocalDirectory({ path });
+ }
+
+ /**
+ * Copy files/folders within a project working directory. An item without
+ * `targetPath` is duplicated next to its source (`name copy.ext`). Never
+ * overwrites; each item succeeds or fails independently.
+ */
+ async copyProjectFiles({
+ deviceId,
+ items,
+ workingDirectory,
+ }: {
+ deviceId?: string;
+ items: CopyLocalFileItem[];
+ workingDirectory: string;
+ }): Promise<LocalCopyFilesResultItem[]> {
+ assertNotWorkspaceRoot(
+ workingDirectory,
+ items.map((item) => item.sourcePath),
+ );
+
+ return deviceId
+ ? lambdaClient.device.copyProjectFiles.mutate({ deviceId, items, workingDirectory })
+ : localFileService.copyLocalFiles({ items });
+ }
+
+ /**
+ * Move files/folders in a project working directory to the trash. Reports
+ * each path. A remote device without a trash (the CLI daemon) rejects the
+ * whole call rather than deleting permanently.
+ */
+ async trashProjectFiles({
+ deviceId,
+ paths,
+ workingDirectory,
+ }: {
+ deviceId?: string;
+ paths: string[];
+ workingDirectory: string;
+ }): Promise<TrashLocalFilesResult> {
+ assertNotWorkspaceRoot(workingDirectory, paths);
+
+ return deviceId
+ ? lambdaClient.device.trashProjectFiles.mutate({ deviceId, paths, workingDirectory })
+ : localFileService.trashLocalFiles({ paths });
+ }
}
export const projectFileService = new ProjectFileService();
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index 06a910d1291..2b007766171 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -942,6 +942,110 @@ describe('chatDockSlice', () => {
});
});
+ describe('retargetLocalFiles', () => {
+ it('moves a renamed file tab, its buffer and active state to the new path', () => {
+ const { result } = renderHook(() => useChatStore());
+ const oldId = localFileTabId({ filePath: '/rt/notes.md', workingDirectory: '/rt' });
+ const newId = localFileTabId({ filePath: '/rt/meeting-notes.md', workingDirectory: '/rt' });
+
+ act(() => {
+ result.current.openLocalFile({ filePath: '/rt/notes.md', workingDirectory: '/rt' });
+ result.current.setLocalFileBuffer(oldId, 'draft');
+ });
+ act(() => {
+ result.current.retargetLocalFiles([{ from: '/rt/notes.md', to: '/rt/meeting-notes.md' }]);
+ });
+
+ const tab = result.current.openLocalFiles.find((file) => file.id === newId);
+ expect(tab?.filePath).toBe('/rt/meeting-notes.md');
+ expect(result.current.openLocalFiles.some((file) => file.id === oldId)).toBe(false);
+ expect(result.current.activeLocalFileId).toBe(newId);
+ expect(result.current.activeLocalFilePath).toBe('/rt/meeting-notes.md');
+ expect(result.current.activeLocalFileIdsByScope[createLocalFileScopeKey('/rt')]).toBe(newId);
+ expect(result.current.dirtyLocalFileContents[newId]).toBe('draft');
+ expect(oldId in result.current.dirtyLocalFileContents).toBe(false);
+ });
+
+ it('carries tabs under a moved folder and leaves other devices alone', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openLocalFile({ filePath: '/mv/src/a.ts', workingDirectory: '/mv' });
+ result.current.openLocalFile({
+ deviceId: 'remote',
+ filePath: '/mv/src/a.ts',
+ workingDirectory: '/mv',
+ });
+ });
+ act(() => {
+ result.current.retargetLocalFiles([{ from: '/mv/src', to: '/mv/lib/src' }]);
+ });
+
+ const paths = result.current.openLocalFiles
+ .filter((file) => file.workingDirectory === '/mv')
+ .map((file) => `${file.deviceId ?? 'local'}:${file.filePath}`);
+ expect(paths).toEqual(['local:/mv/lib/src/a.ts', 'remote:/mv/src/a.ts']);
+ });
+ it('carries tabs under a moved folder with Windows path separators', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: 'C:\\win\\src\\a.ts',
+ workingDirectory: 'C:\\win',
+ });
+ });
+ act(() => {
+ result.current.retargetLocalFiles([{ from: 'C:\\win\\src', to: 'C:\\win\\lib' }]);
+ });
+
+ expect(
+ result.current.openLocalFiles
+ .filter((file) => file.workingDirectory === 'C:\\win')
+ .map((file) => file.filePath),
+ ).toEqual(['C:\\win\\lib\\a.ts']);
+ });
+ });
+
+ describe('closeLocalFilesAt', () => {
+ it('closes tabs of deleted files and of files inside a deleted folder', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openLocalFile({ filePath: '/del/a.md', workingDirectory: '/del' });
+ result.current.openLocalFile({ filePath: '/del/dir/b.md', workingDirectory: '/del' });
+ result.current.openLocalFile({ filePath: '/del/keep.md', workingDirectory: '/del' });
+ });
+ act(() => {
+ result.current.closeLocalFilesAt(['/del/a.md', '/del/dir']);
+ });
+
+ expect(
+ result.current.openLocalFiles
+ .filter((file) => file.workingDirectory === '/del')
+ .map((file) => file.filePath),
+ ).toEqual(['/del/keep.md']);
+ });
+
+ it('closes tabs inside a deleted folder with Windows path separators', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: 'D:\\del\\dir\\b.md',
+ workingDirectory: 'D:\\del',
+ });
+ });
+ act(() => {
+ result.current.closeLocalFilesAt(['D:\\del\\dir']);
+ });
+
+ expect(
+ result.current.openLocalFiles.filter((file) => file.workingDirectory === 'D:\\del'),
+ ).toEqual([]);
+ });
+ });
+
describe('saveLocalFile', () => {
const target = {
deviceId: 'device-1',
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index 92c9e5edc43..9ba324fbb15 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -27,6 +27,10 @@ const getCurrentViewType = (portalStack: PortalViewData[]): PortalViewType | nul
return top?.type ?? null;
};
+/** `filePath` is `dir` itself or lies beneath it, with either path separator (Windows uses a backslash). */
+const isSameOrInsidePath = (filePath: string, dir: string) =>
+ filePath === dir || filePath.startsWith(`${dir}/`) || filePath.startsWith(`${dir}\\`);
+
const findLocalFileIndexById = (
openLocalFiles: Array<OpenLocalFileParams & { id?: string }>,
id: string,
@@ -587,6 +591,63 @@ export class ChatPortalActionImpl {
);
};
+ /**
+ * Points open tabs at the paths their files were renamed or moved to, so a
+ * tab — and its unsaved buffer — follows the file instead of going stale.
+ * Moving a folder carries every tab beneath it.
+ */
+ retargetLocalFiles = (moves: { from: string; to: string }[], deviceId?: string): void => {
+ const { activeLocalFileId, activeLocalFileIdsByScope, dirtyLocalFileContents, openLocalFiles } =
+ this.#get();
+ const nextPathOf = (filePath: string) => {
+ for (const { from, to } of moves) {
+ if (isSameOrInsidePath(filePath, from)) return `${to}${filePath.slice(from.length)}`;
+ }
+ };
+
+ const idMap = new Map<string, string>();
+ const nextFiles = openLocalFiles.map((file) => {
+ if (file.sandboxTopicId || file.deviceId !== deviceId) return file;
+ const filePath = nextPathOf(file.filePath);
+ if (!filePath) return file;
+ const next = { ...file, filePath };
+ next.id = createLocalFileTabId(next);
+ idMap.set(getLocalFileTabId(file), next.id);
+ return next;
+ });
+ if (idMap.size === 0) return;
+
+ const remap = (id: string) => idMap.get(id) ?? id;
+ const nextActiveId = activeLocalFileId && remap(activeLocalFileId);
+ const nextActive = nextActiveId && nextFiles.find((file) => file.id === nextActiveId);
+ this.#set(
+ {
+ activeLocalFileId: nextActiveId,
+ activeLocalFileIdsByScope: Object.fromEntries(
+ Object.entries(activeLocalFileIdsByScope).map(([scope, id]) => [scope, remap(id)]),
+ ),
+ ...(nextActive ? { activeLocalFilePath: nextActive.filePath } : {}),
+ dirtyLocalFileContents: Object.fromEntries(
+ Object.entries(dirtyLocalFileContents).map(([id, content]) => [remap(id), content]),
+ ),
+ openLocalFiles: nextFiles,
+ },
+ false,
+ 'retargetLocalFiles',
+ );
+ };
+
+ /** Closes the tabs of files that were deleted, including everything under a deleted folder. */
+ closeLocalFilesAt = (paths: string[], deviceId?: string): void => {
+ const removed = this.#get().openLocalFiles.filter(
+ (file) =>
+ !file.sandboxTopicId &&
+ file.deviceId === deviceId &&
+ paths.some((path) => isSameOrInsidePath(file.filePath, path)),
+ );
+ for (const file of removed) this.#get().closeLocalFileTab(getLocalFileTabId(file));
+ };
+
saveLocalFile = async ({
deviceId,
filePath,