aurum-core 0.0.23

On-device speech I/O core: whisper.cpp STT, ONNX TTS, cleanup, providers
Documentation
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
//! Time-based remote STT chunk-and-stitch (JOE-2212 / JOE-2219).
//!
//! Long lectures can exceed [`TranscriptLimits::max_segment_chars`] when a vendor
//! returns a single continuous segment, or truncate on full-file remote paths.
//! Client-side audio chunking (~210s windows, dual-ref eval band) keeps each
//! request small and stitches text/segments with time offsets.
//!
//! JOE-2219 adds silence-aware boundaries, bounded overlap, deduplication, and
//! timestamp provenance. Local whisper full-file behavior is unchanged.

use crate::audio::AudioInput;
use crate::error::{ProviderError, Result};
use crate::providers::{Segment, TranscriptionOptions, TranscriptionResult};
use crate::remote::limits::{validate_segments, validate_text_bounds, TranscriptLimits};
use crate::remote::long_form::{
    dedupe_segments_overlap, derive_timestamps_reliable, plan_boundary_windows,
    stitch_text_with_overlap, LongFormPolicy, TimestampSource,
};
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;

/// Default remote STT window length (seconds). Matches Plaud dual-ref chunk recipes.
pub const DEFAULT_REMOTE_STT_CHUNK_SECS: f64 = 210.0;

/// Minimum duration that triggers chunking (must be > 0 and finite).
pub fn needs_time_chunk(duration_secs: f64, chunk_secs: f64) -> bool {
    duration_secs.is_finite()
        && chunk_secs.is_finite()
        && chunk_secs > 0.0
        && duration_secs > chunk_secs
}

/// Inclusive start / exclusive end sample ranges with start offset in seconds.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChunkWindow {
    pub start_sample: usize,
    pub end_sample: usize,
    pub offset_secs: f64,
}

/// Plan non-overlapping PCM windows covering `[0, total_samples)`.
///
/// Legacy hard-cut planner retained for tests and explicit fixed-window fallback.
/// Prefer [`plan_boundary_windows`] with PCM for production long-form.
pub fn plan_chunk_windows(
    total_samples: usize,
    sample_rate: u32,
    chunk_secs: f64,
) -> Vec<ChunkWindow> {
    if total_samples == 0 || sample_rate == 0 || !chunk_secs.is_finite() || chunk_secs <= 0.0 {
        return vec![ChunkWindow {
            start_sample: 0,
            end_sample: total_samples,
            offset_secs: 0.0,
        }];
    }
    let chunk_samples = ((chunk_secs * f64::from(sample_rate)).round() as usize).max(1);
    if total_samples <= chunk_samples {
        return vec![ChunkWindow {
            start_sample: 0,
            end_sample: total_samples,
            offset_secs: 0.0,
        }];
    }
    let mut out = Vec::new();
    let mut start = 0usize;
    while start < total_samples {
        let end = (start + chunk_samples).min(total_samples);
        out.push(ChunkWindow {
            start_sample: start,
            end_sample: end,
            offset_secs: start as f64 / f64::from(sample_rate),
        });
        if end == total_samples {
            break;
        }
        start = end;
    }
    out
}

/// Slice mono PCM into a new [`AudioInput`] for one window.
pub fn slice_audio_window(input: &AudioInput, window: ChunkWindow) -> Result<AudioInput> {
    let samples = input.samples();
    let start = window.start_sample.min(samples.len());
    let end = window.end_sample.min(samples.len()).max(start);
    if start == end {
        return Err(ProviderError::Other {
            message: "remote STT chunk window is empty".into(),
        }
        .into());
    }
    let slice: Arc<[f32]> = Arc::from(samples[start..end].to_vec());
    let sr = input.sample_rate();
    let duration = if sr > 0 {
        (end - start) as f64 / f64::from(sr)
    } else {
        0.0
    };
    Ok(AudioInput::from_parts_unchecked(
        PathBuf::from(format!(
            "pcm://remote-stt-chunk/{:.3}-{:.3}",
            window.offset_secs,
            window.offset_secs + duration
        )),
        slice,
        sr,
        duration,
    ))
}

