talk-rs 0.7.1

Voice dictation for Linux -- record, transcribe, and paste
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Dictate command implementation.
//!
//! Records audio, streams it to the transcription API, and pastes the result
//! into the focused application via clipboard.

mod models;
mod oneshot;
mod picker;
mod realtime;
mod text;
mod toggle;

use crate::audio::bt_profile;
use crate::audio::file_source::{OggFileSource, WavFileSource};
use crate::audio::monitor_capture::MonitorCapture;
use crate::audio::pipewire_capture::PipeWireCapture;
use crate::audio::recording_feedback::{
    RecordingBadgeTeardown, RecordingFeedback, RecordingFeedbackOptions, RecordingOverlayOptions,
};
use crate::audio::resample;
use crate::audio::{AudioCapture, CHUNK_DURATION_MS};

use crate::config::{AudioConfig, Config, Provider};
use crate::daemon;
use crate::error::TalkError;
use crate::paste::{
    default_root, focus_window, get_active_window, paste_with_root, PasteNode,
    RealtimeClipboardGuard,
};
use crate::recording_cache;
use crate::telemetry::{BroadcastSink, TelemetrySink, TranscriptionEvent};
use crate::transcription;
use crate::x11::overlay::IndicatorKind;
use crate::x11::visualizer::VisualizerHandle;
use models::{resolve_model, resolve_provider};
use oneshot::dictate_oneshot;
use picker::{run_pick, PickParams};
use realtime::dictate_realtime;
use std::path::PathBuf;
use toggle::toggle_dispatch;
use tokio_util::sync::CancellationToken;

/// Options for the dictate command.
pub struct DictateOpts {
    pub save: Option<PathBuf>,
    pub output_yaml: Option<PathBuf>,
    pub input_audio_file: Option<PathBuf>,
    pub retry_last: bool,
    pub pick: bool,
    pub replace_last_paste: bool,
    pub provider: Option<Provider>,
    pub model: Option<String>,
    pub diarize: bool,
    pub timestamp: bool,
    pub realtime: bool,
    pub toggle: bool,
    pub no_sounds: bool,
    pub no_boop: bool,
    pub no_chunk_paste: bool,
    pub no_paste: bool,
    pub monitor: bool,
    pub no_overlay: bool,
    pub no_auto_pause: bool,
    pub viz: Option<crate::config::VizMode>,
    pub mono: bool,
    pub upload_format: crate::transcription::UploadFormat,
    pub no_bt_auto_switch: bool,
    pub daemon: bool,
    pub target_window: Option<String>,
    pub verbose: u8,
}

