AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

FilesystemClaudeTextEditorMiddleware Uses Locale Encoding Causing Unicode Errors And Data Corruption On Non-UTF-8 Systems

The filesystem middleware reads and writes files using the system's locale encoding instead of UTF-8. On Windows and other non-UTF-8 locales, non-ASCII content such as accents or CJK characters raises UnicodeEncodeError/UnicodeDecodeError or silently writes files in a non-UTF-8 encoding, breaking interoperability and causing tool call failures.

highConfidence 95%LangchainAffected V1.7.2

Origin Analysis

The middleware methods call `Path.read_text()` and `Path.write_text()` without specifying an encoding, so Python uses the locale's default encoding (e.g., cp1252, cp936, or US-ASCII) instead of UTF-8.
1. Set a non-UTF-8 locale (e.g., `LC_ALL=C LANG=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0` on Unix, or use a Windows cp1252/cp936 system). 2. Initialize `FilesystemClaudeTextEditorMiddleware` with a temporary root path. 3. Call `_handle_create` with file_text containing non-ASCII like "# Café ☕". 4. Observe UnicodeEncodeError. 5. Write a UTF-8 file to the root, then call `_handle_view`, `_handle_str_replace`, or `_handle_insert`; observe UnicodeDecodeError or ValueError.

Fixing Code Block

Edge Case Audit

The fix forces UTF-8 for all operations. Existing files written under a different locale encoding (e.g., cp1252) will now fail to decode or may be misread. Consider adding migration/detection logic or accepting an encoding parameter. If a global monkey patch to `Path.read_text`/`Path.write_text` is used instead of patching the middleware directly, it will affect unrelated code and may cause unexpected behavior; revert immediately if other modules rely on locale encoding. Also, on Windows, file handles may need to be closed properly to avoid locking; ensure writes are atomic if concurrency is a concern. Rollback: revert to the original methods (remove the `encoding` argument) or set `PYTHONUTF8=1` at runtime as a temporary workaround.

Ecosystem Topology