/// Soft-split an overlong single segment into adjacent pieces under `max_chars`.
///
/// Used when a vendor returns one continuous hyp for a chunk that still exceeds
/// [`TranscriptLimits::max_segment_chars`] (rare for ~210s speech, but fail-closed
/// without soft-split would block the whole job).
pub fn soft_split_text_segments(
    text: &str,
    start: f64,
    end: f64,
    max_chars: usize,
) -> Vec<Segment> {
    let max_chars = max_chars.max(1);
    let chars: Vec<char> = text.chars().collect();
    if chars.is_empty() {
        return vec![Segment::from_parts_with_source(
            start,
            end,
            String::new(),
            TimestampSource::SyntheticSpan,
        )];
    }
    if chars.len() <= max_chars {
        // Full-span carrier without further subdivision.
        return vec![Segment::from_parts_with_source(
            start,
            end,
            text.to_string(),
            TimestampSource::SyntheticSpan,
        )];
    }
    let n_parts = chars.len().div_ceil(max_chars);
    let span = (end - start).max(0.0);
    let mut segs = Vec::with_capacity(n_parts);
    for i in 0..n_parts {
        let c0 = i * max_chars;
        let c1 = ((i + 1) * max_chars).min(chars.len());
        let piece: String = chars[c0..c1].iter().collect();
        let t0 = start + span * (c0 as f64 / chars.len() as f64);
        let t1 = start + span * (c1 as f64 / chars.len() as f64);
        // Soft-split timing is interpolated, not provider-observed (JOE-2219).
        segs.push(Segment::from_parts_with_source(
            t0,
            t1.max(t0),
            piece,
            TimestampSource::Interpolated,
        ));
    }
    segs
}

/// Offset segments by `offset_secs` and soft-split any that still exceed limits.
///
/// Offset segments are marked [`TimestampSource::ChunkOffset`] unless they were
/// already interpolated (soft-split).
pub fn normalize_chunk_segments(
    segments: &[Segment],
    offset_secs: f64,
    limits: TranscriptLimits,
) -> Vec<Segment> {
    let mut out = Vec::new();
    for seg in segments {
        let start = seg.start() + offset_secs;
        let end = seg.end() + offset_secs;
        let text = seg.text();
        if text.chars().count() > limits.max_segment_chars {
            out.extend(soft_split_text_segments(
                text,
                start,
                end,
                limits.max_segment_chars,
            ));
        } else {
            let source = if matches!(
                seg.timestamp_source(),
                TimestampSource::Interpolated | TimestampSource::SyntheticSpan
            ) {
                seg.timestamp_source()
            } else if offset_secs.abs() > f64::EPSILON {
                TimestampSource::ChunkOffset
            } else {
                match seg.timestamp_source() {
                    TimestampSource::Unavailable => TimestampSource::ProviderSegment,
                    other => other,
                }
            };
            out.push(Segment::from_parts_with_source(
                start,
                end,
                text.to_string(),
                source,
            ));
        }
    }
    out
}

/// Join chunk results into one transcript for the full media duration.
pub fn stitch_chunk_results(
    parts: &[(f64, TranscriptionResult)],
    full_duration_secs: f64,
    provider: &str,
    limits: TranscriptLimits,
) -> Result<TranscriptionResult> {
    if parts.is_empty() {
        return Err(ProviderError::TranscriptionFailed {
            reason: "remote STT chunk-and-stitch produced no chunks".into(),
        }
        .into());
    }

    let mut text_parts: Vec<(String, f64)> = Vec::with_capacity(parts.len());
    let mut segments: Vec<Segment> = Vec::new();
    let mut backend_kind = parts[0].1.backend_kind();
    let model = parts[0].1.model().to_string();
    let language = parts[0].1.language().map(|s| s.to_string());
    let provider_name = parts[0].1.provider().to_string();
    let mut stitch_warnings: Vec<String> = Vec::new();

    for (i, (offset, r)) in parts.iter().enumerate() {
        // Prefer ASR label if any chunk is dedicated ASR.
        if matches!(r.backend_kind(), crate::providers::BackendKind::Asr) {
            backend_kind = crate::providers::BackendKind::Asr;
        }
        let mut chunk_segs = normalize_chunk_segments(r.segments(), *offset, limits);
        if i > 0 {
            let prev_len = segments.len();
            let earlier = if prev_len > 0 {
                &segments[prev_len.saturating_sub(3)..]
            } else {
                &[]
            };
            // Overlap secs unknown at stitch layer when using legacy planner; 0 means no dedupe.
            let (deduped, warn) = dedupe_segments_overlap(earlier, &chunk_segs, 0.0, *offset);
            if let Some(w) = warn {
                stitch_warnings.push(w);
            }
            chunk_segs = deduped;
        }
        let t = r.text().trim();
        if !t.is_empty() {
            text_parts.push((t.to_string(), 0.0));
        }
        segments.extend(chunk_segs);
    }

    let (text, text_warns) = stitch_text_with_overlap(&text_parts);
    stitch_warnings.extend(text_warns);
    validate_text_bounds(&text, None, limits, provider)?;
    validate_segments(&segments, full_duration_secs, limits, provider)?;

    let sources: Vec<_> = segments.iter().map(|s| s.timestamp_source()).collect();
    let timestamps_reliable =
        derive_timestamps_reliable(&sources) && parts.iter().all(|(_, r)| r.timestamps_reliable());

    let mut result = TranscriptionResult::openrouter(
        text,
        segments,
        language,
        model,
        full_duration_secs,
        timestamps_reliable,
    );
    result.set_provider(if provider_name.is_empty() {
        provider
    } else {
        provider_name.as_str()
    });
    result.set_backend_kind(backend_kind);
    result.set_timestamps_reliable(timestamps_reliable);
    result.set_warnings(stitch_warnings);
    result.validate_segments()?;
    Ok(result)
}

