Skip to main content

lumen_dioxus/data/
ai.rs

1//! AI surfaces: `PromptComposer`, `StreamMessage`, `SourceCitation`, `ToolActivity`,
2//! `ApprovalCard`, `Reasoning`, `MessageActions`, and `PromptSuggestions`.
3//!
4//! They show application-owned state; none of them calls a model or performs the requested
5//! operation. Each emits a typed request that the application must still authorize.
6
7// cspell:words feff hexdigit onreset
8
9use std::collections::HashMap;
10
11use dioxus::prelude::*;
12
13use crate::class::compose;
14use crate::hooks::{use_controllable, use_unique_id};
15use crate::{Button, ButtonSize, ButtonVariant, CopyButton, Label};
16
17const VERTICAL_STACK_GROUP: &str = "ui-stack ui-stack--vertical ui-stack--gap-group ui-stack--align-stretch ui-stack--justify-start";
18const VERTICAL_STACK_RELATED: &str = "ui-stack ui-stack--vertical ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start";
19const HORIZONTAL_STACK_RELATED: &str = "ui-stack ui-stack--horizontal ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start ui-stack--wrap";
20
21/// Default most characters a [`PromptComposer`] accepts.
22pub const PROMPT_COMPOSER_DEFAULT_LIMIT: u32 = 4000;
23
24/// A usable prompt length limit: 1 to `i32::MAX`, defaulting to 4000 for zero.
25pub fn normalize_prompt_composer_limit(limit: Option<u32>) -> u32 {
26    match limit {
27        None | Some(0) => PROMPT_COMPOSER_DEFAULT_LIMIT,
28        Some(limit) => limit.min(2_147_483_647),
29    }
30}
31
32/// Whether a prompt can be sent: not blank and within `limit` UTF-16 code units, like the
33/// browser's `maxlength`.
34pub fn can_submit_prompt_composer(text: &str, limit: u32) -> bool {
35    !text.trim().is_empty()
36        && text.encode_utf16().count()
37            <= usize::try_from(normalize_prompt_composer_limit(Some(limit))).unwrap_or(usize::MAX)
38}
39
40/// The request a [`PromptComposer`] emits when the user sends a prompt.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct PromptComposerSubmitDetail {
43    /// The prompt, trimmed.
44    pub text: String,
45}
46
47/// Props for [`PromptComposer`].
48#[derive(Props, Clone, PartialEq)]
49pub struct PromptComposerProps {
50    /// Controlled prompt text.
51    #[props(into)]
52    pub value: Option<String>,
53    /// Initial text when uncontrolled; also the value a form reset restores.
54    #[props(default, into)]
55    pub default_value: String,
56    /// Called with the text on every edit.
57    pub on_value_change: Option<EventHandler<String>>,
58    /// Called with the trimmed prompt when the user sends it.
59    pub on_prompt_submit: Option<EventHandler<PromptComposerSubmitDetail>>,
60    /// Called when the user asks to stop a pending response.
61    pub on_stop: Option<EventHandler<()>>,
62    /// Disables the input and both buttons.
63    #[props(default)]
64    pub disabled: bool,
65    /// Marks a response in progress: disables sending and shows the stop button.
66    #[props(default)]
67    pub pending: bool,
68    /// Sends on Enter; Shift+Enter still inserts a new line.
69    #[props(default)]
70    pub submit_on_enter: bool,
71    /// Most characters accepted. Defaults to 4000.
72    pub max_length: Option<u32>,
73    /// Visible label of the input. Defaults to `Message`.
74    #[props(default = "Message".to_string(), into)]
75    pub label: String,
76    /// Send button text. Defaults to `Send`.
77    #[props(default = "Send".to_string(), into)]
78    pub send_label: String,
79    /// Stop button text. Defaults to `Stop`.
80    #[props(default = "Stop".to_string(), into)]
81    pub stop_label: String,
82    /// Form id. The input id becomes `{id}-input`; generated when unset.
83    #[props(into)]
84    pub id: Option<String>,
85    /// Extra controls before the send button, such as an attachment button.
86    pub actions: Option<Element>,
87    /// Extra classes appended after the Lumen classes.
88    #[props(into)]
89    pub class: Option<String>,
90    /// Any other `<form>` or global attribute.
91    #[props(extends = GlobalAttributes, extends = form)]
92    pub attributes: Vec<Attribute>,
93    /// Content after the buttons, such as a hint.
94    pub children: Element,
95}
96
97/// An accessible prompt input with send and stop requests.
98///
99/// The form never submits to a server: sending calls `on_prompt_submit` with the trimmed text.
100#[component]
101pub fn PromptComposer(props: PromptComposerProps) -> Element {
102    let generated = use_unique_id();
103    let input_id = props
104        .id
105        .as_ref()
106        .map_or(generated, |id| format!("{id}-input"));
107    let default_value = props.default_value.clone();
108    let draft = use_controllable(
109        props.value.clone(),
110        || props.default_value.clone(),
111        props.on_value_change,
112    );
113    let text = draft.get();
114    let limit = normalize_prompt_composer_limit(props.max_length);
115    let (disabled, pending) = (props.disabled, props.pending);
116    let send_disabled = disabled || pending || !can_submit_prompt_composer(&text, limit);
117    let submit_on_enter = props.submit_on_enter;
118    let (on_submit, on_stop) = (props.on_prompt_submit, props.on_stop);
119    let class = compose([Some("ui-form ui-prompt-composer"), props.class.as_deref()]);
120    let submit = move || {
121        let current = draft.peek();
122
123        if disabled || pending || !can_submit_prompt_composer(&current, limit) {
124            return;
125        }
126
127        if let Some(handler) = on_submit {
128            handler.call(PromptComposerSubmitDetail {
129                text: current.trim().to_string(),
130            });
131        }
132    };
133
134    rsx! {
135        form {
136            aria_busy: pending.then_some("true"),
137            class,
138            "data-disabled": "{disabled}",
139            "data-pending": "{pending}",
140            "data-status": if pending { "submitting" } else { "idle" },
141            "data-submit-on-enter": "{submit_on_enter}",
142            "data-ui-prompt-composer": "true",
143            id: props.id.clone(),
144            method: "post",
145            onsubmit: move |event| {
146                event.prevent_default();
147                submit();
148            },
149            onreset: move |_| {
150                if !draft.is_controlled() {
151                    draft.set(default_value.clone());
152                }
153            },
154            ..props.attributes,
155            Label { r#for: "{input_id}", "{props.label}" }
156            textarea {
157                class: "ui-textarea",
158                "data-ui-prompt-input": "true",
159                disabled,
160                id: "{input_id}",
161                maxlength: "{limit}",
162                name: "prompt",
163                required: true,
164                rows: "3",
165                value: "{text}",
166                oninput: move |event| draft.set(event.value()),
167                onkeydown: move |event| {
168                    let modifiers = event.modifiers();
169
170                    if !submit_on_enter || event.key() != Key::Enter || event.is_composing()
171                        || modifiers.shift() || modifiers.alt() || modifiers.ctrl() || modifiers.meta()
172                    {
173                        return;
174                    }
175
176                    event.prevent_default();
177                    submit();
178                },
179            }
180            div {
181                class: HORIZONTAL_STACK_RELATED,
182                "data-direction": "horizontal",
183                "data-ui-stack": "true",
184                if let Some(actions) = props.actions {
185                    {actions}
186                }
187                Button {
188                    "data-ui-prompt-send": "true",
189                    disabled: send_disabled,
190                    r#type: "submit",
191                    // Dioxus Native reports no submit events, so the button sends the prompt itself
192                    // and keeps the browser from submitting the form again.
193                    onclick: move |event: MouseEvent| {
194                        event.prevent_default();
195                        submit();
196                    },
197                    "{props.send_label}"
198                }
199                Button {
200                    "data-ui-prompt-stop": "true",
201                    disabled,
202                    hidden: !pending,
203                    variant: ButtonVariant::Secondary,
204                    onclick: move |_| {
205                        if pending
206                            && !disabled
207                            && let Some(handler) = on_stop
208                        {
209                            handler.call(());
210                        }
211                    },
212                    "{props.stop_label}"
213                }
214            }
215            {props.children}
216        }
217    }
218}
219
220/// Lifecycle of a [`StreamMessage`] or a [`Reasoning`].
221#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
222#[non_exhaustive]
223pub enum StreamMessageStatus {
224    /// Not started.
225    #[default]
226    Idle,
227    /// Content is arriving; the content region is marked busy.
228    Streaming,
229    /// Finished.
230    Complete,
231    /// Failed.
232    Error,
233    /// Stopped by the user.
234    Canceled,
235}
236
237impl StreamMessageStatus {
238    /// The `data-status` value.
239    pub fn as_str(self) -> &'static str {
240        match self {
241            Self::Idle => "idle",
242            Self::Streaming => "streaming",
243            Self::Complete => "complete",
244            Self::Error => "error",
245            Self::Canceled => "canceled",
246        }
247    }
248}
249
250/// Props for [`StreamMessage`].
251#[derive(Props, Clone, PartialEq)]
252pub struct StreamMessageProps {
253    /// Lifecycle state.
254    #[props(default)]
255    pub status: StreamMessageStatus,
256    /// Concise status announced politely, such as `Writing a reply`.
257    #[props(into)]
258    pub status_label: String,
259    /// Accessible name of the message. Defaults to `Assistant`.
260    #[props(default = "Assistant".to_string(), into)]
261    pub label: String,
262    /// Controls after the status, such as copy or retry.
263    pub actions: Option<Element>,
264    /// Citations shown after the message, usually [`SourceCitation`]s.
265    pub sources: Option<Element>,
266    /// Extra classes appended after the Lumen classes.
267    #[props(into)]
268    pub class: Option<String>,
269    /// Any other `<article>` or global attribute.
270    #[props(extends = GlobalAttributes, extends = article)]
271    pub attributes: Vec<Attribute>,
272    /// The streamed content. It is not a live region, so tokens are not announced one by one.
273    pub children: Element,
274}
275
276/// An assistant message that separates streaming content from concise status announcements.
277#[component]
278pub fn StreamMessage(props: StreamMessageProps) -> Element {
279    let class = compose([
280        Some("ui-message ui-message--assistant ui-stream-message"),
281        props.class.as_deref(),
282    ]);
283    let streaming = props.status == StreamMessageStatus::Streaming;
284
285    rsx! {
286        article {
287            aria_label: "{props.label}",
288            class,
289            "data-from": "assistant",
290            "data-status": props.status.as_str(),
291            ..props.attributes,
292            div {
293                aria_busy: if streaming { "true" } else { "false" },
294                aria_live: "off",
295                class: "ui-prose",
296                "data-slot": "prose",
297                "data-ui-stream-content": "true",
298                {props.children}
299            }
300            div {
301                class: HORIZONTAL_STACK_RELATED,
302                "data-direction": "horizontal",
303                "data-ui-stack": "true",
304                span { aria_live: "polite", role: "status", "{props.status_label}" }
305                if let Some(actions) = props.actions {
306                    {actions}
307                }
308            }
309            if let Some(sources) = props.sources {
310                {sources}
311            }
312        }
313    }
314}
315
316fn is_unsafe_url_character(character: char) -> bool {
317    u32::from(character) <= 32 || character == '\u{7f}' || character == '\\'
318}
319
320fn is_forbidden_host_character(byte: u8) -> bool {
321    !byte.is_ascii_graphic()
322        || matches!(
323            byte,
324            b'#' | b'%'
325                | b'/'
326                | b':'
327                | b'<'
328                | b'>'
329                | b'?'
330                | b'@'
331                | b'['
332                | b'\\'
333                | b']'
334                | b'^'
335                | b'|'
336        )
337}
338
339const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
340
341fn percent_encode(out: &mut String, text: &str, extra: &[u8]) {
342    for character in text.chars() {
343        if character.is_ascii() && !extra.contains(&(character as u8)) {
344            out.push(character);
345        } else {
346            let mut buffer = [0; 4];
347
348            for byte in character.encode_utf8(&mut buffer).bytes() {
349                out.push('%');
350                out.push(char::from(HEX_DIGITS[usize::from(byte >> 4)]));
351                out.push(char::from(HEX_DIGITS[usize::from(byte & 0x0f)]));
352            }
353        }
354    }
355}
356
357fn is_dot_segment(segment: &str, double: bool) -> bool {
358    let lower = segment.to_ascii_lowercase();
359
360    if double {
361        matches!(lower.as_str(), ".." | ".%2e" | "%2e." | "%2e%2e")
362    } else {
363        matches!(lower.as_str(), "." | "%2e")
364    }
365}
366
367/// Resolves `rest` (`/path?query#fragment`) the way the URL parser serializes it.
368fn serialize_path(rest: &str) -> String {
369    let (before_fragment, fragment) = match rest.split_once('#') {
370        Some((head, fragment)) => (head, Some(fragment)),
371        None => (rest, None),
372    };
373    let (path, query) = match before_fragment.split_once('?') {
374        Some((path, query)) => (path, Some(query)),
375        None => (before_fragment, None),
376    };
377    let mut segments: Vec<&str> = Vec::new();
378    let raw: Vec<&str> = path.split('/').skip(1).collect();
379
380    for (index, segment) in raw.iter().enumerate() {
381        let last = index + 1 == raw.len();
382
383        if is_dot_segment(segment, true) {
384            segments.pop();
385
386            if last {
387                segments.push("");
388            }
389        } else if is_dot_segment(segment, false) {
390            if last {
391                segments.push("");
392            }
393        } else {
394            segments.push(segment);
395        }
396    }
397
398    let mut out = String::new();
399
400    if segments.is_empty() {
401        out.push('/');
402    }
403
404    for segment in segments {
405        out.push('/');
406        percent_encode(&mut out, segment, b"\"<>`{}");
407    }
408
409    if let Some(query) = query {
410        out.push('?');
411        percent_encode(&mut out, query, b"\"<>'");
412    }
413
414    if let Some(fragment) = fragment {
415        out.push('#');
416        percent_encode(&mut out, fragment, b"\"<>`");
417    }
418
419    out
420}
421
422fn web_citation_href(value: &str) -> Option<String> {
423    let (scheme, rest) = value.split_once(':')?;
424    let scheme = scheme.to_ascii_lowercase();
425    let default_port = match scheme.as_str() {
426        "http" => "80",
427        "https" => "443",
428        _ => return None,
429    };
430    let rest = rest.trim_start_matches('/');
431    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
432    let (authority, path) = rest.split_at(authority_end);
433
434    if authority.contains('@') {
435        return None;
436    }
437
438    let (host, port) = if let Some(inner) = authority.strip_prefix('[') {
439        let (address, after) = inner.split_once(']')?;
440
441        if address.is_empty()
442            || !address
443                .bytes()
444                .all(|byte| byte.is_ascii_hexdigit() || byte == b':' || byte == b'.')
445        {
446            return None;
447        }
448
449        (
450            format!("[{}]", address.to_ascii_lowercase()),
451            after.strip_prefix(':'),
452        )
453    } else {
454        let (host, port) = match authority.split_once(':') {
455            Some((host, port)) => (host, Some(port)),
456            None => (authority, None),
457        };
458
459        if host.is_empty() || host.bytes().any(is_forbidden_host_character) {
460            return None;
461        }
462
463        (host.to_ascii_lowercase(), port)
464    };
465
466    let port = match port {
467        None | Some("") => None,
468        Some(port) if port.len() <= 5 && port.bytes().all(|byte| byte.is_ascii_digit()) => {
469            let number: u32 = port.parse().ok()?;
470
471            if number > 65_535 {
472                return None;
473            }
474
475            let number = number.to_string();
476            (number != default_port).then_some(number)
477        }
478        Some(_) => return None,
479    };
480
481    let mut href = format!("{scheme}://{host}");
482
483    if let Some(port) = port {
484        href.push(':');
485        href.push_str(&port);
486    }
487
488    let path = if path.starts_with('/') {
489        path.to_string()
490    } else {
491        format!("/{path}")
492    };
493    href.push_str(&serialize_path(&path));
494
495    Some(href)
496}
497
498/// A safe citation destination: an `http` or `https` URL without credentials (serialized the way
499/// the browser URL parser does for common inputs), or a local absolute path such as `/docs`.
500/// Executable schemes, protocol-relative URLs, and URLs with control characters, spaces, or
501/// backslashes return `None`.
502pub fn resolve_source_citation_href(value: &str) -> Option<String> {
503    if value.chars().any(is_unsafe_url_character) {
504        return None;
505    }
506
507    if value.starts_with('/') && !value.starts_with("//") {
508        return Some(value.to_string());
509    }
510
511    web_citation_href(value)
512}
513
514/// Props for [`SourceCitation`].
515#[derive(Props, Clone, PartialEq)]
516pub struct SourceCitationProps {
517    /// Destination. Unsafe values render the citation as plain text.
518    #[props(into)]
519    pub href: String,
520    /// Visible name of the source.
521    #[props(into)]
522    pub label: String,
523    /// Extra classes appended after the Lumen classes.
524    #[props(into)]
525    pub class: Option<String>,
526    /// Any other `<a>` or global attribute.
527    #[props(extends = GlobalAttributes, extends = a)]
528    pub attributes: Vec<Attribute>,
529    /// Text after the label, such as a page number.
530    pub children: Element,
531}
532
533/// A named source link restricted to safe web URLs and local paths.
534#[component]
535pub fn SourceCitation(props: SourceCitationProps) -> Element {
536    let href = resolve_source_citation_href(&props.href);
537
538    if let Some(href) = href {
539        let class = compose([Some("ui-link ui-source-citation"), props.class.as_deref()]);
540
541        return rsx! {
542            a {
543                class,
544                "data-slot": "link",
545                "data-variant": "default",
546                href,
547                rel: "noopener noreferrer",
548                ..props.attributes,
549                "{props.label}"
550                {props.children}
551            }
552        };
553    }
554
555    let class = compose([Some("ui-source-citation"), props.class.as_deref()]);
556
557    rsx! {
558        span { class, "{props.label}" {props.children} }
559    }
560}
561
562/// Lifecycle of a [`ToolActivity`].
563#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
564#[non_exhaustive]
565pub enum ToolActivityStatus {
566    /// Waiting to run.
567    #[default]
568    Queued,
569    /// In progress.
570    Running,
571    /// Finished successfully.
572    Success,
573    /// Failed.
574    Error,
575    /// Stopped.
576    Canceled,
577}
578
579impl ToolActivityStatus {
580    /// The `data-status` value.
581    pub fn as_str(self) -> &'static str {
582        match self {
583            Self::Queued => "queued",
584            Self::Running => "running",
585            Self::Success => "success",
586            Self::Error => "error",
587            Self::Canceled => "canceled",
588        }
589    }
590}
591
592/// Props for [`ToolActivity`].
593#[derive(Props, Clone, PartialEq)]
594pub struct ToolActivityProps {
595    /// Summary text naming the tool call.
596    #[props(into)]
597    pub label: String,
598    /// Lifecycle state.
599    #[props(default)]
600    pub status: ToolActivityStatus,
601    /// Concise status, exposed as a status region.
602    #[props(into)]
603    pub status_label: String,
604    /// Controlled disclosure state.
605    pub open: Option<bool>,
606    /// Initial disclosure state when uncontrolled.
607    #[props(default)]
608    pub default_open: bool,
609    /// Called with the new disclosure state.
610    pub on_open_change: Option<EventHandler<bool>>,
611    /// Extra classes appended after the Lumen classes.
612    #[props(into)]
613    pub class: Option<String>,
614    /// Any other `<details>` or global attribute.
615    #[props(extends = GlobalAttributes, extends = details)]
616    pub attributes: Vec<Attribute>,
617    /// Tool input, progress, or results.
618    pub children: Element,
619}
620
621/// A disclosure of application-owned tool progress and results.
622#[component]
623pub fn ToolActivity(props: ToolActivityProps) -> Element {
624    let open = use_controllable(props.open, || props.default_open, props.on_open_change);
625    let class = compose([
626        Some("ui-collapsible ui-tool-activity"),
627        props.class.as_deref(),
628    ]);
629
630    rsx! {
631        details {
632            class,
633            "data-status": props.status.as_str(),
634            "data-ui-collapsible": "true",
635            open: open.get(),
636            ..props.attributes,
637            summary {
638                onclick: move |event| {
639                    event.prevent_default();
640                    open.set(!open.peek());
641                },
642                "{props.label}"
643            }
644            div {
645                class: VERTICAL_STACK_RELATED,
646                "data-direction": "vertical",
647                "data-ui-stack": "true",
648                span { role: "status", "{props.status_label}" }
649                {props.children}
650            }
651        }
652    }
653}
654
655/// State of an [`ApprovalCard`] request.
656#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
657#[non_exhaustive]
658pub enum ApprovalCardStatus {
659    /// Waiting for a decision; the buttons are enabled.
660    #[default]
661    Pending,
662    /// Approved.
663    Approved,
664    /// Rejected.
665    Rejected,
666}
667
668impl ApprovalCardStatus {
669    /// The `data-status` value.
670    pub fn as_str(self) -> &'static str {
671        match self {
672            Self::Pending => "pending",
673            Self::Approved => "approved",
674            Self::Rejected => "rejected",
675        }
676    }
677}
678
679/// The decision an [`ApprovalCard`] requests.
680#[derive(Clone, Copy, Debug, PartialEq, Eq)]
681pub enum ApprovalCardResponse {
682    /// Approve the request.
683    Approve,
684    /// Reject the request.
685    Reject,
686}
687
688impl ApprovalCardResponse {
689    /// The `data-ui-approval-response` value.
690    pub fn as_str(self) -> &'static str {
691        match self {
692            Self::Approve => "approve",
693            Self::Reject => "reject",
694        }
695    }
696}
697
698/// The request an [`ApprovalCard`] emits. The application must still authorize the operation.
699#[derive(Clone, Debug, PartialEq, Eq)]
700pub struct ApprovalCardResponseDetail {
701    /// The pending request id.
702    pub request_id: String,
703    /// The decision.
704    pub response: ApprovalCardResponse,
705}
706
707/// Props for [`ApprovalCard`].
708#[derive(Props, Clone, PartialEq)]
709pub struct ApprovalCardProps {
710    /// Heading and accessible name, such as `Delete 3 files`.
711    #[props(into)]
712    pub label: String,
713    /// Application-owned id of the pending request.
714    #[props(into)]
715    pub request_id: String,
716    /// Request state; only pending requests accept a decision.
717    #[props(default)]
718    pub status: ApprovalCardStatus,
719    /// Concise status, exposed as a status region.
720    #[props(into)]
721    pub status_label: String,
722    /// Disables both buttons.
723    #[props(default)]
724    pub disabled: bool,
725    /// Approve button text. Defaults to `Approve`.
726    #[props(default = "Approve".to_string(), into)]
727    pub approve_label: String,
728    /// Reject button text. Defaults to `Reject`.
729    #[props(default = "Reject".to_string(), into)]
730    pub reject_label: String,
731    /// Called with the decision.
732    pub on_response: Option<EventHandler<ApprovalCardResponseDetail>>,
733    /// Extra classes appended after the Lumen classes.
734    #[props(into)]
735    pub class: Option<String>,
736    /// Any other `<div>` or global attribute.
737    #[props(extends = GlobalAttributes, extends = div)]
738    pub attributes: Vec<Attribute>,
739    /// Details of the request.
740    pub children: Element,
741}
742
743/// Collects an explicit decision for an application-owned pending request.
744#[component]
745pub fn ApprovalCard(props: ApprovalCardProps) -> Element {
746    // The markup of a comfortable default `Card`, written out so the root can spread attributes.
747    let class = compose([
748        Some("ui-card ui-card--comfortable ui-approval-card"),
749        props.class.as_deref(),
750    ]);
751    let locked = props.disabled || props.status != ApprovalCardStatus::Pending;
752    let buttons_disabled = locked || props.request_id.is_empty();
753    let respond = {
754        let request_id = props.request_id.clone();
755        let on_response = props.on_response;
756
757        move |response: ApprovalCardResponse| {
758            if buttons_disabled {
759                return;
760            }
761
762            if let Some(handler) = on_response {
763                handler.call(ApprovalCardResponseDetail {
764                    request_id: request_id.clone(),
765                    response,
766                });
767            }
768        }
769    };
770    let approve = respond.clone();
771
772    rsx! {
773        div {
774            aria_label: "{props.label}",
775            class,
776            "data-density": "comfortable",
777            "data-disabled": "{props.disabled}",
778            "data-request-id": "{props.request_id}",
779            "data-slot": "card",
780            "data-status": props.status.as_str(),
781            "data-ui-approval-card": "true",
782            "data-variant": "default",
783            ..props.attributes,
784            div {
785                class: VERTICAL_STACK_GROUP,
786                "data-direction": "vertical",
787                "data-ui-stack": "true",
788                strong { "{props.label}" }
789                {props.children}
790                span { role: "status", "{props.status_label}" }
791                div {
792                    class: HORIZONTAL_STACK_RELATED,
793                    "data-direction": "horizontal",
794                    "data-ui-stack": "true",
795                    Button {
796                        "data-ui-approval-response": "approve",
797                        disabled: locked,
798                        onclick: move |_| approve(ApprovalCardResponse::Approve),
799                        "{props.approve_label}"
800                    }
801                    Button {
802                        "data-ui-approval-response": "reject",
803                        disabled: locked,
804                        variant: ButtonVariant::Secondary,
805                        onclick: move |_| respond(ApprovalCardResponse::Reject),
806                        "{props.reject_label}"
807                    }
808                }
809            }
810        }
811    }
812}
813
814/// The inputs of [`resolve_reasoning_open`].
815#[derive(Clone, Copy, Debug, PartialEq, Eq)]
816pub struct ReasoningOpenOptions {
817    /// The status before the change.
818    pub previous: StreamMessageStatus,
819    /// The new status.
820    pub next: StreamMessageStatus,
821    /// Whether the disclosure is open now.
822    pub open: bool,
823    /// The person opened or closed the disclosure themselves; their choice always wins.
824    pub user_toggled: bool,
825    /// Close once when streaming ends.
826    pub collapse_on_complete: bool,
827}
828
829/// Whether a [`Reasoning`] disclosure is open after its status changes, like
830/// `resolveLumenReasoningOpen` in `@santi020k/lumen-core`.
831///
832/// It opens when streaming starts and closes once when streaming ends (unless
833/// `collapse_on_complete` is off). Once the person has opened or closed it, their choice wins.
834pub fn resolve_reasoning_open(options: ReasoningOpenOptions) -> bool {
835    let ReasoningOpenOptions {
836        previous,
837        next,
838        open,
839        user_toggled,
840        collapse_on_complete,
841    } = options;
842
843    if user_toggled || previous == next {
844        return open;
845    }
846
847    if next == StreamMessageStatus::Streaming {
848        return true;
849    }
850
851    if previous == StreamMessageStatus::Streaming && collapse_on_complete {
852        return false;
853    }
854
855    open
856}
857
858/// Disclosure state of a [`Reasoning`]: whether it is open, the status it last followed, and
859/// whether the person toggled it.
860#[derive(Clone, Copy, PartialEq, Eq)]
861struct ReasoningState {
862    open: bool,
863    status: StreamMessageStatus,
864    user_toggled: bool,
865}
866
867/// Props for [`Reasoning`].
868#[derive(Props, Clone, PartialEq)]
869pub struct ReasoningProps {
870    /// Summary text, such as `Thinking…` or `Thought for 12 seconds`. Localize it in the app.
871    #[props(into)]
872    pub label: String,
873    /// Lifecycle of the reasoning. Defaults to `Complete`; it opens while `Streaming`.
874    #[props(default = StreamMessageStatus::Complete)]
875    pub status: StreamMessageStatus,
876    /// Closes once when streaming ends, unless the person already opened or closed it. Defaults
877    /// to `true`.
878    #[props(default = true)]
879    pub collapse_on_complete: bool,
880    /// Initial disclosure state. Leave it unset to start open only while streaming.
881    pub default_open: Option<bool>,
882    /// Extra classes appended after the Lumen class.
883    #[props(into)]
884    pub class: Option<String>,
885    /// Any other `<details>` or global attribute.
886    #[props(extends = GlobalAttributes, extends = details)]
887    pub attributes: Vec<Attribute>,
888    /// The reasoning. It is not a live region, so streamed tokens are not announced one by one.
889    pub children: Element,
890}
891
892/// A collapsible view of a model's reasoning.
893///
894/// It opens while `status` is `Streaming` and closes once when streaming ends; once the person
895/// opens or closes it, their choice wins. The summary toggles the disclosure in Rust on every
896/// renderer instead of relying on the browser's native `<details>` behavior.
897#[component]
898pub fn Reasoning(props: ReasoningProps) -> Element {
899    let status = props.status;
900    let mut state = use_signal(|| ReasoningState {
901        open: props
902            .default_open
903            .unwrap_or(status == StreamMessageStatus::Streaming),
904        status,
905        user_toggled: false,
906    });
907    let current = *state.peek();
908
909    // A status change opens or closes the disclosure once, during render like lumen-react.
910    if current.status != status {
911        state.set(ReasoningState {
912            open: resolve_reasoning_open(ReasoningOpenOptions {
913                previous: current.status,
914                next: status,
915                open: current.open,
916                user_toggled: current.user_toggled,
917                collapse_on_complete: props.collapse_on_complete,
918            }),
919            status,
920            user_toggled: current.user_toggled,
921        });
922    }
923
924    let open = state.read().open;
925    let class = compose([Some("ui-reasoning"), props.class.as_deref()]);
926    let streaming = status == StreamMessageStatus::Streaming;
927
928    rsx! {
929        details {
930            class,
931            "data-collapse-on-complete": "{props.collapse_on_complete}",
932            "data-status": status.as_str(),
933            "data-ui-reasoning": "true",
934            open,
935            ..props.attributes,
936            summary {
937                onclick: move |event| {
938                    event.prevent_default();
939                    let current = *state.peek();
940                    state.set(ReasoningState {
941                        open: !current.open,
942                        user_toggled: true,
943                        ..current
944                    });
945                },
946                span { class: "ui-reasoning__label", "{props.label}" }
947            }
948            div {
949                aria_busy: if streaming { "true" } else { "false" },
950                aria_live: "off",
951                class: "ui-reasoning__content",
952                "data-ui-reasoning-content": "true",
953                {props.children}
954            }
955        }
956    }
957}
958
959/// A rating recorded by [`MessageActions`].
960#[derive(Clone, Copy, Debug, PartialEq, Eq)]
961pub enum MessageFeedback {
962    /// A good response.
963    Positive,
964    /// A bad response.
965    Negative,
966}
967
968impl MessageFeedback {
969    /// The `data-feedback` and `data-ui-message-action` value.
970    pub fn as_str(self) -> &'static str {
971        match self {
972            Self::Positive => "positive",
973            Self::Negative => "negative",
974        }
975    }
976}
977
978/// The rating after the person presses `pressed`, like `nextLumenMessageFeedback` in
979/// `@santi020k/lumen-core`: pressing the current rating clears it, and pressing the other one
980/// replaces it.
981pub fn next_message_feedback(
982    current: Option<MessageFeedback>,
983    pressed: MessageFeedback,
984) -> Option<MessageFeedback> {
985    if current == Some(pressed) {
986        None
987    } else {
988        Some(pressed)
989    }
990}
991
992/// The request a [`MessageActions`] emits when the person rates a message.
993#[derive(Clone, Debug, PartialEq, Eq)]
994pub struct MessageFeedbackDetail {
995    /// The rated message.
996    pub message_id: String,
997    /// The new rating; `None` when the person cleared their earlier choice.
998    pub value: Option<MessageFeedback>,
999}
1000
1001/// The request a [`MessageActions`] emits when the person asks for a new response. The
1002/// application owns regeneration.
1003#[derive(Clone, Debug, PartialEq, Eq)]
1004pub struct MessageRetryDetail {
1005    /// The message to regenerate.
1006    pub message_id: String,
1007}
1008
1009/// Props for [`MessageActions`].
1010#[derive(Props, Clone, PartialEq)]
1011pub struct MessageActionsProps {
1012    /// Identifies the message in retry and feedback requests. Retry and rating stay disabled
1013    /// while it is empty.
1014    #[props(into)]
1015    pub message_id: String,
1016    /// Accessible name of the group. Defaults to `Message actions`.
1017    #[props(default = "Message actions".to_string(), into)]
1018    pub label: String,
1019    /// Text the copy button writes to the clipboard. Omit it to leave copy out.
1020    #[props(into)]
1021    pub copy_value: Option<String>,
1022    /// Copies through the app instead of the browser clipboard (see `CopyButton::on_copy`). Use it
1023    /// on Dioxus Native, which has no clipboard API.
1024    pub on_copy: Option<Callback<String, bool>>,
1025    /// Accessible name of the copy button. Defaults to `Copy`.
1026    #[props(default = "Copy".to_string(), into)]
1027    pub copy_label: String,
1028    /// Accessible name of the copy button after a copy. Defaults to `Copied`.
1029    #[props(default = "Copied".to_string(), into)]
1030    pub copied_label: String,
1031    /// Accessible name of the copy button after a failure. Defaults to `Could not copy`.
1032    #[props(default = "Could not copy".to_string(), into)]
1033    pub copy_error_label: String,
1034    /// Shows a retry button that requests a new response.
1035    #[props(default)]
1036    pub retry: bool,
1037    /// Accessible name of the retry button. Defaults to `Retry`.
1038    #[props(default = "Retry".to_string(), into)]
1039    pub retry_label: String,
1040    /// Shows the good and bad response pair. Defaults to `true`.
1041    #[props(default = true)]
1042    pub show_feedback: bool,
1043    /// Controlled rating: `Some(rating)`, where `rating` is `None` when unrated. Omit it to let
1044    /// the component keep the rating, starting from `default_feedback`.
1045    pub feedback: Option<Option<MessageFeedback>>,
1046    /// Initial rating when `feedback` is not controlled.
1047    pub default_feedback: Option<MessageFeedback>,
1048    /// Accessible name of the good response button. Defaults to `Good response`.
1049    #[props(default = "Good response".to_string(), into)]
1050    pub positive_label: String,
1051    /// Accessible name of the bad response button. Defaults to `Bad response`.
1052    #[props(default = "Bad response".to_string(), into)]
1053    pub negative_label: String,
1054    /// Turns off retry and rating, for example while the answer streams. Copy stays available.
1055    #[props(default)]
1056    pub disabled: bool,
1057    /// Called when the person asks for a new response.
1058    pub on_retry: Option<EventHandler<MessageRetryDetail>>,
1059    /// Called with the new rating; its `value` is `None` when the person cleared their choice.
1060    pub on_feedback: Option<EventHandler<MessageFeedbackDetail>>,
1061    /// Extra classes appended after the Lumen class.
1062    #[props(into)]
1063    pub class: Option<String>,
1064    /// Any other `<div>` or global attribute.
1065    #[props(extends = GlobalAttributes, extends = div)]
1066    pub attributes: Vec<Attribute>,
1067    /// Extra actions after the built-in buttons.
1068    pub children: Element,
1069}
1070
1071/// Copy, retry, and rating actions under an assistant message.
1072///
1073/// Retry only requests a new response and rating only records a choice; the application owns
1074/// regeneration, storage, and any follow-up question. Pressing the current rating clears it.
1075/// Lumen's stylesheet hides the button text and draws icons; the text stays as each button's
1076/// accessible name.
1077#[component]
1078pub fn MessageActions(props: MessageActionsProps) -> Element {
1079    let rating = use_controllable(props.feedback, || props.default_feedback, None);
1080    let current = rating.get();
1081    let inactive = props.disabled || props.message_id.is_empty();
1082    let class = compose([Some("ui-message-actions"), props.class.as_deref()]);
1083    let pressed_state = |feedback: MessageFeedback| {
1084        if current == Some(feedback) {
1085            "true"
1086        } else {
1087            "false"
1088        }
1089    };
1090    let request_retry = {
1091        let message_id = props.message_id.clone();
1092        let on_retry = props.on_retry;
1093
1094        move |_: MouseEvent| {
1095            if !inactive && let Some(handler) = on_retry {
1096                handler.call(MessageRetryDetail {
1097                    message_id: message_id.clone(),
1098                });
1099            }
1100        }
1101    };
1102    let rate = {
1103        let message_id = props.message_id.clone();
1104        let on_feedback = props.on_feedback;
1105
1106        move |pressed: MessageFeedback| {
1107            if inactive {
1108                return;
1109            }
1110
1111            let value = next_message_feedback(rating.peek(), pressed);
1112            rating.set(value);
1113
1114            if let Some(handler) = on_feedback {
1115                handler.call(MessageFeedbackDetail {
1116                    message_id: message_id.clone(),
1117                    value,
1118                });
1119            }
1120        }
1121    };
1122    let rate_positive = rate.clone();
1123
1124    rsx! {
1125        div {
1126            aria_label: "{props.label}",
1127            class,
1128            "data-disabled": "{props.disabled}",
1129            "data-feedback": current.map_or("", MessageFeedback::as_str),
1130            "data-message-id": "{props.message_id}",
1131            "data-ui-message-actions": "true",
1132            role: "group",
1133            ..props.attributes,
1134            if let Some(value) = props.copy_value {
1135                CopyButton {
1136                    copied_label: props.copied_label,
1137                    error_label: props.copy_error_label,
1138                    label: props.copy_label.clone(),
1139                    on_copy: props.on_copy,
1140                    size: ButtonSize::Icon,
1141                    value,
1142                    variant: ButtonVariant::Ghost,
1143                    "{props.copy_label}"
1144                }
1145            }
1146            if props.retry {
1147                Button {
1148                    "data-ui-message-action": "retry",
1149                    disabled: inactive,
1150                    size: ButtonSize::Icon,
1151                    variant: ButtonVariant::Ghost,
1152                    onclick: request_retry,
1153                    "{props.retry_label}"
1154                }
1155            }
1156            if props.show_feedback {
1157                Button {
1158                    aria_pressed: pressed_state(MessageFeedback::Positive),
1159                    "data-ui-message-action": MessageFeedback::Positive.as_str(),
1160                    disabled: inactive,
1161                    size: ButtonSize::Icon,
1162                    variant: ButtonVariant::Ghost,
1163                    onclick: move |_| rate_positive(MessageFeedback::Positive),
1164                    "{props.positive_label}"
1165                }
1166                Button {
1167                    aria_pressed: pressed_state(MessageFeedback::Negative),
1168                    "data-ui-message-action": MessageFeedback::Negative.as_str(),
1169                    disabled: inactive,
1170                    size: ButtonSize::Icon,
1171                    variant: ButtonVariant::Ghost,
1172                    onclick: move |_| rate(MessageFeedback::Negative),
1173                    "{props.negative_label}"
1174                }
1175            }
1176            {props.children}
1177        }
1178    }
1179}
1180
1181/// A starter prompt offered by [`PromptSuggestions`].
1182#[derive(Clone, Debug, Default, PartialEq, Eq)]
1183pub struct PromptSuggestion {
1184    /// Visible button text.
1185    pub label: String,
1186    /// The prompt it sends. Defaults to the label when unset or blank.
1187    pub value: Option<String>,
1188}
1189
1190impl PromptSuggestion {
1191    /// A suggestion whose prompt is its label.
1192    pub fn new(label: impl Into<String>) -> Self {
1193        Self {
1194            label: label.into(),
1195            value: None,
1196        }
1197    }
1198
1199    /// Sets the prompt when it differs from the label.
1200    #[must_use]
1201    pub fn with_value(mut self, value: impl Into<String>) -> Self {
1202        self.value = Some(value.into());
1203        self
1204    }
1205}
1206
1207/// A suggestion ready to render: a visible label and the prompt it sends.
1208#[derive(Clone, Debug, PartialEq, Eq)]
1209pub struct ResolvedPromptSuggestion {
1210    /// Visible button text, trimmed.
1211    pub label: String,
1212    /// The prompt, trimmed; the label when the suggestion has no prompt of its own.
1213    pub value: String,
1214}
1215
1216/// The request a [`PromptSuggestions`] emits when the person chooses a suggestion.
1217#[derive(Clone, Debug, PartialEq, Eq)]
1218pub struct PromptSuggestionDetail {
1219    /// The chosen prompt.
1220    pub value: String,
1221}
1222
1223/// JavaScript white space and line terminators: the characters `String.prototype.trim` removes.
1224fn is_js_whitespace(character: char) -> bool {
1225    const SPACES: [char; 14] = [
1226        '\t', '\n', '\u{b}', '\u{c}', '\r', ' ', '\u{a0}', '\u{1680}', '\u{2028}', '\u{2029}',
1227        '\u{202f}', '\u{205f}', '\u{3000}', '\u{feff}',
1228    ];
1229
1230    SPACES.contains(&character) || ('\u{2000}'..='\u{200a}').contains(&character)
1231}
1232
1233/// Keeps suggestions with a visible label, trims both fields, and falls back to the label as the
1234/// prompt, like `normalizeLumenPromptSuggestions` in `@santi020k/lumen-core`.
1235pub fn normalize_prompt_suggestions(
1236    suggestions: &[PromptSuggestion],
1237) -> Vec<ResolvedPromptSuggestion> {
1238    suggestions
1239        .iter()
1240        .filter_map(|suggestion| {
1241            let label = suggestion.label.trim_matches(is_js_whitespace);
1242
1243            if label.is_empty() {
1244                return None;
1245            }
1246
1247            let value = suggestion
1248                .value
1249                .as_deref()
1250                .map(|value| value.trim_matches(is_js_whitespace))
1251                .filter(|value| !value.is_empty())
1252                .unwrap_or(label);
1253
1254            Some(ResolvedPromptSuggestion {
1255                label: label.to_string(),
1256                value: value.to_string(),
1257            })
1258        })
1259        .collect()
1260}
1261
1262/// Distinct, order-stable keys for repeated suggestions that do not rely on the list index.
1263fn prompt_suggestion_keys(items: &[ResolvedPromptSuggestion]) -> Vec<String> {
1264    let mut seen: HashMap<(&str, &str), usize> = HashMap::new();
1265
1266    items
1267        .iter()
1268        .map(|item| {
1269            let count = seen
1270                .entry((item.label.as_str(), item.value.as_str()))
1271                .or_insert(0);
1272            let key = format!("{:?}:{:?}#{count}", item.label, item.value);
1273            *count += 1;
1274            key
1275        })
1276        .collect()
1277}
1278
1279/// Fills a prompt composer in the browser, like `fillLumenPromptComposer` in
1280/// `@santi020k/lumen-core`: the textarea gets the value through the native setter and an `input`
1281/// event, so a `PromptComposer` (Dioxus or any framework) sees the change. With `submit`, the
1282/// form is submitted once its send button is enabled, waiting up to a second for the composer to
1283/// render the new text. Values travel through the eval channel, never through the script text.
1284const FILL_PROMPT_COMPOSER: &str = r"const [id, value, submit] = await dioxus.recv();
1285const target = document.getElementById(id);
1286if (!target) return false;
1287const input = target instanceof HTMLTextAreaElement
1288  ? target
1289  : target.querySelector('textarea[data-ui-prompt-input]') ?? target.querySelector('textarea');
1290if (!(input instanceof HTMLTextAreaElement) || input.disabled || input.readOnly) return false;
1291const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;
1292if (setValue) setValue.call(input, value); else input.value = value;
1293input.dispatchEvent(new Event('input', { bubbles: true }));
1294input.focus();
1295input.setSelectionRange(value.length, value.length);
1296const form = input.form;
1297const send = form?.querySelector('button[data-ui-prompt-send]');
1298if (!submit || !form || !(send instanceof HTMLButtonElement)) return true;
1299const request = () => {
1300  if (send.isConnected && !send.disabled) form.requestSubmit(send);
1301};
1302if (!send.disabled) {
1303  request();
1304  return true;
1305}
1306const observer = new MutationObserver(() => {
1307  if (send.disabled) return;
1308  observer.disconnect();
1309  clearTimeout(timer);
1310  request();
1311});
1312const timer = setTimeout(() => observer.disconnect(), 1000);
1313observer.observe(send, { attributeFilter: ['disabled'], attributes: true });
1314return true;";
1315
1316/// Fills the composer with id `target` on web and desktop. Dioxus Native has no JavaScript, so
1317/// the request fails quietly there and the app sets the composer value from
1318/// `on_suggestion_select` instead.
1319fn fill_prompt_composer(target: String, value: String, submit: bool) {
1320    let eval = document::eval(FILL_PROMPT_COMPOSER);
1321    let _ = eval.send((target, value, submit));
1322}
1323
1324/// Props for [`PromptSuggestions`].
1325#[derive(Props, Clone, PartialEq)]
1326pub struct PromptSuggestionsProps {
1327    /// The starter prompts. Suggestions with a blank label are skipped.
1328    pub suggestions: Vec<PromptSuggestion>,
1329    /// Accessible name of the group. Defaults to `Suggested prompts`.
1330    #[props(default = "Suggested prompts".to_string(), into)]
1331    pub label: String,
1332    /// The id of a [`PromptComposer`] form or textarea. On web and desktop, choosing a suggestion
1333    /// fills it.
1334    #[props(into)]
1335    pub target: Option<String>,
1336    /// Submits the target composer after filling it.
1337    #[props(default)]
1338    pub submit_on_select: bool,
1339    /// Disables every suggestion.
1340    #[props(default)]
1341    pub disabled: bool,
1342    /// Called with the chosen prompt before the target composer is filled. On Dioxus Native, set
1343    /// a controlled composer's value here.
1344    pub on_suggestion_select: Option<EventHandler<PromptSuggestionDetail>>,
1345    /// Extra classes appended after the Lumen class.
1346    #[props(into)]
1347    pub class: Option<String>,
1348    /// Any other `<div>` or global attribute.
1349    #[props(extends = GlobalAttributes, extends = div)]
1350    pub attributes: Vec<Attribute>,
1351    /// Extra content after the suggestions.
1352    pub children: Element,
1353}
1354
1355/// Starter prompts that fill a [`PromptComposer`].
1356///
1357/// Choosing a suggestion calls `on_suggestion_select`, then, on web and desktop, fills the
1358/// composer named by `target` and optionally submits it. It renders nothing when there are no
1359/// suggestions and no children.
1360#[component]
1361pub fn PromptSuggestions(props: PromptSuggestionsProps) -> Element {
1362    let items = normalize_prompt_suggestions(&props.suggestions);
1363
1364    if items.is_empty() && !super::has_content(&props.children) {
1365        return rsx! {};
1366    }
1367
1368    let keys = prompt_suggestion_keys(&items);
1369    let class = compose([Some("ui-prompt-suggestions"), props.class.as_deref()]);
1370    let (disabled, submit) = (props.disabled, props.submit_on_select);
1371    let on_select = props.on_suggestion_select;
1372    let target = props.target.clone().filter(|target| !target.is_empty());
1373
1374    rsx! {
1375        div {
1376            aria_label: "{props.label}",
1377            class,
1378            "data-disabled": "{disabled}",
1379            "data-submit-on-select": "{submit}",
1380            "data-target": props.target,
1381            "data-ui-prompt-suggestions": "true",
1382            role: "group",
1383            ..props.attributes,
1384            for (item, key) in items.into_iter().zip(keys) {
1385                Button {
1386                    key: "{key}",
1387                    "data-ui-prompt-suggestion": "true",
1388                    "data-value": item.value.clone(),
1389                    disabled,
1390                    size: ButtonSize::Sm,
1391                    variant: ButtonVariant::Outline,
1392                    onclick: {
1393                        let (value, target) = (item.value.clone(), target.clone());
1394
1395                        move |_| {
1396                            if disabled {
1397                                return;
1398                            }
1399
1400                            if let Some(handler) = on_select {
1401                                handler.call(PromptSuggestionDetail { value: value.clone() });
1402                            }
1403
1404                            if let Some(target) = target.clone() {
1405                                fill_prompt_composer(target, value.clone(), submit);
1406                            }
1407                        }
1408                    },
1409                    "{item.label}"
1410                }
1411            }
1412            {props.children}
1413        }
1414    }
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use super::{
1420        MessageFeedback, PromptSuggestion, ReasoningOpenOptions, ResolvedPromptSuggestion,
1421        StreamMessageStatus, can_submit_prompt_composer, next_message_feedback,
1422        normalize_prompt_composer_limit, normalize_prompt_suggestions, prompt_suggestion_keys,
1423        resolve_reasoning_open, resolve_source_citation_href,
1424    };
1425
1426    #[test]
1427    fn prompt_limits_follow_lumen_core() {
1428        assert_eq!(normalize_prompt_composer_limit(None), 4000);
1429        assert_eq!(normalize_prompt_composer_limit(Some(0)), 4000);
1430        assert_eq!(
1431            normalize_prompt_composer_limit(Some(u32::MAX)),
1432            2_147_483_647
1433        );
1434        assert!(can_submit_prompt_composer(" hi ", 4000));
1435        assert!(!can_submit_prompt_composer("   ", 4000));
1436        assert!(!can_submit_prompt_composer("hello", 4));
1437        // Limits count UTF-16 code units like the browser.
1438        assert!(!can_submit_prompt_composer("😀😀", 3));
1439    }
1440
1441    #[test]
1442    fn citations_accept_only_safe_destinations() {
1443        let cases = [
1444            (
1445                "https://example.com/report",
1446                Some("https://example.com/report"),
1447            ),
1448            ("HTTPS://Example.COM", Some("https://example.com/")),
1449            (
1450                "http://example.com:80/a?b=c#d",
1451                Some("http://example.com/a?b=c#d"),
1452            ),
1453            (
1454                "https://example.com:8443/x/../y/./z",
1455                Some("https://example.com:8443/y/z"),
1456            ),
1457            (
1458                "https://example.com/a\"b<c>",
1459                Some("https://example.com/a%22b%3Cc%3E"),
1460            ),
1461            (
1462                "https://example.com/café",
1463                Some("https://example.com/caf%C3%A9"),
1464            ),
1465            ("https:example.com", Some("https://example.com/")),
1466            ("/docs/guide", Some("/docs/guide")),
1467            ("//evil.example", None),
1468            ("javascript:alert(1)", None),
1469            ("https://user:pass@example.com", None),
1470            ("https://example.com/a b", None),
1471            ("https://exa\\mple.com", None),
1472            ("https://example.com:99999", None),
1473            ("https://", None),
1474            ("data:text/html,hi", None),
1475            ("", None),
1476        ];
1477
1478        for (input, expected) in cases {
1479            assert_eq!(
1480                resolve_source_citation_href(input).as_deref(),
1481                expected,
1482                "{input}"
1483            );
1484        }
1485    }
1486
1487    #[test]
1488    fn citation_resolution_is_linear_for_long_input() {
1489        let long = format!("https://example.com/{}", "a/".repeat(100_000));
1490        assert!(resolve_source_citation_href(&long).is_some());
1491        assert!(resolve_source_citation_href(&"/".repeat(200_000)).is_none());
1492    }
1493
1494    #[test]
1495    fn reasoning_open_state_follows_lumen_core() {
1496        use StreamMessageStatus::{Complete, Error, Idle, Streaming};
1497
1498        // (previous, next, open, user toggled, collapse on complete) => open
1499        let cases = [
1500            ((Idle, Streaming, false, false, true), true),
1501            ((Streaming, Complete, true, false, true), false),
1502            ((Streaming, Error, true, false, true), false),
1503            ((Streaming, Complete, true, false, false), true),
1504            ((Streaming, Complete, true, true, true), true),
1505            ((Idle, Streaming, false, true, true), false),
1506            ((Complete, Complete, true, false, true), true),
1507            ((Idle, Complete, false, false, true), false),
1508        ];
1509
1510        for ((previous, next, open, user_toggled, collapse_on_complete), expected) in cases {
1511            let options = ReasoningOpenOptions {
1512                previous,
1513                next,
1514                open,
1515                user_toggled,
1516                collapse_on_complete,
1517            };
1518
1519            assert_eq!(resolve_reasoning_open(options), expected, "{options:?}");
1520        }
1521    }
1522
1523    #[test]
1524    fn message_feedback_toggles_and_clears() {
1525        use MessageFeedback::{Negative, Positive};
1526
1527        assert_eq!(next_message_feedback(None, Positive), Some(Positive));
1528        assert_eq!(next_message_feedback(Some(Positive), Positive), None);
1529        assert_eq!(
1530            next_message_feedback(Some(Positive), Negative),
1531            Some(Negative)
1532        );
1533        assert_eq!(next_message_feedback(Some(Negative), Negative), None);
1534        assert_eq!(Positive.as_str(), "positive");
1535        assert_eq!(Negative.as_str(), "negative");
1536    }
1537
1538    fn resolved(label: &str, value: &str) -> ResolvedPromptSuggestion {
1539        ResolvedPromptSuggestion {
1540            label: label.to_string(),
1541            value: value.to_string(),
1542        }
1543    }
1544
1545    #[test]
1546    fn prompt_suggestions_keep_labeled_items_and_fall_back_to_the_label() {
1547        let suggestions = [
1548            PromptSuggestion::new(" Summarize ").with_value(" Summarize this thread "),
1549            PromptSuggestion::new("Plan a trip"),
1550            PromptSuggestion::new("Blank value").with_value("  "),
1551            PromptSuggestion::new("   "),
1552            PromptSuggestion::new("").with_value("No label"),
1553            // JavaScript's trim removes U+FEFF; Rust's does not.
1554            PromptSuggestion::new("\u{feff}Draft\u{3000}"),
1555        ];
1556
1557        assert_eq!(
1558            normalize_prompt_suggestions(&suggestions),
1559            vec![
1560                resolved("Summarize", "Summarize this thread"),
1561                resolved("Plan a trip", "Plan a trip"),
1562                resolved("Blank value", "Blank value"),
1563                resolved("Draft", "Draft"),
1564            ]
1565        );
1566        assert_eq!(normalize_prompt_suggestions(&[]), []);
1567    }
1568
1569    #[test]
1570    fn prompt_suggestion_normalization_is_linear_for_long_input() {
1571        let long = "x".repeat(100_000);
1572        let padded = format!(" {long} ");
1573
1574        assert_eq!(
1575            normalize_prompt_suggestions(&[PromptSuggestion::new(padded)]),
1576            vec![resolved(&long, &long)]
1577        );
1578        assert_eq!(
1579            normalize_prompt_suggestions(&[PromptSuggestion::new(" ".repeat(200_000))]),
1580            []
1581        );
1582    }
1583
1584    #[test]
1585    fn repeated_prompt_suggestions_get_distinct_keys() {
1586        let items = [
1587            resolved("Summarize", "Summarize this thread"),
1588            resolved("Plan", "Plan"),
1589            resolved("Summarize", "Summarize this thread"),
1590        ];
1591        let keys = prompt_suggestion_keys(&items);
1592
1593        assert_eq!(keys.len(), 3);
1594        assert_ne!(keys[0], keys[2]);
1595        assert_ne!(keys[0], keys[1]);
1596        assert_eq!(keys, prompt_suggestion_keys(&items));
1597    }
1598}