Skip to content
Chapter 4 · How it works 4-6

Gui implementation

Chat Escape first dismisses an open model, reasoning or context flyout through its FlyoutBase owner and consumes that key. Other open flyout/menu presenters defer run handling to the popup. With no popup, the shared keyboard policy keeps approval/question precedence and stops an active run from the composer or chat surface. The three flyouts also register Escape on their content root while open, including already-handled routed keys, because popup focus has a separate route from the chat surface. Per-owner subscriptions detach on close and survive a stale close callback after reopening. Dismissing the context flyout cancels the pending hover timer and suppresses reopening until the pointer leaves the meter. The Host may await another model response after a terminal tool exits. Live file/task panels show work so far. Terminal run state owns normal transcript settlement.

When adopting an active run after history replay, ActiveRunTranscriptProjection reattaches the assistant row with the same SourceRunId to the live activity collection. Completed earlier turns remain settled. The reply accumulator starts with that row's durable text, so subsequent deltas append without discarding the replayed prefix; a retry reset truncates only text from its live model step. Normal terminal completion and cancellation settle that same row. A stale or already-terminal adoption cannot rearm it, and a repeat adoption preserves pending deltas. If the view only has the replay seed when the run settles, history reload uses the persisted assistant reply for that same run once it is available.

Workspace selection uses the desktop Windows App SDK folder picker, associated with the owning window's WindowId. WorkspaceFolderPicker permits one dialog at a time and treats native Cancel/close as no selection. Unexpected failures reach the existing inline error and bounded exception-category/HRESULT trace. The selected path is pinned through the existing sidebar store; selecting a folder does not grant workspace trust or execution permission.

A new chat has no implicit project. The app never falls back to its install directory or that directory's parent: the run request carries an empty workspace_path, the Host allocates a scratch workspace for the session, and the client adopts the returned canonical path for execution. Chats without a chosen project stay in Recents, including after the Host returns scratch metadata. Scratch storage never creates a workspace header in the sidebar. An explicit manual move to a project group controls presentation without rewriting the execution workspace. Only Host-confirmed scratch ownership permits silent trust approval; the explicit trust endpoint still records the decision. Path shape alone does not authorize it. Refresh merges workspace_kind into existing rows and includes it in their change fingerprint. The Recents + creates a session with no chosen project; the Host allocates its private scratch directory when a run starts. The first durable history refresh keeps the chat in Recents. CLI-origin chats retain the separate CLI section. The workspace menu has one Delete workspace… action. After confirmation it deletes the group's chats through the single-session endpoint, then removes the workspace pin and clears its new-chat selection. The project folder and its files stay on disk. Empty pinned workspaces use the same action with zero chat deletes. Before confirmation it enumerates the unfiltered session listing (at most 100 pages and 10,000 sessions), with a frozen grouping snapshot; missing pages, duplicate sessions, repeated cursors or exceeded bounds abort planning. Bulk planning preserves local workspace hints for open drafts whose Host summaries do not yet have workspace paths, without overriding known durable paths. Bulk deletion retains the UI context and returns an explicit navigation outcome when the active chat is deleted; a later user navigation takes precedence. A complete listing is checked again before unpinning: a failed delete, a new chat outside the confirmed plan, an unavailable listing or a failed preference write retains the workspace for retry. Named partial artifact cleanup stays visible in the result.

Terminal failures keep their actionable inline status above the composer even when no assistant reply was rendered. The transcript does not add a terminal summary card; settled thinking rows alone must not hide a failed run. Write activity retains its Write label even when its required operation field is missing; rejected creation attempts must not appear as Editing.

Current reference. System ownership · Domain glossary · Tool policy.

Startup screen

The desktop startup wordmark is "Ru Agent" written out in Inter, one run per letter (WelcomeOverlay.Wave.cs). While the app loads, a colour wave travels through the letters: each takes its colour from a point on a looping ink, brand green, info blue, ink ramp (StartupWordmarkWave, 3.6 s per loop), offset by a fixed share of a loop per letter so the colour moves through the word. The wave is the loading indicator: there is no progress rail or sweep. Ready, error and reduced motion use the resting colours instead: Ru in the brand green, Agent in ink, and grey after an error. There is no glow or gradient on the text.

The backdrop is the app's own meteor shower (MeteorShowerField, also the Meteor Shower theme's backdrop), not a separate field. It runs while loading and stops on an error, when Windows animations are off, in high contrast, and on dismissal. A neutral Composition vignette (WelcomeOverlay.Vignette.cs, black corners, clear centre, no brand colour) frames the screen in Dark only; it is hidden in Light and in high contrast. A slow push-in (16 seconds, ease-out) scales the meteor field (5%) and the wordmark (9%) at different rates so they read as depth; on ready the push continues for the 180 ms exit and the wordmark swells as the screen clears.

WelcomeOverlay owns layout/status and its Motion partial owns a bounded entrance and the exit; the Backdrop partial owns the meteor field and the 50 ms timer that drives the wave. Real startup readiness interrupts the entrance; there is no minimum display time, invented percentage or completion delay, and the colour wave exposes nothing to automation. Large text and narrow/short windows scale the wordmark down inside a scrollable content host. The content StackPanel explicitly centers on both axes. The overlay is pinned to the actual XamlRoot.Size, aligned top-left, and follows viewport changes rather than inheriting a possibly wider shell layout. Its Layout partial releases the XamlRoot subscription on unload/close. The wave timer stops on readiness, error, exit, unload and disposal; the display never waits for a wave cycle. No web surface or per-frame rendering event is used.

StartupScreenPresentation maps the shell's startup phase to reader-facing copy. Host readiness waits for MainWindow to compose the chat surface before dismissal; optional catalog/session/health refreshes do not hold the usable surface behind the screen. Slow startup shows a factual hint after eight seconds. Missing-root, Host failure and unexpected startup exceptions stop motion and remain visible with an Open app action; Enter/Space also dismiss those settled error states.

The loading watch checks the shared OS animation gate every 250 ms, replacing motion with the resting wordmark and a still backdrop when animations are disabled, including live changes. Unloading/window close stops timers and storyboards and completes any pending dismissal task; repeated dismissal shares the in-flight completion. Ready/error status is applied immediately and announced politely rather than delayed by a fade.

Model picker loading

ChatModelPickerViewModel refreshes the selected provider in parallel with the Models.dev directory. Opening the picker projects available catalog data immediately; the selected provider's catalog supplies its group until the grouped controller has a result. An empty result or reported failure from that group is preserved. With no rows yet, an in-flight refresh shows Loading models…. Provider publications share a fixed 150 ms window that applies the newest snapshot without extending the deadline; continuous updates therefore cannot delay the first results until the full refresh finishes. The existing projection still determines supported protocols and rows.

Settings reads carry a read generation and selection version. A newer read, manual save (both start and successful completion), rebind, or authoritative settings selection prevents an older response from adopting stale settings. Grouped catalog publications carry SelectionVersion: Settings-origin changes advance it; local picker synchronization and availability updates do not. This preserves Settings adoption without letting delayed catalog callbacks own the choice, including when the selection callback is still queued on the dispatcher.

Submission snapshots the displayed backend/model before asynchronous session, preset or confirmation work and sends CreateRunProviderSelection through the selected-run contract. Queued turns retain the snapshot captured at enqueue. Reconciliation and session recovery retain that snapshot. A missing choice refuses submission while preserving the draft. Another client's default settings therefore cannot silently choose the provider/model for that turn. The in-flight submission owns a cancellation token from preparation through run creation. Stop and session navigation cancel it; a newly created session is adopted only while the captured open generation remains current, and the final create checks that the submission still owns the visible session. A stale-session recovery may replace that snapshot only while the original session still owns the recovery; Stop also waits for the create to settle before reconciling an ambiguous create outcome.

Context window popup

The compact composer popup shows used/context capacity, a thin segmented bar and three rows: System prompt, Tool definitions and Messages. ChatView.Context.cs keeps native painting; ContextPanelPresenter formats numeric estimates. Categories come from the prepared request, never from subtracting provider usage. They are approximate (~); the current draft is included in Messages. Images use a fixed 4,800-token allowance per image rather than provider image tokenization. Category proportions describe that estimate; the overall fill follows reported prompt usage when available, so category sums need not equal the provider total.

