1use 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
21pub const PROMPT_COMPOSER_DEFAULT_LIMIT: u32 = 4000;
23
24pub 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
32pub 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#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct PromptComposerSubmitDetail {
43 pub text: String,
45}
46
47#[derive(Props, Clone, PartialEq)]
49pub struct PromptComposerProps {
50 #[props(into)]
52 pub value: Option<String>,
53 #[props(default, into)]
55 pub default_value: String,
56 pub on_value_change: Option<EventHandler<String>>,
58 pub on_prompt_submit: Option<EventHandler<PromptComposerSubmitDetail>>,
60 pub on_stop: Option<EventHandler<()>>,
62 #[props(default)]
64 pub disabled: bool,
65 #[props(default)]
67 pub pending: bool,
68 #[props(default)]
70 pub submit_on_enter: bool,
71 pub max_length: Option<u32>,
73 #[props(default = "Message".to_string(), into)]
75 pub label: String,
76 #[props(default = "Send".to_string(), into)]
78 pub send_label: String,
79 #[props(default = "Stop".to_string(), into)]
81 pub stop_label: String,
82 #[props(into)]
84 pub id: Option<String>,
85 pub actions: Option<Element>,
87 #[props(into)]
89 pub class: Option<String>,
90 #[props(extends = GlobalAttributes, extends = form)]
92 pub attributes: Vec<Attribute>,
93 pub children: Element,
95}
96
97#[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(¤t, 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
222#[non_exhaustive]
223pub enum StreamMessageStatus {
224 #[default]
226 Idle,
227 Streaming,
229 Complete,
231 Error,
233 Canceled,
235}
236
237impl StreamMessageStatus {
238 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#[derive(Props, Clone, PartialEq)]
252pub struct StreamMessageProps {
253 #[props(default)]
255 pub status: StreamMessageStatus,
256 #[props(into)]
258 pub status_label: String,
259 #[props(default = "Assistant".to_string(), into)]
261 pub label: String,
262 pub actions: Option<Element>,
264 pub sources: Option<Element>,
266 #[props(into)]
268 pub class: Option<String>,
269 #[props(extends = GlobalAttributes, extends = article)]
271 pub attributes: Vec<Attribute>,
272 pub children: Element,
274}
275
276#[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
367fn 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
498pub 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#[derive(Props, Clone, PartialEq)]
516pub struct SourceCitationProps {
517 #[props(into)]
519 pub href: String,
520 #[props(into)]
522 pub label: String,
523 #[props(into)]
525 pub class: Option<String>,
526 #[props(extends = GlobalAttributes, extends = a)]
528 pub attributes: Vec<Attribute>,
529 pub children: Element,
531}
532
533#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
564#[non_exhaustive]
565pub enum ToolActivityStatus {
566 #[default]
568 Queued,
569 Running,
571 Success,
573 Error,
575 Canceled,
577}
578
579impl ToolActivityStatus {
580 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#[derive(Props, Clone, PartialEq)]
594pub struct ToolActivityProps {
595 #[props(into)]
597 pub label: String,
598 #[props(default)]
600 pub status: ToolActivityStatus,
601 #[props(into)]
603 pub status_label: String,
604 pub open: Option<bool>,
606 #[props(default)]
608 pub default_open: bool,
609 pub on_open_change: Option<EventHandler<bool>>,
611 #[props(into)]
613 pub class: Option<String>,
614 #[props(extends = GlobalAttributes, extends = details)]
616 pub attributes: Vec<Attribute>,
617 pub children: Element,
619}
620
621#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
657#[non_exhaustive]
658pub enum ApprovalCardStatus {
659 #[default]
661 Pending,
662 Approved,
664 Rejected,
666}
667
668impl ApprovalCardStatus {
669 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
681pub enum ApprovalCardResponse {
682 Approve,
684 Reject,
686}
687
688impl ApprovalCardResponse {
689 pub fn as_str(self) -> &'static str {
691 match self {
692 Self::Approve => "approve",
693 Self::Reject => "reject",
694 }
695 }
696}
697
698#[derive(Clone, Debug, PartialEq, Eq)]
700pub struct ApprovalCardResponseDetail {
701 pub request_id: String,
703 pub response: ApprovalCardResponse,
705}
706
707#[derive(Props, Clone, PartialEq)]
709pub struct ApprovalCardProps {
710 #[props(into)]
712 pub label: String,
713 #[props(into)]
715 pub request_id: String,
716 #[props(default)]
718 pub status: ApprovalCardStatus,
719 #[props(into)]
721 pub status_label: String,
722 #[props(default)]
724 pub disabled: bool,
725 #[props(default = "Approve".to_string(), into)]
727 pub approve_label: String,
728 #[props(default = "Reject".to_string(), into)]
730 pub reject_label: String,
731 pub on_response: Option<EventHandler<ApprovalCardResponseDetail>>,
733 #[props(into)]
735 pub class: Option<String>,
736 #[props(extends = GlobalAttributes, extends = div)]
738 pub attributes: Vec<Attribute>,
739 pub children: Element,
741}
742
743#[component]
745pub fn ApprovalCard(props: ApprovalCardProps) -> Element {
746 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
816pub struct ReasoningOpenOptions {
817 pub previous: StreamMessageStatus,
819 pub next: StreamMessageStatus,
821 pub open: bool,
823 pub user_toggled: bool,
825 pub collapse_on_complete: bool,
827}
828
829pub 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#[derive(Clone, Copy, PartialEq, Eq)]
861struct ReasoningState {
862 open: bool,
863 status: StreamMessageStatus,
864 user_toggled: bool,
865}
866
867#[derive(Props, Clone, PartialEq)]
869pub struct ReasoningProps {
870 #[props(into)]
872 pub label: String,
873 #[props(default = StreamMessageStatus::Complete)]
875 pub status: StreamMessageStatus,
876 #[props(default = true)]
879 pub collapse_on_complete: bool,
880 pub default_open: Option<bool>,
882 #[props(into)]
884 pub class: Option<String>,
885 #[props(extends = GlobalAttributes, extends = details)]
887 pub attributes: Vec<Attribute>,
888 pub children: Element,
890}
891
892#[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
961pub enum MessageFeedback {
962 Positive,
964 Negative,
966}
967
968impl MessageFeedback {
969 pub fn as_str(self) -> &'static str {
971 match self {
972 Self::Positive => "positive",
973 Self::Negative => "negative",
974 }
975 }
976}
977
978pub 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#[derive(Clone, Debug, PartialEq, Eq)]
994pub struct MessageFeedbackDetail {
995 pub message_id: String,
997 pub value: Option<MessageFeedback>,
999}
1000
1001#[derive(Clone, Debug, PartialEq, Eq)]
1004pub struct MessageRetryDetail {
1005 pub message_id: String,
1007}
1008
1009#[derive(Props, Clone, PartialEq)]
1011pub struct MessageActionsProps {
1012 #[props(into)]
1015 pub message_id: String,
1016 #[props(default = "Message actions".to_string(), into)]
1018 pub label: String,
1019 #[props(into)]
1021 pub copy_value: Option<String>,
1022 pub on_copy: Option<Callback<String, bool>>,
1025 #[props(default = "Copy".to_string(), into)]
1027 pub copy_label: String,
1028 #[props(default = "Copied".to_string(), into)]
1030 pub copied_label: String,
1031 #[props(default = "Could not copy".to_string(), into)]
1033 pub copy_error_label: String,
1034 #[props(default)]
1036 pub retry: bool,
1037 #[props(default = "Retry".to_string(), into)]
1039 pub retry_label: String,
1040 #[props(default = true)]
1042 pub show_feedback: bool,
1043 pub feedback: Option<Option<MessageFeedback>>,
1046 pub default_feedback: Option<MessageFeedback>,
1048 #[props(default = "Good response".to_string(), into)]
1050 pub positive_label: String,
1051 #[props(default = "Bad response".to_string(), into)]
1053 pub negative_label: String,
1054 #[props(default)]
1056 pub disabled: bool,
1057 pub on_retry: Option<EventHandler<MessageRetryDetail>>,
1059 pub on_feedback: Option<EventHandler<MessageFeedbackDetail>>,
1061 #[props(into)]
1063 pub class: Option<String>,
1064 #[props(extends = GlobalAttributes, extends = div)]
1066 pub attributes: Vec<Attribute>,
1067 pub children: Element,
1069}
1070
1071#[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#[derive(Clone, Debug, Default, PartialEq, Eq)]
1183pub struct PromptSuggestion {
1184 pub label: String,
1186 pub value: Option<String>,
1188}
1189
1190impl PromptSuggestion {
1191 pub fn new(label: impl Into<String>) -> Self {
1193 Self {
1194 label: label.into(),
1195 value: None,
1196 }
1197 }
1198
1199 #[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#[derive(Clone, Debug, PartialEq, Eq)]
1209pub struct ResolvedPromptSuggestion {
1210 pub label: String,
1212 pub value: String,
1214}
1215
1216#[derive(Clone, Debug, PartialEq, Eq)]
1218pub struct PromptSuggestionDetail {
1219 pub value: String,
1221}
1222
1223fn 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
1233pub 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
1262fn 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
1279const 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
1316fn 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#[derive(Props, Clone, PartialEq)]
1326pub struct PromptSuggestionsProps {
1327 pub suggestions: Vec<PromptSuggestion>,
1329 #[props(default = "Suggested prompts".to_string(), into)]
1331 pub label: String,
1332 #[props(into)]
1335 pub target: Option<String>,
1336 #[props(default)]
1338 pub submit_on_select: bool,
1339 #[props(default)]
1341 pub disabled: bool,
1342 pub on_suggestion_select: Option<EventHandler<PromptSuggestionDetail>>,
1345 #[props(into)]
1347 pub class: Option<String>,
1348 #[props(extends = GlobalAttributes, extends = div)]
1350 pub attributes: Vec<Attribute>,
1351 pub children: Element,
1353}
1354
1355#[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 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 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 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}