Skip to content

CliUI: UTF-8-safe Print/PrintLn helpers + full WriteLn sweep - #147

Merged
FMXExpress merged 1 commit into
mainfrom
claude/utf8-console-println
Jun 5, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/utf8-console-println

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

UTF-8-safe console output. Adds PasClaw.CliUI.Print / PrintLn / PrintErr / PrintLnErr helpers and migrates every console-bound Write/WriteLn call site across cmd/*, TUI, and CliUI itself (~24 files, ~460 sites).

Approach is adapted from the UTF8ConsoleDemo WriteConsoleW pattern.

Why

PasClaw already calls SetConsoleOutputCP(CP_UTF8) + SetTextCodePage(Output/ErrOutput) at startup (PasClaw.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 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.
  • UTF-8 bytes via WriteFile when stdout/stderr is redirected to a pipe or file (where WriteConsoleW returns ERROR_INVALID_HANDLE). Byte stream is what less, grep, jq etc. expect.

On FPC any-OS and Delphi non-Windows, the helpers pass through to 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.

Migration shape

Helpers are NOT variadic — they take one string. Pascal's WriteLn('foo: ', x, ' bar') patterns converted to either:

  • string concat: PrintLn('foo: ' + StrVar + ' bar')
  • Format for non-string args: 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 TextFile/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 aren't 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 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, OK
  • make test-openai-server-tools — unchanged, OK
  • Full FPC build clean — no new warnings on touched units
  • Live exercise on Windows: pasclaw status should 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, and MCP/Skills. Agent.pas was 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

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).
@FMXExpress
FMXExpress merged commit bb0bbd5 into main 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).
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