/// Dictate: record audio, transcribe, and paste into focused application.
pub async fn dictate(opts: DictateOpts) -> Result<(), TalkError> {
    // Toggle mode: start or stop a daemon
    if opts.toggle {
        return toggle_dispatch(&opts).await;
    }

    let _daemon_owner = if opts.daemon {
        Some(daemon::dictate_slot()?.owner_guard())
    } else {
        None
    };

    let save_path = opts.save;

    // Load configuration
    let config = Config::load(None)?;

    // Build the runtime paste-node tree from config (or fall back to
    // the default `chunk(150) → clipboard(ctrl-shift-v, 200, 400)`
    // tree when no `paste:` section is configured).  `--no-chunk-paste`
    // strips chunk wrappers from whatever tree is configured.
    let paste_root: std::sync::Arc<dyn PasteNode> = match config.paste.as_ref() {
        Some(p) => std::sync::Arc::from(p.build_root(opts.no_chunk_paste)),
        None => std::sync::Arc::from(default_root(opts.no_chunk_paste)),
    };

    // Resolve paste timing from config (defaults: 200 / 400).  Drives
    // the settle loop in `paste_with_root` and the realtime guard.
    let paste_timing = config
        .paste
        .as_ref()
        .map(|p| p.timing())
        .unwrap_or_default();

    // Determine target window: use --target-window arg (from daemon mode)
    // or capture the currently active window.
    let target_window = if let Some(wid) = opts.target_window {
        log::debug!("using target window from argument: {}", wid);
        Some(wid)
    } else if !opts.daemon {
        let wid = get_active_window().await;
        if let Some(ref w) = wid {
            log::debug!("captured active window: {}", w);
        }
        wid
    } else {
        None
    };

    let mut input_audio_file = opts.input_audio_file.clone();
    let mut replace_char_count: Option<usize> = None;
    let mut cached_brief: Option<recording_cache::RecordingMetadataBrief> = None;
    if opts.retry_last {
        let last_audio = recording_cache::last_recording_path()
            .or_else(|_| recording_cache::latest_recording_path())?;
        input_audio_file = Some(last_audio);
    }

    // Load existing pick so the picker can seed its initial state.
    // Source of truth: the pick file (Layer 1).  Sidecars are
    // Layer 3 internals and never consulted here.
    if let Some(ref audio) = input_audio_file {
        if let Some((provider, model, _streaming, text)) = recording_cache::read_pick(audio) {
            cached_brief = Some(recording_cache::RecordingMetadataBrief {
                transcript: text,
                provider: Some(provider.to_string()),
                model: Some(model),
            });
        }
    }

    // Character count for --replace-last-paste comes from the paste
    // state file, not from any transcript source.
    if opts.replace_last_paste {
        if let Ok(Some(state)) = recording_cache::read_last_paste_state() {
            replace_char_count = Some(state.char_count);
        }
    }

    if opts.pick {
        return run_pick(
            config,
            PickParams {
                input_audio_file,
                cached_brief,
                replace_char_count,
                replace_last_paste: opts.replace_last_paste,
                provider: opts.provider,
                model: opts.model,
                target_window,
                paste_root: paste_root.clone(),
                paste_timing,
            },
        )
        .await;
    }

    // Mode C: file input + default options -> consult the pick file
    // directly.  If it exists, paste its text without running any
    // capture/transcription pipeline.  Matches the `transcribe`
    // command's default branch.
    let specific_options = opts.provider.is_some() || opts.model.is_some() || opts.diarize;
    if let Some(ref audio) = input_audio_file {
        if !specific_options {
            if let crate::recording_cache::TranscriptStatus::Available(text) =
                crate::recording_cache::get_transcript(audio)
            {
                log::info!(
                    "pick file present for {} — pasting without new transcription",
                    audio.display()
                );
                paste_with_root(
                    paste_root.as_ref(),
                    target_window.as_ref(),
                    &text,
                    replace_char_count.unwrap_or(0),
                    None,
                    &crate::telemetry::NoOpSink,
                    paste_timing,
                    // Cached-transcript path has no sound player wired.
                    None,
                )
                .await?;
                let _ = recording_cache::write_last_paste_state(target_window.as_deref(), &text);
                println!("{}", text);
                return Ok(());
            }
        }
    }

    // Resolve recording feedback before GTK, capture-source construction, and
    // Bluetooth switching, preserving dictate's established sound-device
    // initialization order.  The two source branches below use these exact
    // rates (16 kHz file input, 48 kHz live PipeWire capture).
    let feedback_capture_rate = if input_audio_file.is_some() {
        AudioConfig::new().sample_rate
    } else {
        48_000
    };
    let viz_mode = opts.viz.or_else(|| {
        config
            .indicators
            .as_ref()
            .and_then(|indicators| indicators.viz)
    });
    if let Some(mode) = viz_mode {
        log::info!("visualizer mode: {}", mode);
    }
    let (silence_tx, silence_rx) = std::sync::mpsc::channel::<bool>();
    let broker = std::sync::Arc::new(BroadcastSink::new(256));
    let sink: std::sync::Arc<dyn TelemetrySink> = broker.clone();
    let suppress_boop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let boop_interval_ms = config
        .indicators
        .as_ref()
        .map(|indicators| indicators.boop_interval_ms)
        .unwrap_or(5_000);
    let mut feedback = RecordingFeedback::new(RecordingFeedbackOptions {
        no_sounds: opts.no_sounds,
        no_boop: opts.no_boop,
        no_overlay: opts.no_overlay,
        viz: viz_mode,
        mono: opts.mono,
        boop_interval_ms,
        capture_rate: feedback_capture_rate,
        pause_audio: true,
        suppress_boop: Some(suppress_boop.clone()),
        overlay: RecordingOverlayOptions {
            silence_tx: Some(silence_tx),
            auto_pause: !opts.no_auto_pause,
            telemetry_rx: Some(broker.subscribe()),
        },
    });

    // Ensure GTK4/GDK4 is initialised so the overlay and visualizer can
    // query monitor geometry via GDK.  `gtk4::init()` is idempotent —
    // safe to call even if the picker path already initialised it.
    if let Err(e) = gtk4::init() {
        log::warn!(
            "GTK4 init failed (overlay/visualizer may be unavailable): {}",
            e
        );
    }

    // Overlay is created AFTER capture_rate is determined (see below),
    // because it needs the sample rate and a shared ring buffer.

    // Initialize visualizer (text panel for status messages / live
    // transcription text).  Audio visualization has moved into the
    // overlay badge itself — the visualizer thread only handles text.
    let visualizer = match VisualizerHandle::new(opts.realtime) {
        Ok(h) => {
            log::debug!("visualizer text panel initialized");
            Some(h)
        }
        Err(e) => {
            log::warn!("visualizer unavailable: {}", e);
            None
        }
    };

    // Generate cache recording path (always, even without --save)
    let (cache_path, _cache_timestamp) = recording_cache::generate_recording_path()?;
    log::info!("cache recording: {}", cache_path.display());

    let provider = resolve_provider(opts.provider, &config);
    let effective_model = resolve_model(opts.model.as_deref(), &config, provider, opts.realtime);

    // Create audio source: live microphone or audio file input.
    //
    // For live capture, record at the device's native rate (typically
    // 48 kHz) and downsample to 16 kHz with a proper anti-aliasing
    // filter.  PCM WAV input is assumed to be 16 kHz already; OGG/Opus
    // input is decoded by `OggFileSource`.
    let encode_config = AudioConfig::new(); // 16 kHz target for encoder
    let from_file = input_audio_file.is_some();
    let (mut capture, capture_rate): (Box<dyn AudioCapture>, u32) =
        if let Some(ref path) = input_audio_file {
            log::info!("using audio file input: {}", path.display());
            let is_ogg = path
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("ogg"));
            let source: Box<dyn AudioCapture> = if is_ogg {
                Box::new(OggFileSource::new(path)?)
            } else {
                Box::new(WavFileSource::new(path, &encode_config)?)
            };
            (source, encode_config.sample_rate)
        } else {
            // Prefer PipeWire native capture — matches pw-cat's audio
            // routing (including Bluetooth devices) exactly.  Fall back
            // to cpal/ALSA if PipeWire is unavailable.
            let rate = 48_000u32; // PipeWire native rate; resampled to 16 kHz downstream
            let capture_config = AudioConfig {
                sample_rate: rate,
                channels: encode_config.channels,
                bitrate: encode_config.bitrate,
            };
            if opts.monitor {
                log::info!(
                    "capture at {}Hz (PipeWire, mic+monitor), target {}Hz",
                    rate,
                    encode_config.sample_rate
                );
                (
                    Box::new(MonitorCapture::new(capture_config)) as Box<dyn AudioCapture>,
                    rate,
                )
            } else {
                log::info!(
                    "capture at {}Hz (PipeWire), target {}Hz",
                    rate,
                    encode_config.sample_rate
                );
                (
                    Box::new(PipeWireCapture::new(capture_config)) as Box<dyn AudioCapture>,
                    rate,
                )
            }
        };

    // Register SIGINT handler early — before any long-running resources
    // (PipeWire capture, sound playback) — so that a quick toggle-off
    // is never missed.  Without this, there is a ~1 s race window
    // between capture.start() and the ctrl_c().await inside
    // dictate_oneshot/dictate_realtime where SIGINT has no handler
    // and the daemon becomes an unkillable orphan.
    let shutdown = CancellationToken::new();
    let shutdown_clone = shutdown.clone();
    let daemon_pid = std::process::id();
    tokio::spawn(async move {
        log::warn!(
            "[DBG] daemon {}: ctrl_c handler task polled, registering handler",
            daemon_pid
        );
        let _ = tokio::signal::ctrl_c().await;
        log::warn!(
            "[DBG] daemon {}: SIGINT received! cancelling shutdown token",
            daemon_pid
        );
        shutdown_clone.cancel();
    });

    log::info!(
        "starting {} transcription{}",
        if opts.realtime {
            "realtime"
        } else {
            "one-shot"
        },
        if from_file { " (from file)" } else { "" }
    );

    // Bluetooth headset profile auto-switching.
    //
    // Only meaningful when we are about to capture live audio — file
    // inputs read from disk and never touch the microphone.  Resolution
    // order: CLI flag `--no-bt-auto-switch` wins; otherwise config
    // `audio.bt_auto_switch` (default `true`).  When enabled we:
    //
    // 1. Recover any stale profile from a prior unclean termination
    //    (the state file at $XDG_RUNTIME_DIR/talk-rs/card-profile.json
    //    is left behind by SIGKILL/crash).  This must run BEFORE
    //    activate_headset so we are restoring to the user's TRUE
    //    original profile, not to whatever HFP profile was active when
    //    the previous run died.
    // 2. Switch any connected BT headset to its best HFP profile so
    //    the headset microphone is enabled.  The returned guard is
    //    moved into dictate_oneshot / dictate_realtime, where it is
    //    triggered explicitly the moment `capture.stop()` returns —
    //    so the user gets A2DP audio back IMMEDIATELY on toggle-off,
    //    not only after the transcription + paste pipeline finishes.
    //    The guard's Drop is also the safety net for early ?-returns
    //    and panics on the path between activation and dispatch.
    //
    // Failures are logged but never fatal; the dictation proceeds on
    // whatever input device is currently active.
    let bt_auto_switch_enabled = !opts.no_bt_auto_switch
        && config
            .audio
            .as_ref()
            .map(|a| a.bt_auto_switch_enabled())
            .unwrap_or(true);
    let bt_guard = if from_file || !bt_auto_switch_enabled {
        if !bt_auto_switch_enabled {
            log::debug!("bt_profile: auto-switching disabled by config/flag");
        }
        bt_profile::HeadsetGuard::new(None)
    } else {
        if let Err(err) = bt_profile::recover_stale_profile() {
            log::warn!("bt_profile: stale-recovery failed (non-fatal): {}", err);
        }
        let saved = match bt_profile::activate_headset() {
            Ok(s) => s,
            Err(err) => {
                log::warn!("bt_profile: activate_headset failed (non-fatal): {}", err);
                None
            }
        };
        bt_profile::HeadsetGuard::new(saved)
    };

    // The start sound is awaited before capture so it cannot enter the
    // recording.  Recording-phase badge and boop begin after capture starts.
    feedback.play_start().await;
    let raw_audio_rx = capture.start()?;
    feedback.initialize_after_capture();

    // Parakeet is a local backend whose model must be downloaded once
    // (~640 MB).  The transcribe pipeline never downloads silently, so
    // for the toggle/dictate flow we download it HERE — before
    // recording starts — showing a "downloading model" badge.  For
    // this non-interactive surface, selecting the Parakeet provider is
    // the consent (user-confirmed).  No-op once the model is installed.
    #[cfg(feature = "parakeet")]
    if provider == Provider::Parakeet {
        let status = crate::transcription::parakeet::consent::resolve(&config)?;
        if !status.present {
            if let Some(o) = feedback.overlay() {
                o.show(IndicatorKind::DownloadingModel);
            }
            log::info!(
                "parakeet model not found at {}; downloading before recording",
                status.model_dir.display()
            );
            crate::transcription::parakeet::model::download_model(
                &status.model_dir,
                status.variant,
            )
            .await?;
        }
    }

    // Show visualizer text panel (positioned relative to recording badge)
    if let Some(ref viz) = visualizer {
        log::debug!("showing visualizer text panel");
        feedback.show_recording_badge();
        viz.show(crate::x11::overlay::BADGE_W);
    } else {
        feedback.show_recording_badge();
    }
    feedback.start_boop();

    // Tee audio through the shared feedback component.  Dictate keeps its
    // existing auto-pause forwarding policy; record selects pass-through.
    let raw_for_resample = if feedback.overlay().is_some() {
        let teed = feedback.route_audio(raw_audio_rx);
        // Spawn silence notification thread: forwards silence events
        // from the overlay to the visualizer text panel and plays
        // periodic alert sounds when no audio is detected.
        let vis_push = visualizer.as_ref().map(|v| v.message_pusher());
        let alert_player = feedback.player().map(|player| player.alert_player());
        if vis_push.is_some() || alert_player.is_some() {
            let suppress = suppress_boop.clone();
            let _ = std::thread::Builder::new()
                .name("silence-notifier".into())
                .spawn(move || {
                    let mut alerting = false;
                    loop {
                        let event = if alerting {
                            match silence_rx.recv_timeout(std::time::Duration::from_secs(2)) {
                                Ok(val) => Some(val),
                                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                                    // Still silent — replay alert sound.
                                    if let Some(ref ap) = alert_player {
                                        ap.play();
                                    }
                                    None
                                }
                                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
                            }
                        } else {
                            match silence_rx.recv() {
                                Ok(val) => Some(val),
                                Err(_) => break,
                            }
                        };

                        if let Some(is_silent) = event {
                            if is_silent {
                                alerting = true;
                                suppress.store(true, std::sync::atomic::Ordering::Relaxed);
                                if let Some(ref push) = vis_push {
                                    push(
                                        "No audio detected \u{2014} check your microphone"
                                            .to_string(),
                                    );
                                }
                                // Play alert immediately on first detection.
                                if let Some(ref ap) = alert_player {
                                    ap.play();
                                }
                            } else {
                                alerting = false;
                                suppress.store(false, std::sync::atomic::Ordering::Relaxed);
                            }
                        }
                    }
                });
        }
        teed
    } else {
        raw_audio_rx
    };

    // Set up the resample pipeline (common to both modes).  Audio has
    // been buffering in the capture channel since capture.start() above.
    let capture_chunk = (capture_rate as usize * CHUNK_DURATION_MS as usize) / 1000;
    let audio_rx = resample::spawn_resample_task(
        capture_rate,
        encode_config.sample_rate,
        raw_for_resample,
        capture_chunk,
    )?;

    if opts.diarize && opts.realtime {
        return Err(TalkError::Config(
            "--diarize is not supported with --realtime: \
             the Mistral realtime WebSocket endpoint does not support speaker diarization"
                .to_string(),
        ));
    }

    let mut t_stop: Option<std::time::Instant> = None;
    let result = if opts.realtime {
        // Realtime mode (--realtime): stream audio over WebSocket.
        // Each segment is pasted into the focused application as it
        // arrives, providing real-time feedback while dictating.

        // Save clipboard and focus target window before recording starts.
        // Each segment is pasted whole (no chunking) — match legacy
        // behaviour by routing through the configured paste tree with
        // chunk wrappers stripped.
        let rt_guard = RealtimeClipboardGuard::begin(paste_timing).await;
        if let Some(ref wid) = target_window {
            log::debug!("pre-focusing target window: {}", wid);
            if !focus_window(wid).await {
                log::warn!("could not pre-focus target window {}", wid);
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }

        // Build the realtime-flavoured root: strip chunk wrappers
        // so each segment is pasted as a single clipboard call.
        let rt_root: std::sync::Arc<dyn PasteNode> = match config.paste.as_ref() {
            Some(p) => std::sync::Arc::from(p.build_root(true)),
            None => std::sync::Arc::from(default_root(true)),
        };

        // Create segment channel for per-segment pasting
        let (seg_tx, mut seg_rx) = tokio::sync::mpsc::channel::<String>(32);

        // Spawn paste consumer: each segment is pasted immediately
        // through the SAME node tree used by the one-shot path.
        let rt_root_for_task = rt_root.clone();
        let paste_task = tokio::spawn(async move {
            let mut is_first = true;
            let mut seg_idx = 0usize;
            // Per-segment guard reuses the rt_guard's clipboard via a
            // fresh per-call PasteCtx; legacy parity requires that
            // every segment uses the same X11Clipboard so the settle
            // loop at end-of-stream observes a meaningful serve
            // counter.  RealtimeClipboardGuard carries the shared
            // clipboard and exposes paste_segment() for this purpose.
            while let Some(segment) = seg_rx.recv().await {
                seg_idx += 1;
                let paste_text = if is_first {
                    is_first = false;
                    segment
                } else {
                    format!(" {}", segment)
                };
                log::trace!(
                    "paste(realtime): segment {} <- {}",
                    seg_idx,
                    crate::paste::log_preview(&paste_text),
                );
                if let Err(e) = rt_guard
                    .paste_segment(
                        rt_root_for_task.as_ref(),
                        &paste_text,
                        &crate::telemetry::NoOpSink,
                    )
                    .await
                {
                    log::warn!("per-segment paste failed: {}", e);
                }
            }
            rt_guard.finish().await;
        });

        let result = match dictate_realtime(
            config.clone(),
            provider,
            opts.model.as_deref(),
            &cache_path,
            audio_rx,
            &mut *capture,
            from_file,
            &mut feedback,
            Some(seg_tx),
            visualizer.as_ref(),
            &shutdown,
            bt_guard,
        )
        .await
        {
            Ok(r) => r,
            Err(e) => {
                // Enrich model-not-found errors with available models.
                let enriched =
                    transcription::enrich_model_error(&config, provider, opts.model.as_deref(), e)
                        .await;
                return Err(enriched);
            }
        };

        // Wait for the paste task to drain every segment and run
        // its end-of-stream settle + restore (inside `rt_guard.finish()`).
        if let Err(e) = paste_task.await {
            log::warn!("paste task error: {}", e);
        }

        result
    } else {
        // One-shot mode (default): capture audio, encode, then transcribe.
        // Dictate is an autonomous pipeline (no human watching),
        // so use `Proportional` so a hung server cannot wedge the
        // pipeline forever.
        let mut transcriber = transcription::create_oneshot_transcriber(
            &config,
            provider,
            opts.model.as_deref(),
            opts.diarize,
            transcription::RequestTimeoutPolicy::Proportional,
        )?;
        transcriber.set_sink(sink.clone());

        let (stream_result, t_stop_val) = dictate_oneshot(
            &mut *capture,
            from_file,
            encode_config.clone(),
            audio_rx,
            &cache_path,
            transcriber,
            &shutdown,
            &mut feedback,
            visualizer.as_ref(),
            &config,
            provider,
            opts.model.as_deref(),
            opts.diarize,
            bt_guard,
        )
        .await;
        t_stop = t_stop_val;

        // If the one-shot transcription failed, fall back to a
        // single call to `transcribe_audio` using the saved OGG
        // file.  Retry lives inside `transcribe_audio` (see
        // `transcription::transport::retry`) — no loop here.
        match stream_result {
            Ok(r) => r,
            Err(first_err) => {
                log::warn!("one-shot transcription failed: {}", first_err);

                // Fall back to file-based transcription.  Retry is
                // already handled by Layer 3.  Same `Proportional`
                // policy as the one-shot path above — autonomous
                // dictate must not hang.
                let result = transcription::transcribe_audio(
                    &cache_path,
                    &config,
                    provider,
                    opts.model.as_deref(),
                    opts.diarize,
                    transcription::TranscribeOptions {
                        allow_api: true,
                        policy: transcription::RequestTimeoutPolicy::Proportional,
                        cancel_token: None,
                        skip_legacy_lock: false,
                    },
                    &sink,
                )
                .await;

                match result {
                    Ok(r) => r,
                    Err(final_err) => {
                        // Model errors get enriched with available
                        // models (display concern).  Other errors are
                        // already after-retry permanent failures.
                        let final_err = if transcription::is_model_error(provider, &final_err) {
                            transcription::enrich_model_error(
                                &config,
                                provider,
                                opts.model.as_deref(),
                                final_err,
                            )
                            .await
                        } else {
                            final_err
                        };
                        let final_msg = format!("{}", final_err);
                        log::error!("{}", final_msg);
                        if let Some(ref viz) = visualizer {
                            viz.push_message(&format!("Error: {}", final_msg));
                        }
                        if let Some(o) = feedback.overlay() {
                            o.hide();
                        }
                        return Ok(());
                    }
                }
            }
        }
    };

    if let Some(t) = t_stop {
        log::info!(
            "timing: stop +{}ms transcription_done",
            t.elapsed().as_millis()
        );
    }

    // Idempotent recording-phase teardown; mode-specific paths may already
    // have cancelled the boop at the instant capture stopped.
    feedback.teardown_recording(RecordingBadgeTeardown::KeepVisible);

    // For realtime mode, play stop sound and hide visualizer here
    // (one-shot mode already did this inside dictate_oneshot on SIGINT).
    if opts.realtime {
        feedback.play_stop().await;
        if let Some(ref viz) = visualizer {
            log::debug!("hiding visualizer");
            viz.hide();
        }
        if let Some(o) = feedback.overlay() {
            log::debug!("hiding overlay");
            o.hide();
        }
    }
    // One-shot mode: overlay is still showing "Transcribing" badge —
    // it will be hidden after paste (below).

    let text = crate::transcription::format_transcription_output(&result, opts.timestamp)
        .trim()
        .to_string();
    let segments = result.segments;
    let metadata = result.metadata;

    // Write the authoritative pick file UNLESS the user asked for a
    // specific model/provider/diarize — those are "give me a
    // one-off transcription", not "produce the authoritative
    // transcript for this recording".  Never overwrites an
    // existing pick (user may have edited it).
    let specific_options = opts.provider.is_some() || opts.model.is_some() || opts.diarize;
    if !specific_options {
        if let Err(e) = recording_cache::write_pick_if_absent(
            &cache_path,
            &provider.to_string(),
            &effective_model,
            opts.realtime,
            &text,
        ) {
            log::warn!("failed to write pick file: {}", e);
        }
    }

    // Write recording cache metadata and rotate old entries.
    let result_for_cache = transcription::TranscriptionResult {
        text: text.clone(),
        metadata: metadata.clone(),
        diarization: result.diarization.clone(),
        segments: segments.clone(),
    };
    let cache_meta_path = recording_cache::TranscriptionCache::store(
        &cache_path,
        provider,
        &effective_model,
        opts.realtime,
        &result_for_cache,
    );
    if let Err(ref e) = cache_meta_path {
        log::warn!("failed to write recording metadata: {}", e);
    }
    if let Ok(ref meta_path) = cache_meta_path {
        if let Err(e) = recording_cache::write_last_pointers(&cache_path, meta_path) {
            log::warn!("failed to update last recording pointers: {}", e);
        }
    }
    if let Err(e) = recording_cache::rotate_cache() {
        log::warn!("failed to rotate recording cache: {}", e);
    }

    // Copy cache OGG to --save path if specified
    if let Some(ref path) = save_path {
        if let Err(e) = std::fs::copy(&cache_path, path) {
            log::warn!("failed to copy recording to {}: {}", path.display(), e);
        } else {
            log::info!("audio saved to: {}", path.display());
        }
    }

    // Copy cache metadata YAML to --output-yaml path if specified
    if let Some(ref yaml_path) = opts.output_yaml {
        match cache_meta_path {
            Ok(ref src) => {
                if let Err(e) = std::fs::copy(src, yaml_path) {
                    log::warn!("failed to copy metadata to {}: {}", yaml_path.display(), e);
                } else {
                    log::info!("metadata YAML saved to: {}", yaml_path.display());
                }
            }
            Err(_) => {
                log::warn!("skipping --output-yaml: cache metadata was not written");
            }
        }
    }

    if text.is_empty() {
        log::warn!(
            "[DBG] daemon {}: empty transcription, exiting normally",
            std::process::id()
        );
        log::warn!("empty transcription — nothing to paste");
        // Hide transcribing overlay and visualizer (one-shot mode keeps
        // them visible until now).
        if !opts.realtime {
            if let Some(o) = feedback.overlay() {
                o.hide();
            }
        }
        return Ok(());
    }

    log::info!("transcription: {}", text);

    // Paste into focused application (one-shot mode only;
    // realtime mode pastes per-segment during recording)
    if !opts.realtime && !opts.no_paste {
        // Keep the overlay visible during paste so the phase layer
        // continues to show.  Emit telemetry events so consumers
        // can track the paste duration on the time axis.
        sink.emit(TranscriptionEvent::PasteStarted {
            t: std::time::Instant::now(),
        });
        if let Some(t) = t_stop {
            log::info!("timing: stop +{}ms paste_start", t.elapsed().as_millis());
        }
        // Wire the alert tone into the paste path so a FINAL paste
        // abort (target-confirmation retries exhausted) plays the same
        // triple-pulse used by the dead-audio "NO SOUND" feature,
        // alongside the red overlay driven by the `Failed` telemetry
        // event.  `None` when sound is disabled / unavailable.
        let paste_alert: Option<std::sync::Arc<dyn Fn() + Send + Sync>> =
            feedback.player().map(|p| {
                let ap = p.alert_player();
                std::sync::Arc::new(move || ap.play()) as std::sync::Arc<dyn Fn() + Send + Sync>
            });
        paste_with_root(
            paste_root.as_ref(),
            target_window.as_ref(),
            &text,
            0,
            t_stop,
            &*sink,
            paste_timing,
            paste_alert,
        )
        .await?;
        let _ = recording_cache::write_last_paste_state(target_window.as_deref(), &text);
        sink.emit(TranscriptionEvent::PasteCompleted {
            t: std::time::Instant::now(),
        });
        // Hide AFTER paste so the overlay stays visible throughout.
        if let Some(o) = feedback.overlay() {
            o.hide();
        }
    }

    // Print transcription to stdout (one-shot mode only;
    // realtime mode already prints segments as they arrive)
    if !opts.realtime {
        println!("{}", text);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn test_dictate_pipeline_with_mocks() {
        use crate::audio::mock::MockAudioCapture;
        use crate::audio::{AudioCapture, AudioWriter, OggOpusWriter};
        use crate::clipboard::{Clipboard, MockClipboard};
        use crate::config::AudioConfig;
        use crate::transcription::{MockOneShotTranscriber, OneShotTranscriber, TranscriptionBody};

        let audio_config = AudioConfig::new();

        // Initialize mock capture
        let mut capture =
            MockAudioCapture::new(audio_config.sample_rate, audio_config.channels, 440.0);
        let audio_rx = capture.start().expect("start capture");

        // Initialize writer
        let mut writer = OggOpusWriter::new(audio_config).expect("create writer");

        // Create stream channel
        let (stream_tx, stream_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(25);

        // Spawn encode task (process a few chunks then stop)
        let encode_task = tokio::spawn(async move {
            let mut rx = audio_rx;
            let mut count = 0;
            let header = writer.header().expect("header");
            if stream_tx.send(header).await.is_err() {
                return;
            }
            while let Some(pcm_chunk) = rx.recv().await {
                let encoded = writer.write_pcm(&pcm_chunk).expect("encode");
                if !encoded.is_empty() && stream_tx.send(encoded).await.is_err() {
                    break;
                }
                count += 1;
                if count >= 3 {
                    break;
                }
            }
            // Finalize
            let remaining = writer.finalize().expect("finalize");
            if !remaining.is_empty() {
                let _ = stream_tx.send(remaining).await;
            }
            // stream_tx dropped here
        });

        // Spawn transcription with mock
        let transcriber = MockOneShotTranscriber::new("Hello world from dictation");
        let transcribe_task = tokio::spawn(async move {
            transcriber
                .fetch_transcription(TranscriptionBody::Pipe {
                    chunks: stream_rx,
                    file_name: "audio.ogg".to_string(),
                })
                .await
        });

        // Wait for encode to finish
        encode_task.await.expect("encode task");

        // Stop capture
        capture.stop().expect("stop capture");

        // Get transcription
        let result = transcribe_task
            .await
            .expect("transcribe task")
            .expect("transcription");
        let text = result.text;
        assert_eq!(text, "Hello world from dictation");

        // Test clipboard operations with mock
        let clipboard = MockClipboard::with_content("original");
        let saved = clipboard.get_text().await.expect("get clipboard");
        assert_eq!(saved, "original");

        clipboard.set_text(&text).await.expect("set clipboard");
        let current = clipboard.get_text().await.expect("get clipboard");
        assert_eq!(current, "Hello world from dictation");

        // Restore
        clipboard.set_text(&saved).await.expect("restore clipboard");
        let restored = clipboard.get_text().await.expect("get clipboard");
        assert_eq!(restored, "original");
    }
}