Skip to content

Commit bf21e7b

Browse files
RBridCopilotshanselman
authored
Fix native chat UI bugs in tray app
* Fix native chat UI bugs in tray app Three bugs in the WinUI 3 native chat timeline: 1. Collapsed tool-burst groups momentarily expanded each time a new tool started running. The CompactSummary now stays collapsed during in-flight work and surfaces progress via a 'running' chip on the right side that flips to 'done' on completion. BurstIsNestable was widened so the group keeps its collapsed shell while children are still streaming. 2a. User-bubble text selection was invisible against the accent-colored bubble background (white-on-light-blue). User bubbles now paint the selection band with SystemAccentColorDark2 (or the system high-contrast highlight color in HC mode) so the white glyphs remain readable while selected. Brush + AccessibilitySettings instances are cached per DispatcherQueue via ConditionalWeakTable to respect WinRT thread affinity, with in-place Color mutation when the accent changes and a cache reset on HighContrast read failure so a transient COM error isn't sticky. Off-thread callers (tests) fall back to one-shot allocations. 2b. The visible text of a user bubble disappeared after a drag-select + mouse-up triggered a reconciler re-render. Root cause: assigning TextBlock.Text on a selection-enabled TextBlock immediately after a selection gesture left the glyph layer blank until the next focus change. Fix: render the user-bubble body via Inlines (Run) instead of Text, paired with the FunctionalUI ConfigureTextBlock skip-guard that preserves Inlines when the incoming Text is empty. A weak per-element plain-string cache avoids rebuilding Inlines on no-op re-renders. Five rounds of adversarial dual-model (Opus + Codex) review applied. All HIGH-consensus findings addressed; LOW-consensus items either rejected with rationale (BurstIsNestable widening is the intended behavior) or deemed N/A (Clear+Add only affects mutating streams, user bubbles are immutable after send). Validated: ./build.ps1 green, Shared.Tests 1958 passed / 29 skipped, Tray.Tests 843 passed. Co-authored-by: Copilot <[email protected]> * Retrigger CI Co-authored-by: Copilot <[email protected]> * Fix user bubble inline cache guard Avoid returning from the selectable inline cache after WinUI has cleared the TextBlock inlines during a re-render. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent 0a164fc commit bf21e7b

1 file changed

Lines changed: 193 additions & 30 deletions

File tree

‎src/OpenClaw.Tray.WinUI/Chat/OpenClawChatTimeline.cs‎

Lines changed: 193 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,146 @@ private static Element SafeMarkdownText(string? text)
107107
.Set(t => { t.TextWrapping = TextWrapping.Wrap; t.IsTextSelectionEnabled = true; });
108108
}
109109

