croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! Voice input for the Termux on-screen keyboard.
//!
//! croft's OSK replaces Android's native soft keyboard (Termux mouse tracking
//! suppresses it), which also removes the keyboard's mic button. This module
//! restores voice dictation by delegating to the `termux-api` package, which
//! drives Android's system `SpeechRecognizer` (the same engine Gboard's mic
//! uses). croft never captures audio or ships a model itself, mirroring how it
//! delegates directory ranking to the host `zoxide`.
//!
//! It calls `termux-dialog speech`, NOT `termux-speech-to-text`, and the
//! difference is the entire fix. Both wrap the same recognizer, but their
//! `RecognitionListener`s diverge on one line: the `termux-speech-to-text`
//! service closes its output stream on `onEndOfSpeech` (which fires the instant
//! you pause), and that races *ahead* of `onResults` - so the final, best
//! transcript is discarded and the caller sees at most buffered partials, or
//! nothing when the recognizer emits no partials (the "No speech detected" /
//! hang we hit). `termux-dialog speech`'s `onEndOfSpeech` is a no-op; it returns
//! `onResults` - the final transcript - as JSON `{"code":..,"text":".."}` (with
//! an `"error"` field on failure) and exits. It also requests `RECORD_AUDIO`
//! itself, so a denied mic surfaces as a real error rather than silence.
//!
//! The mic is a tap, not push-to-talk: Termux turns any finger hold into its
//! own text-selection gesture (hardcoded in TerminalView, unsuppressible from a
//! TUI), so a sustained press can never reach croft. A tap opens the system
//! speech dialog; speaking and then pausing commits the transcript, and the
//! dialog owns cancellation (its own button, or a second mic tap kills it).

use std::io::Read;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

use crate::jobs::{Job, Poll, Start};

/// The name of the thread that reads a voice session's result, which the
/// crash notice names.
pub const THREAD: &str = "croft-voice";

use crate::lsp::log_file;

/// The Termux:API CLI that fronts Android's `SpeechRecognizer`. The `speech`
/// dialog widget (`termux-dialog speech`) returns the final `onResults`
/// transcript as JSON; the `termux-speech-to-text` service discards it (see the
/// module doc), so `termux-dialog` is the binary croft drives.
const BINARY: &str = "termux-dialog";

/// `termux-dialog` widget that opens the system speech recognizer.
const SPEECH_WIDGET: &str = "speech";

/// Shown as the dialog's title while it listens.
const DIALOG_TITLE: &str = "croft voice input";

/// JSON keys in `termux-dialog`'s result object.
const JSON_TEXT: &str = "text";
const JSON_ERROR: &str = "error";

/// The recognizer error code Android raises when Termux:API lacks the mic
/// permission; mapped to an actionable hint instead of a raw code.
const ERR_NO_MIC_PERMISSION: &str = "ERROR_INSUFFICIENT_PERMISSIONS";

/// Installed on Termux from the bootstrap's `pkg`; provides `BINARY` in
/// `$PREFIX/bin` (always on PATH). The Termux:API *app* (APK) must also be
/// present for the command to actually reach Android; a missing app surfaces as
/// a runtime failure, not something `pkg` can fix.
const TERMUX_INSTALL_PKG: &str = "pkg install -y termux-api";

/// Whether the host can do voice input at all, and if not, why.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Availability {
    /// Termux with `termux-speech-to-text` present: good to go.
    Ready,
    /// Not running under Termux; voice input is Termux-only.
    NeedsTermux,
    /// Termux, but the `termux-api` package is not installed yet.
    NeedsApi,
}

/// Outcome of one push-to-talk session, delivered to the app's per-tick drain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceMsg {
    /// Recognized text to inject into the focused pane.
    Transcript(String),
    /// The session ended without recognizing anything.
    Empty,
    /// The session could not run (spawn error, recognizer missing, ...).
    Failed(String),
}

/// True while a recognition session is live; drives the mic key's armed glow
/// and the status-line "Listening" hint. A process-global flag so the OSK
/// render path can read it without app plumbing (one relaxed atomic load).
static LISTENING: AtomicBool = AtomicBool::new(false);