/// Stitch with explicit per-chunk overlap seconds (boundary-aware planner).
pub fn stitch_chunk_results_with_overlaps(
    parts: &[(f64, f64, TranscriptionResult)],
    full_duration_secs: f64,
    provider: &str,
    limits: TranscriptLimits,
) -> Result<TranscriptionResult> {
    // Map to (offset, result) and re-run segment path with overlap-aware text.
    if parts.is_empty() {
        return Err(ProviderError::TranscriptionFailed {
            reason: "remote STT chunk-and-stitch produced no chunks".into(),
        }
        .into());
    }
    let mut text_parts: Vec<(String, f64)> = Vec::with_capacity(parts.len());
    let mut segments: Vec<Segment> = Vec::new();
    let mut backend_kind = parts[0].2.backend_kind();
    let model = parts[0].2.model().to_string();
    let language = parts[0].2.language().map(|s| s.to_string());
    let provider_name = parts[0].2.provider().to_string();
    let mut stitch_warnings: Vec<String> = Vec::new();

    for (i, (offset, overlap_secs, r)) in parts.iter().enumerate() {
        if matches!(r.backend_kind(), crate::providers::BackendKind::Asr) {
            backend_kind = crate::providers::BackendKind::Asr;
        }
        let mut chunk_segs = normalize_chunk_segments(r.segments(), *offset, limits);
        if i > 0 && *overlap_secs > 0.0 {
            let earlier = segments.as_slice();
            let (deduped, warn) =
                dedupe_segments_overlap(earlier, &chunk_segs, *overlap_secs, *offset);
            if let Some(w) = warn {
                stitch_warnings.push(w);
            }
            chunk_segs = deduped;
        }
        let t = r.text().trim();
        if !t.is_empty() {
            text_parts.push((t.to_string(), if i == 0 { 0.0 } else { *overlap_secs }));
        }
        segments.extend(chunk_segs);
    }

    let (text, text_warns) = stitch_text_with_overlap(&text_parts);
    stitch_warnings.extend(text_warns);
    validate_text_bounds(&text, None, limits, provider)?;
    validate_segments(&segments, full_duration_secs, limits, provider)?;
    let sources: Vec<_> = segments.iter().map(|s| s.timestamp_source()).collect();
    let timestamps_reliable = derive_timestamps_reliable(&sources)
        && parts.iter().all(|(_, _, r)| r.timestamps_reliable());

    let mut result = TranscriptionResult::openrouter(
        text,
        segments,
        language,
        model,
        full_duration_secs,
        timestamps_reliable,
    );
    result.set_provider(if provider_name.is_empty() {
        provider
    } else {
        provider_name.as_str()
    });
    result.set_backend_kind(backend_kind);
    result.set_timestamps_reliable(timestamps_reliable);
    result.set_warnings(stitch_warnings);
    result.validate_segments()?;
    Ok(result)
}