110+
// Cache plain (non-markdown) text per TextBlock so we can reuse the
111+
// assistant-bubble's Inlines-based render path for user prompts without
112+
// re-clearing/rebuilding the run on every re-render. Going through
113+
// Inlines (instead of the TextBlock.Text property) avoids a WinUI quirk
114+
// where setting Text on a selection-enabled TextBlock during a parent
115+
// re-render that fires immediately after the user finishes selecting can
116+
// leave the glyph layer visually empty until the next focus change.
117+
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<TextBlock, string>
118+
s_plainCache = new();
119+
120+
// Per-DispatcherQueue selection-highlight brushes for the user
121+
// bubble. The bubble background is the user's chosen system accent
122+
// (which may be red, green, purple, …), so a hardcoded color would
123+
// clash whenever the accent is non-blue. SystemAccentColorDark2 is
124+
// the OS-defined "darker shade of the current accent" — guaranteed
125+
// darker than the bubble's AccentFillColorDefault background and
126+
// high-contrast against the bubble's white foreground for every
127+
// accent. In High Contrast the bubble switches to
128+
// SystemColorHighlight (often near-black), so we fall back to the
129+
// OS-guaranteed SystemColorHighlightColor for the band there.
130+
//
131+
// SolidColorBrush is a DependencyObject with thread affinity, so a
132+
// single static instance would crash with RPC_E_WRONG_THREAD if a
133+
// second window on a different dispatcher ever tried to use it.
134+
// Keying by DispatcherQueue keeps one shared brush per window while
135+
// still avoiding per-render allocation. ConditionalWeakTable lets a
136+
// closing window's brush be collected with its dispatcher. The
137+
// brush's Color is mutated in place when the source color changes
138+
// (e.g. user switches their accent in Windows Settings) so
139+
// already-rendered TextBlocks update atomically.
140+
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<
141+
Microsoft.UI.Dispatching.DispatcherQueue, SolidColorBrush> s_accentDarkByDispatcher = new();
142+
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<
143+
Microsoft.UI.Dispatching.DispatcherQueue, SolidColorBrush> s_hcHighlightByDispatcher = new();
144+
// AccessibilitySettings is a WinRT object with DispatcherQueue
145+
// affinity: an instance created on one dispatcher cannot reliably
146+
// be read from another. We deliberately avoid Lazy<>: Lazy
147+
// permanently caches the factory's result, so a single failed
148+
// construction would cache null forever and silently disable the
149+
// High Contrast code path. Per-dispatcher cache keyed by
150+
// ConditionalWeakTable lets each window have its own instance,
151+
// collected when its dispatcher dies. On any thrown exception we
152+
// drop the cached instance so the next render retries from scratch.
153+
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<
154+
Microsoft.UI.Dispatching.DispatcherQueue,
155+
global::Windows.UI.ViewManagement.AccessibilitySettings> s_a11yByDispatcher = new();
156+
157+
private static bool TryDetectHighContrast()
158+
{
159+
var dispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
160+
if (dispatcher is null)
161+
{
162+
// Off-thread caller (tests, design-time). One-shot, no caching.
163+
try { return new global::Windows.UI.ViewManagement.AccessibilitySettings().HighContrast; }
164+
catch { return false; }
165+
}
166+
if (!s_a11yByDispatcher.TryGetValue(dispatcher, out var settings))
167+
{
168+
try
169+
{
170+
settings = new global::Windows.UI.ViewManagement.AccessibilitySettings();
171+
s_a11yByDispatcher.Add(dispatcher, settings);
172+
}
173+
catch { return false; }
174+
}
175+
try { return settings.HighContrast; }
176+
catch
177+
{
178+
// Drop the cached instance so the next call retries.
179+
s_a11yByDispatcher.Remove(dispatcher);
180+
return false;
181+
}
182+
}
183+
184+
private static SolidColorBrush GetUserBubbleSelectionBrush(bool isHighContrast)
185+
{
186+
var dispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
187+
var table = isHighContrast ? s_hcHighlightByDispatcher : s_accentDarkByDispatcher;
188+
var color = isHighContrast
189+
? TryGetThemeColor("SystemColorHighlightColor", Microsoft.UI.Colors.Blue)
190+
: TryGetThemeColor("SystemAccentColorDark2", Microsoft.UI.Colors.DarkBlue);
191+
192+
// No dispatcher means we're being called off-thread (e.g.
193+
// from a unit test). Allocate a one-shot brush — it can't be
194+
// safely cached without a dispatcher to key it on.
195+
if (dispatcher is null)
196+
return new SolidColorBrush(color);
197+
198+
if (!table.TryGetValue(dispatcher, out var brush))
199+
{
200+
brush = new SolidColorBrush(color);
201+
table.Add(dispatcher, brush);
202+
}
203+
else if (brush.Color != color)
204+
{
205+
// Mutate in place rather than reallocating: TextBlocks
206+
// rendered earlier hold a reference to this brush, so
207+
// updating .Color updates them atomically without waiting
208+
// for the next render pass.
209+
brush.Color = color;
210+
}
211+
return brush;
212+
}
213+
214+
private static Color TryGetThemeColor(string key, Color fallback)
215+
{
216+
try
217+
{
218+
var app = Application.Current;
219+
if (app is null) return fallback;
220+
if (app.Resources.TryGetValue(key, out var v))
221+
{
222+
// Theme dictionaries usually store Color, but a custom
223+
// theme override can supply a SolidColorBrush under the
224+
// same key. Accept either rather than silently falling
225+
// back to DarkBlue / Blue when the resource is present
226+
// but wrapped in a brush.
227+
if (v is Color c) return c;
228+
if (v is SolidColorBrush brush) return brush.Color;
229+
}
230+
}
231+
catch { /* resource lookup can throw in unpackaged/test hosts */ }
232+
return fallback;
233+
}
234+
235+
private static void ApplyPlainSelectableInlines(TextBlock textBlock, string? text)
236+
{
237+
var normalized = text ?? string.Empty;
238+
// ConfigureTextBlock may set Text="" and clear Inlines before this
239+
// setter runs again, so only skip when the cached run is still present.
240+
if (textBlock.Inlines.Count > 0
241+
&& s_plainCache.TryGetValue(textBlock, out var cached)
242+
&& cached == normalized)
243+
return;
244+
s_plainCache.AddOrUpdate(textBlock, normalized);
245+
textBlock.Inlines.Clear();
246+
if (normalized.Length > 0)
247+
textBlock.Inlines.Add(new Run { Text = normalized });
248+
}
249+
110250
// Cache parsed markdown text per TextBlock to avoid re-clearing and
111251
// rebuilding Inlines on every re-render when message content is stable.
112252
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<TextBlock, string>
@@ -573,13 +713,7 @@ static Element TimelineInset(Element child, double top = 2, double bottom = 2) =
573713
// High-contrast themes need a thicker border to render at all
574714
// (WinUI guidance: 2px minimum). Detect once at render time so the
575715
// tool card border stays visible when HC is on, normal 1px otherwise.
576-
double toolCardBorderThickness = 1;
577-
try
578-
{
579-
if (new global::Windows.UI.ViewManagement.AccessibilitySettings().HighContrast)
580-
toolCardBorderThickness = 2;
581-
}
582-
catch { /* AccessibilitySettings can throw in unpackaged hosts; default to 1px. */ }
716+
double toolCardBorderThickness = TryDetectHighContrast() ? 2 : 1;
583717

