Skip to content

fix(server): handle permission-denied directories gracefully - #856

Merged
unhappychoice merged 3 commits into
unhappychoice:mainfrom
yangching2:fix/handle-inaccessible-directories
Jul 25, 2026
Merged

unhappychoice merged 3 commits into
unhappychoice:mainfrom
yangching2:fix/handle-inaccessible-directories

Conversation

@yangching2

@yangching2 yangching2 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a crash where running npx mdts in a folder that contains a sub-directory the process can't read made the whole tree view unusable (Error: EACCES: permission denied, scandir ...). Inaccessible directories are now skipped gracefully — in both the file-tree API and the livereload watcher — with a single friendly log line, and no scary error/stack trace.

Problem

When mdts is started (zero-config, no --glob) inside a directory tree that has an unreadable sub-folder, two things break:

  1. The file tree never loads. GET /api/filetree returns HTTP 500. getFileTree calls fs.readdirSync recursively with no error handling; the first unreadable sub-directory throws EACCES, the async Express 5 handler rejects, and with no error handler registered the default 500 is returned. The frontend's tree panel is left blank — the app appears completely broken.
  2. The console spews a scary error. chokidar's livereload watcher hits EACCES on the same directory and the error handler prints the raw error with a full stack trace, then tears down the entire watcher and disables livereload — even though a single unreadable path is non-fatal.

There was no simple workaround: no --exclude flag exists, EXCLUDED_DIRECTORIES is hardcoded, and --glob only helps if the user already knows and lists every markdown path.

Root cause

  • src/server/routes/filetree.ts — getFileTree used fs.readdirSync(...) with no try/catch.
  • src/server/watcher.ts — the chokidar error handler treated every error as fatal. Per chokidar's own _handleError, EACCES/EPERM on one path is non-fatal: that path simply isn't watched while the rest continue.

Changes

1. File tree — skip unreadable directories (getFileTree)

Wrapped readdirSync in a try/catch. The "can't enumerate this directory" error family (EACCES, EPERM, plus the ENOENT/ENOTDIR races where an entry vanishes mid-scan) logs a skip and returns an empty sub-tree so the rest renders:

 Server   🔒 Skipping inaccessible directory: compose/data/timescale

Unexpected errors still propagate (still a 500), so genuine failures aren't hidden.

2. Livereload — keep watching on permission errors

Both watchers (directory and file-pattern) now detect permission errors, log one friendly line, and leave the watcher running:

 Livereload   🔒 Can't watch "compose/data/timescale" (permission denied); live-reload skipped for it, others still watched.

Genuinely fatal errors keep the existing teardown + guidance (e.g. the EMFILE hint).

Before After
GET /api/filetree HTTP 500, blank tree HTTP 200, full tree (minus unreadable dirs)
Console on unreadable dir red 🚫 Error ... + stack trace + "Livereload will be disabled" one 🔒 ... info line
Livereload disabled globally continues for all readable paths

Verification

Tested by launching against a real folder containing an unreadable sub-directory (compose/data/timescale → Permission denied):

node dist/index.js /path/to/folder -H 0.0.0.0 -p 8531 --no-open
  • ✅ GET /api/filetree → HTTP 200; tree renders all top-level entries; timescale absent, rest intact
  • ✅ Skip log fired for the unreadable directory
  • ✅ Console clean — no error / 🚫 / stack trace / "disabled" lines
  • ✅ Watcher not torn down (no "Directory watcher closed"); livereload still active for readable files
  • ✅ npm test — 123 passed (13 suites), incl. new regression tests
  • ✅ npm run lint — clean (30 files)

New tests

  • test/unit/server/routes/filetree.test.ts — readdirSync throws EACCES → endpoint returns 200 with the rest of the tree.
  • test/unit/server/watcher.test.ts — EACCES error event → friendly log, no close/unwatch, no logger.error (for both directory and file-pattern watchers).

Notes

  • No CLI changes — zero-config npx mdts continues to "just work".
  • No breaking changes; only previously-fatal permission paths are now non-fatal.
  • Touched only the default (non-glob) file-tree path; the --glob path already avoided readdirSync.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • File tree responses now continue when encountering inaccessible directories, skipping only those subtrees while keeping available readable files.
    • Live reload now ignores permission-denied watcher targets instead of disabling live reload for the whole setup.
    • Permission-denied cases produce clearer, target-specific “skipped due to permission” messages rather than generic interruption.
  • Tests
    • Added unit tests for file tree handling of unreadable directories and watcher behavior on EACCES permission errors.
    • Added unit tests for new error classification helpers used by these flows.

