ailloli_ui_widgets/controls/
chat_widget.rs

1//! Stateful chat transcript and resizable composer control.
2
3use std::cell::RefCell;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
8use crate::layout::{
9    Column, Container, FlexItemExt, LayoutExt, ResizeBar, ResizeBarStyle, ResizeDragPhase, Row,
10    ScrollView,
11};
12use crate::primitives::Icon;
13use crate::text::Text;
14use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
15use ailloli_ui_core::event::Event;
16use ailloli_ui_core::geometry::{Constraints, Rect, Size};
17use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
18use ailloli_ui_core::{
19    ChatItemId, ChatMessage, ChatMessageKind, ChatMessageStatus, ChatRole, ChatSessionState,
20    ChatSessionStatus, Color, FontId, TextStyle, Theme,
21};
22use ailloli_ui_runtime::component::{
23    ComponentNode, Context, IntoView, Signal, State, View, Widget,
24};
25use ailloli_ui_runtime::input::EventCtx;
26use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
27use ailloli_ui_runtime::scene::PaintCtx;
28use ailloli_ui_runtime::{DrawCmd, DrawRRect, DrawText};
29use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, TextSystem, WrapMode};
30use lucide_icons::Icon as LucideIcon;
31
32use super::button::{Button, ButtonVariant};
33use super::popup::PopupPlacement;
34use super::select::{Select, SelectSize};
35use super::text_input::{TextInput, TextInputStyle};
36
37/// Shared context-aware handler for every [`ChatWidgetAction`].
38///
39/// # Examples
40///
41/// ```
42/// use std::rc::Rc;
43/// use ailloli_ui_widgets::controls::ChatWidgetActionHandler;
44/// let handler: ChatWidgetActionHandler<()> = Rc::new(|_ctx, _action| {});
45/// let _ = handler;
46/// ```
47pub type ChatWidgetActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatWidgetAction)>;
48/// Shared context-aware handler for submitted composer text.
49///
50/// # Examples
51///
52/// ```
53/// use std::rc::Rc;
54/// use ailloli_ui_widgets::controls::ChatWidgetSendHandler;
55/// let handler: ChatWidgetSendHandler<()> = Rc::new(|_ctx, text| assert!(!text.is_empty()));
56/// let _ = handler;
57/// ```
58pub type ChatWidgetSendHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
59/// Shared context-aware handler for a message ID and copied text.
60///
61/// # Examples
62///
63/// ```
64/// use std::rc::Rc;
65/// use ailloli_ui_widgets::controls::ChatWidgetCopyHandler;
66/// let handler: ChatWidgetCopyHandler<()> = Rc::new(|_ctx, _id, _text| {});
67/// let _ = handler;
68/// ```
69pub type ChatWidgetCopyHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatItemId, String)>;
70/// Shared context-aware handler for a retryable message ID.
71///
72/// # Examples
73///
74/// ```
75/// use std::rc::Rc;
76/// use ailloli_ui_widgets::controls::ChatWidgetRetryHandler;
77/// let handler: ChatWidgetRetryHandler<()> = Rc::new(|_ctx, _id| {});
78/// let _ = handler;
79/// ```
80pub type ChatWidgetRetryHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatItemId)>;
81/// Shared renderer replacing the built-in message bubble for every message.
82///
83/// # Examples
84///
85/// ```
86/// use std::rc::Rc;
87/// use ailloli_ui_runtime::component::View;
88/// use ailloli_ui_widgets::controls::ChatMessageRenderer;
89/// let renderer: ChatMessageRenderer<()> = Rc::new(|_message| View::empty());
90/// let _ = renderer;
91/// ```
92pub type ChatMessageRenderer<A> = Rc<dyn Fn(&ChatMessage) -> View<A>>;
93
94#[derive(Debug, Clone, PartialEq)]
95/// User intent emitted by the transcript and composer.
96///
97/// A general action handler runs before any specialized Send/Copy/Retry handler,
98/// so configuring both intentionally produces two callbacks. Copy actions do not
99/// write the clipboard themselves. `SetComposerHeight` expects a finite logical-
100/// pixel value; NaN makes derived `PartialEq` non-reflexive despite the legacy
101/// `Eq` marker on this enum.
102///
103/// # Examples
104///
105/// ```
106/// use ailloli_ui_core::ChatItemId;
107/// use ailloli_ui_widgets::controls::ChatWidgetAction;
108/// let actions = [
109///     ChatWidgetAction::Send { text: "Hi".into() },
110///     ChatWidgetAction::Copy { item_id: ChatItemId::new("1"), text: "Hi".into() },
111///     ChatWidgetAction::Retry { item_id: ChatItemId::new("1") },
112///     ChatWidgetAction::SetComposerDraft { text: "draft".into() },
113///     ChatWidgetAction::SetComposerPermission { value: "read_only".into() },
114///     ChatWidgetAction::SetComposerModel { model_id: None },
115///     ChatWidgetAction::SetComposerReasoning { reasoning_level: None },
116///     ChatWidgetAction::SetComposerHeight { height: 112.0 },
117///     ChatWidgetAction::StopTurn,
118/// ];
119/// assert_eq!(actions.len(), 9);
120/// ```
121pub enum ChatWidgetAction {
122    /// Submit non-blank composer text exactly as stored, without clearing it.
123    Send {
124        /// Exact UTF-8 composer contents forwarded to the owner.
125        text: String,
126    },
127    /// Request copying one item's current text.
128    Copy {
129        /// Stable identifier of the item whose copy affordance was activated.
130        item_id: ChatItemId,
131        /// Exact UTF-8 text to place on the clipboard.
132        text: String,
133    },
134    /// Request retry for an eligible item.
135    Retry {
136        /// Stable identifier of the item from which retry should resume.
137        item_id: ChatItemId,
138    },
139    /// Notify that the already-bound composer draft changed.
140    SetComposerDraft {
141        /// Complete replacement UTF-8 draft, including any whitespace.
142        text: String,
143    },
144    /// Select a permission option value.
145    SetComposerPermission {
146        /// Provider-neutral option value supplied by the composer model.
147        value: String,
148    },
149    /// Select a model ID, or provider default with `None`.
150    SetComposerModel {
151        /// Selected opaque model ID, or `None` to request the provider default.
152        model_id: Option<String>,
153    },
154    /// Select a reasoning level, or default with `None`.
155    SetComposerReasoning {
156        /// Selected opaque reasoning value, or `None` for the model default.
157        reasoning_level: Option<String>,
158    },
159    /// Request composer height in logical pixels.
160    SetComposerHeight {
161        /// Requested composer height in logical pixels before owner-side policy.
162        height: f32,
163    },
164    /// Request stopping the running turn.
165    StopTurn,
166}
167
168impl Eq for ChatWidgetAction {}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171/// One value/label pair shown in a composer select.
172///
173/// Values and labels are stored without validation; duplicates and empty strings
174/// are allowed.
175///
176/// # Examples
177///
178/// ```
179/// use ailloli_ui_widgets::controls::ChatComposerOption;
180/// let option = ChatComposerOption::new("model-id", "Model name");
181/// assert_eq!((option.value.as_str(), option.label.as_str()), ("model-id", "Model name"));
182/// ```
183pub struct ChatComposerOption {
184    /// Value emitted when selected.
185    pub value: String,
186    /// Visible option label.
187    pub label: String,
188}
189
190impl ChatComposerOption {
191    /// Stores a value and label unchanged.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use ailloli_ui_widgets::controls::ChatComposerOption;
197    /// let option = ChatComposerOption::new("fast", "Fast");
198    /// assert_eq!(option.value, "fast");
199    /// ```
200    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
201        Self {
202            value: value.into(),
203            label: label.into(),
204        }
205    }
206}
207
208#[derive(Debug, Clone, PartialEq)]
209/// Composer select choices, availability, run state, and height bounds.
210///
211/// The defaults provide permission values `read_only`, `workspace_write`, and
212/// `danger_full_access`; model/reasoning lists are empty, reasoning is disabled,
213/// and the composer is not running.
214///
215/// # Examples
216///
217/// ```
218/// use ailloli_ui_widgets::controls::ChatComposerControls;
219/// let controls = ChatComposerControls::default();
220/// assert_eq!(controls.selected_permission, "read_only");
221/// assert_eq!(controls.permission_options.len(), 3);
222/// assert_eq!((controls.height, controls.min_height, controls.max_height), (112.0, 72.0, 220.0));
223/// ```
224pub struct ChatComposerControls {
225    /// Permission choices in display order.
226    pub permission_options: Vec<ChatComposerOption>,
227    /// Controlled permission value; it may be absent from the option list.
228    pub selected_permission: String,
229    /// Model choices in display order; provider default is added separately.
230    pub model_options: Vec<ChatComposerOption>,
231    /// Controlled model ID, or provider default with `None`.
232    pub selected_model_id: Option<String>,
233    /// Reasoning choices in display order; default is added separately.
234    pub reasoning_options: Vec<ChatComposerOption>,
235    /// Controlled reasoning value, or default with `None`.
236    pub selected_reasoning_level: Option<String>,
237    /// Whether permission selection is enabled when not running.
238    pub permission_enabled: bool,
239    /// Whether model selection is enabled when not running.
240    pub model_enabled: bool,
241    /// Whether reasoning selection is enabled when nonempty and not running.
242    pub reasoning_enabled: bool,
243    /// Whether the composer shows Stop and disables all selectors.
244    pub running: bool,
245    /// Requested composer height in logical pixels.
246    pub height: f32,
247    /// Inclusive minimum composer height in logical pixels.
248    pub min_height: f32,
249    /// Inclusive maximum composer height in logical pixels.
250    pub max_height: f32,
251}
252
253impl Default for ChatComposerControls {
254    fn default() -> Self {
255        Self {
256            permission_options: vec![
257                ChatComposerOption::new("read_only", "read_only"),
258                ChatComposerOption::new("workspace_write", "write"),
259                ChatComposerOption::new("danger_full_access", "full_acess"),
260            ],
261            selected_permission: "read_only".into(),
262            model_options: Vec::new(),
263            selected_model_id: None,
264            reasoning_options: Vec::new(),
265            selected_reasoning_level: None,
266            permission_enabled: true,
267            model_enabled: true,
268            reasoning_enabled: false,
269            running: false,
270            height: 112.0,
271            min_height: 72.0,
272            max_height: 220.0,
273        }
274    }
275}
276
277impl ChatComposerControls {
278    /// Returns finite height clamped to inclusive bounds, else `112.0`.
279    ///
280    /// # Panics
281    ///
282    /// Panics when `height` is finite and either bound is NaN or `min_height` is
283    /// greater than `max_height`, following [`f32::clamp`].
284    ///
285    /// # Examples
286    ///
287    /// ```
288    /// use ailloli_ui_widgets::controls::ChatComposerControls;
289    /// let controls = ChatComposerControls { height: 500.0, ..Default::default() };
290    /// assert_eq!(controls.clamped_height(), 220.0);
291    /// let controls = ChatComposerControls { height: f32::NAN, ..Default::default() };
292    /// assert_eq!(controls.clamped_height(), 112.0);
293    /// ```
294    pub fn clamped_height(&self) -> f32 {
295        if self.height.is_finite() {
296            self.height.clamp(self.min_height, self.max_height)
297        } else {
298            112.0
299        }
300    }
301}
302
303#[derive(Clone, Debug)]
304/// Colors, typography, radii, spacing, and preferred size of a [`ChatWidget`].
305///
306/// Numeric geometry is expressed in logical pixels. [`Self::from_theme`] uses a
307/// `520 x 260` preferred size, 8-pixel outer padding/gap, a 6-pixel message gap,
308/// and non-compact rendering.
309///
310/// # Examples
311///
312/// ```
313/// use ailloli_ui_widgets::controls::ChatWidgetStyle;
314/// let style = ChatWidgetStyle::default();
315/// assert_eq!((style.width, style.height), (520.0, 260.0));
316/// assert!(!style.compact);
317/// ```
318pub struct ChatWidgetStyle {
319    /// Root background color.
320    pub background: Color,
321    /// Root border widths and colors.
322    pub border: Border,
323    /// Header and inline-action background color.
324    pub header_background: Color,
325    /// Background used for user messages.
326    pub user_background: Color,
327    /// Background used for assistant messages.
328    pub assistant_background: Color,
329    /// Background used for system and tool messages.
330    pub tool_background: Color,
331    /// Background used for error-kind or failed messages.
332    pub error_background: Color,
333    /// Message-body and header text style.
334    pub text: TextStyle,
335    /// Empty-state and inline-action text style.
336    pub muted: TextStyle,
337    /// Message role, kind, and status text style.
338    pub role_text: TextStyle,
339    /// Composer input and container style.
340    pub input: TextInputStyle,
341    /// Root corner radii in logical pixels.
342    pub radius: Radius,
343    /// Header corner radius in logical pixels.
344    pub header_radius: f32,
345    /// Message-bubble corner radius in logical pixels.
346    pub message_radius: f32,
347    /// Composer and inline-action corner radius in logical pixels.
348    pub inline_button_radius: f32,
349    /// Root inner padding in logical pixels.
350    pub padding: f32,
351    /// Vertical gap between header, transcript, and composer in logical pixels.
352    pub gap: f32,
353    /// Vertical gap between message bubbles in logical pixels.
354    pub message_gap: f32,
355    /// Preferred widget height in logical pixels.
356    pub height: f32,
357    /// Preferred widget width in logical pixels.
358    pub width: f32,
359    /// Whether compact header, bubble padding, and density are rendered.
360    pub compact: bool,
361}
362
363impl Default for ChatWidgetStyle {
364    fn default() -> Self {
365        Self::from_theme(Theme::default())
366    }
367}
368
369impl ChatWidgetStyle {
370    /// Creates the default chat style from `theme`.
371    ///
372    /// Palette-derived text and border colors coexist with deliberately dark
373    /// fixed transcript surfaces. No dimension is scaled or validated.
374    ///
375    /// # Examples
376    ///
377    /// ```
378    /// use ailloli_ui_core::Theme;
379    /// use ailloli_ui_widgets::controls::ChatWidgetStyle;
380    /// let style = ChatWidgetStyle::from_theme(Theme::default());
381    /// assert_eq!(style.padding, 8.0);
382    /// assert_eq!(style.message_gap, 6.0);
383    /// ```
384    pub fn from_theme(theme: Theme) -> Self {
385        let palette = theme.palette();
386        let mut input = TextInputStyle::from_theme(theme);
387        input.text = TextStyle::new(FontId::Ui, 13, palette.text);
388        input.bg = Color::hex_rgb(0x111827);
389        Self {
390            background: Color::hex_rgb(0x0B1018),
391            border: Border::new(1.0, palette.border.with_alpha(0.78)),
392            header_background: Color::hex_rgb(0x111827),
393            user_background: palette.accent.with_alpha(0.22),
394            assistant_background: Color::hex_rgb(0x17202A),
395            tool_background: Color::hex_rgb(0x1E293B),
396            error_background: Color::hex_rgb(0x3A1717),
397            text: TextStyle::new(FontId::Ui, 13, palette.text),
398            muted: TextStyle::new(FontId::Ui, 11, palette.text_muted),
399            role_text: TextStyle::new(FontId::Ui, 11, palette.text_muted),
400            input,
401            radius: Radius::uniform(theme.radius().md),
402            header_radius: 6.0,
403            message_radius: 6.0,
404            inline_button_radius: 5.0,
405            padding: 8.0,
406            gap: 8.0,
407            message_gap: 6.0,
408            height: 260.0,
409            width: 520.0,
410            compact: false,
411        }
412    }
413
414    /// Applies the predefined compact density and preferred height.
415    ///
416    /// This sets `compact`, padding, both gaps, and height, while preserving the
417    /// width and all colors. By contrast, [`ChatWidget::compact`] changes only
418    /// the rendering flag on an already configured widget style.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use ailloli_ui_widgets::controls::ChatWidgetStyle;
424    /// let style = ChatWidgetStyle::default().compact();
425    /// assert_eq!((style.padding, style.gap, style.message_gap), (6.0, 6.0, 4.0));
426    /// assert_eq!((style.width, style.height, style.compact), (520.0, 190.0, true));
427    /// ```
428    pub fn compact(mut self) -> Self {
429        self.compact = true;
430        self.padding = 6.0;
431        self.gap = 6.0;
432        self.message_gap = 4.0;
433        self.height = 190.0;
434        self
435    }
436}
437
438/// Stateful transcript with message actions and a controlled composer.
439///
440/// `A` is the application action returned by non-context callbacks. The draft
441/// is always signal-backed. Use [`Self::bind_session`] when session changes must
442/// remain observable after construction; [`Self::new`] stores its session value
443/// in private state.
444///
445/// # Examples
446///
447/// ```
448/// use ailloli_ui_core::{ChatSessionId, ChatSessionState};
449/// use ailloli_ui_runtime::component::State;
450/// use ailloli_ui_widgets::controls::ChatWidget;
451/// let session = ChatSessionState::new(ChatSessionId::new("demo"), "Demo");
452/// let widget: ChatWidget<()> = ChatWidget::new(Some(session), State::new(String::new()));
453/// let _ = widget;
454/// ```
455pub struct ChatWidget<A = ()> {
456    /// Root layout, updated by layout builders and [`Self::chat_style`].
457    pub(crate) layout: LayoutStyle,
458    /// Flex-parent participation configured by generated layout builders.
459    pub(crate) flex_item: FlexItemStyle,
460    /// Optional live chat session.
461    session: Signal<Option<ChatSessionState>>,
462    /// Writable composer draft.
463    draft: Signal<String>,
464    /// Visual configuration.
465    style: ChatWidgetStyle,
466    /// General callback invoked for every action.
467    on_action: Option<ChatWidgetActionHandler<A>>,
468    /// Specialized Send callback.
469    on_send: Option<ChatWidgetSendHandler<A>>,
470    /// Specialized Copy callback.
471    on_copy: Option<ChatWidgetCopyHandler<A>>,
472    /// Specialized Retry callback.
473    on_retry: Option<ChatWidgetRetryHandler<A>>,
474    /// Optional replacement renderer for all transcript items.
475    message_renderer: Option<ChatMessageRenderer<A>>,
476    /// Optional view inserted above the resize bar.
477    composer_accessory: Option<View<A>>,
478    /// Composer state and options.
479    composer_controls: ChatComposerControls,
480    /// Whether the transcript scroll follows its end.
481    follow_latest: bool,
482}
483
484crate::impl_layout_builders!(ChatWidget);
485
486impl<A: 'static> ChatWidget<A> {
487    /// Creates a widget from a session snapshot and writable draft signal.
488    ///
489    /// The snapshot is moved into private state and cannot subsequently be
490    /// replaced by the caller. Use [`Self::bind_session`] for a live session.
491    ///
492    /// # Examples
493    ///
494    /// ```
495    /// use ailloli_ui_runtime::component::State;
496    /// use ailloli_ui_widgets::controls::ChatWidget;
497    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new("draft".to_string()));
498    /// let _ = widget;
499    /// ```
500    pub fn new(session: Option<ChatSessionState>, draft: impl Into<Signal<String>>) -> Self {
501        Self::bind_session(State::new(session).into_signal(), draft)
502    }
503
504    /// Creates a widget backed by live session and draft signals.
505    ///
506    /// `None` renders the no-session state; `Some` with no messages renders the
507    /// empty-session state. The draft signal is updated by the text input before
508    /// `SetComposerDraft` is emitted.
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// use ailloli_ui_core::ChatSessionState;
514    /// use ailloli_ui_runtime::component::State;
515    /// use ailloli_ui_widgets::controls::ChatWidget;
516    /// let session = State::new(None::<ChatSessionState>);
517    /// let draft = State::new(String::new());
518    /// let widget: ChatWidget<()> = ChatWidget::bind_session(session, draft);
519    /// let _ = widget;
520    /// ```
521    pub fn bind_session(
522        session: impl Into<Signal<Option<ChatSessionState>>>,
523        draft: impl Into<Signal<String>>,
524    ) -> Self {
525        let style = ChatWidgetStyle::default();
526        Self {
527            layout: LayoutStyle::default()
528                .width(style.width)
529                .height(style.height),
530            flex_item: FlexItemStyle::default(),
531            session: session.into(),
532            draft: draft.into(),
533            style,
534            on_action: None,
535            on_send: None,
536            on_copy: None,
537            on_retry: None,
538            message_renderer: None,
539            composer_accessory: None,
540            composer_controls: ChatComposerControls::default(),
541            follow_latest: true,
542        }
543    }
544
545    /// Replaces the chat style and resets preferred layout width and height.
546    ///
547    /// Layout builders called after this method override those two dimensions.
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use ailloli_ui_runtime::component::State;
553    /// use ailloli_ui_widgets::controls::{ChatWidget, ChatWidgetStyle};
554    /// let style = ChatWidgetStyle { width: 640.0, height: 320.0, ..Default::default() };
555    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new())).chat_style(style);
556    /// let _ = widget;
557    /// ```
558    pub fn chat_style(mut self, style: ChatWidgetStyle) -> Self {
559        self.layout = self.layout.width(style.width).height(style.height);
560        self.style = style;
561        self
562    }
563
564    /// Enables or disables compact rendering without changing style geometry.
565    ///
566    /// Use [`ChatWidgetStyle::compact`] through [`Self::chat_style`] to also apply
567    /// the compact padding, gaps, and 190-pixel preferred height.
568    ///
569    /// # Examples
570    ///
571    /// ```
572    /// use ailloli_ui_runtime::component::State;
573    /// use ailloli_ui_widgets::controls::ChatWidget;
574    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new())).compact(true);
575    /// let _ = widget;
576    /// ```
577    pub fn compact(mut self, compact: bool) -> Self {
578        self.style.compact = compact;
579        self
580    }
581
582    /// Dispatches the application action returned for every widget action.
583    ///
584    /// For Send, Copy, and Retry this callback runs before the corresponding
585    /// specialized callback when both are configured.
586    ///
587    /// # Examples
588    ///
589    /// ```
590    /// use ailloli_ui_runtime::component::State;
591    /// use ailloli_ui_widgets::controls::ChatWidget;
592    /// let widget = ChatWidget::new(None, State::new(String::new())).on_action(|_action| ());
593    /// let _ = widget;
594    /// ```
595    pub fn on_action(mut self, f: impl Fn(ChatWidgetAction) -> A + 'static) -> Self {
596        self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
597        self
598    }
599
600    /// Handles every widget action with direct event-context access.
601    ///
602    /// The handler may dispatch zero or multiple application actions and runs
603    /// before specialized Send, Copy, or Retry handlers.
604    ///
605    /// # Examples
606    ///
607    /// ```
608    /// use ailloli_ui_runtime::component::State;
609    /// use ailloli_ui_widgets::controls::ChatWidget;
610    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
611    ///     .on_action_ctx(|_ctx, _action| {});
612    /// let _ = widget;
613    /// ```
614    pub fn on_action_ctx(
615        mut self,
616        f: impl Fn(&mut EventCtx<A>, ChatWidgetAction) + 'static,
617    ) -> Self {
618        self.on_action = Some(Rc::new(f));
619        self
620    }
621
622    /// Dispatches the application action returned for submitted text.
623    ///
624    /// Blank-after-trimming drafts are not submitted. Non-blank text is passed
625    /// unchanged, including surrounding whitespace, and the draft is not cleared.
626    ///
627    /// # Examples
628    ///
629    /// ```
630    /// use ailloli_ui_runtime::component::State;
631    /// use ailloli_ui_widgets::controls::ChatWidget;
632    /// let widget = ChatWidget::new(None, State::new("Hello".to_string())).on_send(|text| {
633    ///     assert_eq!(text, "Hello");
634    /// });
635    /// let _ = widget;
636    /// ```
637    pub fn on_send(mut self, f: impl Fn(String) -> A + 'static) -> Self {
638        self.on_send = Some(Rc::new(move |ctx, text| ctx.dispatch(f(text))));
639        self
640    }
641
642    /// Handles submitted text with direct event-context access.
643    ///
644    /// # Examples
645    ///
646    /// ```
647    /// use ailloli_ui_runtime::component::State;
648    /// use ailloli_ui_widgets::controls::ChatWidget;
649    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
650    ///     .on_send_ctx(|_ctx, _text| {});
651    /// let _ = widget;
652    /// ```
653    pub fn on_send_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
654        self.on_send = Some(Rc::new(f));
655        self
656    }
657
658    /// Dispatches the application action returned for a copy request.
659    ///
660    /// The widget supplies the message ID and its current text but performs no
661    /// clipboard write.
662    ///
663    /// # Examples
664    ///
665    /// ```
666    /// use ailloli_ui_runtime::component::State;
667    /// use ailloli_ui_widgets::controls::ChatWidget;
668    /// let widget = ChatWidget::new(None, State::new(String::new()))
669    ///     .on_copy(|_item_id, _text| ());
670    /// let _ = widget;
671    /// ```
672    pub fn on_copy(mut self, f: impl Fn(ChatItemId, String) -> A + 'static) -> Self {
673        self.on_copy = Some(Rc::new(move |ctx, item_id, text| {
674            ctx.dispatch(f(item_id, text))
675        }));
676        self
677    }
678
679    /// Handles a copy request with direct event-context access.
680    ///
681    /// # Examples
682    ///
683    /// ```
684    /// use ailloli_ui_runtime::component::State;
685    /// use ailloli_ui_widgets::controls::ChatWidget;
686    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
687    ///     .on_copy_ctx(|_ctx, _item_id, _text| {});
688    /// let _ = widget;
689    /// ```
690    pub fn on_copy_ctx(
691        mut self,
692        f: impl Fn(&mut EventCtx<A>, ChatItemId, String) + 'static,
693    ) -> Self {
694        self.on_copy = Some(Rc::new(f));
695        self
696    }
697
698    /// Dispatches the application action returned for a retry request.
699    ///
700    /// User messages are retryable. Assistant messages are retryable only when
701    /// they carry a request ID; system and tool messages are never retryable.
702    ///
703    /// # Examples
704    ///
705    /// ```
706    /// use ailloli_ui_runtime::component::State;
707    /// use ailloli_ui_widgets::controls::ChatWidget;
708    /// let widget = ChatWidget::new(None, State::new(String::new())).on_retry(|_item_id| ());
709    /// let _ = widget;
710    /// ```
711    pub fn on_retry(mut self, f: impl Fn(ChatItemId) -> A + 'static) -> Self {
712        self.on_retry = Some(Rc::new(move |ctx, item_id| ctx.dispatch(f(item_id))));
713        self
714    }
715
716    /// Handles a retry request with direct event-context access.
717    ///
718    /// # Examples
719    ///
720    /// ```
721    /// use ailloli_ui_runtime::component::State;
722    /// use ailloli_ui_widgets::controls::ChatWidget;
723    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
724    ///     .on_retry_ctx(|_ctx, _item_id| {});
725    /// let _ = widget;
726    /// ```
727    pub fn on_retry_ctx(mut self, f: impl Fn(&mut EventCtx<A>, ChatItemId) + 'static) -> Self {
728        self.on_retry = Some(Rc::new(f));
729        self
730    }
731
732    /// Replaces the complete built-in bubble for every message.
733    ///
734    /// A custom view is responsible for body, metadata, and any Copy/Retry UI;
735    /// it also bypasses the optimized retained transcript renderer.
736    ///
737    /// # Examples
738    ///
739    /// ```
740    /// use ailloli_ui_runtime::component::{State, View};
741    /// use ailloli_ui_widgets::controls::ChatWidget;
742    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
743    ///     .message_renderer(|_message| View::empty());
744    /// let _ = widget;
745    /// ```
746    pub fn message_renderer(mut self, f: impl Fn(&ChatMessage) -> View<A> + 'static) -> Self {
747        self.message_renderer = Some(Rc::new(f));
748        self
749    }
750
751    /// Inserts a prebuilt view above the composer resize bar.
752    ///
753    /// # Examples
754    ///
755    /// ```
756    /// use ailloli_ui_runtime::component::{State, View};
757    /// use ailloli_ui_widgets::controls::ChatWidget;
758    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
759    ///     .composer_accessory(View::empty());
760    /// let _ = widget;
761    /// ```
762    pub fn composer_accessory(mut self, accessory: View<A>) -> Self {
763        self.composer_accessory = Some(accessory);
764        self
765    }
766
767    /// Replaces permission/model/reasoning choices, enabled state, and height.
768    ///
769    /// The values are controlled: emitted actions do not mutate this snapshot.
770    /// While `running`, selectors are disabled and the turn button emits Stop.
771    ///
772    /// # Examples
773    ///
774    /// ```
775    /// use ailloli_ui_runtime::component::State;
776    /// use ailloli_ui_widgets::controls::{ChatComposerControls, ChatWidget};
777    /// let controls = ChatComposerControls { running: true, ..Default::default() };
778    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
779    ///     .composer_controls(controls);
780    /// let _ = widget;
781    /// ```
782    pub fn composer_controls(mut self, controls: ChatComposerControls) -> Self {
783        self.composer_controls = controls;
784        self
785    }
786
787    /// Sets whether the vertical transcript scroll follows its end.
788    ///
789    /// # Examples
790    ///
791    /// ```
792    /// use ailloli_ui_runtime::component::State;
793    /// use ailloli_ui_widgets::controls::ChatWidget;
794    /// let widget: ChatWidget<()> = ChatWidget::new(None, State::new(String::new()))
795    ///     .follow_latest(false);
796    /// let _ = widget;
797    /// ```
798    pub fn follow_latest(mut self, enabled: bool) -> Self {
799        self.follow_latest = enabled;
800        self
801    }
802}
803
804impl<A: 'static> IntoView<A> for ChatWidget<A> {
805    fn into_view(self) -> View<A> {
806        let layout = self.layout;
807        finish_view_sized(
808            View::component(ChatWidgetComponent {
809                layout,
810                session: self.session,
811                draft: self.draft,
812                style: self.style,
813                on_action: self.on_action,
814                on_send: self.on_send,
815                on_copy: self.on_copy,
816                on_retry: self.on_retry,
817                message_renderer: self.message_renderer,
818                composer_accessory: self.composer_accessory,
819                composer_controls: self.composer_controls,
820                follow_latest: self.follow_latest,
821            }),
822            self.flex_item,
823            LayoutSizeHint::from_layout(layout),
824        )
825    }
826}
827
828/// Reactive component that materializes the configured chat view tree.
829struct ChatWidgetComponent<A> {
830    /// Root layout copied from the public builder.
831    layout: LayoutStyle,
832    /// Live session source.
833    session: Signal<Option<ChatSessionState>>,
834    /// Writable composer draft.
835    draft: Signal<String>,
836    /// Visual configuration shared by child builders.
837    style: ChatWidgetStyle,
838    /// General action handler.
839    on_action: Option<ChatWidgetActionHandler<A>>,
840    /// Specialized Send handler.
841    on_send: Option<ChatWidgetSendHandler<A>>,
842    /// Specialized Copy handler.
843    on_copy: Option<ChatWidgetCopyHandler<A>>,
844    /// Specialized Retry handler.
845    on_retry: Option<ChatWidgetRetryHandler<A>>,
846    /// Optional replacement message renderer.
847    message_renderer: Option<ChatMessageRenderer<A>>,
848    /// Optional view placed above the resize control.
849    composer_accessory: Option<View<A>>,
850    /// Controlled composer settings.
851    composer_controls: ChatComposerControls,
852    /// Transcript follow-end setting.
853    follow_latest: bool,
854}
855
856/// Cheaply cloned callback bundle shared by generated child controls.
857struct ChatWidgetHandlers<A> {
858    /// General handler invoked first.
859    on_action: Option<ChatWidgetActionHandler<A>>,
860    /// Specialized Send handler.
861    on_send: Option<ChatWidgetSendHandler<A>>,
862    /// Specialized Copy handler.
863    on_copy: Option<ChatWidgetCopyHandler<A>>,
864    /// Specialized Retry handler.
865    on_retry: Option<ChatWidgetRetryHandler<A>>,
866}
867
868impl<A> Clone for ChatWidgetHandlers<A> {
869    /// Clones only the reference-counted callback handles.
870    fn clone(&self) -> Self {
871        Self {
872            on_action: self.on_action.clone(),
873            on_send: self.on_send.clone(),
874            on_copy: self.on_copy.clone(),
875            on_retry: self.on_retry.clone(),
876        }
877    }
878}
879
880impl<A: 'static> ComponentNode<A> for ChatWidgetComponent<A> {
881    /// Builds the header, transcript, optional accessory, resize bar, and composer.
882    fn build(&self, context: &mut Context<A>) -> View<A> {
883        let composer_resize_start_height = context.signal(None::<f32>);
884        let mut content = Column::new()
885            .fill()
886            .gap(self.style.gap)
887            .child(self.header())
888            .child(self.messages().fill());
889        let mut composer_area = Column::new().fill_width();
890        if let Some(accessory) = self.composer_accessory.clone() {
891            composer_area = composer_area.child(accessory);
892        }
893        composer_area = composer_area
894            .child(self.composer_resize_bar(composer_resize_start_height))
895            .child(self.composer());
896        content = content.child(composer_area);
897
898        let mut root = Container::new()
899            .background(self.style.background)
900            .border(self.style.border.widths.top, self.style.border.colors.top)
901            .radius(self.style.radius.tl)
902            .padding(self.style.padding)
903            .clip_children(true)
904            .child(content);
905        *root.layout_mut() = self.layout;
906        root.into_view()
907    }
908}
909
910impl<A: 'static> ChatWidgetComponent<A> {
911    /// Takes cheap clones of the configured callback handles.
912    fn handlers(&self) -> ChatWidgetHandlers<A> {
913        ChatWidgetHandlers {
914            on_action: self.on_action.clone(),
915            on_send: self.on_send.clone(),
916            on_copy: self.on_copy.clone(),
917            on_retry: self.on_retry.clone(),
918        }
919    }
920
921    /// Builds the reactive `title - status - count msg` header.
922    fn header(&self) -> View<A> {
923        let session = self.session.clone();
924        let title = session.to_text_with(|session| {
925            let (title, status, count) = session
926                .as_ref()
927                .map(|session| {
928                    (
929                        session.title.clone(),
930                        session_status_label(session.status).to_string(),
931                        session.messages.len(),
932                    )
933                })
934                .unwrap_or_else(|| ("No session".into(), "idle".into(), 0));
935            format!("{title} - {status} - {count} msg")
936        });
937        Container::new()
938            .fill_width()
939            .height(if self.style.compact { 32.0 } else { 40.0 })
940            .background(self.style.header_background)
941            .radius(self.style.header_radius)
942            .padding(6.0)
943            .child(
944                Row::new().gap(8.0).fill_width().child(
945                    Container::new()
946                        .fill_width()
947                        .child(Text::new(title).style(self.style.text).nowrap()),
948                ),
949            )
950            .into_view()
951    }
952
953    /// Builds either the optimized transcript leaf or custom-renderer column.
954    fn messages(&self) -> View<A> {
955        if self.message_renderer.is_none() {
956            return ScrollView::vertical()
957                .follow_end(self.follow_latest)
958                .child(
959                    View::leaf(ChatMessagesWidget {
960                        layout: LayoutStyle::default().fill_width(),
961                        session: self.session.clone(),
962                        style: self.style.clone(),
963                        handlers: self.handlers(),
964                        geometry: Rc::new(RefCell::new(ChatMessagesGeometry::default())),
965                    })
966                    .fill_width(),
967                )
968                .fill_width()
969                .into_view();
970        }
971
972        let mut list = Column::new().gap(self.style.message_gap).fill_width();
973        let session = self.session.read();
974        match &session {
975            Some(session) if !session.messages.is_empty() => {
976                for message in &session.messages {
977                    let rendered = self
978                        .message_renderer
979                        .as_ref()
980                        .map(|renderer| renderer(message))
981                        .unwrap_or_else(|| self.message_bubble(message));
982                    list = list.child(rendered);
983                }
984            }
985            Some(_) => {
986                list = list.child(Text::new("No messages yet").style(self.style.muted));
987            }
988            None => {
989                list = list.child(Text::new("No chat session").style(self.style.muted));
990            }
991        }
992
993        ScrollView::vertical()
994            .follow_end(self.follow_latest)
995            .child(list)
996            .fill_width()
997            .into_view()
998    }
999
1000    /// Builds one non-optimized message bubble with eligible action buttons.
1001    fn message_bubble(&self, message: &ChatMessage) -> View<A> {
1002        let background = message_background(&self.style, message);
1003        let role = format!(
1004            "{} / {}{}",
1005            role_label(message.role),
1006            kind_label(message.kind),
1007            status_suffix(message.status)
1008        );
1009        let copy = ChatWidgetAction::Copy {
1010            item_id: message.id.clone(),
1011            text: message.text.clone(),
1012        };
1013        let copy_handlers = self.handlers();
1014        let mut actions = Row::new()
1015            .gap(6.0)
1016            .child(action_button("Copy", copy, copy_handlers));
1017        if message_is_retryable(message) {
1018            actions = actions.child(action_button(
1019                "Retry",
1020                ChatWidgetAction::Retry {
1021                    item_id: message.id.clone(),
1022                },
1023                self.handlers(),
1024            ));
1025        }
1026        Container::new()
1027            .fill_width()
1028            .background(background)
1029            .radius(self.style.message_radius)
1030            .padding(if self.style.compact { 6.0 } else { 8.0 })
1031            .child(
1032                Column::new()
1033                    .gap(4.0)
1034                    .fill_width()
1035                    .child(Text::new(role).style(self.style.role_text).nowrap())
1036                    .child(
1037                        Text::new(if message.text.is_empty() {
1038                            "...".to_string()
1039                        } else {
1040                            message.text.clone()
1041                        })
1042                        .style(self.style.text)
1043                        .wrap_anywhere(),
1044                    )
1045                    .child(actions),
1046            )
1047            .into_view()
1048    }
1049
1050    /// Builds the horizontal drag target and emits unclamped requested heights.
1051    fn composer_resize_bar(&self, resize_start_height: Signal<Option<f32>>) -> View<A> {
1052        let current_height = self.composer_controls.clamped_height();
1053        let resize_handlers = self.handlers();
1054        ResizeBar::<A>::horizontal()
1055            .fill_width()
1056            .height(8.0)
1057            .resize_bar_style(ResizeBarStyle {
1058                hit_thickness: 8.0,
1059                line_thickness: 2.0,
1060                idle_color: self.style.input.border_focused,
1061                hover_color: self.style.input.border_focused,
1062                active_color: self.style.input.border_focused,
1063                ..ResizeBarStyle::default()
1064            })
1065            .on_resize_ctx(move |ctx, event| {
1066                let drag_start_height = match event.phase {
1067                    ResizeDragPhase::Start => {
1068                        resize_start_height.set(Some(current_height));
1069                        current_height
1070                    }
1071                    ResizeDragPhase::Drag | ResizeDragPhase::End => {
1072                        resize_start_height.read().unwrap_or(current_height)
1073                    }
1074                };
1075                emit_chat_widget_action(
1076                    ctx,
1077                    &resize_handlers,
1078                    ChatWidgetAction::SetComposerHeight {
1079                        height: drag_start_height - event.total_delta,
1080                    },
1081                );
1082                if event.phase == ResizeDragPhase::End {
1083                    resize_start_height.set(None);
1084                }
1085            })
1086            .into_view()
1087            .key("ailloli_ui-chat-composer-resize-bar")
1088    }
1089
1090    /// Builds controlled selects, text input, and Send/Stop turn button.
1091    fn composer(&self) -> View<A> {
1092        let draft = self.draft.clone();
1093        let handlers = self.handlers();
1094        let controls = self.composer_controls.clone();
1095        let draft_handlers = self.handlers();
1096        let height = controls.clamped_height();
1097        let content_height = (height - 14.0).max(0.0);
1098        let input_height = (content_height - 34.0).max(0.0);
1099        let selected_permission = controls.selected_permission.clone();
1100        let selected_model = controls.selected_model_id.clone().unwrap_or_default();
1101        let selected_reasoning = controls
1102            .selected_reasoning_level
1103            .clone()
1104            .unwrap_or_default();
1105        let mut permission_select = Select::<String, A>::new()
1106            .placeholder("permissions")
1107            .selected(selected_permission)
1108            .popup_placement(PopupPlacement::Top)
1109            .select_size(SelectSize::Compact)
1110            .width(122.0)
1111            .height(30.0)
1112            .disabled(controls.running || !controls.permission_enabled);
1113        for option in &controls.permission_options {
1114            permission_select =
1115                permission_select.option(option.value.clone(), option.label.clone());
1116        }
1117        let permission_handlers = self.handlers();
1118        permission_select = permission_select.on_change_ctx(move |ctx, value| {
1119            emit_chat_widget_action(
1120                ctx,
1121                &permission_handlers,
1122                ChatWidgetAction::SetComposerPermission { value },
1123            );
1124        });
1125
1126        let mut model_select = Select::<String, A>::new()
1127            .placeholder("model")
1128            .selected(selected_model)
1129            .popup_placement(PopupPlacement::Top)
1130            .select_size(SelectSize::Compact)
1131            .fill_width()
1132            .height(30.0)
1133            .disabled(controls.running || !controls.model_enabled)
1134            .option(String::new(), "Provider default");
1135        for option in &controls.model_options {
1136            model_select = model_select.option(option.value.clone(), option.label.clone());
1137        }
1138        let model_handlers = self.handlers();
1139        model_select = model_select.on_change_ctx(move |ctx, value| {
1140            emit_chat_widget_action(
1141                ctx,
1142                &model_handlers,
1143                ChatWidgetAction::SetComposerModel {
1144                    model_id: (!value.is_empty()).then_some(value),
1145                },
1146            );
1147        });
1148
1149        let mut reasoning_select = Select::<String, A>::new()
1150            .placeholder("reasoning")
1151            .selected(selected_reasoning)
1152            .popup_placement(PopupPlacement::Top)
1153            .select_size(SelectSize::Compact)
1154            .width(92.0)
1155            .height(30.0)
1156            .disabled(
1157                controls.running
1158                    || !controls.reasoning_enabled
1159                    || controls.reasoning_options.is_empty(),
1160            )
1161            .option(String::new(), "default");
1162        for option in &controls.reasoning_options {
1163            reasoning_select = reasoning_select.option(option.value.clone(), option.label.clone());
1164        }
1165        let reasoning_handlers = self.handlers();
1166        reasoning_select = reasoning_select.on_change_ctx(move |ctx, value| {
1167            emit_chat_widget_action(
1168                ctx,
1169                &reasoning_handlers,
1170                ChatWidgetAction::SetComposerReasoning {
1171                    reasoning_level: (!value.is_empty()).then_some(value),
1172                },
1173            );
1174        });
1175
1176        let button_handlers = handlers.clone();
1177        let running = controls.running;
1178        let button_icon = if running {
1179            LucideIcon::SquareStop
1180        } else {
1181            LucideIcon::Play
1182        };
1183        let button_variant = if running {
1184            ButtonVariant::Destructive
1185        } else {
1186            ButtonVariant::Primary
1187        };
1188
1189        Container::new()
1190            .fill_width()
1191            .height(height)
1192            .background(self.style.input.bg)
1193            .border(1.0, self.style.input.border)
1194            .radius(self.style.inline_button_radius)
1195            .padding(6.0)
1196            .clip_children(true)
1197            .child(
1198                Column::new()
1199                    .gap(4.0)
1200                    .fill_width()
1201                    .child(
1202                        TextInput::<A>::new()
1203                            .bind(self.draft.clone())
1204                            .multiline()
1205                            .placeholder("Ask...")
1206                            .input_style(TextInputStyle {
1207                                bg: Color::TRANSPARENT,
1208                                border: Color::TRANSPARENT,
1209                                border_focused: Color::TRANSPARENT,
1210                                radius: 0.0,
1211                                ..self.style.input
1212                            })
1213                            .on_change_ctx(move |ctx, text| {
1214                                emit_chat_widget_action(
1215                                    ctx,
1216                                    &draft_handlers,
1217                                    ChatWidgetAction::SetComposerDraft { text },
1218                                );
1219                            })
1220                            .height(input_height)
1221                            .fill_width()
1222                            .into_view()
1223                            .key("ailloli_ui-chat-composer-input"),
1224                    )
1225                    .child(
1226                        Row::new()
1227                            .gap(6.0)
1228                            .fill_width()
1229                            .child(
1230                                permission_select
1231                                    .into_view()
1232                                    .key("ailloli_ui-chat-composer-permission-select"),
1233                            )
1234                            .child(
1235                                model_select
1236                                    .into_view()
1237                                    .key("ailloli_ui-chat-composer-model-select"),
1238                            )
1239                            .child(
1240                                reasoning_select
1241                                    .into_view()
1242                                    .key("ailloli_ui-chat-composer-reasoning-select"),
1243                            )
1244                            .child(
1245                                Button::new()
1246                                    .variant(button_variant)
1247                                    .width(32.0)
1248                                    .height(30.0)
1249                                    .radius(self.style.inline_button_radius)
1250                                    .child(
1251                                        Icon::lucide(button_icon)
1252                                            .size(15.0)
1253                                            .into_view()
1254                                            .key("ailloli_ui-chat-composer-turn-button-icon"),
1255                                    )
1256                                    .on_click_ctx(move |ctx| {
1257                                        if running {
1258                                            emit_chat_widget_action(
1259                                                ctx,
1260                                                &button_handlers,
1261                                                ChatWidgetAction::StopTurn,
1262                                            );
1263                                            return;
1264                                        }
1265                                        let text = draft.read();
1266                                        if text.trim().is_empty() {
1267                                            return;
1268                                        }
1269                                        emit_chat_widget_action(
1270                                            ctx,
1271                                            &button_handlers,
1272                                            ChatWidgetAction::Send { text },
1273                                        );
1274                                    })
1275                                    .into_view()
1276                                    .key("ailloli_ui-chat-composer-turn-button"),
1277                            ),
1278                    ),
1279            )
1280            .into_view()
1281    }
1282}
1283
1284/// Retained transcript leaf that caches measured text and hit geometry.
1285struct ChatMessagesWidget<A> {
1286    /// Size behavior supplied to the runtime layout engine.
1287    layout: LayoutStyle,
1288    /// Live session whose message sequence is rendered.
1289    session: Signal<Option<ChatSessionState>>,
1290    /// Message styles and geometry constants.
1291    style: ChatWidgetStyle,
1292    /// Copy and Retry action destinations.
1293    handlers: ChatWidgetHandlers<A>,
1294    /// Last measured geometry, shared across layout, paint, and events.
1295    geometry: Rc<RefCell<ChatMessagesGeometry>>,
1296}
1297
1298#[derive(Clone, Default)]
1299/// Cached geometry for one transcript width and exact message identity/content.
1300struct ChatMessagesGeometry {
1301    /// Measured available width in logical pixels.
1302    width: f32,
1303    /// Per-message measurement and action-hit geometry in session order.
1304    items: Vec<ChatMessageGeometry>,
1305    /// Sum of message heights and inter-message gaps in logical pixels.
1306    total_height: f32,
1307}
1308
1309#[derive(Clone)]
1310/// Cached text layouts and local rectangles for a single message.
1311struct ChatMessageGeometry {
1312    /// Message identity used for cache validation.
1313    item_id: ChatItemId,
1314    /// Rendered role/kind/status string used for cache validation.
1315    role_text: String,
1316    /// Rendered body or empty-body sentinel used for cache validation.
1317    body_text: String,
1318    /// Top offset in transcript-local logical pixels.
1319    y: f32,
1320    /// Full bubble height in logical pixels.
1321    height: f32,
1322    /// Role line height in logical pixels.
1323    role_height: f32,
1324    /// Body text height in logical pixels.
1325    body_height: f32,
1326    /// Prepared role text retained for painting.
1327    role_layout: Arc<PreparedTextLayout>,
1328    /// Prepared body text retained for painting.
1329    body_layout: Arc<PreparedTextLayout>,
1330    /// Transcript-local Copy hit rectangle.
1331    copy_rect: Rect,
1332    /// Transcript-local Retry hit rectangle when the message is eligible.
1333    retry_rect: Option<Rect>,
1334}
1335
1336impl<A: 'static> Widget<A> for ChatMessagesWidget<A> {
1337    /// Returns the stable diagnostic widget name.
1338    fn debug_name(&self) -> &'static str {
1339        "ChatMessages"
1340    }
1341
1342    /// Measures the transcript, caches geometry, and clamps its runtime size.
1343    fn layout(
1344        &self,
1345        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1346        ctx: &mut LayoutCtx<'_>,
1347        _children: &mut [LayoutChild],
1348        constraints: Constraints,
1349    ) -> LayoutResult {
1350        let width = constraints.max_w.max(0.0);
1351        let session = self.session.read();
1352        let geometry = match session.as_ref() {
1353            Some(session) if !session.messages.is_empty() => measure_chat_messages_geometry(
1354                ctx.text_system.as_deref_mut(),
1355                session,
1356                &self.style,
1357                width,
1358            ),
1359            _ => ChatMessagesGeometry {
1360                width,
1361                items: Vec::new(),
1362                total_height: self.style.text.px_size as f32 * 1.6,
1363            },
1364        };
1365        let height = match session.as_ref() {
1366            Some(session) if !session.messages.is_empty() => geometry.total_height,
1367            _ => self.style.text.px_size as f32 * 1.6,
1368        };
1369        *self.geometry.borrow_mut() = geometry;
1370        let size = apply_layout_size(Size::new(width, height.max(24.0)), self.layout, constraints);
1371        let viewport = Rect::new(0.0, 0.0, size.w, size.h);
1372        LayoutResult {
1373            size,
1374            children: Vec::new(),
1375            paint_bounds: viewport,
1376            visual_bounds: viewport,
1377            overlay_hit_bounds: Vec::new(),
1378            clip: None,
1379            is_window_root_clip: false,
1380            artifact: None,
1381        }
1382    }
1383
1384    /// Paints cached messages or the appropriate empty-state text.
1385    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1386        let session = self.session.read();
1387        match session.as_ref() {
1388            Some(session) if !session.messages.is_empty() => {
1389                let Some(geometry) = self.geometry_for_paint(ctx, session, bounds.w) else {
1390                    return;
1391                };
1392                for (message, item) in session.messages.iter().zip(geometry.items.iter()) {
1393                    paint_message(
1394                        ctx,
1395                        bounds.x,
1396                        bounds.y,
1397                        bounds.w,
1398                        &self.style,
1399                        message,
1400                        item,
1401                    );
1402                }
1403            }
1404            Some(_) => paint_plain_text(
1405                ctx,
1406                "No messages yet",
1407                bounds.x,
1408                bounds.y,
1409                bounds.w,
1410                self.style.muted,
1411            ),
1412            None => paint_plain_text(
1413                ctx,
1414                "No chat session",
1415                bounds.x,
1416                bounds.y,
1417                bounds.w,
1418                self.style.muted,
1419            ),
1420        }
1421    }
1422
1423    /// Handles only pressed primary-pointer events within cached action rectangles.
1424    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1425        let Event::Pointer(PointerEvent::Button {
1426            pos,
1427            button: MouseButton::Left,
1428            pressed: true,
1429            ..
1430        }) = event
1431        else {
1432            return;
1433        };
1434        if !bounds.contains(pos.x, pos.y) {
1435            return;
1436        }
1437        let Some(action) = self.action_at(bounds, pos.x, pos.y) else {
1438            return;
1439        };
1440        emit_chat_widget_action(ctx, &self.handlers, action);
1441        ctx.request_repaint();
1442        ctx.stop_propagation();
1443    }
1444}
1445
1446impl<A> ChatMessagesWidget<A> {
1447    /// Returns matching cached geometry or remeasures it for the paint context.
1448    ///
1449    /// `None` means the remeasured data still cannot be proven to match the
1450    /// current session and width, so painting must be skipped for this frame.
1451    fn geometry_for_paint(
1452        &self,
1453        ctx: &mut PaintCtx<'_>,
1454        session: &ChatSessionState,
1455        width: f32,
1456    ) -> Option<ChatMessagesGeometry> {
1457        let cached = self.geometry.borrow().clone();
1458        if cached.matches(session, width) {
1459            return Some(cached);
1460        }
1461
1462        let geometry = measure_chat_messages_geometry(
1463            ctx.text_system.as_deref_mut(),
1464            session,
1465            &self.style,
1466            width,
1467        );
1468        if geometry.matches(session, width) {
1469            *self.geometry.borrow_mut() = geometry.clone();
1470            Some(geometry)
1471        } else {
1472            None
1473        }
1474    }
1475
1476    /// Hit-tests absolute coordinates against validated local Copy/Retry regions.
1477    fn action_at(&self, bounds: Rect, x: f32, y: f32) -> Option<ChatWidgetAction> {
1478        let session = self.session.read()?;
1479        let geometry = self.geometry.borrow();
1480        if !geometry.matches(&session, bounds.w) {
1481            return None;
1482        }
1483        let local_x = x - bounds.x;
1484        let local_y = y - bounds.y;
1485        for (message, item) in session.messages.iter().zip(geometry.items.iter()) {
1486            if item.copy_rect.contains(local_x, local_y) {
1487                return Some(ChatWidgetAction::Copy {
1488                    item_id: message.id.clone(),
1489                    text: message.text.clone(),
1490                });
1491            }
1492            if message_is_retryable(message)
1493                && item
1494                    .retry_rect
1495                    .is_some_and(|retry| retry.contains(local_x, local_y))
1496            {
1497                return Some(ChatWidgetAction::Retry {
1498                    item_id: message.id.clone(),
1499                });
1500            }
1501        }
1502        None
1503    }
1504}
1505
1506/// Paints one bubble from premeasured geometry and returns its height.
1507fn paint_message(
1508    ctx: &mut PaintCtx<'_>,
1509    x: f32,
1510    y: f32,
1511    width: f32,
1512    style: &ChatWidgetStyle,
1513    message: &ChatMessage,
1514    geometry: &ChatMessageGeometry,
1515) -> f32 {
1516    let padding = message_padding(style);
1517    let message_y = y + geometry.y;
1518    let rect = Rect::new(x, message_y, width.max(0.0), geometry.height);
1519    debug_assert!(geometry.body_height >= 0.0);
1520
1521    ctx.push(DrawCmd::RRect(DrawRRect {
1522        rect,
1523        radius: style.message_radius,
1524        color: message_background(style, message),
1525    }));
1526    paint_layout(
1527        ctx,
1528        geometry.role_layout.clone(),
1529        x + padding,
1530        message_y + padding,
1531        style.role_text.color,
1532    );
1533    paint_layout(
1534        ctx,
1535        geometry.body_layout.clone(),
1536        x + padding,
1537        message_y + padding + geometry.role_height + 4.0,
1538        style.text.color,
1539    );
1540    paint_inline_button(
1541        ctx,
1542        rect_to_absolute(geometry.copy_rect, x, y),
1543        "Copy",
1544        style,
1545    );
1546    if let Some(retry) = geometry.retry_rect {
1547        paint_inline_button(ctx, rect_to_absolute(retry, x, y), "Retry", style);
1548    }
1549
1550    geometry.height
1551}
1552
1553/// Paints a single unwrapped line when a text system is available.
1554fn paint_plain_text(
1555    ctx: &mut PaintCtx<'_>,
1556    text: &str,
1557    x: f32,
1558    y: f32,
1559    width: f32,
1560    style: TextStyle,
1561) {
1562    if let Some(layout) = layout_text(ctx, text, style, width, WrapMode::NoWrap) {
1563        paint_layout(ctx, layout, x, y, style.color);
1564    }
1565}
1566
1567/// Paints a retained transcript action surface and vertically centered label.
1568fn paint_inline_button(ctx: &mut PaintCtx<'_>, rect: Rect, label: &str, style: &ChatWidgetStyle) {
1569    ctx.push(DrawCmd::RRect(DrawRRect {
1570        rect,
1571        radius: style.inline_button_radius,
1572        color: style.header_background.with_alpha(0.72),
1573    }));
1574    if let Some(layout) = layout_text(ctx, label, style.muted, rect.w, WrapMode::NoWrap) {
1575        let text_y = rect.y + (rect.h - text_layout_height(Some(&layout), style.muted)) * 0.5;
1576        paint_layout(ctx, layout, rect.x + 8.0, text_y, style.muted.color);
1577    }
1578}
1579
1580/// Creates a cached layout with a nonnegative maximum width.
1581///
1582/// Returns `None` when the paint context has no text system.
1583fn layout_text(
1584    ctx: &mut PaintCtx<'_>,
1585    text: &str,
1586    style: TextStyle,
1587    max_width: f32,
1588    wrap_mode: WrapMode,
1589) -> Option<Arc<PreparedTextLayout>> {
1590    let ts = ctx.text_system.as_deref_mut()?;
1591    Some(ts.layout_cached(TextLayoutParams {
1592        text,
1593        style,
1594        max_width: Some(max_width.max(0.0)),
1595        wrap_mode,
1596    }))
1597}
1598
1599/// Emits a text draw command positioned from the first-line baseline.
1600fn paint_layout(
1601    ctx: &mut PaintCtx<'_>,
1602    layout: Arc<PreparedTextLayout>,
1603    x: f32,
1604    y: f32,
1605    color: Color,
1606) {
1607    let baseline = layout
1608        .lines
1609        .first()
1610        .map(|line| line.baseline_y)
1611        .unwrap_or(0.0);
1612    ctx.push(DrawCmd::Text(DrawText {
1613        pos: [x, y + baseline],
1614        color,
1615        decoration: ailloli_ui_core::TextDecoration::None,
1616        layout,
1617    }));
1618}
1619
1620/// Returns measured height or a `1.25 * font size` logical-pixel fallback.
1621fn text_layout_height(layout: Option<&Arc<PreparedTextLayout>>, style: TextStyle) -> f32 {
1622    layout
1623        .map(|layout| layout.metrics.height)
1624        .unwrap_or(style.px_size as f32 * 1.25)
1625}
1626
1627impl ChatMessagesGeometry {
1628    /// Checks width tolerance, item count, IDs, and rendered text cache keys.
1629    ///
1630    /// Widths within 0.5 logical pixels are treated as equivalent.
1631    fn matches(&self, session: &ChatSessionState, width: f32) -> bool {
1632        if (self.width - width).abs() > 0.5 || self.items.len() != session.messages.len() {
1633            return false;
1634        }
1635        self.items
1636            .iter()
1637            .zip(session.messages.iter())
1638            .all(|(item, message)| {
1639                item.item_id == message.id
1640                    && item.role_text == message_role_text(message)
1641                    && item.body_text == message_body_text(message)
1642            })
1643    }
1644}
1645
1646/// Measures all transcript geometry with the supplied or a temporary text system.
1647fn measure_chat_messages_geometry(
1648    text_system: Option<&mut TextSystem>,
1649    session: &ChatSessionState,
1650    style: &ChatWidgetStyle,
1651    width: f32,
1652) -> ChatMessagesGeometry {
1653    if let Some(text_system) = text_system {
1654        measure_chat_messages_geometry_with_text_system(text_system, session, style, width)
1655    } else {
1656        let mut text_system = TextSystem::new();
1657        measure_chat_messages_geometry_with_text_system(&mut text_system, session, style, width)
1658    }
1659}
1660
1661/// Measures messages in order and inserts `message_gap` before every item but the first.
1662fn measure_chat_messages_geometry_with_text_system(
1663    text_system: &mut TextSystem,
1664    session: &ChatSessionState,
1665    style: &ChatWidgetStyle,
1666    width: f32,
1667) -> ChatMessagesGeometry {
1668    let mut y = 0.0;
1669    let mut items = Vec::with_capacity(session.messages.len());
1670    for (idx, message) in session.messages.iter().enumerate() {
1671        if idx > 0 {
1672            y += style.message_gap;
1673        }
1674        let item = measure_message_geometry(text_system, message, style, width, y);
1675        y += item.height;
1676        items.push(item);
1677    }
1678    ChatMessagesGeometry {
1679        width,
1680        items,
1681        total_height: y,
1682    }
1683}
1684
1685/// Measures one message's text, bubble height, and local action rectangles.
1686fn measure_message_geometry(
1687    text_system: &mut TextSystem,
1688    message: &ChatMessage,
1689    style: &ChatWidgetStyle,
1690    width: f32,
1691    y: f32,
1692) -> ChatMessageGeometry {
1693    let padding = message_padding(style);
1694    let content_width = (width - padding * 2.0).max(0.0);
1695    let role_text = message_role_text(message);
1696    let body_text = message_body_text(message);
1697    let role_layout = text_system.layout_cached(TextLayoutParams {
1698        text: &role_text,
1699        style: style.role_text,
1700        max_width: Some(content_width),
1701        wrap_mode: WrapMode::NoWrap,
1702    });
1703    let body_layout = text_system.layout_cached(TextLayoutParams {
1704        text: &body_text,
1705        style: style.text,
1706        max_width: Some(content_width),
1707        wrap_mode: WrapMode::WordOrAnywhere,
1708    });
1709    let role_height = text_layout_height(Some(&role_layout), style.role_text);
1710    let body_height = text_layout_height(Some(&body_layout), style.text);
1711    let action_y = y + padding + role_height + 4.0 + body_height + 6.0;
1712    let copy_rect = Rect::new(padding, action_y, 48.0, action_button_height());
1713    let retry_rect = message_is_retryable(message)
1714        .then(|| Rect::new(padding + 54.0, action_y, 50.0, action_button_height()));
1715    ChatMessageGeometry {
1716        item_id: message.id.clone(),
1717        role_text,
1718        body_text,
1719        y,
1720        height: padding * 2.0 + role_height + 4.0 + body_height + 6.0 + action_button_height(),
1721        role_height,
1722        body_height,
1723        role_layout,
1724        body_layout,
1725        copy_rect,
1726        retry_rect,
1727    }
1728}
1729
1730/// Translates a transcript-local rectangle to paint-space coordinates.
1731fn rect_to_absolute(rect: Rect, x: f32, y: f32) -> Rect {
1732    Rect::new(x + rect.x, y + rect.y, rect.w, rect.h)
1733}
1734
1735/// Formats the lowercase role, kind, and non-complete status suffix.
1736fn message_role_text(message: &ChatMessage) -> String {
1737    format!(
1738        "{} / {}{}",
1739        role_label(message.role),
1740        kind_label(message.kind),
1741        status_suffix(message.status)
1742    )
1743}
1744
1745/// Returns message text or the visible `...` sentinel for an empty body.
1746fn message_body_text(message: &ChatMessage) -> String {
1747    if message.text.is_empty() {
1748        "...".to_string()
1749    } else {
1750        message.text.clone()
1751    }
1752}
1753
1754/// Reports whether Retry is available for the message's role and request ID.
1755fn message_is_retryable(message: &ChatMessage) -> bool {
1756    match message.role {
1757        ChatRole::User => true,
1758        ChatRole::Assistant => message.request_id.is_some(),
1759        ChatRole::System | ChatRole::Tool => false,
1760    }
1761}
1762
1763/// Returns 6 compact or 8 regular logical pixels of bubble padding.
1764fn message_padding(style: &ChatWidgetStyle) -> f32 {
1765    if style.compact {
1766        6.0
1767    } else {
1768        8.0
1769    }
1770}
1771
1772/// Returns the retained action hit height in logical pixels.
1773fn action_button_height() -> f32 {
1774    22.0
1775}
1776
1777/// Builds a tree-based ghost action button for custom-renderer fallback paths.
1778fn action_button<A: 'static>(
1779    label: &'static str,
1780    action: ChatWidgetAction,
1781    handlers: ChatWidgetHandlers<A>,
1782) -> Button<A> {
1783    Button::with_label_variant(label, ButtonVariant::Ghost)
1784        .height(24.0)
1785        .on_click_ctx(move |ctx| {
1786            emit_chat_widget_action(ctx, &handlers, action.clone());
1787        })
1788}
1789
1790/// Invokes the general handler first, then the matching specialized handler.
1791fn emit_chat_widget_action<A>(
1792    ctx: &mut EventCtx<A>,
1793    handlers: &ChatWidgetHandlers<A>,
1794    action: ChatWidgetAction,
1795) {
1796    if let Some(handler) = &handlers.on_action {
1797        handler(ctx, action.clone());
1798    }
1799    match action {
1800        ChatWidgetAction::Send { text } => {
1801            if let Some(handler) = &handlers.on_send {
1802                handler(ctx, text);
1803            }
1804        }
1805        ChatWidgetAction::Copy { item_id, text } => {
1806            if let Some(handler) = &handlers.on_copy {
1807                handler(ctx, item_id, text);
1808            }
1809        }
1810        ChatWidgetAction::Retry { item_id } => {
1811            if let Some(handler) = &handlers.on_retry {
1812                handler(ctx, item_id);
1813            }
1814        }
1815        ChatWidgetAction::SetComposerDraft { .. }
1816        | ChatWidgetAction::SetComposerPermission { .. }
1817        | ChatWidgetAction::SetComposerModel { .. }
1818        | ChatWidgetAction::SetComposerReasoning { .. }
1819        | ChatWidgetAction::SetComposerHeight { .. }
1820        | ChatWidgetAction::StopTurn => {}
1821    }
1822}
1823
1824/// Chooses error background first, otherwise maps the message role to a surface.
1825fn message_background(style: &ChatWidgetStyle, message: &ChatMessage) -> Color {
1826    if message.kind == ChatMessageKind::Error || message.status == ChatMessageStatus::Failed {
1827        return style.error_background;
1828    }
1829    match message.role {
1830        ChatRole::User => style.user_background,
1831        ChatRole::Assistant => style.assistant_background,
1832        ChatRole::System | ChatRole::Tool => style.tool_background,
1833    }
1834}
1835
1836/// Returns the stable lowercase role label.
1837fn role_label(role: ChatRole) -> &'static str {
1838    match role {
1839        ChatRole::System => "system",
1840        ChatRole::User => "user",
1841        ChatRole::Assistant => "assistant",
1842        ChatRole::Tool => "tool",
1843    }
1844}
1845
1846/// Returns the stable lowercase message-kind label.
1847fn kind_label(kind: ChatMessageKind) -> &'static str {
1848    match kind {
1849        ChatMessageKind::Text => "text",
1850        ChatMessageKind::Reasoning => "reasoning",
1851        ChatMessageKind::Command => "command",
1852        ChatMessageKind::FileChange => "file",
1853        ChatMessageKind::ToolCall => "tool",
1854        ChatMessageKind::Status => "status",
1855        ChatMessageKind::Error => "error",
1856    }
1857}
1858
1859/// Returns an optional leading-space status suffix; complete has none.
1860fn status_suffix(status: ChatMessageStatus) -> &'static str {
1861    match status {
1862        ChatMessageStatus::Pending => " pending",
1863        ChatMessageStatus::Streaming => " streaming",
1864        ChatMessageStatus::Complete => "",
1865        ChatMessageStatus::Failed => " failed",
1866    }
1867}
1868
1869/// Returns the stable lowercase session-status label.
1870fn session_status_label(status: ChatSessionStatus) -> &'static str {
1871    match status {
1872        ChatSessionStatus::Idle => "idle",
1873        ChatSessionStatus::Ready => "ready",
1874        ChatSessionStatus::Running => "running",
1875        ChatSessionStatus::Waiting => "waiting",
1876        ChatSessionStatus::Failed => "failed",
1877        ChatSessionStatus::Completed => "completed",
1878    }
1879}