minutes-cli 0.36.0

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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! Live transcript streaming view (`minutes transcript --follow`).
//!
//! Tails the active live transcript session for humans watching in a terminal
//! (such as a Rex pane beside an AI agent). Reads the lightweight status
//! sidecar on each tick and only parses the JSONL file when new lines arrive,
//! a session rolls over, or a session ends.

use anyhow::Result;
#[cfg(feature = "whisper")]
use minutes_core::live_transcript::{
    LiveTranscriptDisabled, SessionStatus, TranscriptLine, TranscriptSource,
};
#[cfg(feature = "whisper")]
use minutes_core::markdown::RemoteAudioStatus;
#[cfg(feature = "whisper")]
use std::io::{self, IsTerminal, Write};
#[cfg(feature = "whisper")]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "whisper")]
use std::time::Duration;

/// Output format for [`follow_transcript`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FollowFormat {
    /// Human-readable timestamped lines on stdout, lifecycle notices on stderr.
    Text,
    /// Streaming NDJSON (one serialized [`TranscriptLine`] per line) on stdout.
    Json,
}

/// Initial history slice printed when attaching to an already-active session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InitialWindow {
    /// Print all lines from the active session, then follow.
    All,
    /// Print lines strictly after the given 1-based line number, then follow.
    SinceLine(usize),
    /// Print lines from the last `duration_ms` milliseconds, then follow.
    SinceDurationMs(u64),
}

/// Configuration for [`follow_transcript`].
#[cfg(feature = "whisper")]
#[derive(Debug, Clone, Copy)]
pub struct FollowOptions {
    pub format: FollowFormat,
    pub initial: InitialWindow,
    pub poll_interval: Duration,
    pub use_color: bool,
}

#[cfg(feature = "whisper")]
impl FollowOptions {
    /// Build options for interactive CLI execution.
    pub fn for_cli(format: FollowFormat, initial: InitialWindow) -> Self {
        let use_color = should_use_color(
            io::stdout().is_terminal() && io::stderr().is_terminal(),
            std::env::var_os("NO_COLOR").is_some(),
            std::env::var("TERM").ok().as_deref(),
        );
        Self {
            format,
            initial,
            poll_interval: Duration::from_millis(250),
            use_color,
        }
    }
}

/// Resolve the effective `--format` value for `minutes transcript`.
///
/// Defaults to `"text"` when `--follow` is set (human terminal viewing) and
/// `"json"` otherwise (preserving agent and script contracts).
pub fn effective_transcript_format(format: Option<&str>, follow: bool) -> &str {
    format.unwrap_or(if follow { "text" } else { "json" })
}

/// Whether subtle ANSI styling should be emitted in text mode.
pub fn should_use_color(is_terminal: bool, no_color: bool, term: Option<&str>) -> bool {
    is_terminal && !no_color && term != Some("dumb")
}

/// Parse a `--since` argument into an [`InitialWindow`].
pub fn parse_since_window(since: Option<&str>) -> Result<InitialWindow> {
    match since {
        None => Ok(InitialWindow::All),
        Some(s) if s.ends_with('m') || s.ends_with('s') => {
            let (num_str, unit) = s.split_at(s.len() - 1);
            let num: u64 = num_str
                .parse()
                .map_err(|_| anyhow::anyhow!("invalid duration: {}", s))?;
            let ms = match unit {
                "m" => num
                    .checked_mul(60_000)
                    .ok_or_else(|| anyhow::anyhow!("duration too large: {}", s))?,
                "s" => num
                    .checked_mul(1000)
                    .ok_or_else(|| anyhow::anyhow!("duration too large: {}", s))?,
                _ => anyhow::bail!("invalid duration unit: {}", unit),
            };
            Ok(InitialWindow::SinceDurationMs(ms))
        }
        Some(s) => {
            let n: usize = s.parse().map_err(|_| {
                anyhow::anyhow!(
                    "invalid --since value: '{}'. Use a line number (42) or duration (5m, 30s)",
                    s
                )
            })?;
            Ok(InitialWindow::SinceLine(n))
        }
    }
}

