use std::{
io::{Stderr, Stdout},
sync::{Arc, Mutex},
};
use haest::{
core::remedy::Limit,
runtime::{HubUi, Ui},
session::{Body, Frame, Hub, Subscription},
tools::SubagentEvent,
wire::{Envelope, Level, Outbound, Path, WIRE_V, now_ms},
};
use tokio::{
sync::{oneshot, watch},
task::JoinHandle,
};
use crate::{agents::AgentLog, render::Renderer};
pub(crate) type Term = Renderer<Stdout, Stderr>;
pub(crate) type Runtime = haest::runtime::Runtime<Arc<TermUi>>;
pub(crate) struct TermUi {
pub term: Arc<Mutex<Term>>,
pub stdin: tokio::sync::Mutex<()>,
lines: HubUi,
log: Mutex<AgentLog>,
slash: bool,
shown: watch::Sender<bool>,
}
impl TermUi {
#[cfg(test)]
pub(crate) fn new(json: bool) -> Self {
let sid = uuid::Uuid::new_v4().to_string();
Self::with_hub(json, Hub::new(sid))
}
pub(crate) fn with_hub(json: bool, hub: Hub) -> Self {
Self {
term: Arc::new(Mutex::new(Renderer::terminal(json))),
stdin: tokio::sync::Mutex::new(()),
lines: HubUi::new(hub),
log: Mutex::default(),
slash: true,
shown: watch::Sender::new(false),
}
}
pub(crate) fn over_stdio(mut self) -> Self {
self.slash = false;
self
}
pub(crate) fn prompting(&self) -> bool {
self.term.lock().unwrap().prompting()
}
pub(crate) fn refused(&self, why: &str) {
self.warn(why);
self.term.lock().unwrap().refused(why);
}
pub(crate) fn ask(&self, question: &str) -> Answering<'_> {
let (tell, drawn) = oneshot::channel();
let ask = Outbound::Ask {
text: question.to_string(),
};
let mut term = self.term.lock().unwrap();
let hub = self.lines.hub();
let seq = hub.publish(Path::main(), ask.clone());
let frame = Envelope {
v: WIRE_V,
sid: hub.sid().to_string(),
seq,
ts: now_ms(),
path: Path::main(),
body: Body::Wire(ask),
};
term.answering(frame, tell);
drop(term);
Answering {
ui: self,
drawn,
enter: false,
}
}
pub(crate) async fn last_notice(&self, level: Level, text: &str) -> Option<Arc<Frame>> {
let hub = self.lines.hub();
let seq = hub.notice(level, text);
let mut kept = hub.subscribe(seq.saturating_sub(1));
while let Some(frame) = kept.recv().await {
if frame.seq >= seq {
return (frame.seq == seq).then_some(frame);
}
}
None
}
pub(crate) async fn shown(&self) {
let mut shown = self.shown.subscribe();
let _ = shown.wait_for(|shown| *shown).await;
}
pub(crate) async fn tell_after_the_end(&self, level: Level, text: &str) {
self.shown().await;
let frame = self.last_notice(level, text).await;
let mut term = self.term.lock().unwrap();
match frame {
Some(frame) => term.frame(&frame),
None => term.notice(level, text),
}
}
}
struct ShownToTheEnd(Arc<TermUi>);
impl Drop for ShownToTheEnd {
fn drop(&mut self) {
self.0.shown.send_replace(true);
}
}
pub(crate) struct Answering<'a> {
ui: &'a TermUi,
drawn: oneshot::Receiver<()>,
enter: bool,
}
impl Answering<'_> {
pub(crate) async fn drawn(&mut self) -> bool {
(&mut self.drawn).await.is_ok()
}
pub(crate) fn answered(mut self, line: Option<&str>) {
self.enter = line.is_some_and(|l| l.ends_with('\n'));
}
}
impl Drop for Answering<'_> {
fn drop(&mut self) {
if let Ok(mut term) = self.ui.term.lock() {
term.answered(self.enter);
}
}
}
pub(crate) fn show(ui: &Arc<TermUi>, mut sub: Subscription) -> JoinHandle<()> {
let done = ShownToTheEnd(ui.clone());
tokio::spawn(async move {
let term = &done.0.term;
while let Some(frame) = sub.recv().await {
term.lock().unwrap().frame(&frame);
}
if let Ok(mut term) = term.lock() {
term.ended();
}
})
}
impl Ui for TermUi {
fn info(&self, text: &str) {
self.lines.info(text);
}
fn warn(&self, text: &str) {
self.lines.warn(text);
}
fn error(&self, text: &str) {
self.lines.error(text);
}
fn remedy(&self, limit: Limit) -> Option<String> {
crate::remedy::remedy(limit, self.slash)
}
fn arrival(&self, headline: &str) {
if self.prompting() {
self.info(&format!("{headline}\nhaest takes it when you press Enter."));
} else {
self.info(headline);
}
}
fn subagent(&self, id: &str, event: &SubagentEvent) {
self.lines.subagent(id, event);
}
fn subagents_running(&self, ids: &[String]) {
if let Some(text) = self.log.lock().unwrap().activity(ids.len()) {
self.lines.info(&text);
}
}
}