The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(voice): move always-on capture into the tinyvoice module
Steven Enamakela62f66616bb9
diff --git a/Cargo.lock b/Cargo.lockindex fa3d1483d7..a7c7b30d02 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -92,28 +92,6 @@ version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"-[[package]]-name = "alsa"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"-dependencies = [- "alsa-sys",- "bitflags 2.13.2",- "cfg-if",- "libc",-]--[[package]]-name = "alsa-sys"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"-dependencies = [- "libc",- "pkg-config",-]-[[package]]name = "ambient-authority"version = "0.0.2"@@ -1126,50 +1104,6 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"-[[package]]-name = "coreaudio-rs"-version = "0.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"-dependencies = [- "bitflags 2.13.2",- "libc",- "objc2-audio-toolbox",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",-]--[[package]]-name = "cpal"-version = "0.18.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"-dependencies = [- "alsa",- "block2",- "coreaudio-rs",- "dasp_sample",- "jni",- "js-sys",- "libc",- "mach2 0.6.0",- "ndk",- "ndk-context",- "num-derive",- "num-traits",- "objc2",- "objc2-audio-toolbox",- "objc2-avf-audio",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",- "web-sys",- "windows 0.62.2",- "windows-core 0.62.2",-]-[[package]]name = "cpubits"version = "0.1.1"@@ -1423,12 +1357,6 @@ dependencies = ["syn 3.0.6",]-[[package]]-name = "dasp_sample"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"-[[package]]name = "data-encoding"version = "2.11.1"@@ -2983,7 +2911,7 @@ dependencies = ["cfg-if","combine","jni-macros",- "jni-sys 0.4.1",+ "jni-sys","log","simd_cesu8","thiserror 2.0.20",@@ -3004,15 +2932,6 @@ dependencies = ["syn 2.0.119",]-[[package]]-name = "jni-sys"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"-dependencies = [- "jni-sys 0.4.1",-]-[[package]]name = "jni-sys"version = "0.4.1"@@ -3320,12 +3239,6 @@ dependencies = ["winapi",]-[[package]]-name = "mach2"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"-[[package]]name = "mach2"version = "0.7.0"@@ -3616,35 +3529,12 @@ dependencies = ["tempfile",]-[[package]]-name = "ndk"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"-dependencies = [- "bitflags 2.13.2",- "jni-sys 0.3.1",- "log",- "ndk-sys",- "num_enum",- "thiserror 1.0.69",-]-[[package]]name = "ndk-context"version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"-[[package]]-name = "ndk-sys"-version = "0.6.0+11769913"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"-dependencies = [- "jni-sys 0.3.1",-]-[[package]]name = "nix"version = "0.29.0"@@ -3812,28 +3702,6 @@ dependencies = ["libc",]-[[package]]-name = "num_enum"-version = "0.7.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"-dependencies = [- "num_enum_derive",- "rustversion",-]--[[package]]-name = "num_enum_derive"-version = "0.7.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"-dependencies = [- "proc-macro-crate",- "proc-macro2",- "quote",- "syn 2.0.119",-]-[[package]]name = "num_threads"version = "0.1.7"@@ -3852,32 +3720,6 @@ dependencies = ["objc2-encode",]-[[package]]-name = "objc2-audio-toolbox"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"-dependencies = [- "bitflags 2.13.2",- "libc",- "objc2",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",-]--[[package]]-name = "objc2-avf-audio"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"-dependencies = [- "bitflags 2.13.2",- "objc2",- "objc2-foundation",-]-[[package]]name = "objc2-cloud-kit"version = "0.3.2"@@ -3889,29 +3731,6 @@ dependencies = ["objc2-foundation",]-[[package]]-name = "objc2-core-audio"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"-dependencies = [- "dispatch2",- "objc2",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",-]--[[package]]-name = "objc2-core-audio-types"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"-dependencies = [- "bitflags 2.13.2",- "objc2",-]-[[package]]name = "objc2-core-data"version = "0.3.2"@@ -4197,7 +4016,6 @@ dependencies = ["tinytools","tinytools-agent","tinytools-std",- "tinyvoice","tinyvoice-bus","tinywallet","tinywallet-bus",@@ -4863,15 +4681,6 @@ dependencies = ["syn 3.0.6",]-[[package]]-name = "proc-macro-crate"-version = "3.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"-dependencies = [- "toml_edit",-]-[[package]]name = "proc-macro2"version = "1.0.107"@@ -6252,7 +6061,7 @@ dependencies = ["cfg-if","lazycell","libc",- "mach2 0.7.0",+ "mach2","nix 0.31.3","num-traits","objc2-core-foundation",@@ -6393,7 +6202,7 @@ dependencies = ["libc","memchr","ntapi",- "windows 0.54.0",+ "windows",][[package]]@@ -7530,18 +7339,6 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"-[[package]]-name = "tinyvoice"-version = "0.1.14"-dependencies = [- "cpal",- "log",- "parking_lot",- "thiserror 2.0.20",- "tinyvoice-bus",- "tokio",-]-[[package]]name = "tinyvoice-bus"version = "0.1.2"@@ -7804,18 +7601,6 @@ dependencies = ["serde_core",]-[[package]]-name = "toml_edit"-version = "0.25.15+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"-dependencies = [- "indexmap",- "toml_datetime",- "toml_parser",- "winnow 1.0.4",-]-[[package]]name = "toml_parser"version = "1.1.3+spec-1.1.0"@@ -8813,27 +8598,6 @@ dependencies = ["windows-targets 0.52.6",]-[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections",- "windows-core 0.62.2",- "windows-future",- "windows-numerics",-]--[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core 0.62.2",-]-[[package]]name = "windows-core"version = "0.54.0"@@ -8857,17 +8621,6 @@ dependencies = ["windows-strings",]-[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core 0.62.2",- "windows-link",- "windows-threading",-]-[[package]]name = "windows-implement"version = "0.60.2"@@ -8896,16 +8649,6 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"-[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core 0.62.2",- "windows-link",-]-[[package]]name = "windows-registry"version = "0.6.1"@@ -9004,15 +8747,6 @@ dependencies = ["windows_x86_64_msvc 0.53.1",]-[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link",-]-[[package]]name = "windows_aarch64_gnullvm"version = "0.52.6"@@ -9123,9 +8857,6 @@ name = "winnow"version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"-dependencies = [- "memchr",-][[package]]name = "winx"diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex 912e5e996f..9173840287 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -81,28 +81,6 @@ version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"-[[package]]-name = "alsa"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"-dependencies = [- "alsa-sys",- "bitflags 2.13.2",- "cfg-if",- "libc",-]--[[package]]-name = "alsa-sys"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"-dependencies = [- "libc",- "pkg-config",-]-[[package]]name = "ambient-authority"version = "0.0.2"@@ -982,50 +960,6 @@ dependencies = ["libc",]-[[package]]-name = "coreaudio-rs"-version = "0.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"-dependencies = [- "bitflags 2.13.2",- "libc",- "objc2-audio-toolbox",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",-]--[[package]]-name = "cpal"-version = "0.18.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"-dependencies = [- "alsa",- "block2",- "coreaudio-rs",- "dasp_sample",- "jni 0.22.4",- "js-sys",- "libc",- "mach2 0.6.0",- "ndk",- "ndk-context",- "num-derive",- "num-traits",- "objc2",- "objc2-audio-toolbox",- "objc2-avf-audio",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",- "web-sys",- "windows 0.62.2",- "windows-core 0.62.2",-]-[[package]]name = "cpufeatures"version = "0.2.17"@@ -1238,12 +1172,6 @@ dependencies = ["syn 3.0.6",]-[[package]]-name = "dasp_sample"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"-[[package]]name = "data-encoding"version = "2.11.1"@@ -3388,12 +3316,6 @@ dependencies = ["uuid",]-[[package]]-name = "mach2"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"-[[package]]name = "mach2"version = "0.7.0"@@ -3568,12 +3490,6 @@ dependencies = ["thiserror 1.0.69",]-[[package]]-name = "ndk-context"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"-[[package]]name = "ndk-sys"version = "0.6.0+11769913"@@ -3699,17 +3615,6 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"-[[package]]-name = "num-derive"-version = "0.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]-[[package]]name = "num-integer"version = "0.1.47"@@ -3802,32 +3707,6 @@ dependencies = ["objc2-quartz-core",]-[[package]]-name = "objc2-audio-toolbox"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"-dependencies = [- "bitflags 2.13.2",- "libc",- "objc2",- "objc2-core-audio",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",-]--[[package]]-name = "objc2-avf-audio"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"-dependencies = [- "bitflags 2.13.2",- "objc2",- "objc2-foundation",-]-[[package]]name = "objc2-cloud-kit"version = "0.3.2"@@ -3839,29 +3718,6 @@ dependencies = ["objc2-foundation",]-[[package]]-name = "objc2-core-audio"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"-dependencies = [- "dispatch2",- "objc2",- "objc2-core-audio-types",- "objc2-core-foundation",- "objc2-foundation",-]--[[package]]-name = "objc2-core-audio-types"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"-dependencies = [- "bitflags 2.13.2",- "objc2",-]-[[package]]name = "objc2-core-data"version = "0.3.2"@@ -4221,7 +4077,6 @@ dependencies = ["tinytools","tinytools-agent","tinytools-std 0.5.0",- "tinyvoice","tinyvoice-bus","tinywallet-bus","tinywallet-crypto",@@ -6240,7 +6095,7 @@ dependencies = ["cfg-if","lazycell","libc",- "mach2 0.7.0",+ "mach2","nix 0.31.3","num-traits","objc2-core-foundation",@@ -7890,18 +7745,6 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"-[[package]]-name = "tinyvoice"-version = "0.1.14"-dependencies = [- "cpal",- "log",- "parking_lot",- "thiserror 2.0.20",- "tinyvoice-bus",- "tokio",-]-[[package]]name = "tinyvoice-bus"version = "0.1.2"@@ -9091,23 +8934,11 @@ version = "0.61.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"dependencies = [- "windows-collections 0.2.0",+ "windows-collections","windows-core 0.61.2",- "windows-future 0.2.1",+ "windows-future","windows-link 0.1.3",- "windows-numerics 0.2.0",-]--[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections 0.3.2",- "windows-core 0.62.2",- "windows-future 0.3.2",- "windows-numerics 0.3.1",+ "windows-numerics",][[package]]@@ -9119,15 +8950,6 @@ dependencies = ["windows-core 0.61.2",]-[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core 0.62.2",-]-[[package]]name = "windows-core"version = "0.57.0"@@ -9150,20 +8972,7 @@ dependencies = ["windows-interface 0.59.3","windows-link 0.1.3","windows-result 0.3.4",- "windows-strings 0.4.2",-]--[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement 0.60.2",- "windows-interface 0.59.3",- "windows-link 0.2.1",- "windows-result 0.4.1",- "windows-strings 0.5.1",+ "windows-strings",][[package]]@@ -9174,18 +8983,7 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"dependencies = ["windows-core 0.61.2","windows-link 0.1.3",- "windows-threading 0.1.0",-]--[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core 0.62.2",- "windows-link 0.2.1",- "windows-threading 0.2.1",+ "windows-threading",][[package]]@@ -9254,16 +9052,6 @@ dependencies = ["windows-link 0.1.3",]-[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core 0.62.2",- "windows-link 0.2.1",-]-[[package]]name = "windows-registry"version = "0.5.3"@@ -9272,7 +9060,7 @@ checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"dependencies = ["windows-link 0.1.3","windows-result 0.3.4",- "windows-strings 0.4.2",+ "windows-strings",][[package]]@@ -9293,15 +9081,6 @@ dependencies = ["windows-link 0.1.3",]-[[package]]-name = "windows-result"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"-dependencies = [- "windows-link 0.2.1",-]-[[package]]name = "windows-strings"version = "0.4.2"@@ -9311,15 +9090,6 @@ dependencies = ["windows-link 0.1.3",]-[[package]]-name = "windows-strings"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"-dependencies = [- "windows-link 0.2.1",-]-[[package]]name = "windows-sys"version = "0.45.0"@@ -9446,15 +9216,6 @@ dependencies = ["windows-link 0.1.3",]-[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link 0.2.1",-]-[[package]]name = "windows-version"version = "0.1.7"diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex 2e0f3c499c..442b4a488c 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -456,10 +456,6 @@ tinydocs-bus = { path = "../../vendor/tinydocs/crates/tinydocs-bus", optional =# Optional: exclusive to the `voice` feature — default-OFF, product-ON, the# same split as `documents` above.tinyvoice-bus = { path = "../../vendor/tinyvoice/crates/tinyvoice-bus", optional = true }-# `cpal` microphone capture (`voice::audio_capture`, `voice::always_on`) remains-# on the library path until its module-owned lifecycle contract is released.-# Hotkeys are already owned by the loaded TinyVoice module.-tinyvoice = { path = "../../vendor/tinyvoice/crates/tinyvoice", default-features = false, features = ["capture"], optional = true }# TinyJuice — the compression wire contract, and nothing else.#@@ -761,7 +757,6 @@ voice = [# only — `serde` and nothing else."dep:tinyvoice-bus","dep:lettre",- "dep:tinyvoice",# Podcast SMTP delivery uses the loadable Channels module. The always-on# bus dependency provides its upload vocabulary without linking providers.# `voice::live`: live voice agent sessions over tinyagents-live.diff --git a/crates/openhuman-core/src/modules/registry/records_voice.rs b/crates/openhuman-core/src/modules/registry/records_voice.rsindex 5afb945e17..7db43dfe7b 100644--- a/crates/openhuman-core/src/modules/registry/records_voice.rs+++ b/crates/openhuman-core/src/modules/registry/records_voice.rs@@ -12,73 +12,70 @@ use crate::modules::types::{LoadPolicy, ModuleRecord, PlatformAsset};/// user has to enable dictation or always-on listening before any of this runs/// — so a session that never speaks should not pay a download or a `dlopen`.///-/// **The VAD deliberately does not come through here.** A segmenter is driven-/// Continuous capture and its device callback are module-owned and read in-/// bounded batches. The VAD remains in the host because it is a local-/// per-frame policy loop; captured samples cross the bus in bounded batches,-/// never through a call made from the audio callback. See [`super::voice`].+/// Devices and audio processing live in the compiled module. Hosts poll bounded+/// capture batches and apply product permission, privacy and transcription policy.pub(crate) const TINYVOICE: ModuleRecord = ModuleRecord {id: "tinyvoice",description: "Wake-word gating, command routing, hallucination detection, capture audio",bus_name: "ai.tinyhumans.tinyvoice.Voice",object_path: "/ai/tinyhumans/tinyvoice/Voice",- version: "0.1.14",- release_url: "https://github.com/tinyhumansai/tinyvoice/releases/tag/v0.1.14",+ version: "0.1.15",+ release_url: "https://github.com/tinyhumansai/tinyvoice/releases/tag/v0.1.15",assets: &[PlatformAsset {host_key: "ubuntu-24.04-x86_64",- archive: "tinyvoice-module-0.1.14-ubuntu-24.04-x86_64.tar.gz",- sha256: "682b56ec246e021708a71a587a9fa55625c3964b10676f9d1220ee4eccdd55a1",+ archive: "tinyvoice-module-0.1.15-ubuntu-24.04-x86_64.tar.gz",+ sha256: "3d56893a20cdb50d305f1d35d535d026a3acd9d92931afc01349f131bc7108e8",},PlatformAsset {host_key: "ubuntu-24.04-arm64",- archive: "tinyvoice-module-0.1.14-ubuntu-24.04-arm64.tar.gz",- sha256: "87cde6de6da8c9d9f392fe43a8547be861363596f64a326cf9deb985e260762d",+ archive: "tinyvoice-module-0.1.15-ubuntu-24.04-arm64.tar.gz",+ sha256: "397409478b8739670f2bd256e9b29120015e366df11189a7484e464b4c0531df",},PlatformAsset {host_key: "ubuntu-22.04-x86_64",- archive: "tinyvoice-module-0.1.14-ubuntu-22.04-x86_64.tar.gz",- sha256: "9bab7b7d6d5e36526f13a02209cd3454ea53ecf8ba68894ffa5f2376765cab71",+ archive: "tinyvoice-module-0.1.15-ubuntu-22.04-x86_64.tar.gz",+ sha256: "412501462ee421e065507023b94451a10559435955954f317969849a4efc8bd9",},PlatformAsset {host_key: "ubuntu-22.04-arm64",- archive: "tinyvoice-module-0.1.14-ubuntu-22.04-arm64.tar.gz",- sha256: "2c77ed20a9745086a1d8e481a7719accaff82464b546671b0070b78610e77628",+ archive: "tinyvoice-module-0.1.15-ubuntu-22.04-arm64.tar.gz",+ sha256: "daa9a5c660a3ec5d6dd3ae9ad08842060383d8c4421bf58934fa070d34c90fa1",},PlatformAsset {host_key: "macos-26-arm64",- archive: "tinyvoice-module-0.1.14-macos-26-arm64.tar.gz",- sha256: "f2856e78eda2f53cacc4799c2a068a5626779f01bff60a792c1f7e37c56324cb",+ archive: "tinyvoice-module-0.1.15-macos-26-arm64.tar.gz",+ sha256: "c25aa3250062f6d02a9442047ea6cb9ab50919923a08bcafea08819a160dd4c7",},PlatformAsset {host_key: "macos-26-x86_64",- archive: "tinyvoice-module-0.1.14-macos-26-x86_64.tar.gz",- sha256: "e4ff4337bcb4fa60c3549e83fe573060d8669b744996fa75d321542b8e6841f3",+ archive: "tinyvoice-module-0.1.15-macos-26-x86_64.tar.gz",+ sha256: "747c2e62f08233cf6657863b1ff9696a0bb9d166126fdde7d717b3c6dac385a1",},PlatformAsset {host_key: "macos-15-arm64",- archive: "tinyvoice-module-0.1.14-macos-15-arm64.tar.gz",- sha256: "c3e6a29cd39617d91463d4315e1dfe432a12f0579116173efac4406a9e2d65a7",+ archive: "tinyvoice-module-0.1.15-macos-15-arm64.tar.gz",+ sha256: "16ef3ee328fb2c51506e8f66c2f3ef5e66b87b3f9505d85834b67bbc3e4b98ff",},PlatformAsset {host_key: "macos-15-x86_64",- archive: "tinyvoice-module-0.1.14-macos-15-x86_64.tar.gz",- sha256: "86d9e654391cf09dc40ac27e0128d614b03ff3853e9bb010b9b31d914e0b1f23",+ archive: "tinyvoice-module-0.1.15-macos-15-x86_64.tar.gz",+ sha256: "1e819f986c59849649c53d75f1a2488a148c1fda3659cd967eaf53d63f2c492b",},PlatformAsset {host_key: "windows-2025-x86_64",- archive: "tinyvoice-module-0.1.14-windows-2025-x86_64.zip",- sha256: "f6a636891710c7443306fdcf6067f24b72b1b98a9873596669377540da0b037b",+ archive: "tinyvoice-module-0.1.15-windows-2025-x86_64.zip",+ sha256: "0cd3476aba36d6aefb7f318a45cbdf5a47efd0668e9a28425aaef2d5bfd72048",},PlatformAsset {host_key: "windows-2022-x86_64",- archive: "tinyvoice-module-0.1.14-windows-2022-x86_64.zip",- sha256: "e5b538e69dfc0cec83adcb6240f09d6d0cb126df76621f8eb63b5da901119baa",+ archive: "tinyvoice-module-0.1.15-windows-2022-x86_64.zip",+ sha256: "ebbde34149317cb306ace5cc61c01abdaa601cecb339c3f2a517f5441858ca46",},PlatformAsset {host_key: "windows-11-arm64",- archive: "tinyvoice-module-0.1.14-windows-11-arm64.zip",- sha256: "8452b6099a0a1debe412e3e69f8591756c5ea49f9e5a112f138fe2e590a0a418",+ archive: "tinyvoice-module-0.1.15-windows-11-arm64.zip",+ sha256: "2701528845188b10f7bcb6b05fc5354d0b733a257325da39b06c68fa1c995398",},],load: LoadPolicy::Lazy,diff --git a/crates/openhuman-core/src/modules/registry_tests.rs b/crates/openhuman-core/src/modules/registry_tests.rsindex f2e688a61b..783e530fdd 100644--- a/crates/openhuman-core/src/modules/registry_tests.rs+++ b/crates/openhuman-core/src/modules/registry_tests.rs@@ -547,3 +547,74 @@ fn tinychannels_registry_matches_health_check_release() {assert_eq!(asset.sha256, sha256);}}++#[cfg(feature = "voice")]+#[test]+fn voice_capture_release_pins_summary_contract_and_every_platform_digest() {+ let record = find("tinyvoice").unwrap();+ assert_eq!(record.version, "0.1.15");+ assert_eq!(tinyvoice_bus::CONTRACT_VERSION, (1, 5));+ let expected = [+ (+ "macos-15-arm64",+ "tinyvoice-module-0.1.15-macos-15-arm64.tar.gz",+ "16ef3ee328fb2c51506e8f66c2f3ef5e66b87b3f9505d85834b67bbc3e4b98ff",+ ),+ (+ "macos-15-x86_64",+ "tinyvoice-module-0.1.15-macos-15-x86_64.tar.gz",+ "1e819f986c59849649c53d75f1a2488a148c1fda3659cd967eaf53d63f2c492b",+ ),+ (+ "macos-26-arm64",+ "tinyvoice-module-0.1.15-macos-26-arm64.tar.gz",+ "c25aa3250062f6d02a9442047ea6cb9ab50919923a08bcafea08819a160dd4c7",+ ),+ (+ "macos-26-x86_64",+ "tinyvoice-module-0.1.15-macos-26-x86_64.tar.gz",+ "747c2e62f08233cf6657863b1ff9696a0bb9d166126fdde7d717b3c6dac385a1",+ ),+ (+ "ubuntu-22.04-arm64",+ "tinyvoice-module-0.1.15-ubuntu-22.04-arm64.tar.gz",+ "daa9a5c660a3ec5d6dd3ae9ad08842060383d8c4421bf58934fa070d34c90fa1",+ ),+ (+ "ubuntu-22.04-x86_64",+ "tinyvoice-module-0.1.15-ubuntu-22.04-x86_64.tar.gz",+ "412501462ee421e065507023b94451a10559435955954f317969849a4efc8bd9",+ ),+ (+ "ubuntu-24.04-arm64",+ "tinyvoice-module-0.1.15-ubuntu-24.04-arm64.tar.gz",+ "397409478b8739670f2bd256e9b29120015e366df11189a7484e464b4c0531df",+ ),+ (+ "ubuntu-24.04-x86_64",+ "tinyvoice-module-0.1.15-ubuntu-24.04-x86_64.tar.gz",+ "3d56893a20cdb50d305f1d35d535d026a3acd9d92931afc01349f131bc7108e8",+ ),+ (+ "windows-11-arm64",+ "tinyvoice-module-0.1.15-windows-11-arm64.zip",+ "2701528845188b10f7bcb6b05fc5354d0b733a257325da39b06c68fa1c995398",+ ),+ (+ "windows-2022-x86_64",+ "tinyvoice-module-0.1.15-windows-2022-x86_64.zip",+ "ebbde34149317cb306ace5cc61c01abdaa601cecb339c3f2a517f5441858ca46",+ ),+ (+ "windows-2025-x86_64",+ "tinyvoice-module-0.1.15-windows-2025-x86_64.zip",+ "0cd3476aba36d6aefb7f318a45cbdf5a47efd0668e9a28425aaef2d5bfd72048",+ ),+ ];+ assert_eq!(record.assets.len(), expected.len());+ for (key, archive, digest) in expected {+ let asset = record.asset_for(key).unwrap();+ assert_eq!(asset.archive, archive);+ assert_eq!(asset.sha256, digest);+ }+}diff --git a/crates/openhuman-core/src/security/credentials/ops/gated_services.rs b/crates/openhuman-core/src/security/credentials/ops/gated_services.rsindex 78075d4a9c..a47db81290 100644--- a/crates/openhuman-core/src/security/credentials/ops/gated_services.rs+++ b/crates/openhuman-core/src/security/credentials/ops/gated_services.rs@@ -208,10 +208,12 @@ pub async fn stop_credential_gated_services(config: &Config) {// accumulate duplicate rdev listeners across logout → login cycles.crate::voice::dictation_listener::stop().await;- // 6. Always-on listening — disable the runtime gate so the mic capture loop- // stops transcribing/delivering after logout (no audio processed while- // logged out). Symmetric with start_login_gated_services step 3b.- crate::voice::always_on::stop();+ // 6. Disable delivery and release module-owned microphone/output leases.+ crate::voice::always_on::shutdown().await;+ #[cfg(feature = "voice")]+ if let Err(error) = crate::voice::capture_lease::close_all().await {+ log::warn!("[services] voice capture cleanup pending: {error}");+ }if let Err(error) = crate::integrations::composio::trigger_history::close_global().await {log::warn!("[composio][history] archive release failed on sign-out: {error}");diff --git a/crates/openhuman-core/src/voice/always_on.rs b/crates/openhuman-core/src/voice/always_on.rsindex 9053625ab8..0d8e22a49e 100644--- a/crates/openhuman-core/src/voice/always_on.rs+++ b/crates/openhuman-core/src/voice/always_on.rs@@ -9,25 +9,16 @@//!//! ## Where the work happens//!-//! Everything that is not device I/O runs in the `tinyvoice` module — the-//! segmenter, the downmix, the resample, the per-frame energies, the WAV-//! framing, the wake-word gate and the intent classifier. This file owns the-//! `cpal` stream, the thread discipline around it, and the policy decisions-//! (what to transcribe, when to pause, what to tell the notch).-//!-//! The split follows the audio callback, not the cost of a call. A module call-//! is ~15 µs against a 20 ms frame, so the bus is not the constraint; the-//! constraint is that `cpal` delivers on a realtime thread where blocking is a-//! dropout. So the callback does the least it can — convert the sample format-//! and forward raw interleaved samples — and every transform happens in the-//! async processor below.+//! Device I/O, callback queues and audio processing run in the loaded TinyVoice+//! module. The host polls bounded batches and owns configuration, permission,+//! transcription routing, privacy gates and lifecycle cleanup.//!//! Privacy: always-on is **opt-in** (`config.voice_server.always_on_enabled`,//! default false) and pauses when the screen is locked.//!//! ## Module layout//!-//! - [`capture`] — the `cpal` stream and its realtime callback.+//! - [`capture`] — bounded bus forwarding and cancellation of the module stream.//! - [`lock_watcher`] — the macOS screen-lock privacy hook.//! - [`processor`] — the async pipeline: VAD session, segmentation, gating.//! - [`transcribe`] — STT, wake-word gating, and local fast-path commands.@@ -37,7 +28,7 @@ mod lock_watcher;mod processor;mod transcribe;-pub use processor::{start_if_enabled, stop};+pub use processor::{shutdown, start_if_enabled, stop};use processor::notch_status;#[cfg(target_os = "macos")]diff --git a/crates/openhuman-core/src/voice/always_on/README.md b/crates/openhuman-core/src/voice/always_on/README.mdindex 14c270cf94..b34ec7dfc3 100644--- a/crates/openhuman-core/src/voice/always_on/README.md+++ b/crates/openhuman-core/src/voice/always_on/README.md@@ -6,7 +6,7 @@ Always-on is opt-in (`config.voice_server.always_on_enabled`, default `false`) a## Where the work happens-Everything that is not device I/O runs in the `tinyvoice` module: the segmenter, the downmix, the resample, the per-frame energies, the WAV framing, the wake-word gate, and the intent classifier. This directory owns the `cpal` stream, the thread discipline around it, and the policy decisions (what to transcribe, when to pause, what to tell the notch).+Device I/O, callback queues, segmentation and audio processing run in the compiled TinyVoice module. This directory owns microphone permission requests through TinyComputer, bounded batch forwarding, transcription routing, privacy gates and lease cleanup.The split follows the audio callback, not the cost of a call. A module call is about 15 microseconds against a 20 ms frame, so the bus is not the constraint. The constraint is that `cpal` delivers audio on a realtime thread where blocking is a dropout, so the callback does the least it can (convert the sample format and forward raw interleaved samples) and every transform happens in the async processor.@@ -14,9 +14,9 @@ The split follows the audio callback, not the cost of a call. A module call is a| File | Role || --- | --- |-| [`capture.rs`](./capture.rs) | Host microphone-permission policy over `tinyvoice::capture`, which owns the `cpal` stream and its realtime callback. `spawn_capture_thread` builds the input stream on a dedicated thread and blocks on a readiness handshake; each callback converts the device sample format to `f32` and forwards the interleaved buffer untouched via `try_send` (never blocking `send`), dropping the newest chunk and counting drops when the processor falls behind. |+| [`capture.rs`](./capture.rs) | Reserves and starts a module-owned stream, polls at most two chunks per call, and forwards ordered batches through a bounded host queue. Cancellation releases the opaque lease; failed cleanup remains tracked for retry. || [`lock_watcher.rs`](./lock_watcher.rs) | The macOS screen-lock privacy hook. `spawn_lock_watcher` polls `CGSessionCopyCurrentDictionary` every two seconds and flips `PAUSED` on lock/unlock transitions. Other platforms log that the watcher is unavailable and never pause (no lock signal yet). |-| [`processor.rs`](./processor.rs) | The async pipeline: owns the `ENABLED`/`PAUSED`/`RUNNING` gates, opens and retries the `tinyvoice::VadSession`, turns raw capture chunks into segmented utterances, and hands finished ones to `transcribe_and_deliver`. `start_if_enabled` is safe to call at boot and at runtime (the Settings toggle calls it through the config RPC); `stop` flips `ENABLED` off for logout without tearing down the microphone stream. |+| [`processor.rs`](./processor.rs) | Owns the enabled/paused gates, VAD session and transcription tasks. Toggle-off and sign-out stop capture, cancel pending transcriptions and drain the processor before restart. || [`transcribe.rs`](./transcribe.rs) | Transcribes a finished utterance through the configured STT provider (the same factory dispatch `voice.stt_dispatch` uses), applies the wake-word gate (`tinyvoice::extract_command`), and routes recognized commands either to a local fast path (`execute_intent`, media transport and volume via `osascript` on macOS) or, for `VoiceIntent::Unknown` or a failed local execution, to the agent via `crate::voice::dictation_listener::publish_transcription`. |`always_on.rs` (one level up, in `voice/`) is the module entry point: it declares these four submodules, re-exports `start_if_enabled`/`stop`, and holds the shared `LOG_PREFIX` constant.@@ -42,7 +42,7 @@ Transcription is forced to English (`Some("en")`) because auto-detect rendered t- The microphone stream is spawned once per process and stays open for the process lifetime once started; toggling `always_on_enabled` off only stops processing, it does not close the stream. Toggling back on reuses it.- A VAD session that fails to open (for example, the module has not finished downloading) does not stop the capture thread. Audio is dropped and the open is retried on `SESSION_RETRY_INTERVAL` so the feature self-heals without a restart.-- `tinyvoice::capture` (via [`capture.rs`](./capture.rs)) never blocks the realtime audio callback: a full queue drops the newest chunk, which is deliberately the newer end to lose, since the queue ahead of it is older speech closer to being transcribed.+- Native callbacks stay inside the module and never wait for bus calls. Its bounded queue drops newest chunks when full; the host polls bounded batches and preserves their order.## See alsodiff --git a/crates/openhuman-core/src/voice/always_on/capture.rs b/crates/openhuman-core/src/voice/always_on/capture.rsindex b85f7b6182..24afa5c0dc 100644--- a/crates/openhuman-core/src/voice/always_on/capture.rs+++ b/crates/openhuman-core/src/voice/always_on/capture.rs@@ -1,16 +1,62 @@-//! Raw microphone capture for the always-on loop.-//!-//! The `cpal` stream, its realtime callback and the bounded-queue forwarding-//! live in `tinyvoice::capture`. This file supplies the host's part: the-//! microphone-permission policy. Downmixing and resampling live in the-//! processor, not in the callback.--pub(super) use tinyvoice::capture::{CaptureFormat, RawChunk};--/// Spawn the dedicated cpal capture thread. Blocks until the stream is set up-/// (or fails), mirroring `audio_capture::start_recording`'s readiness handshake.-pub(super) fn spawn_capture_thread(+//! Bounded batch forwarding from module-owned continuous microphone capture.+use crate::config::Config;+use crate::voice::capture_lease::{CaptureLease, Kind};+pub(super) use tinyvoice_bus::capture::{CaptureFormat, RawChunk};+static STOP: std::sync::LazyLock<tokio::sync::watch::Sender<u64>> =+ std::sync::LazyLock::new(|| tokio::sync::watch::channel(0).0);+pub(super) fn stop_subscription() -> tokio::sync::watch::Receiver<u64> {+ STOP.subscribe()+}+pub(super) fn request_stop() {+ STOP.send_modify(|generation| *generation = generation.wrapping_add(1));+}+/// Owns the forwarding task; cancellation closes its opaque capture lease.+pub(super) struct CapturePump(tokio::task::JoinHandle<()>);+impl Drop for CapturePump {+ fn drop(&mut self) {+ self.0.abort();+ }+}+/// Start a module stream and forward ordered batches to the bounded processor queue.+pub(super) async fn spawn_capture_thread(+ config: &Config,tx: tokio::sync::mpsc::Sender<RawChunk>,-) -> Result<CaptureFormat, String> {- tinyvoice::capture::spawn_capture_thread(tx, || Ok(())).map_err(|e| e.to_string())+) -> Result<(CaptureFormat, CapturePump), String> {+ let lease = CaptureLease::reserve(config, Kind::Stream).await?;+ let stream = lease.start_stream().await?;+ let mut stopped = STOP.subscribe();+ let task = tokio::spawn(async move {+ loop {+ if tx.is_closed() {+ break;+ }+ let reply = tokio::select! {+ biased;+ _ = stopped.changed() => break,+ reply = lease.poll() => reply,+ };+ let batch = match reply {+ Ok(batch) => batch,+ Err(error) => {+ log::warn!("[voice::always_on] capture batch unavailable: {error}");+ break;+ }+ };+ for chunk in batch.chunks {+ tokio::select! {+ biased;+ _ = stopped.changed() => return,+ result = tx.send(chunk) => if result.is_err() { return; },+ }+ }+ if batch.closed {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ if let Err(error) = lease.close().await {+ log::warn!("[voice::always_on] capture cleanup pending: {error}");+ }+ });+ Ok((stream.format, CapturePump(task)))}diff --git a/crates/openhuman-core/src/voice/always_on/processor.rs b/crates/openhuman-core/src/voice/always_on/processor.rsindex 01cd9b58bd..05ccade37c 100644--- a/crates/openhuman-core/src/voice/always_on/processor.rs+++ b/crates/openhuman-core/src/voice/always_on/processor.rs@@ -31,13 +31,22 @@ const SESSION_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_se/// decide whether to send.const CAPTURE_QUEUE_CHUNKS: usize = 256;-/// The capture thread + processor have been spawned (once per process).+/// A module capture lease and processor are active.static RUNNING: AtomicBool = AtomicBool::new(false);+static LIFECYCLE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+static PROCESSOR: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>> =+ std::sync::Mutex::new(None);+struct RunningGuard;+impl Drop for RunningGuard {+ fn drop(&mut self) {+ RUNNING.store(false, Ordering::SeqCst);+ }+}/// Runtime on/off, mirrors `config.voice_server.always_on_enabled`. Toggling it/// at runtime takes effect immediately: when false the processor drops all audio/// (nothing is transcribed or sent). Lets the Settings toggle work without a-/// restart. (The mic stream itself stays open until the next launch.)+/// restart. Disabling capture releases the module stream.pub(super) static ENABLED: AtomicBool = AtomicBool::new(false);/// When true, the processor drops audio and resets the segmenter (privacy hook:@@ -63,6 +72,11 @@ const MAX_UTTERANCE_SAMPLES: usize = TARGET_SAMPLE_RATE as usize * 60;/// routes each finished utterance through STT and the dictation delivery bus (so/// it reaches the agent exactly like a hotkey dictation, and lights up the notch).pub async fn start_if_enabled(app_config: &Config) {+ if !app_config.voice_server.always_on_enabled {+ shutdown().await;+ return;+ }+ let _lifecycle = LIFECYCLE.lock().await;let on = app_config.voice_server.always_on_enabled;ENABLED.store(on, Ordering::SeqCst);if !on {@@ -74,6 +88,7 @@ pub async fn start_if_enabled(app_config: &Config) {return;}+ let running = RunningGuard;if let Err(error) = crate::modules::accessibility::AccessibilityClient::new(app_config).microphone_permission(false).await@@ -92,36 +107,11 @@ pub async fn start_if_enabled(app_config: &Config) {vad.max_utterance_ms);- // The cpal stream is `!Send`, so it lives on a dedicated thread that pushes- // RAW interleaved chunks over a channel to the async processor below —- // deliberately raw: every transform now happens off the audio callback.- // `spawn_capture_thread` blocks on a synchronous readiness handshake while- // the OS builds the input stream — cold WASAPI init on Windows can take a- // while — so run it on the blocking pool. This function is polled- // concurrently with the other login-gated services (#3490), and blocking an- // async worker here would stall them.let (tx, mut rx) = tokio::sync::mpsc::channel::<RawChunk>(CAPTURE_QUEUE_CHUNKS);- log::debug!(- "{LOG_PREFIX} starting microphone capture (blocking readiness handshake on the blocking pool)"- );- // Distinguish a Tokio join failure (the blocking task itself panicked) from a- // `spawn_capture_thread` setup error (e.g. no input device), so the log points- // at the right layer instead of flattening both into one message.- let format = match tokio::task::spawn_blocking(move || spawn_capture_thread(tx)).await {- Ok(Ok(format)) => {- log::debug!("{LOG_PREFIX} microphone capture stream ready");- format- }- Ok(Err(e)) => {- log::warn!("{LOG_PREFIX} could not start microphone capture: {e}");- RUNNING.store(false, Ordering::SeqCst);- return;- }- Err(join_err) => {- log::error!(- "{LOG_PREFIX} microphone capture setup task failed to join (panicked): {join_err}"- );- RUNNING.store(false, Ordering::SeqCst);+ let (format, pump) = match spawn_capture_thread(app_config, tx).await {+ Ok(stream) => stream,+ Err(error) => {+ log::warn!("{LOG_PREFIX} could not start microphone capture: {error}");return;}};@@ -130,20 +120,20 @@ pub async fn start_if_enabled(app_config: &Config) {spawn_lock_watcher();let onset_threshold = vad.onset_threshold;- tokio::spawn(async move {+ let mut stopped = super::capture::stop_subscription();+ let processor = tokio::spawn(async move {+ let _running = running;+ let _pump = pump;// The segmenter lives in the module now, so opening it can fail for// reasons unrelated to audio — a download that has not happened yet, a// host with no published artifact.//- // That failure must NOT end this task. The capture thread is already- // running and owns the microphone for the process lifetime; returning- // here would clear `RUNNING` while the stream stays live, and the next- // `start_if_enabled` would sail past the `RUNNING` guard and open a- // *second* microphone stream. So the session is opened lazily and- // retried, and audio is dropped until there is one.+ // Retain the known capture lease while retrying VAD setup. Cancellation+ // closes both the processor and its module-owned stream.let mut session: Option<tinyvoice::VadSession> = None;let mut last_open_attempt: Option<std::time::Instant> = None;+ let mut transcriptions = tokio::task::JoinSet::new();let mut pending: Vec<f32> = Vec::new();let mut utterance: Vec<f32> = Vec::new();// Test-build diagnostics: confirm audio actually flows from the mic and@@ -154,7 +144,12 @@ pub async fn start_if_enabled(app_config: &Config) {let mut level_frames: u32 = 0;let mut last_level_log = std::time::Instant::now();- while let Some(chunk) = rx.recv().await {+ 'capture: while let Some(chunk) = tokio::select! {+ biased;+ _ = stopped.changed() => None,+ _ = transcriptions.join_next(), if !transcriptions.is_empty() => continue 'capture,+ chunk = rx.recv() => chunk,+ } {if !first_chunk_logged {first_chunk_logged = true;log::info!(@@ -328,7 +323,7 @@ pub async fn start_if_enabled(app_config: &Config) {);if emit {let cfg = config.clone();- tokio::spawn(async move {+ spawn_transcription(&mut transcriptions, &stopped, async move {transcribe_and_deliver(&cfg, captured).await;});}@@ -350,24 +345,36 @@ pub async fn start_if_enabled(app_config: &Config) {}}+ transcriptions.abort_all();+ while transcriptions.join_next().await.is_some() {}if let Some(open) = session.as_ref() {if let Err(error) = open.close(&config).await {log::warn!("{LOG_PREFIX} could not close the VAD session: {error}");}}log::info!("{LOG_PREFIX} capture channel closed; processor exiting");- RUNNING.store(false, Ordering::SeqCst);});+ *PROCESSOR.lock().expect("voice processor state poisoned") = Some(processor);}-/// Disable always-on listening at runtime (logout). Flips the `ENABLED` gate so-/// the processor immediately drops all audio — nothing is transcribed or sent —-/// the symmetric counterpart to [`start_if_enabled`]. The cpal stream itself-/// stays open (it's spawned once per process and reused if the user logs back in-/// and re-enables), but no audio is processed while disabled.+/// Immediately disable processing; async shutdown also releases the microphone.pub fn stop() {- if ENABLED.swap(false, Ordering::SeqCst) {- log::info!("{LOG_PREFIX} stopped (logout) — capture idle, audio dropped");+ ENABLED.store(false, Ordering::SeqCst);+ super::capture::request_stop();+}+/// Release continuous capture and wait for its processor on sign-out or toggle off.+pub async fn shutdown() {+ let _lifecycle = LIFECYCLE.lock().await;+ stop();+ if let Err(error) = crate::voice::capture_lease::close_streams().await {+ log::warn!("{LOG_PREFIX} capture cleanup pending: {error}");+ }+ let processor = PROCESSOR+ .lock()+ .expect("voice processor state poisoned")+ .take();+ if let Some(processor) = processor {+ let _ = processor.await;}}@@ -381,3 +388,19 @@ pub(super) fn notch_status(status: &str, ttl_ms: u32) {.with_ttl_ms(ttl_ms),);}++/// Retain the stream's observed stop generation, including a stop during VAD work.+pub(super) fn spawn_transcription(+ tasks: &mut tokio::task::JoinSet<()>,+ cancelled: &tokio::sync::watch::Receiver<u64>,+ task: impl std::future::Future<Output = ()> + Send + 'static,+) {+ let mut cancelled = cancelled.clone();+ tasks.spawn(async move {+ tokio::select! {+ biased;+ _ = cancelled.changed() => {},+ () = task => {},+ }+ });+}diff --git a/crates/openhuman-core/src/voice/always_on_tests.rs b/crates/openhuman-core/src/voice/always_on_tests.rsindex 07191c7f5d..0cf3d65baa 100644--- a/crates/openhuman-core/src/voice/always_on_tests.rs+++ b/crates/openhuman-core/src/voice/always_on_tests.rs@@ -45,3 +45,17 @@ fn a_nonpositive_utterance_ceiling_cannot_collapse_to_zero() {1);}++#[tokio::test]+async fn an_utterance_started_after_stop_never_polls_its_transcription() {+ let (stop, observed) = tokio::sync::watch::channel(0_u64);+ let delivered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let task_delivered = delivered.clone();+ stop.send_replace(1);+ let mut tasks = tokio::task::JoinSet::new();+ processor::spawn_transcription(&mut tasks, &observed, async move {+ task_delivered.store(true, Ordering::SeqCst);+ });+ tasks.join_next().await.unwrap().unwrap();+ assert!(!delivered.load(Ordering::SeqCst));+}diff --git a/crates/openhuman-core/src/voice/audio_capture.rs b/crates/openhuman-core/src/voice/audio_capture.rsindex 4b5e8d4204..3f72f817f8 100644--- a/crates/openhuman-core/src/voice/audio_capture.rs+++ b/crates/openhuman-core/src/voice/audio_capture.rs@@ -1,94 +1,42 @@-//! Microphone audio capture.-//!-//! Records audio from the default input device and produces 16-kHz mono WAV-//! bytes suitable for STT transcription. The `cpal` device flow lives in-//! `tinyvoice::capture`; this file supplies the host's microphone-permission-//! policy and, on stop, runs the raw samples through the `tinyvoice` module-//! (downmix, resample, silence gate, WAV framing).--use log::info;-+//! Host recording policy over module-owned native capture and audio preparation.+use super::capture_lease::{CaptureLease, Kind};use crate::config::Config;--const LOG_PREFIX: &str = "[voice_capture]";--/// Target sample rate for STT (16 kHz mono).-pub(crate) const TARGET_SAMPLE_RATE: u32 = tinyvoice::capture::TARGET_SAMPLE_RATE;--/// Samples per measurement frame — 20 ms at [`TARGET_SAMPLE_RATE`].-///-/// Matches the always-on loop's framing so a "peak RMS" means the same thing-/// in both paths; a different window would make the same audio report a-/// different peak depending on which recorder captured it.-const FRAME_SAMPLES: u32 = TARGET_SAMPLE_RATE / 50;--/// RMS below which the module's silence gate drops audio.-///-/// The value the in-process gate used before this moved to the module.-const SILENCE_GATE_THRESHOLD: f32 = 0.002;--/// Result of a completed recording.+/// Sample rate of the TinyVoice output contract (mono 16 kHz PCM).+pub(crate) const TARGET_SAMPLE_RATE: u32 = 16_000;+/// Prepared recording and module-computed metrics used by the STT gates.#[derive(Debug, Clone)]pub struct RecordingResult {- /// WAV-encoded audio bytes (16 kHz, mono, 16-bit PCM).+ /// Prepared WAV audio.pub wav_bytes: Vec<u8>,- /// Duration of the recording in seconds.+ /// Duration of the gated output.pub duration_secs: f32,- /// Number of samples captured.+ /// Mono sample count after gating.pub sample_count: usize,- /// Peak RMS energy observed during recording.- /// Used for silence detection — values below ~0.002 indicate no speech.+ /// Peak RMS measured before gating.pub peak_rms: f32,}--/// Handle to a recording in progress. Call `stop()` to end recording.+/// Opaque recording lease. Dropping it cancels capture and releases output.pub struct RecordingHandle {- /// The device recording; `None` only for a handle built by a test.- inner: Option<tinyvoice::capture::RecordingHandle>,- /// A finished result to hand back instead of preparing one.- ///- /// Test-only. `stop` now ends in module calls, so a test that wants to- /// exercise what the *pipeline* does with a result — the short-audio and- /// silence gates in `server` — would otherwise have to stand up a module- /// to assert something that has nothing to do with audio.+ inner: Option<CaptureLease>,#[cfg(test)]finalized: Option<Result<RecordingResult, String>>,}--/// What the capture thread produces: the device's own samples, untouched.-///-/// The thread does no signal processing at all: it converts the sample-/// format and accumulates. Downmixing, resampling, silence gating and WAV-/// framing all happen in [`RecordingHandle::stop`], through the `tinyvoice`-/// module, off the audio thread.-pub use tinyvoice::capture::RawRecording;-impl RecordingHandle {- /// Signal the recording to stop, then turn the raw capture into a result.- ///- /// Takes `config` because everything after "stop the stream" is a module- /// call: downmix, resample, silence-gate and frame the audio. Doing that- /// here rather than on the capture thread is what keeps the audio callback- /// free of signal processing.- ///- /// # Errors- ///- /// The capture error if the recording itself failed, or the module error if- /// the audio cannot be prepared. Both are strings the caller surfaces.- pub async fn stop(mut self, config: &Config) -> Result<RecordingResult, String> {+ /// Stop capture, read prepared audio in bounded slices, and release it.+ pub async fn stop(mut self, _config: &Config) -> Result<RecordingResult, String> {#[cfg(test)]- if let Some(finalized) = self.finalized.take() {- return finalized;+ if let Some(result) = self.finalized.take() {+ return result;}-- let Some(inner) = self.inner.take() else {- return Err("recording already stopped".to_string());- };- let raw = inner.stop().await.map_err(|e| e.to_string())?;- finalize(config, &raw).await+ let lease = self.inner.take().ok_or("recording already stopped")?;+ let result = lease.finish().await;+ if result.is_err() {+ if let Err(error) = lease.close().await {+ log::warn!("[voice_capture] recording cleanup pending: {error}");+ }+ }+ result}-- /// A handle whose `stop` yields `result` without touching audio or the bus.#[cfg(test)]pub(crate) fn from_test_result(result: Result<RecordingResult, String>) -> Self {Self {@@ -97,91 +45,27 @@ impl RecordingHandle {}}}--/// Turn a raw capture into a WAV plus the metrics the caller gates on.-///-/// Three module calls rather than one, because the caller needs two different-/// views of the same audio: the peak energy is measured on the *ungated*-/// samples — silence detection has to see the silence — while the WAV is the-/// gated version, which is what the STT engine should be billed for.-async fn finalize(config: &Config, raw: &RawRecording) -> Result<RecordingResult, String> {- use crate::modules::voice as tinyvoice;-- let channels = u16::try_from(raw.channels)- .map_err(|_| format!("implausible channel count: {}", raw.channels))?;-- // Ungated 16 kHz mono, for the energy measurement.- let mono = tinyvoice::prepare_frames(config, &raw.samples, raw.source_rate, channels)- .await- .map_err(|e| format!("could not prepare captured audio: {e}"))?;-- // One frame's worth per measurement, matching the always-on loop's framing.- let peak_rms = tinyvoice::frame_energies(config, &mono, FRAME_SAMPLES)- .await- .map_err(|e| format!("could not measure captured audio: {e}"))?- .into_iter()- .fold(0.0f32, f32::max);-- // Gated, framed as WAV — what actually gets uploaded.- let wav_bytes = tinyvoice::prepare_capture(- config,- &raw.samples,- raw.source_rate,- channels,- SILENCE_GATE_THRESHOLD,- )- .await- .map_err(|e| format!("could not encode captured audio: {e}"))?;-- // Derived from the WAV that is actually returned, not from `mono`.- //- // `mono` is the UNGATED buffer — it exists to measure peak energy, which- // has to see the silence. `wav_bytes` is the gated one. Reporting `mono`'s- // length here would describe audio the caller does not have: `server.rs`- // gates on `duration_secs` against `min_duration_secs`, so a recording that- // is mostly silence would claim a long duration and pass a check it should- // fail. Before the gate moved to the module it ran in the capture callback,- // so the buffer this was derived from was already gated and the two agreed.- //- // 16-bit mono PCM after a 44-byte header, so two bytes per sample.- let sample_count = wav_bytes.len().saturating_sub(44) / 2;- let duration_secs = sample_count as f32 / TARGET_SAMPLE_RATE as f32;- info!(- "{LOG_PREFIX} recording finalized: {duration_secs:.1}s, {} bytes WAV, peak_rms={peak_rms:.6}",- wav_bytes.len()- );-- Ok(RecordingResult {- wav_bytes,- duration_secs,- sample_count,- peak_rms,- })-}--/// Start recording from the default microphone.-///-/// Returns a `RecordingHandle` that must be `.stop().await`-ed to get-/// the captured audio. Recording runs on a dedicated OS thread inside-/// `tinyvoice::capture` because `cpal::Stream` is `!Send` (it must be created-/// and dropped on the same thread).+/// Obtain permission through TinyComputer before starting a TinyVoice recording.pub async fn start_recording(config: &Config) -> Result<RecordingHandle, String> {crate::modules::accessibility::AccessibilityClient::new(config).microphone_permission(true).await.map_err(|e| e.to_string())?;- let inner = tokio::task::spawn_blocking(|| tinyvoice::capture::start_recording(|| Ok(())))- .await- .map_err(|e| format!("microphone setup task failed: {e}"))?- .map_err(|e| e.to_string())?;+ let lease = CaptureLease::reserve(config, Kind::Recording).await?;+ lease.start_recording().await?;Ok(RecordingHandle {- inner: Some(inner),+ inner: Some(lease),#[cfg(test)]finalized: None,})}--/// List available input devices.-pub fn list_input_devices() -> Result<Vec<String>, String> {- tinyvoice::capture::list_input_devices().map_err(|e| e.to_string())+/// Enumerate native input devices through the loaded module.+pub async fn list_input_devices(config: &Config) -> Result<Vec<String>, String> {+ use tinyvoice_bus::{capture::CaptureResult, names::methods};+ let result: CaptureResult<Vec<String>> =+ crate::modules::client::ModuleClient::new(config.clone())+ .call_confidential("tinyvoice", methods::LIST_INPUT_DEVICES, ())+ .await+ .map_err(|e| e.to_string())?;+ result.map_err(|_| "input device enumeration failed".to_string())}diff --git a/crates/openhuman-core/src/voice/capture_lease.rs b/crates/openhuman-core/src/voice/capture_lease.rsnew file mode 100644index 0000000000..a9a14092e2--- /dev/null+++ b/crates/openhuman-core/src/voice/capture_lease.rs@@ -0,0 +1,385 @@+//! Host ownership and cancellation of opaque TinyVoice capture leases.+use super::audio_capture::{RecordingResult, TARGET_SAMPLE_RATE};+use crate::{config::Config, modules::client::ModuleClient};+use base64::Engine as _;+use serde::{de::DeserializeOwned, Serialize};+use std::collections::HashMap;+use std::sync::{+ atomic::{AtomicBool, AtomicU64, Ordering},+ Arc, LazyLock, Mutex,+};+use tinyvoice_bus::{+ capture::{+ AudioOutput, CaptureBatch, CaptureError, CaptureHandle, CapturePollRequest, CaptureResult,+ CaptureStream, MicrophonePermission, ReadAudioRequest, RecordingFinishRequest,+ RecordingStartRequest, RecordingSummary, RecordingSummaryRequest,+ },+ names::methods,+};++const MODULE: &str = "tinyvoice";+const READ_BYTES: usize = 256 * 1024;+const MAX_OUTPUT_BYTES: usize = 32 * 1024 * 1024;+static RECORDING_GENERATION: AtomicU64 = AtomicU64::new(0);+static STREAM_GENERATION: AtomicU64 = AtomicU64::new(0);+static NEXT_ID: AtomicU64 = AtomicU64::new(1);+static LEASES: LazyLock<Mutex<HashMap<u64, Arc<State>>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));+static HOOK: AtomicBool = AtomicBool::new(false);+#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) enum Kind {+ Recording,+ Stream,+}+impl Kind {+ fn generation(self) -> &'static AtomicU64 {+ match self {+ Self::Recording => &RECORDING_GENERATION,+ Self::Stream => &STREAM_GENERATION,+ }+ }+}+#[async_trait::async_trait]+trait Port: Send + Sync {+ async fn call(+ &self,+ member: &'static str,+ args: serde_json::Value,+ ) -> Result<serde_json::Value, String>;+}+struct BusPort(ModuleClient);+#[async_trait::async_trait]+impl Port for BusPort {+ async fn call(+ &self,+ member: &'static str,+ args: serde_json::Value,+ ) -> Result<serde_json::Value, String> {+ self.0+ .call_confidential(MODULE, member, args)+ .await+ .map_err(|e| e.to_string())+ }+}+struct State {+ id: u64,+ port: Arc<dyn Port>,+ handle: CaptureHandle,+ kind: Kind,+ closed: AtomicBool,+ serial: tokio::sync::Mutex<()>,+}+impl State {+ async fn call<T: DeserializeOwned>(+ &self,+ member: &'static str,+ args: impl Serialize,+ ) -> Result<CaptureResult<T>, String> {+ let args = serde_json::to_value(args).map_err(|_| malformed())?;+ let value = self.port.call(member, args).await?;+ serde_json::from_value(value).map_err(|_| malformed())+ }+ fn check_open(&self) -> Result<(), String> {+ if self.closed.load(Ordering::SeqCst) {+ Err("capture lease closed".into())+ } else {+ Ok(())+ }+ }+ async fn close(&self) -> Result<(), String> {+ let _serial = self.serial.lock().await;+ if self.closed.load(Ordering::SeqCst) {+ return Ok(());+ }+ match self.kind {+ Kind::Recording => {+ cleanup_result(+ self.call::<()>(methods::RECORDING_CANCEL, (&self.handle,))+ .await?,+ )?;+ cleanup_result(+ self.call::<()>(methods::RELEASE_AUDIO_OUTPUT, (&self.handle,))+ .await?,+ )?;+ }+ Kind::Stream => cleanup_result(+ self.call::<()>(methods::CAPTURE_STOP, (&self.handle,))+ .await?,+ )?,+ }+ self.mark_closed();+ Ok(())+ }+ fn mark_closed(&self) {+ self.closed.store(true, Ordering::SeqCst);+ LEASES+ .lock()+ .expect("capture lease registry poisoned")+ .remove(&self.id);+ }+}+/// Dropping a lease schedules cleanup; failed cleanup stays registered for retry.+pub(super) struct CaptureLease {+ state: Arc<State>,+}+impl CaptureLease {+ pub(super) async fn reserve(config: &Config, kind: Kind) -> Result<Self, String> {+ let port: Arc<dyn Port> = Arc::new(BusPort(ModuleClient::new(config.clone())));+ Self::reserve_with_port(port, kind).await+ }+ async fn reserve_with_port(port: Arc<dyn Port>, kind: Kind) -> Result<Self, String> {+ let generation = kind.generation().load(Ordering::SeqCst);+ let reply = port+ .call(+ methods::RESERVE_CAPTURE,+ serde_json::to_value((RecordingStartRequest {+ permission: MicrophonePermission::Granted,+ handle: None,+ },))+ .map_err(|_| malformed())?,+ )+ .await?;+ let handle: CaptureResult<CaptureHandle> =+ serde_json::from_value(reply).map_err(|_| malformed())?;+ let state = Arc::new(State {+ id: NEXT_ID.fetch_add(1, Ordering::Relaxed),+ port,+ handle: handle.map_err(capture_error)?,+ kind,+ closed: AtomicBool::new(false),+ serial: tokio::sync::Mutex::new(()),+ });+ LEASES+ .lock()+ .expect("capture lease registry poisoned")+ .insert(state.id, state.clone());+ register_shutdown();+ let lease = Self { state };+ if generation != kind.generation().load(Ordering::SeqCst) {+ lease.close().await?;+ return Err("capture cancelled during lifecycle change".into());+ }+ Ok(lease)+ }+ pub(super) async fn start_recording(&self) -> Result<(), String> {+ let _serial = self.state.serial.lock().await;+ self.state.check_open()?;+ let handle: CaptureHandle = self+ .state+ .call(+ methods::RECORDING_START,+ (RecordingStartRequest {+ permission: MicrophonePermission::Granted,+ handle: Some(self.state.handle.clone()),+ },),+ )+ .await?+ .map_err(capture_error)?;+ if handle != self.state.handle {+ return Err(malformed());+ }+ Ok(())+ }+ pub(super) async fn start_stream(&self) -> Result<CaptureStream, String> {+ let _serial = self.state.serial.lock().await;+ self.state.check_open()?;+ let stream: CaptureStream = self+ .state+ .call(+ methods::CAPTURE_START,+ (RecordingStartRequest {+ permission: MicrophonePermission::Granted,+ handle: Some(self.state.handle.clone()),+ },),+ )+ .await?+ .map_err(capture_error)?;+ if stream.handle != self.state.handle+ || stream.format.source_rate == 0+ || stream.format.channels == 0+ {+ return Err(malformed());+ }+ Ok(stream)+ }+ pub(super) async fn poll(&self) -> Result<CaptureBatch, String> {+ let _serial = self.state.serial.lock().await;+ self.state.check_open()?;+ let batch: CaptureBatch = self+ .state+ .call(+ methods::CAPTURE_POLL,+ (CapturePollRequest {+ handle: self.state.handle.clone(),+ max_chunks: 2,+ },),+ )+ .await?+ .map_err(capture_error)?;+ if batch.chunks.len() > 2+ || batch.chunks.iter().any(|chunk| {+ chunk.samples.len() > 32_768+ || chunk.samples.iter().any(|sample| !sample.is_finite())+ })+ {+ return Err(malformed());+ }+ Ok(batch)+ }+ pub(super) async fn finish(&self) -> Result<RecordingResult, String> {+ let _serial = self.state.serial.lock().await;+ self.state.check_open()?;+ let output: AudioOutput = self+ .state+ .call(+ methods::RECORDING_FINISH,+ (RecordingFinishRequest {+ handle: self.state.handle.clone(),+ gate_threshold: 0.002,+ },),+ )+ .await?+ .map_err(capture_error)?;+ if output.handle != self.state.handle || !(44..=MAX_OUTPUT_BYTES).contains(&output.length) {+ return Err(malformed());+ }+ let summary: RecordingSummary = self+ .state+ .call(+ methods::RECORDING_SUMMARY,+ (RecordingSummaryRequest {+ handle: self.state.handle.clone(),+ },),+ )+ .await?+ .map_err(capture_error)?;+ if !summary.peak_rms.is_finite()+ || summary.peak_rms < 0.0+ || summary.sample_count > MAX_OUTPUT_BYTES / 2+ || summary.sample_count.saturating_mul(2).saturating_add(44) != output.length+ {+ return Err(malformed());+ }+ let mut wav_bytes = Vec::with_capacity(output.length);+ while wav_bytes.len() < output.length {+ let length = READ_BYTES.min(output.length - wav_bytes.len());+ let encoded: String = self+ .state+ .call(+ methods::READ_AUDIO_OUTPUT,+ (ReadAudioRequest {+ handle: self.state.handle.clone(),+ offset: wav_bytes.len(),+ length,+ },),+ )+ .await?+ .map_err(capture_error)?;+ if encoded.len() > READ_BYTES.div_ceil(3) * 4 {+ return Err(malformed());+ }+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded)+ .map_err(|_| malformed())?;+ if bytes.len() != length {+ return Err(malformed());+ }+ wav_bytes.extend(bytes);+ }+ cleanup_result(+ self.state+ .call::<()>(methods::RELEASE_AUDIO_OUTPUT, (&self.state.handle,))+ .await?,+ )?;+ self.state.mark_closed();+ Ok(RecordingResult {+ wav_bytes,+ duration_secs: summary.sample_count as f32 / TARGET_SAMPLE_RATE as f32,+ sample_count: summary.sample_count,+ peak_rms: summary.peak_rms,+ })+ }+ pub(super) async fn close(&self) -> Result<(), String> {+ self.state.close().await+ }+}+impl Drop for CaptureLease {+ fn drop(&mut self) {+ if self.state.closed.load(Ordering::SeqCst) {+ return;+ }+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {+ let state = self.state.clone();+ runtime.spawn(async move {+ if let Err(error) = state.close().await {+ log::warn!("[voice_capture] lease cleanup pending: {error}");+ }+ });+ }+ }+}+fn malformed() -> String {+ ModuleClient::report_malformed_reply(MODULE);+ crate::modules::client::ModuleCallError::ModuleFault.to_string()+}+fn capture_error(error: CaptureError) -> String {+ let reason = match error {+ CaptureError::PermissionDenied => "microphone permission denied",+ CaptureError::Cancelled => "capture cancelled",+ CaptureError::Closed => "capture module closed",+ CaptureError::Busy => "microphone already in use",+ CaptureError::UnknownHandle => "capture lease unavailable",+ CaptureError::LimitExceeded => "capture limit exceeded",+ CaptureError::InvalidParameters => "invalid capture parameters",+ CaptureError::Device(_) => "microphone operation failed",+ };+ reason.into()+}+fn cleanup_result(result: CaptureResult<()>) -> Result<(), String> {+ match result {+ Ok(()) | Err(CaptureError::UnknownHandle) => Ok(()),+ Err(error) => Err(capture_error(error)),+ }+}+/// Release every retained capture lease on sign-out, including failed Drop cleanup.+pub(crate) async fn close_all() -> Result<(), String> {+ close_kind(None).await+}+pub(super) async fn close_streams() -> Result<(), String> {+ close_kind(Some(Kind::Stream)).await+}+async fn close_kind(kind: Option<Kind>) -> Result<(), String> {+ for candidate in [Kind::Recording, Kind::Stream] {+ if kind.is_none_or(|kind| kind == candidate) {+ candidate.generation().fetch_add(1, Ordering::SeqCst);+ }+ }+ let states: Vec<_> = LEASES+ .lock()+ .expect("capture lease registry poisoned")+ .values()+ .filter(|state| kind.is_none_or(|kind| kind == state.kind))+ .cloned()+ .collect();+ let mut failure = None;+ for state in states {+ if let Err(error) = state.close().await {+ failure = Some(error);+ }+ }+ failure.map_or(Ok(()), Err)+}+fn register_shutdown() {+ if HOOK.swap(true, Ordering::SeqCst) {+ return;+ }+ crate::core::shutdown::register(|| async {+ HOOK.store(false, Ordering::SeqCst);+ if let Err(error) = close_all().await {+ log::warn!("[voice_capture] shutdown cleanup pending: {error}");+ }+ });+}+#[cfg(test)]+#[path = "capture_lease_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/voice/capture_lease_tests.rs b/crates/openhuman-core/src/voice/capture_lease_tests.rsnew file mode 100644index 0000000000..4b99adb723--- /dev/null+++ b/crates/openhuman-core/src/voice/capture_lease_tests.rs@@ -0,0 +1,223 @@+use super::*;++#[tokio::test]+async fn missing_module_never_starts_a_local_microphone() {+ let mut config = Config::default();+ config.modules.enabled = false;+ let error = CaptureLease::reserve(&config, Kind::Recording)+ .await+ .err()+ .unwrap();+ assert!(error.contains("MODULE_CALL_REPORTED"));+}++#[tokio::test]+async fn unavailable_cleanup_retains_the_lease_for_retry() {+ let port = Arc::new(Fixture::default());+ port.fail_cleanup.store(true, Ordering::SeqCst);+ let lease = fixture_lease(port.clone(), Kind::Recording);+ assert!(lease.close().await.is_err());+ assert!(!lease.state.closed.load(Ordering::SeqCst));+ port.fail_cleanup.store(false, Ordering::SeqCst);+ lease.close().await.unwrap();+ assert!(lease.state.closed.load(Ordering::SeqCst));+ assert_eq!(+ *port.calls.lock().unwrap(),+ vec![+ methods::RECORDING_CANCEL,+ methods::RECORDING_CANCEL,+ methods::RELEASE_AUDIO_OUTPUT+ ]+ );+}++#[tokio::test]+async fn finishing_reads_bounded_output_and_uses_module_metrics() {+ let port = Arc::new(Fixture::default());+ let lease = fixture_lease(port.clone(), Kind::Recording);+ let result = lease.finish().await.unwrap();+ assert_eq!(result.wav_bytes, vec![7; READ_BYTES + 2]);+ assert_eq!(result.sample_count, (READ_BYTES + 2 - 44) / 2);+ assert_eq!(result.peak_rms, 0.25);+ assert_eq!(+ port.reads.lock().unwrap().as_slice(),+ &[(0, READ_BYTES), (READ_BYTES, 2)]+ );+ assert!(lease.state.closed.load(Ordering::SeqCst));+}++#[tokio::test]+async fn cancelled_finish_releases_the_known_recording_and_output() {+ let port = Arc::new(Fixture::default());+ port.block_finish.store(true, Ordering::SeqCst);+ let lease = fixture_lease(port.clone(), Kind::Recording);+ let state = lease.state.clone();+ let task = tokio::spawn(async move { lease.finish().await });+ port.entered.notified().await;+ task.abort();+ let _ = task.await;+ state.close().await.unwrap();+ assert!(state.closed.load(Ordering::SeqCst));+ let calls = port.calls.lock().unwrap();+ assert!(calls.contains(&methods::RECORDING_CANCEL));+ assert!(calls.contains(&methods::RELEASE_AUDIO_OUTPUT));+}++#[tokio::test]+async fn closed_stream_cannot_poll_or_restart_after_sign_out() {+ let port = Arc::new(Fixture::default());+ let lease = fixture_lease(port.clone(), Kind::Stream);+ lease.close().await.unwrap();+ assert!(lease.poll().await.is_err());+ assert!(lease.start_stream().await.is_err());+ assert_eq!(*port.calls.lock().unwrap(), vec![methods::CAPTURE_STOP]);+}++#[derive(Default)]+struct Fixture {+ calls: std::sync::Mutex<Vec<&'static str>>,+ reads: std::sync::Mutex<Vec<(usize, usize)>>,+ fail_cleanup: AtomicBool,+ block_finish: AtomicBool,+ block_reserve: AtomicBool,+ release_reserve: tokio::sync::Notify,+ entered: tokio::sync::Notify,+}+#[async_trait::async_trait]+impl Port for Fixture {+ async fn call(+ &self,+ member: &'static str,+ args: serde_json::Value,+ ) -> Result<serde_json::Value, String> {+ self.calls.lock().unwrap().push(member);+ if self.fail_cleanup.load(Ordering::SeqCst) && member == methods::RECORDING_CANCEL {+ return Err("MODULE_CALL_REPORTED: transport failed".into());+ }+ match member {+ methods::RESERVE_CAPTURE => {+ if self.block_reserve.load(Ordering::SeqCst) {+ self.entered.notify_one();+ self.release_reserve.notified().await;+ }+ Ok(serde_json::to_value(CaptureResult::Ok(CaptureHandle("lease".into()))).unwrap())+ }++ methods::RECORDING_FINISH => {+ if self.block_finish.load(Ordering::SeqCst) {+ self.entered.notify_one();+ std::future::pending::<()>().await;+ }+ Ok(serde_json::to_value(CaptureResult::Ok(AudioOutput {+ handle: CaptureHandle("lease".into()),+ length: READ_BYTES + 2,+ }))+ .unwrap())+ }+ methods::RECORDING_SUMMARY => {+ Ok(serde_json::to_value(CaptureResult::Ok(RecordingSummary {+ sample_count: (READ_BYTES + 2 - 44) / 2,+ peak_rms: 0.25,+ }))+ .unwrap())+ }+ methods::READ_AUDIO_OUTPUT => {+ let request: ReadAudioRequest = serde_json::from_value(args[0].clone()).unwrap();+ self.reads+ .lock()+ .unwrap()+ .push((request.offset, request.length));+ Ok(serde_json::to_value(CaptureResult::Ok(+ base64::engine::general_purpose::STANDARD.encode(vec![7; request.length]),+ ))+ .unwrap())+ }+ methods::RECORDING_CANCEL => Ok(serde_json::to_value(CaptureResult::<()>::Err(+ CaptureError::UnknownHandle,+ ))+ .unwrap()),+ _ => Ok(serde_json::to_value(CaptureResult::Ok(())).unwrap()),+ }+ }+}+fn fixture_lease(port: Arc<Fixture>, kind: Kind) -> CaptureLease {+ CaptureLease {+ state: Arc::new(State {+ id: 0,+ port,+ handle: CaptureHandle("lease".into()),+ kind,+ closed: AtomicBool::new(false),+ serial: tokio::sync::Mutex::new(()),+ }),+ }+}++#[cfg(feature = "modules")]+#[tokio::test]+async fn capture_never_retries_through_an_unattested_bus() {+ use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};+ #[derive(Clone)]+ struct Unattested(Arc<AtomicU64>);+ #[tinybus::interface(name = "test.Capture")]+ impl Unattested {+ async fn recording_start(+ &self,+ _: RecordingStartRequest,+ ) -> tinybus::Result<CaptureResult<CaptureHandle>> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(Ok(CaptureHandle("lease".into())))+ }+ }+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let service = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let calls = Arc::new(AtomicU64::new(0));+ service+ .serve_at(+ ObjectPath::new("/test/Capture").unwrap(),+ Unattested(calls.clone()),+ )+ .await+ .unwrap();+ service.request_name("test.Capture").await.unwrap();+ let proxy = caller+ .proxy("test.Capture", "/test/Capture", "test.Capture")+ .unwrap();+ let lease = CaptureLease {+ state: Arc::new(State {+ id: 0,+ port: Arc::new(BusPort(ModuleClient::fixture(proxy))),+ handle: CaptureHandle("lease".into()),+ kind: Kind::Recording,+ closed: AtomicBool::new(false),+ serial: tokio::sync::Mutex::new(()),+ }),+ };+ let error = lease.start_recording().await.unwrap_err();+ assert!(error.contains("MODULE_CALL_REPORTED"));+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ lease.state.closed.store(true, Ordering::SeqCst);+}++#[tokio::test]+async fn a_reservation_finishing_after_sign_out_is_closed_before_start() {+ let port = Arc::new(Fixture::default());+ port.block_reserve.store(true, Ordering::SeqCst);+ let task_port = port.clone();+ let task =+ tokio::spawn(async move { CaptureLease::reserve_with_port(task_port, Kind::Stream).await });+ port.entered.notified().await;+ Kind::Stream.generation().fetch_add(1, Ordering::SeqCst);+ port.release_reserve.notify_one();+ assert!(task.await.unwrap().is_err());+ assert_eq!(+ *port.calls.lock().unwrap(),+ vec![methods::RESERVE_CAPTURE, methods::CAPTURE_STOP]+ );+}diff --git a/crates/openhuman-core/src/voice/mod.rs b/crates/openhuman-core/src/voice/mod.rsindex 61242822e3..1cdd2a823e 100644--- a/crates/openhuman-core/src/voice/mod.rs+++ b/crates/openhuman-core/src/voice/mod.rs@@ -39,6 +39,8 @@ pub mod audio_toolkit;#[cfg(feature = "voice")]pub mod bus;#[cfg(feature = "voice")]+pub(crate) mod capture_lease;+#[cfg(feature = "voice")]pub use bus::publish_ptt_transcript_committed;#[cfg(feature = "voice")]pub(crate) mod cli;diff --git a/crates/openhuman-core/src/voice/stub.rs b/crates/openhuman-core/src/voice/stub.rsindex 5d03fe6261..786e470d0b 100644--- a/crates/openhuman-core/src/voice/stub.rs+++ b/crates/openhuman-core/src/voice/stub.rs@@ -186,6 +186,9 @@ pub mod always_on {/// No-op: nothing to stop.pub fn stop() {}++ /// No-op: no module capture leases exist when voice is disabled.+ pub async fn shutdown() {}}// ---------------------------------------------------------------------------diff --git a/docs/module-boundary-inventory.md b/docs/module-boundary-inventory.mdindex 80095a40ff..3a2c819d55 100644--- a/docs/module-boundary-inventory.md+++ b/docs/module-boundary-inventory.md@@ -21,7 +21,7 @@ copying its implementation into a host, or accepting weaker isolation.| tinywallet | tinywallet-crypto, tinywallet-web3, tinywallet-x402 through remaining host imports | tinywallet-bus | core wallet/web3/x402 | Contract is pure at v0.13.0; native transfer preparation/execution use confidential module calls with host custody, exact approval binding and explicit close. Initialization, remaining validation, Web3 quotes/swaps, x402 payments, budgets and ledger still need host cutover || tinybox | tinybox-core, tinybox-jail, tinybox-docker, tinybox-host, tinybox-ssh | tinybox-bus | core sandbox and security, desktop gateways | Pre-core gateways use the released v0.1.18 bus client. Core sandbox execution and shell analysis still require cutover || tinycomputer | tinycomputer-accessibility | tinycomputer-bus | core voice, paste/focus and permission checks | Permission, focus, paste, Globe listener vocabulary/operations; preserve native thread and target rules |-| tinyvoice | tinyvoice, cpal (also through accessibility probe) | tinyvoice-bus | core voice capture/hotkeys | Devices, recording/capture and hotkey lifecycle, bounded event batches; computer module permission decisions |+| tinyvoice | None | tinyvoice-bus | core voice capture/hotkeys | Module-owned devices, recording and continuous capture, bounded audio reads/batches, explicit lease cleanup; computer module permission decisions || tinyruntime | tinyruntime-pyserver | tinyruntime-bus | core Python worker, optional TinyJuice ML | Excluded from this migration: TinyRuntime is being removed separately || tinydocs / tinymemory | pdf-extract, calamine through tinymemory-integrations/documents-office | tinydocs-bus | core memory converter and file sources | Replace OfficeConverter with bus DocumentConverter; XLSX extraction plus existing PDF/DOCX/PPTX metadata/format coverage || tinysearch | none observed | tinysearch-bus | core module search proxy | Preserve existing bus adapter; enforce contract and host dependency graphs |@@ -319,3 +319,11 @@ The desktop lockfile also catches up the already-merged Wallet v0.13.0 pin.Its pure contract removes the two stale contract exceptions; eleven hostimplementation exceptions remain. Runtime channel dispatch and relay deliverystill need migration.+++TinyVoice capture uses released v0.1.15 (contract 1.5), including owner-computed+recording summaries. The host holds opaque reservations, reads WAV output in+256 KiB slices, polls at most two continuous chunks per request, and releases+leases on cancellation, sign-out and shutdown. Failed cleanup stays registered+for retry. Microphone authorization remains a TinyComputer call; the host does+not link TinyVoice or CPAL. The existing hotkey adapter remains module-backed.diff --git a/scripts/ci/module-boundaries.json b/scripts/ci/module-boundaries.jsonindex c97e57cd36..d19c2f73e0 100644--- a/scripts/ci/module-boundaries.json+++ b/scripts/ci/module-boundaries.json@@ -131,11 +131,6 @@"package": "tinybox-docker","reason": "Sandbox execution, shell analysis and pre-core gateways need a bus contract."},- {- "scope": "hosts",- "package": "tinyvoice",- "reason": "Capture and hotkey lifecycles need module operations."- },{"scope": "hosts","package": "tinywallet-crypto",@@ -150,11 +145,6 @@"scope": "hosts","package": "tinywallet-x402","reason": "Validation, transaction construction, web3 and x402 need module operations."- },- {- "scope": "hosts",- "package": "cpal",- "reason": "Voice capture and the accessibility microphone probe still link host audio-device access."}],"excludedSubsystems": [diff --git a/vendor/tinyvoice b/vendor/tinyvoiceindex 5d545f5719..5f49b5619c 160000--- a/vendor/tinyvoice+++ b/vendor/tinyvoice@@ -1 +1 @@-Subproject commit 5d545f57195e4a6f0ba64b009d514eefd4c1b1d2+Subproject commit 5f49b5619c63a6917a0476c3a009f4edb9cefc15