Skip to content

TUI: sort sessions newest-first + render assistant chat as markdown - #182

Merged
FMXExpress merged 2 commits into
mainfrom
claude/tui-session-sort-and-markdown
Jun 8, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/tui-session-sort-and-markdown

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

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

ListSessions used to return whatever order FindFirst happened 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:

  • Primary key: Meta.UpdatedAt descending — the freshest session lands at index 0.
  • Tiebreakers: Meta.CreatedAt desc, then Meta.Id desc — deterministic even when several sessions saved in the same second (the cron-side mass-spawn case).
  • Insertion sort. Session count is dozens-to-low-hundreds; O(N²) doesn't matter and avoids a Generics.Defaults import.

The sort lives inside ListSessions itself, so both the TUI session pane (RefreshSessions) and the CLI pasclaw session list see freshest-at-top without either having to opt in. New public SortSessionsNewestFirst helper for testability.

Markdown in TUI chat pane

Cfg.RenderMarkdown was honored by the agent CLI (Cmd.Agent.MaybeRender) and by the TUI's FPC line-based branch (HandleUserInput), but the Delphi positioned-TUI's RenderMsgLines piped raw Msg.Content straight 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 RenderMsgLines takes a RenderMd: Boolean parameter (forwarded from Self.RenderMarkdownEnabled in DrawChatPane). When True and the role is mrAssistant, the body flows through PasClaw.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.Render was already in the TUI's implementation uses, and RenderMarkdownEnabled was already wired in by Cmd_TUI_Run. Net effect: the existing toggle now actually does something in the Delphi build.

Tests

TestSortNewestFirst in working_state_tests covers the primary key + both tiebreakers (UpdatedAt-tie broken by CreatedAt; same Updated+Created broken by Id). The markdown path piggybacks on the existing markdown_render_tests for the renderer itself; the wiring is shallow enough that a build + smoke test is sufficient.

Test plan

  • make rebuilds cleanly (FPC, mode delphi)
  • make test — all 12 suites green (smoke + 10 existing + working_state_tests with the new TestSortNewestFirst)
  • Manual: pasclaw tui against a workspace with several sessions — confirm session pane shows newest at the top, selection follows when a stale session updates.
  • Manual: pasclaw session list — same ordering at the CLI.
  • Manual: ask the model to reply with a markdown table or fenced code block in pasclaw tui — confirm the rendered output shows ANSI-styled headings / code blocks instead of literal asterisks and hashes.
  • Manual: pasclaw tui --no-render-markdown (or render_markdown: false in config) — confirm raw markdown passes through verbatim.

Generated by Claude Code

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1571 to +1572
if RenderMd and (Msg.Role = mrAssistant) and (Trim(Body) <> '') then
Body := RenderMarkdown(Body);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.
@FMXExpress
FMXExpress merged commit e3ecc12 into main Jun 8, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
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.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
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('').
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