Skip to content

Fix FPC mojibake at byte-stream boundaries (TagUTF8 codepage retag) - #148

Merged
FMXExpress merged 1 commit into
mainfrom
claude/fpc-utf8-codepage-tag
Jun 5, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/fpc-utf8-codepage-tag

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

TL;DR

PR #147 fixed the wrong layer. The console-output sweep was patching a symptom. The actual mojibake (é → é in TUI and web UI) is upstream: under FPC {$MODE DELPHI}, strings returned by TStringStream(... TEncoding.UTF8).DataString, Indy response reads, and file reads come back with StringCodePage = 0 (system default) even though their bytes are valid UTF-8. Anything that downstream calls TEncoding.UTF8.GetBytes on those strings — gateway response writer, SSE streamer, file writes, memory log — interprets the bytes as the system codepage (CP1252 on Windows) and re-encodes to UTF-8. Double-encode → mojibake.

That's why the same corruption showed up in both the TUI and the web UI: the output layer wasn't the source. Both paths were consuming already-corrupted bytes.

Direct probe

Bytes := TBytes.Create($63, $61, $66, $C3, $A9);   { "café" UTF-8 }
S := TStringStream.Create('', TEncoding.UTF8);
S.WriteBuffer(Bytes[0], 5);
Body := S.DataString;
StringCodePage(Body)  =>  0   { not 65001 }

The bytes are correct, the tag is wrong. Subsequent TEncoding.UTF8.GetBytes(Body) treats C3 A9 as CP1252 (é) and re-encodes as 4 UTF-8 bytes. That's the bug.

Fix

One-line in-place retag at every boundary where external bytes enter:

procedure TagUTF8(var S: string); inline;
begin
  if S = '' then Exit;
  {$IFDEF FPC}
  SetCodePage(RawByteString(S), CP_UTF8, False);  { no convert — bytes unchanged }
  {$ENDIF}
end;

