Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/tools/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,19 @@ export async function listDirectory(dirPath: string, depth: number = 2): Promise

const MAX_NESTED_ITEMS = 100; // Maximum items to show per nested directory

try {
const stats = await fs.stat(validPath);
if (!stats.isDirectory()) {
throw new Error(`Path is not a directory: ${dirPath}`);
}
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
throw new Error(`Directory not found: ${dirPath}`);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
throw error;
}
Comment on lines +689 to +704

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The new top-level fs.stat pre-check changes error behavior for inaccessible directories: if stat fails with EACCES/EPERM/ETIMEDOUT, the function now throws immediately instead of returning the existing [DENIED] ... entry format. This breaks the established list-directory contract used by the UI/parser for access-denied cases. Handle these permission/timeout errors in this block the same way as the readdir catch (append [DENIED] and return), or remove this pre-check and rely on the existing readdir handling. [logic error]

Severity Level: Major ⚠️
- ⚠️ list_directory tool no longer returns [DENIED] for permissions.
- ⚠️ File preview UI can't mark denied root directories correctly.
- ⚠️ Error responses diverge from documented list_directory behavior.
Steps of Reproduction ✅
1. Build the project so the runtime JS artifacts exist (as in the PR test instructions,
run `npm run build`) and note that the list_directory tool is wired up via
`handleListDirectory` in `src/handlers/filesystem-handlers.ts:325-331`, which calls
`listDirectory(parsed.path, parsed.depth)` and wraps any thrown error with
`createErrorResponse` from `src/error-handlers.ts:9-16`.

2. In a Node script or REPL, mirror the setup used in
`test/test-list-directory-errors.js:6-15`: import `configManager` from
`dist/config-manager.js` and `listDirectory` from `dist/tools/filesystem.js`, set
`allowedDirectories` to a temporary root (e.g.
`/tmp/desktop-commander-list-directory-errors`), create a subdirectory `denied-root` under
this root, then remove execute/search permissions on it (e.g. `await fs.mkdir(deniedDir);
await fs.chmod(deniedDir, 0);`) so that `fs.stat(deniedDir)` fails with `EACCES`/`EPERM`
on your platform.

3. Call `await listDirectory(deniedDir, 1)` (same function under test in
`test/test-list-directory-errors.js:26-31`): inside `src/tools/filesystem.ts:674-681`,
`listDirectory` validates the path then hits the new pre-check `fs.stat(validPath)` at
lines `680-683`; because the directory is not stat-able, the `catch` block at `684-691`
sees an `EACCES`/`EPERM` error, does not match `ENOENT`/`ENOTDIR`, and rethrows the raw
error instead of producing a `[DENIED]` entry.

4. Observe that the promise from `listDirectory` rejects with a generic `EACCES`/`EPERM`
error and no `[DENIED]`-prefixed line, so the recursive `fs.readdir` call and its error
handler at `src/tools/filesystem.ts:48-63` (which pushes `[DENIED] ${displayPath}` and is
explicitly documented with "Keep [DENIED] prefix so UI parser regex still matches.") is
never reached; when invoked through the tool path (`handleListDirectory` in
`src/handlers/filesystem-handlers.ts:325-331` and tool metadata in `src/server.ts:37-69`),
this means the directory tool returns an `Error: ... permission denied` response instead
of a listing containing `[DENIED]`, breaking the contract relied on by
`parseDirectoryEntries` in `src/ui/file-preview/src/directory-controller.ts:55-58` and the
documented behavior in `src/server.ts:63-64` ("If a directory cannot be accessed, it will
show [DENIED] instead.").

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/tools/filesystem.ts
**Line:** 680:691
**Comment:**
	*Logic Error: The new top-level `fs.stat` pre-check changes error behavior for inaccessible directories: if `stat` fails with `EACCES`/`EPERM`/`ETIMEDOUT`, the function now throws immediately instead of returning the existing `[DENIED] ...` entry format. This breaks the established list-directory contract used by the UI/parser for access-denied cases. Handle these permission/timeout errors in this block the same way as the `readdir` catch (append `[DENIED]` and return), or remove this pre-check and rely on the existing `readdir` handling.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎


async function listRecursive(currentPath: string, currentDepth: number, relativePath: string = '', isTopLevel: boolean = true): Promise<void> {
if (currentDepth <= 0) return;

Expand All @@ -685,6 +698,9 @@ export async function listDirectory(dirPath: string, depth: number = 2): Promise
entries = await fs.readdir(currentPath, { withFileTypes: true });
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (isTopLevel && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
throw new Error(`Directory not found: ${dirPath}`);
}
const displayPath = relativePath || path.basename(currentPath);
// Keep [DENIED] prefix so UI parser regex still matches.
// Append a hint for permission/timeout errors so user gets context.
Expand Down Expand Up @@ -1010,4 +1026,4 @@ export async function writePdf(
} else {
throw new Error('Invalid content type for writePdf. Expected string (markdown) or array of operations.');
}
}
}
61 changes: 61 additions & 0 deletions test/test-list-directory-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import assert from 'assert';
import fs from 'fs/promises';
import os from 'os';
import path from 'path';

import { configManager } from '../dist/config-manager.js';
import { listDirectory } from '../dist/tools/filesystem.js';

const TEST_ROOT = path.join(os.tmpdir(), 'desktop-commander-list-directory-errors');

async function setup() {
const originalConfig = await configManager.getConfig();
await fs.mkdir(TEST_ROOT, { recursive: true });
await configManager.setValue('allowedDirectories', [TEST_ROOT]);
return originalConfig;
}

async function teardown(originalConfig) {
await configManager.updateConfig(originalConfig);
await fs.rm(TEST_ROOT, { recursive: true, force: true });
}

async function testMissingDirectoryReturnsNotFound() {
const missingDir = path.join(TEST_ROOT, 'missing-dir');

await assert.rejects(
listDirectory(missingDir, 1),
(error) => {
assert(error instanceof Error);
assert(error.message.includes(`Directory not found: ${missingDir}`));
assert(!error.message.includes('[DENIED]'));
return true;
},
'Missing directories should raise a not-found error instead of returning [DENIED]',
);

console.log('✓ missing directory returns not-found error');
}

export default async function runTests() {
let originalConfig;
try {
originalConfig = await setup();
await testMissingDirectoryReturnsNotFound();
console.log('\n✅ list_directory error tests passed!');
return true;
} catch (error) {
console.error('❌ list_directory error test failed:', error instanceof Error ? error.message : String(error));
return false;
} finally {
if (originalConfig) {
await teardown(originalConfig);
}
}
}

if (import.meta.url === `file://${process.argv[1]}`) {
runTests().then((ok) => {
process.exit(ok ? 0 : 1);
});
}