The existing transient usage-estimate frame supplies categories during a run; optional metadata on durable model usage restores them when a chat is reopened. Restoration reads the originating run's pinned identity and context capacity. A model whose catalog publishes no window is pinned with the assumed 1,048,576-token window (assumed), so the popup names that capacity instead of refusing to show a fill. Missing legacy metadata shows — for System prompt and Tool definitions, with only a visible-message estimate available. Unknown capacity on an older run is stated explicitly. When the last request failed before reporting provider usage, the same numbers are labelled as an estimate for the next request and the note says the last request failed; the popup never calls those tokens "used". Run/session ownership, sequence guards and compaction invalidate stale categories. Provider billing and cache counters remain independent of these display estimates.

RetainedContextMeterPresenter uses the shared RequestContextReading to correlate durable model.step_started/model.usage_recorded events with transient estimates through optional model_step_id. Reported usage takes precedence over a delayed estimate for the same step; compaction retires old steps, and a new durable step accepts the transient cursor restarting after reconnect. Raw provider input is normalized using the exact pinned protocol and input_tokens_include_cache, so inclusive cache buckets are not added twice. Older envelopes without the optional step identity remain readable and retain durable-sequence guards. A new run in the same conversation keeps the previous reading as its floor until the new request's estimate or usage arrives; only switching conversations clears it. The meter button's accessible help includes the total and all three values, so the reading remains available even when the flyout opens as a transient hover.

Model picker and reasoning panel

The composer's model picker lists models under their provider heading; a footer names the keys. Opening the picker centres the model in use by offset, without animation; a catalog update or a search rebuild keeps the reader's scroll offset (a new search starts at the top), so the list never jumps while it is open. The first open after launch can only do this once the catalog has arrived, so that open starts at the top. The marked row is painted instantly (a fade there read as lag); the search well's focus border fades (UiMotion.FadeBrush); a changed list fades in, and both panels enter with UiMotion.Enter. The reasoning panel is one segmented choice. The segments are equal, each as wide as the widest label measured in SemiBold and the user's UI font, and the panel widens past its 300 px minimum to fit them. A pill (UiMotion.SlideX) marks the segment under the pointer or the keys (Left/Right or Up/Down), and the sentence below it, from ReasoningEffortDescriptions, fades when it changes. Click or Enter commits and closes; leaving changes nothing. The sentences say what a level asks of the model, not how a provider behaves, and an unknown level is named as "Provider setting". A model that offers only its default shows one dimmed segment and says it has no adjustable reasoning effort. Everything applies instantly when Windows animations are off.

Workspace trust card

The first run in a folder the user chose waits for explicit workspace trust. The prompt is a card above the composer (WorkspaceTrustPanelControl), in the prompt slot shared with the approval and question cards, not a modal dialog. It shows the policy copy, the folder in a mono inset and, for a drive root or the user profile, a scope warning. Focus lands on Cancel, Escape cancels, and nothing approves by default; Approve and Cancel are the only paths to TrustAsync, and the decision stays the Host's. Because the card does not block the window it can go away unanswered: a session change, a run that no longer needs trust, a new guard owner or window close completes the pending wait with no decision (DismissWorkspaceTrustCard), the run stays parked, and the prompt returns when the session is shown again. A declined send still returns to the composer. Chat Escape does not stop the run while the card is showing, and the native preview hides under it like under approvals. A Host-confirmed scratch workspace is still approved silently and never shows the card.

Prompt slot above the composer

The approval, question and trust cards share one slot in the input column, in its free first row: above the composer and its status line, not over them. A card used to float over the composer from the root grid; when the prompt fills became translucent over a background, the composer's text box, placeholder and Send/Stop button showed through the card and the card's scope hint mixed with the composer footer. The slot is inside InputContainer, so it inherits the composer's conversation width and the side panel's reserved margin, and the composer stays whole underneath. The cards are mutually exclusive because a run waits on one prompt at a time. Showing a card grows the input block and shrinks the transcript row instead of moving the composer. The approval card is bounded so a long prompt cannot take the window: the summary caps at three lines, the command block scrolls past 96 px and the scope hint at two lines.

Session usage panel