584718
// Avatar: 36×36 circle (Kenny uses circular avatars). Same constructor
585719
// as before but radius defaults to half the size for a perfect circle.
@@ -982,14 +1116,45 @@ Element RenderUserEntry(ChatTimelineItem entry, bool startsBurst, bool endsBurst
9821116
foreach (var ae in attachmentElements) bubbleChildren.Add(ae);
9831117
if (hasMessage)
9841118
{
1119+
// Resolve HC + selection brush once per render method call
1120+
// rather than per Set-lambda re-run. HC state cannot change
1121+
// mid-render, and the brush is cached per-dispatcher so
1122+
// every user bubble in this render shares the same instance.
1123+
bool isHighContrast = TryDetectHighContrast();
1124+
var selectionHighlightBrush = GetUserBubbleSelectionBrush(isHighContrast);
9851125
bubbleChildren.Add(
986-
TextBlock(messageText)
1126+
TextBlock(string.Empty)
9871127
.Set(t =>
9881128
{
9891129
t.TextWrapping = TextWrapping.Wrap;
9901130
t.FontSize = 14;
9911131
t.Foreground = userBubbleFg;
9921132
t.IsTextSelectionEnabled = true;
1133+
// The default SelectionHighlightColor is the
1134+
// system accent — which equals the user bubble's
1135+
// background — so the highlight band is invisible
1136+
// against the bubble, and WinUI does NOT auto-
1137+
// invert an explicitly-set Foreground for
1138+
// selected glyphs. Outside High Contrast, use a
1139+
// darker shade of the current accent
1140+
// (SystemAccentColorDark2) so the band tracks
1141+
// whichever accent the user picked while keeping
1142+
// the white foreground readable. In High Contrast
1143+
// the bubble background switches to
1144+
// SystemColorHighlight (often near-black), where
1145+
// an accent-derived band may drop below WCAG
1146+
// 3:1, so fall back to the system selection
1147+
// color the OS guarantees contrasts with both
1148+
// surfaces.
1149+
t.SelectionHighlightColor = selectionHighlightBrush;
1150+
// Render through Inlines (a single Run) rather
1151+
// than the .Text property. This matches the
1152+
// assistant bubble's selection-safe path and
1153+
// sidesteps a WinUI bug where setting Text on a
1154+
// selection-enabled TextBlock during a re-render
1155+
// triggered by the mouse-up that ends a drag-
1156+
// select leaves the glyph layer visually empty.
1157+
ApplyPlainSelectableInlines(t, messageText);
9931158
}));
9941159
}
9951160

@@ -1428,20 +1593,19 @@ Element PhantomChevron() => Caption("▸")
14281593
// Read the live exploration state for the burst variant.
14291594
// Defaults to Auto, which picks the best variant per burst:
14301595
// - single-step → Plain (one inline row, nothing to fold)
1431-
// - all terminal → CompactSummary (1-line collapsed summary,
1596+
// - multi-step → CompactSummary (1-line collapsed summary,
14321597
// click chevron to expand the steps)
1433-
// - any running → Plain (per-step status visible in real time)
1434-
// Matches Scott's feedback: keep live progress legible while
1435-
// executing, then tidy up to a one-liner once the turn finishes.
1598+
// CompactSummary applies even while a step is in-flight: the
1599+
// header's aggregate status pill flips to "Running" (and back
1600+
// to "Done") so the user sees live progress without the group
1601+
// momentarily expanding to show the running row. Expanding
1602+
// mid-burst would yank the per-step list back into view every
1603+
// time the agent invoked another tool, which is exactly what
1604+
// collapsed mode is supposed to avoid.
14361605
var style = ChatExplorationState.ToolBurstStyle;
14371606
if (style == ToolBurstStyle.Auto)
14381607
{
1439-
bool allTerminal = true;
1440-
foreach (var e in entries)
1441-
{
1442-
if (e.ToolResult == ChatToolCallStatus.InProgress) { allTerminal = false; break; }
1443-
}
1444-
style = (entries.Count >= 2 && allTerminal)
1608+
style = entries.Count >= 2
14451609
? ToolBurstStyle.CompactSummary
14461610
: ToolBurstStyle.Plain;
14471611
}
@@ -2120,10 +2284,12 @@ void Flush(int endExclusive)
21202284
var nestedConsumed = new System.Collections.Generic.HashSet<int>();
21212285

21222286
// Nestable rule: a burst nests inside the assistant bubble when it
2123-
// would otherwise render as a single visible row — i.e. one chip
2124-
// (count==1) or a collapsed multi-step summary (count>=2 with every
2125-
// step in a terminal state, under Auto / CompactSummary). In-flight
2126-
// multi-step bursts stay external so live progress remains visible.
2287+
// renders as a single visible row — one chip (count==1) or a
2288+
// collapsed multi-step CompactSummary header (count>=2, under
2289+
// Auto / CompactSummary). In-flight multi-step bursts also nest;
2290+
// their aggregate status pill flips Running → Done so live progress
2291+
// is visible without expanding the group. Error rows stay external
2292+
// (see check below) so failures remain prominent.
21272293
bool BurstIsNestable(System.Collections.Generic.List<ChatTimelineItem> b)
21282294
{
21292295
if (b.Count == 0) return false;
@@ -2136,15 +2302,12 @@ bool BurstIsNestable(System.Collections.Generic.List<ChatTimelineItem> b)
21362302
if (e.ToolResult == ChatToolCallStatus.Error) return false;
21372303
}
21382304
if (b.Count == 1) return true;
2139-
bool allTerminal = true;
2140-
foreach (var e in b)
2141-
{
2142-
if (e.ToolResult == ChatToolCallStatus.InProgress) { allTerminal = false; break; }
2143-
}
2305+
// Multi-step bursts collapse into a single CompactSummary row
2306+
// under Auto / CompactSummary, so they fit comfortably inside
2307+
// an assistant bubble even while a step is in-flight — the
2308+
// aggregate status pill on the header shows Running/Done.
21442309
var s = ChatExplorationState.ToolBurstStyle;
2145-
if (s == ToolBurstStyle.Auto || s == ToolBurstStyle.CompactSummary)
2146-
return allTerminal;
2147-
return false;
2310+
return s == ToolBurstStyle.Auto || s == ToolBurstStyle.CompactSummary;
21482311
}
21492312

21502313
for (int k = 0; k < orderedIdx.Length; k++)

0 commit comments

Comments
 (0)