use minutes_core::Config;
use std::io::{IsTerminal, Write};
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
const APP: &str = "minutes";
const MAX_MSG_BYTES: usize = 2048;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Working,
BlockedOnQuestion,
Done,
Error,
}
impl State {
fn wire(self) -> &'static str {
match self {
State::Working => "working",
State::BlockedOnQuestion => "blocked",
State::Done => "done",
State::Error => "error",
}
}
}
pub fn format_report(state: State, progress: Option<u8>, msg: &str) -> String {
let mut body = format!("state={}", state.wire());
if state == State::BlockedOnQuestion {
body.push_str(":kind=question");
}
if state == State::Working {
if let Some(progress) = progress {
body.push_str(&format!(":progress={}", progress.min(100)));
}
}
body.push_str(":app=");
body.push_str(APP);
let clean = clean_message(msg);
if !clean.is_empty() {
body.push_str(":msg=");
body.push_str(&base64_standard(clean.as_bytes()));
}
format!("\x1b]7501;{body}\x1b\\")
}
pub(crate) fn base64_standard(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b = [
chunk[0],
chunk.get(1).copied().unwrap_or(0),
chunk.get(2).copied().unwrap_or(0),
];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for (i, shift) in [18u32, 12, 6, 0].into_iter().enumerate() {
if i <= chunk.len() {
out.push(ALPHABET[((n >> shift) & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
fn clean_message(msg: &str) -> String {
let mut clean = String::new();
for ch in msg.chars().filter(|ch| !ch.is_control()) {
if clean.len() + ch.len_utf8() > MAX_MSG_BYTES {
break;
}
clean.push(ch);
}
clean.trim().to_string()
}
pub fn should_report(
config_enabled: bool,
stderr_is_terminal: bool,
term: Option<&str>,
windows_vt_terminal: bool,
) -> bool {
if !config_enabled || !stderr_is_terminal {
return false;
}
if term == Some("dumb") {
return false;
}
!cfg!(windows) || windows_vt_terminal
}
fn windows_vt_terminal() -> bool {
["REX_BLOCK", "WT_SESSION", "TERM_PROGRAM"]
.iter()
.any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
}
#[derive(Clone)]
pub struct ProgramStatus {
sink: Option<Arc<Mutex<Box<dyn Write + Send>>>>,
}
impl ProgramStatus {
pub fn from_config(config: &Config) -> Self {
let enabled = should_report(
config.workspace.program_status_enabled(),
std::io::stderr().is_terminal(),
std::env::var("TERM").ok().as_deref(),
windows_vt_terminal(),
);
if enabled {
Self::with_writer(Box::new(std::io::stderr()))
} else {
Self::disabled()
}
}
pub fn disabled() -> Self {
Self { sink: None }
}
pub fn with_writer(writer: Box<dyn Write + Send>) -> Self {
Self {
sink: Some(Arc::new(Mutex::new(writer))),
}
}
pub fn report(&self, state: State, progress: Option<u8>, msg: &str) {
let Some(sink) = &self.sink else {
return;
};
let report = format_report(state, progress, msg);
if let Ok(mut writer) = sink.lock() {
let _ = writer.write_all(report.as_bytes());
let _ = writer.flush();
}
}
pub fn start_elapsed(&self, label: &'static str) -> ElapsedTicker {
self.start_elapsed_every(label, Duration::from_secs(60))
}
fn start_elapsed_every(&self, label: &'static str, interval: Duration) -> ElapsedTicker {
self.report(State::Working, None, label);
if self.sink.is_none() {
return ElapsedTicker::inert();
}
let status = self.clone();
let (stop, stopped) = mpsc::channel::<()>();
let started = Instant::now();
let handle = std::thread::Builder::new()
.name("program-status".into())
.spawn(move || {
while let Err(RecvTimeoutError::Timeout) = stopped.recv_timeout(interval) {
status.report(State::Working, None, &elapsed_message(label, started));
}
})
.ok();
ElapsedTicker {
stop: Some(stop),
handle,
}
}
}
fn elapsed_message(label: &str, started: Instant) -> String {
let minutes = started.elapsed().as_secs() / 60;
if minutes == 0 {
label.to_string()
} else {
format!("{label} · {minutes} min")
}
}
pub struct ElapsedTicker {
stop: Option<Sender<()>>,
handle: Option<JoinHandle<()>>,
}
impl ElapsedTicker {
fn inert() -> Self {
Self {
stop: None,
handle: None,
}
}
pub fn stop(mut self) {
self.shutdown();
}
fn shutdown(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
impl Drop for ElapsedTicker {
fn drop(&mut self) {
self.shutdown();
}
}
pub fn stage_message(stage: minutes_core::pipeline::PipelineStage) -> &'static str {
use minutes_core::pipeline::PipelineStage;
match stage {
PipelineStage::Transcribing => "Transcribing",
PipelineStage::Diarizing => "Identifying speakers",
PipelineStage::Summarizing => "Summarizing",
PipelineStage::Saving => "Saving",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Default)]
struct Capture(Arc<Mutex<Vec<u8>>>);
impl Write for Capture {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Capture {
fn text(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
#[test]
fn report_matches_the_protocol_example_encoding() {
assert_eq!(
format_report(State::Working, None, "Installing updates"),
"\x1b]7501;state=working:app=minutes:msg=SW5zdGFsbGluZyB1cGRhdGVz\x1b\\"
);
}
#[test]
fn base64_matches_rfc_4648_vectors() {
for (input, expected) in [
("", ""),
("f", "Zg=="),
("fo", "Zm8="),
("foo", "Zm9v"),
("foob", "Zm9vYg=="),
("fooba", "Zm9vYmE="),
("foobar", "Zm9vYmFy"),
] {
assert_eq!(base64_standard(input.as_bytes()), expected, "{input:?}");
}
assert_eq!(base64_standard("·".as_bytes()), "wrc=");
}
#[test]
fn blocked_reports_carry_question_kind_and_no_progress() {
let report = format_report(State::BlockedOnQuestion, Some(40), "Waiting");
assert!(report.starts_with("\x1b]7501;state=blocked:kind=question:app=minutes:msg="));
assert!(!report.contains("progress"));
}
#[test]
fn progress_is_clamped_and_only_sent_while_working() {
assert!(format_report(State::Working, Some(250), "x").contains(":progress=100:"));
assert!(!format_report(State::Done, Some(50), "x").contains("progress"));
}
#[test]
fn values_stay_inside_the_protocol_character_set() {
let report = format_report(State::Error, None, "Failed: a;b:c");
let body = report
.strip_prefix("\x1b]7501;")
.and_then(|rest| rest.strip_suffix("\x1b\\"))
.unwrap();
for pair in body.split(':') {
let (key, value) = pair.split_once('=').unwrap();
assert!(key.chars().all(|c| c.is_ascii_lowercase()), "{key}");
assert!(
value
.chars()
.all(|c| c.is_ascii_alphanumeric() || "_.,+/=-".contains(c)),
"{value}"
);
}
}
#[test]
fn control_characters_are_removed_and_long_messages_are_cut() {
assert_eq!(clean_message("a\nb\tc\u{1b}d"), "abcd");
let long = "é".repeat(MAX_MSG_BYTES);
let cut = clean_message(&long);
assert!(cut.len() <= MAX_MSG_BYTES);
assert!(cut.chars().all(|c| c == 'é'));
assert_eq!(
format_report(State::Done, None, "\n"),
"\x1b]7501;state=done:app=minutes\x1b\\"
);
}
#[test]
fn reporting_requires_config_and_a_terminal() {
assert!(!should_report(false, true, None, true));
assert!(!should_report(true, false, None, true));
assert!(!should_report(true, true, Some("dumb"), true));
assert!(should_report(true, true, Some("xterm-256color"), true));
assert_eq!(
should_report(true, true, Some("xterm-256color"), false),
!cfg!(windows)
);
}
#[test]
fn disabled_reporter_writes_nothing_and_its_ticker_is_inert() {
let status = ProgramStatus::disabled();
status.report(State::Done, None, "Saved");
let ticker = status.start_elapsed("Recording");
assert!(ticker.handle.is_none());
ticker.stop();
}
#[test]
fn ticker_reports_immediately_and_stops_before_the_final_report() {
let capture = Capture::default();
let status = ProgramStatus::with_writer(Box::new(capture.clone()));
let ticker = status.start_elapsed_every("Recording", Duration::from_millis(5));
std::thread::sleep(Duration::from_millis(30));
ticker.stop();
status.report(State::Done, None, "Saved");
let text = capture.text();
let reports: Vec<&str> = text.split("\x1b\\").filter(|r| !r.is_empty()).collect();
assert!(reports.len() >= 2, "{reports:?}");
assert!(reports[0].contains("state=working"));
assert!(reports.last().unwrap().contains("state=done"));
assert!(reports[..reports.len() - 1]
.iter()
.all(|r| r.contains("state=working")));
}
#[test]
fn elapsed_message_shows_minutes_after_the_first() {
assert_eq!(elapsed_message("Recording", Instant::now()), "Recording");
if let Some(earlier) = Instant::now().checked_sub(Duration::from_secs(185)) {
assert_eq!(elapsed_message("Recording", earlier), "Recording · 3 min");
}
}
}