No-op on Delphi proper (string = UnicodeString, codepages don't apply). On FPC mode delphi, retags the AnsiString in place without touching the underlying bytes.

Boundaries retagged

  • PasClaw.Providers.HTTP — every Result.Body := Resp.DataString site in PostJSON / PutJSON / GetJSONURL / GetURL / PostRaw / DoRequest, including exception-handler bodies that surface server error text.
  • PasClaw.Utils.ReadFileText — bytes read from disk via TEncoding.UTF8.GetString come back CP_0; retag at the boundary.
  • PasClaw.Utils.WriteFileText — retag input before TEncoding.UTF8.GetBytes to disk.
  • PasClaw.Memory.WriteLine — session log writes.
  • PasClaw.Gateway.Server.WriteBodyStream — defence-in-depth on the HTTP-response writer.
  • PasClaw.Gateway.Server.TSSEStreamer.WriteRaw — same, for the SSE chunked-transfer path that bypasses WriteBodyStream.

What's NOT touched

Source-literal path — non-ASCII string literals in .pas files (e.g. ✓ in Cmd.Model) get the correct tag from the file's UTF-8 BOM / lack-of-codepage-directive interaction, which appears to be working in practice. If a regression surfaces, the targeted fix is {$CODEPAGE UTF8} at the top of the affected unit, not a global sweep.

Test plan

New file: src/tests/utf8_codepage_tag_tests.pas

  • TestTagOnDataString — reproduces the exact failing path (TStringStream + TEncoding.UTF8 → DataString → assign); asserts StringCodePage = 0 before, CP_UTF8 after.
  • TestRoundTripThroughEncoding — the smoking gun: tagged string round-trips through TEncoding.UTF8.GetBytes losslessly. Before this fix, this assertion would fail with double-encoded bytes.
  • TestEmptyStringNoOp — TagUTF8('') is safe.
  • make test-anthropic-server-tools / make test-openai-server-tools / make test-println-helper — all unchanged, OK.
  • make smoke — all 11 commands pass.
  • Live exercise on Windows: hit a Claude model with a French/Cyrillic/CJK prompt and confirm the response renders correctly in both pasclaw tui and the gateway web UI (this is the one we can't automate; needs a Windows box with cmd.exe + a browser).

Note on PR #147

The output-layer helpers from #147 (Print / PrintLn / WriteConsoleW fallback) are independently correct on Windows + Delphi — that path's RTL codepage trap is real. But the mojibake the user was seeing wasn't coming from that layer; it was coming from this one. Keeping #147 as a defence-in-depth measure for output is fine; this PR fixes the actual upstream source.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

PR #147 fixed the wrong layer. The console-output sweep was patching
a symptom — the bug is that strings produced by TStringStream(...
TEncoding.UTF8).DataString, Indy response reads, and file reads come
back tagged StringCodePage=0 (system default) even though their
bytes are valid UTF-8. Downstream code that calls TEncoding.UTF8.GetBytes
on those strings (gateway response writer, SSE streamer, file
writes, memory log) interprets the bytes as the system codepage
(CP1252 on Windows) and re-encodes them to UTF-8 — classic double-
encoding: `é` (UTF-8 `C3 A9`) becomes `é` (`C3 83 C2 A9`) on the
wire. That's why the same mojibake showed up in the TUI and the web
UI — the output layer wasn't the source, both paths consumed
already-corrupted bytes.

Direct probe under FPC 3.2.2 + mode delphi:

    Bytes := TBytes.Create($63, $61, $66, $C3, $A9);  { "café" UTF-8 }
    S := TStringStream.Create('', TEncoding.UTF8);
    S.WriteBuffer(Bytes[0], 5);
    Body := S.DataString;
    StringCodePage(Body)  =>  0   { not 65001 }

The string's bytes are correct, but the tag is wrong. Subsequent
TEncoding.UTF8.GetBytes(Body) treats `C3 A9` as CP_1252 (`é`) and
re-encodes as 4 UTF-8 bytes. That's the mojibake.

Fix is a one-line in-place retag at every boundary where external
bytes enter:

    procedure TagUTF8(var S: string); inline;
    begin
      if S = '' then Exit;
      {$IFDEF FPC}
      SetCodePage(RawByteString(S), CP_UTF8, False);  { no convert }
      {$ENDIF}
    end;

No-op on Delphi proper (string = UnicodeString, codepages don't
apply). On FPC mode delphi, retags the AnsiString in place without
touching the underlying bytes — so anything that was already UTF-8
stays exactly UTF-8 on the wire after this fix.

Boundaries retagged (where TagUTF8 is called):

  - PasClaw.Providers.HTTP — every Result.Body := Resp.DataString
    site in PostJSON / PutJSON / GetJSONURL / GetURL / PostRaw /
    DoRequest, including the exception-handler bodies that surface
    error text from the server.
  - PasClaw.Utils.ReadFileText — bytes read from disk via
    TEncoding.UTF8.GetString come back CP_0; retag at the boundary.
  - PasClaw.Utils.WriteFileText — input string retagged before
    TEncoding.UTF8.GetBytes to disk.
  - PasClaw.Memory.WriteLine — session log writes.
  - PasClaw.Gateway.Server.WriteBodyStream — defence-in-depth on
    the HTTP-response writer.
  - PasClaw.Gateway.Server.TSSEStreamer.WriteRaw — same, for the
    SSE chunked-transfer path that bypasses WriteBodyStream.

Doesn't touch the source-literal path; non-ASCII string literals
in our .pas files (e.g. ✓ in Cmd.Model, é/è in CliUI banner if
any) get the correct tag from the file's UTF-8 BOM / lack-of-
codepage-directive interaction, which is already working in
practice. If a regression surfaces there, the targeted fix is
{$CODEPAGE UTF8} at the top of the affected unit, not a global
sweep.

New test: src/tests/utf8_codepage_tag_tests.pas

  - TestTagOnDataString: reproduces the exact path (TStringStream
    + TEncoding.UTF8 → DataString → assign), asserts StringCodePage=0
    before TagUTF8 and CP_UTF8 after.
  - TestRoundTripThroughEncoding: the smoking gun — tagged string
    round-trips through TEncoding.UTF8.GetBytes losslessly. Before
    the fix this would produce double-encoded bytes; the test would
    fail.
  - TestEmptyStringNoOp: TagUTF8('') is safe.

  make test-utf8-codepage-tag    -> OK
  make test-anthropic-server-tools / -openai-server-tools / -println-helper
                                 -> all OK (unchanged)
  make smoke                      -> all 11 commands pass
@FMXExpress
FMXExpress merged commit 5fdba8c into main Jun 5, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jun 6, 2026
You were right — PRs FMXExpress#147 and FMXExpress#148 fixed adjacent symptoms, not the
banner. The PASCLAW box-drawing banner lives in a single file
(PasClaw.CliUI.pas) and doesn't touch HTTP, JSON, or LLM responses,
so the mojibake there points at compile-time source-file encoding,
not runtime output.

Without `{$CODEPAGE UTF8}`, FPC reads the source bytes in the system
default codepage. On Linux that's UTF-8 (works by accident — the
literal stores the raw UTF-8 bytes as CP_0-tagged AnsiString and the
terminal interprets them as UTF-8). On Windows the system codepage
is CP1252; each byte of `█` (`E2 96 88`) becomes a separate AnsiChar
tagged CP1252, and at output time the runtime transcodes CP1252 ->
UTF-8, double-encoding every glyph. Classic banner mojibake.

`{$CODEPAGE UTF8}` tells FPC: the bytes in this file ARE UTF-8.
Literals are stored verbatim and tagged CP_UTF8. Output transcodes
CP_UTF8 -> CP_UTF8 = nothing, so the bytes that arrive at the
terminal are exactly the bytes in the source. Delphi modern (XE+)
accepts the same directive.

Only CliUI gets the directive because only CliUI has non-ASCII
string literals that flow through `PrintLn`. If more non-ASCII
glyphs migrate into other surfaces (Onboard ✓, Vault search panel
chars), the directive should land there too.

Build verification (Linux + FPC 3.2.2):
  make                              -> 1 note, 0 warnings on CliUI
  banner-byte dump                  -> e2 96 88 e2 96 88 ... (correct UTF-8
                                       for ██ — unchanged from before,
                                       confirming Linux didn't regress)
  make smoke                        -> all 11 commands OK

`{$WARN IMPLICIT_STRING_CAST OFF}` + `_LOSS OFF` silence 17 false-
positive FPC warnings the directive introduces on
`PrintLn(Ansi.BoldBlue + L1 + Ansi.Reset)` — `Ansi.*` fields are
AnsiString CP_0, the L1 literal is now AnsiString CP_UTF8, FPC
promotes to UnicodeString to concat, then back to AnsiString for the
parameter. Bytes are correct throughout; the warnings are noise.

Live-verify-on-Windows still required (no CI for that path).
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