π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(files): handle filtered search and staged deletions (#18906)
Arvin Xua4b20150df7d
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 40e53524ac4..e768444101e 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -612,7 +612,9 @@ export const deviceRouter = router({searchProjectFiles: deviceProcedure.input(z.object({+ changedOnly: z.boolean().optional(),deviceId: z.string(),+ excludeIgnored: z.boolean().optional(),limit: z.number().int().positive().max(500).optional(),query: z.string(),scope: z.string(),@@ -620,7 +622,9 @@ export const deviceRouter = router({).query(async ({ ctx, input }) => {const result = await deviceGateway.searchProjectFiles({+ changedOnly: input.changedOnly,deviceId: input.deviceId,+ excludeIgnored: input.excludeIgnored,limit: input.limit,query: input.query,scope: input.scope,diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex a960f1d84f3..baabd308452 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -932,7 +932,9 @@ export class DeviceGateway {* compact tree subset with ancestor directories.*/async searchProjectFiles(params: {+ changedOnly?: boolean;deviceId: string;+ excludeIgnored?: boolean;limit?: number;query: string;scope: string;@@ -940,14 +942,27 @@ export class DeviceGateway {userId: string;workspaceId?: string;}): Promise<DeviceProjectFileSearchResult | undefined> {- const { userId, deviceId, limit, query, scope, timeout = 30_000, workspaceId } = params;+ const {+ changedOnly,+ userId,+ deviceId,+ excludeIgnored,+ limit,+ query,+ scope,+ timeout = 30_000,+ workspaceId,+ } = params;const client = this.getClient();if (!client) return undefined;try {const result = await client.invokeRpc<DeviceProjectFileSearchResult>({ deviceId, timeout, userId, workspaceId },- { method: 'searchProjectFiles', params: { limit, query, scope } },+ {+ method: 'searchProjectFiles',+ params: { changedOnly, excludeIgnored, limit, query, scope },+ },);if (!result.success || !result.data) {diff --git a/packages/device-control/src/__tests__/projectFileIndex.test.ts b/packages/device-control/src/__tests__/projectFileIndex.test.tsindex 2bf43e6afb9..21f0016abb6 100644--- a/packages/device-control/src/__tests__/projectFileIndex.test.ts+++ b/packages/device-control/src/__tests__/projectFileIndex.test.ts@@ -145,6 +145,65 @@ describe('defaultSearchProjectFiles', () => {]);});+ it('applies eligible-path and ignore filters before truncating search results', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-filtered-'));+ cleanup.push(dir);+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });+ await writeFile(path.join(dir, '.gitignore'), '*.local\n');+ await Promise.all(+ Array.from({ length: 201 }, (_, index) =>+ writeFile(path.join(dir, `target-${index.toString().padStart(3, '0')}.ts`), 'target\n'),+ ),+ );+ await writeFile(path.join(dir, 'target-secret.local'), 'ignored\n');+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: dir });+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: dir });+ execFileSync('git', ['add', '.'], { cwd: dir });+ execFileSync('git', ['commit', '-m', 'init'], { cwd: dir });+ await writeFile(path.join(dir, 'target-200.ts'), 'changed\n');++ const result = await defaultSearchProjectFiles({+ changedOnly: true,+ excludeIgnored: true,+ limit: 1,+ query: 'target',+ scope: dir,+ });++ expect(result.entries.map((entry) => entry.relativePath)).toEqual(['target-200.ts']);+ });++ it('fuzzy-ranks missing eligible paths with indexed files before applying the limit', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-deleted-'));+ cleanup.push(dir);+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });+ await writeFile(path.join(dir, 'button-helper.ts'), 'button\n');+ await writeFile(path.join(dir, 'Button.tsx'), 'button\n');+ await writeFile(path.join(dir, 'ButtonStory.tsx'), 'button\n');+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: dir });+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: dir });+ execFileSync('git', ['add', '.'], { cwd: dir });+ execFileSync('git', ['commit', '-m', 'init'], { cwd: dir });+ await Promise.all([+ rm(path.join(dir, 'Button.tsx')),+ rm(path.join(dir, 'ButtonStory.tsx')),+ writeFile(path.join(dir, 'button-helper.ts'), 'changed\n'),+ ]);++ const result = await defaultSearchProjectFiles({+ changedOnly: true,+ limit: 2,+ query: 'btn',+ scope: dir,+ });++ const relativePaths = result.entries+ .filter((entry) => !entry.isDirectory)+ .map((entry) => entry.relativePath);+ expect(relativePaths).toHaveLength(2);+ expect(relativePaths).toContain('Button.tsx');+ });+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.tsindex 1670f581f23..eda6e356ef8 100644--- a/packages/device-control/src/projectFileIndex.ts+++ b/packages/device-control/src/projectFileIndex.ts@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process';import path from 'node:path';import { promisify } from 'node:util';+import { getGitWorkingTreeFiles } from '@lobechat/local-file-shell/git';import fg from 'fast-glob';import { projectFileSearchManager } from './projectFileSearchManager';@@ -193,6 +194,47 @@ export const defaultGetProjectFileIndex = async (};};+const filterSearchCandidates = (+ entries: ProjectFileIndexEntry[],+ params: ProjectFileSearchParams,+ includePaths?: string[],+) => {+ if (!params.excludeIgnored && !includePaths) return entries;++ const includedPaths = includePaths ? new Set(includePaths) : undefined;+ return entries.filter(+ (entry) =>+ entry.isDirectory ||+ ((!params.excludeIgnored || !entry.gitIgnored) &&+ (!includedPaths || includedPaths.has(entry.relativePath))),+ );+};++const includeMissingSearchCandidates = (+ entries: ProjectFileIndexEntry[],+ includePaths: string[] | undefined,+ root: string,+) => {+ if (!includePaths) return entries;++ const indexedPaths = new Set(entries.map((entry) => entry.relativePath));+ const rootPrefix = `${path.resolve(root)}${path.sep}`;+ const missingFiles = includePaths+ .filter((relativePath) => !indexedPaths.has(relativePath))+ .map((relativePath) => path.resolve(root, relativePath))+ .filter((absolutePath) => absolutePath.startsWith(rootPrefix));++ if (missingFiles.length === 0) return entries;++ const additions = buildEntries(missingFiles, root).filter((entry) => {+ if (indexedPaths.has(entry.relativePath)) return false;+ indexedPaths.add(entry.relativePath);+ return true;+ });++ return [...entries, ...additions];+};+export const defaultSearchProjectFiles = async (params: ProjectFileSearchParams,): Promise<ProjectFileSearchResult> => {@@ -210,6 +252,9 @@ export const defaultSearchProjectFiles = async (rootResult?.stdout && !exitCode ? rootResult.stdout.trim() || requestedScope : requestedScope;if (rootResult?.stdout && !exitCode) {+ const includePaths = params.changedOnly+ ? Object.values(await getGitWorkingTreeFiles(root)).flat()+ : undefined;const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([execFileAsync('git',@@ -246,7 +291,11 @@ export const defaultSearchProjectFiles = async (.split('\n').map((item) => item.trim()).filter(Boolean);- const entries = buildEntries(files, root, ignoredPaths);+ const entries = filterSearchCandidates(+ includeMissingSearchCandidates(buildEntries(files, root, ignoredPaths), includePaths, root),+ params,+ includePaths,+ );return {entries: projectFileSearchManager.selectEntries(entries, params.query, limit),@@ -260,7 +309,11 @@ export const defaultSearchProjectFiles = async (}const files = await projectFileSearchManager.collectNonGitFilePaths(requestedScope);- const entries = buildEntries(files, requestedScope);+ const entries = filterSearchCandidates(+ includeMissingSearchCandidates(buildEntries(files, requestedScope), undefined, requestedScope),+ params,+ params.changedOnly ? [] : undefined,+ );return {entries: projectFileSearchManager.selectEntries(entries, params.query, limit),diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 082a13915d8..57ed1b64db7 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -138,6 +138,8 @@ export interface ProjectFileIndexResult {}export interface ProjectFileSearchParams extends ProjectFileIndexParams {+ changedOnly?: boolean;+ excludeIgnored?: boolean;limit?: number;query: string;}diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex f59a5c44ace..9b862f25030 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -291,6 +291,8 @@ export interface ProjectFileIndexResult {}export interface ProjectFileSearchParams extends ProjectFileIndexParams {+ changedOnly?: boolean;+ excludeIgnored?: boolean;limit?: number;query: string;}diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex 030d14cd70d..d581581a7d6 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -13,7 +13,7 @@ const okTrpcResponse = (data: unknown) =>status: 200,});-describe('lambdaClient transfer-job status transport', () => {+describe('lambdaClient large-input query transport', () => {const fetchMock = vi.fn();beforeEach(() => {@@ -38,6 +38,8 @@ describe('lambdaClient transfer-job status transport', () => {agentId: 'agt_test',topicIds: Array.from({ length: 1000 }, (_, i) => `tpc_${String(i).padStart(16, '0')}`),}),+ 'topicIds',+ 1000,],['group.getTransferJobStatus',@@ -46,19 +48,24 @@ describe('lambdaClient transfer-job status transport', () => {groupId: 'grp_test',topicIds: Array.from({ length: 1000 }, (_, i) => `tpc_${String(i).padStart(16, '0')}`),}),+ 'topicIds',+ 1000,],- ] as const)('sends %s with 1000 topicIds as a POST request', async (path, call) => {- fetchMock.mockResolvedValueOnce(okTrpcResponse(null));+ ] as const)(+ 'sends %s with a large path/id array as a POST request',+ async (path, call, arrayField, expectedLength) => {+ fetchMock.mockResolvedValueOnce(okTrpcResponse(null));- await expect(call()).resolves.toBeNull();+ await expect(call()).resolves.toBeNull();- expect(fetchMock).toHaveBeenCalledTimes(1);- const [input, init] = fetchMock.mock.calls[0] as [RequestInfo | URL, RequestInit];- expect(init.method).toBe('POST');- // The input travels in the body, not the query string.- expect(String(input)).toContain(`/trpc/lambda/${path}`);- expect(String(input).length).toBeLessThan(2083);- const body = JSON.parse(String(init.body)) as { json: { topicIds: string[] } };- expect(body.json.topicIds).toHaveLength(1000);- });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [input, init] = fetchMock.mock.calls[0] as [RequestInfo | URL, RequestInit];+ expect(init.method).toBe('POST');+ // The input travels in the body, not the query string.+ expect(String(input)).toContain(`/trpc/lambda/${path}`);+ expect(String(input).length).toBeLessThan(2083);+ const body = JSON.parse(String(init.body)) as { json: Record<string, unknown[]> };+ expect(body.json[arrayField]).toHaveLength(expectedLength);+ },+ );});diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsxindex dd1bdbb598f..f7945acd99b 100644--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx@@ -147,6 +147,7 @@ vi.mock('../useProjectFiles', () => ({useProjectFiles: (_deviceId: string | undefined, workingDirectory: string) => ({data: {...projectFilesMock.data,+ entries: projectFilesMock.data.entries,source: workingDirectory === '/non-git' ? 'glob' : projectFilesMock.data.source,},isLoading: false,@@ -198,12 +199,24 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({items,}: {children?: ReactNodeType;- items: { key: string; label: ReactNodeType; onClick?: () => void }[];+ items: {+ key: string;+ label: ReactNodeType;+ onCheckedChange?: (checked: boolean) => void;+ onClick?: () => void;+ }[];}) => (<div>{children}{items.map((item) => (- <button key={item.key} type={'button'} onClick={item.onClick}>+ <button+ key={item.key}+ type={'button'}+ onClick={() => {+ item.onClick?.();+ item.onCheckedChange?.(true);+ }}+ >{item.label}</button>))}@@ -341,9 +354,33 @@ describe('Files β reveal request integration', () => {'src/foo/','src/foo/bar.ts','root.ts',+ 'deleted.ts',]);});+ it('sends active Git and ignore filters to the file host before search truncation', async () => {+ render(<Files workingDirectory="/repo" />);++ fireEvent.click(screen.getByText('workingPanel.files.views.changes'));+ fireEvent.click(screen.getByTitle('workingPanel.files.filters.title'));+ fireEvent.click(screen.getByText('workingPanel.files.filters.hideIgnored'));+ expandSearch();+ fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {+ target: { value: 'bar' },+ });++ await waitFor(() => {+ expect(searchProjectFilesMock).toHaveBeenCalledWith(+ expect.objectContaining({+ excludeIgnored: true,+ changedOnly: true,+ limit: 200,+ query: 'bar',+ }),+ );+ });+ });+it('resets the Git changes view when the workspace changes or is not Git-backed', async () => {const { rerender } = render(<Files workingDirectory="/repo" />);@@ -500,6 +537,8 @@ describe('Files β reveal request integration', () => {await waitFor(() => {expect(searchProjectFilesMock).toHaveBeenCalledWith({deviceId: undefined,+ excludeIgnored: false,+ changedOnly: false,limit: 200,query: 'bar',scope: '/repo',diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.tsindex 29fa3c5bda2..3bed46af741 100644--- a/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts@@ -1,7 +1,7 @@import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';import { describe, expect, it } from 'vitest';-import { filterProjectFileEntries } from './fileFilter';+import { filterProjectFileEntries, mergeMissingDeletedEntries } from './fileFilter';const entries: ProjectFileIndexEntry[] = [{ isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },@@ -66,3 +66,25 @@ describe('filterProjectFileEntries', () => {]);});});++describe('mergeMissingDeletedEntries', () => {+ it('recreates missing staged deletions and their absent ancestor directories', () => {+ const result = mergeMissingDeletedEntries(+ entries,+ ['src/components/Button.tsx', 'removed/deep/file.ts'],+ '/repo',+ );++ expect(result.map((entry) => entry.relativePath)).toEqual([+ ...entries.map((entry) => entry.relativePath),+ 'removed/',+ 'removed/deep/',+ 'removed/deep/file.ts',+ ]);+ expect(result.at(-1)).toMatchObject({+ isDirectory: false,+ name: 'file.ts',+ path: '/repo/removed/deep/file.ts',+ });+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.tsindex 87142049d59..1998467734b 100644--- a/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts@@ -1,4 +1,5 @@import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';+import path from 'pathe';export interface ProjectFileDisplayFilter {changedOnly: boolean;@@ -8,6 +9,50 @@ export interface ProjectFileDisplayFilter {const isPathInsideDirectory = (filePath: string, directoryPath: string) =>filePath.startsWith(directoryPath);+const getDirectoryPaths = (relativePath: string): string[] => {+ const segments = relativePath.split('/');+ return segments.slice(0, -1).map((_, index) => `${segments.slice(0, index + 1).join('/')}/`);+};++/**+ * A staged deletion is absent from `git ls-files`, so the project index cannot+ * supply its row. Recreate only those missing rows (and ancestors) from Git's+ * status paths so the Changes view remains complete.+ */+export const mergeMissingDeletedEntries = (+ entries: ProjectFileIndexEntry[],+ deletedPaths: string[],+ root: string,+): ProjectFileIndexEntry[] => {+ const existingPaths = new Set(entries.map((entry) => entry.relativePath));+ const missingPaths = deletedPaths.filter((relativePath) => !existingPaths.has(relativePath));+ if (missingPaths.length === 0) return entries;++ const additions: ProjectFileIndexEntry[] = [];+ for (const relativePath of missingPaths) {+ for (const directoryPath of getDirectoryPaths(relativePath)) {+ if (existingPaths.has(directoryPath)) continue;+ existingPaths.add(directoryPath);+ additions.push({+ isDirectory: true,+ name: path.basename(directoryPath),+ path: path.join(root, directoryPath),+ relativePath: directoryPath,+ });+ }++ existingPaths.add(relativePath);+ additions.push({+ isDirectory: false,+ name: path.basename(relativePath),+ path: path.join(root, relativePath),+ relativePath,+ });+ }++ return [...entries, ...additions];+};+export const filterProjectFileEntries = (entries: ProjectFileIndexEntry[],dirtyFilePaths: Set<string>,diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsxindex 8d05b2b820c..52741d40f97 100644--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx@@ -37,7 +37,7 @@ import { projectFileService } from '@/services/projectFile';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';-import { filterProjectFileEntries } from './fileFilter';+import { filterProjectFileEntries, mergeMissingDeletedEntries } from './fileFilter';import { isExcludedProjectFileEntry } from './fileVisibility';import { buildGitStatusEntries, useGitWorkingTreeFiles } from './useGitWorkingTreeFiles';import { useProjectFiles } from './useProjectFiles';@@ -249,15 +249,28 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {[workingTreeGitStatus],);const displayEntries = useMemo(() => {- const visibleEntries = (isFiltering ? (searchEntries ?? []) : entries).filter(- (entry) => !isExcludedProjectFileEntry(entry),+ const indexedEntries = isFiltering ? (searchEntries ?? []) : entries;+ const entriesWithDeleted = mergeMissingDeletedEntries(+ indexedEntries,+ isFiltering ? [] : (gitFiles?.deleted ?? []),+ projectRoot,);+ const visibleEntries = entriesWithDeleted.filter((entry) => !isExcludedProjectFileEntry(entry));return filterProjectFileEntries(visibleEntries, dirtyFilePaths, {changedOnly,hideIgnored,});- }, [changedOnly, dirtyFilePaths, entries, hideIgnored, isFiltering, searchEntries]);+ }, [+ changedOnly,+ dirtyFilePaths,+ entries,+ gitFiles?.deleted,+ hideIgnored,+ isFiltering,+ projectRoot,+ searchEntries,+ ]);const nodes = useMemo(() => buildTreeNodes(displayEntries, projectRootName),[displayEntries, projectRootName],@@ -310,7 +323,9 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {void projectFileService.searchProjectFiles({+ changedOnly,deviceId,+ excludeIgnored: hideIgnored,limit: PROJECT_FILE_TREE_SEARCH_LIMIT,query: normalizedDebouncedQuery,scope: workingDirectory,@@ -331,7 +346,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {return () => {cancelled = true;};- }, [deviceId, normalizedDebouncedQuery, workingDirectory]);+ }, [changedOnly, deviceId, hideIgnored, normalizedDebouncedQuery, workingDirectory]);// Skip resyncs when defaultExpandedIds is structurally unchanged so the user's expansions survive re-renders.const prevDefaultRef = useRef<string[]>([]);diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.tsindex fa85238aa7d..9829c56f341 100644--- a/src/services/projectFile.test.ts+++ b/src/services/projectFile.test.ts@@ -159,6 +159,8 @@ describe('projectFileService', () => {expect(mockDeviceClient.searchProjectFiles.query).toHaveBeenCalledWith({deviceId: 'device-1',+ excludeIgnored: undefined,+ changedOnly: undefined,limit: 20,query: 'button',scope: '/repo',@@ -182,6 +184,8 @@ describe('projectFileService', () => {});expect(mockLocalFileService.searchProjectFiles).toHaveBeenCalledWith({+ excludeIgnored: undefined,+ changedOnly: undefined,limit: 20,query: 'button',scope: '/repo',diff --git a/src/services/projectFile.ts b/src/services/projectFile.tsindex e1ac95d6893..9964cf9580a 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -73,20 +73,30 @@ class ProjectFileService {/** Search files within a project working directory. Matching runs on the file host. */async searchProjectFiles({+ changedOnly,deviceId,+ excludeIgnored,limit,query,scope,}: {+ changedOnly?: boolean;deviceId?: string;+ excludeIgnored?: boolean;limit?: number;query: string;scope: string;}): Promise<ProjectFileSearchResult | undefined> {return deviceId- ? ((await lambdaClient.device.searchProjectFiles.query({ deviceId, limit, query, scope })) ??- undefined)- : localFileService.searchProjectFiles({ limit, query, scope });+ ? ((await lambdaClient.device.searchProjectFiles.query({+ changedOnly,+ deviceId,+ excludeIgnored,+ limit,+ query,+ scope,+ })) ?? undefined)+ : localFileService.searchProjectFiles({ changedOnly, excludeIgnored, limit, query, scope });}/** File preview payload for a file in a project working directory. */