/// Run `one_shot` once, or boundary-aware chunk + stitch when audio is longer
/// than the policy target (JOE-2212 / JOE-2219).
///
/// The callback receives **owned** inputs so futures do not borrow across awaits.
/// One absolute cancel token from `options` is checked before every chunk.
pub async fn transcribe_maybe_chunked<F, Fut>(
    input: &AudioInput,
    options: &TranscriptionOptions,
    provider: &str,
    chunk_secs: f64,
    mut one_shot: F,
) -> Result<TranscriptionResult>
where
    F: FnMut(AudioInput, TranscriptionOptions) -> Fut,
    Fut: Future<Output = Result<TranscriptionResult>>,
{
    let duration = input.duration_secs();
    if !needs_time_chunk(duration, chunk_secs) {
        return one_shot(input.clone(), options.clone()).await;
    }

    let mut policy = LongFormPolicy::from_env_or_default();
    if chunk_secs.is_finite() && chunk_secs > 0.0 {
        policy.target_secs = chunk_secs;
        policy.max_secs = policy.max_secs.max(chunk_secs);
    }
    // Fall back to fixed windows if boundary policy is invalid for this call.
    let planned = match plan_boundary_windows(input.samples(), input.sample_rate(), &policy) {
        Ok(p) => p,
        Err(e) => {
            tracing::warn!(
                error = %e,
                "long-form boundary planner failed; using fixed windows"
            );
            plan_chunk_windows(input.len(), input.sample_rate(), chunk_secs)
                .into_iter()
                .map(|w| crate::remote::long_form::PlannedWindow {
                    window: w,
                    kind: crate::remote::long_form::BoundaryKind::FixedFallback,
                    overlap_secs: 0.0,
                })
                .collect()
        }
    };

    tracing::info!(
        provider,
        duration_secs = duration,
        chunk_secs = policy.target_secs,
        chunks = planned.len(),
        "remote STT boundary-aware chunk-and-stitch (JOE-2219)"
    );

    // One parent OpContext for the whole long-form job (deadline + cancel + progress).
    let parent_op = options.resolve_op_context();
    parent_op.check()?;
    parent_op.emit(
        "stt",
        format!(
            "long_form_start chunks={} target_secs={:.1}",
            planned.len(),
            policy.target_secs
        ),
    );

    let mut parts: Vec<(f64, f64, TranscriptionResult)> = Vec::with_capacity(planned.len());
    for (i, planned_w) in planned.iter().enumerate() {
        // Absolute deadline / cancel from the parent operation (not only cancel).
        parent_op.check().map_err(|e| match e {
            crate::error::TranscriptionError::Provider(ProviderError::Cancelled) => {
                ProviderError::Cancelled.into()
            }
            other => other,
        })?;
        parent_op.emit(
            "stt",
            format!(
                "chunk {}/{} offset_secs={:.1} boundary={:?}",
                i + 1,
                planned.len(),
                planned_w.window.offset_secs,
                planned_w.kind
            ),
        );
        let window = planned_w.window;
        let chunk_input = slice_audio_window(input, window)?;
        tracing::debug!(
            provider,
            chunk = i + 1,
            of = planned.len(),
            offset_secs = window.offset_secs,
            chunk_duration = chunk_input.duration_secs(),
            boundary = ?planned_w.kind,
            "remote STT chunk"
        );
        // Propagate the same OpContext into each chunk so one-shot paths share
        // the parent deadline rather than minting a cancel-only context.
        let mut chunk_opts = options.clone();
        chunk_opts.op = Some(parent_op.clone());
        chunk_opts.cancel = Some(parent_op.cancel.clone());
        let result = one_shot(chunk_input, chunk_opts)
            .await
            .map_err(|e| match e {
                crate::error::TranscriptionError::Provider(
                    ProviderError::TranscriptionFailed { reason },
                ) => ProviderError::TranscriptionFailed {
                    reason: format!(
                        "chunk {}/{} (offset {:.1}s): {reason}",
                        i + 1,
                        planned.len(),
                        window.offset_secs
                    ),
                }
                .into(),
                other => other,
            })?;
        parts.push((window.offset_secs, planned_w.overlap_secs, result));
    }

    stitch_chunk_results_with_overlaps(&parts, duration, provider, TranscriptLimits::default())
}