/// Data source backing [`follow_transcript`]. Abstracted for deterministic tests.
#[cfg(feature = "whisper")]
pub trait FollowSource {
    /// Current session status snapshot.
    fn status(&self) -> SessionStatus;
    /// Read finalized transcript lines strictly after `since_line`.
    fn read_since_line(&self, since_line: usize) -> Result<Vec<TranscriptLine>>;
    /// Read finalized transcript lines from the last `duration_ms` milliseconds.
    fn read_since_duration(&self, duration_ms: u64) -> Result<Vec<TranscriptLine>>;
}

/// Production [`FollowSource`] backed by `minutes_core::live_transcript`.
#[cfg(feature = "whisper")]
pub struct LiveTranscriptSource;

#[cfg(feature = "whisper")]
impl FollowSource for LiveTranscriptSource {
    fn status(&self) -> SessionStatus {
        minutes_core::live_transcript::session_status()
    }

    fn read_since_line(&self, since_line: usize) -> Result<Vec<TranscriptLine>> {
        Ok(minutes_core::live_transcript::read_since_line(since_line)?)
    }

    fn read_since_duration(&self, duration_ms: u64) -> Result<Vec<TranscriptLine>> {
        Ok(minutes_core::live_transcript::read_since_duration(
            duration_ms,
        )?)
    }
}

#[cfg(feature = "whisper")]
#[derive(Debug, Clone, PartialEq, Eq)]
struct SessionIdentity {
    session_id: Option<String>,
    pid: Option<u32>,
}

#[cfg(feature = "whisper")]
impl SessionIdentity {
    fn from_status(status: &SessionStatus) -> Self {
        Self {
            session_id: status.session_id.clone(),
            pid: status.pid,
        }
    }

    fn changed_from(&self, other: &Self) -> bool {
        if let (Some(a), Some(b)) = (&self.session_id, &other.session_id) {
            if a != b {
                return true;
            }
        }
        if let (Some(a), Some(b)) = (self.pid, other.pid) {
            if a != b {
                return true;
            }
        }
        false
    }
}

/// Whether a Unicode scalar is a directional control character that can
/// visually reorder text in a terminal (trojan-source / bidi spoofing).
fn is_bidi_control(ch: char) -> bool {
    matches!(
        ch,
        '\u{061C}'
            | '\u{200E}'
            | '\u{200F}'
            | '\u{202A}'..='\u{202E}'
            | '\u{2066}'..='\u{2069}'
    )
}

/// Strip terminal control and bidi-override characters from untrusted
/// transcript/speaker text before printing in text mode so escape sequences
/// or directional overrides cannot control or spoof the pane.
pub fn sanitize_terminal_text(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '\n' | '\r' | '\t' => out.push(' '),
            c if c.is_control() || is_bidi_control(c) => {}
            c => out.push(c),
        }
    }
    out.trim().to_string()
}

/// Format one [`TranscriptLine`] for terminal display in text mode.
#[cfg(feature = "whisper")]
pub fn format_text_line(line: &TranscriptLine, use_color: bool) -> String {
    let ts = line.ts.format("%H:%M:%S");
    let text = sanitize_terminal_text(&line.text);
    let speaker = line
        .speaker
        .as_deref()
        .map(sanitize_terminal_text)
        .filter(|s| !s.is_empty());

    match (speaker, use_color) {
        (Some(speaker), true) => format!("\x1b[2m{ts}\x1b[0m  \x1b[36m{speaker}\x1b[0m  {text}"),
        (Some(speaker), false) => format!("[{ts}] [{speaker}] {text}"),
        (None, true) => format!("\x1b[2m{ts}\x1b[0m  {text}"),
        (None, false) => format!("[{ts}] {text}"),
    }
}

#[cfg(feature = "whisper")]
fn format_notice(msg: &str, use_color: bool) -> String {
    if use_color {
        format!("\x1b[2m{msg}\x1b[0m")
    } else {
        msg.to_string()
    }
}

#[cfg(feature = "whisper")]
fn format_warning(msg: &str, use_color: bool) -> String {
    if use_color {
        format!("\x1b[33m{msg}\x1b[0m")
    } else {
        msg.to_string()
    }
}

#[cfg(feature = "whisper")]
fn source_tag(source: Option<&TranscriptSource>) -> &'static str {
    match source {
        Some(TranscriptSource::RecordingSidecar) => "recording sidecar",
        Some(TranscriptSource::Standalone) => "live session",
        None => "live session",
    }
}

