Repository navigation
TUI widgets — Delphi-side positioned two-pane layout (sessions left, chat right) - #122
Conversation
…chat right) Upgrades `pasclaw tui` on the Delphi build path from a scrollback REPL to a taskman-style positioned full-screen TUI with two panes: session list on the left, chat scrollback + input on the right. Header with provider/model/clock, footer with focus-aware hotkeys. ~700 LOC in the Delphi branch of PasClaw.TUI.pas; FPC branch unchanged. Pattern lifted from Daniele Teti's TUI guide (https://www.danieleteti.it/post/tui-delphi-dmvcframework-en/) and the taskman example: per-frame redraw via GetConsoleSize + GotoXY + WriteAnsiText, non-blocking KeyPressed/GetKey loop, ConsoleTheme for styling (ConsoleThemeNavy by default), background TRunToolLoopThread so the UI stays responsive while the LLM call runs. What you get on Delphi: - Session list pane reads from PasClaw.Session.Store.ListSessions (the PR #117 store); Up/Down navigates; Enter loads; N spawns a fresh session; D then Y deletes (one-key confirm matches `pasclaw session delete` semantics); R refreshes manually. The list also auto-refreshes every 3s so cron-side / parallel-CLI changes show up without keystrokes. - Chat pane renders TSession.Messages with role-colored headers (user=cyan, assistant=magenta, tool=yellow), hard-wrap at pane width, line-based scrollback (Up/Dn scrolls in 5-line jumps, auto-pins to bottom on new turn). Tool-call bodies show as `-> name(args)` lines. Divider above the input shows the PasClaw.Agent.Steering pending count plus a spinner that rotates each frame while the loop runs. - Input is single-line, single-char editing. Enter sends; while a loop is in flight, Enter pushes to the steering queue instead (the loop drains it at iteration top — PR #120 mechanism). Slash commands recognized: /quit /exit /q /new /clear /help /tools. Unknown slashes flash an error rather than getting sent to the model. - Tab swaps focus between panes; the focused pane gets a `>` marker on its selection and an underscore cursor on the input line. Q or Escape quits. Terminal resize is detected per frame and triggers a ClrScr to drop stale ink. - Pane widths auto-compute: session pane = 32 cols capped at W/3, minimum 24; chat takes the remainder. Header+footer take 3 rows. If terminal < 60x12 a one-line warning is shown instead of the layout (avoids garbled output on tiny windows). Plumbing: - TTUI grew a public `SessionId: string` (Cmd_TUI_Run forwards from new `--session` flag, mirroring `pasclaw agent --session <id>`). Empty = auto-allocate per PR #117 default-persist; existing id = resume; missing id = pre-seed. - TTUI.Destroy added (Delphi only) to terminate any in-flight worker thread and free FSession on TUI shutdown. - The FPC branch keeps its ANSI line-based renderer verbatim. It ignores SessionId silently (the FPC build has no session pane yet — sketched in the file header as a follow-up). Built clean under FPC (the path that compiles in this environment); the Delphi branch is gated by {$IFNDEF FPC} so the FPC smoke (11/11 OK) covers the non-TUI cmds; Delphi-side compile + UX needs a human on a real Delphi 12 IDE to verify (no dcc64 in this env). README updated to describe the new layout + hotkeys + that the FPC build is unchanged. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7410385e12
ℹ️ 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".
| KEY_TAB = 9; | ||
| begin | ||
| case Key of | ||
| Ord('q'), Ord('Q'), KEY_ESCAPE: |
There was a problem hiding this comment.
Allow q characters in chat input
When the chat pane is focused, typing any lowercase or uppercase q is intercepted here before HandleChatKey can append it to FInputBuf, so ordinary prompts such as question immediately quit the TUI. Restrict the quit hotkey to the session pane, an empty chat buffer, or a modifier-based shortcut so chat input can contain q.
Useful? React with 👍 / 👎.
| SetLength(FSession.Messages, Length(Loop.FinalMessages) + 1); | ||
| for i := 0 to High(Loop.FinalMessages) do | ||
| FSession.Messages[i] := Loop.FinalMessages[i]; |
There was a problem hiding this comment.
Bind completed turns to their originating session
If a request is in flight and the user switches sessions with Tab + Enter, starts a new session with N, or submits /new, the worker still contains the original session history but this completion path writes Loop.FinalMessages into the mutable current FSession. The next successful response can therefore overwrite and persist the newly selected session with another conversation's history. Disable session changes while FLoopThread is active or retain the originating session object/id with the worker and apply the result only there.
Useful? React with 👍 / 👎.
| Worker.Terminate; | ||
| Worker.WaitFor; |
There was a problem hiding this comment.
Avoid waiting indefinitely for an uncancellable worker on quit
If the user presses Escape or the quit hotkey while a provider request or tool call is still running, shutdown reaches this WaitFor immediately. TRunToolLoopThread.Execute only calls RunToolLoop, and the loop does not inspect the thread's Terminated flag, so the preceding Terminate does not cancel the active operation; a slow provider call or hanging shell tool can leave the advertised quit action blocked indefinitely. Use a bounded wait or propagate cancellation into the loop instead of synchronously waiting here.
Useful? React with 👍 / 👎.
| Ord('n'), Ord('N'): | ||
| begin | ||
| FConfirmDelete := False; | ||
| StartNewSession; |
There was a problem hiding this comment.
Make N cancel a pending deletion
In the session pane, after D enables delete confirmation, the footer advertises [N]o cancel, but pressing N enters this branch and starts a fresh session instead. Handle FConfirmDelete before the normal session shortcuts so N only dismisses the confirmation prompt.
Useful? React with 👍 / 👎.
…ssion, bounded shutdown, N cancels delete Four legit Codex findings on the TUI widgets PR — all fixed in place on PR #122. FPC build remains untouched (the entire patch is inside the {$IFNDEF FPC} branch). P1 — Q/q quit intercepted before chat input. The top-level HandleKey grabbed Ord('q')/Ord('Q')/KEY_ESCAPE as a global quit, so typing "question" in the chat input immediately killed the TUI. Fix: Escape stays the only universal quit. Q in the SESSION pane quits (unambiguous — no input field there). Q in the CHAT pane quits only when the input buffer is empty; with anything typed it falls through to the printable-char branch so words containing q work. Discoverability path preserved (Q with empty input is the obvious "quit from chat" gesture). P1 — Completed turns now bind to their originating session id. Previous PollLoopWorker wrote Loop.FinalMessages into the currently-loaded FSession, so a Tab+Enter / N / /new while a loop was in flight would overwrite a freshly selected session with the in-flight conversation's history. Fix: capture FLoopSessionId at StartTurn, then on completion route the result via ApplyLoopResultTo(originatingId, ...). When that id matches FSession.Meta.Id the update happens in place; when it doesn't, we open the originating TSession by id, append + persist + free without touching the currently-loaded one. Same fix for the timeout, error, and steering-push paths so all four flows respect the binding. A flash message "result -> <id>" surfaces the cross-session save so the user sees where it landed. P2 — Unbounded WaitFor on quit. TRunToolLoopThread.Execute calls RunToolLoop which doesn't inspect the thread's Terminated flag, so a hung HTTP call or stuck shell tool kept the synchronous WaitFor in Destroy blocked indefinitely — the advertised "press Q to quit" silently froze. Fix: 250ms bounded wait on DoneEvent; if the worker hasn't finished by then, hand ownership to the OS via FreeOnTerminate and let process teardown reap it. Matches the pattern PollLoopWorker already uses for the per-turn timeout path. P2 — N now only cancels delete confirmation. The footer hint advertised "[Y]es delete [N]o cancel" during the confirm-delete state, but N also fell through to StartNewSession because the general case statement handled Ord('n')/Ord('N') unconditionally. Fix: short-circuit the entire confirm-delete handler at the top of HandleSessionKey — Y deletes, anything else just dismisses the prompt. Below that, the normal N/D/R/Enter handlers no longer redundantly clear FConfirmDelete (the gate above did it). FPC build clean (443553 lines), smoke 11/11 OK. Delphi-side compile + runtime needs human verification; the changes are constrained to the {$IFNDEF FPC} branch the previous PR established. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
When /model is invoked in session A (provider=openai) and the operator switches to session B (provider=anthropic) before the HTTP refresh returns, PollModelRefresh used to open A's roster against B's context. ApplyModelSelection on a pick would then write an openai model id into B's Meta.Model, so B silently ends up talking to anthropic with an openai id. Same shape as the FLoopSessionId fix on PR #122. Cache save is unconditional (the HTTP succeeded; the roster is authoritative regardless of focus) but the overlay only raises when the currently-active session still uses the refreshed provider. Provider-mismatch flashes a "switch to a session using <name> to pick" notice instead. Extracted the "active provider" lookup OpenModelMenu and PollModelRefresh now both rely on into a shared ActiveProviderName helper so they agree on the comparison.
Two bugs in one wiring on the TUI side, both flagged by Codex: 1. Order of operations. AccumulateLoopStats ran AFTER ApplyLoopResultTo's Save. The Meta.Stats increment had nothing to flush it to disk on the normal path -- TUI sessions kept reporting zero counters at /v1/stats with the flag turned on. 2. Cross-session race. AccumulateLoopStats mutated FSession.Meta, but a worker can complete after the operator has already switched to a different session. Pre-fix: the new session silently absorbed the originating session's stats. Fix: move the persistent half of the accumulation INSIDE ApplyLoopResultTo, between the Working-state update and the Save. ApplyLoopResultTo already opens the originating session by id (via the FLoopSessionId mechanism PR #122 added for messages), so: - The Save that immediately follows picks up the new counters. - The right session gets credited regardless of where FSession points by the time the worker completes. TTUI.AccumulateLoopStats is reduced to the in-memory FStats* updates that drive the /stats overlay -- those still need to run regardless of Cfg.StatsCollectionEnabled. Tests (session_stats_tests): - TestAccumulateThenSavePersistsCounters pins the order: accumulate first, save second, reload, counters survive. A future refactor that reverses the order fails this test instead of silently dropping data. - TestAccumulateRoutesToOriginatingSession simulates the cross-session race by creating two sessions, accumulating into the first, saving, and asserting the sibling stays clean. Pins the by-id routing contract.
#221) Two Codex findings, both legit: 1) Decouple checkpoint turns from stats collection. The old design pulled BeginTurn's TurnNumber from TSession.Meta.Stats.Turns. That counter only increments inside ApplyLoopResultTo when StatsCollectionEnabled is True -- the opt-in stats subsystem. With stats off (the DEFAULT), every TUI turn called BeginTurn(1) and overwrote the same turn-0001 manifest. /undo N could only ever see the latest snapshotted turn instead of the last N. Fix: the checkpoints module now owns the counter. At InitCheckpoints we scan SessionDir for the highest existing turn-NNNN entry and resume from there; each BeginTurn (no arg now) just increments. Independent of stats; survives pasclaw restarts cleanly (turn numbers don't repeat across runs of the same session). New test (TestInitResumesFromExistingTurnDirs) pins it: drop a turn-0001 dir on disk, re-Init the same session, verify the next BeginTurn lands on turn-0002 and /undo 1 restores the start-of-turn-2 state correctly. 2) Keep in-flight snapshots bound to their origin session. When the operator switched sessions while a tool loop was still running, SelectSession called InitCheckpoints for the newly displayed session -- mutating the module globals while the background worker's fs_write hooks still expected the OLD session's state. Subsequent writes landed in the WRONG session's dir; /undo on the origin session couldn't see them; /undo on the displayed session would later restore unrelated files. Fix: SelectSession (and the post-delete-resurrect path) only call RewireCheckpoints when FLoopThread is nil. Otherwise they set a new FPendingCheckpointRewire flag. PollLoopWorker fires the deferred rewire at every completion path (happy / failure / timeout), so the next user turn on the displayed session correctly initialises checkpoints for THAT session before StartTurn calls BeginTurn. This mirrors the same "loop owns the session it started in" shape FLoopSessionId already enforces for result delivery (Codex P1 on PR #122). https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Upgrades
pasclaw tuion the Delphi build from a scrollback REPL to a taskman-style positioned full-screen TUI: session list on the left, chat scrollback + input on the right. Header with provider/model/clock, footer with focus-aware hotkeys. ~700 LOC in the Delphi branch ofPasClaw.TUI.pas; FPC branch unchanged.Pattern lifted from Daniele Teti's TUI guide and the taskman example the user shared: per-frame redraw via
GetConsoleSize+GotoXY+WriteAnsiText, non-blockingKeyPressed/GetKeyloop,ConsoleThemefor styling (ConsoleThemeNavyby default), backgroundTRunToolLoopThreadso the UI stays responsive while the LLM call runs.What you get on Delphi
PasClaw.Session.Store.ListSessions(the PR Persistent session management — durable conversations across restarts #117 store). Up/Down navigates, Enter loads, N spawns a fresh session, D then Y deletes (one-key confirm matchingpasclaw session delete), R refreshes manually. The list auto-refreshes every 3 s so cron-side / parallel-CLI changes show up without keystrokes.TSession.Messageswith role-colored headers (user=cyan, assistant=magenta, tool=yellow), hard-wrap at pane width, line-based scrollback (Up/Dn scrolls in 5-line jumps, auto-pins to bottom on new turn). Tool-call bodies show as-> name(args)lines. Divider above the input shows thePasClaw.Agent.Steeringpending count plus a spinner that rotates each frame while the loop runs./quit /exit /q /new /clear /help /tools. Unknown slashes flash an error rather than getting sent to the model.>marker on its selection and an underscore cursor on the input line. Q or Escape quits. Terminal resize is detected per frame and triggers aClrScrto drop stale ink.Plumbing
TTUIgrew a publicSessionId: string.Cmd_TUI_Runforwards from new--sessionflag, mirroringpasclaw agent --session <id>. Empty = auto-allocate per PR Persistent session management — durable conversations across restarts #117 default-persist; existing id = resume; missing id = pre-seed.TTUI.Destroyadded (Delphi only) to terminate any in-flight worker thread and freeFSessionon TUI shutdown.SessionIdsilently — the FPC build has no session pane yet (sketched in the file header as a follow-up).Test plan
make smoke11/11 OKpasclaw tuiboots, prints header, accepts/quit)dcc64) — verify the{$IFNDEF FPC}branch compiles. The env this PR was authored in has nodcc64; I've been conservative with Delphi syntax (hoisted inline-var declarations to method-top, dropped anonymous-record fields, keptTArray<string>andString.Splitto known stable overloads).Out of scope (deliberate)
Consoleworks under FPC mode-delphi in principle but isn't tested; cross-compile would be a separate PR.OnToolCall/OnToolResultthrough to a render queue.Generated by Claude Code