mod reduce;
pub use reduce::apply;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use ratatui::style::Color;
use ratatui::text::Line;
use crate::event::WorkstreamSummary;
use crate::model::{CommandDescriptor, PickerRequest, StatuslineSegment};
use crate::run::TuiModel;
use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
#[derive(Debug, Clone)]
pub struct ChatLine {
pub role: ChatRole,
pub text: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatRole {
User,
Assistant,
Error,
Status,
}
#[derive(Debug, Clone)]
pub struct ReplApp {
pub chat: Vec<ChatLine>,
pub input_buf: String,
pub cursor_pos: usize,
pub scroll_offset: usize,
pub last_max_scroll: Arc<AtomicUsize>,
pub history: Vec<String>,
pub history_idx: Option<usize>,
pub saved_input: Option<String>,
pub show_banner: bool,
pub label: String,
pub user_label: String,
pub accent_color: Color,
pub status_prefix: String,
pub banner_title: String,
pub version: String,
pub recent_activity: Vec<String>,
pub banner_art: Vec<Line<'static>>,
pub commands: Vec<CommandDescriptor>,
pub active_picker: Option<PickerRequest>,
pub busy: bool,
pub streaming_idx: Option<usize>,
pub statusline: Vec<StatuslineSegment>,
pub active_workstream: Option<WorkstreamSummary>,
pub quit: bool,
pub pending_submit: Option<String>,
pub pending_cancel: bool,
pub last_prompt: String,
pub last_bash_block: Option<String>,
pub current_generation: u64,
}
impl ReplApp {
pub fn new(label: impl Into<String>, user_label: impl Into<String>) -> Self {
let label = label.into();
let status_prefix = format!("[{label}] ");
let banner_title = label.clone();
Self {
chat: Vec::new(),
input_buf: String::new(),
cursor_pos: 0,
scroll_offset: 0,
last_max_scroll: Arc::new(AtomicUsize::new(0)),
history: Vec::new(),
history_idx: None,
saved_input: None,
show_banner: true,
label,
user_label: user_label.into(),
accent_color: Color::Cyan,
status_prefix,
banner_title,
version: env!("CARGO_PKG_VERSION").to_string(),
recent_activity: Vec::new(),
banner_art: Vec::new(),
commands: Vec::new(),
active_picker: None,
busy: false,
streaming_idx: None,
statusline: Vec::new(),
active_workstream: None,
quit: false,
pending_submit: None,
pending_cancel: false,
last_prompt: String::new(),
last_bash_block: None,
current_generation: 0,
}
}
pub fn push_user(&mut self, text: impl Into<String>) {
self.chat.push(ChatLine {
role: ChatRole::User,
text: text.into(),
});
self.scroll_offset = 0;
}
pub fn push_assistant(&mut self, text: impl Into<String>, is_error: bool) {
let role = if is_error {
ChatRole::Error
} else {
ChatRole::Assistant
};
let raw: String = text.into();
let trimmed = trim_surrounding_blank_lines(&raw);
let collapsed = strip_interior_blank_lines(&trimmed);
self.chat.push(ChatLine {
role,
text: collapsed,
});
self.scroll_offset = 0;
self.update_last_bash_block();
}
pub fn update_last_bash_block(&mut self) {
for entry in self.chat.iter().rev() {
if entry.role != ChatRole::Assistant {
continue;
}
if let Some(block) = crate::render::markdown::extract_last_shell_block(&entry.text) {
self.last_bash_block = Some(block);
return;
}
}
self.last_bash_block = None;
}
pub fn push_status(&mut self, text: impl Into<String>) {
self.chat.push(ChatLine {
role: ChatRole::Status,
text: text.into(),
});
self.scroll_offset = 0;
}
pub fn clear_scrollback(&mut self) {
self.chat.clear();
self.streaming_idx = None;
self.scroll_offset = 0;
}
pub fn open_picker(&mut self, request: PickerRequest) {
self.active_picker = Some(request);
}
pub fn close_picker(&mut self) {
self.active_picker = None;
}
pub fn confirm_picker_selection(&mut self, index: usize) -> Option<String> {
let request = self.active_picker.as_ref()?;
let selected = request.items.get(index)?;
let composed = crate::commands::compose_selection(request, selected);
self.active_picker = None;
Some(composed)
}
pub(crate) fn submit_line(&mut self, line: String) {
if self.busy {
return;
}
self.remember_input(&line);
self.last_prompt = line.clone();
self.push_user(line.clone());
match crate::commands::route(&line) {
crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Clear) => {
self.clear_scrollback();
}
crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Quit) => {
self.quit = true;
}
crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Help) => {
self.push_status(crate::commands::render_help(&self.commands));
}
crate::commands::Route::Forward(forwarded) => {
self.busy = true;
self.pending_submit = Some(forwarded);
}
}
}
pub fn remember_input(&mut self, line: &str) {
if line.trim().is_empty() {
return;
}
if self.history.last().map(|s| s.as_str()) == Some(line) {
return;
}
self.history.push(line.to_string());
}
pub fn set_input(&mut self, s: String) {
self.cursor_pos = s.len();
self.input_buf = s;
}
pub fn insert_char(&mut self, c: char) {
self.input_buf.insert(self.cursor_pos, c);
self.cursor_pos += c.len_utf8();
self.history_idx = None;
}
pub fn backspace(&mut self) {
if self.cursor_pos == 0 {
return;
}
let mut prev = self.cursor_pos - 1;
while prev > 0 && !self.input_buf.is_char_boundary(prev) {
prev -= 1;
}
self.input_buf.replace_range(prev..self.cursor_pos, "");
self.cursor_pos = prev;
}
pub fn cursor_left(&mut self) {
if self.cursor_pos == 0 {
return;
}
let mut prev = self.cursor_pos - 1;
while prev > 0 && !self.input_buf.is_char_boundary(prev) {
prev -= 1;
}
self.cursor_pos = prev;
}
pub fn cursor_right(&mut self) {
if self.cursor_pos >= self.input_buf.len() {
return;
}
let mut next = self.cursor_pos + 1;
while next < self.input_buf.len() && !self.input_buf.is_char_boundary(next) {
next += 1;
}
self.cursor_pos = next;
}
pub fn history_prev(&mut self) {
if self.history.is_empty() {
return;
}
let new_idx = match self.history_idx {
None => {
self.saved_input = Some(self.input_buf.clone());
self.history.len() - 1
}
Some(i) => i.saturating_sub(1),
};
self.history_idx = Some(new_idx);
let entry = self.history[new_idx].clone();
self.set_input(entry);
}
pub fn history_next(&mut self) {
let Some(i) = self.history_idx else { return };
if i + 1 >= self.history.len() {
let restore = self.saved_input.take().unwrap_or_default();
self.history_idx = None;
self.set_input(restore);
} else {
self.history_idx = Some(i + 1);
let entry = self.history[i + 1].clone();
self.set_input(entry);
}
}
pub fn take_input(&mut self) -> Option<String> {
let trimmed = self.input_buf.trim();
if trimmed.is_empty() {
return None;
}
let out = std::mem::take(&mut self.input_buf);
self.cursor_pos = 0;
self.history_idx = None;
self.saved_input = None;
Some(out)
}
pub fn scroll(&mut self, delta: isize) {
if delta < 0 {
self.scroll_offset = self.scroll_offset.saturating_add((-delta) as usize);
} else {
self.scroll_offset = self.scroll_offset.saturating_sub(delta as usize);
}
let cap = self
.last_max_scroll
.load(std::sync::atomic::Ordering::Relaxed);
if self.scroll_offset > cap {
self.scroll_offset = cap;
}
}
}
impl TuiModel for ReplApp {
fn should_quit(&self) -> bool {
self.quit
}
fn take_pending_submit(&mut self) -> Option<String> {
self.pending_submit.take()
}
fn take_pending_cancel(&mut self) -> bool {
std::mem::replace(&mut self.pending_cancel, false)
}
fn on_cancelled(&mut self) {
self.busy = false;
self.streaming_idx = None;
self.push_status("cancelled");
}
fn set_current_generation(&mut self, generation: u64) {
self.current_generation = generation;
}
}