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): improve workspace file explorer (#18892)

Arvin Xubb389fde519f
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 8dd728e2d44..7e8cf8cca11 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2169,15 +2169,23 @@
"workingPanel.documents.saved": "All changes saved",
"workingPanel.documents.title": "Document",
"workingPanel.documents.unsaved": "Unsaved changes",
+ "workingPanel.files.collapseAll": "Collapse Folders in Explorer",
"workingPanel.files.copyAbsolutePath": "Copy Path",
"workingPanel.files.copyRelativePath": "Copy Relative Path",
"workingPanel.files.empty": "No files in this workspace",
+ "workingPanel.files.filters.changedOnly": "Show Git Changes Only",
+ "workingPanel.files.filters.hideIgnored": "Exclude Ignored Files",
+ "workingPanel.files.filters.title": "Filter Files",
"workingPanel.files.noSearchResults": "No matching files",
"workingPanel.files.open": "Open File",
+ "workingPanel.files.search": "Search Files",
"workingPanel.files.searchPlaceholder": "Filter files...",
"workingPanel.files.showInReview": "Show in Review",
"workingPanel.files.showInSystem": "Reveal in Folder",
"workingPanel.files.title": "Files",
+ "workingPanel.files.views.changes": "Git Changes",
+ "workingPanel.files.views.project": "Project",
+ "workingPanel.files.views.title": "File View",
"workingPanel.localFile.binary": "Binary file โ€” preview unavailable",
"workingPanel.localFile.close": "Close",
"workingPanel.localFile.closeLeft": "Close to the Left",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 50cbd5b8c35..8bfd09a5e2b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2169,15 +2169,23 @@
"workingPanel.documents.saved": "ๅทฒไฟๅญ˜ๅ…จ้ƒจๅ˜ๆ›ด",
"workingPanel.documents.title": "ๆ–‡ๆกฃ",
"workingPanel.documents.unsaved": "ๆœ‰ๆœชไฟๅญ˜็š„ๅ˜ๆ›ด",
+ "workingPanel.files.collapseAll": "ๆŠ˜ๅ ่ต„ๆบ็ฎก็†ๅ™จไธญ็š„ๆ–‡ไปถๅคน",
"workingPanel.files.copyAbsolutePath": "ๅคๅˆถ่ทฏๅพ„",
"workingPanel.files.copyRelativePath": "ๅคๅˆถ็›ธๅฏน่ทฏๅพ„",
"workingPanel.files.empty": "ๆญคๅทฅไฝœๅŒบไธญๆฒกๆœ‰ๆ–‡ไปถ",
+ "workingPanel.files.filters.changedOnly": "ไป…ๆ˜พ็คบ Git ๅ˜ๆ›ด",
+ "workingPanel.files.filters.hideIgnored": "ไธๅŒ…ๅซๅทฒๅฟฝ็•ฅๆ–‡ไปถ",
+ "workingPanel.files.filters.title": "็ญ›้€‰ๆ–‡ไปถ",
"workingPanel.files.noSearchResults": "ๆฒกๆœ‰ๅŒน้…็š„ๆ–‡ไปถ",
"workingPanel.files.open": "ๆ‰“ๅผ€ๆ–‡ไปถ",
+ "workingPanel.files.search": "ๆœ็ดขๆ–‡ไปถ",
"workingPanel.files.searchPlaceholder": "็ญ›้€‰ๆ–‡ไปถ...",
"workingPanel.files.showInReview": "ๅœจๅฎกๆŸฅไธญๆŸฅ็œ‹",
"workingPanel.files.showInSystem": "ๅœจๆ–‡ไปถๅคนไธญๆ˜พ็คบ",
"workingPanel.files.title": "ๆ–‡ไปถ",
+ "workingPanel.files.views.changes": "Git ๅ˜ๆ›ด",
+ "workingPanel.files.views.project": "้กน็›ฎ",
+ "workingPanel.files.views.title": "ๆ–‡ไปถ่ง†ๅ›พ",
"workingPanel.localFile.binary": "ไบŒ่ฟ›ๅˆถๆ–‡ไปถ โ€” ๆ— ๆณ•้ข„่งˆ",
"workingPanel.localFile.close": "ๅ…ณ้—ญ",
"workingPanel.localFile.closeLeft": "ๅ…ณ้—ญๅทฆไพง",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d086bb1d86b..1258d3c3c6d 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2536,13 +2536,21 @@ export default {
'workingPanel.skills.title': 'Skills',
'workingPanel.files.copyAbsolutePath': 'Copy Path',
'workingPanel.files.copyRelativePath': 'Copy Relative Path',
+ 'workingPanel.files.collapseAll': 'Collapse Folders in Explorer',
'workingPanel.files.empty': 'No files in this workspace',
+ 'workingPanel.files.filters.changedOnly': 'Show Git Changes Only',
+ 'workingPanel.files.filters.hideIgnored': 'Exclude Ignored Files',
+ 'workingPanel.files.filters.title': 'Filter Files',
'workingPanel.files.noSearchResults': 'No matching files',
'workingPanel.files.open': 'Open File',
+ 'workingPanel.files.search': 'Search Files',
'workingPanel.files.searchPlaceholder': 'Filter files...',
'workingPanel.files.showInReview': 'Show in Review',
'workingPanel.files.showInSystem': 'Reveal in Folder',
'workingPanel.files.title': 'Files',
+ 'workingPanel.files.views.changes': 'Git Changes',
+ 'workingPanel.files.views.project': 'Project',
+ 'workingPanel.files.views.title': 'File View',
'workingPanel.review.baseRef.default': 'default',
'workingPanel.review.baseRef.loading': 'Loading branchesโ€ฆ',
'workingPanel.review.baseRef.reset': 'Reset to default branch',
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index 6c69fe2c3da..dd1bdbb598f 100644
--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { Ref } from 'react';
+import type { ReactNode as ReactNodeType, Ref } from 'react';
import { useImperativeHandle } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -29,6 +29,83 @@ const gitFilesMock = vi.hoisted(() => ({
}));
const openLocalFileMock = vi.hoisted(() => vi.fn());
const searchProjectFilesMock = vi.hoisted(() => vi.fn());
+const projectFilesMock = vi.hoisted(() => ({
+ data: {
+ entries: [
+ { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
+ { isDirectory: true, name: 'foo', path: '/repo/src/foo', relativePath: 'src/foo/' },
+ {
+ isDirectory: false,
+ name: 'bar.ts',
+ path: '/repo/src/foo/bar.ts',
+ relativePath: 'src/foo/bar.ts',
+ },
+ { isDirectory: false, name: 'root.ts', path: '/repo/root.ts', relativePath: 'root.ts' },
+ {
+ isDirectory: false,
+ name: '__project_root__',
+ path: '/repo/__project_root__',
+ relativePath: '__project_root__',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.env.local',
+ path: '/repo/.env.local',
+ relativePath: '.env.local',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.DS_Store',
+ path: '/repo/.DS_Store',
+ relativePath: '.DS_Store',
+ },
+ { isDirectory: false, name: 'draft.md~', path: '/repo/draft.md~', relativePath: 'draft.md~' },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: '.git',
+ path: '/repo/.git',
+ relativePath: '.git/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: 'config',
+ path: '/repo/.git/config',
+ relativePath: '.git/config',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'node_modules',
+ path: '/repo/node_modules',
+ relativePath: 'node_modules/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: '.next',
+ path: '/repo/.next',
+ relativePath: '.next/',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'dist',
+ path: '/repo/dist',
+ relativePath: 'dist/',
+ },
+ { isDirectory: true, name: 'build', path: '/repo/build', relativePath: 'build/' },
+ { isDirectory: true, name: '.github', path: '/repo/.github', relativePath: '.github/' },
+ { isDirectory: true, name: '.vscode', path: '/repo/.vscode', relativePath: '.vscode/' },
+ ],
+ indexedAt: '2026-01-01',
+ root: '/repo',
+ source: 'git' as 'git' | 'glob',
+ },
+}));
// โ”€โ”€โ”€ mocks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -67,100 +144,10 @@ vi.mock('../useGitWorkingTreeFiles', () => ({
}));
vi.mock('../useProjectFiles', () => ({
- useProjectFiles: () => ({
+ useProjectFiles: (_deviceId: string | undefined, workingDirectory: string) => ({
data: {
- entries: [
- { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
- { isDirectory: true, name: 'foo', path: '/repo/src/foo', relativePath: 'src/foo/' },
- {
- isDirectory: false,
- name: 'bar.ts',
- path: '/repo/src/foo/bar.ts',
- relativePath: 'src/foo/bar.ts',
- },
- {
- isDirectory: false,
- name: 'root.ts',
- path: '/repo/root.ts',
- relativePath: 'root.ts',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: '.env.local',
- path: '/repo/.env.local',
- relativePath: '.env.local',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: '.DS_Store',
- path: '/repo/.DS_Store',
- relativePath: '.DS_Store',
- },
- {
- isDirectory: false,
- name: 'draft.md~',
- path: '/repo/draft.md~',
- relativePath: 'draft.md~',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: '.git',
- path: '/repo/.git',
- relativePath: '.git/',
- },
- {
- gitIgnored: true,
- isDirectory: false,
- name: 'config',
- path: '/repo/.git/config',
- relativePath: '.git/config',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: 'node_modules',
- path: '/repo/node_modules',
- relativePath: 'node_modules/',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: '.next',
- path: '/repo/.next',
- relativePath: '.next/',
- },
- {
- gitIgnored: true,
- isDirectory: true,
- name: 'dist',
- path: '/repo/dist',
- relativePath: 'dist/',
- },
- {
- isDirectory: true,
- name: 'build',
- path: '/repo/build',
- relativePath: 'build/',
- },
- {
- isDirectory: true,
- name: '.github',
- path: '/repo/.github',
- relativePath: '.github/',
- },
- {
- isDirectory: true,
- name: '.vscode',
- path: '/repo/.vscode',
- relativePath: '.vscode/',
- },
- ],
- indexedAt: '2026-01-01',
- root: '/repo',
- source: 'git',
+ ...projectFilesMock.data,
+ source: workingDirectory === '/non-git' ? 'glob' : projectFilesMock.data.source,
},
isLoading: false,
isValidating: false,
@@ -190,6 +177,49 @@ vi.mock('antd', async (importOriginal) => ({
message: messageSpy,
}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button title={title} type={'button'} onClick={onClick} />
+ ),
+ Button: ({ children, title }: { children?: ReactNodeType; title?: string }) => (
+ <button title={title} type={'button'}>
+ {children}
+ </button>
+ ),
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children?: ReactNodeType;
+ items: { key: string; label: ReactNodeType; onClick?: () => void }[];
+ }) => (
+ <div>
+ {children}
+ {items.map((item) => (
+ <button key={item.key} type={'button'} onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </div>
+ ),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Center: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
+ copyToClipboard: vi.fn(),
+ Empty: ({ description }: { description?: ReactNodeType }) => <div>{description}</div>,
+ Flexbox: ({ children }: { children?: ReactNodeType }) => <div>{children}</div>,
+ Icon: () => <span />,
+ stopPropagation: vi.fn(),
+}));
+
vi.mock('antd-style', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
@@ -214,9 +244,14 @@ const setReveal = (path: string, nonce: number) => {
});
};
+const expandSearch = () => {
+ fireEvent.click(screen.getByTitle('workingPanel.files.search'));
+};
+
// โ”€โ”€โ”€ tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
beforeEach(() => {
+ projectFilesMock.data.source = 'git';
explorerTreeProps.current = undefined;
handleSpies.focus.mockClear();
handleSpies.select.mockClear();
@@ -267,14 +302,80 @@ describe('Files โ€” reveal request integration', () => {
);
});
+ it('wraps every visible entry in a named project root folder', () => {
+ render(<Files workingDirectory="/repo" />);
+
+ const nodes = explorerTreeProps.current?.nodes as {
+ id: string;
+ name: string;
+ parentId: string | null;
+ }[];
+
+ expect(nodes[0]).toMatchObject({
+ id: '\0project-root',
+ name: 'repo',
+ parentId: null,
+ });
+ expect(nodes.find((node) => node.id === 'src/')).toMatchObject({
+ parentId: '\0project-root',
+ });
+ expect(nodes.find((node) => node.id === 'root.ts')).toMatchObject({
+ parentId: '\0project-root',
+ });
+ expect(nodes.find((node) => node.id === '__project_root__')).toMatchObject({
+ name: '__project_root__',
+ parentId: '\0project-root',
+ });
+ expect(new Set(nodes.map((node) => node.id)).size).toBe(nodes.length);
+ expect(explorerTreeProps.current?.defaultExpandedIds).toContain('\0project-root');
+ });
+
+ it('switches from the project view to a Git changes view', () => {
+ render(<Files workingDirectory="/repo" />);
+
+ fireEvent.click(screen.getByText('workingPanel.files.views.changes'));
+
+ expect((explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id)).toEqual([
+ '\0project-root',
+ 'src/',
+ 'src/foo/',
+ 'src/foo/bar.ts',
+ 'root.ts',
+ ]);
+ });
+
+ it('resets the Git changes view when the workspace changes or is not Git-backed', async () => {
+ const { rerender } = render(<Files workingDirectory="/repo" />);
+
+ fireEvent.click(screen.getByText('workingPanel.files.views.changes'));
+ expect(
+ (explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id),
+ ).not.toContain('.env.local');
+
+ rerender(<Files workingDirectory="/another-repo" />);
+ await waitFor(() => {
+ expect(
+ (explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id),
+ ).toContain('.env.local');
+ });
+
+ fireEvent.click(screen.getByText('workingPanel.files.views.changes'));
+ rerender(<Files workingDirectory="/non-git" />);
+ await waitFor(() => {
+ expect(
+ (explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id),
+ ).toContain('.env.local');
+ });
+ });
+
it('passes git working tree status and per-item context menu items into ExplorerTree', () => {
render(<Files workingDirectory="/repo" />);
expect(explorerTreeProps.current?.gitStatus).toEqual([
- { path: '.env.local', status: 'ignored' },
- { path: 'root.ts', status: 'added' },
- { path: 'src/foo/bar.ts', status: 'modified' },
- { path: 'deleted.ts', status: 'deleted' },
+ { path: 'repo/.env.local', status: 'ignored' },
+ { path: 'repo/root.ts', status: 'added' },
+ { path: 'repo/src/foo/bar.ts', status: 'modified' },
+ { path: 'repo/deleted.ts', status: 'deleted' },
]);
expect(explorerTreeProps.current?.unsafeCSS).toContain(
"[data-item-git-status='ignored'] > :where(",
@@ -391,6 +492,7 @@ describe('Files โ€” reveal request integration', () => {
});
render(<Files workingDirectory="/repo" />);
+ expandSearch();
fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {
target: { value: 'bar' },
});
@@ -403,7 +505,7 @@ describe('Files โ€” reveal request integration', () => {
scope: '/repo',
});
expect((explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id)).toEqual(
- ['src/', 'src/foo/', 'src/foo/bar.ts'],
+ ['\0project-root', 'src/', 'src/foo/', 'src/foo/bar.ts'],
);
});
});
@@ -432,13 +534,14 @@ describe('Files โ€” reveal request integration', () => {
});
render(<Files workingDirectory="/repo" />);
+ expandSearch();
fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {
target: { value: 'git' },
});
await waitFor(() => {
expect((explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id)).toEqual(
- ['.github/', '.github/ci.yml'],
+ ['\0project-root', '.github/', '.github/ci.yml'],
);
});
});
@@ -452,6 +555,7 @@ describe('Files โ€” reveal request integration', () => {
});
render(<Files workingDirectory="/repo" />);
+ expandSearch();
fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {
target: { value: 'missing' },
});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts
new file mode 100644
index 00000000000..29fa3c5bda2
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts
@@ -0,0 +1,68 @@
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+import { describe, expect, it } from 'vitest';
+
+import { filterProjectFileEntries } from './fileFilter';
+
+const entries: ProjectFileIndexEntry[] = [
+ { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
+ {
+ isDirectory: true,
+ name: 'components',
+ path: '/repo/src/components',
+ relativePath: 'src/components/',
+ },
+ {
+ isDirectory: false,
+ name: 'Button.tsx',
+ path: '/repo/src/components/Button.tsx',
+ relativePath: 'src/components/Button.tsx',
+ },
+ {
+ isDirectory: false,
+ name: 'index.ts',
+ path: '/repo/src/index.ts',
+ relativePath: 'src/index.ts',
+ },
+ {
+ gitIgnored: true,
+ isDirectory: true,
+ name: 'dist',
+ path: '/repo/dist',
+ relativePath: 'dist/',
+ },
+];
+
+describe('filterProjectFileEntries', () => {
+ it('preserves all entries when no display filter is active', () => {
+ expect(
+ filterProjectFileEntries(entries, new Set(), { changedOnly: false, hideIgnored: false }),
+ ).toEqual(entries);
+ });
+
+ it('keeps changed files and their ancestor directories only', () => {
+ const result = filterProjectFileEntries(entries, new Set(['src/components/Button.tsx']), {
+ changedOnly: true,
+ hideIgnored: false,
+ });
+
+ expect(result.map((entry) => entry.relativePath)).toEqual([
+ 'src/',
+ 'src/components/',
+ 'src/components/Button.tsx',
+ ]);
+ });
+
+ it('excludes ignored entries without dropping parents of visible files', () => {
+ const result = filterProjectFileEntries(entries, new Set(), {
+ changedOnly: false,
+ hideIgnored: true,
+ });
+
+ expect(result.map((entry) => entry.relativePath)).toEqual([
+ 'src/',
+ 'src/components/',
+ 'src/components/Button.tsx',
+ 'src/index.ts',
+ ]);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts
new file mode 100644
index 00000000000..87142049d59
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts
@@ -0,0 +1,34 @@
+import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
+
+export interface ProjectFileDisplayFilter {
+ changedOnly: boolean;
+ hideIgnored: boolean;
+}
+
+const isPathInsideDirectory = (filePath: string, directoryPath: string) =>
+ filePath.startsWith(directoryPath);
+
+export const filterProjectFileEntries = (
+ entries: ProjectFileIndexEntry[],
+ dirtyFilePaths: Set<string>,
+ filter: ProjectFileDisplayFilter,
+) => {
+ if (!filter.changedOnly && !filter.hideIgnored) return entries;
+
+ const matchingFiles = entries.filter((entry) => {
+ if (entry.isDirectory) return false;
+ if (filter.hideIgnored && entry.gitIgnored) return false;
+ return !filter.changedOnly || dirtyFilePaths.has(entry.relativePath);
+ });
+
+ const visibleFilePaths = new Set(matchingFiles.map((entry) => entry.relativePath));
+
+ return entries.filter((entry) => {
+ if (!entry.isDirectory) return visibleFilePaths.has(entry.relativePath);
+ if (filter.hideIgnored && entry.gitIgnored) return false;
+
+ return matchingFiles.some((file) =>
+ isPathInsideDirectory(file.relativePath, entry.relativePath),
+ );
+ });
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index c26ac85ff6c..8d05b2b820c 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -2,10 +2,20 @@
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
import { Center, copyToClipboard, Empty, Flexbox, Icon, stopPropagation } from '@lobehub/ui';
-import { ActionIcon, Input, toast } from '@lobehub/ui/base-ui';
+import { ActionIcon, Button, DropdownMenu, Input, toast } from '@lobehub/ui/base-ui';
import type { GitStatusEntry } from '@pierre/trees';
import { createStaticStyles } from 'antd-style';
-import { FileIcon, SearchIcon, XIcon } from 'lucide-react';
+import {
+ CheckIcon,
+ ChevronDownIcon,
+ FileIcon,
+ FolderTreeIcon,
+ FoldVerticalIcon,
+ GitCompareArrowsIcon,
+ ListFilterIcon,
+ SearchIcon,
+ XIcon,
+} from 'lucide-react';
import type { DragEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -27,6 +37,7 @@ import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
+import { filterProjectFileEntries } from './fileFilter';
import { isExcludedProjectFileEntry } from './fileVisibility';
import { buildGitStatusEntries, useGitWorkingTreeFiles } from './useGitWorkingTreeFiles';
import { useProjectFiles } from './useProjectFiles';
@@ -60,10 +71,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
min-height: 0;
`,
subheader: css`
+ display: flex;
flex-shrink: 0;
+ gap: 4px;
+ align-items: center;
+
padding-block: 6px 8px;
padding-inline: 12px;
`,
+ search: css`
+ flex: 1;
+ min-width: 0;
+ `,
}));
const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
@@ -84,6 +103,15 @@ const FILE_TREE_UNSAFE_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';
+
+const getProjectRootName = (root: string) => {
+ const normalizedRoot = root.replace(/[\\/]+$/, '');
+ return normalizedRoot.split(/[\\/]/).pop() || root;
+};
const getParentRelativePath = (relativePath: string): string | null => {
const cleaned = stripTrailingSlash(relativePath);
@@ -94,22 +122,31 @@ const getParentRelativePath = (relativePath: string): string | null => {
const buildTreeNodes = (
entries: ProjectFileIndexEntry[],
+ rootName: string,
): ExplorerTreeNode<ProjectFileIndexEntry>[] => {
// The index gives every file plus the chain of containing directories, each
// with a unique relativePath (directories end with "/"). Use that string as
// the stable node id and derive parentId from the path itself.
const ids = new Set(entries.map((entry) => entry.relativePath));
- return entries.map((entry) => {
- const parentRel = getParentRelativePath(entry.relativePath);
- const parentId = parentRel && ids.has(parentRel) ? parentRel : null;
- return {
- data: entry,
- id: entry.relativePath,
- isFolder: entry.isDirectory,
- name: entry.name,
- parentId,
- };
- });
+ return [
+ {
+ id: PROJECT_ROOT_NODE_ID,
+ isFolder: true,
+ name: rootName,
+ parentId: null,
+ },
+ ...entries.map((entry) => {
+ const parentRel = getParentRelativePath(entry.relativePath);
+ const parentId = parentRel && ids.has(parentRel) ? parentRel : PROJECT_ROOT_NODE_ID;
+ return {
+ data: entry,
+ id: entry.relativePath,
+ isFolder: entry.isDirectory,
+ name: entry.name,
+ parentId,
+ };
+ }),
+ ];
};
const buildIgnoredGitStatusEntries = (entries: ProjectFileIndexEntry[]): GitStatusEntry[] =>
@@ -117,6 +154,9 @@ const buildIgnoredGitStatusEntries = (entries: ProjectFileIndexEntry[]): GitStat
.filter((entry) => entry.gitIgnored)
.map((entry) => ({ path: entry.relativePath, status: 'ignored' }));
+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[] = [];
@@ -127,14 +167,20 @@ const getAncestorIds = (filePath: string): string[] => {
};
interface FilesSearchBarProps {
+ onClose: () => void;
onDebouncedChange: (query: string) => void;
}
// Keystrokes stay local to this component: only the debounced query reaches
// the tree host, so typing never re-renders the ExplorerTree subtree.
-const FilesSearchBar = memo<FilesSearchBarProps>(({ onDebouncedChange }) => {
+const FilesSearchBar = memo<FilesSearchBarProps>(({ onClose, onDebouncedChange }) => {
const { t } = useTranslation('chat');
const [searchQuery, setSearchQuery] = useState('');
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ inputRef.current?.focus();
+ }, []);
useEffect(() => {
const timer = setTimeout(() => onDebouncedChange(searchQuery), FILE_SEARCH_DEBOUNCE_MS);
@@ -145,16 +191,28 @@ const FilesSearchBar = memo<FilesSearchBarProps>(({ onDebouncedChange }) => {
<Input
placeholder={t('workingPanel.files.searchPlaceholder')}
prefix={<Icon icon={SearchIcon} size={13} />}
+ ref={inputRef}
size={'small'}
style={{ width: '100%' }}
value={searchQuery}
suffix={
- searchQuery ? (
- <ActionIcon icon={XIcon} size={12} onClick={() => setSearchQuery('')} />
- ) : undefined
+ <ActionIcon
+ icon={XIcon}
+ size={12}
+ onClick={() => {
+ if (searchQuery) setSearchQuery('');
+ else onClose();
+ }}
+ />
}
onChange={(e) => setSearchQuery(e.target.value)}
- onKeyDown={stopPropagation}
+ onKeyDown={(event) => {
+ stopPropagation(event);
+ if (event.key !== 'Escape') return;
+ setSearchQuery('');
+ onDebouncedChange('');
+ onClose();
+ }}
/>
);
});
@@ -170,39 +228,59 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
workingDirectory,
data?.source === 'git',
);
+ const projectSource = data?.source;
const projectRoot = data?.root ?? workingDirectory;
const entries = useMemo(() => data?.entries ?? [], [data]);
+ const [viewMode, setViewMode] = useState<FileViewMode>('project');
+ const [hideIgnored, setHideIgnored] = useState(false);
+ const [searchExpanded, setSearchExpanded] = useState(false);
const [debouncedQuery, setDebouncedQuery] = useState('');
const [searchEntries, setSearchEntries] = useState<ProjectFileIndexEntry[] | undefined>();
const [isSearching, setIsSearching] = useState(false);
+ const projectRootName = getProjectRootName(projectRoot);
const normalizedDebouncedQuery = debouncedQuery.trim();
const isFiltering = normalizedDebouncedQuery.length > 0;
- const displayEntries = useMemo(
- () =>
- (isFiltering ? (searchEntries ?? []) : entries).filter(
- (entry) => !isExcludedProjectFileEntry(entry),
- ),
- [entries, isFiltering, searchEntries],
- );
- const nodes = useMemo(() => buildTreeNodes(displayEntries), [displayEntries]);
+ const changedOnly = viewMode === 'changes';
+ const hasDisplayFilter = isFiltering || changedOnly || hideIgnored;
const workingTreeGitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);
- const gitStatus = useMemo(
- () => [...buildIgnoredGitStatusEntries(displayEntries), ...workingTreeGitStatus],
- [displayEntries, workingTreeGitStatus],
- );
const dirtyFilePaths = useMemo(
() => new Set(workingTreeGitStatus.map((entry) => entry.path)),
[workingTreeGitStatus],
);
+ const displayEntries = useMemo(() => {
+ const visibleEntries = (isFiltering ? (searchEntries ?? []) : entries).filter(
+ (entry) => !isExcludedProjectFileEntry(entry),
+ );
+
+ return filterProjectFileEntries(visibleEntries, dirtyFilePaths, {
+ changedOnly,
+ hideIgnored,
+ });
+ }, [changedOnly, dirtyFilePaths, entries, hideIgnored, isFiltering, searchEntries]);
+ const nodes = useMemo(
+ () => buildTreeNodes(displayEntries, projectRootName),
+ [displayEntries, projectRootName],
+ );
+ const gitStatus = useMemo(
+ () =>
+ prefixGitStatusPaths(
+ [...buildIgnoredGitStatusEntries(displayEntries), ...workingTreeGitStatus],
+ projectRootName,
+ ),
+ [displayEntries, projectRootName, workingTreeGitStatus],
+ );
// Pre-expand top-level directories so the user sees something useful on first
// paint without having to click through every folder.
const defaultExpandedIds = useMemo(
() =>
nodes
- .filter((node) => node.isFolder && (isFiltering || node.parentId == null))
+ .filter(
+ (node) =>
+ node.id === PROJECT_ROOT_NODE_ID || (node.isFolder && (isFiltering || changedOnly)),
+ )
.map((node) => node.id),
- [isFiltering, nodes],
+ [changedOnly, isFiltering, nodes],
);
const treeStyleVars = useMemo(
() => getExplorerTreeStyleVars({ reserveChevronSlot: nodes.some((node) => node.isFolder) }),
@@ -211,6 +289,14 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const [expandedIds, setExpandedIds] = useState<string[]>([]);
+ useEffect(() => {
+ setViewMode('project');
+ }, [deviceId, workingDirectory]);
+
+ useEffect(() => {
+ if (projectSource && projectSource !== 'git') setViewMode('project');
+ }, [projectSource]);
+
useEffect(() => {
if (!normalizedDebouncedQuery) {
setIsSearching(false);
@@ -259,6 +345,45 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const treeRef = useRef<ExplorerTreeHandle>(null);
+ const handleCollapseAll = useCallback(() => {
+ treeRef.current?.setExpanded([]);
+ setExpandedIds([]);
+ }, []);
+
+ const viewItems = useMemo(
+ () => [
+ {
+ extra: viewMode === 'project' ? <CheckIcon size={14} /> : undefined,
+ icon: <FolderTreeIcon size={14} />,
+ key: 'project',
+ label: t('workingPanel.files.views.project'),
+ onClick: () => setViewMode('project'),
+ },
+ {
+ disabled: data?.source !== 'git',
+ extra: viewMode === 'changes' ? <CheckIcon size={14} /> : undefined,
+ icon: <GitCompareArrowsIcon size={14} />,
+ key: 'changes',
+ label: t('workingPanel.files.views.changes'),
+ onClick: () => setViewMode('changes'),
+ },
+ ],
+ [data?.source, t, viewMode],
+ );
+
+ const filterItems = useMemo(
+ () => [
+ {
+ checked: hideIgnored,
+ key: 'hide-ignored',
+ label: t('workingPanel.files.filters.hideIgnored'),
+ onCheckedChange: setHideIgnored,
+ type: 'checkbox' as const,
+ },
+ ],
+ [hideIgnored, t],
+ );
+
useEffect(() => {
if (!isFiltering) return;
treeRef.current?.setExpanded(defaultExpandedIds);
@@ -274,7 +399,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const nodeIds = new Set(nodes.map((n) => n.id));
if (!nodeIds.has(path)) return;
- const ancestors = getAncestorIds(path);
+ const ancestors = [PROJECT_ROOT_NODE_ID, ...getAncestorIds(path)];
const nextExpanded = Array.from(new Set([...expandedIds, ...ancestors]));
treeRef.current?.setExpanded(nextExpanded);
treeRef.current?.select(path);
@@ -403,7 +528,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
[canOfferFile, dirtyFilePaths, isRemote, openNode, openWorkingSidebar, publishFile, t],
);
- const isEmpty = nodes.length === 0;
+ const isEmpty = displayEntries.length === 0;
if (!data && isLoading) {
return (
@@ -416,7 +541,57 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
return (
<Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
<div className={styles.subheader}>
- <FilesSearchBar onDebouncedChange={setDebouncedQuery} />
+ {searchExpanded ? (
+ <div className={styles.search}>
+ <FilesSearchBar
+ onClose={() => setSearchExpanded(false)}
+ onDebouncedChange={setDebouncedQuery}
+ />
+ </div>
+ ) : (
+ <>
+ <DropdownMenu items={viewItems} placement={'bottomLeft'}>
+ <Button
+ icon={viewMode === 'project' ? FolderTreeIcon : GitCompareArrowsIcon}
+ size={'small'}
+ style={{ maxWidth: 'calc(100% - 84px)' }}
+ title={t('workingPanel.files.views.title')}
+ type={'text'}
+ >
+ {t(
+ viewMode === 'project'
+ ? 'workingPanel.files.views.project'
+ : 'workingPanel.files.views.changes',
+ )}
+ <ChevronDownIcon size={12} />
+ </Button>
+ </DropdownMenu>
+ <div style={{ flex: 1 }} />
+ </>
+ )}
+ {!searchExpanded && (
+ <ActionIcon
+ icon={SearchIcon}
+ size={'small'}
+ title={t('workingPanel.files.search')}
+ onClick={() => setSearchExpanded(true)}
+ />
+ )}
+ <DropdownMenu items={filterItems} placement={'bottomRight'}>
+ <ActionIcon
+ active={hideIgnored}
+ icon={ListFilterIcon}
+ size={'small'}
+ title={t('workingPanel.files.filters.title')}
+ />
+ </DropdownMenu>
+ <ActionIcon
+ disabled={nodes.length === 0}
+ icon={FoldVerticalIcon}
+ size={'small'}
+ title={t('workingPanel.files.collapseAll')}
+ onClick={handleCollapseAll}
+ />
</div>
{isEmpty && isFiltering && isSearching ? (
<Center flex={1}>
@@ -427,7 +602,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
<Empty
icon={FileIcon}
description={t(
- isFiltering ? 'workingPanel.files.noSearchResults' : 'workingPanel.files.empty',
+ hasDisplayFilter ? 'workingPanel.files.noSearchResults' : 'workingPanel.files.empty',
)}
/>
</Center>