yangching2 and others added 2 commits July 24, 2026 21:46
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]>
A permission error (EACCES/EPERM) on a single sub-directory is non-fatal —
chokidar keeps watching everything else — but the watcher's error handler
treated it as fatal: it tore down the whole watcher, disabled livereload,
and printed the raw error with a stack trace.

Detect permission errors, log a single friendly line, and leave the
watcher running. Genuinely fatal errors (e.g. EMFILE) keep the existing
teardown and guidance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@netlify

netlify Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for mdts-unhappychoice ready!

Name Link
🔨 Latest commit 7e33313
🔍 Latest deploy log https://app.netlify.com/projects/mdts-unhappychoice/deploys/6a64c3afb188810008641fb8
😎 Deploy Preview https://deploy-preview-856--mdts-unhappychoice.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d9b19972-2ae0-4f25-996d-56d6467a8097

📥 Commits

Reviewing files that changed from the base of the PR and between 1953b77 and 7e33313.

📒 Files selected for processing (4)
  • src/server/routes/filetree.ts
  • src/server/watcher.ts
  • src/utils/errors.ts
  • test/unit/utils/errors.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server/watcher.ts

📝 Walkthrough

Walkthrough

The file tree now skips inaccessible directories while preserving readable entries. Directory and file-pattern watchers treat permission-denied errors as non-fatal, logging affected paths without closing watchers or disabling live reload. Shared error predicates and unit tests support these behaviors.

Changes

Filesystem resilience

Layer / File(s) Summary
Classify filesystem errors
src/utils/errors.ts, test/unit/utils/errors.test.ts
Shared predicates classify permission-related and unreadable-directory errno codes, with tests covering valid, invalid, and non-error inputs.
Skip unreadable directories
src/server/routes/filetree.ts, test/unit/server/routes/filetree.test.ts
Unreadable directory errors are logged and produce empty subtrees, while other errors are re-thrown. Tests verify accessible files and expected response metadata remain available.
Preserve watchers after permission errors
src/server/watcher.ts, test/unit/server/watcher.test.ts
Directory and file-pattern watchers log permission-denied paths and remain active; tests verify no teardown or error logging occurs for these cases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: unhappychoice

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: handling permission-denied directories gracefully in server code.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/unit/server/watcher.test.ts (1)

273-291: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test EPERM as well as EACCES.

Both watcher tests cover only EACCES, although production treats EPERM equivalently. Parameterize each case over both permission-denied codes so either handler cannot regress to supporting only one.

