Tui implementation¶
Current reference. System ownership · Domain glossary · Tool policy.
The CLI's ChatModelUsage resolves header metadata separately from chat
orchestration. It keeps a retained run's context window from its snapshot and
uses catalog details only for rates; line/JSON chat skips that lookup.
The header token count and percentage describe one model request's prompt input,
independent of the run-cumulative billing counters used for session cost. A prepared
estimate has a ~ prefix; the provider's per-request modelusage JSON payload replaces
it when available, including a lower reported value. Cache buckets follow the pinned
protocol and input_tokens_include_cache flag. Output tokens never enter occupancy.
The percentage divides by the full pinned context window for Chat Completions,
Responses or Anthropic Messages, not max_prompt_tokens (which excludes output
reserve). A bounded run-metadata read pins fresh-run capacity; unknown capacity leaves
the count visible without a percentage. Catalog capacity is only a pre-pin fallback.
RequestContextReading is shared with WinUI. Durable model_step_id and event
sequence associate estimates and usage with their request; transient sequence is
only ordered within that step. Reported usage rejects delayed estimates, a new step
accepts a restarted transient cursor, and compaction clears the old reading until
new request evidence arrives. A new run resets causal/billing cursors while keeping
the last reading during preparation; reopening the same run keeps its billing
baseline. Missing usage keeps an available estimate instead of inventing zero.
Core TUI¶
Shared chat controller¶
ChatSessionEngine is the only conversation controller in agent chat. It owns
submission guards/snapshots, admission, the bounded queue, prompt history,
turn cancellation, pause/resume and the independent task inspection
lane. ChatSession.Engine.cs wires the same command and run handlers, attachment
ownership and shutdown settlement for every presentation. A typed Continue
that reopens a retained run revalidates its owner/state and preserves its provider
pin; it does not require current default settings to match a new submission.
TgChatLoop is a native key binding over this controller, with
TgChatEngineView translating its notifications to Terminal.Gui widgets.
ChatLineAdapter reads continued lines, submits them to the controller and waits
for the turn and attachment intake before reading again. PlainChatInput only
reads input; it has no conversation loop or second history. Text and NDJSON keep
their existing event/output projections. Human diagnostics and prompts stay off
JSON stdout. EOF and cancellation stop the controller and await owned settlement.
Stopped controllers refuse new input before routing and again at queue admission,
so shutdown during snapshot validation does not consume a draft or its attachments.
ChatPresentationSelection selects capabilities once: interactive terminals use
Terminal.Gui; redirected stdin/stdout, --json, --classic, any NO_COLOR,
TERM=dumb or a startup viewport below 80×24 use append-only line I/O. These are
adapters to one controller, not alternative chat engines. Native resize stays in
the same native host; there is no handover to a second loop.
Tui/ contains shared semantic formatting, measurement and event projection as
well as the line reader. It is not another interactive renderer. Native welcome
artwork still owns the galaxy, wordmark, sweep and meteors. The unused legacy
welcome/header drawing methods have been removed; shared glyph data and path
shortening remain. Host orchestration, protocol routes, provider selection
compatibility and Broker permissions are unchanged by this client refactor.
Failure, approval and activity copy resolve through the shared client tables
(AgentFailureCopy, AgentApprovalCopy): the transcript never prints a bare wire
token such as checkpoint_incomplete or external_directory_required. A code the
copy table does not know gets a human sentence with a /status and log pointer;
the token itself stays in the Host log and RU_TUI_DEBUG diagnostics. Protocol
mismatch, run-cancel failure and session-replay notices follow the same rule.
--json, NDJSON and RPC are machine surfaces and keep their codes.
Terminal chat omits /skills and /skill from handling, completion, palettes and
help; entering either command reports unknown_command without a run or catalog
mutation. Ordinary prompts can still ask for a skill. Host discovery, the model's
skill tool, GUI skill controls and typed run-command contracts retain their
existing invocation rules.
Activity and conversation flow¶
Native chat keeps routine successful tool receipts out of the transcript, including their result lines and bounded diffs. The live activity indicator remains while a tool runs; the turn footer still counts all tools and successful edits. This presentation filter applies to live and replayed activity without changing stored evidence. Failed or unknown actions retain compact rows between model prose and the following response. Common actions align their targets in a shared column on wide terminals; narrow terminals reclaim that space. These rows use neutral action names and explicit outcomes rather than claiming an edit succeeded. Units follow the actual tool: read counts are lines, search counts are matches, and terminal exit codes appear only when supplied by typed activity metadata. Exit/failure evidence takes priority when space is limited.
A native tool row is self-contained: display name, target, and bounded metrics stay inline, and the row keeps no hidden inspector. Ctrl+O is reserved for the model's reasoning; diffs are bounded and the overflow is summarized as a line count rather than hidden behind a key. Late successful metadata removes an unknown receipt without a blank gap; late failure metadata can reveal a previously hidden successful receipt. Visible diagnostic rows update by activity identity, preserving semantic colors. Explicit failure or a nonzero process exit code takes precedence over a legacy success label. Row removal rebases other activity and recovery marks on the UI thread; retention generations still protect evicted history from stale updates.
A command row names the script's first real statement, skipping preference, encoding,
environment and location setup, and counts the remaining statements ((+3 more)). A
failed row's reason line is omitted when it only repeats the exit code. A status row
that only reports ok, or a bare lifecycle code such as in_progress, is hidden, as in
the Desktop feed; a known code is worded (started a subagent) and a code with no
wording earns no row. A failed status always shows, worded from its code when it has no
sentence. The model's narration between tool rows gets its own dim guttered row, so a
run that talks through its work says so live instead of only in a reopened session. A
provider-reported thought opens a ◦ Thinking row when its step starts and settles in
place, so it sits above the answer that step streams rather than under it:
◦ Thought 31.0s at a second or more, ◦ Thought briefly under a second, and
◦ Thought stopped when the step fails. A plain output surface cannot rewrite a row, so
it keeps the completion-only form and announces only thoughts of at least one second.
Blocks of tool rows print no tally of their own: the turn footer carries the tool count
plus edits and failures (✓ 2m13s · 27 tools · 4 edits · 1 failed). A discovery row's
count lives in the metrics column only. Unknown outcomes stay explicit; run completion
never proves tool success. The live row distinguishes waiting for the model,
provider-reported thinking, response streaming, tool execution, compaction and
tool/request retry. Approval, trust and parked states keep their nonspinning
presentation. This adds no animation timer, Host protocol or execution authority.
Line/JSON adapters retain their output ownership and plain tool layout.
One active conversation¶
The native TUI runs one TgChatWindow and one conversation controller. /new
replaces the current idle session; /sessions opens saved history in the same
window. There are no concurrent session workers, tab strip, F6 navigation or
Alt+N shortcut. Active or held/queued work must finish or be cancelled before
changing sessions. Opening saved history resolves its recorded workspace and
session preset before replacing current state. A missing recorded folder fails
closed; one session's full-access choice does not become another session's default.
Deleting the open session returns to the empty landing; it never opens another saved conversation on its own, and the next prompt creates a session lazily, so no empty replacement conversation is left behind. A refused session or model change names the actual blocker (a running turn, queued prompts, or a paused approval/question), and a stray submit while a local panel owns the input is dropped instead of being reported as a queue failure.
Native session opens paint recent saved messages while the full message page and per-run activity load. Rich replay replaces the initial rows once the reads settle. On a session switch, usage restoration runs alongside rich replay. The same workspace lookup supplies the native switch's recorded path and label.
A fresh prompt retains its submitted provider/model through
POST /agent/v1/runs/selected. The Host stores that intent atomically with
admission; already admitted runs and queued snapshots keep their original
selection. Older Hosts refuse this route without falling back to unselected
creation. Permission presets remain session-scoped.
/exit stops attachment admission, cancels work started by this TUI and waits
for run/attachment settlement after the bounded UI drain. Runs adopted from
another client are detached on exit; explicit Escape still cancels the adopted
run. Saved conversations remain available through /sessions.
Escape can cancel pending task inspection before its panel opens. Inspection cancellation keeps priority over model cancellation.
TgPromptEditor owns a SteadyBar cursor, so focus, typing, wrapping and modal
return keep a non-blinking vertical caret. The composer does not override it with
a block. Existing drivers emit the terminal cursor style; no extra timer or
render loop is introduced.
The composer metadata can display the selected effort alone (for example max or high) between model and provider.
Startup and existing selection refreshes use the settings response's selected
reasoning value, with no extra catalog call or polling. Model/provider changes
clear the old display until refreshed; preset-only changes preserve it. Missing
values and retained-run summaries without a pinned effort show —. This is a
configuration label, not a claim of reasoning support or proof of provider-side
application. Narrow layouts bound the label and hide it at the smallest widths,
preserving the input editor. /reasoning remains the existing selection command.
Completed native turn footers append ctrl+o thinking when the turn ends with a
nonempty model-reported thinking block. Reasoning stays collapsed and uses the
existing expansion key and retention budget. The marker resets at turn/view reset
and when the turn's latest block is not reasoning, so missing or older-turn
reasoning is not advertised. No reasoning is requested or generated by this
presentation hint, and plain/sequential output remains unchanged.
Fresh chat starts without a persisted session. Bootstrap reads configuration and
builds the frame, but does not POST session creation. Native session navigation
reports switch to session "<title>" through command feedback; missing titles use
Untitled session. The title comes from the already-loaded, bounded/sanitized
session result, with no extra lookup. Native durable-turn and fallback text replay
omit technical replay summaries while preserving conversation rows, truncation
warnings and retained-run recovery. Plain output retains the replay summaries.
Local slash controls such as model/provider/status/help/preset do not materialize
a conversation; native local
commands keep the welcome screen instead of appending a user-message card or
advertising model work. Short results stay in the hint row until the next input;
multiline results use a closable document. Existing conversations retain normal
report output. Command capture is bounded and isolated from independent run output.
These commands retain their operation lifetime and input guards.
Custom prompt commands retain their run behavior. /follow is removed from
completion, help and dispatch. Continue reopens only the current session's
known followable run (running, or waiting on an approval or a question); without
one it remains an ordinary prompt. Runs no longer park for a Continue (ADR 0048).
A classifier admits this recovery while a queue is held, without claiming
draft attachments. Repeated recovery input while busy stays in the draft.
The first ordinary prompt creates the session before its policy/run setup; /new
remains explicit creation and selecting an existing session still reopens it.
Queued snapshots admitted from the initial empty draft may bind only to that
draft's materialized session. Provider/model/workspace/preset, attachments and
idempotency key stay unchanged, and existing-session or other-session snapshots
cannot be rebound. A lost/failed create acknowledgement does not automatically
retry or start a run; choose a session or reopen chat. Before materialization,
session-dependent task/subagent controls report no session
without issuing blank-id API requests. Status labels the session not started.
Stopping the UI keeps its two-second bound for ordinary turn handlers. The chat owner separately retains a pending create request until acknowledgement recovery settles and any late accepted run's cancellation request completes. It waits for that settlement before disposing the API client; UI completion alone does not mean the pending run is unowned.
The terminal is a compact coding surface: chat, inline tool activity and expandable
errors/diffs, approvals, attachments, session/model selection, run recovery and
background terminal task inspection/control.
The header retains its live context meter and shows the session title as soon as a
reopened session is replayed. Completed todo_write activities replace the native
session checklist. On wide terminals, the list sits beside the transcript and wraps
long items. Narrow or short terminals and completed lists use a one-line summary.
The composer spans both columns. Clicking the heading or pressing Ctrl+T opens a
read-only, scrollable list that receives subsequent updates. A clear snapshot or a
session switch resets the list. Durable run activity replay restores the latest
recorded snapshot, including for a retained run. The plain output adapter keeps its
bounded inline checklist and progress rows. Reattaching a tracked run counts elapsed
time from its start; resuming a parked
run counts from the resume. Prompt history remains available with Up/Down. Detailed inspection
belongs in the GUI; headless CLI and RPC capabilities are independent of this UI scope.
Terminal.Gui owns the interactive screen. Shared event and Markdown formatting
projects semantic transcript rows and styled runs directly to native attributes;
sequential text output and legacy command/diagnostic imports remain separate adapters.
Only Terminal.Gui draws an interactive frame; the append-only adapter prints rows
without cursor positioning, sticky footer, live-row repaint, resize rebuild or
framed composer. TuiSurface serializes writes per sink, without retaining a
duplicate transcript or imposing a process-wide write lock on other sessions.
Transcript history belongs to the native view; prompt history belongs to the
shared conversation controller. The native live row, footer and panels are unchanged.
Both adapters share one text engine. TuiText owns display-cell measurement, rune
decoding, wrapping and the common truncations; the Terminal.Gui importer and the
append-only writer call it instead of keeping their own tables. A row measured one
cell short wraps on the real terminal and misplaces every absolute cursor move after
it, so the table has to be single: CJK and the common emoji blocks measure two cells,
tabs advance to the same 8-column stops the terminal uses, and an unpaired UTF-16
surrogate renders as U+FFFD rather than throwing from the paint path. Model and tool
text is stripped of ANSI escape sequences, C0/C1 controls and bidi/format characters
before either sink sees it; a sequence split across two streamed deltas is neutralised
rather than left to complete. Native presentation rows expand tabs from the row's
current column before measuring. A submitted multiline prompt is one user-block row per
source line, with continuation rows aligned under the chevron. Span-painted bullet and
quote rows repeat their marker column or │ gutter on continuation rows, with the body
wrapped in the remaining width, so the screen and classic renderers agree on the shape.
The native transcript retains at most 2,000 rows / 200,000 characters, with a
16,000-unit per-line cap. The append-only sink writes directly and retains no
rebuild history.
Avoid: Requiring GUI feature parity or treating presentation metadata as authority.
Native paragraph projection splits styled, tab-expanded prose into storage segments of at most 16,000 UTF-16 units at rune boundaries before applying the view's per-row cap. Continuation segments copy without an inserted newline and wrap as one logical paragraph. Ordinary prose reflows only the last visual row with the changing tail; indented text, quote/list affixes and double-space layout use whole-row reflow to keep the original wrapper and synthetic prefixes consistent across storage boundaries. The native writer tracks the entire provisional segment count and replaces it together on each preview or commit, including when the total history budget has evicted earlier segments. Retry, suppression and durable turn replacement operate on all segments. The existing 2,000-row/200,000-character history budget still bounds retained content; segmentation does not change the model's durable context.
StreamingMarkdownProjector owns native line/paragraph accumulation and preview
cadence; tool activity and run lifecycle remain in TuiTranscript. Completed
rows within one incoming chunk use bounded commit batches (64 rows or
16 Ki characters, with a single oversized source row kept intact). The first
commit remains eager; queued rows flush before previews, empty commits and return
from Append, so subsequent tool/lifecycle output cannot overtake them. Each
dispatch owns its row array. There is no timer or cross-event buffering, and the
unfinished-line preview cadence is unchanged.
Important-text paint combines explicit Markdown styles with a shared deterministic
TuiDataTone matcher for numeric/date forms and supported file extensions,
including .js, .jsx, .ts, .tsx, .html and .css. Extension matching is
case-insensitive; the original displayed spelling is preserved.
Numeric forms include signed dot/comma decimals, grouped amounts, percentages and
common currency symbols or USD/EUR/GBP/JPY/CNY/VND codes. Dates use ISO year-month-day
or day-month-year with slash, dash or dot separators and require a valid calendar
date. Invalid date candidates stay plain instead of exposing colored numeric
fragments. File matches, including digit-leading basenames, take precedence over
numbers; version/IP chains and bare integers remain plain. Matching changes paint,
not the displayed text or the interpretation of a numeric value.
Native prose, including indented text, lists and quotes, receives the same default-ink
decoration on preview and commit. Explicit bold, links and inline-code paint remains
authoritative. Fenced code is identified by its Line-colored gutter and retains its
lexical styles. Verified tables retain typed inline runs through alignment, wrapping
and the narrow label/value layout; cells receive data tone before wrapping so tokens
split across display rows keep their paint. Plain table output serializes the same
layout without terminal attributes. None of this changes model context or tool policy.
A closed fence ends with a dim rule naming its language and line count, so a long block
visibly finishes instead of simply stopping (an empty bare fence still emits nothing).
Its
StreamingParagraphParser checkpoints settled top-level inline content at whitespace
boundaries, using Markdig source spans rather than pairing Markdown delimiters itself.
Only the unresolved suffix is reparsed on later deltas. Open delimiters, ambiguous
literal syntax and unclosed links/code remain provisional even when long; correctness
takes precedence over a fixed tail-size cap. Completed soft lines add one space.
Ambiguous block prefixes do not advance paragraph/fence state during preview.
Settled TranscriptLine objects retain identity and their starting display column.
The native writer caches their tab-expanded styled segments with weak keys and replaces
only the changed tail, keeping settled view rows intact. Retention-evicted settled
segments stay evicted on later updates; changed unresolved content can still be
reprojected. Reset/retry clears parser state and provisional segments together. The
append-only output adapter continues to use its existing line renderer.
List rows (• or 1. markers) wrap on words under their marker in the native view;
other indented rows keep exact columns.
The native view does not invalidate wrapped history just because a new/tail row contains a pipe. It tracks the last verified table's source range and column count while its wrap layout is valid. A header/separator pair, a valid body extension or editing a row already rendered as a table triggers the existing full table reflow; ordinary log/code pipes use incremental append/tail wrapping. New rows beyond the existing 100-rendered-row table cap do not keep extending that table. A cheap negative divider check avoids inline parsing when a separator is impossible. Styled/escaped separators and the renderer's existing entity behavior are retained. Resize, retention and multi-row removal still invalidate the layout and rediscover table ranges; expanded-block handling is unchanged. This optimization changes no history cap, parser/source text, model input, copy content or execution authority.
Before a new prompt's first write, a settings read that loses the local Host can resolve a replacement once through the existing managed Host starter. The client authenticates and reads settings again, then checks the queued provider and model before sending with the original session and submission identity. This path applies to fresh prompts with no retained run. Authorization errors, changed settings and failed recovery retain the paused queue and attachments.
Mouse drag selects the transcript's displayed rows without moving composer focus. Copy keeps whole graphemes and uses the displayed line breaks. Selection coordinates belong to the current wrap layout, so a rebuild clears them. Copy checks that the selected endpoints still refer to the same rows if streamed output updates the tail. While a text selection is active, both Ctrl+C and Ctrl+Shift+C copy it because the Windows input driver can report the shifted chord as Ctrl+C.
Pending images appear as [image 1] [image 2] in the composer's spacer row,
including while another turn streams. The labels are presentation only; submission
snapshots retain the original image data URLs. Queued/admitted images leave the draft;
images held after a pre-acceptance failure are marked held: until accepted.
Clipboard decode and image-limit failures also appear in the live status row. The
terminal paste route treats an empty bracketed paste as a request to read the
local image clipboard, matching Windows Terminal's image-only Ctrl+V signal.
Only the focused composer may attach an image; pickers, documents, the command
palette, questions and secret fields consume the signal without changing the
hidden draft. Non-empty paste payloads remain text and do not read the clipboard.
Dropped files follow the desktop rules
(ADR 0053): any existing file path
on its own line attaches, whatever its type. UTF-8 text of at most 8 KiB is inlined;
every other file is sent as a workspace path the agent reads with read, and a file
outside the workspace is first copied into .ru\attachments (AttachmentStaging,
labelled copied to .ru/attachments/<name>; Backspace on an empty prompt deletes the
copy again). An image is sent by path when the Host's catalog says the active model reads
no images. A folder fails as attachment_is_folder, a copy over 64 MiB as
attachment_too_large, and a file that would push the composed prompt past
AgentRunLimits.MaxPromptChars (200,000) is refused when it is attached rather than
when the prompt is sent. The vision warning comes from the Host's
/models catalog (accepts_images), not from a list of model names. GIF and TIFF
images are accepted and re-encoded like BMP; an image that needs no resize still loses
its EXIF/XMP/text metadata, and a JPEG its EXIF rotates is re-encoded upright.
The resizer reads the PNG/JPEG/BMP/WebP container header and rejects a source canvas over
64 MP before GDI+ allocates the decoded surface; the longest side is then capped at 2576
and the encoded result at 4 MB, retrying lower quality and a smaller long edge when the
first encode exceeds the byte cap.
Attachment handlers are registered to their session before starting. Shutdown stops new handlers, cancels the session lifetime and awaits the registered work before clearing pending attachments or disposing views. An idle tab can be closed, or an inactive deleted-session page removed, only after its attachments finish. Image and dropped-text reads propagate the caller's cancellation token; image decode, resize, encoding and base64 conversion check cancellation between stages. GDI+ calls are synchronous and finish the current native call before cancellation is observed. A canceled load never becomes an attachment error or enters the draft. Clipboard temp images not yet transferred to pending state are released on failure/cancellation; pending state owns cleanup after a successful transfer.
Read-only document panels strip legacy ANSI sequences before wrapping into native
card rows. Their wrap budget includes the card's item indentation, preventing
per-row clipping; the original output still reaches the transcript's styled importer.
Picker capability belongs to the input adapter, rather than Console.IsInputRedirected.
An absent picker enables the line adapter's text listing; a null answer from an
opened picker is cancellation. Model/backend/reasoning handlers return at that
boundary without appending a text option panel or saving settings. Esc restores
composer focus. The native provider and model pickers show catalog availability in
the footer. A report opened over the welcome screen stays in its document panel.
An open conversation keeps the report in the transcript after the panel closes.
Panel and picker labels coming from a remote catalog (provider names, model ids) are sanitized like transcript text before they are measured or painted.
The repository bin/ru.cmd launcher prefers the standalone Release win-x64 CLI
publish and falls back to the desktop's flat publish when that CLI is absent.
An already running terminal keeps its loaded binary until it exits.
/provider [name] combines provider selection and masked credential entry in the
existing serialized native panels. The picker uses the live models.dev catalog
with the same built-in/fallback choices. It closes before the key box opens;
neither selection nor credential is sent before confirmation. Escape cancels
without saving. Empty input preserves a known stored credential, or permits a
keyless custom endpoint; otherwise an API key is required. A typed key goes
alone to POST /settings/provider/key, which checks it with the provider (or the
custom server) before storing it; only once it is stored does one settings POST
carry the backend. A refused key (provider_key_rejected,
provider_key_unverified, provider_key_malformed, provider_key_too_long)
changes neither the key nor the provider. A keyless custom endpoint sends only
the backend. The provider, backend and advisor pickers add the Host's
provider_key_status to a provider with a stored key (· key ok,
· key not checked yet, · key refused).
/key <provider> uses the same checked save. Failures print a code and fixed
text, never an exception message or the submitted secret, and are not retried.
Help, palette and completion advertise only /provider; legacy /backend and
/key handlers remain callable. /provider remove <name> uses the existing signout
endpoint. It is a configuration repair command for paused queues and does not
claim pending attachments; live model/provider pins remain unchanged. JSON refuses
secret prompting; sequential mode lists providers when no picker exists. The
previous undocumented /provider alias for model selection is replaced by this
provider setup flow; model selection stays under /model.
/preset opens the permission picker; /preset plan and /preset standard also
select directly. full_access always requires a separate interactive confirmation
whose default is to keep the current selection. Escape changes nothing. The selected
full_access profile treats structured protected paths as ordinary allowed targets;
hard-invalid requests remain denied by the Broker. The selected
preset and confirmation stay in the chat's next-turn intent, update the header permission label and
/status, and flow through the existing versioned session-policy update, snapshot
and rollback at run creation. The command does not mutate a live run or confer tool
authority. Busy/queued transitions and retained runs block changes; pending attachments
remain with the draft. Noninteractive Full Access selection is refused.
The same picker includes Remembered rules, also reachable with /preset rules.
This branch leaves preset intent and Full Access confirmation unchanged. It reads
global rules and current-workspace project rules through the existing policy API.
Project identity comes from authenticated, paged session metadata matched against
the canonical workspace path; no session/run is created for discovery. Reads are
bounded to ten metadata pages and 1,000 rules. Missing, ambiguous or incomplete
workspace metadata is an explicit project-scope notice, not an empty-rule claim.
ChatApprovalRulesWorkflow owns list/details/removal navigation through the native
modal request gate. Ask/Deny rules are read-only: deleting those could widen access.
Removing an Allow rule defaults to Keep, requires explicit confirmation, rechecks
the workspace identity and exact scoped rule, sends one interactive DELETE, and
rereads that scope before reporting success. Esc/cancellation never confirms and a
lost acknowledgement is never retried automatically. Removing a durable rule does
not clear other grants, change the selected preset or rewrite existing run snapshots.
Busy/queued/retained-run guards remain in force. Line/JSON adapters list only;
JSON emits a remembered_rules record and keeps diagnostics off stdout. Policy list
responses without an items array fail with invalid_response instead of looking empty.
Terminal.Gui status/help reports are emitted without the legacy inner border, using the available document label width. Only the native modal supplies a frame; retained transcript rows remain unboxed and can reflow without splitting border columns.
Context and token reports¶
Native /status selects Overview, Context or Session usage; explicit
/status overview|context|usage bypasses the picker. Line/JSON keeps the bare
overview behavior. Sections remain read-only local commands: no new conversation,
run, permission update or model request is created. The existing queue/paused
controls and document modal request gate retain ownership of input and attachments.
Reports follow the existing queue and take a snapshot at command execution; they
do not add a parallel control operation or a live-refresh timer.
ChatTokenUsage parses optional provider counts and normalizes inclusive cached
input into disjoint billing buckets. Missing counts/accounting/rates remain unknown,
including partial pricing; zero requires an explicit measured zero. ChatUsageReader
binds every run and durable event to the selected conversation, de-duplicates payload
references and verifies event order. Replays use live=0; limits are eight recent
listed runs, 8,192 events, 256 distinct usage reports and 8,388,608 UTF-16 code units of replay/payload text
per run. The section read has a 20-second deadline; optional price lookup is limited
to two seconds per run. No history/payload read is triggered by typing or drawing.
Context reads only the latest run's newest usage payload after its last compaction, without reading historical billing payloads or prices. System/tools/messages are request-size estimates, distinct from provider prompt tokens and cumulative billing. A retained run owns its published window/reserve; next-turn catalog selection cannot replace them. A compaction with no newer usage keeps the reading unknown. A live prepared-request estimate may fill an otherwise unreported matching run; compaction and usage frames clear it. The unsent draft estimate uses the GUI's rough 3.5 characters-per-token ratio plus the Protocol image allowance and is labelled separately.
Session usage sums step billing while peak is the largest individual reported step.
The display states the recent-run scope, incomplete fields and priced coverage.
Prices use recorded provider/model identities with current catalog rates, never
the currently selected next-turn model. JSON sections emit context or
session_usage records, with diagnostics on stderr. ChatUsagePresentation builds
plain document rows; the existing modal performs wrapping, scrolling and resize.
Document modal bounds follow the wrapped body height plus card chrome, capped by the available window height. The wrap cache is shared by measurement and drawing; content replacement requests layout, and resize clamps the scroll offset against the new page size. The popup does not clear background cells outside its card.
ask_user in Terminal.Gui uses a native modal answer editor. The question and
numbered choices share a wrapped, scrollable region. Up/Down, Tab/Shift+Tab and
mouse clicks select suggestions, including their continuation lines. The Other
choice restores the custom draft and caret when switching back. Only Enter confirms.
Text paste and Unicode/newlines
remain answer text, never slash commands. The composer draft/cursor survives the
modal. Escape defers the question and pauses queued prompts without cancelling the
Host run; Continue can reopen that tracked question while the queue is paused.
ChatInputWorkflow checks the exact run/session and waiting-input snapshot before
and after editing, sends once through AgentApiClient.AnswerAsync, and deduplicates
acknowledged input events. The Host retains consume-once and policy authority.
Retained input recovery uses a finite replay (2048 events, 64 KiB per frame, four
seconds), requires matching run/session/event identity and the summary cursor, then
refreshes the run before opening the editor. Missing/stale questions fail visibly;
uncertain POSTs never trigger an automatic retry. Line/JSON adapters retain the
out-of-band answer command and do not consume stdin on behalf of the question.
ChatTaskWorkflow implements /tasks [run-id] and /tasks kill <execution-id> using
the existing typed Host command API, with no execution or policy logic in the UI.
It captures session/run identity before awaiting, verifies membership before each
command, filters foreground entries, sanitizes labels and refuses malformed lists.
Interactive stop defaults to keep; after confirmation a fresh list must still show
the exact background execution running. A stop acknowledgement is reported as a
request, never fabricated final completion. Errors and uncertain POSTs do not retry
automatically. Broker absence is an explicit failure, not an empty success.
Terminal.Gui has one bounded task-control operation independent of the model turn and submission queue. It bypasses attachment snapshot/admission, blocks overlapping submissions until finished, and cancels/drains on shutdown. Escape during its fetch cancels task control rather than the model. It adds no timer or periodic network traffic: refresh is an explicit picker action. Modal request serialization is shared with native questions and approval/trust prompts, preventing one panel's response from resolving another panel's waiter. Line and JSON I/O remain nonmodal adapters.
The TUI has no recorded-change inspector or turn-branching controls.
/changes, /history and the legacy /rewind alias are removed from the catalog,
help and dispatch, including the auxiliary control lane. Ordinary sends do not
stage or commit conversation branches. Saved-session replay and input recall
remain in their existing owners. Host/GUI and headless session APIs are independent.
The terminal no longer handles /delete, /resume, /retry, /release or
/clear. They are absent from help, palettes and completion, and an explicit
removed-command guard refuses them before snapshot/admission, paused-queue control
or custom prompt-command lookup. Transcript reset remains an internal lifecycle
operation. The sessions browser retains its existing operations; /sessions id:<id>
provides explicit switching without changing title-query behavior.
Rejected submissions retain the paused queue and held attachment labels, with no
automatic replay; diagnostics direct users to close/reopen chat. Parked-run text
points to external CLI cancellation. Public session/run APIs and GUI behavior remain
unchanged.
The native permission label is drawn immediately before the top-right usage
cluster, using the existing green accent, instead of the composer metadata row.
Composer preset changes forward to the header through one presentation event, so
startup, selection, session replay and retained-run updates share the same path.
The header remains blank on the empty welcome screen; session title, preset and
usage appear when conversation content is present. The workspace/path heading
is removed. Header chrome is drawn above the landing sky. Idle footer text is empty instead of Ready; explicit feedback,
attachments, approvals and queued/running states remain visible. Narrow headers retain the preset
and compact token count before optional percentage/cost details. No policy,
approval, token accounting or command behavior changes.
Workspace display¶
The native header does not display a workspace path or a no-project placeholder.
Workspace selection, execution cwd and permissions are unchanged. /status
retains a sanitized full workspace path, wrapped to fit the panel. Feedback and
attachment labels do not populate a workspace heading.
Welcome sky¶
The native welcome surface uses TuiGalaxySky, a deterministic 2x4-dot Braille
raster matching the approved wide spiral-galaxy preview. A warm nucleus and
bulge sit inside six full-length spiral arms, dust lanes and a sparse halo.
The arms are evenly spaced through a full turn and share the fixed particle
budget. Filament and tangent-link sampling uses the particle index within each
arm, keeping all six arms detailed rather than tying those patterns to an arm ID.
The sky palette uses dark indigo envelopes, blue/teal ridges, lavender dust,
muted rose knots and an ivory nucleus. Lower stars also include blue, teal,
lavender and rose accents; a few foreground stars use warm glints.
The native welcome wordmark uses a green-to-blue RU gradient and a muted green AGENT,
with a narrow warm light sweeping across for 2.5 seconds every 10 active welcome
seconds. AGENT's darker green face leaves brightness headroom for that
warm sweep. Its first sweep starts at two seconds. TgWelcomeWordmark caches glyph
strings and 16 light levels per cell. When the driver reports Sixel or enabled
Kitty raster support, the centered logo uses square tiles with subtle inner gutters,
small rims along every letter and four shadow layers cast down/right.
RU and AGENT use matching low-contrast inner seams with subpixel coverage colors; their outer
silhouettes stay defined. Glyph shapes, face colors and raster dimensions remain
the same; placement follows the galaxy core.
TgSquareWordmarkRaster reuses two 354x84 pixel buffers, updates at most 10 times
per active second during the sweep and reuses its quiet frame between sweeps.
TgWordmarkPalette fixes the Sixel palette across the complete light-sweep cycle,
so lighting RU cannot recolor untouched AGENT faces or make soft seams jump.
It samples the existing raster's quiet frame and 25 sweep frames once, retaining
seams and face colors. The palette reserves up to three warm highlights so the
narrow beam survives quantization. Cached palettes respect the terminal limit
(up to 32 colors); warm lookup does not allocate or resample the image. Cropped
Sixel fragments use the same palette; Kitty retains full pixel colors.
The existing welcome clock owns animation timing; no additional periodic timer or
background renderer is started. The welcome animates for one cycle
(TgLandingView.ActiveCycle, the 10-second sweep period) after it appears and after
each key, mouse event or resize, then holds a still frame; it settles only between
sweeps, so the light never freezes mid-beam, and resumes without jumping forward.
While the welcome is still (or hidden) and no run is active, the session clock
ticks every 50 ms instead of every 18 ms. An untouched welcome therefore stops
redrawing: the sky used to cost about 10% of one core indefinitely.
TgLandingView inherits ImageView for native
raster ownership and cleanup. It captures the ID of the image command registered
by the base view once, then places its bounded logo through Terminal.Gui's output
buffer after text. It does not duplicate the library's private ID format. Sky,
meteors and logo share the same view, keeping a black matte beneath the logo
image regions. The sky/lower stars and meteors skip that rectangle; scaled output
pixels also fill holes and padding with opaque black so raster-owned text blanks
cannot leave old dots behind. The fixed Sixel palette includes exact black.
Scaled pixels and encoded data are cached; only a changed sweep
frame, output size, protocol or palette limit requires re-encoding. The Sixel
palette uses at most 32 colors, respecting a smaller reported terminal limit.
Sixel placement is re-emitted after text redraws to keep the animated sky from
erasing the logo; cached encoding avoids repeated conversion during quiet frames.
TgSynchronizedFrame brackets raster welcome frames with DEC synchronized-output
mode 2026 through the existing driver. It ends the batch on
IApplication.LayoutAndDrawComplete, after Driver.Refresh has flushed both text
and raster data. This prevents the terminal from presenting the intermediate
text pass that temporarily erases Sixel letters. Removal frames are included;
disposal closes an unfinished batch after an aborted draw. Glyph-only welcome
frames do not enable this mode. This does not add a renderer, timer or change
the animation cadence; terminals without mode 2026 support ignore the sequences.
The raster's frame must fit outside the header, composer and hint; its output is
capped at 262,144 pixels and invalid cell resolutions are rejected. Unsupported
terminals, constrained frames and welcome overlays retain the existing glyph
wordmark with its small lower half-block shadow. Raster placements are removed
when hidden or covered and restored when visible again. The classic header keeps
its existing palette.
Ice-white glints in the galaxy are sparse
instead of covering every ridge. A rounder bulge and a few steady cross-shaped
foreground stars add depth without full-screen flashes, extra particles or timers.
Fine ribbons sit inside each wider arm envelope, with compressed stellar knots,
gently undulating dust lanes and occasional faint tangent links. The core uses
a loose, slightly irregular bulge with Gaussian light/density falloff, mixing
ivory, ice, pale silver and blue haze instead of filling central Braille cells
into solid blocks. Its seeded edge varies gently and drifts at a quarter of the
arm rotation speed; the bright central anchor remains fixed.
These details reuse the same particle loop and cell buffers; tangent links add
only a bounded secondary dot for a small subset of arm stars.
The welcome layout keeps roughly the top 75% as an independent galaxy canvas.
The wordmark is centered on its core (50% across / 64% down the sky region),
and the composer sits two terminal rows below the three-row logo. The sky can
extend beside and below the composer; input bounds and the whole hint row are
excluded from its painting. Short windows and tall drafts shrink the sky and
clamp the logo/prompt to preserve input and hints. A separate sparse star field
fills the remaining space below the galaxy canvas.
TuiWelcomeStars hashes cell coordinates without particle storage and varies
only brightness on the existing welcome clock, so positions do not jump.
The core retains a 1.5x projection scale; arms/halo/rings have an additional 1.1x
multiplier, giving a nominal 2.508-raster-width disc centered at 50% across / 64%
down its dedicated sky region. The centered wordmark is painted above the galaxy.
Its outer vertical radius factor is 0.957 (with 0.54 inclination compression), giving
a wider, tilted-disc silhouette. Arms have broader, feathered dust bands.
After flattening, the disc receives an additional -8-degree screen-plane rotation
around its fixed core, with a nominal 1.2 dot aspect correction. This tilts the
elliptical outline itself; rotating only the unprojected disc would leave its
outline level. The wordmark/input, background stars and falling-star paths are
not screen-rotated. Trigonometric coefficients are cached.
Outer stars are clipped at the edges. Arms rotate at 0.045 rad/s
and radial phase moves inward at 0.015/s, fading before wrapping to the outside.
The galaxy remains the primary welcome effect. TuiShootingStars adds 2–3 short
falling streaks per 40 seconds of active welcome time, first appearing at 12
seconds. Each shower lasts at most 3.1 seconds, with a white head fading
through neutral gray to a dark gray tail, roughly 32% longer than before. Meteor colors use
a separate cached palette to preserve neutral white/gray streaks over the colored galaxy.
The head travels to the bottom of the full welcome viewport; the remaining tail
exits afterwards rather than
disappearing inside the galaxy's shorter sky region. Up to 72 sparse Braille
cells are collected on the stack and merged with the sky/lower stars before
painting the wordmark. Input bounds and the entire hint row stay excluded.
This does not add a screen-sized buffer or inherit the galaxy raster's dimension
cap. No retained particle objects, background tasks or extra timer are created, and
the same welcome clock controls both effects.
The terminal font owns glyph metrics. The existing wordmark and composer stay above the black sky. No provider calls are added.
The line adapter prints its existing plain startup banner.
Slash suggestions align to the full composer width and end directly above its
top row. Their height and vertical position use the same current match-count
measurement, so filtering / down to /model or expanding it again cannot reuse
the previous menu height and leave a gap or cover the prompt. The measurement
keeps the existing available-height bound when the terminal is resized.
TgSlashDropdown.SetMatches also invalidates layout when the measured panel
height changes. Live typing and backspace can change that data without changing
the layout delegates themselves; redraw alone would keep an old black frame.
The geometry delegates are installed once. Identical ordered match contents
preserve the keyboard selection and do not dirty the list. Stable-height updates
redraw only the list; opening, closing and height changes repaint the parent to
erase exposed cells. Hiding an already-closed list does not invalidate the page.
The welcome has no FX button or On/Low/Off selection. Galaxy, meteors and the wordmark remain animated. Tab retains command completion in the composer.
The native application caps input/render dispatch at 60 iterations per second. The existing UI timer owns activity/footer updates; the welcome clock uses a 50 ms budget (at most 20 FPS). Actual cadence depends on terminal output. The clock stops while the landing is hidden or has no viewport; it resumes without catching up and caps a delayed step at 100 ms. Slash suggestions, palette, documents and modals leave the welcome clock running. Raster images are suppressed while covered by panels and restored when uncovered. First transcript/live content hides the landing; an empty transcript restores it. Typing an unsent draft leaves it visible.
TuiGalaxySky reuses the existing dot/color arrays when geometry and animation
time match, so static redraws do not repeat particle calculations. An already
closed slash dropdown no longer invalidates the entire window during typing;
actual dropdown removal and geometry changes still repaint.
Two byte buffers store masks and foreground ownership per cell; they are reused until resize, capped at 240 columns by 100 rows (48,000 payload bytes), with black outside that raster. Main particle count is bounded at 43,200, plus a halo/core fraction and sparse background stars, without retained particle objects. Glyph strings and palette attributes are cached. The raster itself allocates no managed memory per steady frame; the Terminal.Gui draw pass still walks the landing cells and its driver owns terminal output diffing. Narrow windows retain the compact Ru Agent fallback. The command-hint row is excluded from sky painting across the full viewport, including beyond the centered hint view, so background stars cannot trail the hint.
Terminal presentation¶
Terminal.Gui is the sole interactive screen engine. Redirected input/output,
--classic, --json, NO_COLOR, dumb and undersized terminals use
PlainChatInput: append-only line output with bounded submission history,
no cursor key loop and no screen/resize reconstruction. Shared command
metadata belongs to ChatCommandCatalog, not the line reader. Minimal
credential input remains separate and never echoes the secret; Terminal.Gui
retains its own masked panels. Startup selection uses 80×24; an active frame
hands over only below 20×12 after 400 ms. Handover disposes the frame before
using plain output and preserves the session/run state. TgTranscriptView
remains the single bounded scroll owner and emits follow-tail state changes
for busy/idle hints, including clear. Workspace-busy hints persist until Host
acceptance or a successful session switch, independent of composer keystrokes.
TgChatLayout owns responsive positioning: centred landing and a padded session
column with a multiline TgPromptEditor. Composer height grows within the
screen budget and uses the chat column's full width in active sessions (80 at home).
TgRuleView separates session context from chat without consuming another row.
The prompt is the opencode-style filled block in the panel tone: no frame
outline and no accent rail, with the preset, model and provider on the meta row
inside the block.
Slash suggestions match composer width; modal picker, approval, secret,
report and command-palette surfaces centre on the whole terminal.
The footer exposes one contextual shortcut and a short five-cell medium block wave,
leaving space for feedback and the queue status.
Transcript and slash-suggestion bounds follow the composer frame. Modal
dismissal restores source-text cursor position and draft focus. TgHintsView
presents running, approval and paused states independently of feedback and
queue count. Retained tool/reasoning blocks share the transcript's row/character
bounds; selection, expansion and explicit copy remain presentation operations.
The session column sits below a two-row header: title/usage, then workspace. The live activity
moved out of the header into the transcript: TgTranscriptView keeps one live
row pinned after the last committed row (opencode-style), drawn from the shared
activity presentation, and a settled tool row replaces it in place. The activity
projection separates glyph/action, target and right-aligned metrics;
response deltas show writing, parked states stay still, and queued tools retain
their own action after another tool settles. Settled rows preserve outcome text
and metrics when shortening targets. Frames below
20 rows keep a single heading row. The header projects session data and catalog
metadata; optional title probes read the session only while its title is missing.
Every animation phase (braille spinner, running-tool
glyph rotation, busy-hint colour wave, elapsed clock) is a pure function of
elapsed seconds in
TuiSpinner, so the 18 ms meteor ticker and any slower cadence yield the same
motion; the ticker runs only while the frame is live, and the live row's
spinner pauses on parked states. Streaming reflows a dirty tail at draw/scroll
boundaries. Unchanged wrapped rows are cached by retained text, paint and viewport
width, including while tool details are expanded; evicted text does not stay alive
through the cache. Turn-end assistant reconciliation reads at most four payloads
concurrently and preserves their model-step order and types. Optional header-title
reads have a 250 ms cancellation deadline. Reopened sessions and an explicit
attach treat waiting_subagents parents as active.
Tool activity metadata is updated by ID and consumed in durable proposal order;
the transient durable sequence is a stream anchor, not a tool identity.
Silent durable run/model metadata does not flush unfinished assistant prose.
Step-rewind callbacks read their row marker on the UI loop after the queued
step-start callback, so a worker-thread retry removes the superseded reply.
When durable text reveals a missing streamed head, the screen replaces the
current turn's prose with the complete step texts, separated by paragraphs,
retaining tool rows and earlier turns. Recovery declines after screen-retention
eviction or reset; sequential output keeps its explicit truncation notice.
Tool-result badges use typed completion activity: the public envelope's status
is a run status and running alone is not a tool failure. Without outcome
metadata the tool row remains neutral and says outcome unavailable.
Late completion details update that existing tool row in place. Row markers
are invalidated by retention, reset and rewinds rather than guessing at a
shifted row. Document panels own their paging keys while focused.
The TUI intentionally keeps core chat, inline tools/diffs, approvals, attachments,
session/model controls, run recovery, help and updates. The live header context
meter remains. Plans render an inline checklist when new and one progress line
after, at existing transcript boundaries, without splitting streamed prose or
retaining a separate task list.
Activity/todo/change inspectors, the project-file browser, session tree, rewind,
Markdown export and separate token/prompt-history reports are absent from the
interactive command surface. Up/Down prompt recall remains. Headless CLI and RPC
retain their own capabilities. File intake uses clipboard/drop or --image, and
Backspace on an empty prompt removes the last pending attachment;
a tracked waiting or running chat run reopens on typed Continue. /attach, /attachments, /paste,
/detach, /continue and /quit are absent from dispatch, help and completion.
/exit is the sole quit command. Escape dismisses overlays or interrupts an
active turn; idle Escape keeps the chat and draft open. Conversation replay retains the latest
20 nonempty messages, with a 100,000-character bound per message; screen
retention is independently bounded by TgTranscriptView.
Command overlays follow the composer and remain bounded within the frame.
Prose reflows across the full viewport width like the classic renderer; verified
Markdown table blocks reflow
from raw rows and preserve values on narrow screens.
A model step the host suppresses for recovery drops the rows it painted, so the
answer that replaces it never reads as the same answer printed twice.
One flat card frame backs every popup — picker, approval, workspace trust,
secret key, document window and slash suggestions — with the title and its
dismiss hint, a dim header rule, the filled selection bar, footer keys and a
scroll position when a list is clipped.
Resize reads the new terminal rectangle from the screen-changed event and forces one full
repaint, so a running turn no longer keeps right-anchored header text and footer glyphs
from the previous width after the terminal grows. The floating picker/approval/secret host is measured to the composed card, so the
welcome sky outside the card stays visible instead of being masked by an opaque
band the width and height of the old modal envelope. The session card switches on Enter and
deletes behind a confirm on Delete, returning to the empty landing when the open
session itself is removed; the first prompt then creates a fresh session lazily.
Rows carry a current-session bullet, relative age, empty/message count and workspace;
typing filters across title, id and workspace. Reasoning uses the same
bounded collapsed-detail owner without repeated feed summaries. Web tool detail
includes queries up to 160 characters or fetched host names. Detail passes the
existing known-secret redactor before the public activity sink; URL credentials,
path, query and fragment do not enter the fetched-host label.
- CLI submission ownership:
ChatSubmissionStateowns pending attachments, snapshot admission, held retry identity and accepted attachment transfers in both terminal paths. A declined trust gate returns the transfer to pending state once; cancellation and failure release its temporary images.ChatSubmissionSnapshotretains immutable intent and the original idempotency key. Rendering and run orchestration remain in the existing dispatcher. - CLI turn ownership:
ChatRunSessionowns turn cancellation, active/parked/followable run identities and unique assistant payload references. A park replayed from an older build cancels following without requesting server cancellation. Interrupting another active run still targets that run. The dispatcher renders and performs the HTTP operations through this state owner.