Skip to content

[bug] Read and Edit tools handle invalid UTF-8 inconsistently: one crashes, the other silently corrupts #33068

Closed

Description

Description

The Read tool (packages/core/src/tool/read-filesystem.ts) uses
ew TextDecoder("utf-8", { fatal: true }) at both paginated and non-paginated read paths (lines ~131 and ~155). When the first 64KB of a file passes the binary detection check but later content contains invalid UTF-8 sequences (e.g. orphan byte 0x80, truncated multi-byte sequences), decoder.decode() throws a TypeError. This exception is not caught and propagates as an unrecoverable Effect defect.

The Edit tool (packages/core/src/tool/edit.ts, line ~31) uses
ew TextDecoder() WITHOUT { fatal: true }, meaning invalid UTF-8 bytes are silently replaced with U+FFFD replacement characters. When the model provides an oldString containing the correct characters but Edit searches the replaced text, matching fails silently with "Could not find oldString".

Two tools in the same codebase handle invalid UTF-8 differently: one crashes, the other silently corrupts data.

Code location

Steps to reproduce

  1. Create a file whose first 64KB is valid ASCII/UTF-8 but contains orphan byte 0x80 at position ~65000
  2. Call
    ead on this file → TextDecoder crashes with TypeError
  3. Call edit on this file → the invalid byte is silently replaced with U+FFFD, oldString matching fails

Expected behavior

Both tools should handle invalid UTF-8 consistently. Either both use { fatal: true } with proper error handling, or both replace invalid sequences with U+FFFD gracefully.

Environment

OpenCode Desktop 1.17.8, Windows 11

Activity

  1. Necmttn commented on Jun 21, 2026

    @Necmttn

    Read/Edit should have one text-decoding policy. For invalid UTF-8, choose one behavior and surface it explicitly: reject as binary/invalid text with byte offset, or decode lossily with a flag and forbid Edit on lossy content.

    Silent replacement in Edit is dangerous because oldString matching can fail against a different byte sequence than the file actually contains. Tests should cover invalid byte in first chunk, later chunk, truncated multibyte sequence, and binary detection false negatives.


    Generated with ax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions