1use crate::terminal::{ChatReply, ChatSummary};
2use crossterm::event::Event;
3use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
4use futures_util::{Stream, StreamExt};
5use ratatui::{
6 Frame,
7 layout::{Constraint, Layout},
8 style::{Color, Style},
9 widgets::{List, ListItem, ListState, Paragraph},
10};
11use rigspark_runtime::{harness::HarnessMessage, sessions::gui_text};
12use std::io;
13use tokio_util::sync::CancellationToken;
14use unicode_segmentation::UnicodeSegmentation;
15
16pub async fn drive<B: ratatui::backend::Backend>(
17 terminal: &mut ratatui::Terminal<B>,
18 events: &mut (impl Stream<Item = io::Result<Event>> + Unpin),
19 engine: &impl crate::terminal::ChatEngine,
20 view: &mut ChatView,
21 color: bool,
22 cancel: &CancellationToken,
23) -> io::Result<u8> {
24 loop {
25 terminal
26 .draw(|frame| render(frame, view, color))
27 .map_err(|error| io::Error::other(error.to_string()))?;
28 let event = tokio::select! {
29 biased;
30 _ = cancel.cancelled() => return Ok(130),
31 event = events.next() => event.ok_or_else(|| io::Error::other("terminal input ended"))??,
32 };
33 let action = match event {
34 Event::Key(key) => handle_key(view, key),
35 Event::Paste(text) => {
36 if let Err(error) = view.insert(&text) {
37 view.error = Some(error.to_string());
38 }
39 InputAction::Continue
40 }
41 _ => InputAction::Continue,
42 };
43 match action {
44 InputAction::Exit => return Ok(u8::from(view.summary.failed_turns > 0)),
45 InputAction::Interrupt => {
46 cancel.cancel();
47 return Ok(130);
48 }
49 InputAction::Continue => continue,
50 InputAction::Submit => (),
51 }
52 let context = view.submit()?;
53 let reply = engine.reply(&context, cancel);
54 tokio::pin!(reply);
55 loop {
56 terminal
57 .draw(|frame| render(frame, view, color))
58 .map_err(|error| io::Error::other(error.to_string()))?;
59 tokio::select! {
60 biased;
61 _ = cancel.cancelled() => return Ok(130),
62 reply = &mut reply => {view.finish(reply); break;},
63 event = events.next() => {
64 let event = event.ok_or_else(|| io::Error::other("terminal input ended"))??;
65 if let Event::Key(key) = event {
66 match handle_key(view,key) {
67 InputAction::Exit => {cancel.cancel(); return Ok(0);}
68 InputAction::Interrupt => {cancel.cancel(); return Ok(130);}
69 _ => (),
70 }
71 }
72 },
73 }
74 }
75 }
76}
77
78pub async fn run_chat(
79 title: &str,
80 engine: &impl crate::terminal::ChatEngine,
81 color: bool,
82 cancel: &CancellationToken,
83) -> io::Result<(ChatSummary, u8)> {
84 let mut view = ChatView::new(title);
85 let mut signals = crate::cancellation::TerminalSignals::new()?;
86 let (mut terminal, _restore) = crate::tui_view::enter_terminal()?;
87 let mut events = crate::terminal_events::terminal_events();
88 let result = tokio::select! {
89 result = drive(&mut terminal, &mut events, engine, &mut view, color, cancel) => result,
90 result = signals.recv() => result,
91 };
92 cancel.cancel();
93 let code = result?;
94 view.summary.cancelled = matches!(code, 129 | 130 | 143);
95 Ok((view.summary, code))
96}
97
98#[derive(Debug, PartialEq, Eq)]
99pub enum InputAction {
100 Continue,
101 Submit,
102 Exit,
103 Interrupt,
104}
105
106pub struct ChatView {
107 title: String,
108 draft: String,
109 history: Vec<HarnessMessage>,
110 pending: Option<String>,
111 error: Option<String>,
112 summary: ChatSummary,
113}
114
115impl ChatView {
116 pub fn new(title: &str) -> Self {
117 Self {
118 title: gui_text(title).chars().take(256).collect(),
119 draft: String::new(),
120 history: Vec::new(),
121 pending: None,
122 error: None,
123 summary: ChatSummary::default(),
124 }
125 }
126 pub fn draft(&self) -> &str {
127 &self.draft
128 }
129 pub fn history(&self) -> &[HarnessMessage] {
130 &self.history
131 }
132 pub fn summary(&self) -> &ChatSummary {
133 &self.summary
134 }
135 pub fn insert(&mut self, text: &str) -> io::Result<()> {
136 let bytes = self.draft.len().saturating_add(text.len());
137 if bytes > 32768 {
138 return Err(io::Error::other(format!(
139 "Draft exceeds 32768 byte limit ({bytes} bytes)"
140 )));
141 }
142 let text = gui_text(text);
143 let next = format!("{}{text}", self.draft);
144 crate::terminal::validate_draft(&next)?;
145 self.draft = next;
146 self.error = None;
147 Ok(())
148 }
149 pub fn submit(&mut self) -> io::Result<Vec<HarnessMessage>> {
150 if self.pending.is_some() || self.draft.trim().is_empty() {
151 return Err(io::Error::other("no submittable draft"));
152 }
153 let turn = std::mem::take(&mut self.draft);
154 self.pending = Some(turn.clone());
155 self.error = None;
156 let mut context = self.history.clone();
157 context.push(HarnessMessage {
158 role: "user".into(),
159 content: turn,
160 });
161 if context.len() > 20 {
162 context.drain(..context.len() - 20);
163 }
164 Ok(context)
165 }
166 pub fn finish(&mut self, reply: Result<ChatReply, String>) {
167 let Some(turn) = self.pending.take() else {
168 return;
169 };
170 let reply = reply.and_then(|reply| {
171 if reply.content.len() > 1024 * 1024 {
172 Err("response exceeds 1 MiB".into())
173 } else {
174 Ok(reply)
175 }
176 });
177 match reply {
178 Ok(reply) => {
179 self.history.push(HarnessMessage {
180 role: "user".into(),
181 content: turn,
182 });
183 self.history.push(HarnessMessage {
184 role: "assistant".into(),
185 content: reply.content,
186 });
187 if self.history.len() > 20 {
188 self.history.drain(..self.history.len() - 20);
189 }
190 self.summary.turns += 1;
191 if reply.memory_warning {
192 self.summary.memory_warnings += 1;
193 self.error = Some("Failed to record memory".into());
194 }
195 }
196 Err(error) => {
197 self.summary.failed_turns += 1;
198 self.error = Some(gui_text(&error).chars().take(1024).collect());
199 }
200 }
201 }
202}
203
204pub fn handle_key(view: &mut ChatView, key: KeyEvent) -> InputAction {
205 if key.kind == KeyEventKind::Release {
206 return InputAction::Continue;
207 }
208 if key.code == KeyCode::Esc {
209 return InputAction::Exit;
210 }
211 if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
212 if view.draft.is_empty() || view.pending.is_some() {
213 return InputAction::Interrupt;
214 }
215 view.draft.clear();
216 return InputAction::Continue;
217 }
218 if view.pending.is_some() {
219 return InputAction::Continue;
220 }
221 let inserted = match key.code {
222 KeyCode::Enter if !view.draft.trim().is_empty() => return InputAction::Submit,
223 KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => Some("\n".into()),
224 KeyCode::Char(character)
225 if !key
226 .modifiers
227 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
228 && !character.is_control() =>
229 {
230 Some(character.to_string())
231 }
232 KeyCode::Backspace => {
233 if let Some((position, _)) = view.draft.grapheme_indices(true).next_back() {
234 view.draft.truncate(position);
235 }
236 None
237 }
238 _ => None,
239 };
240 if let Some(text) = inserted
241 && let Err(error) = view.insert(&text)
242 {
243 view.error = Some(error.to_string());
244 }
245 InputAction::Continue
246}
247
248fn transcript_lines(view: &ChatView) -> Vec<String> {
249 let pending = view.pending.as_ref().map(|turn| {
250 (
251 ">",
252 crate::accessible_text::multiline(turn)
253 .unwrap_or_else(|_| "[draft exceeds display limits]".into()),
254 )
255 });
256 let history = view.history.iter().rev().take(10).map(|message| {
257 (
258 if message.role == "user" { ">" } else { " " },
259 crate::accessible_text::chat_message(&message.content)
260 .unwrap_or_else(|_| "[message exceeds display limits]".into()),
261 )
262 });
263 let mut retained_bytes = 0usize;
264 let mut lines = Vec::new();
265 'messages: for (prefix, visible) in pending.into_iter().chain(history) {
266 for line in visible.lines().rev() {
267 let bytes = prefix.len() + 1 + line.len() + 1;
268 if retained_bytes + bytes > 192 * 1024 {
269 break 'messages;
270 }
271 retained_bytes += bytes;
272 lines.push(format!("{prefix} {line}"));
273 }
274 }
275 lines.reverse();
276 lines
277}
278
279pub fn render(frame: &mut Frame<'_>, view: &ChatView, color: bool) {
280 let [header, transcript, status, input] = Layout::vertical([
281 Constraint::Length(1),
282 Constraint::Min(1),
283 Constraint::Length(1),
284 Constraint::Length(if frame.area().height > 8 { 3 } else { 1 }),
285 ])
286 .areas(frame.area());
287 let accent = if color {
288 Style::default().fg(Color::Cyan)
289 } else {
290 Style::default()
291 };
292 frame.render_widget(
293 Paragraph::new(format!("rigspark / chat / {}", view.title)).style(accent),
294 header,
295 );
296 let lines = transcript_lines(view);
297 let mut state = ListState::default().with_selected(lines.len().checked_sub(1));
298 frame.render_stateful_widget(
299 List::new(lines.into_iter().map(ListItem::new).collect::<Vec<_>>()),
300 transcript,
301 &mut state,
302 );
303 frame.render_widget(
304 Paragraph::new(if view.pending.is_some() {
305 "Waiting for response..."
306 } else {
307 view.error.as_deref().unwrap_or("Ready")
308 }),
309 status,
310 );
311 let draft = view
312 .draft
313 .lines()
314 .rev()
315 .take(3)
316 .collect::<Vec<_>>()
317 .into_iter()
318 .rev()
319 .collect::<Vec<_>>()
320 .join("\n");
321 frame.render_widget(Paragraph::new(format!("> {draft}")).style(accent), input);
322}
323
324#[cfg(test)]
325mod display_tests {
326 use super::*;
327
328 #[test]
329 fn newline_heavy_transcript_and_pending_draft_share_the_display_budget() {
330 let mut view = ChatView::new("local");
331 for _ in 0..5 {
332 view.insert("question").unwrap();
333 view.submit().unwrap();
334 view.finish(Ok(crate::terminal::ChatReply {
335 content: "\n".repeat(65536),
336 memory_warning: false,
337 }));
338 }
339 view.insert("pending\r\nlast line").unwrap();
340 view.submit().unwrap();
341 let lines = transcript_lines(&view);
342 assert!(lines.iter().map(|line| line.len() + 1).sum::<usize>() <= 192 * 1024);
343 assert_eq!(lines.last().unwrap(), "> last line");
344 assert!(lines.iter().all(|line| !line.contains(['\r', '\n'])));
345 assert_eq!(view.history.len(), 10);
346 }
347
348 #[test]
349 fn transcript_budget_keeps_latest_rows_without_mutating_history() {
350 let mut view = ChatView::new("local");
351 for index in 0..6 {
352 view.insert("question").unwrap();
353 view.submit().unwrap();
354 view.finish(Ok(crate::terminal::ChatReply {
355 content: format!("{}\nLATEST-{index}", "x".repeat(60 * 1024)),
356 memory_warning: false,
357 }));
358 }
359 let before: Vec<_> = view
360 .history
361 .iter()
362 .map(|message| message.content.clone())
363 .collect();
364 let lines = transcript_lines(&view);
365 assert!(lines.iter().map(|line| line.len() + 1).sum::<usize>() <= 192 * 1024);
366 assert!(lines.last().unwrap().contains("LATEST-5"));
367 assert!(lines.iter().filter(|line| line.len() > 1024).count() < 6);
368 assert_eq!(
369 before,
370 view.history
371 .iter()
372 .map(|message| message.content.clone())
373 .collect::<Vec<_>>()
374 );
375 }
376}