Repository navigation
CliUI: UTF-8-safe Print/PrintLn helpers + full WriteLn sweep - #147
Merged
Merged
Conversation
Adds PasClaw.CliUI.Print / PrintLn / PrintErr / PrintLnErr and
migrates every console-bound Write/WriteLn call site across cmd/*,
TUI, and CliUI itself (~24 files, ~460 call sites).
Why
---
We already set SetConsoleOutputCP(CP_UTF8) and SetTextCodePage on
Output/ErrOutput at startup (CliUI.EnableUTF8Console). But under
modern Delphi, WriteLn on a console-bound Text file routes through
the per-Text-file codepage cache: UnicodeString -> ANSI CP bytes
-> console. That conversion is the fragile one. Even with the
console CP correctly set to UTF-8, the *Text-file* codepage path
can still ANSI-encode characters before they ever reach the
console, producing mojibake (é -> é, … -> …) and missing
glyphs on default Windows consoles.
The new helpers bypass that path entirely on Windows + Delphi by
calling WriteConsoleW(GetStdHandle(...), PWideChar(S), Length(S),
...) — UTF-16 straight to the renderer, no codepage conversion.
When stdout/stderr is redirected to a pipe or file (where
WriteConsoleW returns ERROR_INVALID_HANDLE), the helpers fall
back to UTF-8 bytes via WriteFile so the byte stream is what
downstream tools (less, grep, jq) expect.
On FPC any-OS and Delphi non-Windows, the helpers just call the
underlying Write(Output, S) / WriteLn(Output, S). FPC's RTL
carries AnsiString as UTF-8 already; POSIX terminals interpret
UTF-8 by default. No bypass needed.
Approach is adapted from the UTF8ConsoleDemo Daniele-Teti style
WriteConsoleW pattern.
Migration shape
---------------
Helpers are NOT variadic — they take one string. Pascal's
WriteLn('foo: ', x, ' bar') patterns convert to either string
concat (PrintLn('foo: ' + StrVar + ' bar')) or Format when the
arg is non-string (PrintLn(Format('count: %d', [N]))). Field-
width specifiers like 'Sessions[i].Id:28' became
Format('%28s', [Sessions[i].Id]) — semantics preserved.
Files NOT touched
-----------------
- WriteLn(SomeTextFile, ...) where target is a file/stream
(config save, log file) — those are correct as-is; the codepage
of the destination file matters there, not the console.
- WriteBuffer / WriteFile / WriteRaw / WriteChunk identifiers —
these are not console output, the sweep only matched bare
WriteLn / Writeln / Write(.
- The Delphi-only branch of PasClaw.TUI.pas — that path already
goes through WriteAnsiText / DMVCFramework's console primitives,
not bare WriteLn.
Test
----
src/tests/println_helper_tests.pas exercises every helper plus a
UTF-8 round-trip line (é è ω 中 ✓). Output captured in test
confirms the bytes are intact when redirected to a file — the
file fallback path is exercised.
make smoke -> all 11 commands OK
make test-println-helper -> OK, UTF-8 round-trip visible
make test-anthropic-server-tools -> OK
make test-openai-server-tools -> OK
Co-developed by 4 parallel migration sub-agents that handled
Membench/Serve/Cron/Status, Session/Update/Steer/Post,
Vault/Onboard/TUI, and MCP/Skills (Agent.pas finished manually
after the agent was interrupted by a stop-hook commit demand).
This was referenced Jun 5, 2026
khongten001
pushed a commit
to khongten001/PasClaw
that referenced
this pull request
Jun 6, 2026
PR FMXExpress#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
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
UTF-8-safe console output. Adds
PasClaw.CliUI.Print/PrintLn/PrintErr/PrintLnErrhelpers and migrates every console-boundWrite/WriteLncall site acrosscmd/*,TUI, andCliUIitself (~24 files, ~460 sites).Approach is adapted from the UTF8ConsoleDemo
WriteConsoleWpattern.Why
PasClaw already calls
SetConsoleOutputCP(CP_UTF8)+SetTextCodePage(Output/ErrOutput)at startup (PasClaw.CliUI.EnableUTF8Console). But under modern Delphi,WriteLnon a console-bound Text file routes through the per-Text-file codepage cache:UnicodeString→ ANSI CP bytes → console. That conversion is the fragile one. Even with the console CP correctly set to UTF-8, the Text-file codepage path can still ANSI-encode characters before they reach the console, producing mojibake (é→é,…→…) and missing glyphs on default Windows consoles.The new helpers bypass that path entirely on Windows + Delphi:
WriteConsoleW(GetStdHandle(...), PWideChar(S), Length(S), ...)when the handle is a real console — UTF-16 straight to the renderer, no codepage conversion.WriteFilewhen stdout/stderr is redirected to a pipe or file (whereWriteConsoleWreturnsERROR_INVALID_HANDLE). Byte stream is whatless,grep,jqetc. expect.On FPC any-OS and Delphi non-Windows, the helpers pass through to
Write(Output, S)/WriteLn(Output, S). FPC's RTL carriesAnsiStringas UTF-8 already; POSIX terminals interpret UTF-8 by default — no bypass needed.Migration shape
Helpers are NOT variadic — they take one
string. Pascal'sWriteLn('foo: ', x, ' bar')patterns converted to either:PrintLn('foo: ' + StrVar + ' bar')Formatfor non-string args:PrintLn(Format('count: %d', [N]))Sessions[i].Id:28becameFormat('%28s', [Sessions[i].Id])— semantics preserved.Files NOT touched
WriteLn(SomeTextFile, ...)where target is aTextFile/stream (config save, log file). Those are correct as-is; the codepage of the destination file matters there, not the console.WriteBuffer/WriteFile/WriteRaw/WriteChunkidentifiers — these aren't console output; the sweep only matched bareWriteLn/Writeln/Write(.PasClaw.TUI.pas— that path already goes throughWriteAnsiText/ DMVCFramework's console primitives, not bareWriteLn.Test plan
make test-println-helper— every helper invoked + UTF-8 round-trip line (é è ω 中 ✓). Confirms bytes are intact when redirected to a file.make smoke— all 11 CLI commands launch cleanly (no compile-time regressions in the touched files)make test-anthropic-server-tools— unchanged, OKmake test-openai-server-tools— unchanged, OKpasclaw statusshould render banner + status panels without mojibake on stock cmd.exe / Windows Terminal (CI doesn't cover this; needs a human with a Windows box)Co-development note
Four parallel migration sub-agents handled
Membench/Serve/Cron/Status,Session/Update/Steer/Post,Vault/Onboard/TUI, andMCP/Skills.Agent.paswas finished manually after the third agent was interrupted by a stop-hook commit demand. The small files (Root, Version, Migrate, Config_, Model, Auth, Gateway, CliUI) were done directly.https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code