#[cfg(feature = "whisper")]
fn write_line_checked(out: &mut impl Write, line: &str) -> io::Result<bool> {
    match writeln!(out, "{line}") {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(false),
        Err(e) => Err(e),
    }
}

#[cfg(feature = "whisper")]
fn flush_checked(out: &mut impl Write) -> io::Result<bool> {
    match out.flush() {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(false),
        Err(e) => Err(e),
    }
}

#[cfg(feature = "whisper")]
fn emit_lines(
    lines: &[TranscriptLine],
    format: FollowFormat,
    use_color: bool,
    out: &mut impl Write,
) -> Result<(usize, bool)> {
    let mut max_line = 0usize;
    for line in lines {
        let rendered = match format {
            FollowFormat::Text => format_text_line(line, use_color),
            FollowFormat::Json => serde_json::to_string(line)?,
        };
        if !write_line_checked(out, &rendered)? {
            return Ok((max_line, false));
        }
        max_line = max_line.max(line.line);
    }
    if !lines.is_empty() && !flush_checked(out)? {
        return Ok((max_line, false));
    }
    Ok((max_line, true))
}

#[cfg(feature = "whisper")]
fn emit_notice(
    options: FollowOptions,
    err: &mut impl Write,
    msg: &str,
    is_warning: bool,
) -> io::Result<()> {
    if options.format != FollowFormat::Text {
        return Ok(());
    }
    let formatted = if is_warning {
        format_warning(msg, options.use_color)
    } else {
        format_notice(msg, options.use_color)
    };
    let _ = write_line_checked(err, &formatted)?;
    let _ = flush_checked(err)?;
    Ok(())
}

/// Stateful follower driven one tick at a time (or in a loop via [`follow_transcript`]).
#[cfg(feature = "whisper")]
struct FollowSessionState {
    options: FollowOptions,
    initialized: bool,
    was_active: bool,
    identity: Option<SessionIdentity>,
    cursor: usize,
    last_seen_line_count: usize,
    last_remote_audio: Option<RemoteAudioStatus>,
    last_diagnostic: Option<String>,
    disabled_reported: bool,
}

#[cfg(feature = "whisper")]
impl FollowSessionState {
    fn new(options: FollowOptions) -> Self {
        Self {
            options,
            initialized: false,
            was_active: false,
            identity: None,
            cursor: 0,
            last_seen_line_count: 0,
            last_remote_audio: None,
            last_diagnostic: None,
            disabled_reported: false,
        }
    }

