1use std::cell::RefCell;
15
16use ratatui::layout::{Constraint, Layout, Rect};
17use ratatui::style::{Color, Modifier, Style};
18use ratatui::text::{Line, Span};
19use ratatui::widgets::{Paragraph, Widget};
20use ratatui::Frame;
21
22use crate::chat_app::{ChatApp, ChatHistoryEntry, ChatMode, ChatRole, ToolCallRecord};
23use crate::theme;
24use crate::theme::BG_PANEL;
25
26thread_local! {
31 pub(crate) static EDITOR_STATE: RefCell<Option<edtui::EditorState>> = const { RefCell::new(None) };
32}
33
34pub fn take_editor_text() -> String {
35 EDITOR_STATE.with(|cell| {
36 let state = cell.borrow();
37 if let Some(ref s) = *state {
38 s.lines.to_string()
39 } else {
40 String::new()
41 }
42 })
43}
44
45pub fn draw(frame: &mut Frame, app: &ChatApp) {
50 let area = frame.area();
51
52 if matches!(app.mode, ChatMode::Editor) {
53 draw_editor_overlay(frame, area, app);
54 return;
55 }
56
57 EDITOR_STATE.with(|cell| {
58 *cell.borrow_mut() = None;
59 });
60
61 let input_height = (app.textarea.lines().len() as u16).max(1) + 2;
62 let [history, input_area, fkey] = Layout::vertical([
63 Constraint::Min(1),
64 Constraint::Length(input_height),
65 Constraint::Length(1),
66 ])
67 .areas(area);
68
69 draw_history(frame, history, app);
70 draw_input_area(frame, input_area, app);
71 draw_fkey_bar(frame, fkey, app);
72
73 if matches!(app.mode, ChatMode::Settings { .. }) {
75 draw_settings_modal(frame, area, app);
76 }
77}
78
79fn wrap_line(text: &str, width: usize, style: Style) -> Vec<Line<'static>> {
85 if text.is_empty() {
86 return vec![Line::from(Span::raw(""))];
87 }
88 let mut lines = Vec::new();
89 let mut remaining = text;
90 while !remaining.is_empty() {
91 let take = remaining
92 .char_indices()
93 .take(width)
94 .last()
95 .map(|(i, c)| i + c.len_utf8())
96 .unwrap_or(remaining.len());
97 let chunk = remaining[..take].to_owned();
98 remaining = &remaining[take..];
99 lines.push(Line::from(Span::styled(chunk, style)));
100 }
101 lines
102}
103
104const SPINNER_FRAMES: &[char] = &['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'];
106
107fn tool_call_lines(tc: &ToolCallRecord, spinner_tick: u32) -> Vec<Line<'static>> {
109 let dim = Style::default().fg(Color::DarkGray);
110 let gear_style = Style::default().fg(Color::Yellow);
111 let ok_style = Style::default().fg(Color::Green);
112 let err_style = Style::default().fg(Color::Red);
113 let spin_style = Style::default().fg(Color::Cyan);
114
115 let args_display = {
117 let a = tc.arguments.trim();
118 let end = a
119 .char_indices()
120 .take(40)
121 .last()
122 .map(|(i, c)| i + c.len_utf8())
123 .unwrap_or(a.len());
124 if a.len() > end {
125 format!("{}…", &a[..end])
126 } else {
127 a.to_owned()
128 }
129 };
130 let header = Line::from(vec![
131 Span::raw(" "),
132 Span::styled("\u{2699} ".to_owned(), gear_style),
133 Span::styled(tc.description.clone(), dim.add_modifier(Modifier::ITALIC)),
134 Span::raw(" "),
135 Span::styled(args_display, dim),
136 ]);
137
138 let status = match &tc.result {
140 None => {
141 let frame = SPINNER_FRAMES[(spinner_tick as usize) % SPINNER_FRAMES.len()];
142 Line::from(vec![
143 Span::raw(" "),
144 Span::styled(frame.to_string(), spin_style),
145 Span::styled(" running\u{2026}".to_owned(), dim),
146 ])
147 }
148 Some(r) => {
149 let (icon, style, text) = if r.starts_with("error:") {
150 ("\u{2717}", err_style, r.as_str())
151 } else {
152 ("\u{2713}", ok_style, r.as_str())
153 };
154 let end = text
155 .char_indices()
156 .take(80)
157 .last()
158 .map(|(i, c)| i + c.len_utf8())
159 .unwrap_or(text.len());
160 let display = if text.len() > end {
161 format!("{}…", &text[..end])
162 } else {
163 text.to_owned()
164 };
165 Line::from(vec![
166 Span::raw(" "),
167 Span::styled(format!("{icon} "), style),
168 Span::styled(display, dim),
169 ])
170 }
171 };
172
173 vec![header, status]
174}
175
176fn entry_lines(
178 entry: &ChatHistoryEntry,
179 width: usize,
180 show_thinking: bool,
181 spinner_tick: u32,
182) -> Vec<Line<'static>> {
183 let mut lines: Vec<Line<'static>> = Vec::new();
184
185 if matches!(entry.role, ChatRole::Tool) {
187 return lines;
191 }
192
193 if !entry.thinking.is_empty() {
195 if show_thinking {
196 let think_header_style = Style::default()
197 .fg(Color::DarkGray)
198 .add_modifier(Modifier::ITALIC);
199 lines.push(Line::from(Span::styled(
200 "\u{256d} thinking".to_owned(),
201 think_header_style,
202 )));
203 let think_style = Style::default()
204 .fg(Color::DarkGray)
205 .add_modifier(Modifier::ITALIC);
206 for logical in entry.thinking.split('\n') {
207 if logical.is_empty() {
208 lines.push(Line::from(Span::raw("")));
209 } else {
210 lines.extend(wrap_line(logical, width.saturating_sub(2), think_style));
211 }
212 }
213 lines.push(Line::from(Span::styled(
214 "\u{2570}\u{2500}\u{2500}\u{2500}".to_owned(),
215 Style::default().fg(Color::DarkGray),
216 )));
217 } else {
218 lines.push(Line::from(vec![
219 Span::styled(
220 "\u{25b8} thinking ".to_owned(),
221 Style::default().fg(Color::DarkGray),
222 ),
223 Span::styled(
224 "[Ctrl-O to show]".to_owned(),
225 Style::default()
226 .fg(Color::DarkGray)
227 .add_modifier(Modifier::DIM),
228 ),
229 ]));
230 }
231 }
232
233 let (prefix, prefix_style): (&str, Style) = match entry.role {
235 ChatRole::User => ("You: ", theme::tab_active()),
236 ChatRole::Assistant => ("AI: ", Style::default().fg(Color::Cyan)),
237 ChatRole::Tool => unreachable!("Tool messages handled above"),
238 };
239
240 let content = &entry.content;
241 if content.is_empty() && entry.thinking.is_empty() && entry.tool_calls.is_empty() {
242 lines.push(Line::from(Span::styled(prefix.to_owned(), prefix_style)));
243 return lines;
244 }
245
246 if !content.is_empty() {
247 let logical_lines: Vec<&str> = content.split('\n').collect();
248 for (li, logical) in logical_lines.iter().enumerate() {
249 if li == 0 {
250 let first_text = format!("{}{}", prefix, logical);
251 let prefix_bytes = prefix.len();
252 if first_text.len() <= width {
253 let line = Line::from(vec![
254 Span::styled(first_text[..prefix_bytes].to_owned(), prefix_style),
255 Span::raw(first_text[prefix_bytes..].to_owned()),
256 ]);
257 lines.push(line);
258 } else {
259 let mut remaining = first_text.as_str();
260 let mut first_chunk = true;
261 while !remaining.is_empty() {
262 let take = remaining
263 .char_indices()
264 .take(width)
265 .last()
266 .map(|(i, c)| i + c.len_utf8())
267 .unwrap_or(remaining.len());
268 let chunk = &remaining[..take];
269 remaining = &remaining[take..];
270 if first_chunk {
271 let pb = prefix_bytes.min(chunk.len());
272 let line = Line::from(vec![
273 Span::styled(chunk[..pb].to_owned(), prefix_style),
274 Span::raw(chunk[pb..].to_owned()),
275 ]);
276 lines.push(line);
277 first_chunk = false;
278 } else {
279 lines.push(Line::from(Span::raw(chunk.to_owned())));
280 }
281 }
282 }
283 } else if logical.is_empty() {
284 lines.push(Line::from(Span::raw("")));
285 } else {
286 lines.extend(wrap_line(logical, width, Style::default()));
287 }
288 }
289 } else if entry.thinking.is_empty() && !entry.tool_calls.is_empty() {
290 lines.push(Line::from(Span::styled(prefix.to_owned(), prefix_style)));
292 }
293
294 for tc in &entry.tool_calls {
296 lines.extend(tool_call_lines(tc, spinner_tick));
297 }
298
299 lines
300}
301
302fn draw_history(frame: &mut Frame, area: Rect, app: &ChatApp) {
303 let width = area.width.max(1) as usize;
304
305 let mut all_lines: Vec<Line<'static>> = Vec::new();
306 for entry in &app.history {
307 all_lines.extend(entry_lines(
308 entry,
309 width,
310 app.show_thinking,
311 app.spinner_tick,
312 ));
313 }
314
315 let total = all_lines.len();
316 let visible = area.height as usize;
317 let skip = if total <= visible {
318 0
319 } else {
320 let tail_start = total.saturating_sub(visible);
321 tail_start.saturating_sub(app.scroll_offset)
322 };
323
324 let display_lines: Vec<Line<'static>> =
325 all_lines.into_iter().skip(skip).take(visible).collect();
326
327 let para = Paragraph::new(display_lines).style(Style::default().bg(theme::BG));
328 frame.render_widget(para, area);
329}
330
331fn draw_input_area(frame: &mut Frame, area: Rect, app: &ChatApp) {
336 match app.mode {
337 ChatMode::Input | ChatMode::Streaming | ChatMode::Settings { .. } => {
338 frame.render_widget(&app.textarea, area);
339 }
340 ChatMode::Editor => {}
341 }
342}
343
344fn draw_fkey_bar(frame: &mut Frame, area: Rect, app: &ChatApp) {
349 if matches!(app.mode, ChatMode::Settings { .. }) {
351 let keys: &[(&str, &str)] = &[
352 ("\u{2191}\u{2193}", "Select"),
353 ("\u{2190}\u{2192}", "Adjust"),
354 ("Enter", "Save"),
355 ("Esc", "Cancel"),
356 ];
357 let mut spans = vec![Span::raw(" ")];
358 for (key, label) in keys {
359 spans.push(Span::styled(*key, theme::help_key()));
360 spans.push(Span::raw(" "));
361 spans.push(Span::styled(*label, theme::help_text()));
362 spans.push(Span::raw(" "));
363 }
364 frame.render_widget(
365 Paragraph::new(Line::from(spans)).style(Style::default().bg(BG_PANEL)),
366 area,
367 );
368 return;
369 }
370
371 let show_status = matches!(app.mode, ChatMode::Input)
372 && app
373 .status
374 .as_deref()
375 .map(|s| s != "Generating\u{2026}" && s != "Cancelled")
376 .unwrap_or(false);
377
378 let line = if show_status {
379 let msg = app.status.as_deref().unwrap_or("");
380 Line::from(vec![
381 Span::raw(" "),
382 Span::styled("Enter", theme::help_key()),
383 Span::raw(" "),
384 Span::styled("Send", theme::help_text()),
385 Span::raw(" "),
386 Span::styled(msg.to_owned(), theme::help_text()),
387 ])
388 } else if matches!(app.mode, ChatMode::Streaming) {
389 let mut spans = vec![Span::raw(" ")];
390 #[cfg(not(target_os = "wasi"))]
393 if app.pending_tool_calls == 0 {
394 spans.extend([
395 Span::styled("Esc", theme::help_key()),
396 Span::raw(" "),
397 Span::styled("Cancel", theme::help_text()),
398 Span::raw(" "),
399 ]);
400 }
401 spans.extend([
402 Span::styled("Enter", theme::help_key()),
403 Span::raw(" "),
404 Span::styled("Queue", theme::help_text()),
405 Span::raw(" "),
406 Span::styled("Ctrl-O", theme::help_key()),
407 Span::raw(" "),
408 Span::styled("Thinking", theme::help_text()),
409 ]);
410 if !app.pending_prompts.is_empty() {
411 spans.push(Span::raw(" "));
412 spans.push(Span::styled(
413 format!("\u{23f3} {} queued", app.pending_prompts.len()),
414 theme::help_text(),
415 ));
416 }
417 Line::from(spans)
418 } else {
419 let keys: &[(&str, &str)] = &[
420 ("Enter", "Send"),
421 ("/path", "VFS"),
422 ("Ctrl-J", "Newline"),
423 ("\u{2191}\u{2193}", "Scroll"),
424 ("Ctrl-E", "Editor"),
425 ("Ctrl-O", "Thinking"),
426 ("Ctrl-Space q", "Close"),
427 ];
428 let mut spans = Vec::new();
429 spans.push(Span::raw(" "));
430 for (key, label) in keys {
431 spans.push(Span::styled(*key, theme::help_key()));
432 spans.push(Span::raw(" "));
433 spans.push(Span::styled(*label, theme::help_text()));
434 spans.push(Span::raw(" "));
435 }
436 Line::from(spans)
437 };
438
439 frame.render_widget(
440 Paragraph::new(line).style(Style::default().bg(theme::BG_PANEL)),
441 area,
442 );
443}
444
445fn draw_settings_modal(frame: &mut Frame, area: Rect, app: &ChatApp) {
454 use ratatui::widgets::Clear;
455
456 let selected_field = match app.mode {
457 ChatMode::Settings { selected_field } => selected_field,
458 _ => return,
459 };
460
461 let modal_w: u16 = 46;
463 let modal_h: u16 = 11;
464 let x = area.x + (area.width.saturating_sub(modal_w)) / 2;
465 let y = area.y + (area.height.saturating_sub(modal_h)) / 2;
466 let modal_area = Rect::new(x, y, modal_w.min(area.width), modal_h.min(area.height));
467
468 frame.render_widget(Clear, modal_area);
469 let block = hyprstream_compositor::theme::modal_block(Line::from(
470 " Chat Settings (Enter save \u{00b7} Esc cancel) ",
471 ));
472 let inner = block.inner(modal_area);
473 frame.render_widget(block, modal_area);
474
475 let draft = &app.settings_draft;
476 let field_defs: &[(&str, String)] = &[
477 ("Max Tokens", format!("{}", draft.max_tokens)),
478 ("Temperature", format!("{:.2}", draft.temperature)),
479 ("Top-P", format!("{:.2}", draft.top_p)),
480 (
481 "Top-K",
482 draft.top_k.map_or("off".to_owned(), |v| v.to_string()),
483 ),
484 (
485 "Context Window",
486 draft
487 .context_window
488 .map_or("model default".to_owned(), |v| format!("{v}")),
489 ),
490 ];
491
492 let sel_style = Style::default()
493 .fg(Color::Cyan)
494 .add_modifier(Modifier::BOLD);
495 let dim_style = Style::default().fg(Color::DarkGray);
496 let val_style = Style::default().fg(Color::White);
497 let arrow_style = Style::default().fg(Color::Cyan);
498
499 let mut lines: Vec<Line<'static>> = field_defs
500 .iter()
501 .enumerate()
502 .map(|(i, (label, value))| {
503 let is_sel = i == selected_field;
504 let cursor = if is_sel { "\u{25b6} " } else { " " };
505 let lbl_style = if is_sel { sel_style } else { dim_style };
506 let (al, ar) = if is_sel {
507 (
508 Span::styled("\u{2039} ", arrow_style),
509 Span::styled(" \u{203a}", arrow_style),
510 )
511 } else {
512 (Span::raw(" "), Span::raw(" "))
513 };
514 Line::from(vec![
515 Span::styled(
516 cursor.to_owned(),
517 if is_sel { sel_style } else { dim_style },
518 ),
519 Span::styled(format!("{:<16}", label), lbl_style),
520 al,
521 Span::styled(format!("{:>10}", value), val_style),
522 ar,
523 ])
524 })
525 .collect();
526
527 lines.push(Line::from(""));
528 lines.push(Line::from(vec![Span::styled(
529 " \u{2191}\u{2193} select \u{2190}\u{2192} adjust",
530 dim_style,
531 )]));
532
533 frame.render_widget(
534 Paragraph::new(lines).style(Style::default().bg(BG_PANEL)),
535 inner,
536 );
537}
538
539fn draw_editor_overlay(frame: &mut Frame, area: Rect, app: &ChatApp) {
540 use ratatui::widgets::Clear;
541 frame.render_widget(Clear, area);
542 let block = hyprstream_compositor::theme::modal_block(Line::from(
543 " Editor (Ctrl-S save · Esc cancel) ",
544 ));
545 let inner = block.inner(area);
546 frame.render_widget(block, area);
547
548 EDITOR_STATE.with(|cell| {
549 let mut opt = cell.borrow_mut();
550 if opt.is_none() {
551 *opt = Some(edtui::EditorState::new(edtui::Lines::from(
552 app.editor_text.as_str(),
553 )));
554 }
555 if let Some(ref mut state) = *opt {
556 edtui::EditorView::new(state)
557 .wrap(true)
558 .render(inner, frame.buffer_mut());
559 }
560 });
561}