use std::{
collections::{hash_map::Entry, HashMap},
io::{self, Write},
};
use rho_protocol::{
CompactionId, CompactionStatus, ContentBlock, SessionEvent, ToolCallId, ToolCallUpdate,
ToolStatus,
};
use crate::control_chars::{escape_controls, LineBreaks};
pub(super) struct TextView<O = io::Stdout, E = io::Stderr> {
out: O,
err: E,
calls: HashMap<ToolCallId, ShownCall>,
compaction: Option<CompactionId>,
line_ended: bool,
}
impl TextView {
pub(super) fn terminal() -> Self {
Self::new(io::stdout(), io::stderr())
}
}
impl<O: Write, E: Write> TextView<O, E> {
pub(super) fn new(out: O, err: E) -> Self {
Self {
out,
err,
calls: HashMap::new(),
compaction: None,
line_ended: true,
}
}
pub(super) fn show(&mut self, event: &SessionEvent) -> io::Result<()> {
match event {
SessionEvent::UserMessage { content, .. } => {
let text = content
.iter()
.map(|block| match block {
ContentBlock::Text { text } => text.as_str(),
ContentBlock::Image { .. } => "[image]",
_ => "[content]",
})
.collect::<Vec<_>>()
.join("\n");
self.block("ed(&text))?;
}
SessionEvent::AgentMessageChunk { text, .. } => self.write(text)?,
SessionEvent::ToolCall(update) => self.tool_call(update)?,
SessionEvent::Card { title, plain, .. } => {
self.block(&format!("{title}\n{}\n", plain.trim_end_matches('\n')))?;
}
SessionEvent::Compaction { id, status } => self.compaction(id, status)?,
SessionEvent::Notice { text } => {
writeln!(self.err, "rho: {}", escape_controls(text, LineBreaks::Keep))?
}
SessionEvent::ResponseDiscarded => {
writeln!(self.err, "rho: provider response discarded; retrying")?
}
SessionEvent::TurnEnded { .. } => self.end_line()?,
SessionEvent::ThoughtChunk { .. }
| SessionEvent::Plan { .. }
| SessionEvent::Usage { .. }
| SessionEvent::TitleChanged { .. }
| SessionEvent::State { .. }
| SessionEvent::InputRequested { .. }
| SessionEvent::InputResolved { .. }
| SessionEvent::InputHeld { .. }
| SessionEvent::OptionsChanged { .. }
| SessionEvent::ProviderRequest
| SessionEvent::ProviderRetry { .. }
| SessionEvent::SteeringDelivered { .. }
| SessionEvent::Background { .. }
| SessionEvent::Activity { .. }
| SessionEvent::Agent { .. }
| SessionEvent::StartedSessionDefaults(_)
| SessionEvent::PullRequests { .. }
| SessionEvent::MarkChanged { .. } => {}
_ => {}
}
self.out.flush()
}
fn tool_call(&mut self, update: &ToolCallUpdate) -> io::Result<()> {
if update.status == Some(ToolStatus::Pending) {
return Ok(());
}
let mut lines = String::new();
let call = match (self.calls.entry(update.id.clone()), &update.title) {
(Entry::Occupied(entry), title) => {
let call = entry.into_mut();
if let Some(title) = title {
call.title.clone_from(title);
}
call
}
(Entry::Vacant(entry), Some(title)) => {
lines.push_str(&format!("• {title}\n"));
entry.insert(ShownCall {
title: title.clone(),
ended: false,
})
}
(Entry::Vacant(_), None) => return Ok(()),
};
let ended = match update.status {
Some(ToolStatus::Failed) => Some("failed"),
Some(ToolStatus::Cancelled) => Some("cancelled"),
_ => None,
};
if let (Some(ended), false) = (ended, call.ended) {
call.ended = true;
lines.push_str(&format!("• {} {ended}\n", call.title));
}
if lines.is_empty() {
return Ok(());
}
self.block(&lines)
}
fn compaction(&mut self, id: &CompactionId, status: &CompactionStatus) -> io::Result<()> {
let started = self.compaction.take().is_some_and(|shown| shown == *id);
match status {
CompactionStatus::Started { .. } => {
self.compaction = Some(id.clone());
self.block("• compact context\n")
}
CompactionStatus::Failed { .. } => self.block("• compact context failed\n"),
CompactionStatus::Completed { .. } if !started => self.block("• compact context\n"),
CompactionStatus::Completed { .. } | CompactionStatus::Cancelled => Ok(()),
_ => Ok(()),
}
}
fn block(&mut self, text: &str) -> io::Result<()> {
self.end_line()?;
self.write(text)
}
pub(super) fn finish(&mut self) -> io::Result<()> {
self.end_line()?;
self.out.flush()
}
pub(super) fn restart(&mut self) -> io::Result<()> {
self.calls.clear();
self.compaction = None;
self.end_line()
}
fn end_line(&mut self) -> io::Result<()> {
if self.line_ended {
return Ok(());
}
self.write("\n")
}
fn write(&mut self, text: &str) -> io::Result<()> {
if text.is_empty() {
return Ok(());
}
self.out
.write_all(escape_controls(text, LineBreaks::Keep).as_bytes())?;
self.line_ended = text.ends_with('\n');
Ok(())
}
}
struct ShownCall {
title: String,
ended: bool,
}
fn quoted(text: &str) -> String {
text.lines().map(|line| format!("> {line}\n")).collect()
}
#[cfg(test)]
#[path = "text_tests.rs"]
mod tests;