    /// Process one status poll. Returns `Ok(false)` when following should stop
    /// cleanly (broken pipe or intentionally disabled recording sidecar).
    fn step(
        &mut self,
        source: &impl FollowSource,
        out: &mut impl Write,
        err: &mut impl Write,
    ) -> Result<bool> {
        let status = source.status();

        // If a recording is active with live_transcript.recording_sidecar = false,
        // tell the user right away instead of sitting blank.
        if let Some(LiveTranscriptDisabled::RecordingSidecarConfig) = status.disabled {
            if !self.disabled_reported {
                self.disabled_reported = true;
                emit_notice(
                    self.options,
                    err,
                    "Live transcript is off for this recording (live_transcript.recording_sidecar = false); the transcript will be written after stop.",
                    true,
                )?;
            }
            return Ok(false);
        }

        if !self.initialized {
            self.initialized = true;
            if status.active {
                self.was_active = true;
                self.identity = Some(SessionIdentity::from_status(&status));
                self.last_seen_line_count = status.line_count;
                emit_notice(
                    self.options,
                    err,
                    &format!(
                        "Following live transcript ({}) — Ctrl-C to stop",
                        source_tag(status.source.as_ref())
                    ),
                    false,
                )?;
                self.maybe_report_warnings(&status, err)?;

                let initial_lines = match self.options.initial {
                    InitialWindow::All => source.read_since_line(0)?,
                    InitialWindow::SinceLine(n) => source.read_since_line(n)?,
                    InitialWindow::SinceDurationMs(ms) => source.read_since_duration(ms)?,
                };
                let (max_emitted, keep_going) = emit_lines(
                    &initial_lines,
                    self.options.format,
                    self.options.use_color,
                    out,
                )?;
                if !keep_going {
                    return Ok(false);
                }
                self.cursor = match self.options.initial {
                    InitialWindow::All => max_emitted.max(status.line_count),
                    InitialWindow::SinceLine(n) => max_emitted.max(n).max(status.line_count),
                    InitialWindow::SinceDurationMs(_) => max_emitted.max(status.line_count),
                };
            } else {
                self.was_active = false;
                emit_notice(
                    self.options,
                    err,
                    "Waiting for live transcript... (Ctrl-C to stop)",
                    false,
                )?;
            }
            return Ok(true);
        }

        // Subsequent ticks.
        if status.active {
            let new_identity = SessionIdentity::from_status(&status);
            if !self.was_active {
                // Transition: inactive -> active.
                self.was_active = true;
                self.identity = Some(new_identity);
                self.cursor = 0;
                self.last_seen_line_count = 0;
                self.last_remote_audio = None;
                self.last_diagnostic = None;
                emit_notice(
                    self.options,
                    err,
                    &format!(
                        "Connected · following {} (Ctrl-C to stop)",
                        source_tag(status.source.as_ref())
                    ),
                    false,
                )?;
            } else {
                let identity_changed = self
                    .identity
                    .as_ref()
                    .is_some_and(|prev| prev.changed_from(&new_identity));
                let truncated = status.line_count < self.last_seen_line_count;
                if identity_changed || truncated {
                    self.identity = Some(new_identity);
                    self.cursor = 0;
                    self.last_seen_line_count = 0;
                    self.last_remote_audio = None;
                    self.last_diagnostic = None;
                    emit_notice(
                        self.options,
                        err,
                        "--- New live transcript session ---",
                        false,
                    )?;
                }
            }

            self.maybe_report_warnings(&status, err)?;

            if status.line_count > self.cursor {
                let lines = source.read_since_line(self.cursor)?;
                let (max_emitted, keep_going) =
                    emit_lines(&lines, self.options.format, self.options.use_color, out)?;
                if !keep_going {
                    return Ok(false);
                }
                self.cursor = max_emitted.max(status.line_count);
            }
            self.last_seen_line_count = status.line_count;
        } else if self.was_active {
            // Transition: active -> inactive. Drain any final flushed lines first.
            let lines = source.read_since_line(self.cursor)?;
            let (max_emitted, keep_going) =
                emit_lines(&lines, self.options.format, self.options.use_color, out)?;
            if !keep_going {
                return Ok(false);
            }
            let final_count = max_emitted.max(status.line_count).max(self.cursor);
            self.was_active = false;
            self.identity = None;
            self.cursor = 0;
            self.last_seen_line_count = 0;
            self.last_remote_audio = None;
            self.last_diagnostic = None;
            emit_notice(
                self.options,
                err,
                &format!(
                    "Live transcript ended ({final_count} line{}). Waiting for next session... (Ctrl-C to stop)",
                    if final_count == 1 { "" } else { "s" }
                ),
                false,
            )?;
        }

        Ok(true)
    }

    fn maybe_report_warnings(
        &mut self,
        status: &SessionStatus,
        err: &mut impl Write,
    ) -> Result<()> {
        if status.remote_audio != self.last_remote_audio {
            self.last_remote_audio = status.remote_audio;
            if let Some(remote_audio) = status.remote_audio {
                let message = match remote_audio {
                    RemoteAudioStatus::Missing => {
                        "[minutes] Remote call audio is missing — live lines are from your microphone only."
                    }
                    RemoteAudioStatus::Partial => {
                        "[minutes] Remote call audio dropped out — recent live lines may be from your microphone only."
                    }
                };
                emit_notice(self.options, err, message, true)?;
            }
        }
        if status.disabled.is_none() && status.diagnostic != self.last_diagnostic {
            self.last_diagnostic = status.diagnostic.clone();
            if let Some(diag) = status.diagnostic.as_deref() {
                emit_notice(self.options, err, &format!("[minutes] {diag}"), true)?;
            }
        }
        Ok(())
    }
}