Also applies to: 426-449

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit/server/watcher.test.ts` around lines 273 - 291, Update the
permission-error watcher tests, including the case near the referenced secondary
range, to parameterize each test over both EACCES and EPERM. Ensure each
generated error uses the current permission code while preserving the existing
non-fatal assertions and expected logging behavior.
test/unit/server/routes/filetree.test.ts (1)

78-97: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the complete filesystem-error contract.

This test only exercises EACCES; it does not verify the other supported codes, the skip log, or that unexpected errors still propagate. Add parameterized cases for EACCES, EPERM, ENOENT, and ENOTDIR, plus an EIO case that remains an error.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit/server/routes/filetree.test.ts` around lines 78 - 97, Expand the
file-tree error-handling tests around the existing inaccessible-directory case
with parameterized skip cases for EACCES, EPERM, ENOENT, and ENOTDIR, asserting
the readable file remains returned and the skip log is emitted. Add an EIO case
asserting the request still fails and the unexpected error propagates.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server/watcher.ts`:
- Around line 81-87: Update describeWatchTarget to use path.win32 for
Windows-aware relative-path handling: determine whether errorPath is absolute,
compute its relation to directory with path.win32.relative, and use
path.win32.sep rather than hard-coded “/” separators. Preserve the fallback for
non-string paths and ensure relative targets are logged while unrelated paths
remain unchanged.

---

Nitpick comments:
In `@test/unit/server/routes/filetree.test.ts`:
- Around line 78-97: Expand the file-tree error-handling tests around the
existing inaccessible-directory case with parameterized skip cases for EACCES,
EPERM, ENOENT, and ENOTDIR, asserting the readable file remains returned and the
skip log is emitted. Add an EIO case asserting the request still fails and the
unexpected error propagates.

In `@test/unit/server/watcher.test.ts`:
- Around line 273-291: Update the permission-error watcher tests, including the
case near the referenced secondary range, to parameterize each test over both
EACCES and EPERM. Ensure each generated error uses the current permission code
while preserving the existing non-fatal assertions and expected logging
behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b54ce9df-d32c-4d46-9d2f-fc4178650d6c

📥 Commits

Reviewing files that changed from the base of the PR and between 0a2193f and 1953b77.

📒 Files selected for processing (4)
  • src/server/routes/filetree.ts
  • src/server/watcher.ts
  • test/unit/server/routes/filetree.test.ts
  • test/unit/server/watcher.test.ts

Comment thread src/server/watcher.ts
Comment on lines +81 to +87
const describeWatchTarget = (error: unknown, directory: string): string => {
const errorPath = (error as NodeJS.ErrnoException)?.path;
if (typeof errorPath !== 'string') return 'a path';
return errorPath.startsWith(`${directory}/`)
? errorPath.slice(directory.length + 1)
: errorPath;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file around watcher.ts =="
if [ -f src/server/watcher.ts ]; then
  sed -n '1,140p' src/server/watcher.ts | nl -ba
else
  echo "src/server/watcher.ts not found"
fi

echo
echo "== Node path behavior for POSIX and win32 =="
node - <<'JS'
const path = require('path');

function describeWatchTarget(errorPath, directory) {
  if (typeof errorPath !== 'string') return 'a path';
  return errorPath.startsWith(`${directory}/`)
    ? errorPath.slice(directory.length + 1)
    : errorPath;
}

const cases = [
  {
    message: 'Linux-style absolute inside',
    errorPath: '/home/app/logs/foo.log',
    directory: '/home/app/logs'
  },
  {
    message: 'Windows-style absolute inside unquoted win32',
    errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
    directory: 'C:\\Users\\AppData\\Local\\Logs'
  },
  {
    message: 'Windows-style absolute inside with path.win32.relative',
    errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
    directory: 'C:\\Users\\AppData\\Local\\Logs',
    win32: true
  }
];

for (const c of cases) {
  if (c.win32) {
    const relativePath = path.win32.relative(c.directory, c.errorPath);
    const isInsideDirectory =
      relativePath !== '..' &&
      !relativePath.startsWith(`..${path.win32.sep}`) &&
      !path.win32.isAbsolute(relativePath);
    console.log(`${c.message}`);
    console.log(`  startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);
    console.log(`  path.win32.relative approach: ${isInsideDirectory && relativePath ? relativePath : c.errorPath}`);
    console.log(`  separators in path: "${c.errorPath}" contains \\? ${c.errorPath.includes('\\')}`);
  } else {
    console.log(`${c.message}`);
    console.log(`  startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);
  }
}
JS

Repository: unhappychoice/mdts

Length of output: 225


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file around watcher.ts =="
if [ -f src/server/watcher.ts ]; then
  sed -n '1,140p' src/server/watcher.ts | awk '{printf "%5d\t%s\n", NR, $0}'
else
  echo "src/server/watcher.ts not found"
fi

echo
echo "== package typescript availability =="
node - <<'JS'
try {
  console.log(require.resolve('typescript'));
} catch (e) {
  console.log('typescript not resolved');
}
JS

echo
echo "== Node path behavior for POSIX and win32 separators =="
node - <<'JS'
const path = require('path');

function describeWatchTarget(errorPath, directory) {
  if (typeof errorPath !== 'string') return 'a path';
  return errorPath.startsWith(`${directory}/`)
    ? errorPath.slice(directory.length + 1)
    : errorPath;
}

const cases = [
  {
    message: 'Linux-style absolute inside',
    errorPath: '/home/app/logs/foo.log',
    directory: '/home/app/logs'
  },
  {
    message: 'Windows-style absolute inside',
    errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
    directory: 'C:\\Users\\AppData\\Local\\Logs'
  }
];

for (const c of cases) {
  console.log(`${c.message}`);
  console.log(`  current startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);

  const relativePath = path.win32.relative(c.directory, c.errorPath);
  const isInsideDirectory =
    relativePath !== '..' &&
    !relativePath.startsWith(`..${path.win32.sep}`) &&
    !path.win32.isAbsolute(relativePath);
  console.log(`  path.win32.relative approach: ${isInsideDirectory && relativePath ? relativePath : c.errorPath}`);
  console.log(`  path input contains backslash: ${c.errorPath.includes('\\')}`);
}
JS

