opencode-voice 0.1.4

A cli utility to control opencode using voice via the HTTP API
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
//! CLI argument parsing and application configuration.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::PathBuf;

/// Whisper model size selection.
///
/// English-only variants (`*.en`) are fine-tuned on English and slightly more
/// accurate for standard accents.  Multilingual variants are trained on 99
/// languages and handle accented English better because they've seen more
/// diverse phonetic patterns.
#[derive(Debug, Clone)]
pub enum ModelSize {
    TinyEn,
    BaseEn,
    SmallEn,
    Tiny,
    Base,
    Small,
}

impl Default for ModelSize {
    fn default() -> Self {
        ModelSize::BaseEn
    }
}

impl std::fmt::Display for ModelSize {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ModelSize::TinyEn => write!(f, "tiny.en"),
            ModelSize::BaseEn => write!(f, "base.en"),
            ModelSize::SmallEn => write!(f, "small.en"),
            ModelSize::Tiny => write!(f, "tiny"),
            ModelSize::Base => write!(f, "base"),
            ModelSize::Small => write!(f, "small"),
        }
    }
}

impl ModelSize {
    /// Returns `true` for multilingual models (without the `.en` suffix).
    pub fn is_multilingual(&self) -> bool {
        matches!(self, ModelSize::Tiny | ModelSize::Base | ModelSize::Small)
    }
}

impl std::str::FromStr for ModelSize {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "tiny.en" => Ok(ModelSize::TinyEn),
            "base.en" => Ok(ModelSize::BaseEn),
            "small.en" => Ok(ModelSize::SmallEn),
            "tiny" => Ok(ModelSize::Tiny),
            "base" => Ok(ModelSize::Base),
            "small" => Ok(ModelSize::Small),
            _ => Err(anyhow::anyhow!(
                "Unknown model size: {}. Valid: tiny.en, tiny, base.en, base, small.en, small",
                s
            )),
        }
    }
}

/// OpenCode voice input CLI tool.
#[derive(Parser, Debug)]
#[command(name = "opencode-voice", about = "Voice input for OpenCode", version)]
pub struct CliArgs {
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// OpenCode server port (required for the run subcommand)
    #[arg(long, short = 'p', global = true)]
    pub port: Option<u16>,

    /// Audio device name
    #[arg(long, global = true)]
    pub device: Option<String>,

    /// Whisper model size (tiny.en, base.en, small.en)
    #[arg(long, short = 'm', global = true)]
    pub model: Option<ModelSize>,

    /// Toggle key character (default: space)
    #[arg(long, short = 'k', global = true)]
    pub key: Option<char>,

    /// Global hotkey name (default: right_option)
    #[arg(long, global = true)]
    pub hotkey: Option<String>,

    /// Disable global hotkey, use terminal key only
    #[arg(long = "no-global", global = true)]
    pub no_global: bool,

    /// Enable push-to-talk mode (default: true)
    #[arg(
        long = "push-to-talk",
        global = true,
        overrides_with = "no_push_to_talk"
    )]
    pub push_to_talk: bool,

    /// Disable push-to-talk mode
    #[arg(long = "no-push-to-talk", global = true)]
    pub no_push_to_talk: bool,

    /// Enable auto-submit after transcription (default: true)
    #[arg(long = "auto-submit", global = true, overrides_with = "no_auto_submit")]
    pub auto_submit: bool,

    /// Disable auto-submit
    #[arg(long = "no-auto-submit", global = true)]
    pub no_auto_submit: bool,

    /// Handle OpenCode permission and question prompts via voice (default: true)
    #[arg(
        long = "handle-prompts",
        global = true,
        overrides_with = "no_handle_prompts"
    )]
    pub handle_prompts: bool,

    /// Disable voice handling of OpenCode prompts
    #[arg(long = "no-handle-prompts", global = true)]
    pub no_handle_prompts: bool,

    /// Debug mode: log key events, audio info, transcripts to stderr; skip OpenCode
    #[arg(long, global = true)]
    pub debug: bool,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Run the voice mode (default)
    Run,
    /// Download and set up the whisper model
    Setup {
        /// Model size to download (tiny, base, small, tiny.en, base.en, small.en)
        #[arg(long, short = 'm')]
        model: Option<ModelSize>,
    },
    /// List available audio input devices
    Devices,
    /// List available key names for hotkey configuration
    Keys,
}

/// Resolved application configuration.
#[derive(Debug, Clone)]
pub struct AppConfig {
    pub whisper_model_path: PathBuf,
    pub opencode_port: u16,
    pub toggle_key: char,
    pub model_size: ModelSize,
    pub auto_submit: bool,
    pub server_password: Option<String>,
    pub data_dir: PathBuf,
    pub audio_device: Option<String>,
    pub use_global_hotkey: bool,
    pub global_hotkey: String,
    pub push_to_talk: bool,
    pub handle_prompts: bool,
    pub debug: bool,
}

