perspective_viewer/components/
chat_panel.rs1use yew::prelude::*;
19
20use crate::agent::{AgentSlot, ChatEntry, Entitlement, render_markdown, tool_names};
21use crate::ui::MirroredTextarea;
22
23#[derive(Properties, PartialEq)]
24struct ChatReasoningProps {
25 reasoning: String,
26 open: bool,
27}
28
29#[function_component]
38fn ChatReasoning(props: &ChatReasoningProps) -> Html {
39 let body_ref = use_node_ref();
40 let scroll_pinned = use_mut_ref(|| true);
41 let seen_len = use_mut_ref(|| None::<usize>);
42 let onscroll = {
43 let body_ref = body_ref.clone();
44 let scroll_pinned = scroll_pinned.clone();
45 Callback::from(move |_: Event| {
46 if let Some(elem) = body_ref.cast::<web_sys::Element>() {
47 let gap = elem.scroll_height() - elem.scroll_top() - elem.client_height();
48 *scroll_pinned.borrow_mut() = gap < 24;
49 }
50 })
51 };
52
53 {
54 let body_ref = body_ref.clone();
55 let scroll_pinned = scroll_pinned.clone();
56 let seen_len = seen_len.clone();
57 let len = props.reasoning.len();
58 use_effect(move || {
59 let grew = seen_len.replace(Some(len)).is_some_and(|seen| len > seen);
60 if grew
61 && *scroll_pinned.borrow()
62 && let Some(elem) = body_ref.cast::<web_sys::Element>()
63 {
64 elem.set_scroll_top(elem.scroll_height());
65 }
66 });
67 }
68
69 html! {
70 <details class="chat-reasoning" open={props.open}>
71 <summary />
72 <div class="chat-reasoning-body scrollable" ref={body_ref} {onscroll}>
73 { &props.reasoning }
74 </div>
75 </details>
76 }
77}
78
79#[derive(Properties, PartialEq)]
89struct ChatInputProps {
90 agent: AgentSlot,
91 busy: bool,
92}
93
94#[function_component]
95fn ChatInput(props: &ChatInputProps) -> Html {
96 let input_ref = use_node_ref();
97
98 let text = use_state_eq(String::new);
102 let submit = {
103 let agent = props.agent.clone();
104 let input_ref = input_ref.clone();
105 let text = text.clone();
106 Callback::from(move |()| {
107 if agent.is_busy() {
108 return;
109 }
110
111 if let Some(elem) = input_ref.cast::<web_sys::HtmlTextAreaElement>() {
112 let prompt = elem.value().trim().to_owned();
113 if prompt.is_empty() {
114 return;
115 }
116
117 elem.set_value("");
118 text.set(String::new());
119 let agent = agent.clone();
120 wasm_bindgen_futures::spawn_local(async move {
121 let _ = agent.run_prompt(prompt).await;
123 });
124 }
125 })
126 };
127
128 let onkeydown = {
129 let submit = submit.clone();
130 Callback::from(move |event: KeyboardEvent| {
131 if event.key() == "Enter" && !event.shift_key() {
132 event.prevent_default();
133 submit.emit(());
134 }
135 })
136 };
137
138 let oninput = {
141 let input_ref = input_ref.clone();
142 let text = text.clone();
143 Callback::from(move |_: InputEvent| {
144 if let Some(elem) = input_ref.cast::<web_sys::HtmlTextAreaElement>() {
145 text.set(elem.value());
146 }
147 })
148 };
149
150 let onsend = submit.reform(|_: MouseEvent| ());
151 let onstop = {
152 let agent = props.agent.clone();
153 Callback::from(move |_: MouseEvent| agent.stop())
154 };
155
156 html! {
157 <div id="chat_input_row">
158 <div id="chat_input_scroll" class="scrollable">
159 <MirroredTextarea
160 id="chat_input"
161 class="chat-input-box"
162 mirror={html! { (*text).clone() }}
163 is_empty={text.is_empty()}
164 textarea_ref={input_ref}
165 placeholder="Ask about your data\u{2026}"
166 disabled={props.busy}
167 {onkeydown}
168 {oninput}
169 />
170 </div>
171 if props.busy {
172 <button id="chat_stop_button" onclick={onstop} />
173 } else {
174 <button id="chat_send_button" onclick={onsend} />
175 }
176 </div>
177 }
178}
179
180#[derive(Properties, PartialEq)]
181struct ChatHeaderProps {
182 agent: AgentSlot,
183 entitlements: Vec<(Entitlement, bool)>,
184 busy: bool,
185 empty: bool,
186}
187
188#[function_component]
189fn ChatHeader(props: &ChatHeaderProps) -> Html {
190 let chips = props
191 .entitlements
192 .iter()
193 .filter_map(|&(entitlement, enabled)| match entitlement {
194 Entitlement::ReadView | Entitlement::ReadDocs => None,
195 _ => {
196 let onclick = {
197 let agent = props.agent.clone();
198 Callback::from(move |_: MouseEvent| {
199 agent.set_entitlement(entitlement, !enabled)
200 })
201 };
202
203 Some(html! {
204 <button
205 class="chat-entitlement"
206 data-entitlement={entitlement.as_str()}
207 aria-pressed={enabled.to_string()}
208 title={tool_names(entitlement).join(", ")}
209 disabled={props.busy}
210 {onclick}
211 />
212 })
213 },
214 })
215 .collect::<Html>();
216
217 let onreset = {
218 let agent = props.agent.clone();
219 Callback::from(move |_: MouseEvent| {
220 let agent = agent.clone();
221 wasm_bindgen_futures::spawn_local(async move { agent.reset().await });
222 })
223 };
224
225 html! {
226 <div id="chat_header" class="sidebar-controls">
227 { chips }
228 <button id="chat_reset_button" disabled={props.busy || props.empty} onclick={onreset} />
229 </div>
230 }
231}
232
233#[derive(Properties, PartialEq)]
234pub struct ChatPanelProps {
235 pub agent: AgentSlot,
236}
237
238#[function_component]
239pub fn ChatPanel(props: &ChatPanelProps) -> Html {
240 let update = use_force_update();
241 {
242 let agent = props.agent.clone();
243 use_effect_with((), move |_| {
244 let sub = agent
245 .on_update
246 .add_notify_listener(&Callback::from(move |_| update.force_update()));
247
248 move || drop(sub)
249 });
250 }
251
252 let log_ref = use_node_ref();
257 let scroll_pinned = use_mut_ref(|| true);
258 let onscroll = {
259 let log_ref = log_ref.clone();
260 let scroll_pinned = scroll_pinned.clone();
261 Callback::from(move |_: Event| {
262 if let Some(elem) = log_ref.cast::<web_sys::Element>() {
263 let gap = elem.scroll_height() - elem.scroll_top() - elem.client_height();
264 *scroll_pinned.borrow_mut() = gap < 30;
265 }
266 })
267 };
268
269 {
270 let log_ref = log_ref.clone();
271 let scroll_pinned = scroll_pinned.clone();
272 use_effect(move || {
273 if let Some(elem) = log_ref.cast::<web_sys::Element>()
274 && *scroll_pinned.borrow()
275 {
276 elem.set_scroll_top(elem.scroll_height());
277 }
278 });
279 }
280
281 let busy = props.agent.is_busy();
282 let transcript = props.agent.transcript();
283 let empty = transcript.is_empty();
284 let retryable = matches!(transcript.last(), Some(ChatEntry::Error(_)));
285 let onretry = {
286 let agent = props.agent.clone();
287 Callback::from(move |_: MouseEvent| {
288 let agent = agent.clone();
289 wasm_bindgen_futures::spawn_local(async move {
290 let _ = agent.retry().await;
291 });
292 })
293 };
294
295 let entries = transcript
296 .into_iter()
297 .map(|entry| match entry {
298 ChatEntry::User(text) => html! {
299 <div class="chat-message chat-user">{ text.trim() }</div>
300 },
301 ChatEntry::Assistant { text, reasoning } => html! {
302 <div class="chat-message chat-assistant">
303 if let Some(reasoning) = reasoning { <ChatReasoning {reasoning} open=false /> }
304 { render_markdown(&text) }
305 </div>
306 },
307 ChatEntry::Tool { name, args, error } => {
308 let class = if error.is_some() {
309 "chat-tool-chip chat-tool-chip-error"
310 } else {
311 "chat-tool-chip"
312 };
313
314 let title = match &error {
315 Some(err) => format!("{err}\n\n{args}"),
316 None => args.clone(),
317 };
318
319 html! { <div {class} {title}>{ name }</div> }
320 },
321 ChatEntry::Error(text) => html! { <div class="chat-message chat-error">{ text }</div> },
322 ChatEntry::Stopped => {
323 html! { <div class="chat-message chat-error">{ "Stopped" }</div> }
324 },
325 })
326 .collect::<Html>();
327
328 let pending = props.agent.pending();
332 let tail = match &pending {
333 Some((text, reasoning)) if !text.is_empty() || !reasoning.is_empty() => html! {
334 <div class="chat-message chat-assistant chat-streaming">
335 if !reasoning.is_empty() {
336 <ChatReasoning reasoning={reasoning.clone()} open={text.is_empty()} />
337 }
338 if !text.is_empty() {
339 { render_markdown(text) }
340 }
341 </div>
342 },
343 _ if busy => html! {
344 <div class="chat-message chat-assistant chat-pending"><span /><span /><span /></div>
345 },
346 _ if retryable => html! { <button id="chat_retry_button" onclick={onretry} /> },
347 _ => html! {},
348 };
349
350 html! {
351 <div id="chat_panel">
352 <ChatHeader
353 agent={props.agent.clone()}
354 entitlements={props.agent.entitlements()}
355 {busy}
356 {empty}
357 />
358 <div id="chat_log" class="scrollable" ref={log_ref} {onscroll}>{ entries }{ tail }</div>
359 <ChatInput agent={props.agent.clone()} {busy} />
360 <div id="chat_badge">{ props.agent.label().unwrap_or_default() }</div>
361 </div>
362 }
363}