Repository: unhappychoice/mdts

Length of output: 6368


Use path.win32 handling for the logged watch target.

describeWatchTarget currently uses / concatenation and a POSIX prefix check, so Windows error paths like C:\Users\...\foo.log are logged as the full absolute path instead of the relative target. Use path.win32 for relative, isAbsolute, and sep while remaining compatible in Node.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/watcher.ts` around lines 81 - 87, Update describeWatchTarget to
use path.win32 for Windows-aware relative-path handling: determine whether
errorPath is absolute, compute its relation to directory with
path.win32.relative, and use path.win32.sep rather than hard-coded “/”
separators. Preserve the fallback for non-string paths and ensure relative
targets are logged while unrelated paths remain unchanged.

Deduplicate the permission-error handling introduced for inaccessible
directories:

- Move the near-identical `isUnreadableDirectoryError` (filetree) and
  `isPermissionError` (watcher) predicates into `src/utils/errors.ts`,
  built on a shared `hasErrnoCode` helper.
- Extract the copy-pasted permission branch of both chokidar `error`
  handlers into `logSkippedWatchTarget`.
- Add unit tests for the new helpers.

No behavior change.

Co-Authored-By: Claude Opus 5 <[email protected]>

@unhappychoice unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for the fix, and for the detailed write-up. I reproduced the problem and the fix locally (a chmod 000 sub-directory under the mounted folder): GET /api/filetree returns 200 with the readable part of the tree, the skip line is logged, and the watcher stays alive. npm test (123 passed) and npm run lint are green on your branch. The approach looks right to me: permission errors are non-fatal, unexpected errors still propagate.

I pushed one refactor commit on top of your branch (7e33313) rather than asking you to round-trip on it:

  • isUnreadableDirectoryError (filetree.ts) and isPermissionError (watcher.ts) were the same predicate with different code lists, so both now live in a new src/utils/errors.ts on top of a shared hasErrnoCode helper.
  • The permission branch of the chokidar error handler was copy-pasted into both setupDirectoryWatcher and setupFilePatternWatcher, so it is now a single logSkippedWatchTarget.
  • Added unit tests for the new helpers.

No behavior change, and your tests still pass (138 passed / 14 suites after the added ones).

A few remaining points, none blocking:

  1. chokidar has a built-in ignorePermissionErrors option. In v4 _handleError skips emitting error entirely for EPERM/EACCES when it is set, so the watcher half of this PR could be a one-line option instead of a handler branch. The trade-off is that the option is silent while your version logs a friendly line, which is arguably the better UX. Did you consider it? If the log line is the point, the current code is fine as is, but it is worth a comment in the code saying so.

  2. The skip line is logged on every /api/filetree request. Livereload reloads the tree on every file add/remove, so a long session inside a folder with an unreadable directory repeats the line indefinitely. Remembering already-warned paths in a Set and logging once would be quieter.

  3. describeWatchTarget slices on a hardcoded ${directory}/, which does not match on Windows separators and falls back to printing the absolute path. path.relative(directory, errorPath) handles both. Note the existing code at watcher.ts has the same pattern, so this is consistent with what is already there, not a regression.

  4. ENOENT/ENOTDIR in the file-tree skip list: the race rationale makes sense, but the message ("Skipping inaccessible directory" with a lock emoji) reads as a permission problem for what may just be a directory that vanished mid-scan. Slightly different wording would avoid the confusion.

One process note on my side: the lint and test workflows have not run on this PR yet, only the Netlify and CodeRabbit checks. I will approve the workflow run so CI actually verifies it before merge.

@codecov

codecov Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.54839% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.19%. Comparing base (0a2193f) to head (7e33313).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/server/routes/filetree.ts 87.50% 1 Missing ⚠️
src/server/watcher.ts 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #856      +/-   ##
==========================================
- Coverage   99.41%   99.19%   -0.23%     
==========================================
  Files          69       70       +1     
  Lines        1549     1616      +67     
  Branches      371      395      +24     
==========================================
+ Hits         1540     1603      +63     
- Misses          8       12       +4     
  Partials        1        1              
Flag Coverage Δ
frontend 99.27% <ø> (-0.17%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@unhappychoice
unhappychoice merged commit e908e47 into unhappychoice:main Jul 25, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants