Skip to content

extra: Move Speech into nsh-extra and recognize speech on Android, Windows and the web - #2947

Merged
madcodelife merged 3 commits into
mainfrom
extra-speech
Nov 23, 2026
Merged

madcodelife merged 3 commits into
mainfrom
extra-speech

Conversation

@madcodelife

@madcodelife madcodelife commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Description

What

Speech (speech recognition) leaves NSH's runtime and becomes the speech module of nsh-extra, and it now recognizes speech on Android, Windows and the web as well as macOS and iOS.

nsh add nsh-extra --features speech
import { Speech, type SpeechSession } from "nsh-extra";

if (await Speech.available()) {
  const session: SpeechSession = Speech.start({ lang: "en-US", interim: true });
  session.on("result", ({ text }) => draft.set(text));
}

The JS API keeps its shape: Speech.available(), Speech.start(options), SpeechSession's events, stop / abort, and the error names. Only the specifier changes.

Platform Recognizer
macOS, iOS the Speech framework fed by the microphone (moved from nsh-platform-apple)
Android android.speech.SpeechRecognizer, RECORD_AUDIO asked when a session starts; available() is false on devices without a recognition service
Windows Windows.Media.SpeechRecognition's continuous dictation; it uses the user's online speech recognition setting, and a session ends with not-allowed while it is off
Web the browser's Web Speech API (SpeechRecognition / webkitSpeechRecognition), through wasm-bindgen; available() is false where the browser has none
Linux, terminal apps (the TUI host, on every OS) none: available() is false and a session ends with unavailable

An app embedded with GPUI uses the platform's recognizer on macOS and Windows.

One session runs at a time in the process: the microphone is one, so starting another ends the one running. A new session of the same app ends it without an error, as abort() does; a session another app of the process starts (an embedding app's other AppView) ends it with error: "audio-capture", the microphone could not be used. A session an app refuses (speech not granted) ends nothing.

Packaging

The CLI no longer adds NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription to every iOS and macOS app. nsh-extra declares what the module needs under [package.metadata.nsh.features.speech], so only apps that turn speech on get them:

  • iOS and macOS: the two usage descriptions; macOS also com.apple.security.device.audio-input.
  • Android: RECORD_AUDIO and a <queries> entry for android.speech.RecognitionService.
  • Windows and the web need no declaration.

The speech capability stays: the module checks it in every function of its JS face (as Push checks notifications) and for sessions Rust code starts.

Generic extension points

The module is built only on hooks any third-party nshm can use:

  • nsh_core::element::access(): the running engine's capabilities, for checks in Rust.
  • nsh_core::element::engine_id(): which engine the calling code runs in, so a module whose state is the process's (one microphone) tells its apps' requests apart.
  • nsh_core::fake::Fake and Registry::fake: a module's stand-in for headless runs. nsh test installs the fakes of the app's sets before the app starts and routes app.fake(name, method, args) to them; the speech fake's methods (hear, end, requests) are documented with the module. A fake may stand in process-wide, so headless apps with different fakes take turns in one process (two #[test]s); the apps one nsh test file opens share theirs. nsh/test keeps no speech-specific calls.
  • nsh-platform-android's proxy::implement: implements Java interfaces (listeners, Runnable) in Rust through java.lang.reflect.Proxy, so an nshm needs no Java classes of its own.

Also

  • nsh reads the version a workspace member inherits (version.workspace = true), so an nshm developed in a Cargo workspace works as a "path" dependency.
  • examples/extra: a small app that turns on nsh-extra and holds the speech tests (moved from examples/gallery, which stays TSX-only). Its tests run in rust-app.yml.
  • apple: Keep each app's speech session its own, and end it when its app stops #2667's fixes to the Apple code this PR moves are kept, for every platform: sessions are matched by ids unique in the process (one app's stop / abort never reaches another's, nor does a late callback a later session); a session another app displaces ends with audio-capture; a session whose app stops is aborted by its own drop, which reaches the platform without going through the engine, so the microphone turns off (a_session_ends_when_its_app_stops). nsh-platform-apple's per-surface speech::Listener goes with the rest of the runtime's speech code.
  • The compat case mod-speech is removed: compat apps link only NSH's runtime, not nshm. nsh-extra's API is covered by its crate tests and examples/extra.

Why

docs/dev/js-modules.md puts a system feature only some apps use, which would add permissions or store declarations to every app, in nsh-extra, with the runtime keeping only generic hooks. Speech is such a feature: every iOS and macOS app without declared capabilities carried the microphone and speech recognition usage descriptions, whether it dictated or not. Moving it also lets each platform's recognizer live in one place, so the module now covers Android, Windows and the web.

Public API

nsh-extra (feature speech), TS:

  • Speech.available(): Promise<boolean>, Speech.start(options?: SpeechOptions): SpeechSession, SpeechSession (on, text, ended, stop, abort): moved from nsh, unchanged.

nsh_extra::speech, Rust:

  • async fn available() -> bool: whether speech can be recognized here.
  • fn recognize(SpeechRequest) -> SpeechRecognition: starts a session; SpeechRecognition (next().await / poll_next, stop, abort; dropping it aborts).
  • fn set_backend(Option<Arc<dyn SpeechBackend>>): an embedding app's own recognizer, process-wide.
  • SpeechRequest { lang, interim } (non-exhaustive, Default), SpeechEvent, SpeechError (ALL: &'static [SpeechError], as_str, from_name, Display), SpeechSink (send, start, result, end, is_ended), trait SpeechControl, trait SpeechBackend (available, start).
  • Feature speech; [package.metadata.nsh.features.speech] (see Packaging).

nsh-core:

  • element::access() -> Option<Arc<access::Access>>: the running engine's capabilities; None on no engine's thread.
  • element::engine_id() -> Option<EngineId>, element::EngineId (opaque, Copy, Eq, Hash, never reused in the process): which engine the calling code runs in.
  • fake::Fake (install(&self), call(&self, method: &str, args: &[JsonValue]) -> Result<JsonValue, String>): a module's stand-in for headless runs.
  • Registry::fake(&mut self, name: &'static str, fake: Arc<dyn Fake>) -> &mut Self; fake names are unique across the sets an app is served (Registry::merged panics otherwise). Registry::fakes (what the headless driver installs) is #[doc(hidden)].
  • Removed (moved to nsh_extra::speech): speech module, speech_available, recognize_speech, SpeechRecognition, Core::set_speech, Environment::speech (in runtime and element), Command::Speech, the root Speech event.

nsh-platform-apple:

  • Removed: speech (command(control, command)), now inside nsh-extra.

nsh-engine:

  • Removed: EngineConfig::speech (now nsh_extra::speech::set_backend).

nsh-testing / nsh/test:

  • Headless::call_fake(name, method, args) -> Result<JsonValue, String>; TS app.fake(name: string, method: string, args?: unknown[]): Promise<unknown>.
  • Headless::start waits while apps with other fakes run in the process (above).
  • Removed: SpeechRequest, Headless's speech methods, TS app.hear(text), app.endSpeech(error?), app.speechRequests(); tests call the fake.

nsh-platform-android (nsh):

  • proxy::implement(env, interfaces: &[&str], handler) -> jni::errors::Result<Proxy>, proxy::Proxy (#[must_use], as_obj): Java interfaces implemented in Rust. Only interfaces; a method returning a primitive gets a boxed value.

CLI:

  • Apps no longer get the speech usage descriptions by default; nsh-extra's speech feature declares them.
  • A "path" nshm whose Cargo.toml inherits its version from its workspace is read.

Breaking Changes

Nothing here is in a recorded release (docs/dev/compatibility.md), so Speech moves without an alias.

- import { Speech, type SpeechSession } from "nsh";
+ import { Speech, type SpeechSession } from "nsh-extra"; // nsh add nsh-extra --features speech
- use nsh_core::speech::{SpeechEvent, SpeechRequest};
- let available = speech_available().await;
- let session = recognize_speech(request);
+ use nsh_extra::speech::{self, SpeechEvent, SpeechRequest};
+ let available = speech::available().await;
+ let session = speech::recognize(request);
- EngineConfig { speech: Some(backend), .. }
+ nsh_extra::speech::set_backend(Some(backend));
- expect(app.speechRequests()).toEqual([{ lang: "en-US", interim: true }]);
- await app.hear("hello");
- await app.endSpeech("network");
+ expect(await app.fake("nsh-extra/speech", "requests")).toEqual([{ lang: "en-US", interim: true }]);
+ await app.fake("nsh-extra/speech", "hear", ["hello"]);
+ await app.fake("nsh-extra/speech", "end", ["network"]);

A session another app displaces now ends with error: "audio-capture" instead of no error.

How to Test

Ran on macOS:

  • cargo test -p nsh-extra --features nsh-extra/camera,nsh-extra/photos,nsh-extra/push,nsh-extra/speech: 71 unit tests, and the extra test binary: a_session_ends_when_its_app_stops, an_app_with_other_fakes_waits_for_the_one_running (two headless apps with registries of their own take turns; it failed before the fix, app A's test reaching app B's fake), apps_with_the_same_fakes_run_together
  • Unit tests of the displacement and ordering rules: a_new_session_ends_the_one_running, another_engines_session_ends_the_one_running_with_audio_capture, a_stale_start_changes_nothing; fake_names_are_unique_across_sets in nsh-core
  • cargo test -p nsh-core -p nsh-engine -p nsh-testing, cargo test -p nsh-testing --features bundle --test testing, cargo test -p nsh-engine --features websocket websocket
  • nsh test examples/extra: 4 passed, through app.fake("nsh-extra/speech", ...)
  • cargo clippy -- -D warnings: the workspace; nsh-extra with every feature; the macOS and Catalyst lines with nsh-extra/speech; nsh-extra for x86_64-pc-windows-msvc and wasm32-unknown-unknown
  • cargo xtask clippy-android: clean for nsh-platform-android and nsh-extra apart from missing_const_for_thread_local on thread_local!s that already use const { }, which this toolchain (1.100) also reports in nsh-core on main
  • javac --release 17 -Xlint:all of nsh-platform-android's Java sources against android.jar: compiles, no warning in NativeProxy.java
  • cargo +nightly fmt --all --check: only files this PR does not touch differ, as on main

Not verified here (devices and browsers):

  • Dictation on an iOS device, a Mac, an Android phone (with and without a recognition service, permission granted and denied), Windows (online speech recognition on and off) and Chrome / Safari.
  • Two AppViews on one device: the displaced app's audio-capture, and the microphone indicator going off when an app stops.
  • nsh package of an app with speech for iOS, macOS and Android: the usage descriptions, the macOS entitlement, RECORD_AUDIO and the <queries> entry in the packaged app.
  • Windows available() off the engine thread: compiled for x86_64-pc-windows-msvc only.
  • On the web, a Rust nshm that calls browser APIs builds with the wasm-bindgen CLI (docs/dev/web.md), so an app with speech needs it installed to build for the web.

Checklist

  • I have read the CONTRIBUTING document and followed the guidelines.
  • Reviewed the changes in this PR and confirmed AI generated code (if any) is accurate.

- A session another engine displaces ends with `audio-capture`; the same
  engine's new session ends it without an error (`element::engine_id()`).
- A refused session ends nothing; a stale platform start changes nothing.
- No recognizer in terminal apps on any OS.
- Headless apps with different fakes take turns in one process; fake names
  are unique across sets; `Registry::fakes` is hidden.
- `nsh/test` drops `app.hear`, `app.endSpeech` and `app.speechRequests`:
  tests call the speech fake through `app.fake`.
- Windows asks WinRT whether speech is available off the engine thread.
- CI lints `nsh-extra` for wasm32; docs follow.
@madcodelife
madcodelife enabled auto-merge (squash) November 23, 2026 14:09
@madcodelife
madcodelife disabled auto-merge November 23, 2026 14:13
@madcodelife
madcodelife merged commit 45d8ee6 into main Nov 23, 2026
12 of 24 checks passed
@madcodelife
madcodelife deleted the extra-speech branch November 23, 2026 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant