Repository navigation
TUI: sort sessions newest-first + render assistant chat as markdown - #182
Conversation
Two TUI papercuts. Both pieces use machinery already in the codebase -- just wires them into the positioned-TUI surface. Session ordering (TUI session pane + `pasclaw session list`): ListSessions used to return whatever order FindFirst yielded (usually inode order, sometimes alphabetical, never useful). Sort newest-first by Meta.UpdatedAt with Meta.CreatedAt and Meta.Id as deterministic tiebreakers -- the freshest session lands at index 0, which is almost always the one the operator wants to resume. Insertion sort over a dozens-of-sessions list; zero perf concern. The sort lives inside ListSessions itself so the TUI pane and the CLI list see the same order without each having to opt in. Markdown rendering in the TUI chat pane: Cfg.RenderMarkdown was respected by the agent CLI (Cmd.Agent.MaybeRender) and by the TUI's FPC line-based branch, but the Delphi positioned-TUI's RenderMsgLines piped raw content into the chat pane verbatim -- so the model's *bold*, # headings, and triple-backtick code blocks reached the operator as literal pipes and hashes. Threaded Self.RenderMarkdownEnabled into RenderMsgLines (new parameter, caller in DrawChatPane forwards it) and ran the body through PasClaw.Markdown.Render.RenderMarkdown when the role is mrAssistant and rendering is on. User / system / tool messages stay verbatim -- user input is the operator's literal text, system / tool content is structured payload (JSON, hashline, shell stdout) that would mangle under markdown rules. Test: TestSortNewestFirst pins the primary key + both tiebreakers in working_state_tests.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2e63249131
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if RenderMd and (Msg.Role = mrAssistant) and (Trim(Body) <> '') then | ||
| Body := RenderMarkdown(Body); |
There was a problem hiding this comment.
Strip ANSI before measuring chat pane width
When markdown rendering is enabled and an assistant message contains styled markdown such as **bold** or a heading, RenderMarkdown injects ANSI escape sequences into Body before this function wraps it. DrawChatPane later pads/truncates these strings with Length(Line), so the escape bytes are counted as visible cells: styled rows are under-padded and can leave stale characters on the right edge, and longer formatted lines can be split in the middle of an escape sequence. The positioned TUI needs ANSI-aware width/slicing here, or markdown should be rendered without embedded ANSI before the pane layout pass.
Useful? React with 👍 / 👎.
When RenderMarkdown is enabled, assistant messages flow through
the markdown renderer which injects ANSI escape sequences (CSI
m for color, bright, italic, etc.). The wrap code in
RenderMsgLines and the pad/truncate in DrawChatPane both used
plain Length(), counting those escape bytes as visible cells.
Two visible bugs:
- Styled rows under-padded -- the row had 80 bytes but only,
say, 74 visible columns, leaving 6 cells of stale content
bleeding from the previous frame on the right edge.
- Longer wrapped rows split in the middle of an escape
sequence -- '\x1b[1m' becomes '\x1b[' on one row and '1m'
on the next, painting garbage and (worse) carrying the
open style into subsequent rows.
Fix in two parts. PasClaw.Utils gets two new public helpers
sitting next to VisibleLength:
- PadVisibleRight(S, W) -- pad to W visible columns, ANSI
contributes zero.
- TruncateVisible(S, MaxVis, out Remainder) -- carve a
visible-width-bounded prefix while keeping CSI sequences
intact, append a closing reset when any escape opened so
the prefix is self-contained.
RenderMsgLines uses VisibleLength for the wrap decision and
iterates TruncateVisible over the line for ANSI-aware wrap.
DrawChatPane uses VisibleLength for the >W test and
PadVisibleRight for the final pad. The wrap-loop temporaries are
kept distinct (WrapRest + NextRest) -- aliasing one variable as
both `const S` and `out Remainder` would let the implementation
zero the input via Remainder := '' before reading a single byte.
Tests: ansi_width_tests pins VisibleLength's ANSI skip,
PadVisibleRight's zero-width ANSI counting, TruncateVisible's
CSI preservation + plain-text path + iterated wrap.
dcc64 errors after PR FMXExpress#182: PasClaw.TUI.pas(1597): E2003 Undeclared identifier: 'VisibleLength' PasClaw.TUI.pas(1611): E2003 Undeclared identifier: 'TruncateVisible' PasClaw.TUI.pas(1685): E2003 Undeclared identifier: 'VisibleLength' PasClaw.TUI.pas(1686): E2003 Undeclared identifier: 'TruncateVisible' PasClaw.TUI.pas(1687): E2003 Undeclared identifier: 'PadVisibleRight' PR FMXExpress#182's Codex P2 fix added calls to the three new ANSI-aware helpers but never added PasClaw.Utils to the TUI's uses clause. FPC happened to resolve the symbols via a transitive impl-uses chain (PasClaw.CliUI's implementation uses PasClaw.Utils) which mode delphi tolerates; dcc64 requires the explicit import. One-line fix: add PasClaw.Utils to the TUI's implementation uses block right next to PasClaw.CliUI. No behavior change.
Two user-reported bugs against PR FMXExpress#182's newest-first session sort, both in the TUI start/navigate path: Bug A -- sort drift when picking older sessions SelectSession used to call PersistSession on the outgoing session "to flush anything pending before the swap." But by the time you get there, every meaningful state change has already been persisted: PollLoopWorker's ApplyLoopResultTo saves after each turn, ApplyModelSelection saves after /model, and so on. Pure navigation had nothing to save -- but PersistSession's unconditional FSession.Touch bumped Meta.UpdatedAt anyway, so peeking at an older session re-promoted the one you LEFT to the top of the newest-first list. Dropped the Persist call. Added a comment explaining what's already persisted at each entry point so a future hand doesn't re-add it on the theory it might miss something. Bug B -- TUI launches with empty chat, mismatched highlight With no --session argument, the left pane highlighted the newest session but the chat pane was blank. TSession.Create('') auto- allocates a brand-new session id, so FSession pointed at a fresh empty in-memory record while FSelSessIdx tracked the newest persisted session at index 0. SessionId resolution in TTUI.Run now does: empty + sessions on disk -> resume the newest by UpdatedAt; empty + no sessions on disk -> fresh id (original PR FMXExpress#117 behavior); non-empty -> honour as-is. Pressing N still spawns a fresh session via StartNewSession -> SelectSession('').
Summary
Two TUI papercuts. Both pieces reuse machinery already in the codebase — just wire it into the positioned-TUI surface.
Session ordering — newest-at-top
ListSessionsused to return whatever orderFindFirsthappened to yield (usually inode-order, sometimes alphabetical, never useful for an operator who just wants to resume the conversation they were in five minutes ago). Now it sorts in place before returning:Meta.UpdatedAtdescending — the freshest session lands at index 0.Meta.CreatedAtdesc, thenMeta.Iddesc — deterministic even when several sessions saved in the same second (the cron-side mass-spawn case).Generics.Defaultsimport.The sort lives inside
ListSessionsitself, so both the TUI session pane (RefreshSessions) and the CLIpasclaw session listsee freshest-at-top without either having to opt in. New publicSortSessionsNewestFirsthelper for testability.Markdown in TUI chat pane
Cfg.RenderMarkdownwas honored by the agent CLI (Cmd.Agent.MaybeRender) and by the TUI's FPC line-based branch (HandleUserInput), but the Delphi positioned-TUI'sRenderMsgLinespiped rawMsg.Contentstraight into the chat pane — so the model's**bold**,# headings, and triple-backtick code blocks reached the operator as literal asterisks, pipes, and hashes.Now
RenderMsgLinestakes aRenderMd: Booleanparameter (forwarded fromSelf.RenderMarkdownEnabledinDrawChatPane). When True and the role ismrAssistant, the body flows throughPasClaw.Markdown.Render.RenderMarkdown— same pipeline the agent CLI uses, just routed into the positioned chat pane. User / system / tool messages stay verbatim — user input is the operator's literal text, system / tool content is structured payload (JSON, hashline patches, shell stdout) that would mangle under markdown rules.PasClaw.Markdown.Renderwas already in the TUI's implementation uses, andRenderMarkdownEnabledwas already wired in byCmd_TUI_Run. Net effect: the existing toggle now actually does something in the Delphi build.Tests
TestSortNewestFirstinworking_state_testscovers the primary key + both tiebreakers (UpdatedAt-tie broken by CreatedAt; same Updated+Created broken by Id). The markdown path piggybacks on the existingmarkdown_render_testsfor the renderer itself; the wiring is shallow enough that a build + smoke test is sufficient.Test plan
makerebuilds cleanly (FPC, mode delphi)make test— all 12 suites green (smoke + 10 existing + working_state_tests with the newTestSortNewestFirst)pasclaw tuiagainst a workspace with several sessions — confirm session pane shows newest at the top, selection follows when a stale session updates.pasclaw session list— same ordering at the CLI.pasclaw tui— confirm the rendered output shows ANSI-styled headings / code blocks instead of literal asterisks and hashes.pasclaw tui --no-render-markdown(orrender_markdown: falsein config) — confirm raw markdown passes through verbatim.Generated by Claude Code