mod reduce;
pub use reduce::apply;
use std::collections::HashMap;
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, PendingPermission, PermissionAnswer, PermissionResponse, PickerRequest,
StatuslineSegment,
};
use crate::run::TuiModel;
use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
pub(crate) const CANCELLING_STATUS: &str = "cancelling…";
pub(crate) const CANCELLED_STATUS: &str = "cancelled";
#[derive(Debug, Clone)]
pub struct ChatLine {
pub role: ChatRole,
pub text: String,
pub tool: Option<ToolCard>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolCard {
pub id: String,
pub tool_name: String,
pub args: serde_json::Value,
pub result: Option<String>,
pub failed: bool,
pub collapsed: bool,
}
impl ToolCard {
pub fn is_error(&self) -> bool {
self.failed && self.result.is_some()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatRole {
User,
Assistant,
Error,
Status,
Delegation,
Delegated,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Delegation {
pub agent_id: String,
pub agent: String,
}
#[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 splash: Vec<String>,
pub recent_activity: Vec<String>,
pub banner_art: Vec<Line<'static>>,
pub commands: Vec<CommandDescriptor>,
pub active_picker: Option<PickerRequest>,
pub pending_permission: Option<PendingPermission>,
pub pending_permission_response: Option<PermissionResponse>,
pub permission_error: Option<String>,
pub busy: bool,
pub cancelling: bool,
pub streaming_idx: Option<usize>,
pub delegations: Vec<Delegation>,
pub agent_streams: HashMap<(String, String), usize>,
pub tool_cards: HashMap<String, 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(),
splash: Vec::new(),
recent_activity: Vec::new(),
banner_art: Vec::new(),
commands: Vec::new(),
active_picker: None,
pending_permission: None,
pending_permission_response: None,
permission_error: None,
busy: false,
cancelling: false,
streaming_idx: None,
delegations: Vec::new(),
agent_streams: HashMap::new(),
tool_cards: HashMap::new(),
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(),
tool: None,
});
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,
tool: None,
});
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(),
tool: None,
});
self.scroll_offset = 0;
}
pub fn clear_scrollback(&mut self) {
self.chat.clear();
self.streaming_idx = None;
self.agent_streams.clear();
self.delegations.clear();
self.tool_cards.clear();
self.scroll_offset = 0;
}
pub fn active_agent(&self) -> Option<&str> {
self.delegations.last().map(|d| d.agent.as_str())
}
pub fn toggle_last_tool_card(&mut self) -> bool {
for entry in self.chat.iter_mut().rev() {
if let Some(card) = entry.tool.as_mut() {
card.collapsed = !card.collapsed;
return true;
}
}
false
}
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.accepts_submit() {
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 accepts_submit(&self) -> bool {
!self.busy && !self.cancelling && self.pending_permission.is_none()
}
pub fn answer_permission(&mut self, answer: PermissionAnswer) {
let Some(pending) = self.pending_permission.take() else {
return;
};
self.permission_error = None;
self.pending_permission_response = Some(PermissionResponse { pending, answer });
}
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();
}
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(0) => return,
Some(i) => i - 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 take_pending_permission_response(&mut self) -> Option<PermissionResponse> {
self.pending_permission_response.take()
}
fn on_cancel_requested(&mut self) {
self.cancelling = true;
self.streaming_idx = None;
self.push_status(CANCELLING_STATUS);
}
fn set_current_generation(&mut self, generation: u64) {
self.current_generation = generation;
}
}