impl AppConfig {
    /// Load configuration from CLI args + environment variables + defaults.
    /// Precedence: CLI flags > env vars > defaults.
    pub fn load(cli: &CliArgs) -> Result<Self> {
        let data_dir = get_data_dir();

        // Port: CLI > env var > default (0 in debug mode) > error
        let port_env = std::env::var("OPENCODE_VOICE_PORT")
            .ok()
            .and_then(|s| s.parse::<u16>().ok());
        let port = cli
            .port
            .or(port_env)
            .or(if cli.debug { Some(0) } else { None })
            .context("OpenCode server port is required. Use --port or set OPENCODE_VOICE_PORT")?;

        // Model: CLI > env var > default
        let model_env = std::env::var("OPENCODE_VOICE_MODEL")
            .ok()
            .and_then(|s| s.parse::<ModelSize>().ok());
        let model_size = cli.model.clone().or(model_env).unwrap_or_default();

        // Device: CLI > env var
        let device_env = std::env::var("OPENCODE_VOICE_DEVICE").ok();
        let audio_device = cli.device.clone().or(device_env);

        // Password: env var only
        let server_password = std::env::var("OPENCODE_SERVER_PASSWORD").ok();

        // Boolean flags: explicit overrides, then defaults
        let auto_submit = if cli.no_auto_submit {
            false
        } else if cli.auto_submit {
            true
        } else {
            true
        };
        let push_to_talk = if cli.no_push_to_talk {
            false
        } else if cli.push_to_talk {
            true
        } else {
            true
        };
        let use_global_hotkey = !cli.no_global;
        let handle_prompts = if cli.no_handle_prompts {
            false
        } else if cli.handle_prompts {
            true
        } else {
            true
        };
        let whisper_model_path = crate::transcribe::setup::get_model_path(&data_dir, &model_size);

        Ok(AppConfig {
            opencode_port: port,
            toggle_key: cli.key.unwrap_or(' '),
            model_size,
            auto_submit,
            server_password,
            data_dir,
            audio_device,
            use_global_hotkey,
            global_hotkey: cli
                .hotkey
                .clone()
                .unwrap_or_else(|| "right_option".to_string()),
            push_to_talk,
            handle_prompts,
            debug: cli.debug,
            whisper_model_path,
        })
    }
}