Opened from a session row's menu, the panel reports what the session's runs cost: price and token total, one four-segment bar (input, output, cache read, cache write) with a legend, and the runs folded behind a header that opens the per-run ledger. The total counts every model step, and each step re-sends the context, so it is many windows, not one. For the session open in the chat the panel therefore shows "Context now" (the composer meter's reading, ChatView.ContextReadingFor) beside it; any other session shows no current window. The label says "tokens", not "billed": cache reads are the cheap part and dominated the figure.

Activity rows

Terminal row details use TerminalActivityCard: the existing row disclosure opens separate monospace command-preview and output areas, with a status dot, reported exit code and Copy action. Horizontal scrolling and selectable text preserve multiline scripts and aligned output. The card opens before any output arrives; missing captured output is labelled explicitly, and clipped output has a notice. AgentActivityItem.Terminal keeps the Host's existing display-safe preview when a completion frame omits detail. Resetting a retried attempt clears only captured output and preserves the disclosure state. Copy carries that card's preview and captured output through the existing handler. This introduces no raw-argument fetch, execution path, context-meter change or new activity-grouping policy. This card is the only place streamed command output appears: there is no separate docked terminal panel above the composer.

Each row of the detailed timeline is one line built from three parts. The verb stays the named label (AgentActivityText, ThinkingLabel or EditPreviewLabel) that the running sweep and settled tone find by name; ActivityRowGlyph puts the kind's glyph before it (danger or warning when the row failed or waits), and ActivityRowTail puts the subject, a mono tail and an exit N badge after it. The words come from AgentActivityItem.RowVerb, RowSubject and RowMeta; DisplayText remains the whole sentence for tooltips, automation names and the compact summary. Only the subject trims, to whatever width the other parts leave. Rows use TranscriptTypography.ActivityFontSize, which equals the message size; muted ink, not size, sets them apart. ChatMessageItem.UpdateActivityGaps gives each displayed prose slice 12px on the side where an activity row sits.

Compact agent activity

Settings › Agent activity offers a two-part Verbose / Compact choice (SettingsView.ActivityStyle.cs) rather than an on/off switch, so neither style reads as "off". Compact (one grouped process line per turn) is the default for a new install; an existing preference file keeps the user's last choice. The device-local Ru/activity-display.json preference applies to open transcripts and newly loaded messages; it does not enter backend settings, model context, durable activity records or execution policy.

Verbose still streams every row while a turn runs, then auto-collapses that turn once it has an answer and no row remains running or waiting. A failed turn without an answer stays expanded so the failure is visible without a click; expanding a collapsed turn is per-message and survives new activity.

Each assistant message with activity gets one quiet disclosure line in compact mode, with no surface or border of its own. A finished turn reads as a sentence of its three most frequent kinds of work, ranked by count with ties in first-appearance order and no counts ("Edited files, ran commands and read files", "… and more" past three); thinking, status and narration rows do not rank. A live turn shows the running activity's own text under a sweeping shimmer (off when Windows animations are off), holds each title at least 150 ms so fast tool bursts do not flicker, and ends in an elapsed clock measured from the reply's creation. Failures and waits add a tail ("waiting for you · 1 failed") and tint the line warning or danger. The leading glyph names the main kind of work and turns into the disclosure chevron on hover, keyboard focus or while open. No total duration is shown for a finished turn, because the transcript does not record when a turn ended. The reply text after the last activity row stays visible; narration written between rows folds into the line with those rows instead of stacking under it. A settled turn that ended on a row shows its last prose. Expanding the line restores the original interleaved text/activity timeline; collapsing reuses the same live text objects. The legacy replay layout uses the same disclosure. Expansion is per message and is not reset when more activity arrives. Existing approval/question surfaces and file-change summaries stay outside this disclosure.

AgentActivitySummaryProjection owns counts/status wording; the native summary control coalesces updates, follows item changes, stops its timer and releases subscriptions on unload. ChatMessageItem.ActivityDisplay keeps the text-only projection, using incremental appends for live segments. The disclosure uses a keyboard-operable button with an accessible action and expanded/collapsed status; it adds no motion. The stored preference is bounded and written atomically; absent/invalid preferences fall back to detailed mode.

Customize page

Customize, directly under New Chat in the sidebar, opens a page in place of the chat (ShellDestination.Customize); selecting a session or New Chat returns to the chat, and /skills typed in the composer opens it. The composer carries no skills button. Typing / in the composer opens a slash menu (ComposerSlashCommands, ChatView.SlashCommands.cs): up to eight .ru/commands/*.md templates from the workspace and the user profile, then /skills. It is a non-light-dismiss Popup, so focus stays in the text box; arrow keys move, Tab or Enter completes, Escape closes, and it closes at the first space. Send and queue both expand a typed custom command into its prompt in the composer before the draft is snapshotted, so the prompt-limit check, the transcript and the Agent see the same text. skill and skills are reserved names a template cannot replace. The page has three tabs:

  • Skills lists the active workspace's catalog through SkillsApiClient, with search, reload, an enable switch per skill, automatic-selection in each row's menu, and adding or removing local skill folders. Use in chat goes back to the open chat with /skill <id> in the composer (ChatView.InsertSkillCommand). Before a chat has a workspace, it lists user-level skills without creating a scratch session or borrowing another project's roots/preferences. Search, reload and Use in chat work there; changing availability and Add require an explicit workspace, with the corresponding controls disabled until it exists.
  • Plugins holds computer use (ADR 0031), moved out of Settings. The switch saves the Host setting and reverts when the save fails; it applies to new runs.
  • Instructions edits the user's own instruction files directly, not through the Host: %USERPROFILE%\.ru\AGENTS.md (all projects) and <workspace>\.ru\AGENTS.md (the open chat's workspace; disabled without one). The project's shared root AGENTS.md, CONTEXT.md and .ru/CONTEXT.md are listed read-only with their presence. InstructionFileStore normalizes the text box's line breaks to \n, writes UTF-8 without a BOM through a temporary file and a replace, and refuses text over the Host's 64 KiB per-file limit (RuInstructionLoader), a file or folder that is a link, and a file whose stamp changed since it was read unless the user confirms the overwrite. The Host reads these files when it composes each prompt, so a save applies from the next message.

The page reloads both tabs each time it is shown. CustomizeSkillsLoader owns the visible skill snapshot, loading/error feedback and cancellation. It also reloads when an open page is rebound to a reconnected Host, or the chat's workspace becomes available or changes. The native Loaded handler reapplies the current snapshot after the navigation transition attaches the page. A refresh keeps the current workspace's rows visible; a workspace change clears them. Hidden or superseded responses cannot replace the current snapshot, and a failed refresh preserves its rows for retry. An initial read without rows shows four static skeleton rows inside the Skills region; a refresh with existing rows keeps those rows visible instead. The heading, tabs and toolbar remain outside the skeleton. Completion or failure removes the placeholders, including when reading the user library without a workspace. Loading/error status is a polite live region; the placeholders are noninteractive, excluded from accessibility content, and add no animation or minimum loading delay. Plugin settings reads likewise check the current activation and backend before applying; a failed read preserves the last toggle state rather than treating it as off.

Notifications

MainWindow.Notifications tells the user about runs while Ru is in the background (minimized, or another window in front): a taskbar flash (FlashWindowEx), the Windows notification sound, and optionally a Windows App SDK app notification whose click opens the session after checking it is listed. AgentNotificationPolicy is the pure rule set: a finish is a live non-terminal-to-terminal transition of one run (completed, or failed/interrupted as "stopped"; a user cancelled is silent); approvals and questions notify once per id, and waits replayed within three seconds of a run appearing are marked seen instead. The open session is observed through its AgentRunController; other sessions only report a finish when the polled session list sees IsAgentRunning go from true to false. Text is the session title only, never the prompt or ask_user question, since banners can reach the lock screen. NotificationPreferenceStore keeps the choices in %LOCALAPPDATA%\Ru\notifications.json (defaults: both events, flash and sound on; Windows notifications off). Turning Windows notifications on calls AppNotificationManager.Register(), which registers the unpackaged app for the current user; turning them off calls Unregister(). The installer does not unregister on uninstall.

Appearance customization

Settings > Appearance holds the user's look-and-feel choices. They are local GUI preferences in %LOCALAPPDATA%\Ru\appearance.json (AppearancePreferenceStore), kept apart from ui-preferences.json because that store rewrites its file with the theme alone. Nothing here reaches the Host or the Broker. AppearanceState is the single live copy: Settings writes through it, every change is saved at once, and MainWindow repaints on its Changed event. AppearancePreferences.Sanitized is the one gate for loaded and imported values: unknown enum values, malformed colors, font names that look like paths or URIs, and background names Ru did not generate fall back to defaults.

  • Background. A picked image or video is copied by AppearanceMediaFiles into %LOCALAPPDATA%\Ru\backgrounds under a generated name (32 hex digits plus the extension); the preferences store only that name, never the source path. Images are capped at 40 MB and videos at 300 MB. AppearanceBackdrop sits under the whole shell with a scrim of the theme canvas at the chosen panel opacity (30-100 %). Only the two root canvases (RuBackdropCanvasBrush on the chat root and the docked side panel, RuBackdropSidebarBrush on the sidebar) become transparent, and the same panel opacity lowers the fills that sit on them: RuBackdropSurfaceBrush (composer, task shelf, side summary card and tabs, message bubbles, terminal and changes cards, approval, question and trust prompts, markdown code blocks and table headers), RuBackdropInsetBrush (the canvas-toned insets inside those) and RuBackdropCodeBrush (file edit previews). The side panel keeps the opaque canvas when it is fullscreen or overlays the chat in a narrow window, since it covers the transcript there. Popups, menus and other cards keep their opaque brushes, and without a background everything is opaque. A video plays muted and looped, pauses while the window is hidden, and holds still when Windows animations are off. A file that fails to decode clears the background.
  • Colors. Overrides are stored per base theme (lightColors, darkColors; Dark and Meteor Shower share the dark set) as #RRGGBB. AppearancePalette.Build lays them over the theme pack, derives the colors the user did not pick, and applies a contrast floor: text at 4.5:1 against canvas, cards and sidebar, secondary text and accent at 3:1 against the canvas. The result is written through RuThemePalettes.Apply(theme, palette), so the theme toggle, title bar and Meteor backdrop still key off the UiTheme enum.
  • Fonts and corners. AppearanceResources.ApplyAtStartup replaces RuUiFontFamily, RuDisplayFontFamily, RuMonoFontFamily and the corner tokens before the first window is built, because XAML reads them with StaticResource. App.xaml styles that already resolved a stock value are swapped for derived styles (BasedOn) rather than edited, since a sealed setter throws inside the XAML runtime. These two apply on the next launch; Settings says so while a restart is pending. A failure here is logged and Ru starts with the stock look.
  • Layout. The sidebar can sit on either edge: MainWindow.ApplySidebarSide reorders the shell columns and mirrors the sidebar's asymmetric radius. The sidebar edge then follows the input on either side: pointer drags, the splitter's arrow keys and Ctrl+Left/Right all flip with it. It applies live.
  • Theme files and reset. Export writes colors, fonts and layout to JSON without the background. Import treats the file as untrusted: size-capped, sanitized, and it never changes the background or panel opacity. Reset (Settings, or "Reset appearance" in the command palette) returns to the stock look and prunes stored background files.

Elements that paint with brushes looked up in code-behind keep the colors they resolved to until they repaint; the Settings rail re-highlights on every appearance change.

Custom model API editor

Settings › Providers › "Add custom model API" opens CustomProviderEditorView (view model CustomProviderEditorViewModel) for a named custom provider (ADR 0034): Provider ID (fixed once saved), display name, base URL, API protocol (OpenAI Chat Completions or Anthropic Messages), API key and the model list with optional context windows. CustomProviderPolicy mirrors the Host's rules so the editor can name the first wrong field and warn before a key would go over plain http:// to another computer; the Host still validates every save. A save replaces the whole custom_providers list and may store one provider's key in the same request. "Fetch available models" saves first, then lists what the server serves; adding from that list fills the model's context window. Delete removes the key before the definition, so no orphaned secret remains. Saved providers appear in "Your providers" and as their own groups in the composer's model picker; the legacy Custom OpenAI slot stays listed as "(legacy)" while configured.

Presentation ownership

WinUI-independent presenters own settings load generations and save ordering, provider-list decisions, attachment admission, model selection, history actions, activity identity/order, and sidebar projection/drop decisions. The views bind their results and retain native controls, timers, dispatcher effects and scrolling. SessionHistoryPresenter serializes approval, input and rewind workflows and suppresses feedback after session ownership changes. AgentRunController keeps HTTP/SSE ownership; its approval/input coordinators capture request identities, and its delta deduplicator owns delivered-frame/reset tracking.

View models

Views are moving to CommunityToolkit.Mvvm view models under gui-winui3/ViewModels, one surface at a time. Settings, the sidebar, the MainWindow shell, and the chat's model picker, run panel, composer and permission preset have moved; the transcript load, run adoption and activity feed in ChatView have not. A view model owns a surface's state and decisions, reaches the Host through a narrow interface (for example ISettingsBackend and IProviderCatalogSession), and receives a dispatch delegate for cross-thread updates instead of touching DispatcherQueue. It exposes strings, booleans and collections only; the view maps tones to brushes and glyphs through x:Bind functions and keeps flyouts, measurement and composition effects. SettingsViewModel owns the provider picker, credentials, autosave, key probe, sign-out and connection test. A credential stays in a key property only until it is saved, validated or removed. Every provider-dependent value (label, key rows, sign-out) is derived in one place from the current choice, so resolving an unset or legacy stored choice cannot leave a stale label or a hidden key row. The Models overview lists configured providers rather than exposing the active provider form on entry. Add Provider uses the searchable, virtualized catalog without its custom row; Add custom Provider opens the existing OpenAI-compatible endpoint directly. Edit opens the same inline editor. Its Back action flushes pending settings/key validation before returning; failed saves or rejected keys stay in the editor. Stored-key status does not imply a successful connection test. The custom endpoint remains the single existing custom configuration; model selection stays in the chat composer. Provider management state lives in SettingsViewModel.Providers.cs, without adding a backend route or credential store. Existing legacy credentials remain listed under their original identity; editing them does not replace them with a Models.dev provider. New credentials use the catalog flow. Back navigation restores keyboard focus to Add Provider. SessionSidebarViewModel owns the sidebar's session list (server rows merged in place with local drafts), workspace grouping, pins, manual organization, refresh and the create, select and delete workflows. MainWindow keeps native list selection, drag visuals, title waves and dialogs; it re-syncs selection on Rendered and supplies the delete confirmations through ISessionDeletionPrompts. A delete removes the row as soon as the Host confirms it, then refreshes with RefreshLatestAsync, which supersedes a poll that may hold the pre-delete list. The workspace sidebar uses the paged Host listing without a dedicated search box, Load more sessions button or pagination notice. Host title/message search and cursor-based pagination remain available through the backend. Group expansion, pins, drag ordering and active-session visibility stay in its projection. There is no separate current-workspace filter. Chat history opens at a bounded newest page; Load earlier messages prepends older rows with absolute indices and preserves the visible scroll anchor. Generation/session checks reject late responses after switching chats, and rewind invalidates obsolete history cursors. Workspaces, Recents and CLI Sessions headings pair their labels with decorative grid, history and minimal terminal-prompt icons; the labels and existing controls remain the accessible interaction targets. List rows are named for UI Automation by their data object's ToString(): a session reads as its title, sidebar headings as their label, and a transcript message as the speaker plus at most 120 characters of its text. These strings are accessibility names only and are never written to logs. Clicking the already-selected session (ItemClick, since SelectionChanged does not fire for it) returns to Chat from Customize or another page without reopening the session. A chat in a Host-confirmed scratch workspace (workspace_kind == "scratch", carried from the session row or the created run, never inferred from the path) shows no folder name in the header breadcrumb, the welcome workspace row or the Customize subtitle. The Settings modal scales from 880×560 up to 1040×720 with the window and always fits its margins. SidebarLayoutState owns one expanded width in the 220–360 px range for every window tier. The workspace-sidebar toggle at the far left of the title bar hides it completely and restores its last width. Back and Forward buttons beside it replay a NavigationHistory<NavLocation> (screen plus chat session, 50 entries): ApplyNavigation and the chat SessionOpened event record each visit, a history move sets _applyingHistory so it does not record itself, and MainWindow.History.cs skips and forgets sessions that no longer exist. MainWindow.SidebarLayout.cs handles pointer identity, capture cancellation and width presentation; the focusable splitter exposes RangeValue, arrows and Home/End. Ctrl+Left/Right uses the same bounds; double-click resets to 250 px. The splitter has a real 10 px layout column and transparent hit surface, with no visible divider in idle, hover or drag states. The native resize cursor and keyboard focus indicator remain available. A 1 px column with negative margins clips a UserControl's pointer target. The removed Starry Night preference resolves to plain Dark; only Light, Dark and Meteor Shower remain selectable. Settings navigation scrolls horizontally in narrow mode and vertically in the wide sidebar; category buttons can grow with text scaling. The command palette uses a 620 px maximum width, safe viewport margins and a height bounded by the overlay. Composer remove controls have 28 px pointer targets. Send/Stop updates its visible glyph and accessible name synchronously with the run state, without a deferred content-swap animation. Light warning text uses the same readable semantic color in the startup resources and runtime palette. ChatModelPickerViewModel owns the chat's model and reasoning selection: the grouped catalog subscription, debounced picker search, model save (a failed save is reported on the composer, not swallowed) and the effort options for the selected model. AgentRunPanelViewModel owns the composer's run surface: the status line, Stop, the send/stop face and placeholder, the approval and question cards, and the one-prompt-per-run workspace-trust guard. Its rules stay in AgentInlinePanelPolicy; it raises ApprovalArrived and QuestionArrived once per prompt id, so the view moves keyboard focus only on a new prompt, and a composer-local message (a rejected file, a queue notice) outlives run refreshes until it is cleared. ChatView still projects the controller into the panel's input and keeps animation, scrolling and the trust dialog itself. The trust dialog names the folder from the Host's session record (or the exact path sent when the run was created), never the composer's current default, and WorkspaceTrustPromptPolicy adds a plain note when that folder is a drive root or the user profile. Waiting feed rows take their headline from AgentWaitPresentation; an explained code moves to the row's tooltip and an unknown one stays on the row. ChatComposerViewModel owns the composer's unsent content: attachments, the per-session draft (ComposerDraftStore), the turn queue and its strip state, and the effective prompt that inlines text attachments. The text box stays the live source of the typed text, because WinUI raises TextChanged after an edit: methods that compare or save text take the box's current value, so text typed while a send awaits the Host is never cleared by that send. The view model writes text back only through TextReplaced (restore and clear), never through a two-way binding. The text box wraps long lines to the composer's width and scrolls only vertically. It grows with its content up to ComposerInputHeightPolicy: 35% of the chat view's height, between 180 and 480 px, re-applied on resize, so a long prompt is read in a window that follows the app's size rather than a fixed eight-line slot. The composed prompt (typed text plus every inlined document) is checked against AgentRunLimits.MaxPromptChars (200,000 characters, shared with the Host and the terminal) before the send and before a turn is queued; an oversized prompt stays in the composer with a named status instead of failing the Host's create call. Picker, drop and clipboard images share the same bounded preparation path.

Any file can be attached (ADR 0053). Small UTF-8 text/code files (at most 8 KiB) are inlined, and an image goes to a model that reads images as an image. Every other file, of any type or size, is attached as a workspace reference: the prompt names its relative path and the agent reads it with read, which extracts PDF, Office and OpenDocument text and tells the model how to open anything else. A file outside the workspace is first copied into <workspace>\.ru\attachments (AttachmentStaging, shared with the terminal; ignored by git through the folder's own .gitignore, at most 64 MiB, equal bytes reuse a copy), and removing its chip before Send deletes the copy. An image attached for a model that reads no images is sent by path too. Text that is not UTF-8 (nor UTF-16 with a byte-order mark) or holds a NUL byte is sent by path instead of being inlined as replacement characters (TextAttachmentDecoder). A new chat with no folder has nowhere to copy a file, so it keeps the local path: PDF/Office documents are extracted to bounded plain text (AttachmentDocumentExtractor, at most half the prompt bound), text is inlined, and other types are refused with a status that says to choose a folder; a document whose extraction cannot fit the prompt is refused at intake, and switching session cancels a running extraction. An image that needs no resize still loses its EXIF/XMP/text metadata (ImageMetadata); a JPEG whose EXIF rotates it is re-encoded upright instead. Chips decode a 280 px thumbnail; the preview dialog decodes the stored image at full size only while it is open. When the Host's catalog says the selected model reads no images (accepts_images: false), attaching an image says so at once. The workspace reference envelope is parsed back into a file chip when history is reopened. Folders themselves are not attached; dropping one says to drop its files. Signature detection reads the supplied stream directly and leaves it open for the decoder; adapters over managed byte streams do not support cloned substreams. Intake failures appear above the composer only while the originating session and generation still own the operation. Sent user messages keep image/file attachments in a separate right-aligned row above the text bubble. Only the typed text receives the bubble background; attachment-only messages show no empty bubble. Overflow attachments can scroll horizontally within the reading column, and message copy/rewind remains on the group. SessionPresetViewModel owns the chat's permission preset and the cached version of the Host's stored selection. Only two rules narrow it: Full Access does not follow the user into a session it was not stored for, and a declined Full Access confirmation falls back to Standard. Opening a session adopts the stored selection (read only, best effort, dropped if the session changed meanwhile) and seeds the version cache, so the next send does not rewrite it; the cached version is reused only while the stored preset still matches the user's choice, so choosing a different preset after adoption writes it instead of sending a stale pin. A write that completes after a switch fails as session_changed. An unknown stored value reads as Standard. Transcript loading, run adoption and the activity feed remain in ChatView partials and their presenters. ShellViewModel owns the window shell's state and decisions. Startup resolves the project root and publishes it before it starts the Host, so the sidebar's section chrome never waits for the Host. It owns the status line, which has one writer: startup, health, a Host exit and failed session actions all report through it, and the view maps its tone to a brush. A Host exit stops the window's polls; a Host exit or an unreachable health poll starts one reconnect loop (every three seconds, each attempt bounded to six), never before the first start succeeded, for a harness run or for a closed window. A Host that comes back is rebound through IShellBackend.RebindAsync even if a later step fails, so the retries stop. Navigation resolves through ShellRoutePolicy; every Chat navigation keeps catalog polling on and reloads models, including one to the chat already showing. Settings shows the chat's preset, read again on every open because the chat can narrow Full Access without an event; an adopted preset repaints Settings only while its session is still active, and a preset chosen in Settings is applied to the chat. A settings save invalidates the catalogs and only the newest provider-selection reload applies. The view model also owns the theme choice and its persistence, the title bar's update entry and the command palette's side-panel state. MainWindow keeps windowing, the title-bar region, the composition of the Host-bound services and views, dialogs, layout and every animation. HostShellBackend resolves the API service, health service and catalog controllers per call, because a reconnect replaces them. NavigationContentSwap owns pending view replacements, including cancellation when the user returns to the already mounted page before an outgoing fade finishes. Every navigation supersedes the previous one; window close rejects pending mounts. UiMotion reacquires the host's composition visual after mounting content and restores its visible state if mounting or starting the fade-in throws. The existing completion handler still reports that error; it cannot leave the whole page at zero opacity. Reduced motion continues to apply the same content swap immediately. CommandPaletteViewModel ranks the shell's commands and sessions for the palette (Ctrl+K): characters must match in order, word starts outrank inner matches, and a command that cannot run now is left out. The shell builds the list on each open, and every entry calls an existing handler (a permission change goes through ShellViewModel.ChoosePresetInSettings, the Settings path). Shortcuts live in KeyboardShortcutCatalog, which the shell's key handler, the palette hints and the shortcuts sheet share; the composer still carries no permission control. ApprovalRulesViewModel backs Settings → Permissions (remembered approvals) through IApprovalRulesClient (implemented by the run client adapter over GET/DELETE /agent/v1/policies): it reads global rules once and project rules per workspace the user has sessions in, keeps its rows when a read fails, and only removes rules. ChatComposerViewModel keeps an accepted send until its run starts, so a declined workspace-trust prompt returns the message to the composer instead of losing it. The empty chat links to Models & Providers while ChatModelPickerViewModel.NeedsProviderSetup is true. The composer shows no permission notice; the conversation header reports the preset. ViewModelBindingContractTests checks that each {x:Bind ViewModel.X}, {x:Bind ModelSelection.X}, {x:Bind Composer.X} and {x:Bind Shell.X} names a public member of the bound view model.

Shared activity and permission-preset enums belong to RuAgent.Protocol. Client-side display policy belongs to RuAgent.Client; the GUI has no project reference to the server's RuAgent.Harness.Core domain assembly. Behavioral presenter tests cover ordering, stale completions, failure cleanup and admission; source guards remain appropriate for explicit ownership and native markup.

Transcript and session behavior

Live SSE activity and delta queues retain separate bounded capacities, then merge by publication sequence before delivery. Queue priority must not reorder an activity ahead of preceding prose. The desktop replay builder joins adjacent text entries into one Markdown segment; only intervening activities divide it. Activity labels share transcript typography across plain and detail-toggle headers, including transitions that reveal reasoning or terminal output. Expanded reasoning stretches across the available reading column instead of a fixed left-aligned width. ConversationWidthState owns the centered reading-column width: two transparent grab strips sit 32 px outside its edges, showing only a short grip on hover or drag. The width is session-local: 720 px by default, a 640 px floor and a 920 px hard cap. Shrinking the window clamps the rendered width; growing it restores the reader's preferred width up to the cap. Restarting the app returns to 720 px. The user bubble, attachments and assistant column all bind to the same width; the composer, the prompt cards above it and the welcome hero follow it with a 16 px gutter on each side. TurnProcessDisclosure replaces the plain activity summary for segmented turns: its header reads Working…, Worked for 1m 5s, Took 1m 5s · failed or Worked, and its body animates between the compact answer and the full process. The header uses the compact activity row's visual language — kind glyph, activity type size and a · N steps meta tail — with the glyph turning into the chevron on hover, focus or while open. A closed turn auto-collapses, a click reopens it, and lost content height is re-measured after the binding changes so the fold never flashes an empty frame. The task shelf is a tab tucked under the composer: the composer surface with a hairline on its open sides, rounded on top, its bottom edge hidden beneath the composer. Its header is the disclosure: collapsed it is one quiet line with the current task, then a per-task segmented progress strip (a continuous bar past twelve tasks), done/total count and chevron. Opening the list adds the remaining count and the next task as a second line. The list opens above it with an ordinal, a state mark and the task text per row; the active row carries a quiet tint and semibold text, with no "NOW"/"NEXT" labels. Expanded tasks use a scroll viewport capped at 224 pixels and one quarter of the chat height (64-pixel minimum). The shelf clears as soon as its last task completes; it never keeps a completion summary. Opening the drawer grows and fades it in over 160 milliseconds (120 to close); segments cross-fade, the active segment breathes while a run is live, and an advancing row's tint and marks cross-fade. Every transition applies instantly when Windows animations are off. Incoming activity data and session replay own its current plan; realizing or recycling a transcript row cannot update it. Routine run/model-step status stays in the transcript; the composer feedback row is for actionable failures, waiting states and local input feedback. Shell policy contexts retain the selected runtime and exact invocation for approval matching; nonempty shell argv allow rules use literal, case-sensitive whole invocations, so script wildcards cannot widen a remembered permission. Deny and ask rules retain pattern matching.

Markdown headings scale from the selected body size: H1 adds 6px, H2 4px, H3 2px and H4 1px; H5/H6 retain body size. Semibold weight and heading-specific line height distinguish sections while keeping wrapped titles readable.

Markdown embedded code/table frames track the available reading-column width without reparsing on resize. Code preserves line boundaries with horizontal scrolling; wide tables scroll within the column. Plain table-cell extraction walks nested inline containers so emphasis and link labels survive display and TSV copy. Rich-block layout lives in MarkdownBlock.RichBlocks.cs, separate from prose and inline rendering. MarkdownRenderPlan identifies unchanged blocks, including resolved reference links; MarkdownBlock.Rendering.cs retains their native paragraphs and embedded controls and replaces only the changed suffix. Code/list indentation and hard breaks survive normalization. Nested list blocks keep their own Paragraph and InlineUIContainer ownership rather than reparenting attached inlines. Large tables render at most 50 rows (including the header) and eight columns; the preview states its visible and total counts. Copy and the full-table dialog use the complete TSV content. Edit activity previews use Protocol's bounded AgentEditPreviewCodec (@@json plus a two-string JSON array), preserving literal backslashes and delimiters. The live publisher redacts decoded values before re-encoding; the GUI also reads legacy @@ old ==> new session details.

GUI conversation ownership lives in the WinUI-independent ChatSessionPresentation. It detaches the outgoing event feed, retains its composer draft, then activates only the latest requested session. Activation cancels the previous history load; monitor callbacks and turn completion are scoped to the active session/turn. AgentRunController retains HTTP/SSE run ownership, while ChatView renders history, activities and scroll effects. Switching sessions never posts cancellation for an acknowledged run. The Host keeps executing and reopening adopts the newest non-terminal run. A switch waits for an in-flight create acknowledgement before detaching; unknown create outcomes retain the pinned request identity and block the switch until reconciliation. Explicit Stop still reconciles and cancels through the existing command path. For existing sessions, while incoming history and durable activities load, the view suspends pending feed timers without clearing or settling the outgoing message graph. Once the latest load is ready, it clears the old activity registry and replaces history in the same dispatcher turn. The transcript explicitly has no item-container transitions, so a bulk reset cannot animate every removed/added row. Sends and rewind are ignored during loading, and load errors replace rather than append to the outgoing history. Superseded loads cannot reset the new load's state. Opening positions the last row synchronously after flushing replacement layout, before yielding for further I/O or first paint. ItemsStackPanel switches from KeepScrollOffset to KeepLastItemInView for that jump, preserving the actual last row as virtualized height estimates change without a ViewChanged event. Pointer and scroll-key input restore KeepScrollOffset and invalidate deferred follow work. A guarded, constant-work LayoutUpdated handler anchors measured tail geometry, covering nested activity templates that complete after the first positioning pass. It never forces recursive layout or polls a timer, and detaches on disposal. All programmatic follow scrolls are unanimated: a native animation can otherwise outlive the layout/session it targeted. Reader scrolling resumes follow only at the actual bottom, after intermediate view changes finish, rather than anywhere inside streaming's 100-pixel proximity allowance. A message a send just added live carries ChatMessageItem.ArrivesLive; its container plays one UiMotion.Enter when first realized and clears the flag, so history loads, reconciles and recycled rows never animate. The approval and question cards enter the same way when they appear. Sidebar session rows fade hover/press/selection layers over 140 ms instead of swapping brushes. The composer carries a 1 px hairline that fades to the muted ink while its text box has focus (ChatView.ComposerFocus.cs). Activity row attachment only binds typography, status and live announcements; it does not fade or translate the row. Visual realization/recycling is not a new agent event. Running label sweeps still respect the OS animation setting. The shell renders sidebar sections and persisted workspace pins before Host startup, independently of session polling. An unchanged poll retains rendered rows, but rebuilds them if the sidebar has not been populated. /sessions adds is_agent_running, resolved for the bounded requested session set through the existing active-session SQLite index. Working-state changes notify existing session rows without changing their layout fingerprint. The sidebar's color wave shares one timer across realized running titles and releases row subscriptions on recycling/window close; reduced motion uses a static tint and the Running accessibility label remains available. Windows animation preference changes are dispatched to the window and refresh that static/animated state without restarting Ru. Windows builds before 19041 use a one-second preference poll because they lack the change event. Window close releases both the OS subscription and the fallback timer. Right-side panel transitions snapshot the presented opacity/translation before stopping a storyboard, so a visibility reversal retargets from its current frame. Session reset still cancels transitions and restores the neutral visual state. AgentReplyAccumulator is the view's sole reply-delta deduplication owner; rebinding the same run preserves delivered-frame and reset identities. Retries truncate only the failed model step's text, preserving earlier steps; snapshots carry the reset offset so frozen slices and activity split offsets discard superseded prose even when reset and replacement deltas coalesce. Live transcript activity insertion drains both pending deltas and the deferred 100 ms text render before AgentLiveSegmentBuilder freezes text at its received end. Queued earlier activities are drained before later text is accepted. Frozen slices settle Markdown once; only the next tail remains live. No line/word heuristic moves sentence suffixes across activity rows. Activity grouping computes visibility, folded durations and repeated details before publishing final values, keeping unchanged rows stable across refreshes. Activity headers keep short tool context on the same line, with bounded labels and metadata and ellipsis for overflow. Tooltips retain the full text; expanded thinking, diffs and terminal output remain separate blocks. Session reopen and end-of-turn reload share SessionTranscriptBuilder, joining messages and activity replay by the persisted source_run_id. A run without a saved assistant message gets its own bubble after its user turn, never an older turn's bubble. Replay preserves the saved final answer when payload reads omit it. Legacy messages without run identities permit ordinal replay only when the message/run counts match; unbalanced histories retain prose without guessing. A same-session reload (end of turn, rewind, paging refresh) merges the rebuilt rows into the bound transcript with TranscriptReconciler instead of a reset: a row that renders the same keeps its instance and container, a locally sent row adopts its durable identity, the streamed reply keeps its segments when the history holds the same text, and only changed rows are replaced. A reset re-created every container and painted the transcript's top before its scroll returned. Opening another session still replaces the list in one reset. The transcript ListView sets ShowsScrollingPlaceholders="False": with placeholders, a reset prepared empty rows at the item minimum height and expanded their templates on later frames, so the opened session grew and jumped under the reader. Lists inside a row use a plain StackPanel rather than a nested virtualizing panel. The side panel and task shelf of the incoming session are laid out in the dispatcher turn that replaces the rows, so the outgoing rows never reflow first. Persisted transcript rows retain their raw server message index independently of hidden or synthetic display rows. Rewind uses that index, then reloads only while the requesting session still owns the view, without restoring live text removed by the rewind. Synthetic rows cannot be rewind targets. Queued turns remain queued until the Host's acceptance callback, including pre-accept errors. The GUI right-side surface keeps its floating session summary and adjacent details panel; narrow windows temporarily hide it without replacing session mode, active tab or fullscreen selection. A tab menu opens or reopens every view. Changes joins replayed message activities with the live run by activity identity; unchanged diff rows retain expansion state. Visibility storyboards are owned and cancelled when superseded. Background tasks offer an explicit refresh action and refresh every two seconds while the surface is visible and the run or a background process is active. Their optional command metadata is bounded and credential-redacted by the existing terminal redactor before retention; it does not change execution authority. GUI task refreshes bind completion to session generation, the selected run and newest request. Interactive-terminal output/exit callbacks carry shell lifetime versions; workspace replacement and shutdown invalidate queued callbacks. Model selection settings saves are serialized, skipping superseded queued choices and publishing only the newest result. These UI ownership guards do not change execution policy. Reasoning saves likewise serialize writes; the latest edit alone settles the label, with the last successful write as its failure fallback. Settings preserves hidden provider fields on load, stacks labels and controls below 840 pixels of modal width, and confines keyboard navigation to the open modal. ProviderKeyProbe owns each Settings editor's candidate-key generation, single-flight request and cancellation, independently of WinUI. Key edits, provider changes and backend replacement invalidate the request; disposal suppresses both its verdict and retries. The view owns debounce timing and renders only the current completion. The authenticated Host still validates and stores the candidate atomically; this coordinator never writes credentials. The box is trimmed before it is sent. A verified key clears the box. An unchecked save (provider_key_unchecked: the provider cannot tell keys apart before use) keeps the text in the box and records it as saved, so finishing a hand-typed key re-saves all of it, Back does not treat the saved text as a pending edit, and changing provider clears it. provider_key_malformed and provider_key_too_long are phrased in the key status. The Custom OpenAI key box follows the same pattern: the settings autosave never carries the key; a quiet box saves the URL, then sends the key alone to the checked key route, and Back flushes a pending key the same way. The custom provider editor saves the definition, then the key through that route, so a refused key leaves the definition saved and the editor open. The provider overview words each stored key from provider_key_status (ProviderKeyStatusText). Provider inputs are disabled during Back's save/reload operation, so a late load cannot overwrite a newly edited value. The TUI keeps raw Markdown lines until completion and projects semantic TranscriptLine/TranscriptRun records directly to Terminal.Gui through ITranscriptPresentationWriter. Row roles are explicit. Markdown previews, completed lines, reply replacement, activity updates, notices and turn outcomes do not serialize through ANSI or infer roles from glyphs. Shared Markdown recognizers and code tokens feed both the direct presentation path and the sequential text serializer. Preview parsing runs at frame cadence; completed code lines remain intact for viewport reflow. Plain output commits at newline or Flush. TgTranscriptWriter retains TextWriter/ANSI import adapters for command reports, diagnostics and existing callers. The native transcript path uses its typed API; Terminal.Gui owns layout, focus, input, scrolling and drawing. Native tool-row appearance and the current controls are retained rather than replacing the whole history with a Markdown view that reparses on every update. Windows initializes Terminal.Gui's .NET console driver: the 2.5 ANSI reader decodes each input packet separately and can corrupt split Unicode scalars. Bracketed paste follows the window's active palette, secret prompt or composer; other modals cannot mutate the hidden draft. Final prose rows share the same span decoration path as appended rows. Reply recovery uses the payload's assistanttext kind and utf8text encoding rather than inspecting JSON keys. Headless run/attach detach at the current durable park boundary with exit 2, without cancelling the run. Chat /release checks session ownership and parked status before cancelling, and retains its run identity if cancellation fails. Repeated park guidance remembers at most 64 run reasons and clears on release or a terminal run event. Explicit OpenAI HTTP 429 quota codes end the run immediately; ordinary throttles retain bounded retries. Neither path changes pinned selection. Host single-instance claims bind the physical identity of both data and log directories, including aliases. Directory handles retain those roots for the claim lifetime. Each mutex has a dedicated owner thread until disposal, so async continuations and an exiting caller thread do not abandon ownership. The shared starter probes an owned descriptor again inside its start gate before classifying an occupied port as a foreign Host. Startup is cancellation-scoped, with checks after asynchronous stages before creating subsequent UI services or timers. Host shutdown remains Host-owned.

Conversation header

ChatHeader is the first row of the chat view's root grid, above the reading column, side surface and composer. Its left side is a breadcrumb: the workspace folder's name (full path in the tooltip), then the open session's title, trimmed against the width the other parts leave. After the title a label names the permission preset with the Settings names (Plan, Standard, Full Access) and a dot coloured by risk: info, success and warning. The label is a notice, not a control: the preset changes only in Settings or the command palette. At the far right, a panel toggle hides or restores the session's side surface, with the same enabled state as its command-palette action. Immediately before it, "Working" with a breathing dot shows while a run is live (the dot holds still when animations are off). Title trimming reserves both action columns so neither control is displaced by a long session name. The header follows the transcript's visibility, so the welcome screen has none. The title updates when a session opens and when the open session is titled by its first prompt; the workspace follows the side surface's workspace and each run's resolved folder; the label follows SessionPresetViewModel.Preset.

Message rail

MessageRailControl sits in ChatContentGrid beside, not inside, ChatListView, so it stays put while the transcript scrolls. It draws one tick per loaded message, spaced by index rather than by row geometry, because the list virtualizes and unrealized rows have no trustworthy position. When the ticks do not fit, MessageRailPolicy groups neighbouring messages into one tick. Ticks are shapes on one hit-test surface; the pointer's Y picks the nearest tick. Ticks for the visible message range are brighter, with its last message emphasized most; hovering lifts the tick under the pointer and tapers its neighbours, through a composition scale rather than a relayout. The hover card reads the message's current Content when shown, strips Markdown, and never takes hit tests, so it cannot steal the pointer from the rail. A click stops following output before jumping (the click lands outside the list, so the list's own input hooks never see it) and settles the jump again after layout. MessageRailPolicy.SelectViewport uses both FirstVisibleIndex and LastVisibleIndex. At the actual bottom, including a transcript that fits without scrolling, it emphasizes the final message; the looser follow-output threshold never highlights a still-offscreen tail. LayoutUpdated refreshes the selection after opening, resizing or streaming layout changes even without ViewChanged; both handlers are released on disposal. Unchanged selections do not restyle ticks, and the existing reduced-motion scale policy is preserved. The rail hides below two messages or when the host is narrower than the reading column plus both gutters. Messages not yet paged in from history have no tick until loaded.

Conversation Session

The conversation and history record owned by the Public Host in the shared agent_harness.db SQLite database (ADR-0013). The DELETE /sessions/{sessionId} route removes the session and its owned Harness artifacts only when the application envelope returns status: "ok"; an HTTP success status alone is not deletion proof. The WinUI workspace + creates and opens this record immediately. Its empty row is a UI draft named New Session, visible only while open. Leaving without sending hides the row; the first accepted chat keeps the same session ID and shows a prompt-derived title until durable history supplies the server title. Hiding an empty draft does not delete the Host record. Replacing an unstarted draft publishes one sidebar render, without an intermediate empty section. Workspace expansion state survives that render, and unchanged workspace headers keep their container identity. Sidebar rows use repositioning without overlapping add/delete entrances; changing Windows' animation preference reconfigures these transitions as well as the running indicators. The create response identifies a known-new session: after the existing detach, draft-retention and preset-narrowing steps, it paints an empty transcript and commits the side-panel layout in one dispatcher turn. It skips activation/history, activity replay, usage and run-adoption reads that only apply to existing sessions. Creating a chat while already on the chat screen does not replay navigation's model/catalog refreshes. No previous workspace path is carried into a new no-project draft. Existing-session replay and latest-open cancellation stay intact. The GUI's ChatSessionPresentation owns the active session identity, asynchronous open/load cancellation, run-monitor lifetime and once-per-turn completion. It keeps the latest session click authoritative; WinUI renders the transcript and retains/restores composer drafts through that owner. New GUI sessions without an explicitly selected workspace request a Host-owned scratch workspace; backend startup still uses the application root. Explicit selections, restored sessions and harness workspaces retain their paths. Different sessions can always run in the same workspace in GUI and CLI; one session still owns at most one non-terminal run. Workspace coordination uses shared membership leases with no cap by default; the existing API can set a cap of two or more, and runnable work beyond a cap waits for a lease. The v18-to-v29 upgrade converts legacy exclusive/single-slot coordinators in place while preserving active runs, approvals and workspace trust. Parallel mode cannot be disabled through workspace policy updates. Sessions share real files: this is not a worktree sandbox or automatic conflict merge. Existing file hash checks, external-change detection and per-session execution permissions still apply. The session listing adds is_agent_running from a bounded active-run query. Created, history-waiting and running states animate their sidebar title; terminal and user/approval/trust/reconciliation waits do not. The existing three-second poll updates this flag independently of row layout. Visible title waves share one timer and private cached brushes; unload/close stops them, and Windows reduced motion uses a static tint with the same accessible Running label. The Files tree hides installer-owned payload using ru-install.json and ru-files.lst, including payload-only subfolders. Unknown files and mixed folders remain visible; unreadable or missing inventories leave files visible. This is presentation filtering, not execution permission or filesystem confinement. During history I/O the outgoing transcript stays intact; replacement happens as one collection reset without row entrance/exit transitions. Sends and rewind wait until the current session load finishes. Opening history completes its initial layout and positions the last row in the replacement dispatcher turn. The last row stays anchored as virtualized heights settle; reader scroll input releases that anchor and preserves manual navigation. Follow uses the final row's measured geometry on layout updates, including nested activity replay. Automatic scrolls are unanimated; manual reading near the end does not resume follow until the viewport reaches the actual bottom. Leaving a session detaches the GUI feed without cancelling its Host-owned run; reopening adopts the newest non-terminal run. Only explicit Stop cancels work. An in-flight create must acknowledge before detachment; an unknown outcome keeps its request identity and requires reconciliation before switching. Persisted GUI rows retain the Host's raw message index for rewind independently of hidden history or synthetic activity rows. A rewind result may update only the session that requested it; queued prompts remain local until Host acceptance. Sidebar placement is separate UI state: app-root sessions default to Recents; manual grouping/reordering survives refresh and restart but never changes the Conversation Session's actual working directory or execution permissions. Avoid: treating an HTTP 200 response as a successful delete

Turn change summary

TurnChangesProjection builds a snapshot from one settled assistant message's edit activities. The latest activity identity wins before filtering; only completed edits with a file path count. Paths group case-insensitively with slash normalization, without filesystem access or authority resolution. Counts sum recorded edit operations using 64-bit totals, not a net Git diff; missing or invalid counts display — rather than a false zero. Each file retains its own ordered edit previews and line offsets instead of concatenating unrelated hunks.

TurnChangesSummaryControl sits after the reply text in the assistant template. It hides while streaming or without edits, shows four files initially and expands into a height-bounded, virtualized list. Its compact header places line totals beside the wrapping title, with a 28px icon, a subdued outline and 32px file rows. It observes message/collection changes while loaded and item updates only once settled; unloading releases subscriptions. The existing run-owned transcript replay restores old turns without adopting the next run's edits. The session-wide Changes tab keeps its independent projection: ChangesTabProjection lists completed edits only (failed, denied, waiting and running edits changed nothing and are not listed or counted), one row per file, most recently edited file first. Rows group by the edit's relative_path; an edit made through an absolute path carries only its basename and joins the one relative path with that name when exactly one exists, otherwise it groups by name alone. A row sums its edits' known line counts (— when none reported one), shows "N edits" when there are several, and expands to that file's edits newest first, each with its line, counts and diff, at most 25 per row. A row shows its folder under the name, and its menu opens a preview, reveals the file in File Explorer or copies its path; preview and reveal resolve the relative path against the session workspace and refuse anything outside it, so a bare basename never opens a file. Agent scratch files (.tmp*, tmp_*, _tmp*, ~$*, .bak, .orig, .rej, .swp, .tmp) are hidden behind a header toggle and dimmed when shown; totals still count them. The header carries the file count instead of repeating the tab's name. Edit and write line counts count lines, not line breaks, so a one-line edit reads +1 −1 instead of +0 −0.

Every tab chip shares one shape. The active chip shows its label and close button, and a hovered chip shows its close button too. The mouse wheel over the strip scrolls it sideways, since the strip hides its scrollbar to stay one line tall.

File clicks and View changes raise a navigation request to the owning chat view. The view validates the current session/message and opens the existing right-panel Changes tab. There is no separate turn reader, file picker or back navigation. Clicking a file expands and scrolls to the row holding its latest recorded edit in the normal session list. An older selected edit's file can replace the oldest visible row within the 100-row cap, and the edit itself stays within its row's 25-edit cap; session totals still cover every edit. Live refreshes retain expanded diffs. Explicit turn navigation opens an overlay on narrow windows instead of suppressing the panel. Session reset or tab closure clears the navigation target. It uses recorded data only, with no file writes, new endpoint or permission changes.

Session Side Surface

The WinUI floating summary card and adjacent details panel share session Changes and background-process data. Changes includes replayed and live edits once per activity identity; it is an edit history, not a Git working-tree diff. Background tasks are processes, distinct from the todo plan. Panel mode, active tab and fullscreen selection survive temporary hiding on narrow windows. The interactive terminal is one user-owned shell that follows the selected workspace, restarting on a workspace change; background refreshes do not take input focus. The summary card previews at most three processes, prioritizing running ones, with an explicit action for the complete list. Files and Terminal open from the panel's views menu rather than separate summary-card shortcuts. Its change count names recorded edits, not unique files: activities carry safe basenames, which cannot distinguish identically named files in different folders. The selected panel tab retains its label and close action; inactive tabs keep their icons, tooltips and accessible names. The views menu opens every tab. Ctrl+Tab and Ctrl+Shift+Tab cycle, and Ctrl+W closes, while focus is within the tab strip only; terminal and document keyboard commands keep their own scope. Visibility and body transitions have separate cancellation owners, restore opacity on completion or unload, and respect Windows animation settings. Tab drags observe handled pointer events and release the label button's capture before the chip captures the gesture; an ordinary click keeps its normal action. Files refresh keeps the current rows visible but disables tree interaction while reading. FileTreeSnapshotLoader revisits only expanded branches within the 1,500-row bound and existing directory filters. A failed same-workspace refresh retains the last listing with retry guidance; switching workspace clears it immediately. Individual branch reads check both refresh generation and expansion version, so a collapse/reopen cannot insert an older result. Status messages occupy a separate row from the tree. An unreadable branch retains one collapsible error note rather than appending another on every retry. Background-process refresh has a busy indicator; Stop disables that process's action until the command settles, and duplicate in-flight stops are ignored. BackgroundTaskObservation retains last known task identities through read failures, labels them stale and retries at 4/8/16/30-second intervals while the surface remains visible. An authoritative successful response resets the delay and can establish an empty list; a root/session change drops the old observation. An explicit broker_gateway_unavailable response retains uncertainty without promising endless retries for a completed run; with no live run and no known task the card says "Tasks appear here while a run is active." instead of an unavailable notice, and the Subagents row hides its detail line until there is something to report. Running turns or last-known running tasks still trigger polling; unavailable data is never presented as an empty list. The subagent observer publishes freshness changes even when snapshot identity is unchanged. Card, narrow-window peek and reader share one summary that includes preparations and unavailable attempts. The resize grip exposes a RangeValue automation peer and arrow/Home/End keys; capture loss, cancellation, hiding and unload end the pointer sequence and commit its last clamped width. Avoid: treating the background-task list as the agent's todo plan

File preview

Clicking a file in Files opens the Preview tab. Folders retain their lazy tree behavior. Preview is user-initiated presentation, not a model tool or a second Broker execution path. It adds no Host route, grant or upload service. The preview closes on file/session/workspace changes and app shutdown; switching tabs or collapsing hides the surface. Narrow windows use the reader overlay.

FilePreviewSource opens only a bounded file beneath the selected workspace, rejects hidden credential-name paths and reparse points, checks the opened handle's final path, and holds a read-only handle without write/delete sharing. Documents, PDFs and images have a 64 MiB input cap; text/Markdown have a 1 MiB cap. HTML and SVG are source text, never active browser content. Unsupported formats are refused rather than opened as executable content.

DocumentPreviewControl cancels superseded reads and owns the current result. Windows.Data.Pdf rasterizes one selected page at a time, at most 1600×2400 pixels; page controls and scroll/zoom remain in the panel. Image decoding refuses inputs above 40 megapixels and limits decode width. Markdown uses the existing native presentation stack. Other text shows in a framed code view: a fixed line-number gutter beside unwrapped lines that scroll sideways, colored by CodeHighlighter from the file's extension (CodePreviewModel; above 400,000 characters the text stays plain), and the header names the language and line count.

CodeTheme is the one code palette for chat code blocks, edit diffs and the file preview: keywords, strings, comments (italic), numbers, calls and capitalized type names each take a theme color. CodeHighlighter covers C#, Python, PowerShell, JSON, XML/XAML/HTML, SQL, shell, YAML, diff, JavaScript/TypeScript, the C family, Java/Kotlin, Go, Rust, TOML/INI and CSS; other files stay plain. Edit diffs (FileEditPreviewControl) color each line from its own side of the edit, show a +/− marker, and tint lines only when the edit removes something: an add-only edit (a new file) marks additions with the gutter bar alone.

Office-like documents use the extension's registered Windows preview handler through CLSCTX_LOCAL_SERVER, never an in-process handler DLL or Office editing automation. COM calls run on a dedicated pumping STA and opening has a 15-second UI wait bound. The Windows/Office renderer remains an optional installed component; Ru does not install it or kill a user's Office processes. A stalled renderer can delay its STA cleanup, but it does not block the WinUI dispatcher. The worker bounds queued work; a timeout disables further Office opens with explicit restart feedback, while other preview types remain usable. Non-ZIP OOXML files, packages with missing required parts or over 8192 entries are rejected before invoking Office. Cleanup retains queue admission. A Focus preview action enters the installed document control; native images/PDFs have a Fit action in addition to page navigation and scroll/zoom. An owned borderless native host tracks the preview rectangle and hides for inactive tabs, closed surfaces, other foreground apps, XAML menus/dialogs and the prompt slot above the composer. It has its own DWM surface because PowerPoint's DirectComposition rendering does not paint correctly in a child of WinUI's no-redirection HWND. A cached 100 ms visibility observer runs only while an Office surface is selected; it restores the preview after popup closure even when XAML layout does not change. Showing and positioning never activate the host or raise the main window. Tab/Escape from the handler returns focus to the preview header. Ordinary tooltips do not blank the document surface. Renderer availability and fidelity depend on the installed handler. These presentation bounds do not claim OS-level confinement of third-party renderers. See ADR 0024.

Run and update lifecycle owners

AgentRunController exposes the existing run API, with lifecycle, feed and approval/input responsibilities in focused files. AgentRunFeedState owns stream deduplication, terminal status and lifetime drop counters; changing run ownership resets feed identity without losing controller-lifetime counters. UpdateAvailabilityMonitor owns immediate/periodic update checks, a bounded request deadline, single-flight execution and cancellation. A callback that ignores cancellation retains its flight slot until it exits; stopping the view never waits indefinitely for it. Expected and unexpected errors reach the view's reporter. Behavioral tests cover timing, stop, ignored cancellation and retries; source checks retain UI wiring rather than implementation statement spelling.