/// Effective chunk length: `AURUM_REMOTE_STT_CHUNK_SECS` if set and valid, else default.
pub fn effective_chunk_secs() -> f64 {
    match std::env::var("AURUM_REMOTE_STT_CHUNK_SECS") {
        Ok(s) => {
            let v: f64 = s.trim().parse().unwrap_or(DEFAULT_REMOTE_STT_CHUNK_SECS);
            if v.is_finite() && v > 0.0 {
                v
            } else {
                DEFAULT_REMOTE_STT_CHUNK_SECS
            }
        }
        Err(_) => DEFAULT_REMOTE_STT_CHUNK_SECS,
    }
}

/// Convenience for tests: 16 kHz silence of `duration_secs`.
#[cfg(test)]
pub fn silence_input(duration_secs: f64) -> AudioInput {
    use crate::audio::WHISPER_SAMPLE_RATE;
    let n = (duration_secs * f64::from(WHISPER_SAMPLE_RATE)).round() as usize;
    AudioInput::from_pcm_slice(&vec![0.0f32; n.max(1)], WHISPER_SAMPLE_RATE).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audio::WHISPER_SAMPLE_RATE;
    use crate::providers::BackendKind;

    #[test]
    fn needs_chunk_threshold() {
        assert!(!needs_time_chunk(100.0, 210.0));
        assert!(!needs_time_chunk(210.0, 210.0));
        assert!(needs_time_chunk(210.1, 210.0));
        assert!(!needs_time_chunk(f64::NAN, 210.0));
    }

    #[test]
    fn plans_four_windows_for_685s() {
        let total = (685.0 * f64::from(WHISPER_SAMPLE_RATE)) as usize;
        let windows = plan_chunk_windows(total, WHISPER_SAMPLE_RATE, 210.0);
        assert_eq!(windows.len(), 4);
        assert_eq!(windows[0].offset_secs, 0.0);
        assert!((windows[1].offset_secs - 210.0).abs() < 0.01);
        assert_eq!(windows.last().unwrap().end_sample, total);
        // Coverage without gaps
        for w in windows.windows(2) {
            assert_eq!(w[0].end_sample, w[1].start_sample);
        }
    }

    #[test]
    fn single_window_when_short() {
        let total = WHISPER_SAMPLE_RATE as usize * 30;
        let windows = plan_chunk_windows(total, WHISPER_SAMPLE_RATE, 210.0);
        assert_eq!(windows.len(), 1);
        assert_eq!(windows[0].end_sample, total);
    }

    #[test]
    fn soft_split_respects_max_chars() {
        let text = "a".repeat(20);
        let segs = soft_split_text_segments(&text, 0.0, 10.0, 8);
        assert!(segs.len() > 1);
        assert!(segs.iter().all(|s| s.text().chars().count() <= 8));
        let joined: String = segs.iter().map(|s| s.text()).collect();
        assert_eq!(joined, text);
    }

    #[test]
    fn stitch_offsets_segments() {
        let mut a = TranscriptionResult::openrouter(
            "hello".to_string(),
            vec![Segment::from_parts_unchecked(0.0, 1.0, "hello".to_string())],
            None,
            "m".to_string(),
            1.0,
            true,
        );
        a.set_provider("openai");
        a.set_backend_kind(BackendKind::Asr);
        a.set_timestamps_reliable(true);

        let mut b = TranscriptionResult::openrouter(
            "world".to_string(),
            vec![Segment::from_parts_unchecked(0.0, 1.0, "world".to_string())],
            None,
            "m".to_string(),
            1.0,
            true,
        );
        b.set_provider("openai");
        b.set_backend_kind(BackendKind::Asr);
        b.set_timestamps_reliable(true);

        let stitched = stitch_chunk_results(
            &[(0.0, a), (210.0, b)],
            420.0,
            "openai",
            TranscriptLimits::default(),
        )
        .unwrap();
        assert_eq!(stitched.text(), "hello world");
        assert_eq!(stitched.segments().len(), 2);
        assert!((stitched.segments()[1].start() - 210.0).abs() < 1e-9);
        assert!(stitched.timestamps_reliable());
        assert_eq!(stitched.provider(), "openai");
    }

    #[test]
    fn stitch_with_overlaps_dedupes_using_later_window_overlap() {
        // Simulates planner ownership: part0 overlap=0, part1 overlap=1.5.
        let mut a = TranscriptionResult::openrouter(
            "the quick brown fox jumps".to_string(),
            vec![Segment::from_parts_with_source(
                0.0,
                5.0,
                "the quick brown fox jumps",
                TimestampSource::ProviderSegment,
            )],
            None,
            "m".to_string(),
            5.0,
            true,
        );
        a.set_provider("openai");
        a.set_backend_kind(BackendKind::Asr);
        a.set_timestamps_reliable(true);

        let mut b = TranscriptionResult::openrouter(
            "fox jumps over the lazy dog".to_string(),
            vec![Segment::from_parts_with_source(
                0.0,
                5.0,
                "fox jumps over the lazy dog",
                TimestampSource::ProviderSegment,
            )],
            None,
            "m".to_string(),
            5.0,
            true,
        );
        b.set_provider("openai");
        b.set_backend_kind(BackendKind::Asr);
        b.set_timestamps_reliable(true);

        let stitched = stitch_chunk_results_with_overlaps(
            &[(0.0, 0.0, a), (3.5, 1.5, b)],
            8.5,
            "openai",
            TranscriptLimits::default(),
        )
        .unwrap();
        // Overlap tokens "fox jumps" should be deduped from the later chunk text path.
        assert!(stitched.text().contains("lazy"));
        assert!(stitched.text().contains("quick"));
        // Low-confidence path may leave warnings empty when text dedupe succeeds.
        let _ = stitched.warnings();
    }

    #[test]
    fn soft_split_marks_interpolated_and_synthetic() {
        let text = "a".repeat(20);
        let segs = soft_split_text_segments(&text, 0.0, 10.0, 8);
        assert!(segs
            .iter()
            .all(|s| s.timestamp_source() == TimestampSource::Interpolated));
        let single = soft_split_text_segments("short", 0.0, 1.0, 100);
        assert_eq!(single.len(), 1);
        assert_eq!(single[0].timestamp_source(), TimestampSource::SyntheticSpan);
    }

    #[tokio::test]
    async fn maybe_chunked_short_is_single_call() {
        let input = silence_input(5.0);
        let opts = TranscriptionOptions {
            model: "whisper-1".into(),
            language: "en".into(),
            timestamps: false,
            cancel: None,
            op: None,
        };
        let mut calls = 0u32;
        let out = transcribe_maybe_chunked(&input, &opts, "t", 210.0, |inp, _| {
            calls += 1;
            let mut r = TranscriptionResult::openrouter(
                "ok".to_string(),
                vec![Segment::from_parts_unchecked(
                    0.0,
                    inp.duration_secs(),
                    "ok".to_string(),
                )],
                None,
                "whisper-1".to_string(),
                inp.duration_secs(),
                false,
            );
            r.set_provider("t");
            async move { Ok(r) }
        })
        .await
        .unwrap();
        assert_eq!(calls, 1);
        assert_eq!(out.text(), "ok");
    }

    #[tokio::test]
    async fn maybe_chunked_long_invokes_multiple() {
        let input = silence_input(500.0);
        let opts = TranscriptionOptions {
            model: "whisper-1".into(),
            language: "en".into(),
            timestamps: false,
            cancel: None,
            op: None,
        };
        let mut calls = 0u32;
        let out = transcribe_maybe_chunked(&input, &opts, "t", 210.0, |inp, _| {
            calls += 1;
            let label = format!("c{calls}");
            let mut r = TranscriptionResult::openrouter(
                label.clone(),
                vec![Segment::from_parts_unchecked(
                    0.0,
                    inp.duration_secs(),
                    label,
                )],
                None,
                "whisper-1".into(),
                inp.duration_secs(),
                false,
            );
            r.set_provider("t");
            async move { Ok(r) }
        })
        .await
        .unwrap();
        assert_eq!(calls, 3); // 210+210+80
        assert!(out.text().contains(' '));
        assert_eq!(out.segments().len(), 3);
        assert!((out.duration_secs() - 500.0).abs() < 0.02);
    }

    #[tokio::test]
    async fn maybe_chunked_honours_cancel() {
        let input = silence_input(500.0);
        let flag = crate::cancel::CancelFlag::new();
        flag.cancel();
        let opts = TranscriptionOptions {
            model: "whisper-1".into(),
            language: "en".into(),
            timestamps: false,
            cancel: Some(flag),
            op: None,
        };
        let err = transcribe_maybe_chunked(&input, &opts, "t", 210.0, |_inp, _| async {
            unreachable!("should cancel before first shot")
        })
        .await
        .unwrap_err();
        assert!(err.to_string().to_lowercase().contains("cancel"));
    }
}