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(agent): render gitignored workspace files (#17517)

Innei432119533c22
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index a2117daf49c..667456d9646 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -182,10 +182,12 @@ const createProjectFileEntry = (
root: string,
absolutePath: string,
isDirectory: boolean,
+ gitIgnored?: boolean,
): ProjectFileIndexEntry => {
const relativePath = toPosixRelativePath(path.relative(root, absolutePath));
return {
+ ...(gitIgnored ? { gitIgnored: true } : {}),
isDirectory,
name: path.basename(absolutePath),
path: absolutePath,
@@ -662,7 +664,7 @@ export default class LocalFileCtr extends ControllerModule {
const root = rootResult.exitCode === 0 ? rootResult.stdout.trim() : requestedScope;
if (rootResult.exitCode === 0) {
- const [trackedResult, untrackedResult] = await Promise.all([
+ const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([
execa(
'git',
['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
@@ -684,6 +686,21 @@ export default class LocalFileCtr extends ControllerModule {
],
{ reject: false, timeout: 10_000 },
),
+ execa(
+ 'git',
+ [
+ '-C',
+ root,
+ '-c',
+ 'core.quotepath=false',
+ 'ls-files',
+ '--others',
+ '--ignored',
+ '--exclude-standard',
+ '--directory',
+ ],
+ { reject: false, timeout: 10_000 },
+ ),
]);
if (trackedResult.exitCode !== 0) {
@@ -698,6 +715,24 @@ export default class LocalFileCtr extends ControllerModule {
.filter(Boolean)
.map((relativePath) => path.resolve(root, relativePath));
+ const ignoredEntries =
+ ignoredResult.exitCode === 0
+ ? ignoredResult.stdout
+ .split('\n')
+ .map((item) => item.trim())
+ .filter(Boolean)
+ .map((relativePath) => {
+ const isDirectory = relativePath.endsWith('/');
+ const normalizedPath = isDirectory ? relativePath.slice(0, -1) : relativePath;
+ return createProjectFileEntry(
+ root,
+ path.resolve(root, normalizedPath),
+ isDirectory,
+ true,
+ );
+ })
+ : [];
+
const seen = new Set<string>();
const fileEntries = files
.filter((filePath) => {
@@ -707,11 +742,22 @@ export default class LocalFileCtr extends ControllerModule {
})
.map((filePath) => createProjectFileEntry(root, filePath, false));
- const entries = [...collectProjectDirectories(files, root), ...fileEntries];
+ const uniqueIgnoredEntries = ignoredEntries.filter((entry) => {
+ if (seen.has(entry.path)) return false;
+ seen.add(entry.path);
+ return true;
+ });
+ const indexedPaths = [...fileEntries, ...uniqueIgnoredEntries].map((entry) => entry.path);
+ const entries = [
+ ...collectProjectDirectories(indexedPaths, root),
+ ...fileEntries,
+ ...uniqueIgnoredEntries,
+ ];
logger.debug('Project file index built from git', {
duration: Date.now() - startedAt,
entries: entries.length,
files: fileEntries.length,
+ ignored: uniqueIgnoredEntries.length,
requestedScope,
root,
});
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index c6249e99fb7..79117b3d26a 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -710,7 +710,8 @@ describe('LocalFileCtr', () => {
exitCode: 0,
stdout: 'src/index.ts\nsrc/components/Button.tsx',
})
- .mockResolvedValueOnce({ exitCode: 0, stdout: 'tmp/local.ts' });
+ .mockResolvedValueOnce({ exitCode: 0, stdout: 'tmp/local.ts' })
+ .mockResolvedValueOnce({ exitCode: 0, stdout: '.env.local\ncache/' });
const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project' });
@@ -733,6 +734,18 @@ describe('LocalFileCtr', () => {
path: '/workspace/project/tmp/local.ts',
relativePath: 'tmp/local.ts',
}),
+ expect.objectContaining({
+ gitIgnored: true,
+ isDirectory: false,
+ path: '/workspace/project/.env.local',
+ relativePath: '.env.local',
+ }),
+ expect.objectContaining({
+ gitIgnored: true,
+ isDirectory: true,
+ path: '/workspace/project/cache',
+ relativePath: 'cache/',
+ }),
]),
);
expect(result).not.toHaveProperty('totalCount');
diff --git a/packages/device-control/src/__tests__/projectFileIndex.test.ts b/packages/device-control/src/__tests__/projectFileIndex.test.ts
index e3f76844aa9..2bf43e6afb9 100644
--- a/packages/device-control/src/__tests__/projectFileIndex.test.ts
+++ b/packages/device-control/src/__tests__/projectFileIndex.test.ts
@@ -24,10 +24,14 @@ describe('defaultGetProjectFileIndex', () => {
await mkdir(path.join(dir, 'src'), { recursive: true });
await writeFile(path.join(dir, 'src', 'index.ts'), 'export const a = 1;\n');
await writeFile(path.join(dir, 'README.md'), '# hi\n');
+ await writeFile(path.join(dir, '.gitignore'), '.env.local\ncache/\n');
execFileSync('git', ['add', '.'], { cwd: dir });
execFileSync('git', ['commit', '-m', 'init'], { cwd: dir });
// Untracked-but-not-ignored file is included via ls-files --others.
await writeFile(path.join(dir, 'scratch.txt'), 'tmp\n');
+ await mkdir(path.join(dir, 'cache'), { recursive: true });
+ await writeFile(path.join(dir, 'cache', 'artifact.bin'), 'ignored\n');
+ await writeFile(path.join(dir, '.env.local'), 'TOKEN=test\n');
const result = await defaultGetProjectFileIndex({ scope: dir });
@@ -36,6 +40,17 @@ describe('defaultGetProjectFileIndex', () => {
expect(rels).toContain('src/index.ts');
expect(rels).toContain('README.md');
expect(rels).toContain('scratch.txt');
+ expect(result.entries.find((entry) => entry.relativePath === '.env.local')).toMatchObject({
+ gitIgnored: true,
+ isDirectory: false,
+ });
+ expect(result.entries.find((entry) => entry.relativePath === 'cache/')).toMatchObject({
+ gitIgnored: true,
+ isDirectory: true,
+ });
+ // Fully ignored directories are represented by one collapsed entry instead
+ // of recursively indexing potentially enormous dependency/build trees.
+ expect(rels).not.toContain('cache/artifact.bin');
// The intermediate directory is surfaced as its own entry.
expect(result.entries.find((e) => e.relativePath === 'src/')?.isDirectory).toBe(true);
expect(result).not.toHaveProperty('totalCount');
@@ -112,6 +127,24 @@ describe('defaultSearchProjectFiles', () => {
expect(relativePaths).not.toContain('nested/deep/other.ts');
});
+ it('returns matching gitignored files with ignore metadata', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-ignored-'));
+ cleanup.push(dir);
+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });
+ await writeFile(path.join(dir, '.gitignore'), '*.local\n');
+ await writeFile(path.join(dir, 'secret.local'), 'ignored\n');
+
+ const result = await defaultSearchProjectFiles({ query: 'secret', scope: dir });
+
+ expect(result.entries).toEqual([
+ expect.objectContaining({
+ gitIgnored: true,
+ isDirectory: false,
+ relativePath: 'secret.local',
+ }),
+ ]);
+ });
+
it('searches hidden project directories in non-git scopes', async () => {
const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-hidden-'));
cleanup.push(dir);
diff --git a/packages/device-control/src/projectFileIndex.ts b/packages/device-control/src/projectFileIndex.ts
index 92fc77d9fed..1670f581f23 100644
--- a/packages/device-control/src/projectFileIndex.ts
+++ b/packages/device-control/src/projectFileIndex.ts
@@ -23,9 +23,11 @@ const createProjectFileEntry = (
root: string,
absolutePath: string,
isDirectory: boolean,
+ gitIgnored?: boolean,
): ProjectFileIndexEntry => {
const relativePath = toPosixRelativePath(path.relative(root, absolutePath));
return {
+ ...(gitIgnored ? { gitIgnored: true } : {}),
isDirectory,
name: path.basename(absolutePath),
path: absolutePath,
@@ -52,7 +54,11 @@ const collectProjectDirectories = (files: string[], root: string): ProjectFileIn
* so nested files attach to explicit parent directory entries instead of
* flattening to the root.
*/
-const buildEntries = (files: string[], root: string): ProjectFileIndexEntry[] => {
+const buildEntries = (
+ files: string[],
+ root: string,
+ ignoredPaths: string[] = [],
+): ProjectFileIndexEntry[] => {
const seen = new Set<string>();
const fileEntries = files
.filter((filePath) => {
@@ -62,7 +68,25 @@ const buildEntries = (files: string[], root: string): ProjectFileIndexEntry[] =>
})
.map((filePath) => createProjectFileEntry(root, filePath, false));
- return [...collectProjectDirectories(files, root), ...fileEntries];
+ // `git ls-files --directory` keeps individual ignored files visible while
+ // collapsing fully ignored directories (for example node_modules/) into one
+ // bounded entry. The trailing slash is therefore meaningful and must be
+ // preserved as directory metadata before resolving the absolute path.
+ const ignoredEntries = ignoredPaths
+ .map((relativePath) => {
+ const isDirectory = relativePath.endsWith('/');
+ const normalizedPath = isDirectory ? relativePath.slice(0, -1) : relativePath;
+ return createProjectFileEntry(root, path.resolve(root, normalizedPath), isDirectory, true);
+ })
+ .filter((entry) => {
+ if (seen.has(entry.path)) return false;
+ seen.add(entry.path);
+ return true;
+ });
+
+ const indexedPaths = [...fileEntries, ...ignoredEntries].map((entry) => entry.path);
+
+ return [...collectProjectDirectories(indexedPaths, root), ...fileEntries, ...ignoredEntries];
};
const collectGlobFilePaths = async (scope: string): Promise<string[]> => {
@@ -84,9 +108,10 @@ const collectGlobFilePaths = async (scope: string): Promise<string[]> => {
/**
* Portable project file index for the CLI (and any non-desktop device). Prefers
- * `git ls-files` (tracked + untracked, submodule-aware) to enumerate the repo,
- * falling back to a `fast-glob` walk when the scope is not a git repo. Mirrors
- * the desktop `LocalFileCtr.getProjectFileIndex` output shape.
+ * `git ls-files` (tracked + untracked + collapsed ignored entries,
+ * submodule-aware) to enumerate the repo, falling back to a `fast-glob` walk
+ * when the scope is not a git repo. Mirrors the desktop
+ * `LocalFileCtr.getProjectFileIndex` output shape.
*/
export const defaultGetProjectFileIndex = async (
params: ProjectFileIndexParams = {},
@@ -104,7 +129,7 @@ export const defaultGetProjectFileIndex = async (
rootResult?.stdout && !exitCode ? rootResult.stdout.trim() || requestedScope : requestedScope;
if (rootResult?.stdout && !exitCode) {
- const [trackedResult, untrackedResult] = await Promise.all([
+ const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([
execFileAsync(
'git',
['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
@@ -115,6 +140,21 @@ export const defaultGetProjectFileIndex = async (
['-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')]
@@ -122,7 +162,11 @@ export const defaultGetProjectFileIndex = async (
.filter(Boolean)
.map((relativePath) => path.resolve(root, relativePath));
- const entries = buildEntries(files, root);
+ const ignoredPaths = ignoredResult.stdout
+ .split('\n')
+ .map((item) => item.trim())
+ .filter(Boolean);
+ const entries = buildEntries(files, root, ignoredPaths);
return {
entries,
@@ -166,7 +210,7 @@ export const defaultSearchProjectFiles = async (
rootResult?.stdout && !exitCode ? rootResult.stdout.trim() || requestedScope : requestedScope;
if (rootResult?.stdout && !exitCode) {
- const [trackedResult, untrackedResult] = await Promise.all([
+ const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([
execFileAsync(
'git',
['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
@@ -177,13 +221,32 @@ export const defaultSearchProjectFiles = async (
['-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')]
.map((item) => item.trim())
.filter(Boolean)
.map((relativePath) => path.resolve(root, relativePath));
- const entries = buildEntries(files, root);
+ const ignoredPaths = ignoredResult.stdout
+ .split('\n')
+ .map((item) => item.trim())
+ .filter(Boolean);
+ const entries = buildEntries(files, root, ignoredPaths);
return {
entries: projectFileSearchManager.selectEntries(entries, params.query, limit),
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 11efa2ce2d4..45ce2513f07 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -103,6 +103,8 @@ export interface LocalFilePreviewResult {
// ─── Project file index ───
export interface ProjectFileIndexEntry {
+ /** Whether Git ignore rules match this file or directory. */
+ gitIgnored?: boolean;
isDirectory: boolean;
name: string;
path: string;
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index ae9fd8d8d7d..1e9982fa07e 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -249,6 +249,8 @@ export interface LocalSearchFilesParams {
}
export interface ProjectFileIndexEntry {
+ /** Whether Git ignore rules match this file or directory. */
+ gitIgnored?: boolean;
isDirectory: boolean;
name: string;
path: string;
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index f7d3f4b5520..e5e1fa188c6 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -604,6 +604,8 @@ export interface DeviceGitWorkingTreeFiles {
/** One entry in a device's project file index. Mirrors `ProjectFileIndexEntry`. */
export interface DeviceProjectFileIndexEntry {
+ /** Whether Git ignore rules match this file or directory. */
+ gitIgnored?: boolean;
isDirectory: boolean;
name: string;
/** Absolute path on the device filesystem. */
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index a3c6941a716..3a54748d91e 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -83,6 +83,13 @@ vi.mock('../useProjectFiles', () => ({
path: '/repo/root.ts',
relativePath: 'root.ts',
},
+ {
+ gitIgnored: true,
+ isDirectory: false,
+ name: '.env.local',
+ path: '/repo/.env.local',
+ relativePath: '.env.local',
+ },
],
indexedAt: '2026-01-01',
root: '/repo',
@@ -195,14 +202,19 @@ describe('Files β€” reveal request integration', () => {
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' },
]);
- expect(explorerTreeProps.current?.unsafeCSS).toBe('folder-css\nhide-pointer-focus-ring-css');
+ expect(explorerTreeProps.current?.unsafeCSS).toContain(
+ "[data-item-git-status='ignored'] > :where(",
+ );
+ expect(explorerTreeProps.current?.unsafeCSS).toContain('opacity: 0.7');
const nodes = explorerTreeProps.current?.nodes as { id: string }[];
const dirtyNode = nodes.find((node) => node.id === 'src/foo/bar.ts');
+ const ignoredNode = nodes.find((node) => node.id === '.env.local');
const cleanFolderNode = nodes.find((node) => node.id === 'src/');
const getContextMenuItems = explorerTreeProps.current?.getContextMenuItems as (
@@ -226,6 +238,9 @@ describe('Files β€” reveal request integration', () => {
'copy-absolute-path',
'copy-relative-path',
]);
+ expect(getContextMenuItems(ignoredNode).map((item) => item.key)).not.toContain(
+ 'show-in-review',
+ );
});
it('opens file previews with the indexed project root as the approved workspace root', () => {
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
index 9717f30d0c5..884ebc451db 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -2,6 +2,7 @@
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
import { Center, copyToClipboard, Empty, Flexbox, SearchBar, stopPropagation } from '@lobehub/ui';
+import type { GitStatusEntry } from '@pierre/trees';
import type { MenuProps } from 'antd';
import { message } from 'antd';
import { createStaticStyles } from 'antd-style';
@@ -65,7 +66,20 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
-const FILE_TREE_UNSAFE_CSS = `${FOLDER_ICON_CSS}\n${HIDE_POINTER_FOCUS_RING_CSS}`;
+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;
@@ -96,6 +110,11 @@ const buildTreeNodes = (
});
};
+const buildIgnoredGitStatusEntries = (entries: ProjectFileIndexEntry[]): GitStatusEntry[] =>
+ entries
+ .filter((entry) => entry.gitIgnored)
+ .map((entry) => ({ path: entry.relativePath, status: 'ignored' }));
+
const getAncestorIds = (filePath: string): string[] => {
const segments = filePath.split('/');
const ancestors: string[] = [];
@@ -128,8 +147,15 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
[entries, isFiltering, searchEntries],
);
const nodes = useMemo(() => buildTreeNodes(displayEntries), [displayEntries]);
- const gitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);
- const dirtyFilePaths = useMemo(() => new Set(gitStatus.map((entry) => entry.path)), [gitStatus]);
+ 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],
+ );
// Pre-expand top-level directories so the user sees something useful on first
// paint without having to click through every folder.
const defaultExpandedIds = useMemo(