Skip to content

Commit bc1d572

Browse files
yangching2claude
andcommitted
fix(server): skip inaccessible directories in the file tree
Running mdts (zero-config) in a folder that contains a sub-directory the process can't read made getFileTree's fs.readdirSync throw EACCES. The throw bubbled up as an HTTP 500 from GET /api/filetree and left the tree panel blank, so the app appeared broken. Wrap readdirSync in try/catch. On the "can't enumerate this directory" family (EACCES/EPERM, plus the ENOENT/ENOTDIR races) log a skip and return an empty sub-tree so the rest still renders. Unexpected errors still propagate. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 0a2193f commit bc1d572

2 files changed

Lines changed: 46 additions & 4 deletions

File tree

‎src/server/routes/filetree.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from 'path';
44
import simpleGit, { SimpleGit, StatusResult, FileStatusResult } from 'simple-git';
55
import { EXCLUDED_DIRECTORIES } from '../../constants';
66
import { ServerContext } from '../context';
7+
import { logger } from '../../utils/logger';
78
import { resolveGlobPatterns } from '../../utils/glob';
89

910
type FileTreeItem = { path: string, status: string, isDirectory?: boolean } | { [key: string]: FileTree };
@@ -39,6 +40,20 @@ const shouldIncludeEntry = (entry: Dirent): boolean => {
3940
return !isDotFileOrDirectory(entry.name) && !EXCLUDED_DIRECTORIES.includes(entry.name);
4041
};
4142

43+
// Errors that mean "this directory can't be enumerated" — skip it and keep going
44+
// rather than failing the whole file tree. EACCES/EPERM cover permission denials;
45+
// ENOENT/ENOTDIR cover races where the entry vanishes or isn't a directory.
46+
const UNREADABLE_DIRECTORY_ERROR_CODES = ['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR'];
47+
48+
const isUnreadableDirectoryError = (error: unknown): boolean => {
49+
return Boolean(
50+
error &&
51+
typeof error === 'object' &&
52+
'code' in error &&
53+
UNREADABLE_DIRECTORY_ERROR_CODES.includes((error as NodeJS.ErrnoException).code as string),
54+
);
55+
};
56+
4257
const buildFileTreeFromPatterns = (
4358
filePatterns: string[],
4459
gitStatus: StatusResult | null,
@@ -95,10 +110,16 @@ const getFileTree = async (
95110
gitStatus: StatusResult | null
96111
): Promise<FileTree> => {
97112
const fullPath = path.join(baseDirectory, currentRelativePath);
98-
const entriesInDir = fs.readdirSync(
99-
fullPath,
100-
{ withFileTypes: true }
101-
);
113+
let entriesInDir: Dirent[];
114+
try {
115+
entriesInDir = fs.readdirSync(fullPath, { withFileTypes: true });
116+
} catch (error) {
117+
if (isUnreadableDirectoryError(error)) {
118+
logger.log('Server', `🔒 Skipping inaccessible directory: ${currentRelativePath || fullPath}`);
119+
return [];
120+
}
121+
throw error;
122+
}
102123
const entries = entriesInDir.filter(shouldIncludeEntry);
103124

104125
const tree: FileTree = [];

‎test/unit/server/routes/filetree.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,27 @@ describe('filetree.ts', () => {
7474
isGitRepository: true,
7575
});
7676
});
77+
78+
it('should skip inaccessible directories (EACCES) and still return the rest of the tree', async () => {
79+
(fs.readdirSync as jest.Mock)
80+
.mockReturnValueOnce([ // For root: an unreadable dir + a readable markdown file
81+
mockDirent('inaccessible', true),
82+
mockDirent('file1.md', false),
83+
])
84+
.mockImplementationOnce(() => { // For inaccessible: permission denied
85+
const error = new Error('permission denied') as NodeJS.ErrnoException;
86+
error.code = 'EACCES';
87+
throw error;
88+
});
89+
90+
const response = await request(app).get('/api/filetree');
91+
expect(response.statusCode).toBe(200);
92+
expect(response.body).toEqual({
93+
fileTree: [{ path: 'file1.md', status: ' ' }],
94+
mountedDirectoryPath: mockDirectory,
95+
isGitRepository: true,
96+
});
97+
});
7798
});
7899

79100
describe('fileTreeRouter with file patterns', () => {

0 commit comments

Comments
 (0)