Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 31 additions & 8 deletions src/tools/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,32 @@ export async function listDirectory(dirPath: string, depth: number = 2): Promise
const results: string[] = [];

const MAX_NESTED_ITEMS = 100; // Maximum items to show per nested directory
const isAccessDeniedError = (err: NodeJS.ErrnoException) =>
err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'ETIMEDOUT';

const getDisplayPath = (targetPath: string): string => path.basename(targetPath) || targetPath;

function addDeniedEntry(displayPath: string): void {
// Keep the payload path-only so the UI can parse denied entries reliably.
results.push(`[DENIED] ${displayPath}`);
}

try {
const stats = await fs.stat(validPath);
if (!stats.isDirectory()) {
throw new Error(`Directory not found: ${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.
}
if (isAccessDeniedError(err)) {
addDeniedEntry(getDisplayPath(validPath));
return results;
}
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,14 +711,11 @@ 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;
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.
if (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'ETIMEDOUT') {
results.push(`[DENIED] ${displayPath} — not accessible (permission denied, cloud-only file, or Full Disk Access not granted)`);
} else {
results.push(`[DENIED] ${displayPath}`);
if (isTopLevel && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
throw new Error(`Directory not found: ${dirPath}`);
}
const displayPath = relativePath || getDisplayPath(currentPath);
addDeniedEntry(displayPath);
return;
}

Expand Down Expand Up @@ -1010,4 +1033,4 @@ export async function writePdf(
} else {
throw new Error('Invalid content type for writePdf. Expected string (markdown) or array of operations.');
}
}
}
106 changes: 106 additions & 0 deletions test/test-list-directory-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import assert from 'assert';
import fs from 'fs/promises';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';

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

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

async function setup() {
const originalConfig = await configManager.getConfig();
const testRoot = await fs.realpath(await fs.mkdtemp(TEST_ROOT_PREFIX));
await configManager.setValue('allowedDirectories', [testRoot]);
return { originalConfig, testRoot };
}

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

async function testMissingDirectoryReturnsNotFound(testRoot) {
const missingDir = path.join(testRoot, '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');
}

async function testTopLevelStatAccessDeniedReturnsDeniedEntry(testRoot) {
const deniedDir = path.join(testRoot, 'stat-denied');
await fs.mkdir(deniedDir);

const originalStat = fs.stat;
fs.stat = async (target, ...args) => {
if (path.resolve(String(target)) === deniedDir) {
const error = new Error(`EACCES: permission denied, stat '${deniedDir}'`);
error.code = 'EACCES';
throw error;
}
return originalStat.call(fs, target, ...args);
};

try {
const entries = await listDirectory(deniedDir, 1);
assert.deepStrictEqual(entries, ['[DENIED] stat-denied']);
console.log('✓ top-level stat access error returns denied entry');
} finally {
fs.stat = originalStat;
}
}

async function testFilePathReturnsNotFound(testRoot) {
const filePath = path.join(testRoot, 'not-a-directory.txt');
await fs.writeFile(filePath, 'not a directory');

await assert.rejects(
listDirectory(filePath, 1),
(error) => {
assert(error instanceof Error);
assert(error.message.includes(`Directory not found: ${filePath}`));
assert(!error.message.includes('Path is not a directory'));
return true;
},
'File paths should use the same not-found contract as missing directories',
);

console.log('✓ file path returns not-found error');
}

export default async function runTests() {
let originalConfig;
let testRoot;
try {
({ originalConfig, testRoot } = await setup());
await testMissingDirectoryReturnsNotFound(testRoot);
await testTopLevelStatAccessDeniedReturnsDeniedEntry(testRoot);
await testFilePathReturnsNotFound(testRoot);
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 && testRoot) {
await teardown(originalConfig, testRoot);
}
}
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
runTests().then((ok) => {
process.exit(ok ? 0 : 1);
});
}