From 7175543e00caa9ce35487fa7f8b1b479c1ba00a2 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 02:54:21 +0100 Subject: M0: streaming provider, SSE decoder, mock provider, i686 build gate --- src/ui.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/ui.rs (limited to 'src/ui.rs') diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..13440b2 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,75 @@ +use std::io::{IsTerminal, Write}; +use std::time::Duration; + +use crate::provider::{Outcome, Sink}; + +pub fn stdout_is_tty() -> bool { + std::io::stdout().is_terminal() +} + +/// Streams to stdout. Colour is used only when stdout is a terminal, so piping +/// the output somewhere gives clean text. +pub struct Renderer { + color: bool, + dimmed: bool, + wrote_text: bool, +} + +impl Renderer { + pub fn new(color: bool) -> Self { + Self { + color, + dimmed: false, + wrote_text: false, + } + } + + fn undim(&mut self) { + if self.dimmed { + print!("\x1b[0m"); + self.dimmed = false; + } + } +} + +impl Sink for Renderer { + fn text(&mut self, s: &str) { + self.undim(); + print!("{s}"); + let _ = std::io::stdout().flush(); + self.wrote_text = true; + } + + fn reasoning(&mut self, s: &str) { + if !self.color { + return; + } + if !self.dimmed { + print!("\x1b[2m"); + self.dimmed = true; + } + print!("{s}"); + let _ = std::io::stdout().flush(); + } + + fn done(&mut self, outcome: &Outcome, elapsed: Duration) { + self.undim(); + if self.wrote_text { + println!(); + } + let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; + if let Some(usage) = &outcome.usage { + let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); + let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); + if let (Some(i), Some(o)) = (input, output) { + parts.push(format!("{i} in · {o} out")); + } + } + let line = format!("─ {}", parts.join(" · ")); + if self.color { + println!("\x1b[2m{line}\x1b[0m"); + } else { + println!("{line}"); + } + } +} -- cgit v1.2.3