1use crate::terminal::{ChatReply, ChatSummary};
2use crate::tui_theme::{self, Theme};
3use crossterm::event::Event;
4use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEventKind};
5use futures_util::{Stream, StreamExt};
6use ratatui::{
7 Frame,
8 layout::{Constraint, Layout, Rect},
9 style::{Modifier, Style},
10 text::{Line, Span},
11 widgets::Paragraph,
12};
13use rigspark_runtime::{harness::HarnessMessage, sessions::gui_text};
14use std::io;
15use std::time::{Duration, Instant};
16use tokio_util::sync::CancellationToken;
17use unicode_segmentation::UnicodeSegmentation;
18
19const MAX_STREAM_BYTES: usize = 1024 * 1024;
20
21fn scroll_event(view: &mut ChatView, event: &Event) {
22 if let Event::Mouse(mouse) = event {
23 match mouse.kind {
24 MouseEventKind::ScrollUp => view.scroll = view.scroll.saturating_add(3),
25 MouseEventKind::ScrollDown => view.scroll = view.scroll.saturating_sub(3),
26 _ => (),
27 }
28 }
29}
30
31fn flush_clipboard(view: &mut ChatView) -> io::Result<()> {
32 match view.clipboard.take() {
33 Some(text) => tui_theme::copy_to_clipboard(&text),
34 None => Ok(()),
35 }
36}
37
38pub async fn drive<B: ratatui::backend::Backend>(
39 terminal: &mut ratatui::Terminal<B>,
40 events: &mut (impl Stream<Item = io::Result<Event>> + Unpin),
41 engine: &impl crate::terminal::ChatEngine,
42 view: &mut ChatView,
43 color: bool,
44 cancel: &CancellationToken,
45) -> io::Result<u8> {
46 loop {
47 terminal
48 .draw(|frame| render(frame, view, color))
49 .map_err(|error| io::Error::other(error.to_string()))?;
50 let event = tokio::select! {
51 biased;
52 _ = cancel.cancelled() => return Ok(130),
53 event = events.next() => event.ok_or_else(|| io::Error::other("terminal input ended"))??,
54 };
55 scroll_event(view, &event);
56 let action = match event {
57 Event::Key(key) => handle_key(view, key),
58 Event::Paste(text) => {
59 if let Err(error) = view.insert(&text) {
60 view.error = Some(error.to_string());
61 }
62 InputAction::Continue
63 }
64 _ => InputAction::Continue,
65 };
66 flush_clipboard(view)?;
67 match action {
68 InputAction::Exit => return Ok(u8::from(view.summary.failed_turns > 0)),
69 InputAction::Interrupt => {
70 cancel.cancel();
71 return Ok(130);
72 }
73 InputAction::Continue => continue,
74 InputAction::Submit => (),
75 }
76 let context = view.submit()?;
77 let (sender, mut deltas) = tokio::sync::mpsc::unbounded_channel();
78 let reply = engine.reply_streaming(&context, cancel, sender);
79 tokio::pin!(reply);
80 loop {
81 terminal
82 .draw(|frame| render(frame, view, color))
83 .map_err(|error| io::Error::other(error.to_string()))?;
84 tokio::select! {
85 biased;
86 _ = cancel.cancelled() => return Ok(130),
87 reply = &mut reply => {view.finish(reply); break;},
88 Some(delta) = deltas.recv() => view.stream(&delta),
89 () = tokio::time::sleep(Duration::from_millis(250)) => (),
90 event = events.next() => {
91 let event = event.ok_or_else(|| io::Error::other("terminal input ended"))??;
92 scroll_event(view, &event);
93 if let Event::Key(key) = event {
94 match handle_key(view,key) {
95 InputAction::Exit => {cancel.cancel(); return Ok(0);}
96 InputAction::Interrupt => {cancel.cancel(); return Ok(130);}
97 _ => (),
98 }
99 }
100 flush_clipboard(view)?;
101 },
102 }
103 }
104 }
105}
106
107pub async fn run_chat(
108 title: &str,
109 engine: &impl crate::terminal::ChatEngine,
110 color: bool,
111 cancel: &CancellationToken,
112) -> io::Result<(ChatSummary, u8)> {
113 let mut view = ChatView::new(title);
114 let mut signals = crate::cancellation::TerminalSignals::new()?;
115 let (mut terminal, _restore) = crate::tui_view::enter_terminal()?;
116 let mut events = crate::terminal_events::terminal_events();
117 let result = tokio::select! {
118 result = drive(&mut terminal, &mut events, engine, &mut view, color, cancel) => result,
119 result = signals.recv() => result,
120 };
121 cancel.cancel();
122 let code = result?;
123 view.summary.cancelled = matches!(code, 129 | 130 | 143);
124 Ok((view.summary, code))
125}
126
127#[derive(Debug, PartialEq, Eq)]
128pub enum InputAction {
129 Continue,
130 Submit,
131 Exit,
132 Interrupt,
133}
134
135pub struct ChatView {
136 title: String,
137 draft: String,
138 history: Vec<HarnessMessage>,
139 pending: Option<String>,
140 streaming: String,
141 error: Option<String>,
142 summary: ChatSummary,
143 scroll: usize,
144 started: Option<Instant>,
145 first_output: Option<Duration>,
146 timing: Option<(Option<Duration>, Duration)>,
147 clipboard: Option<String>,
148 notice: Option<&'static str>,
149}
150
151impl ChatView {
152 pub fn new(title: &str) -> Self {
153 Self {
154 title: gui_text(title).chars().take(256).collect(),
155 draft: String::new(),
156 history: Vec::new(),
157 pending: None,
158 streaming: String::new(),
159 error: None,
160 summary: ChatSummary::default(),
161 scroll: 0,
162 started: None,
163 first_output: None,
164 timing: None,
165 clipboard: None,
166 notice: None,
167 }
168 }
169 pub fn stream(&mut self, delta: &str) {
171 if self.pending.is_none() {
172 return;
173 }
174 if self.first_output.is_none() {
175 self.first_output = self.started.map(|started| started.elapsed());
176 }
177 let room = MAX_STREAM_BYTES.saturating_sub(self.streaming.len());
178 let mut end = delta.len().min(room);
179 while !delta.is_char_boundary(end) {
180 end -= 1;
181 }
182 self.streaming.push_str(&delta[..end]);
183 }
184 pub fn streaming(&self) -> &str {
185 &self.streaming
186 }
187 pub fn take_clipboard(&mut self) -> Option<String> {
188 self.clipboard.take()
189 }
190 pub fn draft(&self) -> &str {
191 &self.draft
192 }
193 pub fn history(&self) -> &[HarnessMessage] {
194 &self.history
195 }
196 pub fn summary(&self) -> &ChatSummary {
197 &self.summary
198 }
199 pub fn insert(&mut self, text: &str) -> io::Result<()> {
200 let bytes = self.draft.len().saturating_add(text.len());
201 if bytes > 32768 {
202 return Err(io::Error::other(format!(
203 "Draft exceeds 32768 byte limit ({bytes} bytes)"
204 )));
205 }
206 let text = gui_text(text);
207 let next = format!("{}{text}", self.draft);
208 crate::terminal::validate_draft(&next)?;
209 self.draft = next;
210 self.error = None;
211 Ok(())
212 }
213 pub fn submit(&mut self) -> io::Result<Vec<HarnessMessage>> {
214 if self.pending.is_some() || self.draft.trim().is_empty() {
215 return Err(io::Error::other("no submittable draft"));
216 }
217 let turn = std::mem::take(&mut self.draft);
218 self.pending = Some(turn.clone());
219 self.error = None;
220 self.streaming.clear();
221 self.scroll = 0;
222 self.started = Some(Instant::now());
223 self.first_output = None;
224 self.timing = None;
225 let mut context = self.history.clone();
226 context.push(HarnessMessage {
227 role: "user".into(),
228 content: turn,
229 });
230 if context.len() > 20 {
231 context.drain(..context.len() - 20);
232 }
233 Ok(context)
234 }
235 pub fn finish(&mut self, reply: Result<ChatReply, String>) {
236 let Some(turn) = self.pending.take() else {
237 return;
238 };
239 self.streaming.clear();
240 if let Some(started) = self.started.take() {
241 self.timing = Some((self.first_output.take(), started.elapsed()));
242 }
243 let reply = reply.and_then(|reply| {
244 if reply.content.len() > 1024 * 1024 {
245 Err("response exceeds 1 MiB".into())
246 } else {
247 Ok(reply)
248 }
249 });
250 match reply {
251 Ok(reply) => {
252 self.history.push(HarnessMessage {
253 role: "user".into(),
254 content: turn,
255 });
256 self.history.push(HarnessMessage {
257 role: "assistant".into(),
258 content: reply.content,
259 });
260 if self.history.len() > 20 {
261 self.history.drain(..self.history.len() - 20);
262 }
263 self.summary.turns += 1;
264 if reply.memory_warning {
265 self.summary.memory_warnings += 1;
266 self.error = Some("Failed to record memory".into());
267 }
268 }
269 Err(error) => {
270 self.summary.failed_turns += 1;
271 self.error = Some(gui_text(&error).chars().take(1024).collect());
272 }
273 }
274 }
275}
276
277pub fn handle_key(view: &mut ChatView, key: KeyEvent) -> InputAction {
278 if key.kind == KeyEventKind::Release {
279 return InputAction::Continue;
280 }
281 if key.code == KeyCode::Esc {
282 return InputAction::Exit;
283 }
284 if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
285 if view.draft.is_empty() || view.pending.is_some() {
286 return InputAction::Interrupt;
287 }
288 view.draft.clear();
289 return InputAction::Continue;
290 }
291 view.notice = None;
292 match key.code {
293 KeyCode::PageUp => {
294 view.scroll = view.scroll.saturating_add(10).min(1 << 20);
295 return InputAction::Continue;
296 }
297 KeyCode::PageDown => {
298 view.scroll = view.scroll.saturating_sub(10);
299 return InputAction::Continue;
300 }
301 KeyCode::End => {
302 view.scroll = 0;
303 return InputAction::Continue;
304 }
305 KeyCode::Char('y') if key.modifiers.contains(KeyModifiers::CONTROL) => {
306 let last = view
307 .history
308 .iter()
309 .rev()
310 .find(|message| message.role == "assistant")
311 .map(|message| message.content.clone());
312 match last {
313 Some(text) => {
314 view.clipboard = Some(text);
315 view.notice = Some("Copied last reply to clipboard");
316 }
317 None => view.notice = Some("No reply to copy yet"),
318 }
319 return InputAction::Continue;
320 }
321 _ => (),
322 }
323 if view.pending.is_some() {
324 return InputAction::Continue;
325 }
326 let inserted = match key.code {
327 KeyCode::Enter if !view.draft.trim().is_empty() => return InputAction::Submit,
328 KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => Some("\n".into()),
329 KeyCode::Char(character)
330 if !key
331 .modifiers
332 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
333 && !character.is_control() =>
334 {
335 Some(character.to_string())
336 }
337 KeyCode::Backspace => {
338 if let Some((position, _)) = view.draft.grapheme_indices(true).next_back() {
339 view.draft.truncate(position);
340 }
341 None
342 }
343 _ => None,
344 };
345 if let Some(text) = inserted
346 && let Err(error) = view.insert(&text)
347 {
348 view.error = Some(error.to_string());
349 }
350 InputAction::Continue
351}
352
353fn transcript_lines(view: &ChatView) -> Vec<String> {
354 let streaming = (view.pending.is_some() && !view.streaming.is_empty()).then(|| {
355 (
356 " ",
357 crate::accessible_text::chat_message(&view.streaming)
358 .unwrap_or_else(|_| "[message exceeds display limits]".into()),
359 )
360 });
361 let pending = view.pending.as_ref().map(|turn| {
362 (
363 ">",
364 crate::accessible_text::multiline(turn)
365 .unwrap_or_else(|_| "[draft exceeds display limits]".into()),
366 )
367 });
368 let history = view.history.iter().rev().take(10).map(|message| {
369 (
370 if message.role == "user" { ">" } else { " " },
371 crate::accessible_text::chat_message(&message.content)
372 .unwrap_or_else(|_| "[message exceeds display limits]".into()),
373 )
374 });
375 let mut retained_bytes = 0usize;
376 let mut lines = Vec::new();
377 'messages: for (prefix, visible) in streaming.into_iter().chain(pending).chain(history) {
378 for line in visible.lines().rev() {
379 let bytes = prefix.len() + 1 + line.len() + 1;
380 if retained_bytes + bytes > 192 * 1024 {
381 break 'messages;
382 }
383 retained_bytes += bytes;
384 lines.push(format!("{prefix} {line}"));
385 }
386 }
387 lines.reverse();
388 lines
389}
390
391pub fn render(frame: &mut Frame<'_>, view: &ChatView, color: bool) {
392 let area = frame.area();
393 let theme = Theme::new(color);
394 let roomy = area.height > 12;
395 let [header, transcript, status, input, footer] = Layout::vertical([
396 Constraint::Length(1),
397 Constraint::Min(1),
398 Constraint::Length(1),
399 Constraint::Length(if roomy {
400 5
401 } else if area.height > 8 {
402 3
403 } else {
404 1
405 }),
406 Constraint::Length(if area.height > 8 { 1 } else { 0 }),
407 ])
408 .areas(area);
409 theme.header(
410 frame,
411 header,
412 &format!("rigspark / chat / {}", view.title),
413 &format!(
414 "{} turn{}",
415 view.summary.turns,
416 if view.summary.turns == 1 { "" } else { "s" }
417 ),
418 );
419 let (rows, scrolled) = transcript_rows(view, transcript, theme);
420 frame.render_widget(Paragraph::new(rows), transcript);
421 let seconds = |duration: Duration| format!("{:.1}s", duration.as_secs_f64());
422 let status_line = if view.pending.is_some() {
423 let mut text = " Waiting for response...".to_owned();
424 if let Some(started) = view.started {
425 text.push_str(&format!(" {}", seconds(started.elapsed())));
426 }
427 if let Some(first) = view.first_output {
428 text.push_str(&format!(" · first output {}", seconds(first)));
429 }
430 Line::styled(text, theme.warning())
431 } else if let Some(error) = &view.error {
432 Line::styled(format!(" {error}"), theme.error())
433 } else if let Some(notice) = view.notice {
434 Line::styled(format!(" {notice}"), theme.success())
435 } else {
436 let mut text = " Ready".to_owned();
437 if let Some((first, total)) = view.timing {
438 if let Some(first) = first {
439 text.push_str(&format!(" · first output {}", seconds(first)));
440 }
441 text.push_str(&format!(" · {} total", seconds(total)));
442 }
443 Line::styled(text, theme.muted())
444 };
445 let right = if scrolled > 0 {
446 Line::styled(format!("↑ {scrolled} lines · End follows "), theme.accent())
447 } else {
448 Line::default()
449 };
450 theme.bar(frame, status, status_line, right);
451 let inner = if roomy {
452 theme.panel(frame, input, "Message")
453 } else {
454 input
455 };
456 let mut draft: Vec<&str> = view.draft.split('\n').collect();
457 let keep = usize::from(inner.height.max(1));
458 draft.drain(..draft.len().saturating_sub(keep));
459 let last = draft.len() - 1;
460 let lines: Vec<_> = draft
461 .into_iter()
462 .enumerate()
463 .map(|(index, text)| {
464 let mut spans = vec![if index == 0 {
465 Span::styled("> ", theme.title())
466 } else {
467 Span::raw(" ")
468 }];
469 spans.push(Span::raw(tail(
470 text,
471 usize::from(inner.width).saturating_sub(3),
472 )));
473 if index == last && view.pending.is_none() {
474 spans.push(Span::styled("▌", theme.accent()));
475 if view.draft.is_empty() {
476 spans.push(Span::styled(" Type a message", theme.muted()));
477 }
478 }
479 Line::from(spans)
480 })
481 .collect();
482 frame.render_widget(Paragraph::new(lines), inner);
483 frame.render_widget(
484 Paragraph::new(theme.hints(
485 &[
486 ("Enter", "send"),
487 ("Ctrl+J", "newline"),
488 ("PgUp/PgDn", "scroll"),
489 ("Ctrl+Y", "copy reply"),
490 ("Ctrl+C", "clear/stop"),
491 ("Esc", "exit"),
492 ],
493 footer.width,
494 )),
495 footer,
496 );
497}
498
499fn tail(text: &str, width: usize) -> String {
501 let mut used = 0;
502 let mut kept: Vec<&str> = text
503 .graphemes(true)
504 .rev()
505 .take_while(|grapheme| {
506 used += crate::tui_theme::width(grapheme);
507 used <= width
508 })
509 .collect();
510 kept.reverse();
511 kept.concat()
512}
513
514fn transcript_rows(view: &ChatView, area: Rect, theme: Theme) -> (Vec<Line<'static>>, usize) {
517 let height = usize::from(area.height);
518 let width = usize::from(area.width.saturating_sub(3)).max(1);
519 let code = theme.accent();
520 let mut rows = Vec::new();
521 let mut previous = None;
522 let mut fenced = false;
523 for line in &transcript_lines(view) {
524 let user = line.starts_with('>');
525 if previous != Some(user) {
526 if previous.is_some() {
527 rows.push(Line::default());
528 }
529 rows.push(if user {
530 Line::styled(" you", theme.title())
531 } else {
532 Line::styled(" assistant", theme.success())
533 });
534 fenced = false;
535 }
536 previous = Some(user);
537 let text = line.get(2..).unwrap_or("");
538 let trimmed = text.trim_start();
539 if !user && trimmed.starts_with("```") {
540 fenced = !fenced;
541 rows.push(Line::styled(format!(" {}", trimmed), theme.muted()));
542 continue;
543 }
544 let (lead, body, style, markup) = if user {
545 ("", text, theme.strong(), false)
546 } else if fenced {
547 ("", text, code, false)
548 } else if let Some(heading) = trimmed
549 .strip_prefix("### ")
550 .or_else(|| trimmed.strip_prefix("## "))
551 .or_else(|| trimmed.strip_prefix("# "))
552 {
553 ("", heading, theme.title(), true)
554 } else if let Some(item) = trimmed
555 .strip_prefix("- ")
556 .or_else(|| trimmed.strip_prefix("* "))
557 {
558 ("• ", item, Style::default(), true)
559 } else {
560 ("", text, Style::default(), true)
561 };
562 let indent = tui_theme::width(lead);
563 for (index, piece) in tui_theme::wrap(body, width.saturating_sub(indent).max(1))
564 .into_iter()
565 .enumerate()
566 {
567 let mut spans = vec![
568 Span::raw(" "),
569 Span::styled(
570 if index == 0 {
571 lead.to_owned()
572 } else {
573 " ".repeat(indent)
574 },
575 theme.muted(),
576 ),
577 ];
578 if markup {
579 spans.extend(inline_markdown(&piece, style, code));
580 } else {
581 spans.push(Span::styled(piece, style));
582 }
583 rows.push(Line::from(spans));
584 }
585 }
586 let below = view.scroll.min(rows.len().saturating_sub(height));
587 let end = rows.len() - below;
588 rows.truncate(end);
589 let start = end.saturating_sub(height);
590 (rows.split_off(start), below)
591}
592
593fn inline_markdown(text: &str, base: Style, code: Style) -> Vec<Span<'static>> {
595 let mut spans = Vec::new();
596 let segments: Vec<&str> = text.split('`').collect();
597 let balanced = segments.len() % 2 == 1;
598 for (index, segment) in segments.iter().enumerate() {
599 if balanced && index % 2 == 1 {
600 spans.push(Span::styled((*segment).to_owned(), code));
601 continue;
602 }
603 let prefix = if !balanced && index > 0 { "`" } else { "" };
604 let parts: Vec<&str> = segment.split("**").collect();
605 let bold_balanced = parts.len() % 2 == 1;
606 for (part_index, part) in parts.iter().enumerate() {
607 let mut content = String::new();
608 if part_index == 0 {
609 content.push_str(prefix);
610 }
611 if !bold_balanced && part_index > 0 {
612 content.push_str("**");
613 }
614 content.push_str(part);
615 if content.is_empty() {
616 continue;
617 }
618 let style = if bold_balanced && part_index % 2 == 1 {
619 base.add_modifier(Modifier::BOLD)
620 } else {
621 base
622 };
623 spans.push(Span::styled(content, style));
624 }
625 }
626 spans
627}
628
629#[cfg(test)]
630mod display_tests {
631 use super::*;
632
633 #[test]
634 fn newline_heavy_transcript_and_pending_draft_share_the_display_budget() {
635 let mut view = ChatView::new("local");
636 for _ in 0..5 {
637 view.insert("question").unwrap();
638 view.submit().unwrap();
639 view.finish(Ok(crate::terminal::ChatReply {
640 content: "\n".repeat(65536),
641 memory_warning: false,
642 }));
643 }
644 view.insert("pending\r\nlast line").unwrap();
645 view.submit().unwrap();
646 let lines = transcript_lines(&view);
647 assert!(lines.iter().map(|line| line.len() + 1).sum::<usize>() <= 192 * 1024);
648 assert_eq!(lines.last().unwrap(), "> last line");
649 assert!(lines.iter().all(|line| !line.contains(['\r', '\n'])));
650 assert_eq!(view.history.len(), 10);
651 }
652
653 #[test]
654 fn transcript_budget_keeps_latest_rows_without_mutating_history() {
655 let mut view = ChatView::new("local");
656 for index in 0..6 {
657 view.insert("question").unwrap();
658 view.submit().unwrap();
659 view.finish(Ok(crate::terminal::ChatReply {
660 content: format!("{}\nLATEST-{index}", "x".repeat(60 * 1024)),
661 memory_warning: false,
662 }));
663 }
664 let before: Vec<_> = view
665 .history
666 .iter()
667 .map(|message| message.content.clone())
668 .collect();
669 let lines = transcript_lines(&view);
670 assert!(lines.iter().map(|line| line.len() + 1).sum::<usize>() <= 192 * 1024);
671 assert!(lines.last().unwrap().contains("LATEST-5"));
672 assert!(lines.iter().filter(|line| line.len() > 1024).count() < 6);
673 assert_eq!(
674 before,
675 view.history
676 .iter()
677 .map(|message| message.content.clone())
678 .collect::<Vec<_>>()
679 );
680 }
681}