pub fn is_listening() -> bool {
    LISTENING.load(Ordering::Relaxed)
}

fn set_listening(on: bool) {
    LISTENING.store(on, Ordering::Relaxed);
}

/// Lifecycle of the one background `termux-api` install attempt per process,
/// surfaced so the mic key can tell the user to wait / retry. Mirrors the
/// zoxide installer's state machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallState {
    Idle = 0,
    Running = 1,
    Done = 2,
    Failed = 3,
}

static INSTALL_STATE: AtomicU8 = AtomicU8::new(0);

fn set_install_state(state: InstallState) {
    INSTALL_STATE.store(state as u8, Ordering::Relaxed);
}

pub fn install_state() -> InstallState {
    match INSTALL_STATE.load(Ordering::Relaxed) {
        1 => InstallState::Running,
        2 => InstallState::Done,
        3 => InstallState::Failed,
        _ => InstallState::Idle,
    }
}

/// `$PREFIX/bin/<BINARY>` existence (cheap, no subprocess), with a `command -v`
/// fallback for non-standard layouts.
fn binary_present() -> bool {
    if let Some(prefix) = std::env::var_os("PREFIX")
        && crate::proc::find::runnable(&PathBuf::from(prefix).join("bin").join(BINARY))
    {
        return true;
    }
    Command::new("sh")
        .arg("-c")
        .arg(format!("command -v {BINARY}"))
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Whether voice input is usable here, and why not when it isn't.
pub fn availability() -> Availability {
    if !crate::iterm2_inline::detect_termux() {
        Availability::NeedsTermux
    } else if binary_present() {
        Availability::Ready
    } else {
        Availability::NeedsApi
    }
}

/// Install `termux-api` on a detached thread so the mic press never blocks the
/// UI; the user retries the mic once it lands. Best-effort and idempotent: a
/// second press while `Running` is a no-op at the call site.
pub fn ensure_api_installed_in_background() {
    if matches!(install_state(), InstallState::Running) {
        return;
    }
    set_install_state(InstallState::Running);
    thread::spawn(|| {
        match Command::new("sh")
            .arg("-c")
            .arg(TERMUX_INSTALL_PKG)
            .output()
        {
            Ok(out) if out.status.success() => {
                log_file::log(&format!("voice: `{TERMUX_INSTALL_PKG}` succeeded"))
            }
            Ok(out) => log_file::log(&format!(
                "voice: `{TERMUX_INSTALL_PKG}` exited {}: {}",
                out.status,
                String::from_utf8_lossy(&out.stderr).trim()
            )),
            Err(e) => log_file::log(&format!(
                "voice: `{TERMUX_INSTALL_PKG}` could not start: {e}"
            )),
        }
        if binary_present() {
            set_install_state(InstallState::Done);
        } else {
            set_install_state(InstallState::Failed);
        }
    });
}

/// Handle to a live recognition session: lets the app kill the client process
/// on a second mic tap. Dropping it without `stop()` leaves the session to
/// finish on Android's own end-of-speech detection.
pub struct VoiceHandle {
    child: Arc<Mutex<Option<Child>>>,
    /// The session's result, read on a thread of its own. A reader that
    /// crashed reads as dead, so the session ends instead of listening for
    /// good (#2602). `None` once it has answered.
    result: Option<Job<VoiceMsg>>,
}

impl VoiceHandle {
    /// Cancel the dialog now (a second mic tap). `termux-dialog` is a wrapper
    /// script whose `termux-api` child inherits the stdout pipe, so killing the
    /// script alone leaves that child holding the pipe open and the reader never
    /// sees EOF. `start` put the tree in its own process group (setsid), so
    /// signal the whole group: that takes down `termux-api` too, the pipe
    /// closes, and the reader finalizes. The happy path does not need this - the
    /// dialog returns on its own when you stop speaking - it is only the escape
    /// hatch for an abandoned session.
    pub fn stop(&self) {
        if let Ok(mut guard) = self.child.lock()
            && let Some(child) = guard.as_mut()
        {
            #[cfg(unix)]
            unsafe {
                libc::kill(-(child.id() as i32), libc::SIGKILL);
            }
            let _ = child.kill();
        }
    }

    /// The session's result, nothing yet, or that its reader crashed, once:
    /// after either it reads as still waiting. A crashed reader never
    /// cleared the listening flag, so it is cleared here, and the dialog it
    /// was reading is closed and reaped.
    pub fn poll(&mut self) -> Poll<VoiceMsg> {
        let Some(result) = &self.result else {
            return Poll::Pending;
        };
        let poll = result.poll();
        if !matches!(poll, Poll::Pending) {
            self.result = None;
        }
        if matches!(poll, Poll::Died) {
            // Nothing will read the dialog's answer or reap it now: close it
            // as a cancel tap would, and reap it, so it does not keep the
            // microphone after the session has ended (#2603 review).
            self.stop();
            if let Some(mut child) = self.child.lock().ok().and_then(|mut guard| guard.take()) {
                let _ = child.wait();
            }
            set_listening(false);
        }
        poll
    }
}

#[cfg(test)]
impl VoiceHandle {
    /// A session whose recognizer has already exited with `msg`: how the
    /// app holds its handle between the reader finishing and the frame loop
    /// draining it.
    pub fn finished(msg: VoiceMsg) -> Self {
        VoiceHandle {
            child: Arc::new(Mutex::new(None)),
            result: Some(Job::finished(msg)),
        }
    }

    /// A session whose reader crashed before it had a result (#2602).
    pub fn crashed() -> Self {
        VoiceHandle {
            child: Arc::new(Mutex::new(None)),
            result: Some(
                Job::spawn(THREAD, Start::Now, || {
                    panic!("the voice reader crashed (on purpose, in a test)")
                })
                .unwrap(),
            ),
        }
    }
}

/// Start a recognition session. Spawns `termux-dialog speech` and reads its
/// single JSON result object on a background job, whose result is the
/// recognized text as the transcript (or `Failed`/`Empty` on a recognizer
/// error or nothing heard). Returns a handle the app keeps to read that
/// result and to cancel on a second mic tap. On a spawn failure the session
/// never opens and its result is `VoiceMsg::Failed`.
pub fn start() -> VoiceHandle {
    set_listening(true);
    // `termux-dialog speech` opens the system speech dialog and prints one JSON
    // object - `{"code":..,"text":".."[, "error":".."]}` - when the recognizer
    // finalizes (`onResults`) or fails (`onError`), then exits. Unlike the
    // `termux-speech-to-text` service it does NOT close on `onEndOfSpeech`, so
    // the final transcript is actually delivered (see the module doc). stderr is
    // captured for diagnosis.
    let mut cmd = Command::new(BINARY);
    cmd.arg(SPEECH_WIDGET)
        .arg("-t")
        .arg(DIALOG_TITLE)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    // Run the wrapper script in its own session/process group so `stop` can
    // signal the whole tree (script + `termux-api`) as a unit; otherwise the
    // `termux-api` child survives, holds the stdout pipe, and the reader hangs.
    #[cfg(unix)]
    unsafe {
        cmd.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    }
    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => {
            set_listening(false);
            log_file::log(&format!("voice: could not start `{BINARY}`: {e}"));
            return VoiceHandle {
                child: Arc::new(Mutex::new(None)),
                result: Some(Job::finished(VoiceMsg::Failed(format!(
                    "voice input unavailable: {e}"
                )))),
            };
        }
    };
    let mut stdout = child.stdout.take();
    let mut stderr = child.stderr.take();
    let shared: Arc<Mutex<Option<Child>>> = Arc::new(Mutex::new(Some(child)));
    let reader_shared = Arc::clone(&shared);
    let reader = Job::spawn(THREAD, Start::Now, move || {
        // The dialog prints a single small JSON object at end-of-speech; read it
        // whole rather than line-by-line.
        let mut json = String::new();
        if let Some(stdout) = stdout.as_mut() {
            let _ = stdout.read_to_string(&mut json);
        }
        // Drain stderr and reap, so a recognizer-side failure (no Termux:API
        // app, no speech-recognition service) leaves a real signal in the log.
        let mut err = String::new();
        if let Some(stderr) = stderr.as_mut() {
            let _ = stderr.read_to_string(&mut err);
        }
        // Take the child out of the shared slot before reaping it. A cancel tap
        // can still arrive after this (the app has not drained the result
        // yet), and `stop` must then find nothing to signal: once reaped, the
        // pid and its process group id are free for the system to reuse.
        // Waiting outside the lock also keeps such a `stop` from blocking the
        // UI thread until the dialog exits.
        let child = reader_shared.lock().ok().and_then(|mut guard| guard.take());
        let status = child.and_then(|mut child| child.wait().ok());
        set_listening(false);
        let parsed = serde_json::from_str::<serde_json::Value>(json.trim()).ok();
        let field = |key: &str| -> String {
            parsed
                .as_ref()
                .and_then(|v| v.get(key))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim()
                .to_string()
        };
        let text = field(JSON_TEXT);
        let rec_err = field(JSON_ERROR);
        log_file::log(&format!(
            "voice: dialog ended status={status:?} text_chars={} error={rec_err:?} stderr={:?}",
            text.chars().count(),
            err.trim()
        ));
        if !text.is_empty() {
            VoiceMsg::Transcript(text)
        } else if rec_err == ERR_NO_MIC_PERMISSION {
            VoiceMsg::Failed(String::from(
                "Grant Termux:API microphone permission, then tap the mic again",
            ))
        } else if !rec_err.is_empty() {
            VoiceMsg::Failed(format!("Voice input error: {rec_err}"))
        } else {
            VoiceMsg::Empty
        }
    });
    let handle = VoiceHandle {
        child: shared,
        result: None,
    };
    match reader {
        Ok(reader) => VoiceHandle {
            result: Some(reader),
            ..handle
        },
        // No thread to read the dialog's answer: close the dialog rather
        // than leave it listening for nobody.
        Err(e) => {
            handle.stop();
            set_listening(false);
            VoiceHandle {
                result: Some(Job::finished(VoiceMsg::Failed(format!(
                    "voice input unavailable: {e}"
                )))),
                ..handle
            }
        }
    }
}

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

    #[test]
    fn install_state_round_trips_through_the_atomic() {
        set_install_state(InstallState::Running);
        assert_eq!(install_state(), InstallState::Running);
        set_install_state(InstallState::Done);
        assert_eq!(install_state(), InstallState::Done);
        set_install_state(InstallState::Idle);
        assert_eq!(install_state(), InstallState::Idle);
    }

    /// #2603 review: a session whose reader crashed closes the dialog it
    /// was reading, its whole process group, and reaps it, so it does not
    /// keep the microphone after the session has ended.
    #[cfg(unix)]
    #[test]
    fn a_session_whose_reader_crashed_closes_its_dialog() {
        let mut cmd = Command::new("sleep");
        cmd.arg("30");
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }
        let child = cmd.spawn().unwrap();
        let pid = child.id() as i32;
        let mut handle = VoiceHandle {
            child: Arc::new(Mutex::new(Some(child))),
            result: Some(
                Job::spawn(THREAD, Start::Now, || {
                    panic!("the voice reader crashed (on purpose, in a test)")
                })
                .unwrap(),
            ),
        };
        let mut died = false;
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(1),
            "the reader's death",
            || {
                died |= matches!(handle.poll(), Poll::Died);
                died
            },
        );
        assert!(
            handle.child.lock().unwrap().is_none(),
            "the dialog is reaped"
        );
        // Reaped, so the pid names no process at all.
        assert_eq!(unsafe { libc::kill(pid, 0) }, -1, "the dialog is gone");
    }

    #[test]
    fn listening_flag_round_trips() {
        set_listening(true);
        assert!(is_listening());
        set_listening(false);
        assert!(!is_listening());
    }
}