/// Follow live transcript updates until `stop` becomes true, stdout closes,
/// or the active recording has live transcript explicitly disabled.
#[cfg(feature = "whisper")]
pub fn follow_transcript(
    source: &impl FollowSource,
    options: FollowOptions,
    stop: &AtomicBool,
    out: &mut impl Write,
    err: &mut impl Write,
) -> Result<()> {
    let mut state = FollowSessionState::new(options);
    while !stop.load(Ordering::Relaxed) {
        if !state.step(source, out, err)? {
            break;
        }
        if stop.load(Ordering::Relaxed) {
            break;
        }
        // Sleep in short slices so Ctrl-C exits promptly even with longer intervals.
        let mut remaining = options.poll_interval;
        let slice = Duration::from_millis(50);
        while !remaining.is_zero() && !stop.load(Ordering::Relaxed) {
            let nap = remaining.min(slice);
            std::thread::sleep(nap);
            remaining = remaining.saturating_sub(nap);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_since_window_handles_all_lines_and_durations() {
        assert_eq!(parse_since_window(None).unwrap(), InitialWindow::All);
        assert_eq!(
            parse_since_window(Some("12")).unwrap(),
            InitialWindow::SinceLine(12)
        );
        assert_eq!(
            parse_since_window(Some("30s")).unwrap(),
            InitialWindow::SinceDurationMs(30_000)
        );
        assert_eq!(
            parse_since_window(Some("5m")).unwrap(),
            InitialWindow::SinceDurationMs(300_000)
        );
        assert!(parse_since_window(Some("bogus")).is_err());
    }

    #[test]
    fn color_respects_tty_no_color_and_dumb_term() {
        assert!(should_use_color(true, false, Some("xterm-256color")));
        assert!(!should_use_color(false, false, Some("xterm-256color")));
        assert!(!should_use_color(true, true, Some("xterm-256color")));
        assert!(!should_use_color(true, false, Some("dumb")));
    }

    #[test]
    fn sanitize_strips_control_chars_and_normalizes_whitespace() {
        assert_eq!(
            sanitize_terminal_text("Hello\x1b[31m\nworld\t!"),
            "Hello[31m world !"
        );
        assert_eq!(sanitize_terminal_text("Alex\x07"), "Alex");
        assert_eq!(
            sanitize_terminal_text("safe\u{202E}gnioops\u{2066}text\u{200F}"),
            "safegnioopstext"
        );
    }

    #[test]
    fn effective_format_defaults_to_text_when_following_and_json_otherwise() {
        assert_eq!(effective_transcript_format(None, false), "json");
        assert_eq!(effective_transcript_format(None, true), "text");
        assert_eq!(effective_transcript_format(Some("json"), true), "json");
        assert_eq!(effective_transcript_format(Some("text"), false), "text");
    }
}

#[cfg(all(test, feature = "whisper"))]
mod follow_tests {
    use super::*;
    use chrono::TimeZone;
    use std::cell::RefCell;
    use std::collections::VecDeque;

    fn make_line(line: usize, text: &str, speaker: Option<&str>) -> TranscriptLine {
        let ts = chrono::Local
            .with_ymd_and_hms(2026, 12, 3, 14, 5, (line % 60) as u32)
            .single()
            .unwrap();
        TranscriptLine {
            line,
            ts,
            offset_ms: (line as u64) * 5_000,
            duration_ms: 2_000,
            text: text.to_string(),
            speaker: speaker.map(str::to_string),
        }
    }

    fn base_status(active: bool, line_count: usize) -> SessionStatus {
        SessionStatus {
            active,
            pid: active.then_some(4242),
            line_count,
            duration_secs: (line_count as f64) * 5.0,
            latest_final_age_secs: None,
            session_id: active.then(|| "sess-1".to_string()),
            jsonl_path: None,
            source: active.then_some(TranscriptSource::Standalone),
            diagnostic: None,
            disabled: None,
            remote_audio: None,
        }
    }

    struct ScriptedSource {
        steps: RefCell<VecDeque<(SessionStatus, Vec<TranscriptLine>)>>,
        current_lines: RefCell<Vec<TranscriptLine>>,
    }

    impl ScriptedSource {
        fn new(steps: Vec<(SessionStatus, Vec<TranscriptLine>)>) -> Self {
            Self {
                steps: RefCell::new(steps.into()),
                current_lines: RefCell::new(Vec::new()),
            }
        }
    }

    impl FollowSource for ScriptedSource {
        fn status(&self) -> SessionStatus {
            let (status, lines) = self
                .steps
                .borrow_mut()
                .pop_front()
                .expect("scripted source exhausted");
            *self.current_lines.borrow_mut() = lines;
            status
        }

        fn read_since_line(&self, since_line: usize) -> Result<Vec<TranscriptLine>> {
            Ok(self
                .current_lines
                .borrow()
                .iter()
                .filter(|l| l.line > since_line)
                .cloned()
                .collect())
        }

        fn read_since_duration(&self, _duration_ms: u64) -> Result<Vec<TranscriptLine>> {
            // Return only the newest line to simulate a narrow duration window.
            Ok(self
                .current_lines
                .borrow()
                .last()
                .cloned()
                .into_iter()
                .collect())
        }
    }

    fn text_options(initial: InitialWindow) -> FollowOptions {
        FollowOptions {
            format: FollowFormat::Text,
            initial,
            poll_interval: Duration::from_millis(1),
            use_color: false,
        }
    }

    #[test]
    fn format_text_line_omits_unknown_speaker_and_strips_controls() {
        let plain = make_line(1, "Hello\x1b[31m\nworld\t!", None);
        assert_eq!(
            format_text_line(&plain, false),
            "[14:05:01] Hello[31m world !"
        );

        let spoken = make_line(2, "Agreed.", Some("Alex\x07"));
        assert_eq!(
            format_text_line(&spoken, false),
            "[14:05:02] [Alex] Agreed."
        );

        let colored = format_text_line(&spoken, true);
        assert!(colored.contains("\x1b[2m14:05:02\x1b[0m"));
        assert!(colored.contains("\x1b[36mAlex\x1b[0m"));
        assert!(colored.ends_with("Agreed."));
    }

    #[test]
    fn waits_for_session_without_dumping_stale_lines_then_streams_and_drains_on_stop() {
        let stale = vec![make_line(1, "Yesterday's meeting", None)];
        let l1 = make_line(1, "Okay, quick sync on Valley deliveries.", None);
        let l2 = make_line(2, "Y.T. has a 90-day exclusive trial.", None);
        let l3 = make_line(3, "Let's confirm Friday.", None);

        let source = ScriptedSource::new(vec![
            (base_status(false, 1), stale),
            (base_status(true, 1), vec![l1.clone()]),
            (base_status(true, 2), vec![l1.clone(), l2.clone()]),
            // Line 3 flushed right as session stopped.
            (base_status(false, 3), vec![l1, l2, l3]),
        ]);

        let mut state = FollowSessionState::new(text_options(InitialWindow::All));
        let mut out = Vec::new();
        let mut err = Vec::new();

        for _ in 0..4 {
            assert!(state.step(&source, &mut out, &mut err).unwrap());
        }

        let stdout = String::from_utf8(out).unwrap();
        let stderr = String::from_utf8(err).unwrap();
        assert!(!stdout.contains("Yesterday's meeting"));
        assert_eq!(
            stdout.lines().collect::<Vec<_>>(),
            vec![
                "[14:05:01] Okay, quick sync on Valley deliveries.",
                "[14:05:02] Y.T. has a 90-day exclusive trial.",
                "[14:05:03] Let's confirm Friday.",
            ]
        );
        assert!(stderr.contains("Waiting for live transcript"));
        assert!(stderr.contains("Connected"));
        assert!(stderr.contains("Live transcript ended (3 lines)"));
    }

    #[test]
    fn since_duration_sets_cursor_past_older_lines_and_only_emits_new_ones() {
        let l1 = make_line(1, "Old line one", None);
        let l2 = make_line(2, "Recent line two", None);
        let l3 = make_line(3, "New line three", None);

        let source = ScriptedSource::new(vec![
            (base_status(true, 2), vec![l1.clone(), l2.clone()]),
            (base_status(true, 2), vec![l1.clone(), l2.clone()]),
            (base_status(true, 3), vec![l1, l2, l3]),
        ]);

        let mut state =
            FollowSessionState::new(text_options(InitialWindow::SinceDurationMs(30_000)));
        let mut out = Vec::new();
        let mut err = Vec::new();

        for _ in 0..3 {
            assert!(state.step(&source, &mut out, &mut err).unwrap());
        }

        let stdout = String::from_utf8(out).unwrap();
        assert_eq!(
            stdout.lines().collect::<Vec<_>>(),
            vec!["[14:05:02] Recent line two", "[14:05:03] New line three",]
        );
    }

    #[test]
    fn handles_session_rollover_without_restarting_follow() {
        let s1 = base_status(true, 2);
        let mut s2 = base_status(true, 1);
        s2.session_id = Some("sess-2".to_string());
        s2.pid = Some(9999);

        let source = ScriptedSource::new(vec![
            (
                s1,
                vec![make_line(1, "First call", None), make_line(2, "Done", None)],
            ),
            (s2, vec![make_line(1, "Second call starts", None)]),
        ]);

        let mut state = FollowSessionState::new(text_options(InitialWindow::All));
        let mut out = Vec::new();
        let mut err = Vec::new();

        assert!(state.step(&source, &mut out, &mut err).unwrap());
        assert!(state.step(&source, &mut out, &mut err).unwrap());

        let stdout = String::from_utf8(out).unwrap();
        let stderr = String::from_utf8(err).unwrap();
        assert_eq!(
            stdout.lines().collect::<Vec<_>>(),
            vec![
                "[14:05:01] First call",
                "[14:05:02] Done",
                "[14:05:01] Second call starts",
            ]
        );
        assert!(stderr.contains("New live transcript session"));
    }

    #[test]
    fn json_mode_streams_ndjson_and_keeps_stderr_quiet() {
        let source = ScriptedSource::new(vec![(
            base_status(true, 1),
            vec![make_line(1, "Ship it", Some("Mat"))],
        )]);

        let options = FollowOptions {
            format: FollowFormat::Json,
            initial: InitialWindow::All,
            poll_interval: Duration::from_millis(1),
            use_color: false,
        };
        let mut state = FollowSessionState::new(options);
        let mut out = Vec::new();
        let mut err = Vec::new();

        assert!(state.step(&source, &mut out, &mut err).unwrap());

        let stdout = String::from_utf8(out).unwrap();
        let parsed: TranscriptLine = serde_json::from_str(stdout.trim()).unwrap();
        assert_eq!(parsed.line, 1);
        assert_eq!(parsed.text, "Ship it");
        assert_eq!(parsed.speaker.as_deref(), Some("Mat"));
        assert!(err.is_empty());
    }

    #[test]
    fn disabled_recording_sidecar_prints_notice_and_exits_cleanly() {
        let mut status = base_status(false, 0);
        status.disabled = Some(LiveTranscriptDisabled::RecordingSidecarConfig);
        let source = ScriptedSource::new(vec![(status, vec![])]);

        let mut state = FollowSessionState::new(text_options(InitialWindow::All));
        let mut out = Vec::new();
        let mut err = Vec::new();

        assert!(!state.step(&source, &mut out, &mut err).unwrap());
        assert!(out.is_empty());
        assert!(String::from_utf8(err)
            .unwrap()
            .contains("recording_sidecar = false"));
    }

    #[test]
    fn remote_audio_warning_prints_once_per_transition() {
        let mut s1 = base_status(true, 0);
        s1.remote_audio = Some(RemoteAudioStatus::Missing);
        let s2 = s1.clone();
        let mut s3 = base_status(true, 0);
        s3.remote_audio = Some(RemoteAudioStatus::Partial);
        let source = ScriptedSource::new(vec![(s1, vec![]), (s2, vec![]), (s3, vec![])]);

        let mut state = FollowSessionState::new(text_options(InitialWindow::All));
        let mut out = Vec::new();
        let mut err = Vec::new();

        assert!(state.step(&source, &mut out, &mut err).unwrap());
        assert!(state.step(&source, &mut out, &mut err).unwrap());
        assert!(state.step(&source, &mut out, &mut err).unwrap());

        let stderr = String::from_utf8(err).unwrap();
        assert_eq!(stderr.matches("Remote call audio is missing").count(), 1);
        assert_eq!(stderr.matches("Remote call audio dropped out").count(), 1);
    }

    #[test]
    fn broken_pipe_exits_cleanly_without_error() {
        struct BrokenPipeWriter;
        impl Write for BrokenPipeWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(io::Error::new(io::ErrorKind::BrokenPipe, "closed"))
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let source = ScriptedSource::new(vec![(
            base_status(true, 1),
            vec![make_line(1, "Hello", None)],
        )]);
        let mut state = FollowSessionState::new(text_options(InitialWindow::All));
        let mut out = BrokenPipeWriter;
        let mut err = Vec::new();

        assert!(!state.step(&source, &mut out, &mut err).unwrap());
    }
}