minutes-cli 0.35.2

CLI for minutes — record, transcribe, and search conversation memory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Program status reports for terminal workspaces (OSC 7501).
//!
//! The Program Status Protocol lets a program tell its terminal whether it is
//! working, blocked on the user, done or failed. Terminals that implement it,
//! such as Rex, show the record in tab spinners and activity lists, including
//! on other devices attached to the same session. Terminals that do not
//! implement it ignore the sequence. See RFC 0008, phase 1.
//!
//! Two rules keep this safe:
//!
//! - Reports go to stderr, and only when stderr is a terminal. Captured stdout
//!   (the JSON results `record` and `process` print) never sees an escape
//!   sequence, and a detached worker with null stdio never reports.
//! - Messages are fixed, generic strings. A status record can be shown on
//!   every client attached to the terminal, so it never carries a meeting
//!   title, attendee name, path or transcript text.

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};

/// Stable program identifier sent as the `app` key.
const APP: &str = "minutes";

/// The protocol caps a decoded `msg` at 2048 bytes.
const MAX_MSG_BYTES: usize = 2048;

/// What a report says the program is doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// Running. May carry a progress percentage.
    Working,
    /// Waiting for the user to answer a question in this terminal.
    BlockedOnQuestion,
    /// Finished; the result is ready to look at.
    Done,
    /// Failed and stopped.
    Error,
}

impl State {
    fn wire(self) -> &'static str {
        match self {
            State::Working => "working",
            State::BlockedOnQuestion => "blocked",
            State::Done => "done",
            State::Error => "error",
        }
    }
}

/// Builds one OSC 7501 report for the root record.
///
/// `progress` is sent only with [`State::Working`] and is clamped to 0–100.
/// Control characters are removed from `msg` and it is cut to the protocol's
/// decoded-size limit on a character boundary, so the terminal never discards
/// the report.
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\\")
}

/// Standard base64 with padding (RFC 4648 section 4), the encoding the
/// protocol uses for free-text values. Kept local so the CLI package gains no
/// dependency.
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()
}

/// Whether reports should be written, from configuration and the environment.
///
/// Windows consoles only understand escape sequences when virtual terminal
/// processing is on, so there reports are limited to terminals that announce
/// themselves (Rex, Windows Terminal, or one that sets `TERM_PROGRAM`).
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()))
}

/// Writes program status reports for the current command.
///
/// A disabled reporter accepts every call and writes nothing, so call sites
/// never branch on whether reporting is on.
#[derive(Clone)]
pub struct ProgramStatus {
    sink: Option<Arc<Mutex<Box<dyn Write + Send>>>>,
}

impl ProgramStatus {
    /// A reporter for this process: writes to stderr when configuration and
    /// the terminal allow it, otherwise does nothing.
    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()
        }
    }

    /// A reporter that writes nothing.
    pub fn disabled() -> Self {
        Self { sink: None }
    }

    /// A reporter that writes every report to `writer`.
    pub fn with_writer(writer: Box<dyn Write + Send>) -> Self {
        Self {
            sink: Some(Arc::new(Mutex::new(writer))),
        }
    }

    /// Sends one report. Write failures are ignored: status is advisory and
    /// must never fail the command that reports it.
    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();
        }
    }

    /// Reports `working` with `label` now, then every minute with the elapsed
    /// time ("Recording · 3 min") until the returned ticker is stopped or
    /// dropped.
    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 || {
                // A stop message or a dropped sender ends the loop.
                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")
    }
}

/// Keeps a `working` record's elapsed time current. Stopping it (or dropping
/// it) joins the thread, so a later report can never be overwritten by a late
/// tick.
pub struct ElapsedTicker {
    stop: Option<Sender<()>>,
    handle: Option<JoinHandle<()>>,
}

impl ElapsedTicker {
    fn inert() -> Self {
        Self {
            stop: None,
            handle: None,
        }
    }

    /// Stops the ticker and waits for its thread to finish.
    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();
    }
}

/// The generic message for a pipeline stage.
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() {
        // The spec's own example encodes "Installing updates" this way.
        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:?}");
        }
        // Multi-byte UTF-8 (the middle dot in "Recording · 3 min").
        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 == 'é'));
        // An empty message drops the key instead of sending an empty value.
        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");
        }
    }
}