/// Returns the platform-appropriate data directory for opencode-voice.
///
/// - macOS: ~/Library/Application Support/opencode-voice/
/// - Linux: $XDG_DATA_HOME/opencode-voice/ or ~/.local/share/opencode-voice/
pub fn get_data_dir() -> PathBuf {
    #[cfg(target_os = "macos")]
    {
        dirs::data_dir()
            .unwrap_or_else(|| {
                dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join("Library")
                    .join("Application Support")
            })
            .join("opencode-voice")
    }
    #[cfg(not(target_os = "macos"))]
    {
        // Linux: XDG_DATA_HOME or ~/.local/share
        std::env::var("XDG_DATA_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join(".local")
                    .join("share")
            })
            .join("opencode-voice")
    }
}

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

    #[test]
    fn test_model_size_display() {
        assert_eq!(ModelSize::TinyEn.to_string(), "tiny.en");
        assert_eq!(ModelSize::BaseEn.to_string(), "base.en");
        assert_eq!(ModelSize::SmallEn.to_string(), "small.en");
    }

    #[test]
    fn test_model_size_from_str() {
        assert!(matches!(
            "tiny.en".parse::<ModelSize>().unwrap(),
            ModelSize::TinyEn
        ));
        assert!(matches!(
            "tiny".parse::<ModelSize>().unwrap(),
            ModelSize::Tiny
        ));
        assert!(matches!(
            "base.en".parse::<ModelSize>().unwrap(),
            ModelSize::BaseEn
        ));
        assert!(matches!(
            "base".parse::<ModelSize>().unwrap(),
            ModelSize::Base
        ));
        assert!(matches!(
            "small.en".parse::<ModelSize>().unwrap(),
            ModelSize::SmallEn
        ));
        assert!(matches!(
            "small".parse::<ModelSize>().unwrap(),
            ModelSize::Small
        ));
    }

    #[test]
    fn test_model_size_from_str_invalid() {
        assert!("large".parse::<ModelSize>().is_err());
        assert!("medium.en".parse::<ModelSize>().is_err());
    }

    #[test]
    fn test_model_size_default() {
        assert!(matches!(ModelSize::default(), ModelSize::BaseEn));
    }

    #[test]
    fn test_get_data_dir_contains_app_name() {
        let dir = get_data_dir();
        let dir_str = dir.to_string_lossy();
        assert!(
            dir_str.contains("opencode-voice"),
            "data dir should contain 'opencode-voice': {}",
            dir_str
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_get_data_dir_macos() {
        let dir = get_data_dir();
        let dir_str = dir.to_string_lossy();
        // On macOS should be under Library/Application Support
        assert!(
            dir_str.contains("Library/Application Support"),
            "macOS data dir should be under Library/Application Support: {}",
            dir_str
        );
    }

    // --- Additional tests added to expand coverage ---

    #[test]
    fn test_model_size_display_tiny_en() {
        assert_eq!(ModelSize::TinyEn.to_string(), "tiny.en");
    }

    #[test]
    fn test_model_size_display_base_en() {
        assert_eq!(ModelSize::BaseEn.to_string(), "base.en");
    }

    #[test]
    fn test_model_size_display_small_en() {
        assert_eq!(ModelSize::SmallEn.to_string(), "small.en");
    }

    #[test]
    fn test_model_size_fromstr_roundtrip_tiny() {
        let s = ModelSize::TinyEn.to_string();
        let parsed: ModelSize = s.parse().unwrap();
        assert!(matches!(parsed, ModelSize::TinyEn));
    }

    #[test]
    fn test_model_size_fromstr_roundtrip_base() {
        let s = ModelSize::BaseEn.to_string();
        let parsed: ModelSize = s.parse().unwrap();
        assert!(matches!(parsed, ModelSize::BaseEn));
    }

    #[test]
    fn test_model_size_fromstr_roundtrip_small() {
        let s = ModelSize::SmallEn.to_string();
        let parsed: ModelSize = s.parse().unwrap();
        assert!(matches!(parsed, ModelSize::SmallEn));
    }

    #[test]
    fn test_model_size_fromstr_short_aliases_are_multilingual() {
        // "tiny", "base", "small" (without .en) map to multilingual variants
        assert!(matches!(
            "tiny".parse::<ModelSize>().unwrap(),
            ModelSize::Tiny
        ));
        assert!(matches!(
            "base".parse::<ModelSize>().unwrap(),
            ModelSize::Base
        ));
        assert!(matches!(
            "small".parse::<ModelSize>().unwrap(),
            ModelSize::Small
        ));
    }

    #[test]
    fn test_model_size_is_multilingual() {
        assert!(!ModelSize::TinyEn.is_multilingual());
        assert!(!ModelSize::BaseEn.is_multilingual());
        assert!(!ModelSize::SmallEn.is_multilingual());
        assert!(ModelSize::Tiny.is_multilingual());
        assert!(ModelSize::Base.is_multilingual());
        assert!(ModelSize::Small.is_multilingual());
    }

    #[test]
    fn test_model_size_fromstr_unknown_returns_error() {
        let result = "large.en".parse::<ModelSize>();
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("large.en"),
            "Error should mention the unknown value"
        );
    }

    #[test]
    fn test_get_data_dir_is_absolute() {
        let dir = get_data_dir();
        assert!(
            dir.is_absolute(),
            "data dir should be an absolute path: {:?}",
            dir
        );
    }

    #[test]
    fn test_get_data_dir_ends_with_opencode_voice() {
        let dir = get_data_dir();
        let last_component = dir.file_name().unwrap().to_string_lossy();
        assert_eq!(last_component, "opencode-voice");
    }

    /// Test AppConfig default field values by constructing a minimal struct literal.
    /// This verifies the documented defaults: auto_submit=true, push_to_talk=true,
    /// handle_prompts=true, use_global_hotkey=true.
    #[test]
    fn test_app_config_default_field_values() {
        let config = AppConfig {
            whisper_model_path: std::path::PathBuf::from("/tmp/model.bin"),
            opencode_port: 3000,
            toggle_key: ' ',
            model_size: ModelSize::TinyEn,
            auto_submit: true,
            server_password: None,
            data_dir: std::path::PathBuf::from("/tmp"),
            audio_device: None,
            use_global_hotkey: true,
            global_hotkey: "right_option".to_string(),
            push_to_talk: true,
            handle_prompts: true,
            debug: false,
        };

        assert!(config.auto_submit, "auto_submit default should be true");
        assert!(config.push_to_talk, "push_to_talk default should be true");
        assert!(
            config.handle_prompts,
            "handle_prompts default should be true"
        );
        assert!(
            config.use_global_hotkey,
            "use_global_hotkey default should be true"
        );
        assert_eq!(config.toggle_key, ' ', "toggle_key default should be space");
        assert_eq!(config.global_hotkey, "right_option");
        assert!(config.server_password.is_none());
        assert!(config.audio_device.is_none());
    }

    #[test]
    fn test_app_config_opencode_port() {
        let config = AppConfig {
            whisper_model_path: std::path::PathBuf::from("/tmp/model.bin"),
            opencode_port: 8080,
            toggle_key: ' ',
            model_size: ModelSize::BaseEn,
            auto_submit: true,
            server_password: None,
            data_dir: std::path::PathBuf::from("/tmp"),
            audio_device: None,
            use_global_hotkey: true,
            global_hotkey: "right_option".to_string(),
            push_to_talk: true,
            handle_prompts: true,
            debug: false,
        };

        assert_eq!(config.opencode_port, 8080);
    }
}