diff --git a/.aoci/baseline.json b/.aoci/baseline.json index 22048337d..b439d9f3b 100644 --- a/.aoci/baseline.json +++ b/.aoci/baseline.json @@ -1,7 +1,7 @@ { "version": 1, "created_at": "2026-11-21T04:46:16Z", - "updated_at": "2026-11-24T05:39:19Z", + "updated_at": "2026-11-25T04:37:25Z", "files": { ".gitattributes": { "role": "index", @@ -161,9 +161,9 @@ }, "aoci.code.txt": { "role": "index", - "sha256": "3c775951f3d312349357d51dbae70a0583d3161c3599a479d89d14e6e8a0f0f0", - "size": 768615, - "normalized_sha256": "3c775951f3d312349357d51dbae70a0583d3161c3599a479d89d14e6e8a0f0f0" + "sha256": "cc05341b71a17c1e322e65cce0e39fbda53d13da5cde45a973e11d3973cc594f", + "size": 771412, + "normalized_sha256": "cc05341b71a17c1e322e65cce0e39fbda53d13da5cde45a973e11d3973cc594f" }, "aoci.meta.txt": { "role": "index", @@ -414,9 +414,9 @@ }, "docs/development/long-recording.md": { "role": "index", - "sha256": "d9e037386da77dabdf466a852b7b6064233fdd89a764a212577c21eb0db8315f", - "size": 4419, - "normalized_sha256": "d9e037386da77dabdf466a852b7b6064233fdd89a764a212577c21eb0db8315f" + "sha256": "34726b2c2602a8e7921ed41ab713ff4a18a26f167881513a1eaf005238745a9f", + "size": 6558, + "normalized_sha256": "34726b2c2602a8e7921ed41ab713ff4a18a26f167881513a1eaf005238745a9f" }, "docs/development/official-style-packs.md": { "role": "index", @@ -2024,9 +2024,9 @@ }, "openless-all/app/crates/openless-core/src/api.rs": { "role": "index", - "sha256": "5da760e185da9c936af9c1cbeb77280f1a4d59cc3741f82dde79de7ecb07c280", - "size": 869726, - "normalized_sha256": "5da760e185da9c936af9c1cbeb77280f1a4d59cc3741f82dde79de7ecb07c280" + "sha256": "4f9b8f0977716f556f67f9e8e810727c06f4477d622a2e33b4b0e4f5eba038ba", + "size": 884949, + "normalized_sha256": "4f9b8f0977716f556f67f9e8e810727c06f4477d622a2e33b4b0e4f5eba038ba" }, "openless-all/app/crates/openless-core/src/api/cloud_note.rs": { "role": "index", @@ -2090,9 +2090,9 @@ }, "openless-all/app/crates/openless-core/src/ask_search.rs": { "role": "index", - "sha256": "c52a4e52390824b91ff418442df5e8f72d8945f577e9ef3e347df17e6cb7b58e", - "size": 26283, - "normalized_sha256": "c52a4e52390824b91ff418442df5e8f72d8945f577e9ef3e347df17e6cb7b58e" + "sha256": "6486c066331ed59a733604777f2d816c27fae6f48ed2bf68503e652fb2b9deee", + "size": 26249, + "normalized_sha256": "6486c066331ed59a733604777f2d816c27fae6f48ed2bf68503e652fb2b9deee" }, "openless-all/app/crates/openless-core/src/ask_voice_capture.rs": { "role": "index", @@ -2102,9 +2102,9 @@ }, "openless-all/app/crates/openless-core/src/asr/bailian.rs": { "role": "index", - "sha256": "8aa6d99da3f5512f8a9241d66461d1d1ab92e3400456fcaad357e0ea19d3bd8a", - "size": 47743, - "normalized_sha256": "8aa6d99da3f5512f8a9241d66461d1d1ab92e3400456fcaad357e0ea19d3bd8a" + "sha256": "d04e75a1d00a4695582309a7012dc9b72967f0577b58c4a108046abff33af92e", + "size": 65024, + "normalized_sha256": "d04e75a1d00a4695582309a7012dc9b72967f0577b58c4a108046abff33af92e" }, "openless-all/app/crates/openless-core/src/asr/dashscope_multimodal.rs": { "role": "index", @@ -2210,9 +2210,9 @@ }, "openless-all/app/crates/openless-core/src/asr/mod.rs": { "role": "index", - "sha256": "df565e582084a18d580a08b59b57a881189966fca68ea10b63de61ab08ba055a", - "size": 2051, - "normalized_sha256": "df565e582084a18d580a08b59b57a881189966fca68ea10b63de61ab08ba055a" + "sha256": "3a66c98ee524729fe34ecc700b948174041e3abbb8868b6fd3081a32b8ec66f7", + "size": 6321, + "normalized_sha256": "3a66c98ee524729fe34ecc700b948174041e3abbb8868b6fd3081a32b8ec66f7" }, "openless-all/app/crates/openless-core/src/asr/pcm.rs": { "role": "index", @@ -2222,15 +2222,15 @@ }, "openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs": { "role": "index", - "sha256": "84e0ddb7fcd0e756b6e9421fcaf43fce51f81c92d0245c355e76ca3d38e9cad0", - "size": 40597, - "normalized_sha256": "84e0ddb7fcd0e756b6e9421fcaf43fce51f81c92d0245c355e76ca3d38e9cad0" + "sha256": "a8b0463d2fcf85134177266a62360fafd6df7417ddea348cf9ff740848a3ca7e", + "size": 53474, + "normalized_sha256": "a8b0463d2fcf85134177266a62360fafd6df7417ddea348cf9ff740848a3ca7e" }, "openless-all/app/crates/openless-core/src/asr/stepfun_realtime.rs": { "role": "index", - "sha256": "1ec95f93a1501b511cdfbc506b948edd1a216dfe81b3ec0eb098f2314a906ca5", - "size": 63360, - "normalized_sha256": "1ec95f93a1501b511cdfbc506b948edd1a216dfe81b3ec0eb098f2314a906ca5" + "sha256": "a0e97c073456f0c34c5ba4de51bb87febe5678506bb64cb9962a936ce6173e85", + "size": 73235, + "normalized_sha256": "a0e97c073456f0c34c5ba4de51bb87febe5678506bb64cb9962a936ce6173e85" }, "openless-all/app/crates/openless-core/src/asr/tencent_cloud.rs": { "role": "index", @@ -2246,27 +2246,27 @@ }, "openless-all/app/crates/openless-core/src/asr/volcengine.rs": { "role": "index", - "sha256": "4f00f77aa42b7c01662d81d599ff7b6660301f4ce472513169b6ba7f578b9339", - "size": 54385, - "normalized_sha256": "4f00f77aa42b7c01662d81d599ff7b6660301f4ce472513169b6ba7f578b9339" + "sha256": "c27557439ee4c78bcce38da4a755a51a1718b031b6efc6ece221bb346630c07a", + "size": 69665, + "normalized_sha256": "c27557439ee4c78bcce38da4a755a51a1718b031b6efc6ece221bb346630c07a" }, "openless-all/app/crates/openless-core/src/asr/wav.rs": { "role": "index", - "sha256": "7a5d2370373493830e398965b5174e2f09463f29cd6cf4b1d648616b531dd2ff", - "size": 2595, - "normalized_sha256": "7a5d2370373493830e398965b5174e2f09463f29cd6cf4b1d648616b531dd2ff" + "sha256": "395584b9e375ffdf58f9c573856c9641f7309a55ce0fd1613a411fb0e8d58b98", + "size": 3713, + "normalized_sha256": "395584b9e375ffdf58f9c573856c9641f7309a55ce0fd1613a411fb0e8d58b98" }, "openless-all/app/crates/openless-core/src/asr/whisper.rs": { "role": "index", - "sha256": "68ac82fd38e3906c3a51e0ab3b3bfad1674f90152a2901a5386cdefd34f5ca83", - "size": 60785, - "normalized_sha256": "68ac82fd38e3906c3a51e0ab3b3bfad1674f90152a2901a5386cdefd34f5ca83" + "sha256": "01d9edfdf268bf97d9f1abf9fef76ff40ad758ae521aa92e6f7b390d0dfe5f42", + "size": 60799, + "normalized_sha256": "01d9edfdf268bf97d9f1abf9fef76ff40ad758ae521aa92e6f7b390d0dfe5f42" }, "openless-all/app/crates/openless-core/src/asr/xfyun.rs": { "role": "index", - "sha256": "fd8808caec88799dfa8ed16cf9646cec4b66719671690ed27f0ef844cb17d295", - "size": 35793, - "normalized_sha256": "fd8808caec88799dfa8ed16cf9646cec4b66719671690ed27f0ef844cb17d295" + "sha256": "cd2feb5e64e5ddb3740e6d26b9b743c400df8357ad8449cdab703e68c5f70677", + "size": 55906, + "normalized_sha256": "cd2feb5e64e5ddb3740e6d26b9b743c400df8357ad8449cdab703e68c5f70677" }, "openless-all/app/crates/openless-core/src/assistant.rs": { "role": "index", @@ -2276,9 +2276,9 @@ }, "openless-all/app/crates/openless-core/src/assistant/budget.rs": { "role": "index", - "sha256": "8ca7ba262a7f0419ab9cbdfa0bb6f81d14dcf0d9b70408b5cdf2bc094def592b", - "size": 50156, - "normalized_sha256": "8ca7ba262a7f0419ab9cbdfa0bb6f81d14dcf0d9b70408b5cdf2bc094def592b" + "sha256": "cdbd7a742981192b7fbe9f1cbc771b69a56020eb8ab0f1ff235715bfc791ec8f", + "size": 50169, + "normalized_sha256": "cdbd7a742981192b7fbe9f1cbc771b69a56020eb8ab0f1ff235715bfc791ec8f" }, "openless-all/app/crates/openless-core/src/assistant/call.rs": { "role": "index", @@ -2318,9 +2318,9 @@ }, "openless-all/app/crates/openless-core/src/audio.rs": { "role": "index", - "sha256": "75328ebc96d0c5de80365e56232ba33f37762c73c79839bf3c6923cb78b99c57", - "size": 36848, - "normalized_sha256": "75328ebc96d0c5de80365e56232ba33f37762c73c79839bf3c6923cb78b99c57" + "sha256": "d5e83388a9410eda0a5b08ff9da28e7fe5c180b79b8b66ab53605543f151f55a", + "size": 49809, + "normalized_sha256": "d5e83388a9410eda0a5b08ff9da28e7fe5c180b79b8b66ab53605543f151f55a" }, "openless-all/app/crates/openless-core/src/audio/dsp_tests.rs": { "role": "index", @@ -2342,9 +2342,9 @@ }, "openless-all/app/crates/openless-core/src/auxiliary.rs": { "role": "index", - "sha256": "202908934eae47b6d69ed5c5c4cc6bc27177f6a82b1c728adf8f28f91e181ebd", - "size": 23237, - "normalized_sha256": "202908934eae47b6d69ed5c5c4cc6bc27177f6a82b1c728adf8f28f91e181ebd" + "sha256": "aeeb373646a191e39cfb352b0a74ba023d81b4db65bb2e8a41265b231fb2a1db", + "size": 30395, + "normalized_sha256": "aeeb373646a191e39cfb352b0a74ba023d81b4db65bb2e8a41265b231fb2a1db" }, "openless-all/app/crates/openless-core/src/builtin_styles/intent-reconstruction-shared-v1.md": { "role": "index", @@ -2366,9 +2366,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_providers.rs": { "role": "index", - "sha256": "eeaa7f4de7455f16e6cf85c33004c4b1e95cc8ee1aee6754d99bd7134ae95ddc", - "size": 177134, - "normalized_sha256": "eeaa7f4de7455f16e6cf85c33004c4b1e95cc8ee1aee6754d99bd7134ae95ddc" + "sha256": "a2f1a1fbf113e6d269dc23fdecbbcbb319002c8038554507fcfdd41f56464481", + "size": 188682, + "normalized_sha256": "a2f1a1fbf113e6d269dc23fdecbbcbb319002c8038554507fcfdd41f56464481" }, "openless-all/app/crates/openless-core/src/cloud_sync.rs": { "role": "index", @@ -2660,9 +2660,9 @@ }, "openless-all/app/crates/openless-core/src/dictation_engine.rs": { "role": "index", - "sha256": "92df83547c253d16a17e44b12e4b27cedb6e11b49f3dea7eb762db548cd4c295", - "size": 213823, - "normalized_sha256": "92df83547c253d16a17e44b12e4b27cedb6e11b49f3dea7eb762db548cd4c295" + "sha256": "6ea1f4b8fe7a8adde1fdec9773981e9eec6dc965dfd63f07102566a40e5f9d00", + "size": 250297, + "normalized_sha256": "6ea1f4b8fe7a8adde1fdec9773981e9eec6dc965dfd63f07102566a40e5f9d00" }, "openless-all/app/crates/openless-core/src/domains.rs": { "role": "index", @@ -2738,9 +2738,9 @@ }, "openless-all/app/crates/openless-core/src/external_audio/archive.rs": { "role": "index", - "sha256": "f29230c53f6f4fe495aa7e0e46279db8d7455be84ac7c365693580286908275f", - "size": 7757, - "normalized_sha256": "f29230c53f6f4fe495aa7e0e46279db8d7455be84ac7c365693580286908275f" + "sha256": "dbc50e1dc2557a5f19077a786559f278742bbbee3e20f426e2f67f604a3b5be7", + "size": 9703, + "normalized_sha256": "dbc50e1dc2557a5f19077a786559f278742bbbee3e20f426e2f67f604a3b5be7" }, "openless-all/app/crates/openless-core/src/history.rs": { "role": "index", @@ -2936,9 +2936,9 @@ }, "openless-all/app/crates/openless-core/src/ports.rs": { "role": "index", - "sha256": "882f707a04d6f3a59b364823ea208a845155599345a1bfe9ba97591aaa86f509", - "size": 34623, - "normalized_sha256": "882f707a04d6f3a59b364823ea208a845155599345a1bfe9ba97591aaa86f509" + "sha256": "f6e4dca9c39ed27044485fbeee9643cd7cc88f015857f8d97678d4ff34c07638", + "size": 35224, + "normalized_sha256": "f6e4dca9c39ed27044485fbeee9643cd7cc88f015857f8d97678d4ff34c07638" }, "openless-all/app/crates/openless-core/src/preference_patch.rs": { "role": "index", @@ -3074,15 +3074,15 @@ }, "openless-all/app/crates/openless-core/src/qa_service/standalone/tests.rs": { "role": "index", - "sha256": "d700ef3e592e3afa2b393d995e05fbd66e0f3c5b373ddd7c34cf60ff672ba335", - "size": 72149, - "normalized_sha256": "d700ef3e592e3afa2b393d995e05fbd66e0f3c5b373ddd7c34cf60ff672ba335" + "sha256": "8a417653ca4b10e845411f76fada906c915ee3f28a47ac8b3b99b55468dfa36e", + "size": 72176, + "normalized_sha256": "8a417653ca4b10e845411f76fada906c915ee3f28a47ac8b3b99b55468dfa36e" }, "openless-all/app/crates/openless-core/src/recording_overlap_tests.rs": { "role": "index", - "sha256": "bc1233bda9b8229156ffd030e6ff35fcc4ee527a54a494bd2e0e47e393220089", - "size": 37654, - "normalized_sha256": "bc1233bda9b8229156ffd030e6ff35fcc4ee527a54a494bd2e0e47e393220089" + "sha256": "83613100e4787f7229d8b4fdb0a2b5fbce7e871a5cfd984b19c0572d5005d4a9", + "size": 38109, + "normalized_sha256": "83613100e4787f7229d8b4fdb0a2b5fbce7e871a5cfd984b19c0572d5005d4a9" }, "openless-all/app/crates/openless-core/src/remote_input_service.rs": { "role": "index", @@ -3116,9 +3116,9 @@ }, "openless-all/app/crates/openless-core/src/shared_types.rs": { "role": "index", - "sha256": "e6e6ee47f2e6da41ad15fbc38ef8e8889b9067653797ed4cd1aae7ed8594ba1c", - "size": 174582, - "normalized_sha256": "e6e6ee47f2e6da41ad15fbc38ef8e8889b9067653797ed4cd1aae7ed8594ba1c" + "sha256": "521f4630518fea910500c367fa356069563f18824fb9edde882484ddd48e8a86", + "size": 175596, + "normalized_sha256": "521f4630518fea910500c367fa356069563f18824fb9edde882484ddd48e8a86" }, "openless-all/app/crates/openless-core/src/shortcut_types.rs": { "role": "index", @@ -3260,15 +3260,15 @@ }, "openless-all/app/crates/openless-core/src/web_search/public_sources.rs": { "role": "index", - "sha256": "bcdae09982f62999ded221a1df4afaa3d56e7cc6786a71a6262dfc9fe04ba3c4", - "size": 16833, - "normalized_sha256": "bcdae09982f62999ded221a1df4afaa3d56e7cc6786a71a6262dfc9fe04ba3c4" + "sha256": "961973c81c37af7b2db5a67c178cb2a3cf7e8ca23e1a6a173daecf68ad1d2366", + "size": 16846, + "normalized_sha256": "961973c81c37af7b2db5a67c178cb2a3cf7e8ca23e1a6a173daecf68ad1d2366" }, "openless-all/app/crates/openless-core/tests/auxiliary_voice_lifecycle.rs": { "role": "observe", - "sha256": "84b766ec8b836ae030fc5d7aae7b3ff645f1d5cfe1907f19127b3dcc87cdf304", - "size": 54201, - "normalized_sha256": "84b766ec8b836ae030fc5d7aae7b3ff645f1d5cfe1907f19127b3dcc87cdf304" + "sha256": "5b9d2c7ae160104546055453b0443ac89f2cadba8ef1de42d38b0cb783ba4922", + "size": 54767, + "normalized_sha256": "5b9d2c7ae160104546055453b0443ac89f2cadba8ef1de42d38b0cb783ba4922" }, "openless-all/app/crates/openless-core/tests/capsule_display_preferences.rs": { "role": "observe", @@ -3296,9 +3296,9 @@ }, "openless-all/app/crates/openless-core/tests/dictation_target_capture.rs": { "role": "observe", - "sha256": "07d55964623f02fd1bb49737c9166789b91b222adb7527d19652ec6abce67fc8", - "size": 53821, - "normalized_sha256": "07d55964623f02fd1bb49737c9166789b91b222adb7527d19652ec6abce67fc8" + "sha256": "866235a04f2c3e6d7baf1f2e80ad6f7a134c45ca50a419fff79d51fbd61c503b", + "size": 57930, + "normalized_sha256": "866235a04f2c3e6d7baf1f2e80ad6f7a134c45ca50a419fff79d51fbd61c503b" }, "openless-all/app/crates/openless-core/tests/gemini_live_dictation.rs": { "role": "observe", @@ -3312,6 +3312,12 @@ "size": 5097, "normalized_sha256": "1444ebe79b36eb2a205d1e72e6ae4cc31eed9256f3c53473e610adf72acb095f" }, + "openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs": { + "role": "observe", + "sha256": "343654e19ae918ac3804de868ec1413a34d46b0903d170e4b02b3fed4a49275f", + "size": 155, + "normalized_sha256": "343654e19ae918ac3804de868ec1413a34d46b0903d170e4b02b3fed4a49275f" + }, "openless-all/app/crates/openless-core/tests/local_asr_contract.rs": { "role": "observe", "sha256": "80180275a521d08b6ec51ebee261912b97c60438cc9d70ae4abeb711a195ecdf", @@ -3344,9 +3350,9 @@ }, "openless-all/app/crates/openless-core/tests/qa_answer_replacement.rs": { "role": "observe", - "sha256": "e898c360dd5b7047b87df653d3674536c5a5591678179511f860dbc507026ba3", - "size": 17013, - "normalized_sha256": "e898c360dd5b7047b87df653d3674536c5a5591678179511f860dbc507026ba3" + "sha256": "9255bd816c650f906a38ec1afc8d6c30c9e84b4b939fe61942dffd0f56052492", + "size": 17406, + "normalized_sha256": "9255bd816c650f906a38ec1afc8d6c30c9e84b4b939fe61942dffd0f56052492" }, "openless-all/app/crates/openless-core/tests/qa_contract.rs": { "role": "observe", @@ -3440,15 +3446,15 @@ }, "openless-all/app/e2e/ask-anything.spec.ts": { "role": "observe", - "sha256": "c8bc1e9722e29a04dd30bd5b2a2f73c4e2dd3adb5c6c361c3374648fb57e58f2", + "sha256": "c2631f8b2ec14b7cc9bf5d4528a86eef6c78e0d872bdce58a866243c3b7d51f8", "size": 4156, - "normalized_sha256": "c8bc1e9722e29a04dd30bd5b2a2f73c4e2dd3adb5c6c361c3374648fb57e58f2" + "normalized_sha256": "c2631f8b2ec14b7cc9bf5d4528a86eef6c78e0d872bdce58a866243c3b7d51f8" }, "openless-all/app/e2e/ask-entry-settings.spec.ts": { "role": "observe", - "sha256": "fe2cd3396c7725f4fbc15ba149a9d4948eac16600a369c212034991be5524c68", - "size": 11306, - "normalized_sha256": "fe2cd3396c7725f4fbc15ba149a9d4948eac16600a369c212034991be5524c68" + "sha256": "d1081859b204e89fb3d6172a55065ff553cd4f0976028744fc27eb32f93464ab", + "size": 11317, + "normalized_sha256": "d1081859b204e89fb3d6172a55065ff553cd4f0976028744fc27eb32f93464ab" }, "openless-all/app/e2e/ask-window.spec.ts": { "role": "observe", @@ -3488,9 +3494,9 @@ }, "openless-all/app/e2e/capsule-overlap.spec.ts": { "role": "observe", - "sha256": "4e3aaf7c9d8f30bb9fb7b494bccaf9737eb318752c1408248d8468ed092b8397", - "size": 16133, - "normalized_sha256": "4e3aaf7c9d8f30bb9fb7b494bccaf9737eb318752c1408248d8468ed092b8397" + "sha256": "8885f08e4a429b7b76d0eff0dec8a26ec6357498641ea8f080e2388b3d09768b", + "size": 16247, + "normalized_sha256": "8885f08e4a429b7b76d0eff0dec8a26ec6357498641ea8f080e2388b3d09768b" }, "openless-all/app/e2e/capsule-reference-motion.spec.ts": { "role": "observe", @@ -3578,15 +3584,15 @@ }, "openless-all/app/e2e/history-store.spec.ts": { "role": "observe", - "sha256": "475eee29370b50bfaca2a56b015d64187cd8fab244eeb7420d1dcc11a28ea7ed", - "size": 20088, - "normalized_sha256": "475eee29370b50bfaca2a56b015d64187cd8fab244eeb7420d1dcc11a28ea7ed" + "sha256": "2a39b16e11d9f73bfefe415024b33b19716482791ff78bb62fe8dd4c8dd43f87", + "size": 13110, + "normalized_sha256": "2a39b16e11d9f73bfefe415024b33b19716482791ff78bb62fe8dd4c8dd43f87" }, "openless-all/app/e2e/interaction-polish.spec.ts": { "role": "observe", - "sha256": "9b05985d438cad477dc883fe0535f56ad4f859b5455543dac4a8ee5d4ad03f9c", - "size": 8275, - "normalized_sha256": "9b05985d438cad477dc883fe0535f56ad4f859b5455543dac4a8ee5d4ad03f9c" + "sha256": "6d8fe670fc10e530199c9f08f63f911a8942aea5c9eca3f4582292b2e71e1272", + "size": 3700, + "normalized_sha256": "6d8fe670fc10e530199c9f08f63f911a8942aea5c9eca3f4582292b2e71e1272" }, "openless-all/app/e2e/live-input-settings.spec.ts": { "role": "observe", @@ -3716,9 +3722,9 @@ }, "openless-all/app/e2e/shortcut-clear-dropdown.spec.ts": { "role": "observe", - "sha256": "80ce8ae208a08a2eef9094b9fe74ceb6abdc4cd5bf5e272035837887bde6cf50", - "size": 3863, - "normalized_sha256": "80ce8ae208a08a2eef9094b9fe74ceb6abdc4cd5bf5e272035837887bde6cf50" + "sha256": "4800b6942410affbcc4c7746d3a84637eb9823f8474dedd917fa7b958f3a297b", + "size": 3701, + "normalized_sha256": "4800b6942410affbcc4c7746d3a84637eb9823f8474dedd917fa7b958f3a297b" }, "openless-all/app/e2e/siwc.spec.ts": { "role": "observe", @@ -4392,9 +4398,9 @@ }, "openless-all/app/harmony/ipc-audit.json": { "role": "index", - "sha256": "e8ecababe505d9c052cb776bed21eee2b320be6e045105e4590d17ae3625ac4c", - "size": 31914, - "normalized_sha256": "e8ecababe505d9c052cb776bed21eee2b320be6e045105e4590d17ae3625ac4c" + "sha256": "29bd8d14ec676300dba5d57581739942635ab2d77eb46554afab1e86c5482fc0", + "size": 29889, + "normalized_sha256": "29bd8d14ec676300dba5d57581739942635ab2d77eb46554afab1e86c5482fc0" }, "openless-all/app/harmony/oh-package.json5": { "role": "index", @@ -4753,9 +4759,15 @@ }, "openless-all/app/linux-egui/src/audio.rs": { "role": "index", - "sha256": "69e53336646e3b676967c5d92ec8707a68bb9601d0c992ca220283809a5dcd22", - "size": 60903, - "normalized_sha256": "69e53336646e3b676967c5d92ec8707a68bb9601d0c992ca220283809a5dcd22" + "sha256": "19a902c4c8adedd2c6ff834c6de232a40b159f72cdf6a416ba0a1b879ccd3d20", + "size": 59367, + "normalized_sha256": "19a902c4c8adedd2c6ff834c6de232a40b159f72cdf6a416ba0a1b879ccd3d20" + }, + "openless-all/app/linux-egui/src/audio/archive.rs": { + "role": "index", + "sha256": "027da4efc5c3fe3bdd982cea24c7c76a2874f91cfd0c0d8953334eb487c9a320", + "size": 4236, + "normalized_sha256": "027da4efc5c3fe3bdd982cea24c7c76a2874f91cfd0c0d8953334eb487c9a320" }, "openless-all/app/linux-egui/src/audio_cue.rs": { "role": "index", @@ -5634,9 +5646,9 @@ }, "openless-all/app/scripts/ci-consolidation.test.mjs": { "role": "index", - "sha256": "c7756911ece58ebe6863ebac3d87350a1bceae668cef7add18d4a1738b089832", - "size": 7541, - "normalized_sha256": "c7756911ece58ebe6863ebac3d87350a1bceae668cef7add18d4a1738b089832" + "sha256": "91de3939182c4b1449a5b303d9c100a041f3bad4059db2f2c149128c656bab9b", + "size": 7629, + "normalized_sha256": "91de3939182c4b1449a5b303d9c100a041f3bad4059db2f2c149128c656bab9b" }, "openless-all/app/scripts/ci-impact.mjs": { "role": "index", @@ -6366,9 +6378,9 @@ }, "openless-all/app/scripts/shared-backend-wire-contract.test.mjs": { "role": "index", - "sha256": "f47394045db027837a6ec1e3b0ed5b7eed8cb8f08cd3bf1bf3cadc0e393e4876", - "size": 28799, - "normalized_sha256": "f47394045db027837a6ec1e3b0ed5b7eed8cb8f08cd3bf1bf3cadc0e393e4876" + "sha256": "05ef43968390c338a54fb7f845fcfc5e5cb298ab39d975e27bbc6350682b1eda", + "size": 28947, + "normalized_sha256": "05ef43968390c338a54fb7f845fcfc5e5cb298ab39d975e27bbc6350682b1eda" }, "openless-all/app/scripts/sherpa-onnx-android.mjs": { "role": "index", @@ -6474,9 +6486,9 @@ }, "openless-all/app/scripts/test-recorder-module.py": { "role": "index", - "sha256": "548f084d5a194236c2a33857cfe3d33dd2020121f9c6c4398df68e876acfa080", - "size": 3952, - "normalized_sha256": "548f084d5a194236c2a33857cfe3d33dd2020121f9c6c4398df68e876acfa080" + "sha256": "304b7cca0fd86c65465d682351495be17a9e77e2ce174efcba3275e7fdc1a0ac", + "size": 4009, + "normalized_sha256": "304b7cca0fd86c65465d682351495be17a9e77e2ce174efcba3275e7fdc1a0ac" }, "openless-all/app/scripts/test-windows-hang-diagnostics.py": { "role": "index", @@ -6606,9 +6618,9 @@ }, "openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs": { "role": "index", - "sha256": "2214469b186adf1a1e453089ebc26e745cac19eafe74c4eb5962672599c7a644", - "size": 9758, - "normalized_sha256": "2214469b186adf1a1e453089ebc26e745cac19eafe74c4eb5962672599c7a644" + "sha256": "38d6eb85b60c522fe352a8d258191517747a460a705c53647638d0ac48939623", + "size": 9760, + "normalized_sha256": "38d6eb85b60c522fe352a8d258191517747a460a705c53647638d0ac48939623" }, "openless-all/app/scripts/windows-hotkey-injection-smoke.ps1": { "role": "index", @@ -6660,9 +6672,9 @@ }, "openless-all/app/scripts/windows-insertion-target-contract.test.mjs": { "role": "index", - "sha256": "74d045bba2fa69ba93478cd98bfb5170528e7e8aeec921bd5cbdf31e0b1392a1", - "size": 7003, - "normalized_sha256": "74d045bba2fa69ba93478cd98bfb5170528e7e8aeec921bd5cbdf31e0b1392a1" + "sha256": "099648483c3f581473e10af3e06aa320959780ec7fd598d43f6575788efc5a86", + "size": 7011, + "normalized_sha256": "099648483c3f581473e10af3e06aa320959780ec7fd598d43f6575788efc5a86" }, "openless-all/app/scripts/windows-keyboard-list-removal.test.mjs": { "role": "index", @@ -6839,9 +6851,9 @@ }, "openless-all/app/src-tauri/backend-tests/Cargo.lock": { "role": "index", - "sha256": "6859cc3be77675a0a0eabd3be8b9e7caccf92d6dbfe9134103891e41eabacc32", - "size": 101140, - "normalized_sha256": "6859cc3be77675a0a0eabd3be8b9e7caccf92d6dbfe9134103891e41eabacc32" + "sha256": "f00ef37bc3ec7a25e71f1748233b7c1837953e0ce511d24875c4eb5d04a093cd", + "size": 101790, + "normalized_sha256": "f00ef37bc3ec7a25e71f1748233b7c1837953e0ce511d24875c4eb5d04a093cd" }, "openless-all/app/src-tauri/backend-tests/Cargo.toml": { "role": "index", @@ -7001,9 +7013,9 @@ }, "openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs": { "role": "observe", - "sha256": "9f1ae1b239939ca54240dc340a99f3ea49056bbc86dfbbe73cf72032a985a813", - "size": 1090, - "normalized_sha256": "9f1ae1b239939ca54240dc340a99f3ea49056bbc86dfbbe73cf72032a985a813" + "sha256": "2faf7dd6abce62d2cdcd068c7e4f08b41ad7c41b848cdfd8c8466f0f4867c0be", + "size": 1791, + "normalized_sha256": "2faf7dd6abce62d2cdcd068c7e4f08b41ad7c41b848cdfd8c8466f0f4867c0be" }, "openless-all/app/src-tauri/backend-tests/tests/uia_cursor_text.rs": { "role": "observe", @@ -7889,15 +7901,15 @@ }, "openless-all/app/src-tauri/src/commands/history.rs": { "role": "index", - "sha256": "584c34ec3bea6a5a52fe04bf5a18a069fb92ec8fce6ac1bb4c22dc676e68e121", - "size": 13519, - "normalized_sha256": "584c34ec3bea6a5a52fe04bf5a18a069fb92ec8fce6ac1bb4c22dc676e68e121" + "sha256": "aff1f3cd0b30b5a4ecb8922c57e766823bbd14408112acc189c9c14a54209fd6", + "size": 13805, + "normalized_sha256": "aff1f3cd0b30b5a4ecb8922c57e766823bbd14408112acc189c9c14a54209fd6" }, "openless-all/app/src-tauri/src/commands/history_retranscription.rs": { "role": "index", - "sha256": "7955bfd82816d060ae056bd7c11525bba878ac9a0c69dac3acc36dd082c6f518", - "size": 4045, - "normalized_sha256": "7955bfd82816d060ae056bd7c11525bba878ac9a0c69dac3acc36dd082c6f518" + "sha256": "6a9754d2edaa16ad2c284240d0ad3a838ee922147b616561f4a93fc1db2f00c3", + "size": 11167, + "normalized_sha256": "6a9754d2edaa16ad2c284240d0ad3a838ee922147b616561f4a93fc1db2f00c3" }, "openless-all/app/src-tauri/src/commands/hotkeys.rs": { "role": "index", @@ -7961,9 +7973,9 @@ }, "openless-all/app/src-tauri/src/commands/selection_voice.rs": { "role": "index", - "sha256": "29e926a7e72df35f91b5dc0bfb0aec227bef0b6757b0202ef4a26a0413104ad1", - "size": 7710, - "normalized_sha256": "29e926a7e72df35f91b5dc0bfb0aec227bef0b6757b0202ef4a26a0413104ad1" + "sha256": "1b33a30a24b93e6254d4094b3159a0e64801339927333de3c79c42c24ce34618", + "size": 7674, + "normalized_sha256": "1b33a30a24b93e6254d4094b3159a0e64801339927333de3c79c42c24ce34618" }, "openless-all/app/src-tauri/src/commands/settings.rs": { "role": "index", @@ -8033,9 +8045,9 @@ }, "openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs": { "role": "index", - "sha256": "7c10456a13f0addf92a55852d07d597abd0957efadc0f1b69f34aac7878ef999", - "size": 36443, - "normalized_sha256": "7c10456a13f0addf92a55852d07d597abd0957efadc0f1b69f34aac7878ef999" + "sha256": "59dbba88f8e5d86b0ace525696e17305e31993df155ffa30db429b814a0e3ecf", + "size": 36279, + "normalized_sha256": "59dbba88f8e5d86b0ace525696e17305e31993df155ffa30db429b814a0e3ecf" }, "openless-all/app/src-tauri/src/coordinator/voice_edit_session.rs": { "role": "index", @@ -8051,9 +8063,9 @@ }, "openless-all/app/src-tauri/src/core_adapters.rs": { "role": "index", - "sha256": "1c7544a3a45db47a24dd515d547036c83344bcfb5908b7575a69e02900f3e644", - "size": 256321, - "normalized_sha256": "1c7544a3a45db47a24dd515d547036c83344bcfb5908b7575a69e02900f3e644" + "sha256": "8a27f396d36a28b1caf7ea46bf23d0b91eb85b372991a947a76a3c98f784eb7a", + "size": 270268, + "normalized_sha256": "8a27f396d36a28b1caf7ea46bf23d0b91eb85b372991a947a76a3c98f784eb7a" }, "openless-all/app/src-tauri/src/correction.rs": { "role": "index", @@ -8123,9 +8135,9 @@ }, "openless-all/app/src-tauri/src/hotkey.rs": { "role": "index", - "sha256": "b22498af2599c79ac768df98a78ad35e2ee802faed4b3e015230467b11b842de", - "size": 129407, - "normalized_sha256": "b22498af2599c79ac768df98a78ad35e2ee802faed4b3e015230467b11b842de" + "sha256": "99bbebc69c5f11e12ed25cd181c77198bbb401a62195172cd576de5e479f49e9", + "size": 129349, + "normalized_sha256": "99bbebc69c5f11e12ed25cd181c77198bbb401a62195172cd576de5e479f49e9" }, "openless-all/app/src-tauri/src/insertion.rs": { "role": "index", @@ -8147,9 +8159,9 @@ }, "openless-all/app/src-tauri/src/lib.rs": { "role": "index", - "sha256": "0a0a62d0e79baff2f8dd76333d17ffb51a3e5f032d9f51f0e35bd60f424cd006", - "size": 168109, - "normalized_sha256": "0a0a62d0e79baff2f8dd76333d17ffb51a3e5f032d9f51f0e35bd60f424cd006" + "sha256": "726b9f6f4aacdeda07c04b3a5f4a38a6e70cfde0329f5dabfa56f509099867ca", + "size": 167916, + "normalized_sha256": "726b9f6f4aacdeda07c04b3a5f4a38a6e70cfde0329f5dabfa56f509099867ca" }, "openless-all/app/src-tauri/src/llm_gemini.rs": { "role": "index", @@ -8351,9 +8363,9 @@ }, "openless-all/app/src-tauri/src/persistence/paths.rs": { "role": "index", - "sha256": "0589f5fc198fdd61ea008cbca3ef5c245753424698f4f3933192812d0f9455d2", - "size": 7760, - "normalized_sha256": "0589f5fc198fdd61ea008cbca3ef5c245753424698f4f3933192812d0f9455d2" + "sha256": "47b3b87c232e38b70a75b91c46a7e14465898ab751a592556b45f5c01bb7400b", + "size": 12488, + "normalized_sha256": "47b3b87c232e38b70a75b91c46a7e14465898ab751a592556b45f5c01bb7400b" }, "openless-all/app/src-tauri/src/persistence/preferences.rs": { "role": "index", @@ -8423,9 +8435,9 @@ }, "openless-all/app/src-tauri/src/recorder.rs": { "role": "index", - "sha256": "12be28b5214b6fd67f371c40c5beef8c8e96d42b68ce5ec248b17885c7dde9a8", - "size": 185292, - "normalized_sha256": "12be28b5214b6fd67f371c40c5beef8c8e96d42b68ce5ec248b17885c7dde9a8" + "sha256": "c706c9235c0893dab1fcbdc883e09897fa59cef581856c61cf9988ea2840cccf", + "size": 200881, + "normalized_sha256": "c706c9235c0893dab1fcbdc883e09897fa59cef581856c61cf9988ea2840cccf" }, "openless-all/app/src-tauri/src/recorder/android_capture.rs": { "role": "index", @@ -8459,9 +8471,9 @@ }, "openless-all/app/src-tauri/src/selection.rs": { "role": "index", - "sha256": "14abb64328a55dc8d927324dc21521f53390531b116bb87a1b64b0c4b68097c2", - "size": 85008, - "normalized_sha256": "14abb64328a55dc8d927324dc21521f53390531b116bb87a1b64b0c4b68097c2" + "sha256": "001e0551d74c2bd7364f011cb2820946d343960321e33a0ec4e6b309f61fb4fc", + "size": 84954, + "normalized_sha256": "001e0551d74c2bd7364f011cb2820946d343960321e33a0ec4e6b309f61fb4fc" }, "openless-all/app/src-tauri/src/selection/clipboard_capture.rs": { "role": "index", @@ -9155,9 +9167,9 @@ }, "openless-all/app/src/api/dictation.ts": { "role": "index", - "sha256": "d52ed38a59e78207233f6361a4d72278d80063c38bb0ac139b63bd9e15073d7c", - "size": 1907, - "normalized_sha256": "d52ed38a59e78207233f6361a4d72278d80063c38bb0ac139b63bd9e15073d7c" + "sha256": "5c67460617ae390073059eeeb8af1341b67cdf5a3f089b67cbd8975300540a7d", + "size": 2183, + "normalized_sha256": "5c67460617ae390073059eeeb8af1341b67cdf5a3f089b67cbd8975300540a7d" }, "openless-all/app/src/api/files.ts": { "role": "index", @@ -9377,9 +9389,9 @@ }, "openless-all/app/src/app/shell/navigation.ts": { "role": "index", - "sha256": "208fb76990dd47815362d6edab5414a002aa2f6083d8edd658e5c1cf31828dd1", - "size": 3478, - "normalized_sha256": "208fb76990dd47815362d6edab5414a002aa2f6083d8edd658e5c1cf31828dd1" + "sha256": "d1118e13c1187e6d5e6f27270a926c80baccd77850442a925f11551074fc1fda", + "size": 3371, + "normalized_sha256": "d1118e13c1187e6d5e6f27270a926c80baccd77850442a925f11551074fc1fda" }, "openless-all/app/src/app/shell/pages.tsx": { "role": "index", @@ -9809,9 +9821,9 @@ }, "openless-all/app/src/features/capsule/Capsule.tsx": { "role": "index", - "sha256": "1ea5188dc0cfbd0f32dc2a684487abf9a285cc77c6612df99d7a7f5ca7cf4a97", - "size": 42531, - "normalized_sha256": "1ea5188dc0cfbd0f32dc2a684487abf9a285cc77c6612df99d7a7f5ca7cf4a97" + "sha256": "ec530d70e98a7832d4f24d60f1057349017b6a65ca36e09e2841109cfaaed2db", + "size": 42472, + "normalized_sha256": "ec530d70e98a7832d4f24d60f1057349017b6a65ca36e09e2841109cfaaed2db" }, "openless-all/app/src/features/capsule/CapsuleStyles.css": { "role": "index", @@ -10679,9 +10691,9 @@ }, "openless-all/app/src/features/settings/shell/tabs.tsx": { "role": "index", - "sha256": "71fbcfa2e1c51fa490d17f5b1d9c70771203e286068ef5753174d5ef60ce2591", - "size": 27395, - "normalized_sha256": "71fbcfa2e1c51fa490d17f5b1d9c70771203e286068ef5753174d5ef60ce2591" + "sha256": "6d8305dd06ba56df12997bc7521a7c82f3732ac4732ba138c6ebbf55c71c8994", + "size": 27323, + "normalized_sha256": "6d8305dd06ba56df12997bc7521a7c82f3732ac4732ba138c6ebbf55c71c8994" }, "openless-all/app/src/features/settings/shell/useSettingsLayer.ts": { "role": "index", @@ -13279,9 +13291,9 @@ }, "openless-all/ios/CoreHost/Patches/ios-input-contracts.patch": { "role": "index", - "sha256": "f7a13e271402b9fdc72e2549a54edc1a020c608040fa92250b7ce00bf3a710a9", - "size": 73149, - "normalized_sha256": "f7a13e271402b9fdc72e2549a54edc1a020c608040fa92250b7ce00bf3a710a9" + "sha256": "ea46c1acbc825a06e5705fa886e6c03e6c344b3bf666c86ad4f46c7b18c0abe1", + "size": 70780, + "normalized_sha256": "ea46c1acbc825a06e5705fa886e6c03e6c344b3bf666c86ad4f46c7b18c0abe1" }, "openless-all/ios/CoreHost/include/OpenLessCore.h": { "role": "index", @@ -13345,15 +13357,15 @@ }, "openless-all/ios/CoreHost/src/recording_maintenance_tests.rs": { "role": "index", - "sha256": "14d3fc9b0f38a98d0fd8c0b089e833461dccddb437a047321d455b3c5f839b4f", - "size": 19301, - "normalized_sha256": "14d3fc9b0f38a98d0fd8c0b089e833461dccddb437a047321d455b3c5f839b4f" + "sha256": "47664dc45a229ec809826d1747d8791dfe82ed093a4f91f2a83ddcf62e6308eb", + "size": 19967, + "normalized_sha256": "47664dc45a229ec809826d1747d8791dfe82ed093a4f91f2a83ddcf62e6308eb" }, "openless-all/ios/CoreHost/src/recordings.rs": { "role": "index", - "sha256": "57508e90aed33cdc217f12600fb8d6632651629cc20a8af2047ca7bbb9a1a9b9", - "size": 12519, - "normalized_sha256": "57508e90aed33cdc217f12600fb8d6632651629cc20a8af2047ca7bbb9a1a9b9" + "sha256": "f3487ebed802dcdf4c3fc597081c3da9e40eab96f0a916ca464d7fd2eb9d4dfa", + "size": 13290, + "normalized_sha256": "f3487ebed802dcdf4c3fc597081c3da9e40eab96f0a916ca464d7fd2eb9d4dfa" }, "openless-all/ios/CoreHost/src/selection.rs": { "role": "index", @@ -17146,9 +17158,9 @@ }, "openless-all/ios/scripts/prepare-core.py": { "role": "index", - "sha256": "25726a9700bdc25b33ebf1b33d1fec35497ada16f0724b6da7ed67cc8366e3e6", - "size": 4433, - "normalized_sha256": "25726a9700bdc25b33ebf1b33d1fec35497ada16f0724b6da7ed67cc8366e3e6" + "sha256": "1154cf1c18095c79baa6d93c488479d2b9b8cbd002beb209dc5b3c0d02f6fb54", + "size": 4447, + "normalized_sha256": "1154cf1c18095c79baa6d93c488479d2b9b8cbd002beb209dc5b3c0d02f6fb54" }, "openless-all/ios/scripts/preview.sh": { "role": "index", diff --git a/aoci.code.txt b/aoci.code.txt index 757849c70..5c5171c41 100644 --- a/aoci.code.txt +++ b/aoci.code.txt @@ -298,15 +298,15 @@ gemini_transcribe_smoke.rs[XN4M]: F:Exercises configured Gemini validation and l ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/=== activity.rs[PD6L]: F:Persists date-bounded text-free daily counts, durations and app activity with stable device contributions for sync | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs | A:ActivityStore, bind_sync_device, bump, sync_replace_records | S:Binding a device never reattributes imported activity to it. Writes participate in the optional encrypted sync mutation gate. android_types.rs[FC5L]: F:Defines serialized Android overlay, insertion, accessibility and Shizuku preferences and computes overlay settings effects | R:code:openless-all/app/android/frontend/lib/androidTypes.ts | A:AndroidOverlayTrigger, AndroidOverlayStatus, AndroidAccessibilityRecoveryResult | S:Overlay settings distinguish a trigger transition from relayout and changes with no overlay action. -api.rs[AG9L]: F:Exposes the shared backend and constructs standalone Ask with the personal assistant, scoped host context and shared usage services | R:code:openless-all/app/crates/openless-core/src/assistant.rs,code:openless-all/app/crates/openless-core/src/qa_service/standalone.rs,code:openless-all/app/crates/openless-core/src/ports.rs | A:OpenLessBackend,create_standalone_ask,update_settings,start_dictation_for_ask_composer,subscribe | S:Assistant and entry reuse the same configured models, search and usage recorder; do not create a separate recorder that bypasses notifications. Settings writes remain revision-serialized. Ask dictation suppresses ordinary external insertion and rechecks recording ownership; previous sessions cannot mutate successors. +api.rs[AG9L]: F:Owns shared backend lifecycle, session routing, settings, history and standalone assistant services | R:code:openless-all/app/crates/openless-core/src/ports.rs,code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/crates/openless-core/src/assistant.rs | A:OpenLessBackend,update_settings,cancel_dictation,create_standalone_ask | S:CapturedDurationMs aligns history draft protection with engine PCM duration. Translation suppresses expression guidance at execution but retains the captured profile for toggling back. Session generations reject late progress. Assistant and entry share usage recording; settings writes stay revision-serialized. ask_context.rs[DS6M]: F:Builds typed Ask context facts and unavailable reasons from the device clock and authorized invocation metadata | R:code:openless-all/app/crates/openless-core/src/qa_service/standalone.rs | A:InvocationContext, ContextProvider, TurnContext | S:Invocation and device-clock facts keep separate times. Weather or spend is represented as unavailable when there is no authorized evidence. ask_search.rs[DN7L]: F:Authorizes a single public Ask search query per attempt, runs bounded retrieval and emits turn-scoped evidence and status | R:code:openless-all/app/crates/openless-core/src/web_search.rs,code:openless-all/app/crates/openless-core/src/qa_service/standalone.rs | A:SearchTurn,SearchAttempt,SearchRun | S:Consume the validated public query once. Keep private prompts and attachments out of search arguments, and stop retrieval after cancellation. ask_voice_capture.rs[AH7M]: F:Reserves and runs standalone Ask microphone capture with silence detection and ASR or multimodal transcription | R:code:openless-all/app/crates/openless-core/src/api.rs, code:openless-all/app/crates/openless-core/src/voice_session.rs | A:Reservation, Capture, Observer | S:Capture owns its reservation and releases it on cancellation or drop. Finishing takes the recording once and seals the matching lifecycle. -audio.rs[KH8L]: F:Normalizes native microphone audio and runs a session-frozen enhancement chain, reference alignment and WAV archive conversion | R:code:openless-all/app/crates/openless-core/src/audio_dsp.rs, code:openless-all/app/crates/micyou-dsp/src/lib.rs | A:AudioProcessor, PcmNormalizer, reset_echo_cancellers, decode_dictation_wav | S:A mid-session audio format change requires resetting processing. Match sample rates before echo cancellation and bound reference backlog. +audio.rs[KH8L]: F:Normalizes audio with stateful antialias filtering and DSP, aligns references and supplies validated bounded archive reads | R:code:openless-all/app/crates/openless-core/src/audio_dsp.rs,code:openless-all/app/crates/micyou-dsp/src/lib.rs | A:AudioProcessor,PcmNormalizer,decode_dictation_wav,canonical_archive_pcm_len,read_canonical_archive_pcm_range | S:Downsampling retains filter history across callback blocks. Reset on format changes; match reference rates and bound backlog. Archive readers require app-generated fixed 44-byte PCM WAV and validate RIFF length, file length, format and sample-aligned range bounds. The general WAV decoder also accepts metadata chunks. audio_dsp.rs[FH6L]: F:Defines compatible DSP settings and processing order and implements the resampler feeding the MicYou chain | R:code:openless-all/app/crates/openless-core/src/audio.rs, code:openless-all/app/crates/micyou-dsp/src/lib.rs | A:AecMode, AudioDspConfig, SpeechResampler | S:Older Boolean echo preferences retain a supported interpretation. Common clocks reuse bounded sinc phases while unusual rates avoid an unbounded cache. -auxiliary.rs[AB6L]: F:Coordinates re-polishing and archived-audio retranscription using frozen Core provider and style choices | R:code:openless-all/app/crates/openless-core/src/cloud_providers.rs,code:openless-all/app/crates/openless-core/src/asr/volcengine.rs,code:openless-all/app/crates/openless-core/src/dictation_engine.rs | A:RepolishRequest,retranscribe_pcm,RetranscriptionCancelGuard | S:Validate PCM before capture; long repolish text chunks via dictation_engine. Volcengine archive replay sends target-sized chunks 100 ms apart; abandoning the future cancels its session. +auxiliary.rs[AB6L]: F:Coordinates frozen-provider repolish and PCM or ranged-archive retranscription with segmented long-audio retries | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:retranscribe_pcm,retranscribe_archive,RetranscriptionCancelGuard | S:Long audio runs serial sixty-second segments; a short archive read fails rather than skipping input. Dropping a request cancels its session. Long repolish reuses the shared text path. cli.rs[EC4S]: F:Parses launcher flags and encodes shared single-instance actions for main window, dictation and QA | R:- | A:LaunchIntent, encode_launch_intent, parse_cli_intent | S:Returns the first recognized option after argv0. -cloud_providers.rs[AN8L]: F:Builds cloud ASR, LLM and multimodal sessions and maps post-ASR overrides into provider-specific requests | R:code:openless-all/app/crates/openless-core/src/provider_rules.rs,code:openless-all/app/crates/openless-core/src/polish_strategy.rs,code:openless-all/app/crates/openless-core/src/qa_service/standalone/model.rs | A:prepare_cloud_transcription,build_cloud_channel_provider,build_cloud_polisher_provider,validate_cloud_transcription_preparation | S:Validate credentials before capture. Header overrides cannot replace authentication. Dictation supplies request overrides but Ask passes None; shared builders must preserve that boundary. Failed Volcengine final-frame sending cancels transport while retaining an already delivered final result. +cloud_providers.rs[AN8L]: F:Builds shared cloud ASR and LLM sessions and verifies transport completion before accepting streaming transcripts | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/crates/openless-core/src/asr/volcengine.rs,code:openless-all/app/crates/openless-core/src/auxiliary.rs | A:finalize_streaming_transcript,build_cloud_channel_provider,prepare_cloud_transcription | S:Long sessions reject failed terminal sends or incomplete transport. Short sessions salvage nonempty text only with <=1s unsent PCM, keeping retryable=true when salvage fails or is blank; cancel never proves full audio. Dictation overrides cannot replace auth; Ask passes none. cloud_sync.rs[AN6L]: F:Implements legacy cloud snapshot status, upload, restore and delete and maps portable fields to local repositories | R:code:openless-all/app/crates/openless-core/src/cloud_sync_types.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_transaction.rs | A:CloudSyncUiPreferences,status,restore_local_unchecked,apply_preferences | S:Credentials and device state are outside the DTO. A registered mutation gate fences legacy multi-file restore alongside encrypted sync and migration. cloud_sync_transaction.rs[PR6S]: F:Stages private replacements and before-images and compensates failed legacy cloud restore file writes | R:code:openless-all/app/crates/openless-core/src/cloud_sync.rs | A:RestoreTransaction, prepare, write_private_file | S:If compensation fails, preserve the recovery files and report an unknown local outcome. cloud_sync_types.rs[LS5M]: F:Defines versioned portable legacy sync payloads, requests, preferences and revision bounds | R:code:openless-all/app/crates/openless-core/src/cloud_sync_validation.rs | A:SYNC_SCHEMA_VERSION, SYNC_MAX_BODY_BYTES, CloudSyncDeleteRequest, SyncPreferences | S:Revision stays within the JavaScript safe integer limit. Only selected preference and style fields are represented. @@ -321,7 +321,7 @@ credentials_legacy.rs[IS6L]: F:Reads and converts legacy desktop vault documents deepseek_suite.rs[AC5S]: F:Stores the dedicated DeepSeek pipeline configuration and exposes its provider invocation and credential readiness | R:code:openless-all/app/crates/openless-core/src/dictation_context.rs, code:docs/deepseek-suite.md | A:DeepSeekSuiteConfig, credentials_status | S:Suite configuration is separate from traditional and multimodal provider selection. deepseek_tts.rs[IN5S]: F:Streams validated text to DeepSeek speech synthesis and passes bounded PCM frames to its consumer | R:code:docs/deepseek-suite.md | A:stream, stream_url | S:Only a successful finish confirms complete output. Invalid text or voice is rejected before connecting. dictation_context.rs[DB7L]: F:Freezes provider identities, style, post-ASR policy, history eligibility and output-target rules for each dictation | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/crates/openless-core/src/polish_strategy.rs | A:DictationContext,DictationPolishContext,ProviderInvocation,effective_polish_prompts,eligible_polish_context_turns | S:Capture uses a session snapshot, including the strategy script. Request overrides start empty; short-text skipping remains target-specific and cannot suppress requested translation. -dictation_engine.rs[AB9L]: F:Orchestrates recording, racing ASR routes, correction, post-ASR policy, polishing, progress and session cleanup | R:code:openless-all/app/crates/openless-core/src/dictation_context.rs,code:openless-all/app/crates/openless-core/src/ports.rs,code:openless-all/app/crates/openless-core/src/polish_strategy.rs | A:PipelineDictationEngine,LocalStandby,buffered_transcription_session,strategy_skips_polish | S:Bound queued PCM and prevent cancelled speech replay into successor sessions. Evaluate policy after correction using the winning ASR metadata; QA bypasses it. Skip applies only to plain dictation without translation, and request overrides affect a cloned polish context, never saved preferences. +dictation_engine.rs[AB9L]: F:Orchestrates capture, buffered or live ASR, archive recovery, local standby, polishing and terminal cleanup | R:code:openless-all/app/crates/openless-core/src/ports.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs,code:openless-all/app/crates/openless-core/src/long_recording.rs | A:PipelineDictationEngine,LocalStandby,BufferedTranscriptionSession,retry_transcription_from_archive | S:Reject nonzero PCM shorter than 100 ms. Both capture entries spill past 8 MiB only with a healthy processed-PCM archive; raw-only debug archives must not replace enhanced ASR input and retain memory stop protection. Finish validates captured byte length. Long recovery and local standby read sixty-second ranges, never accept a partial segment set. CapturedDurationMs precedes final ASR progress. Cancelled audio cannot enter successors; post-ASR policy uses winning metadata and cloned settings. domains.rs[LG8L]: F:Defines host-facing runtime ports and DTOs for recording, QA, selection, agent, remote input and other platform services | R:code:openless-all/app/crates/openless-core/src/api.rs | A:RuntimeRestoreGuard,VoiceEditPlanResult | S:Runtime operations are scoped to the owning turn or session. Serialized remote input status and events exclude pairing credentials. edit_plan.rs[KB6L]: F:Parses structured selection edit proposals and deterministically applies bounded literal, regex and full rewrite operations | R:code:openless-all/app/crates/openless-core/src/selection_voice_service.rs | A:EditPlan,RegexFlags,EditOperation | S:Bound operation count and lengths and mask credential-shaped text where the literal replacement path handles sensitive spans. endpoint_security.rs[KS6S]: F:Validates configured HTTP endpoints and prepares one DNS resolution for adapters to reuse on connection | R:code:openless-all/app/crates/openless-core/src/net.rs | A:ResolvedEndpoint, validate_http_endpoint, resolve_http_endpoint | S:Syntax validation permits user-selected networks. Literal IP addresses do not need a DNS pin, and hostname callers should reuse the returned addresses. @@ -351,7 +351,7 @@ omni.rs[AN7L]: F:Dispatches text/audio multimodal completion and streaming with output_cleaning.rs[KA5L]: F:Removes model thinking blocks, wrapping fences and routine prefixes from text-polish results | R:code:openless-all/app/crates/openless-core/src/polish.rs | A:clean_polish_output, sentence_like_segments | S:Sentence segmentation preserves decimal points and common abbreviations. persistence.rs[PD7M]: F:Provides atomic JSON replacement, durable writes and lossless reads for shared file repositories | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs | A:atomic_write, atomic_write_for_sync, ensure_durable_file, read_lossless_rows | S:Ordinary writes acquire the optional mutation permit. Sync replacement uses its existing exclusive permit and tracks failures after rename distinctly. polish.rs[AN8L]: F:Builds text-polish requests and streams across compatible, Codex and agent-backed providers with strategy overrides and usage capture | R:code:openless-all/app/crates/openless-core/src/llm_protocol.rs,code:openless-all/app/crates/openless-core/src/prompt_compose.rs | A:OpenAICompatibleLLMProvider,CodexOAuthConfig,LlmUsageObserver,apply_openai_compatible_thinking_control_with_effort | S:Usage observers receive no request text and must return promptly. Provider capability rules override requested effort; official reasoning models use max_completion_tokens. Codex omits unsupported token limits and sampling fields rather than retrying an invalid request. -ports.rs[LG8L]: F:Defines native capture, insertion, resources, polish and transcription contracts including optional ASR metadata | R:code:openless-all/app/crates/openless-core/src/api.rs,code:openless-all/app/crates/openless-core/src/config.rs | A:AudioRecorder,RecordingArchive,ResourceResolver,TextPolisher,TranscriptionSession,TranscriptMetadata | S:Provisional capture requires explicit host support. Resource resolution rejects absolute and parent-relative paths. Default transcript metadata is absent; providers must not manufacture language or confidence values. +ports.rs[LG8L]: F:Defines host audio, archive, insertion, transcription, polish and progress contracts | R:code:openless-all/app/crates/openless-core/src/api.rs,code:openless-all/app/src-tauri/src/core_adapters.rs | A:RecordingArchive,EngineProgress,AudioRecorder,TranscriptionSession,TranscriptMetadata | S:Archive handles outlive capture stop. Default range reads still load whole PCM; hosts must override for bounded memory. write_error latches archive health separately from availability. CapturedDurationMs reports PCM duration, not wall time. Missing ASR metadata must remain absent. preference_patch.rs[DC6S]: F:Applies field edits to the latest preferences and retries bounded revision conflicts through the strict transaction | R:code:openless-all/app/crates/openless-core/src/api.rs | A:patch_preferences,revision_conflict,update_fields | S:Retry only explicit revision conflicts. Each retry rereads current settings so independent writes remain intact. preferences.rs[PD7L]: F:Persists, repairs, merges and snapshots device preferences while maintaining in-memory state and compatibility | R:code:openless-all/app/crates/openless-core/src/persistence.rs, code:openless-all/app/crates/openless-core/src/shared_types.rs | A:PreferencesStore, sync_replace_raw, backup_unparseable_preferences | S:Back up invalid bytes before salvage, preserve unknown compatible keys on save, and keep stale preference writes from rerouting a stored sync token. prompt_cache.rs[KP6L]: F:Applies service-specific request cache parameters and stable-prefix reuse where the actual endpoint and model support it | R:code:openless-all/app/crates/openless-core/src/llm_protocol.rs, code:docs/prompt-cache-policy.md | A:apply, supports_usage, apply_anthropic_prefixes | S:Verified origin and path determine eligibility. Caller-provided cache controls own their breakpoint budget. @@ -369,7 +369,7 @@ selection_service.rs[AB6L]: F:Controls shared selection capture, polishing, text selection_voice_intent.rs[DB6L]: F:Classifies selection voice commands, manual intent and translation and normalizes provider intent and result text | R:code:openless-all/app/crates/openless-core/src/selection_voice_service.rs | A:SelectionVoiceIntentClassification, selection_voice_instruction_looks_like_translation | S:Legacy edit keywords cannot force an unrelated question into an edit. Preserve the result body when cleaning headings. selection_voice_service.rs[AB7L]: F:Orchestrates selection voice recording, intent resolution, edit-plan generation, preview and apply or QA handoff | R:code:openless-all/app/crates/openless-core/src/selection_voice_intent.rs,code:openless-all/app/crates/openless-core/src/edit_plan.rs | A:begin_runtime_work,generate_edit_plan,voice_edit_plan | S:Retain the original selection across focus changes and require preview owner identity before applying. A stale owner cannot target a new editor. settings.rs[LC7M]: F:Defines strict settings requests, collision policy, host effect changes, rollback receipts and runtime transactions | R:code:openless-all/app/crates/openless-core/src/api.rs | A:SettingsCollisionPolicy, SettingsEffectFailure, WindowsKeyboardRuntimeTarget | S:Compute effects from effective preference state. Capture receipts before returning failures so the coordinator can compensate partial host changes. -shared_types.rs[LC8L]: F:Defines portable preferences, defaults, hotkeys, language and pipeline values including custom polish strategy settings | R:code:openless-all/app/crates/openless-core/src/preferences.rs,code:openless-all/app/crates/openless-core/src/shortcut_types.rs | A:UserPreferences,UserPreferencesWire,PipelineMode,HotkeyBinding,effective_pipeline_mode | S:Legacy settings deserialize compatibly. Strategy defaults are disabled and empty in both wire and native preferences. Effective recognition mode can differ from configured mode; native shortcut defaults remain target-specific. +shared_types.rs[LC8L]: F:Defines portable preferences, compatible wire decoding, shortcut choices and pipeline defaults | R:code:openless-all/app/crates/openless-core/src/preferences.rs,code:openless-all/app/crates/openless-core/src/shortcut_types.rs | A:UserPreferences,UserPreferencesWire,PipelineMode,effective_pipeline_mode | S:Legacy preferences retain absent optional QA shortcut and translation tap choices rather than inventing a user selection. Strategy defaults stay disabled and empty. Effective recognition mode and native shortcut defaults may differ by target. shortcut_types.rs[DH7L]: F:Validates shortcut bindings, normalizes legacy key representations and detects or reconciles collisions | R:code:openless-all/app/crates/openless-core/src/shared_types.rs, code:openless-all/app/crates/openless-core/src/settings.rs | A:ShortcutBindingError, reject_hotkey_collisions, validate_primary | S:Literal Space must stay meaningful. Mouse or Mac dictation keys are restricted to dictation, and style-pack shortcuts have lowest priority. silence_auto_stop.rs[KH5M]: F:Classifies audio levels for no-speech cancellation and one-shot stopping after speech followed by quiet | R:code:openless-all/app/crates/openless-core/src/ask_voice_capture.rs | A:SilenceAutoStop, SilenceDecision, on_level, after_speech | S:Require consecutive speech blocks before treating ordinary level spikes as speech. Wake commands can initialize the threshold as already met. streaming_insert.rs[KU7M]: F:Defines streaming insertion eligibility, text cleanup and final reconciliation against the actual typed prefix | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs | A:StreamingInsertState, FinalReconciliation, streaming_insert_eligible, resolve_macos_newline_mode | S:Write only the uninserted tail if final text still matches the typed prefix. Divergence or a failed write returns a copy fallback. @@ -413,22 +413,22 @@ tests.rs[TS4S]: F:Covers PDF worker page numbering, invalid and encrypted input, tests.rs[TB4S]: F:Checks Ask attachment leases, stale preparation, limit errors and image decode and preview behavior | R:code:openless-all/app/crates/openless-core/src/ask_attachment/registry.rs | A:selection_preview_is_scalar_bounded_and_lease_survives_removal, pending_entries_cannot_be_leased_and_late_results_do_not_reappear | S:Thumbnail preview must never return the supplied source image bytes. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/asr/=== -bailian.rs[IN6L]: F:Implements classic DashScope realtime ASR with PCM chunking, websocket task events and cumulative transcript assembly | R:code:openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs | A:send_last_frame | S:Wait for task-started before sending buffered audio. Partial updates replace the same sentence ID and residual PCM remains buffered until finish. +bailian.rs[IN6L]: F:Implements classic DashScope realtime task handshake, paced FIFO audio, completion and transcript assembly | R:code:openless-all/app/crates/openless-core/src/asr/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:send_last_frame,audio_coverage,is_stream_complete | S:Wait for task-started; finish follows audio in one worker. Send/close failures resolve final_tx atomically with send_error so concurrent cancel preserves short partials. dashscope_multimodal.rs[IN6L]: F:Transcribes recorded WAV with DashScope batch APIs, supporting synchronous requests and asynchronous upload and polling | R:code:openless-all/app/crates/openless-core/src/provider_rules.rs | A:with_protocol, async_transcription_body | S:Model protocol selects the request path. Transfer URLs are validated and long chunks have separate processing deadlines. elevenlabs.rs[IN5L]: F:Sends recorded WAV to ElevenLabs Scribe and parses the resulting text and duration | R:code:openless-all/app/crates/openless-core/src/asr/wav.rs | A:speech_to_text_url | S:Uses multipart file and model_id with the provider-specific credential header. frame.rs[KN5M]: F:Encodes and parses Volcengine binary speech frames, message types, sequence flags and error bodies | R:code:openless-all/app/crates/openless-core/src/asr/volcengine.rs | A:ParsedFrame, has_sequence | S:Parse the optional sequence only for qualifying flags. Error frames carry a distinct error code before payload size. gemini.rs[IN6L]: F:Runs dedicated Gemini batch transcription through resumable file upload, Interactions polling and cleanup | R:code:openless-all/app/crates/openless-core/src/asr/gemini_live.rs, code:docs/gemini-transcribe.md | A:transcribe_timeout, files_upload_url, cancel_interaction | S:Use the upload resource URI in the transcription interaction. Cancellation addresses both in-flight upload and interaction resources. gemini_live.rs[IN6S]: F:Exposes shared Gemini Live capture, PCM batching, finish and cancellation for traditional and smart transcription | R:code:openless-all/app/crates/openless-core/src/asr/gemini_live/session.rs | A:GeminiLiveASR, finish, consume_pcm_chunk | S:Dropping the session signals cancellation. Audio queues are bounded separately from socket setup and finish deadlines. mimo.rs[IN5L]: F:Routes batch audio transcription through MiMo or OrcaRouter chat-completions with WAV input | R:code:openless-all/app/crates/openless-core/src/asr/pcm.rs, code:openless-all/app/crates/openless-core/src/provider_rules.rs | A:cancel, pcm_duration_ms | S:Split oversized audio into request-safe chunks and combine the returned transcripts. -mod.rs[LB5T]: F:Exposes platform-independent ASR clients and common transcript output and capture test helpers | R:code:openless-all/app/crates/openless-core/src/ports.rs | A:RawTranscript, TranscriptCapture | S:- +mod.rs[LB5S]: F:Exports ASR clients and provides shared cancellable WebSocket writes, send pacing and transcript capture | R:code:openless-all/app/crates/openless-core/src/ports.rs | A:RawTranscript,PacedSendClock,send_ws_message_with_timeout,TranscriptCapture | S:Frame deadlines bound writes including writer-lock acquisition. Pacing uses scheduled slots and cancellation interrupts waits. pcm.rs[KH4T]: F:Calculates milliseconds from canonical 16 kHz mono PCM16 bytes | R:- | A:pcm_duration_ms_from_bytes, pcm_duration_ms | S:An odd trailing byte does not count as a complete sample. -qwen_realtime.rs[IN6L]: F:Implements Qwen realtime ASR WebSocket sessions with open, base64 audio, VAD segment events and transcript snapshots | R:code:openless-all/app/crates/openless-core/src/asr/bailian.rs | A:mark_session_started, endpoint_scheme_is_secure_websocket | S:The endpoint model selects the realtime schema. Unflushed PCM remains buffered across regular chunks. -stepfun_realtime.rs[IN6L]: F:Implements StepFun realtime speech configuration, audio transport and ordered VAD transcript projections | R:code:openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs | A:StepfunRealtimeCredentials, session_update_message, mark_session_started | S:Send the model in session configuration and concatenate confirmed text with the unsettled tail. Closing the last VAD segment relies on silence rather than a finish event. +qwen_realtime.rs[IN6L]: F:Implements Qwen realtime session configuration, paced FIFO audio, VAD text and completion coverage | R:code:openless-all/app/crates/openless-core/src/asr/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:send_last_frame,audio_coverage,is_stream_complete | S:Unflushed PCM flushes on finish; closed channels fail finish. Send/close errors resolve final_tx and start errors atomically so cancel cannot preempt partial salvage. +stepfun_realtime.rs[IN6L]: F:Implements StepFun realtime configuration, paced audio, VAD transcript projection and tail completion | R:code:openless-all/app/crates/openless-core/src/asr/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:send_last_frame,audio_coverage,is_stream_complete | S:Tail silence closes VAD and is excluded from byte coverage. Worker records failure atomically into final_tx before notifying written_tx so cancel keeps short partials. tencent_cloud.rs[IN6L]: F:Implements a single authenticated Tencent realtime recognition connection with ordered PCM, partial snapshots and final result handling | R:code:openless-all/app/crates/openless-core/src/asr/tencent_cloud/segmented.rs | A:connect_url, send_last_frame, flush_pending_audio, signal_error | S:Keep the trailing PCM ordered ahead of end. A final packet cannot complete a segment until the client has sent end. -volcengine.rs[IN7L]: F:Implements Volcengine SAUC authentication, ordered websocket audio, partial snapshots and final transcript assembly | R:code:openless-all/app/crates/openless-core/src/asr/frame.rs,code:docs/volcengine-setup.md | A:VolcengineStreamingASR,send_last_frame,await_final_result | S:Drain queued audio before the terminal frame; a stalled drain fails rather than overtaking audio. Utterance definite is not stream completion; only frame flags terminate reception. -wav.rs[KH3T]: F:Wraps canonical 16 kHz mono PCM16 samples in a RIFF WAV header for batch ASR | R:code:openless-all/app/crates/openless-core/src/asr/pcm.rs | A:encode_wav_16k_mono | S:- -whisper.rs[IN6L]: F:Buffers speech and calls compatible batch transcription endpoints with WAV, optional segmentation and confidence filtering | R:code:openless-all/app/crates/openless-core/src/asr/wav.rs | A:transcribe, split_pcm_by_duration | S:Missing confidence metrics keep a segment unchanged. Default chunking submits one recording unless a provider-specific limit applies. -xfyun.rs[IN6L]: F:Implements iFlytek RTASR handshake, authenticated audio streaming, transcript corrections and shutdown | R:code:docs/xfyun-asr.md | A:XfyunCredentials, open_session, finish_error | S:Errors before handshake wake the pending opener. Some close paths salvage recognized text when no final frame arrives. +volcengine.rs[IN7L]: F:Implements authenticated SAUC framing, paced FIFO audio, terminal acknowledgement and transcript assembly | R:code:openless-all/app/crates/openless-core/src/asr/frame.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:send_last_frame,audio_coverage,is_stream_complete | S:One worker sends audio before negative-sequence end; utterance definite is not completion. Faults latch send_error and claim final_tx under one lock before cancel runs. +wav.rs[KH3T]: F:Encodes canonical PCM samples or PCM bytes into a 16 kHz mono PCM16 RIFF WAV | R:code:openless-all/app/crates/openless-core/src/asr/whisper.rs | A:encode_wav_16k_mono,encode_wav_16k_mono_pcm_bytes | S:Byte encoder ignores an odd trailing byte. +whisper.rs[IN6L]: F:Submits buffered PCM to compatible batch endpoints with chunk limits and confidence filtering | R:code:openless-all/app/crates/openless-core/src/asr/wav.rs | A:transcribe,split_pcm_by_duration | S:Move PCM out for transcription and restore it before newly arrived audio on error. Direct byte WAV encoding avoids an intermediate sample copy. Missing confidence metrics retain text. +xfyun.rs[IN6L]: F:Implements authenticated RTASR handshake, realtime paced FIFO audio, end acknowledgement and corrected transcripts | R:code:openless-all/app/crates/openless-core/src/asr/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_providers.rs | A:open_session,send_last_frame,audio_coverage,is_stream_complete | S:End is a worker sentinel, never written after timeout. Handshake errors wake opener. Send/close faults resolve finished and final_tx under one lock before writer close. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/asr/gemini/=== tests.rs[TN5L]: F:Exercises Gemini endpoint normalization, silence validation, upload and interaction cancellation, and transcript formats with local fixtures | R:code:openless-all/app/crates/openless-core/src/asr/gemini.rs | A:full_interactions_endpoint_is_normalized_for_every_request, failed_or_malformed_interaction_never_validates_as_silence | S:Malformed or unsuccessful interactions cannot masquerade as successful silence verification. @@ -494,7 +494,7 @@ tests.rs[TS5L]: F:Exercises native encrypted sync repository capture, mutation f tests.rs[TA5L]: F:Exercises experimental model downloads, activation, cancellation, validation failure and unsupported runtimes through fixtures | R:code:openless-all/app/crates/openless-core/src/experimental_asr.rs | A:Fixture, failed_download_never_creates_ready_channels, unsupported_models_are_not_downloaded | S:A failed or corrupt download cannot publish a ready channel. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/external_audio/=== -archive.rs[PD5M]: F:Writes and finalizes retained external recording WAV files and enforces archive retention and deletion | R:code:openless-all/app/crates/openless-core/src/external_audio.rs | A:ExternalRecordingArchive, append, discard | S:Archive state belongs to one session and must finalize the WAV before reporting it available. +archive.rs[PD5M]: F:Writes retained external recording WAVs and supports validated bounded range reads, retention and deletion | R:code:openless-all/app/crates/openless-core/src/external_audio.rs,code:openless-all/app/crates/openless-core/src/audio.rs | A:ExternalRecordingArchive,append,pcm_byte_len,read_pcm_range | S:Range reads validate the finalized header and length without loading the whole WAV. One session owns archive state; finish syncs its file before recovery. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/host_document/=== diff.rs[KA5L]: F:Extracts a minimal bounded text edit and derives learnable corrections across Unicode word and identifier boundaries | R:code:openless-all/app/crates/openless-core/src/correction_observation.rs | A:minimal_edit, learned_rule, identifier_span | S:An expanded word must satisfy its length bound as a whole rather than becoming a truncated learned phrase. @@ -753,7 +753,7 @@ openless.desktop[FV3T]: F:Registers the Linux OpenLess launcher command, icon, c top.openless.OpenLess.metainfo.xml[FV3T]: F:Provides AppStream identity, site, desktop launcher and binary metadata for Linux packages | R:code:openless-all/app/linux-egui/packaging/openless.desktop | A:- | S:- ===/Users/lvbaiqing/project/openless/openless-all/app/linux-egui/src/=== -audio.rs[IH7L]: F:Implements native Linux CPAL microphone capture, playback reference, PCM delivery and session archives | R:code:openless-all/app/crates/openless-core/src/audio.rs, code:openless-all/app/linux-egui/src/backend.rs | A:LinuxCpalRecorder, start_linux_recording, select_playback_monitor_device | S:Keep realtime delivery bounded and join recording workers at stop. Match playback monitors by route identity instead of translated display name. +audio.rs[IH7L]: F:Implements native Linux CPAL capture, playback reference, processed PCM delivery and session archive ownership | R:code:openless-all/app/linux-egui/src/audio/archive.rs,code:openless-all/app/crates/openless-core/src/audio.rs,code:openless-all/app/linux-egui/src/backend.rs | A:LinuxCpalRecorder,start_linux_recording,select_playback_monitor_device | S:Keep realtime delivery bounded and join workers at stop. Playback monitors match route identity, not translated names. Archive range access is independent of CPAL and uses the dedicated adapter. audio_cue.rs[IH5M]: F:Synthesizes the shared recording cue as PCM and plays it on the default Linux output sink | R:code:openless-all/app/linux-egui/src/audio.rs | A:CueTone, play_cue_start, render_cue_mono | S:Use a detached worker rather than blocking the UI. New generations silence previous sounds, and missing output remains a nonfatal feedback failure. audio_mute.rs[IH5M]: F:Temporarily mutes default Linux playback during recording and restores the prior state via a guard | R:code:openless-all/app/linux-egui/src/audio.rs | A:AudioMuteGuard, PlatformMuteGuard, parse_wpctl_muted | S:Remember whether the sink was already muted. Dropping a disabled guard has no system effect. audio_player.rs[IH5M]: F:Plays history PCM through default Linux output with pause, seek and progress | R:code:openless-all/app/linux-egui/src/linux_app/history.rs | A:ClipPlayer, play, is_finished, seek_ms | S:Paused output is silent and does not advance the playback cursor. @@ -904,7 +904,7 @@ ci-cache-usage.sh[OP5M]: F:Reads GitHub cache usage and optionally prunes closed ci-cache-usage.test.mjs[TP5M]: F:Verifies cache reporting and pruning policies against isolated GitHub CLI fixtures | R:code:openless-all/app/scripts/ci-cache-usage.sh | A:run, check | S:Records simulated deletion calls locally instead of altering real caches. ci-changed-areas.sh[OQ5T]: F:Wraps changed-area graph classification in a CI-safe boolean result | R:code:openless-all/app/scripts/ci-impact.mjs | A:- | S:An unknown, missing or failed classification runs the check. Only a valid false skips it. ci-changed-areas.test.mjs[TQ5L]: F:Tests Git change classification, Cargo reachability and CI job wiring against synthetic commits and workflow checks | R:code:openless-all/app/scripts/ci-changed-areas.sh | A:check, reset | S:All Git fixtures are isolated. Failure contracts preserve the decision to run checks when impact is uncertain. -ci-consolidation.test.mjs[TQ5S]: F:Checks consolidated platform CI, desktop-only gating, iOS and Windows job wiring and maintenance privileges | R:code:.github/workflows/ci.yml | A:- | S:Consolidation must preserve independent platform check obligations. +ci-consolidation.test.mjs[TQ5S]: F:Checks consolidated CI, desktop-only gating, isolated provider acceptance and iOS and Windows job obligations | R:code:.github/workflows/ci.yml | A:- | S:The UI aggregate skips provider-only manual acceptance runs while retaining ordinary PR obligations. ci-impact.mjs[XQ6M]: F:Determines platform impact using Git changes, manifest closures and evaluated Cargo target clauses | R:code:openless-all/app/scripts/ci-changed-areas.sh | A:classify, decide, buildGraph, closureFor, evaluateCfg | S:Missing diffs, unknown path ownership or metadata failures default to running the affected validation. ci-macos-runner-contract.test.mjs[TV4T]: F:Checks macOS runner selection preserves Windows matrix and platform gate coverage | R:code:.github/workflows/ci.yml | A:- | S:- ci-performance.test.mjs[TP5M]: F:Exercises aggregate CI scripts, shared Cargo target reuse and Windows installer failure propagation with local fixtures | R:code:.github/workflows/ci.yml, code:.github/workflows/release-tauri.yml | A:runGate | S:The fixture checks actual Cargo freshness and that installer failures cannot be hidden by later steps. @@ -1010,7 +1010,7 @@ rustc-macos-proc-macro-wrapper.test.mjs[TV4T]: F:Exercises proc-macro crate-type selection-intent-reopen.test.mjs[TU5T]: F:Exercises the reused Selection Voice intent picker after choosing or canceling in a mocked React and IPC environment. | R:- | A:- | S:The shown event must reset disabled button state on the same mounted picker without requiring a remount. selection-workspace-extra-controls-contract.test.mjs[TU4T]: F:Checks that selection workspace advanced controls and system prompt editing live in an accessible dialog. | R:code:openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx | A:- | S:The primary section must remain free of textarea editing controls. settings-modal-scroll-isolation.test.mjs[TU4T]: F:Checks FloatingShell settings-open scoping and background scrollbar suppression while the settings modal is active. | R:code:openless-all/app/src/app/shell/FloatingShell.tsx,code:openless-all/app/src/styles/tokens.css | A:- | S:WebKitGTK requires the scoped scrollbar pseudo-element to be hidden directly. -shared-backend-wire-contract.test.mjs[TG6L]: F:Checks shared Core ownership and frontend-to-host contract parity across Tauri, Android, remote input, and optional local ASR. | R:code:openless-all/app/src-tauri/src/lib.rs,code:openless-all/app/crates/openless-core/src/local_asr_service.rs | A:- | S:Coordinator cannot own a Tauri AppHandle. Mobile dictation target restoration is a no-op without enabling Selection Polish. +shared-backend-wire-contract.test.mjs[TG6L]: F:Checks Core ownership and frontend-to-host contract parity across Tauri, Android, remote input and local ASR | R:code:openless-all/app/src-tauri/src/commands/history.rs,code:openless-all/app/src-tauri/src/core_adapters.rs | A:- | S:History retranscription resolves and leases its file before forwarding to Core. Coordinator cannot own AppHandle. Mobile target restoration does not enable Selection Polish. sherpa-onnx-android.mjs[OV5S]: F:Downloads, checks, extracts, and locates pinned arm64 Sherpa ONNX native libraries for Android builds. | R:code:openless-all/app/scripts/run-android-tauri-build.mjs | A:SHERPA_ONNX_ANDROID_ABI; sherpaOnnxAndroidLibDir; ensureSherpaOnnxAndroidLibs | S:The crate does not fetch Android binaries, so the build must link from the staged directory. sign-android-apks.mjs[OV5T]: F:Creates detached updater signatures for release APKs through Tauri's signer. | R:code:openless-all/app/scripts/merge-release-signatures.mjs | A:APK path arguments; TAURI_SIGNING_PRIVATE_KEY | S:Uses the desktop updater key and skips APKs with an existing sidecar. sign-harmony-hap.py[OV5S]: F:Signs staged Harmony HAP and APP outputs with a selected external keystore, certificate chain, and provisioning profile. | R:code:openless-all/app/scripts/package-harmony-hap.sh | A:TOOLCHAIN SIGNING_DIR OUTPUT_DIR; --release; --prefix | S:Sign both artifact kinds through hap-sign-tool sign-app. Store material is supplied outside the repository. @@ -1028,7 +1028,7 @@ test-card-lifecycle-macos.py[TU5T]: F:Exercises accept, reject, and timeout for test-compare-audio-outputs.py[TH4T]: F:Checks exact PCM comparison with negative controls for one changed sample and a truncated output. | R:- | A:- | S:- test-native-capsule-macos.py[TU5S]: F:Runs the macOS native capsule helper in an app fixture while sampling LaunchServices role, readiness, and exit behavior. | R:- | A:--helper; --cycles | S:Only the UIElement role is allowed and the helper must never become foreground. test-native-capsule-windows.ps1[TU5S]: F:Exercises native Windows capsule helper startup, window placement, and shutdown, idle, and EOF paths across styles. | R:- | A:HelperPath; OutputDirectory; results.json | S:The visible capsule must not steal foreground activation. -test-recorder-module.py[TH5T]: F:Builds the production recorder tests against a minimal standalone Rust bridge, excluding unrelated app and ASR dependencies. | R:- | A:--check; forwarded cargo arguments | S:Cross-target check mode compiles the test surface without linking or executing it. +test-recorder-module.py[TH5T]: F:Builds production recorder and audio tests against a standalone Rust bridge without Tauri or ASR runtime dependencies | R:code:openless-all/app/src-tauri/src/recorder.rs,code:openless-all/app/crates/openless-core/src/audio.rs | A:--check,forwarded Cargo arguments | S:Cross-target check mode compiles tests without linking or executing them. test-windows-hang-diagnostics.py[TO4T]: F:Builds and runs an isolated harness for the production hang diagnostics facade with the feature enabled and disabled. | R:- | A:- | S:Use injected memory or failing writers so tests never touch the user's diagnostic session. test-windows-runtime-target.py[TV5S]: F:Exercises the Windows owner-thread helper and optionally runs real vendored Wry lifecycle cases with resolved dependency checks. | R:code:openless-all/app/src-tauri/Cargo.toml | A:--runtime | S:The runtime fixture must resolve the same workspace dependency identities and patched crate source. ts-resolve-hook.mjs[XL3T]: F:Resolves extensionless relative ESM imports to TypeScript files for Node-based localization scripts. | R:code:openless-all/app/scripts/register-ts-loader.mjs | A:resolve | S:- @@ -1120,7 +1120,7 @@ tauri.macos.conf.json[FV5T]: F:Overrides macOS DMG artwork and placement coordin tauri.windows.conf.json[FV5T]: F:Overrides Windows main and capsule window presentation and sets frontend build commands. | R:code:openless-all/app/src-tauri/tauri.conf.json,code:openless-all/app/scripts/windows-ui-config.test.mjs | A:Windows Tauri window overrides | S:Keep capsule initial focus and visibility policy separate from the main window. ===/Users/lvbaiqing/project/openless/openless-all/app/src-tauri/backend-tests/=== -Cargo.lock[FV4L]: F:Pins the independent backend test harness and shared Core dependencies including native Ask context support | R:code:openless-all/app/src-tauri/backend-tests/Cargo.toml | A:Cargo lockfile format 4 | S:- +Cargo.lock[FV4L]: F:Pins the independent backend test harness and shared Core graph including native Apple context and declared test dependencies | R:code:openless-all/app/src-tauri/backend-tests/Cargo.toml | A:Cargo lockfile format 4 | S:- Cargo.toml[TV5T]: F:Defines the isolated backend test crate and shared or platform-gated dependencies for native module contracts | R:code:openless-all/app/src-tauri/backend-tests/Cargo.lock,code:openless-all/app/src-tauri/backend-tests/build.rs | A:openless-backend-tests,Rust 1.99 | S:Import production adapters without launching Tauri or native UI. Gate OS dependencies; shared async and time crates support scoped Ask context and wire fixtures. build.rs[OV4T]: F:Embeds a Common Controls v6 manifest dependency into Windows MSVC backend test executables. | R:code:openless-all/app/src-tauri/backend-tests/Cargo.toml | A:- | S:Native subclass helper exports need this manifest. @@ -1167,7 +1167,7 @@ cli.rs[CE3T]: F:Re-exports the shared Core CLI intent parser and types for Tauri combo_hotkey.rs[IH6M]: F:Registers custom dictation shortcuts and forwards native press and release edges for the selected binding. | R:code:openless-all/app/src-tauri/src/macos_dictation_key.rs | A:ComboHotkeyEvent; custom registration | S:Filter events by the current registration ID and avoid duplicate registration when native dictation owns the binding. coordinator.rs[AG8L]: F:Assembles Core host ports and native lifecycle, shortcuts, auxiliary windows and service-usage change notifications | R:code:openless-all/app/src-tauri/src/tauri_coordinator_host.rs,code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs,code:openless-all/app/crates/openless-core/src/usage_ledger.rs,code:openless-all/app/src/data/usage.ts | A:Coordinator,backend,present_core_capsule,start_hotkey_supervisors_when_ready | S:Keep business sessions in Core and supervisors on committed registrations. Shared UsageRecorder emits payload-free service-usage:changed only to main after persistence/failure changes. Restore capsule hit testing when auxiliary cards hide. coordinator_state.rs[DB6L]: F:Implements framework-free dictation coordinator state transitions for start, pending stop, cancel, focus, and abort. | R:code:openless-all/app/src-tauri/src/coordinator.rs | A:SessionId; SessionState; SessionPhase | S:Retain stop during startup until listening is ready. Ignore callbacks whose session UUID no longer matches the active session. -core_adapters.rs[IG8L]: F:Implements native Tauri ports for Core, including audio, transcription, editor delivery, runtime effects, and platform services. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/insertion.rs,code:openless-all/app/src-tauri/src/asr/local/mod.rs | A:Tauri Core port implementations,AppHandleSlot | S:Native release checks use the owning runtime and lease generation. Uncertain TSF delivery must not retry through another write path, and unverified focus limits fallback. +core_adapters.rs[IG8L]: F:Implements Tauri native ports including capture, leased ranged archives, ASR, editor delivery and platform services | R:code:openless-all/app/src-tauri/src/recorder.rs,code:openless-all/app/src-tauri/src/persistence/paths.rs,code:openless-all/app/crates/openless-core/src/ports.rs | A:TauriRecordingArchive,TauriActiveRecording,TauriPendingAudioCapture,publish_archive_recording_fault | S:Hold archive leases before creation through processing/migration and release immediately on discard. Archive length/range/full reads fail closed on write_error or non-canonical headers inside leased blocking tasks. Level callbacks report archive faults async via Core executor without joining self. Native release checks keep generation; uncertain TSF never retries. correction.rs[CB3T]: F:Re-exports shared Core correction rule application for Tauri callers. | R:- | A:apply_correction_rules; apply_rule | S:- desktop_resources.rs[RU7L]: F:Manages Tauri window construction, close and reopen lifetime, low-memory behavior, and native card resources. | R:code:openless-all/app/src-tauri/src/lib.rs,code:openless-all/app/src-tauri/src/macos_card_panel.rs | A:configure; ensure_main; close_main; hide_main_with_grace | S:Fix renderer ownership at launch. Save the main URL before unload and restore it on failed destruction; a reopen cancels only its own pending close. device_watch.rs[IH5S]: F:Registers native input-device watchers for tray microphone updates on device list or default input changes. | R:code:openless-all/app/src-tauri/src/lib.rs | A:spawn_native_watcher | S:Report successful registration synchronously so failed native setup cannot be mistaken for active notifications. @@ -1197,7 +1197,7 @@ playback_reference_macos.m[IH6T]: F:Creates and drives a private Core Audio outp playback_reference_macos.rs[IH6S]: F:Wraps the Objective-C output tap and converts its timestamped audio callbacks into the Core reference buffer. | R:code:openless-all/app/src-tauri/src/playback_reference_macos.m,code:openless-all/app/src-tauri/src/playback_reference.rs | A:PlaybackReference; start | S:Stop and destroy native callbacks before releasing their Rust context. polish.rs[CB3T]: F:Re-exports Core LLM polishing protocol implementations for the Tauri host. | R:- | A:- | S:- qa_adapter.rs[IB7L]: F:Adapts native selection and focus, recording, credentials, and host result delivery for Core's legacy QA service. | R:code:openless-all/app/src-tauri/src/selection.rs,code:openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs | A:TauriQaHostContext; SelectionVoiceTargetBinder | S:Core owns phase, cancellation, and messages. Scope native handles and completion to the originating session so an await cannot resurrect a removed turn. -recorder.rs[IH8L]: F:Owns native microphone streams, converts input to common PCM, and integrates warm capture, audio processing, metering, and optional archives. | R:code:openless-all/app/src-tauri/src/recorder/android_capture.rs,code:openless-all/app/src-tauri/src/playback_reference.rs,code:openless-all/app/src-tauri/src/core_adapters.rs | A:Recorder,AudioConsumer,WarmCaptureHub | S:Deliver 16 kHz mono little-endian Int16 to ASR. Keep stream ownership off async callers and defer shared configuration until active capture claims settle. +recorder.rs[IH8L]: F:Owns native cold and warm capture, DSP delivery and bounded asynchronous WAV archiving with retained-error recovery | R:code:openless-all/app/src-tauri/src/core_adapters.rs,code:openless-all/app/crates/openless-core/src/audio.rs,code:openless-all/app/src-tauri/src/playback_reference.rs | A:Recorder,WarmCaptureHub,WavArchiveStatus,WavArchiveWriter,WavArchiver | S:ASR and archives use 16 kHz mono PCM16. The queue caps pending frames by max_queue_bytes (default 32 MiB) without blocking callbacks. Write, seek, sync and capacity faults latch permanently and forbid appends; Finalize and Drop still try prefix-header repair while retaining the failure. Stop joins both writers; warm claims keep archive ownership. selection.rs[IH7L]: F:Captures external selection text and editor target metadata for the platform selection workspace and guards subsequent reactivation and replacement. | R:code:openless-all/app/src-tauri/src/selection/clipboard_capture.rs,code:openless-all/app/src-tauri/src/host_document/mod.rs | A:SelectionContext,SelectionInsertionTarget,resolve_selection_workspace_capture_with_diag | S:Prefer macOS AX without the clipboard. Windows must prove the captured window and control after reactivation before editing. shortcut_binding.rs[CH6L]: F:Validates shared shortcut policy and parses native registration keys and modifiers for Tauri. | R:code:openless-all/app/src-tauri/src/hotkey.rs,code:openless-all/app/src-tauri/src/side_aware_combo.rs | A:validate_binding; parse_global_hotkey; ShortcutBindingError | S:Route side-aware and mouse bindings through native hooks rather than forcing them through global-hotkey registration. side_aware_combo.rs[IH7L]: F:Tracks physical left and right modifier states and emits paired shortcut edges for side-aware dictation chords. | R:code:openless-all/app/src-tauri/src/hotkey.rs,code:openless-all/app/src-tauri/src/shortcut_binding.rs | A:SideAwareComboMonitor,SideModifier,handle_companion_key_down | S:Preserve one Pressed event per held gesture. Companion keys can abort a modifier chord without producing another primary press. @@ -1301,7 +1301,7 @@ dictionary.rs[EB6S]: F:Binds Core vocabulary, correction review, insert fallback experimental_asr.rs[EB5T]: F:Exposes experimental ASR status, enablement, deletion, and notice acknowledgment to the host frontend. | R:code:openless-all/app/src-tauri/src/asr/local/experimental.rs | A:experimental_asr_status; experimental_asr_set_enabled; experimental_asr_delete; experimental_asr_acknowledge | S:Report explicit unavailable status on unsupported targets and require the main window for mutations. foundry_asr.rs[EB6M]: F:Adapts Core local ASR status, model catalog, source settings, preparation, and release into the legacy Foundry frontend IPC shape. | R:code:openless-all/app/src-tauri/src/asr/local/foundry.rs,code:openless-all/app/src-tauri/src/commands/local_asr.rs | A:FoundryStatusWire; FoundryCatalogWire; Foundry-specific IPC | S:Keep legacy field names and shapes while Core owns runtime and catalog state. github_oauth.rs[EI6S]: F:Adapts Core GitHub device authorization and marketplace authentication status for Tauri IPC. | R:code:openless-all/app/src-tauri/src/commands/marketplace.rs | A:GithubDeviceStartResponse; GitHub device flow IPC | S:Preserve the existing tagged poll result and omit the device secret from start response. -history.rs[ED7M]: F:Exposes dictation history, activity app icons, recording read and export, and replay or re-transcription operations through Tauri. | R:code:openless-all/app/src-tauri/src/activity_app_icons.rs,code:openless-all/app/src-tauri/src/commands/dictation.rs | A:list_history,read_audio_recording,get_activity_app_icons | S:Validate session IDs before file access. Replace the original failed history entry only for transcription failure or empty transcript. +history.rs[ED7M]: F:Exposes history, recording playback and export, app icons and leased archive retranscription through Tauri | R:code:openless-all/app/src-tauri/src/commands/history_retranscription.rs,code:openless-all/app/src-tauri/src/persistence/paths.rs | A:list_history,read_audio_recording,export_audio_recording,retranscribe_recording | S:Validate IDs before path lookup. Hold archive leases across playback reads, export dialogs/copies and retranscription. Replace history only when failed or empty entry allows. hotkeys.rs[EH6M]: F:Exposes Tauri shortcut validation and settings updates while reusing Core hotkey collision and normalization policy. | R:code:openless-all/app/src-tauri/src/shortcut_binding.rs,code:openless-all/app/src-tauri/src/coordinator.rs | A:validate_shortcut_binding; validate_combo_hotkey; shortcut setter IPC | S:Keep side-specific chords for dictation only and validate conflicts across selection tools and style packs before saving. local_asr.rs[EB7L]: F:Exposes Core local ASR status, storage, model configuration, activation, explicit prepare and release, and model directory actions. | R:code:openless-all/app/crates/openless-core/src/local_asr_service.rs,code:openless-all/app/src-tauri/src/commands/foundry_asr.rs | A:Local ASR Tauri IPC; model and status wire structs | S:Keep legacy frontend fields when adding catalog metadata. Validate typed runtime and model targets before forwarding. marketplace.rs[EE6S]: F:Exposes Core marketplace operations and writes downloaded packages through native filesystem or Android content targets. | R:code:openless-all/app/src-tauri/src/commands/github_oauth.rs,code:openless-all/app/src-tauri/src/android/jni.rs | A:Marketplace Tauri IPC | S:Route content URIs only through Android JNI and reject file URI confusion before writing local paths. @@ -1312,13 +1312,13 @@ providers.rs[EB5T]: F:Exposes Core provider policy descriptors, credential valid qa.rs[EU6M]: F:Exposes Less Computer panel display, focus, submission, voice recording, and approval actions through Tauri. | R:code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs,code:openless-all/app/src-tauri/src/coordinator/dictation_core.rs | A:Less Computer window and action IPC | S:Only the owning panel may control its voice or submit approvals. Keep separate from the standalone Ask command surface. remote_input.rs[EN6S]: F:Adapts Core remote input status, LAN addresses, pairing PIN reset, and locale sync to Tauri settings commands. | R:code:openless-all/app/src-tauri/src/remote_server/mod.rs | A:get_remote_input_status; regenerate_remote_pin; set_remote_locale | S:Return the new committed PIN only after Core completes reset. Preserve the legacy secret status wire shape for this explicit query. selection_polish.rs[EB4T]: F:Provides a developer command that starts the Core selection-polish path with default raw-mode input. | R:- | A:run_selection_polish_for_dev | S:- -selection_voice.rs[EB6M]: F:Exposes Core selection voice intent, preview, apply, and revert actions and supplies corresponding Tauri payloads. | R:code:openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs | A:SelectionVoiceIntentPromptPayload,SelectionVoicePreviewPayload,selection voice IPC | S:Validate the active preview owner before applying or reverting and preserve stable sourceText wire naming. +selection_voice.rs[EB6M]: F:Exposes Windows selection voice intent, preview, apply and revert IPC and Tauri payloads | R:code:openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs | A:SelectionVoiceIntentPromptPayload,SelectionVoicePreviewPayload,confirm_selection_voice_preview | S:Claim a Core ticket before synchronous native application, then finalize its receipt. A stale QA dismissal cannot revoke completed delivery; keep sourceText wire naming. settings.rs[EC7L]: F:Exposes Core settings snapshots and updates and coordinates the Tauri runtime effects and platform update entry points. | R:code:openless-all/app/src-tauri/src/coordinator/native_dictation_key.rs,code:openless-all/app/src-tauri/src/android/updater.rs,code:openless-all/app/src-tauri/src/update_source.rs | A:TauriSettingsRuntime; set_settings; get_settings_snapshot; update_setting_fields | S:Keep dedicated update-channel preferences across ordinary saves. Report runtime side-effect failures to the Core settings transaction and validate update origins before downloading. sherpa_asr.rs[EB6M]: F:Adapts Core Sherpa model catalogs, source settings, status, download metadata, and preparation to legacy frontend commands. | R:code:openless-all/app/src-tauri/src/asr/local/sherpa.rs,code:openless-all/app/src-tauri/src/commands/local_asr.rs | A:SherpaCatalogWire; Sherpa-specific IPC | S:Reject unknown model families and modes at the adapter boundary without panicking. siwc.rs[EI6S]: F:Maps Tauri channel sign-in actions to Core SIWC and launches authorization in the native browser. | R:code:openless-all/app/src-tauri/src/android/mod.rs,code:openless-all/app/src-tauri/src/commands/credentials.rs | A:siwc_status; siwc_models; siwc_action | S:Return attempt identity without exposing the authorization URL. Android keeps a native lease until authorization ends and cancels the attempt if launch fails. style_packs.rs[EE6M]: F:Exposes Core style pack creation, editing, activation, import and export, and refreshes native tray menus after changes. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/crates/openless-core/src/style_packs.rs | A:Style pack Tauri IPC,activate_style_pack_by_id | S:Refresh platform tray presentation on the main thread after successful mutations. voice_edit.rs[EU6S]: F:Exposes Voice Edit panel lifecycle, recording finalization, commit, and state commands to Tauri. | R:code:openless-all/app/src-tauri/src/coordinator/voice_edit_session.rs | A:voice_edit_window_open; voice_edit_window_close; get_voice_edit_state | S:Validate the main-window caller and open Windows WebView2 from asynchronous IPC. Start the session only when the panel explicitly requests it. -history_retranscription.rs[EB6S]: F:Re-transcribes archived history WAV recordings via Core auxiliary service and updates failed history entries | R:code:openless-all/app/src-tauri/src/commands/history.rs,code:openless-all/app/crates/openless-core/src/auxiliary.rs | A:HistoryRetranscriptionResult,retranscribe_recording_with_path | S:Rejects active dictation and non-QuickNote multimodal entries; maps Core errors to bounded symbolic reasons so provider secrets never cross IPC. +history_retranscription.rs[EB6M]: F:Validates RIFF chunks and retranscribes archived history audio through bounded range reads and Core auxiliary ASR | R:code:openless-all/app/src-tauri/src/commands/history.rs,code:openless-all/app/crates/openless-core/src/auxiliary.rs | A:HistoryWavArchive,retranscribe_recording_with_path | S:Keep one open file; reject odd-aligned or overflowing PCM ranges, duplicate data and truncated WAV. Reject active/multimodal entries; IPC returns bounded error codes only. ===/Users/lvbaiqing/project/openless/openless-all/app/src-tauri/src/coordinator/=== capsule_focus.rs[IU7L]: F:Captures and restores external editor focus and coordinates native capsule projection, payload publication, and exclusive Escape handling. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/tauri_coordinator_host.rs | A:capture_external_focus_target,restore_focus_target_if_possible | S:Serialize payload publication and gate late capsule cleanup on the same epoch, so it cannot hide or overwrite a successor. @@ -1326,7 +1326,7 @@ dictation_core.rs[AB6S]: F:Forwards native dictation hotkey edges into Core, han hotkey_loops.rs[AH7L]: F:Supervises platform shortcut listeners and bridges native events into dictation, selection tools, Less Computer, styles, and agent actions. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/coordinator/native_dictation_key.rs,code:openless-all/app/src-tauri/src/coordinator/dictation_core.rs | A:Native hotkey supervisor and router | S:Keep native hotkey registration on its required thread. Cancellation and panel stop are scoped to current session ownership even during async startup. native_dictation_key.rs[IH6S]: F:Registers native dictation and mouse bindings synchronously for the host side of a Core settings transaction. | R:code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs,code:openless-all/app/src-tauri/src/commands/settings.rs | A:try_update_native_dictation_binding; try_install_mouse_dictation | S:Fail if the runtime shortcut target changes during registration. Do not register new bindings during shutdown. restore_runtime.rs[AR7M]: F:Reconciles actual Tauri runtime state after Core restores credentials and preferences under its migration journal. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs | A:bind_restore_runtime_effects; restore host effects | S:Run under the exclusive restore boundary without performing ordinary settings persistence again. Surface invalid or unsupported enabled runtime targets. -selection_voice_session.rs[AB7L]: F:Adapts the Core selection voice session to native recording, capsule ownership, preview windows, and text application effects. | R:code:openless-all/app/src-tauri/src/commands/selection_voice.rs,code:openless-all/app/src-tauri/src/selection.rs | A:Selection voice host coordination | S:Revoke the host owner before cancellation cleanup so an in-flight startup cannot republish its capture after Escape. +selection_voice_session.rs[AB7L]: F:Adapts Core selection voice sessions to Windows recording, capsule ownership, previews and native text application | R:code:openless-all/app/src-tauri/src/commands/selection_voice.rs,code:openless-all/app/src-tauri/src/selection.rs | A:apply_selection_voice_preview_ticket,finish_selection_voice_preview_host | S:Cancel revokes host ownership before cleanup. Full desktop selections are revalidated at the original target before paste; literal truncation-like text is not a legacy placeholder. voice_edit_session.rs[AB7L]: F:Binds Core Voice Edit drafts and phases to native recording, editor targets, panel state, and guarded commit effects. | R:code:openless-all/app/src-tauri/src/commands/voice_edit.rs,code:openless-all/app/src-tauri/src/selection.rs | A:VoiceEditHostState,Voice Edit host adapter | S:Fence async results by originating session and reserve native commit before writing. Convert Android UTF-16 offsets without splitting surrogate pairs. ===/Users/lvbaiqing/project/openless/openless-all/app/src-tauri/src/host_document/=== @@ -1354,7 +1354,7 @@ desktop_onboarding.rs[PD4T]: F:Loads and atomically stores the local desktop onb dictionary.rs[PD5T]: F:Adapts the app data directory, vocabulary operations, and preset storage to shared Core repositories. | R:code:openless-all/app/src-tauri/src/persistence/mod.rs,code:openless-all/app/src-tauri/src/commands/dictionary.rs | A:DictionaryStore; save_vocab_presets | S:The fallback filename is separate from durable vocabulary state. history.rs[PD5T]: F:Adapts local history paths and retention-aware append, list, and deletion operations to the shared Core repository. | R:code:openless-all/app/src-tauri/src/commands/history.rs,code:openless-all/app/src-tauri/src/persistence/mod.rs | A:HistoryStore; append_with_retention | S:Keep fallback entries separate from the durable history file. mod.rs[PD6S]: F:Defines native application storage roots, persistence module exports, and shared JSON load and atomic write helpers. | R:code:openless-all/app/src-tauri/src/persistence/android_storage.rs,code:openless-all/app/src-tauri/src/persistence/paths.rs | A:data_dir; atomic_write; ensure_dir | S:Missing or empty state can default. Report invalid JSON and failed replacement instead of treating them as first run. -paths.rs[PD6M]: F:Resolves the configurable model root, Foundry caches, and debug recording archive paths and prunes retained recordings. | R:code:openless-all/app/src-tauri/src/persistence/mod.rs,code:openless-all/app/src-tauri/src/persistence/preferences.rs | A:models_root; prune_recordings; foundry_local_root | S:Append OpenLess/models to a custom base. Restrict retention pruning to recording WAV files. +paths.rs[PD6M]: F:Resolves model and recording storage roots and prunes recordings while protecting active archive leases | R:code:openless-all/app/src-tauri/src/core_adapters.rs,code:openless-all/app/src-tauri/src/commands/history.rs | A:acquire_recording_archive_lease,prune_recordings,models_root | S:Canonical path leases are counted until drop. Deletion and lease acquisition share a lock; age and count pruning skip leased WAV files. Custom model bases append OpenLess/models. preferences.rs[PD6T]: F:Adapts platform preference paths to the shared Core preferences store and style-preserving write API. | R:code:openless-all/app/src-tauri/src/persistence/mod.rs,code:openless-all/app/src-tauri/src/commands/settings.rs | A:PreferencesStore; set_preserving_current_style_preferences | S:Compatibility wrapper and backend share the same repository instance so Core writes are visible without reopening JSON. siwc.rs[PS6S]: F:Implements native SIWC credential and atomic head storage separate from the provider vault. | R:code:openless-all/app/src-tauri/src/commands/siwc.rs,code:openless-all/app/src-tauri/src/persistence/android_credentials.rs | A:NativeSiwcVault; SiwcVault implementation | S:Exclude SIWC sessions from provider exports and backups. Verify stored record identity and preserve compare-head behavior. style_pack.rs[PD5S]: F:Adapts Tauri data paths and style pack repository operations, including import provenance and ZIP export, to Core. | R:code:openless-all/app/crates/openless-core/src/style_packs.rs,code:openless-all/app/src-tauri/src/commands/style_packs.rs | A:StylePackStore; export_to_zip | S:Core owns style repository state and preference compatibility. @@ -1523,7 +1523,7 @@ cloud-sync.ts[EN5T]: F:Exposes cloud and encrypted sync commands and provides su contracts.ts[CG4T]: F:Exposes shared frontend types and Core backend and transcript event types through a stable import path. | R:code:openless-all/app/src/lib/types.ts,code:openless-all/app/src/lib/backendEvent.ts | A:BackendEvent; TranscriptDelta; TranscriptSnapshot | S:- corrections.ts[EB4T]: F:Re-exports frontend correction-rule and pending vocabulary suggestion operations. | R:code:openless-all/app/src/lib/ipc/vocab.ts | A:- | S:- deletion-batch.ts[AD6T]: F:Executes confirmed multi-record deletions, reports acknowledged IDs, and retains unconfirmed IDs for retry. | R:- | A:createDeletionBatch; IncompleteDeletion | S:Never replay an acknowledged deletion. Deliver the successful subset before signaling incomplete results. -dictation.ts[EB6T]: F:Exposes frontend dictation IPC, window subscriptions and optional caption diagnostic reporting | R:code:openless-all/app/src/lib/ipc/dictation.ts,code:openless-all/app/src/runtime/windows/auxiliaryEvents.ts | A:createCapsuleSubscriptions,getCapsuleAuxiliarySnapshot,mainCaptionTraceEnabled,reportMainCaptionTrace | S:Capsule state is window-scoped; transcripts and preferences are app-scoped. Browser previews return tracing disabled and reporting performs no native action. +dictation.ts[EB6T]: F:Exposes dictation IPC, capsule job and card replay, subscriptions and optional caption tracing | R:code:openless-all/app/src/lib/ipc/dictation.ts,code:openless-all/app/src/runtime/windows/auxiliaryEvents.ts | A:createCapsuleSubscriptions,getCapsuleAuxiliarySnapshot,CapsuleProcessingJob | S:Capsule state and cards are window-scoped; jobs, transcripts and preferences are app-scoped. Browser replay includes empty processing jobs and never enables native tracing. files.ts[ED4T]: F:Exposes file dialogs, sharing, export and local migration commands, with clipboard routing for native and browser preview. | R:code:openless-all/app/src/lib/ipc/vocab.ts | A:copyTextToClipboard; openAndroidLocalMigration | S:Preview uses the browser clipboard instead of the native command. history.ts[ED6T]: F:Coordinates history queries and mutations through the frontend history store and exports recorded audio per host. | R:code:openless-all/app/src/data/snapshot-query.ts | A:listHistory; deleteHistoryEntry; retranscribeRecording; exportAudioRecording | S:Refresh history through the mutation store and require a nonempty WAV data URL on the preview download path. hotkeys.ts[EH4T]: F:Re-exports shortcut IPC operations and shared hotkey utilities through the frontend API. | R:code:openless-all/app/src/lib/ipc/hotkeys.ts,code:openless-all/app/src/lib/hotkey.ts | A:- | S:- @@ -1646,7 +1646,7 @@ GithubLoginModal.tsx[AI6M]: F:Runs the shared marketplace GitHub device login UI ===/Users/lvbaiqing/project/openless/openless-all/app/src/features/capsule/=== AudioCue.tsx[AU5T]: F:Observes capsule recording state and preferences and plays a scoped recording start cue on supported runtimes. | R:code:openless-all/app/src/api/dictation.ts,code:openless-all/app/src/lib/audioCue.ts | A:AudioCueListener | S:Only the primary capsule owns audio playback. Dispose subscriptions and stop audio when that ownership ends. -Capsule.tsx[AU8L]: F:Renders recording state, transcript, translation and auxiliary cards, with native input regions and optional caption tracing | R:code:openless-all/app/src/api/dictation.ts,code:openless-all/app/src/features/capsule/LiveTranscriptPill.tsx,code:openless-all/app/src/features/capsule/useMainCaptionTrace.ts | A:Capsule | S:Subscribe before replay for late-created mirrors. Session changes clear transcripts; auxiliary cards cannot own recording state. Report actual inline transcript visibility to tracing rather than treating hidden or split-rail text as rendered. +Capsule.tsx[AU8L]: F:Renders capture, foreground and background processing, transcript, translation and cards with native input regions | R:code:openless-all/app/src/api/dictation.ts,code:openless-all/app/src/features/capsule/LiveTranscriptPill.tsx,code:openless-all/app/src/features/capsule/useMainCaptionTrace.ts | A:Capsule,ClassicCapsule | S:Subscribe before replay; each auxiliary stream has its own revision. Cancel and confirm target the displayed session rather than a stale transcript owner. Only active foreground states show its translation badge. Report actual inline transcript visibility to tracing; hidden and split-rail text are not inline renders. CapsuleStyles.css[FU5L]: F:Defines shared recording pill, translation badge, live transcript, and auxiliary capsule visual styles. | R:code:openless-all/app/src/features/capsule/Capsule.tsx,code:openless-all/app/src/features/capsule/LiveTranscriptPill.tsx | A:Shared capsule style classes and variables | S:Maintain separation between transcript paint and the capsule control geometry. CapsuleTranslationBadge.tsx[AU5M]: F:Renders the capsule's live translation target, loads host preferences, and applies a mutable session target change. | R:code:openless-all/app/src/features/capsule/useCapsuleLanguageMenu.ts,code:openless-all/app/src/api/dictation.ts | A:CapsuleTranslationBadge | S:Ignore stale preference reads and label mutations with the target session so old responses cannot update a new recording. InsertFallbackCard.tsx[AU6M]: F:Displays the entire insertion fallback text, reports fitted card height, and provides copy and timed dismissal feedback. | R:code:openless-all/app/src/lib/insertFallbackLayout.ts,code:openless-all/app/src/api/dictation.ts | A:InsertFallbackCard | S:Pause expiry while hovered and copy through native IPC because the card intentionally avoids taking focus. Ignore completions from stale copy epochs. @@ -1820,7 +1820,7 @@ ChannelEditorHostContext.ts[CU5T]: F:Defines optional nested channel editor cont SettingsModal.tsx[AU7L]: F:Renders responsive settings navigation, nested page headers, search, provider-editor hosting and official help links | R:code:openless-all/app/src/features/settings/shell/useSettingsNavigation.ts,code:openless-all/app/src/features/settings/shell/useSettingsLayer.ts,code:openless-all/app/src/features/settings/shell/tabs.tsx | A:SettingsModal,SettingsSectionId | S:Finish nested provider writes before navigation or close. Keep retained form/title together, inert surfaces unfocusable, and scroll/modal ownership tied to the active pane. navigation.ts[AU6M]: F:Defines settings categories and capability-filtered subpages including Advanced intent routing and polish strategy | R:code:openless-all/app/src/features/settings/shell/tabs.tsx,code:openless-all/app/src/features/settings/shell/useSettingsNavigation.ts | A:visibleSettingsSections,resolveServiceView,visibleAdvancedPages | S:Unified Ask and legacy history depend on host capability; intent routing is desktop-only. Polish strategy is a nested Advanced destination, not a Privacy editor. settings-workspace.css[FU5S]: F:Styles settings workspace interaction, compact headers, responsive form layouts, and working pane geometry. | R:code:openless-all/app/src/features/settings/shell/SettingsModal.tsx | A:Settings workspace styles | S:Keep inert layers out of pointer interaction and switch to stacked form layout in narrow containers. -tabs.tsx[AU7L]: F:Composes platform-gated General, services, privacy and selected Advanced subpages with persistent service pipeline controls | R:code:openless-all/app/src/features/settings/shell/navigation.ts,code:openless-all/app/src/features/settings/sections/AskEntrySettingsSection.tsx,code:openless-all/app/src/features/settings/sections/PolishStrategySection.tsx | A:GeneralTab,PrivacyTab,AdvancedTab,ServicesTab | S:Keep pipeline controls mounted and retain the category strip's layout slot. Rapid choices replace only the queued destination; provider and preference writes remain serialized before leaving. +tabs.tsx[AU7L]: F:Composes platform-gated settings tabs and single-instance Advanced subpages with persistent service pipeline controls | R:code:openless-all/app/src/features/settings/shell/navigation.ts,code:openless-all/app/src/features/settings/sections/AskEntrySettingsSection.tsx,code:openless-all/app/src/features/settings/sections/PolishStrategySection.tsx | A:GeneralTab,PrivacyTab,AdvancedTab,ServicesTab | S:Keep pipeline controls mounted and retain the category strip's layout slot. Rapid choices replace only the queued destination; provider and preference writes remain serialized before leaving. useSettingsLayer.ts[AU6T]: F:Registers the settings surface with viewport modal stacking and tracks its popup host, geometry boundary, and painted lifetime. | R:code:openless-all/app/src/ui/overlays/modalStack.ts | A:useSettingsLayer | S:Use mobile priority where applicable and unregister ownership when the layer closes or unmounts. useSettingsNavigation.ts[AU6M]: F:Coordinates settings navigation, localized headers, cross-language search aliases, scroll restoration and focus handoff | R:code:openless-all/app/src/features/settings/shell/navigation.ts,code:openless-all/app/src/features/settings/shell/SettingsModal.tsx,code:openless-all/app/src/i18n/index.ts | A:useSettingsNavigation | S:Search foreign aliases while keeping labels in the chosen locale. Preserve the newest query across pending draft flush and focus only the active non-inert surface. @@ -2262,8 +2262,8 @@ lib.rs[EG9L]: F:Owns iOS native Core host creation, C ABI, callbacks and executo library.rs[ED6T]: F:Adapts iOS history, bounded search, detail, archive cleanup and repolish requests to shared Core product repositories. | R:code:openless-all/ios/CoreHost/src/control.rs,code:openless-all/ios/CoreHost/src/recording_maintenance.rs | A:library_snapshot; history_entry; delete_history_with_recordings | S:Only explicit detail reads return original text. Hold admission throughout durable history and audio maintenance. library_tests.rs[TD5S]: F:Checks bounded iOS history and full detail, search, vocabulary persistence, repolish and deletion of retained recordings. | R:code:openless-all/ios/CoreHost/src/library.rs | A:- | S:Repolish must not alter original history, and failed transcription can retain real audio until deletion. recording_maintenance.rs[PR7M]: F:Reconciles iOS private recording files and history ownership using a bounded per-asset journal and gated startup or idle maintenance. | R:code:openless-all/ios/CoreHost/src/recordings.rs,code:openless-all/ios/CoreHost/src/library.rs | A:before_history_removal; recording lifecycle reconciliation | S:Quarantine unknown orphans instead of deleting them. A durable prior link distinguishes intended history deletion from an unrelated WAV. -recording_maintenance_tests.rs[TR6L]: F:Covers recording archive journal repair, idle admission, bounded scans and idempotent retries after interrupted native actions. | R:code:openless-all/ios/CoreHost/src/recording_maintenance.rs | A:- | S:Do not scan during starting capture or concurrent management. Pre-mutation failure must retain the history and audio. -recordings.rs[PD7M]: F:Implements bounded private WAV archive construction, finalization, read and removal for Core's iOS recording lifecycle. | R:code:openless-all/ios/CoreHost/src/recording_maintenance.rs,code:openless-all/ios/CoreHost/src/lib.rs | A:WavArchive; RecordingArchive implementation | S:Retain failed recognition when requested and discard successful or canceled ordinary recordings. Discard is idempotent and late frames cannot recreate files. +recording_maintenance_tests.rs[TR6L]: F:Covers iOS archive journal repair, idle admission, bounded scans, retries and secure bounded PCM range access | R:code:openless-all/ios/CoreHost/src/recording_maintenance.rs,code:openless-all/ios/CoreHost/src/recordings.rs | A:- | S:Do not scan during capture admission or concurrent management. Pre-mutation failures retain history and audio; range reads retain secure file validation. +recordings.rs[PD7M]: F:Implements private bounded iOS WAV creation, finalization, metadata and range reads and idempotent removal | R:code:openless-all/ios/CoreHost/src/recording_maintenance.rs,code:openless-all/app/crates/openless-core/src/audio.rs | A:WavArchive,open_wav,pcm_byte_len,read_pcm_range | S:Range reads retain private-directory, inode and single-link checks and the 30-minute size bound. Final headers must match file length; discard is idempotent and late frames cannot recreate files. selection.rs[IB5T]: F:Implements supplied-text-only iOS selection processing and preview host actions for shared Core. | R:code:openless-all/ios/CoreHost/src/control.rs | A:SuppliedTextRuntime,SelectionPreviewActions | S:This host port cannot capture or replace foreground editor text. style_library.rs[EE7M]: F:Adapts iOS style packs, marketplace, ordered translation and capability queries and private archive staging to Core. | R:code:openless-all/ios/CoreHost/src/control.rs,code:openless-all/ios/App/StyleArchiveImport.swift | A:prepare_staging; style_library; marketplace_install | S:Accept only bounded private staged sources, never keyboard-container archives. Keep Core responsible for validating archive content and prompt behavior. style_library_tests.rs[TE6L]: F:Tests iOS style pack policy, archive staging, marketplace handling, and public capability projections. | R:code:openless-all/ios/CoreHost/src/style_library.rs | A:- | S:Reject bad archive inputs before mutation and never infer verification, eligibility, or enablement from the presence of private credentials. @@ -2952,7 +2952,7 @@ collect-rust-licenses.py[OV5T]: F:Collects attribution for reachable non-dev iOS export-ui-evidence.py[XQ4T]: F:Exports XCUITest screenshot attachments under traceable names and maintains the evidence index. | R:code:openless-all/ios/UITests/UIAuditTests.swift | A:XCResult bundle and output directory | S:Preserve failure association metadata and avoid duplicate output names. package-ipa.py[OV6T]: F:Validates an unsigned iOS device product and packages it as a verifiable IPA with build, size, and digest evidence. | R:code:openless-all/ios/scripts/validate-product.py | A:app output | S:Verify members, contents and permissions before atomic publication. Require a new destination outside the app bundle and never overwrite. prediction-tests.swift[TB5T]: F:Checks real offline keyboard dictionary predictions and measures combined English and Chinese lookup latency. | R:code:openless-all/ios/Keyboard/KeyboardPredictionEngine.swift | A:Prediction SQLite path argument | S:A continuation appends only the remaining suffix so typed input cannot be duplicated. -prepare-core.py[OV7T]: F:Stages an isolated iOS copy of Core, applies the contracted patch, and records byte identities for reproducible reuse. | R:code:openless-all/ios/CoreHost/Patches/ios-input-contracts.patch,code:openless-all/ios/scripts/build-core.sh | A:Prepared iOS Core tree and source.json | S:Lock staging, verify the patch before applying, and reject shared-source drift during copy. Keep unmodified sibling dependencies read-only. +prepare-core.py[OV7T]: F:Stages and fingerprints isolated iOS Core, validates and applies its patch and exposes shared host-test dependencies | R:code:openless-all/ios/CoreHost/Patches/ios-input-contracts.patch,code:openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs | A:main,generated_files | S:Stage under lock, validate patch and reject shared-source drift. Expose sibling host helpers read-only for tests; never patch shared sources. preview.sh[OV5T]: F:Builds the iOS Personal simulator preview, installs it on the selected simulator, validates installed resources, and launches. | R:code:openless-all/ios/scripts/validate-product.py,code:openless-all/ios/scripts/resolve-xcodegen.sh | A:IOS_SIMULATOR_ID | S:Require staged native libraries and compiled Rime assets before preview installation. resolve-xcodegen.sh[OV4T]: F:Resolves XcodeGen from an explicit executable override, the pinned local bootstrap build, or PATH. | R:code:openless-all/ios/scripts/bootstrap.sh | A:OPENLESS_XCODEGEN_BIN | S:An invalid explicit override fails rather than silently selecting another binary. rime-smoke.mm[TH5T]: F:Exercises real native Rime composition, candidate and space commit, raw input, deletion and clearing against a staged dictionary. | R:code:openless-all/ios/RimeBridge/OLRimeSession.mm | A:Compiled Rime data path argument | S:Use a temporary writable user directory and remove it on completion. @@ -2985,7 +2985,7 @@ delivery.md[SV6S]: F:Documents CI trigger rules, signing, OSS mirroring, and rel fn-retranscribe-feedback-20261123.md[SB4T]: F:Logs timeline and WAV evidence for Fn rapid-segment continuity and history retranscription debugging | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/src-tauri/src/commands/history_retranscription.rs | A:- | S:Confirms 16kHz mono PCM WAVs reached Volcengine ASR and distinguishes empty ASR output from provider errors. linux.md[SH5T]: F:Documents the Linux egui host architecture, Fcitx5 integration, IPC socket protocol, and logging | R:code:openless-all/app/linux-egui/src/lib.rs,code:openless-all/app/linux-egui/src/backend.rs | A:LinuxBackendBuilder,LinuxHost,openless.log | S:Linux has no local ASR, self-updater, or reliable edit watcher; logs rotate at 2 MiB with 3 historical files. local-models.md[SB6S]: F:Defines local ASR model file, channel, and inference lifecycle transitions across platforms | R:code:openless-all/app/src-tauri/src/asr/local/experimental.rs,code:openless-all/app/src-tauri/src/asr/local/sherpa_runtime.rs | A:downloadPending,installPending,deletePending | S:File presence, active channel, and loaded inference engine are separate states; macOS legacy Qwen/Whisper manager is retired. -long-recording.md[SB6T]: F:Specifies long-recording protection (>5 min), WAV archiving, ASR replay, and 4000-char chunked polish | R:code:openless-all/app/crates/openless-core/src/long_recording.rs,code:openless-all/app/crates/openless-core/src/dictation_engine.rs | A:PipelineDictationEngine | S:Threshold is strictly >5 min of captured 16kHz PCM, never model duration; raw ASR text is saved to history draft before polish. +long-recording.md[SB6T]: F:Defines long-recording capture, fault cleanup, bounded archive recovery and chunked polish contracts | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/src-tauri/src/recorder.rs | A:PipelineDictationEngine | S:Protection starts after 5 min PCM; spill needs processed audio. Archive failure retains error across prefix repair. Tencent realtime lacks coverage/pacing checks. official-style-packs.md[SB6T]: F:Documents official intent-reconstruction 1.3.0 style pack distribution, shared body, and alias upgrades | R:code:openless-all/app/crates/openless-core/src/builtin_styles/intent-reconstruction-v1.json,code:openless-all/app/crates/openless-core/src/style_pack_store.rs | A:builtin_intent_pack,reconcile_builtin_packs | S:Upgrades market aliases in place without merging or deleting IDs while preserving user enablement and bindings. polish-strategy.md[SB6T]: F:Documents the optional Rhai post-ASR polish strategy script input map and fallback contract | R:code:openless-all/app/crates/openless-core/src/polish_strategy.rs | A:charCount,audioDurationMs,asrProvider | S:Disabled by default; empty or failing scripts fall back to normal polishing. recording-overlap.md[SB6T]: F:Documents overlapping dictation capture vs background post-processing ownership and cancellation | R:code:openless-all/app/crates/openless-core/src/dictation_engine.rs,code:openless-all/app/crates/openless-core/src/api.rs | A:submit_dictation_session,wait_for_dictation_submission,cancel_dictation | S:Only one session owns the microphone at a time; next recording may start once native audio stop is confirmed. @@ -3022,3 +3022,6 @@ edit_settle.rs[DH6S]: F:Tracks Windows UIA edit quiet periods, IME composition s ===/Users/lvbaiqing/project/openless/openless-all/app/src-tauri/src/insertion/=== clipboard_delivery.rs[IH7S]: F:Serializes host clipboard backup, copy, paste dispatch, confirmation, and conditional restore behind a global delivery lease | R:code:openless-all/app/src-tauri/src/insertion.rs | A:ClipboardDelivery,lock,try_lock,copy_with,insert_with,insert_with_confirmation | S:Lock order is delivery gate then target metadata; never reacquire gate during AX/UIA validation. Unconfirmed ordinary pastes retain text instead of restoring. + +===/Users/lvbaiqing/project/openless/openless-all/app/linux-egui/src/audio/=== +archive.rs[PD6S]: F:Implements Linux RecordingArchive with bounded validated PCM ranges, whole-file compatibility reads and discard | R:code:openless-all/app/linux-egui/src/audio.rs,code:openless-all/app/crates/openless-core/src/audio.rs | A:LinuxRecordingArchive,pcm_byte_len,read_pcm_range | S:Metadata and range I/O run on blocking tasks. Range reads require finalized canonical headers and reject out-of-bounds or truncated payloads; they never load the whole WAV. diff --git a/docs/development/long-recording.md b/docs/development/long-recording.md index 418b69058..ee9fa7bfb 100644 --- a/docs/development/long-recording.md +++ b/docs/development/long-recording.md @@ -16,7 +16,7 @@ 最终 ASR 原文在进入长录音润色之前写回已有历史草稿;即使文字处理迟迟未完成或进程被中断,也不必只靠界面内存找回原文。尚未完成的草稿不标记为已插入或已润色。 -Tauri 录音归档线程保持异步文件写入,队列不再因短暂积压丢弃 PCM。最终停止要等待队列写完与 WAV 头结算。录音开始前的预录、取消、真实设备故障仍沿现有会话与资源管理,不把麦克风实际没有采集到的声音当成可恢复内容。 +Tauri 录音归档线程保持异步文件写入,待写队列限制为 32 MiB。超过容量或发生写盘、头部更新、同步失败时锁存首个错误并反馈录音会话,后续不能宣称归档完整;归档故障通过异步 Core 清理停止录音、取消 ASR 并释放会话占用,不依赖用户再次取消。普通短暂积压不丢帧。最终停止要等待队列写完与 WAV 头结算。追加失败后仍锁存首个错误并禁止后续追加,但显式结算及 Drop 都尝试将已成功保留的 PCM 长度写回头部;可播放的保留片段不代表原录音完整。录音开始前的预录、取消、真实设备故障仍沿现有会话与资源管理,不把麦克风实际没有采集到的声音当成可恢复内容。 原始音频调试模式的临时采集前缀只写一次,后续原始 PCM 由原始通道写入;热麦克风路径不再把同一帧的处理前/后版本都追加到一个 WAV。普通播放与重放的主档案仍使用原来的格式和目录。长录音完成后通过归档头、文件长度和采集量核对完整性;Tauri 无需为这一步把半小时音频全部读入内存。 @@ -34,4 +34,10 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib wav_archive_keeps 这些检查只能证明已发送全部输入分段、请求协议正常完成和交付顺序;不能用来保证任何模型绝不遗漏语义,也不能替代真实服务时限、网络和物理麦克风的长时间验收。当前实现针对共享传统 ASR→LLM 听写链路,不把独立 Omni 音频模型管线或云笔记的专用存储策略冒称已经验收。 -验证结果:等待本候选的云端检查,不复用 Beta.3 父提交的通过结果。 +稳定模式有可用的处理后音频归档时,内存 PCM 超过 8 MiB 后改用归档作为重放源;仅保留原始调试音频时继续使用内存缓冲及原有容量停止保护,不能替换增强后的 ASR 输入;停录并结算后核对完整长度,分块读取。讯飞、火山、百炼及 Qwen/StepFun 实时发送线程按各自节奏发送音频,结束帧走同一 FIFO;写入失败不得被队列排空掩盖。字节写入统计只能证明本机 WebSocket 写入,不能证明服务端逐字识别完整。腾讯云实时 ASR 尚未接入上述 `finalize_streaming_transcript` 覆盖率校验与稳定模式归档重放节流,留作后续跟进。 + +恢复、本地兜底和历史重转录按段读取,桌面适配层使用范围 I/O,避免每段再次加载整段 WAV。历史入口解析 RIFF chunk,允许合法元数据块,拒绝截短文件。活动归档持有保留策略租约,创建、处理、迁移及重转录期间排除清理。Linux、iOS 和远程输入归档也覆盖范围读取与头部长度检查;iOS 保留原有私有路径及文件身份校验。RecordingArchive 的默认范围读取仍仅是兼容回退,新宿主不得据此宣称内存有界;这些改动也不代表所有平台的内存峰值均已消除。 + +最低有效录音为 100 ms 非零 PCM;这只排除采集尚未就绪时的极短片段,不是音量阈值。历史草稿的长录音判断沿采集 PCM 时长更新,保持与引擎的五分钟门槛一致。 + +火山 45000081/45000000、设备冷启动延迟、Windows 嗡鸣仍缺少确认根因所需的真实会话证据。分段识别的语句边界质量、润色上下文和断点续跑、Omni、iOS 容量保护与 Linux 写盘解耦仍不属于已完成验收。 diff --git a/openless-all/app/crates/openless-core/src/api.rs b/openless-all/app/crates/openless-core/src/api.rs index a86bb6c42..e186e59e9 100644 --- a/openless-all/app/crates/openless-core/src/api.rs +++ b/openless-all/app/crates/openless-core/src/api.rs @@ -1,6 +1,6 @@ -mod cloud_note; #[path = "ask_voice_capture.rs"] pub mod ask_voice_capture; +mod cloud_note; use futures_util::future::BoxFuture; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; @@ -1834,21 +1834,39 @@ impl MutableState { fn processing_snapshots(&self) -> Vec { let mut tasks: Vec<_> = self.processing_dictations.values().collect(); tasks.sort_by_key(|task| task.submitted_at); - tasks.into_iter().map(|task| task.snapshot.clone()).collect() + tasks + .into_iter() + .map(|task| task.snapshot.clone()) + .collect() } fn session(&self, id: SessionId) -> Option<&DictationStateSnapshot> { - if self.dictation.session_id == Some(id) { Some(&self.dictation) } - else { self.processing_dictations.get(&id).map(|task| &task.snapshot) } + if self.dictation.session_id == Some(id) { + Some(&self.dictation) + } else { + self.processing_dictations + .get(&id) + .map(|task| &task.snapshot) + } } fn session_mut(&mut self, id: SessionId) -> Option<&mut DictationStateSnapshot> { - if self.dictation.session_id == Some(id) { Some(&mut self.dictation) } - else { self.processing_dictations.get_mut(&id).map(|task| &mut task.snapshot) } + if self.dictation.session_id == Some(id) { + Some(&mut self.dictation) + } else { + self.processing_dictations + .get_mut(&id) + .map(|task| &mut task.snapshot) + } } fn session_context(&self, id: SessionId) -> Option<&Arc> { - if self.dictation.session_id == Some(id) { self.dictation_context.as_ref() } - else { self.processing_dictations.get(&id).map(|task| &task.context) } + if self.dictation.session_id == Some(id) { + self.dictation_context.as_ref() + } else { + self.processing_dictations + .get(&id) + .map(|task| &task.context) + } } } @@ -2501,6 +2519,13 @@ impl EngineProgressSink for BackendEngineProgress { ); } } + EngineProgress::CapturedDurationMs(duration_ms) => { + let mut state = self.state.write().expect("backend state lock poisoned"); + ensure_active_session(&state, session_id)?; + if let Some(snapshot) = state.session_mut(session_id) { + snapshot.elapsed_ms = duration_ms; + } + } EngineProgress::RecordingLimitReached => { let state = self.state.read().expect("backend state lock poisoned"); ensure_capture_session(&state, session_id)?; @@ -2555,7 +2580,9 @@ impl EngineProgressSink for BackendEngineProgress { state.session_mut(session_id).unwrap().phase = phase; self.events.publish( Some(session_id), - BackendEventKind::DictationStateChanged(state.session(session_id).unwrap().clone()), + BackendEventKind::DictationStateChanged( + state.session(session_id).unwrap().clone(), + ), ); self.phase_changed.notify_waiters(); } @@ -3200,7 +3227,10 @@ impl OpenLessBackend { ) -> Result<&crate::cloud_sync_e2ee_store::CoreSyncStore, BackendError> { self.local_migration_store.as_deref().ok_or_else(|| { self.startup_error.clone().unwrap_or_else(|| { - BackendError::new(BackendErrorCode::InvalidState, "local migration is unavailable") + BackendError::new( + BackendErrorCode::InvalidState, + "local migration is unavailable", + ) }) }) } @@ -3297,7 +3327,9 @@ impl OpenLessBackend { } else { AppStyleStore::open( &config.data_dir, - deps.marketplace_config.as_ref().map(|config| config.base_url.clone()), + deps.marketplace_config + .as_ref() + .map(|config| config.base_url.clone()), ) }; let events = Arc::new(EventBus::new(256)); @@ -3670,7 +3702,9 @@ impl OpenLessBackend { voice_activation_generation: Arc::new(AtomicU64::new(0)), voice_activation_handoff_generation: AtomicU64::new(0), voice_activation_configure_gate: tokio::sync::Mutex::new(()), - voice_activation_link: Mutex::new(crate::voice_activation_hotkey::VoiceActivationLink::default()), + voice_activation_link: Mutex::new( + crate::voice_activation_hotkey::VoiceActivationLink::default(), + ), backend_lifecycle_gate: tokio::sync::Mutex::new(()), backend_shutdown_requested: AtomicBool::new(false), voice_activation_session: Arc::new(Mutex::new(None)), @@ -3697,10 +3731,14 @@ impl OpenLessBackend { fn voice_activation_intent(&self) -> (bool, bool, u64) { let prefs = self.get_preferences(); - let linked = prefs.voice_activation_enabled && prefs.voice_activation_hotkey_linked + let linked = prefs.voice_activation_enabled + && prefs.voice_activation_hotkey_linked && self.deps.voice_activation_runtime.is_some(); let (requested, revision) = { - let mut state = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let mut state = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); state.configure(linked); (state.requested, state.revision) }; @@ -3717,7 +3755,10 @@ impl OpenLessBackend { return; } let revision = { - let mut state = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let mut state = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); if self.voice_activation_generation.load(Ordering::Acquire) != generation { return; } @@ -3731,18 +3772,28 @@ impl OpenLessBackend { async fn recover_voice_activation_failure(&self, generation: u64, error: BackendError) { self.pause_linked_voice_activation_after_failure(generation); - match self.stop_voice_activation_if_current(generation, - crate::voice_activation::VoiceActivationStopReason::RuntimeFailure).await + match self + .stop_voice_activation_if_current( + generation, + crate::voice_activation::VoiceActivationStopReason::RuntimeFailure, + ) + .await { Ok(true) => { if self.voice_activation_intent().1 { - self.events.publish(None, BackendEventKind::VoiceActivationStateChanged( - crate::voice_activation::VoiceActivationStateSnapshot { - phase: voice_activation_failure_phase(error.code), - activation_generation: self.voice_activation_generation.load(Ordering::Acquire), - session_id: None, - message: Some(error.message), - })); + self.events.publish( + None, + BackendEventKind::VoiceActivationStateChanged( + crate::voice_activation::VoiceActivationStateSnapshot { + phase: voice_activation_failure_phase(error.code), + activation_generation: self + .voice_activation_generation + .load(Ordering::Acquire), + session_id: None, + message: Some(error.message), + }, + ), + ); } else if self.voice_activation_is_requested() { let _ = self.configure_voice_activation().await; } @@ -3761,19 +3812,29 @@ impl OpenLessBackend { pub fn accept_voice_activation_hotkey_edge(&self, edge: DictationHotkeyEdge) -> Option { self.voice_activation_intent(); let prefs = self.get_preferences(); - if !prefs.voice_activation_enabled || !prefs.voice_activation_hotkey_linked + if !prefs.voice_activation_enabled + || !prefs.voice_activation_hotkey_linked || self.deps.voice_activation_runtime.is_none() { return None; } let (changed, paused, revision, generation) = { - let mut state = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let mut state = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); let changed = state.edge(edge); let generation = if changed { - let handoff = self.voice_activation_handoff_generation.load(Ordering::Acquire); + let handoff = self + .voice_activation_handoff_generation + .load(Ordering::Acquire); if !state.requested { - state.finalize_session = self.voice_activation_session.lock() - .expect("voice activation session lock poisoned").as_ref().map(|s| s.session_id); + state.finalize_session = self + .voice_activation_session + .lock() + .expect("voice activation session lock poisoned") + .as_ref() + .map(|s| s.session_id); if handoff != 0 { state.finalize_generation = Some(handoff); } @@ -3783,7 +3844,9 @@ impl OpenLessBackend { if handoff != 0 && state.finalize_generation == Some(handoff) { self.voice_activation_generation.load(Ordering::Acquire) } else { - self.voice_activation_generation.fetch_add(1, Ordering::AcqRel) + 1 + self.voice_activation_generation + .fetch_add(1, Ordering::AcqRel) + + 1 } } else { self.voice_activation_generation.load(Ordering::Acquire) @@ -3794,14 +3857,21 @@ impl OpenLessBackend { if let Some(runtime) = &self.deps.voice_activation_runtime { runtime.set_capture_paused(revision, paused); } - self.events.publish(None, BackendEventKind::VoiceActivationStateChanged( - crate::voice_activation::VoiceActivationStateSnapshot { - phase: if paused { crate::voice_activation::VoiceActivationPhase::Pausing } - else { crate::voice_activation::VoiceActivationPhase::Starting }, - activation_generation: generation, - session_id: None, - message: None, - })); + self.events.publish( + None, + BackendEventKind::VoiceActivationStateChanged( + crate::voice_activation::VoiceActivationStateSnapshot { + phase: if paused { + crate::voice_activation::VoiceActivationPhase::Pausing + } else { + crate::voice_activation::VoiceActivationPhase::Starting + }, + activation_generation: generation, + session_id: None, + message: None, + }, + ), + ); } Some(changed) } @@ -3812,21 +3882,38 @@ impl OpenLessBackend { if !preferences.voice_activation_enabled || !preferences.voice_activation_hotkey_linked { return None; } - let state = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let state = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); Some((state.requested, state.revision)) } pub async fn reconcile_voice_activation_hotkey(&self) -> Result<(), BackendError> { - let paused_session = self.voice_activation_link.lock() - .expect("voice link lock poisoned").finalize_session; + let paused_session = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned") + .finalize_session; let session_id = paused_session.or_else(|| { - self.voice_activation_intent().1.then(|| self.voice_activation_session.lock() - .expect("voice activation session lock poisoned").as_ref().map(|s| s.session_id)).flatten() + self.voice_activation_intent() + .1 + .then(|| { + self.voice_activation_session + .lock() + .expect("voice activation session lock poisoned") + .as_ref() + .map(|s| s.session_id) + }) + .flatten() }); if let Some(session_id) = session_id { // Recorder stop can reconfigure activation: never hold configure_gate here. if let Err(error) = self.stop_dictation_session(session_id).await { - if !matches!(error.code, BackendErrorCode::InvalidState | BackendErrorCode::Busy) { + if !matches!( + error.code, + BackendErrorCode::InvalidState | BackendErrorCode::Busy + ) { return Err(error); } } @@ -3835,8 +3922,12 @@ impl OpenLessBackend { } async fn settle_stale_voice_dictation(&self, session_id: SessionId) { - let must_finalize = self.voice_activation_link.lock() - .expect("voice link lock poisoned").finalize_session == Some(session_id); + let must_finalize = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned") + .finalize_session + == Some(session_id); if must_finalize || self.voice_activation_intent().1 { let _ = self.stop_dictation_session(session_id).await; let _ = self.configure_voice_activation().await; @@ -3853,10 +3944,15 @@ impl OpenLessBackend { let _configure_gate = self.voice_activation_configure_gate.lock().await; let (effective, paused, revision) = self.voice_activation_intent(); let preferences = self.get_preferences(); - let pending_body = self.voice_activation_link.lock() - .expect("voice link lock poisoned").finalize_generation; + let pending_body = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned") + .finalize_generation; if pending_body.is_some_and(|generation| { - self.voice_activation_handoff_generation.load(Ordering::Acquire) == generation + self.voice_activation_handoff_generation + .load(Ordering::Acquire) + == generation }) { return Ok(()); } @@ -3900,7 +3996,8 @@ impl OpenLessBackend { // activation was never enabled. Existing subscribers expect // BackendStarted to be the first startup event; later disable/error // transitions still publish Disabled below when a visible state exists. - let should_publish_disabled = paused || had_previous_handle + let should_publish_disabled = paused + || had_previous_handle || self .events .latest_voice_activation_state() @@ -3913,8 +4010,11 @@ impl OpenLessBackend { None, BackendEventKind::VoiceActivationStateChanged( crate::voice_activation::VoiceActivationStateSnapshot { - phase: if paused { crate::voice_activation::VoiceActivationPhase::Paused } - else { crate::voice_activation::VoiceActivationPhase::Disabled }, + phase: if paused { + crate::voice_activation::VoiceActivationPhase::Paused + } else { + crate::voice_activation::VoiceActivationPhase::Disabled + }, activation_generation: generation, session_id: None, message: None, @@ -3976,7 +4076,8 @@ impl OpenLessBackend { }); let configured = if preferences.voice_activation_hotkey_linked && !config.wake_enabled { Err(crate::ports::VoiceActivationError::InvalidConfig( - "enable the wake phrase before linking the recording shortcut".into())) + "enable the wake phrase before linking the recording shortcut".into(), + )) } else { runtime.configure(config, sink).await }; @@ -3988,7 +4089,12 @@ impl OpenLessBackend { .lock() .expect("voice activation handle lock poisoned"); if self.voice_activation_generation.load(Ordering::Acquire) != generation - || self.voice_activation_link.lock().expect("voice link lock poisoned").revision != revision + || self + .voice_activation_link + .lock() + .expect("voice link lock poisoned") + .revision + != revision { Some(handle) } else { @@ -4324,9 +4430,15 @@ impl OpenLessBackend { } => { let backend = Arc::clone(self); self.deps.task_spawner.spawn(Box::pin(async move { - backend.recover_voice_activation_failure(activation_generation, - BackendError::new(BackendErrorCode::Platform, - "voice activation microphone capture failed")).await; + backend + .recover_voice_activation_failure( + activation_generation, + BackendError::new( + BackendErrorCode::Platform, + "voice activation microphone capture failed", + ), + ) + .await; })); } VoiceActivationSignal::RuntimeStateChanged { .. } => {} @@ -4415,7 +4527,10 @@ impl OpenLessBackend { }); } { - let mut link = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let mut link = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); if link.finalize_generation == Some(generation) { link.finalize_session = Some(session_id); } @@ -4451,7 +4566,10 @@ impl OpenLessBackend { return; } { - let mut link = self.voice_activation_link.lock().expect("voice link lock poisoned"); + let mut link = self + .voice_activation_link + .lock() + .expect("voice link lock poisoned"); if link.finalize_session == Some(session_id) { link.finalize_session = None; link.finalize_generation = None; @@ -4541,10 +4659,15 @@ impl OpenLessBackend { let search = Arc::new(crate::ask_search::WebSearchTool::new( self.deps.credential_store.clone(), )); - let usage = self.deps.services.usage_recorder.clone().map(|recorder| AskUsagePersistence { - recorder, - clock: self.clock.clone(), - }); + let usage = self + .deps + .services + .usage_recorder + .clone() + .map(|recorder| AskUsagePersistence { + recorder, + clock: self.clock.clone(), + }); let assistant = Arc::new(crate::assistant::PersonalAssistant::new( crate::assistant::AssistantDependencies { models: models.clone(), @@ -5528,7 +5651,7 @@ impl OpenLessBackend { backend: BackendSnapshot { running: true, dictation: state.dictation.clone(), - processing_dictations: state.processing_snapshots(), + processing_dictations: state.processing_snapshots(), vocabulary_revision: self.vocabulary_revision.load(Ordering::Acquire), history_revision: self.history_revision.load(Ordering::Acquire), style_pack_revision: self.style_pack_revision.load(Ordering::Acquire), @@ -5544,7 +5667,7 @@ impl OpenLessBackend { backend: BackendSnapshot { running: true, dictation: state.dictation.clone(), - processing_dictations: state.processing_snapshots(), + processing_dictations: state.processing_snapshots(), vocabulary_revision: self.vocabulary_revision.load(Ordering::Acquire), history_revision: self.history_revision.load(Ordering::Acquire), style_pack_revision: self.style_pack_revision.load(Ordering::Acquire), @@ -5760,9 +5883,16 @@ impl OpenLessBackend { } /// Immutable final mode, language, context and materials for a submitted segment. - pub fn submitted_dictation_context(&self, session_id: SessionId) -> Option> { - self.state.read().expect("backend state lock poisoned") - .processing_dictations.get(&session_id).map(|task| Arc::clone(&task.context)) + pub fn submitted_dictation_context( + &self, + session_id: SessionId, + ) -> Option> { + self.state + .read() + .expect("backend state lock poisoned") + .processing_dictations + .get(&session_id) + .map(|task| Arc::clone(&task.context)) } /// Resolves only after the device stop joined and this segment became a job. @@ -5770,7 +5900,9 @@ impl OpenLessBackend { pub async fn wait_for_dictation_submission(&self, session_id: SessionId) { loop { let changed = self.phase_changed.notified(); - if self.submitted_dictation_context(session_id).is_some() { return; } + if self.submitted_dictation_context(session_id).is_some() { + return; + } changed.await; } } @@ -5778,7 +5910,12 @@ impl OpenLessBackend { /// Resolve an explicit owner before a UI/CLI cancellation crosses an await. pub fn dictation_cancel_target(&self) -> Option { let state = self.state.read().expect("backend state lock poisoned"); - state.dictation.session_id.or_else(|| state.processing_snapshots().first().and_then(|task| task.session_id)) + state.dictation.session_id.or_else(|| { + state + .processing_snapshots() + .first() + .and_then(|task| task.session_id) + }) } /// Dispatch a launcher/single-instance intent through the same state @@ -5808,8 +5945,12 @@ impl OpenLessBackend { let qa = &self.deps.services.qa; let snapshot = qa.snapshot().await?; match (snapshot.phase, snapshot.session_id) { - (crate::QaPhase::Recording, Some(session_id)) => qa.stop_recording(session_id).await?, - (crate::QaPhase::Thinking | crate::QaPhase::AwaitingApproval, _) => return Ok(CliDispatchOutcome::Noop), + (crate::QaPhase::Recording, Some(session_id)) => { + qa.stop_recording(session_id).await? + } + (crate::QaPhase::Thinking | crate::QaPhase::AwaitingApproval, _) => { + return Ok(CliDispatchOutcome::Noop) + } _ => qa.start_question().await?, } Ok(CliDispatchOutcome::QaToggled) @@ -5967,7 +6108,8 @@ impl OpenLessBackend { edge: DictationHotkeyEdge, options: DictationHotkeyDispatchOptions, ) -> Result { - self.dispatch_dictation_hotkey_edge_inner(edge, options, None).await + self.dispatch_dictation_hotkey_edge_inner(edge, options, None) + .await } pub async fn dispatch_arbitrated_dictation_hotkey_press( @@ -5976,8 +6118,11 @@ impl OpenLessBackend { still_held: impl Fn() -> bool + Send + Sync, ) -> Result { self.dispatch_dictation_hotkey_edge_inner( - edge, DictationHotkeyDispatchOptions::default(), Some(&still_held), - ).await + edge, + DictationHotkeyDispatchOptions::default(), + Some(&still_held), + ) + .await } async fn dispatch_dictation_hotkey_edge_inner( @@ -6015,8 +6160,8 @@ impl OpenLessBackend { if still_held.is_some_and(|check| !check()) { return Ok(CliDispatchOutcome::Noop); } - let modifier_only = still_held.is_none() && - (crate::shortcut_types::is_modifier_chord_binding(&preferences.dictation_hotkey) + let modifier_only = still_held.is_none() + && (crate::shortcut_types::is_modifier_chord_binding(&preferences.dictation_hotkey) || crate::hotkey_interpreter::modifier_arbitration_required( crate::shortcut_types::legacy_modifier_trigger(&preferences.dictation_hotkey), mode, @@ -6173,7 +6318,8 @@ impl OpenLessBackend { let session = self.snapshot().dictation.session_id; drop(_dispatch_guard); self.stop_dictation_session_with_options(session, options.stop, None) - .await.map(CliDispatchOutcome::DictationCompleted) + .await + .map(CliDispatchOutcome::DictationCompleted) } HotkeyIntent::Cancel { press_id } => { let active = self.snapshot().dictation.session_id; @@ -6197,20 +6343,38 @@ impl OpenLessBackend { let _dispatch = self.hotkey_dispatch_gate.lock().await; let snapshot = self.snapshot().dictation; if let Some(session_id) = snapshot.session_id { - if !matches!(snapshot.phase, DictationPhase::Starting | DictationPhase::Recording) { - return Err(BackendError::new(BackendErrorCode::Busy, "dictation is finalizing")); + if !matches!( + snapshot.phase, + DictationPhase::Starting | DictationPhase::Recording + ) { + return Err(BackendError::new( + BackendErrorCode::Busy, + "dictation is finalizing", + )); } if let Err(error) = self.cancel_dictation(Some(session_id)).await { // The independent combo-abort bridge may have claimed this same // prefix already. Its native cleanup still owns the voice lease. if self.snapshot().dictation.session_id.is_some() - || error.code != BackendErrorCode::InvalidState { return Err(error); } + || error.code != BackendErrorCode::InvalidState + { + return Err(error); + } } } - let provisional = std::mem::take(&mut *self.pending_audio_captures.lock() - .expect("pending audio capture lock poisoned")); - for capture in provisional.into_values() { capture.discard().await?; } - self.hotkey.lock().expect("hotkey interpreter lock poisoned").reset(); + let provisional = std::mem::take( + &mut *self + .pending_audio_captures + .lock() + .expect("pending audio capture lock poisoned"), + ); + for capture in provisional.into_values() { + capture.discard().await?; + } + self.hotkey + .lock() + .expect("hotkey interpreter lock poisoned") + .reset(); // Logical cancellation can precede the final native cleanup hold. Never // cancel another domain or open a second microphone during that interval. for _ in 0..25 { @@ -6219,7 +6383,10 @@ impl OpenLessBackend { } tokio::time::sleep(std::time::Duration::from_millis(20)).await; } - Err(BackendError::new(BackendErrorCode::Busy, "microphone is still being released")) + Err(BackendError::new( + BackendErrorCode::Busy, + "microphone is still being released", + )) } /// Accept the only mutable dictation intent into the current session. The @@ -6235,13 +6402,16 @@ impl OpenLessBackend { /// Toggle only the capture that owned the completed native Shift gesture. /// Startup retains raw intent until context capture resolves the effective mode. pub fn toggle_dictation_translation_for_session( - &self, session_id: SessionId, + &self, + session_id: SessionId, ) -> Result<(), BackendError> { self.change_dictation_translation(Some(session_id), None) } fn change_dictation_translation( - &self, expected_session_id: Option, requested: Option, + &self, + expected_session_id: Option, + requested: Option, ) -> Result<(), BackendError> { let preferences = self.get_preferences(); { @@ -6263,11 +6433,16 @@ impl OpenLessBackend { ) })?; if expected_session_id.is_some_and(|expected| expected != session_id) { - return Err(BackendError::new(BackendErrorCode::InvalidState, - "translation gesture belongs to a recording that has ended")); + return Err(BackendError::new( + BackendErrorCode::InvalidState, + "translation gesture belongs to a recording that has ended", + )); } - let requested = requested.unwrap_or_else(|| !state.dictation_translation_requested - .unwrap_or(state.dictation.translation_active)); + let requested = requested.unwrap_or_else(|| { + !state + .dictation_translation_requested + .unwrap_or(state.dictation.translation_active) + }); state.dictation_translation_requested = Some(requested); let effective = if let Some(context) = state.dictation_context.as_ref() { let updated = Arc::new(context.with_translation_requested(requested)); @@ -6315,25 +6490,44 @@ impl OpenLessBackend { session_id: SessionId, target_language: String, ) -> Result { - let target = crate::language_catalog::native_language_name(&target_language) - .ok_or_else(|| BackendError::new(BackendErrorCode::InvalidArgument, "unsupported translation language"))?; - let _write_guard = self.settings_write_gate.lock() + let target = + crate::language_catalog::native_language_name(&target_language).ok_or_else(|| { + BackendError::new( + BackendErrorCode::InvalidArgument, + "unsupported translation language", + ) + })?; + let _write_guard = self + .settings_write_gate + .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let mut state = self.state.write().expect("backend state lock poisoned"); ensure_running(&state)?; if state.dictation.session_id != Some(session_id) || state.dictation.phase != DictationPhase::Recording { - return Err(BackendError::new(BackendErrorCode::InvalidState, - "translation picker belongs to a recording that has ended")); + return Err(BackendError::new( + BackendErrorCode::InvalidState, + "translation picker belongs to a recording that has ended", + )); } - let context = state.dictation_context.as_ref().ok_or_else(|| - BackendError::new(BackendErrorCode::InvalidState, "recording context is not ready"))?; + let context = state.dictation_context.as_ref().ok_or_else(|| { + BackendError::new( + BackendErrorCode::InvalidState, + "recording context is not ready", + ) + })?; if !context.polish.translation_active - || !crate::shared_types::translation_effective(true, &target, &context.polish.working_languages) + || !crate::shared_types::translation_effective( + true, + &target, + &context.polish.working_languages, + ) { - return Err(BackendError::new(BackendErrorCode::InvalidArgument, - "translation is inactive or the target matches the only working language")); + return Err(BackendError::new( + BackendErrorCode::InvalidArgument, + "translation is inactive or the target matches the only working language", + )); } let mut updated = (**context).clone(); updated.polish.translation_target_language = target.clone(); @@ -6345,7 +6539,8 @@ impl OpenLessBackend { }; // Keep finalization outside this critical section. A failed save changes neither // the active target nor the remembered choice, and no other preference is overwritten. - self.preferences.update(|preferences| preferences.translation_target_language = target)?; + self.preferences + .update(|preferences| preferences.translation_target_language = target)?; state.dictation_context = Some(Arc::new(updated)); // The common stop boundary must also send the changed context to a streaming engine. state.dictation_translation_requested = Some(true); @@ -6376,13 +6571,26 @@ impl OpenLessBackend { self.siwc_service() } - pub async fn begin_siwc_sign_in(&self, channel: String, new_account: bool, enable_usage: bool) -> Result { + pub async fn begin_siwc_sign_in( + &self, + channel: String, + new_account: bool, + enable_usage: bool, + ) -> Result { let service = self.siwc_for_channel(&channel).await?; - let launch = service.begin_sign_in(channel.clone(), new_account, enable_usage).await.map_err(crate::siwc::SiwcError::into_backend)?; + let launch = service + .begin_sign_in(channel.clone(), new_account, enable_usage) + .await + .map_err(crate::siwc::SiwcError::into_backend)?; // Storage/browser preparation can race channel deletion or a provider switch. let current = self.siwc_for_channel(&channel).await; - if current.is_ok() && service.authorizing(&channel, &launch.attempt_id) { return Ok(launch); } - service.cancel_attempt(&channel, &launch.attempt_id).await.map_err(crate::siwc::SiwcError::into_backend)?; + if current.is_ok() && service.authorizing(&channel, &launch.attempt_id) { + return Ok(launch); + } + service + .cancel_attempt(&channel, &launch.attempt_id) + .await + .map_err(crate::siwc::SiwcError::into_backend)?; current?; Err(crate::siwc::error("cancelled").into_backend()) } @@ -6407,7 +6615,10 @@ impl OpenLessBackend { .iter() .any(|c| &c.id == channel && c.provider_type == crate::siwc::PROVIDER_ID) { - let session = service.status(channel).await.map_err(crate::siwc::SiwcError::into_backend)?; + let session = service + .status(channel) + .await + .map_err(crate::siwc::SiwcError::into_backend)?; let model = self .deps .credential_store @@ -6644,7 +6855,11 @@ impl OpenLessBackend { .any(|c| c.id == id && c.provider_type == crate::siwc::PROVIDER_ID) { if let Some(service) = self.deps.credential_store.siwc() { - if service.has_binding(&id).await.map_err(crate::siwc::SiwcError::into_backend)? { + if service + .has_binding(&id) + .await + .map_err(crate::siwc::SiwcError::into_backend)? + { return Ok(false); } } @@ -6692,7 +6907,10 @@ impl OpenLessBackend { }) .await?; if let Some(service) = service { - service.detach(id).await.map_err(crate::siwc::SiwcError::into_backend)?; + service + .detach(id) + .await + .map_err(crate::siwc::SiwcError::into_backend)?; } Ok(()) } @@ -6742,8 +6960,14 @@ impl OpenLessBackend { .map(|_| ()) } - pub async fn invalidate_channel_test(&self, kind: ChannelKind, id: String) -> Result<(), BackendError> { - self.apply_channel_mutation(ChannelMutation::InvalidateTest { kind, id }).await.map(|_| ()) + pub async fn invalidate_channel_test( + &self, + kind: ChannelKind, + id: String, + ) -> Result<(), BackendError> { + self.apply_channel_mutation(ChannelMutation::InvalidateTest { kind, id }) + .await + .map(|_| ()) } pub async fn invalidate_channel_tests(&self, kind: ChannelKind) -> Result<(), BackendError> { @@ -7162,7 +7386,8 @@ impl OpenLessBackend { } pub async fn refresh_and_publish_credentials(&self) -> Result { - self.provider_credentials_revision.fetch_add(1, Ordering::AcqRel); + self.provider_credentials_revision + .fetch_add(1, Ordering::AcqRel); self.dictation_provider_warmth.lock().unwrap().take(); let status = crate::deepseek_suite::credentials_status( self.deps.credential_store.as_ref(), @@ -7738,7 +7963,8 @@ impl OpenLessBackend { surface: crate::main_dictation_trace::CaptionTraceSurface, stage: crate::main_dictation_trace::CaptionTraceStage, ) { - self.main_dictation_trace.webview(session, sequence, surface, stage); + self.main_dictation_trace + .webview(session, sequence, surface, stage); } fn trace_main_dictation_history(&self, session: SessionId, checkpoint: &'static str) { @@ -7981,11 +8207,23 @@ impl OpenLessBackend { pub fn expression_profile_directions( &self, ) -> Result, BackendError> { - let profile = self.expression_profile.lock().map_err(|_| { - BackendError::new(BackendErrorCode::Internal, "expression profile lock unavailable") - })?.clone(); + let profile = self + .expression_profile + .lock() + .map_err(|_| { + BackendError::new( + BackendErrorCode::Internal, + "expression profile lock unavailable", + ) + })? + .clone(); profile - .ok_or_else(|| BackendError::new(BackendErrorCode::Persistence, "expression profile is unavailable"))? + .ok_or_else(|| { + BackendError::new( + BackendErrorCode::Persistence, + "expression profile is unavailable", + ) + })? .stable_directions() } @@ -7996,7 +8234,10 @@ impl OpenLessBackend { })?; self.disarm_edit_observation(); let mut profile = self.expression_profile.lock().map_err(|_| { - BackendError::new(BackendErrorCode::Internal, "expression profile lock unavailable") + BackendError::new( + BackendErrorCode::Internal, + "expression profile lock unavailable", + ) })?; if let Some(existing) = profile.as_ref() { if existing.clear().is_ok() { @@ -8054,8 +8295,13 @@ impl OpenLessBackend { // reading any document for an obsolete completion. { let state = self.state.read().expect("backend state lock poisoned"); - if state.dictation.session_id.is_some_and(|id| id != session_id) - || state.session(session_id).is_none_or(|snapshot| snapshot.phase != DictationPhase::Completed) + if state + .dictation + .session_id + .is_some_and(|id| id != session_id) + || state + .session(session_id) + .is_none_or(|snapshot| snapshot.phase != DictationPhase::Completed) { return; } @@ -8063,7 +8309,8 @@ impl OpenLessBackend { self.disarm_edit_observation(); let preferences = self.get_preferences(); if !enabled - || (!preferences.vocabulary_learning_enabled && !preferences.expression_learning_enabled) + || (!preferences.vocabulary_learning_enabled + && !preferences.expression_learning_enabled) || !matches!(insert_outcome, Some(InsertOutcome::Inserted)) || typed_text.trim().is_empty() { @@ -8095,7 +8342,9 @@ impl OpenLessBackend { } let sink = Arc::new(CombinedEditObservationSink { vocabulary, - expression_generation: expression_profile.as_ref().map(|profile| profile.generation()), + expression_generation: expression_profile + .as_ref() + .map(|profile| profile.generation()), expression_profile, typed_text: typed_text.to_string(), session_id, @@ -8371,7 +8620,10 @@ impl OpenLessBackend { capture_key: Option, ) -> Result { self.reserve_dictation_session_with_id( - SessionId::new(), insert_text, output_target, capture_key, + SessionId::new(), + insert_text, + output_target, + capture_key, ) } @@ -8400,7 +8652,11 @@ impl OpenLessBackend { // Freeze the destination and its matching host-context reader before context/credential // awaits or feedback can change foreground focus. No native preparation happens yet. let (inserter, host_context) = if insert_text { - match self.deps.text_inserter.capture_target_for_session(session_id) { + match self + .deps + .text_inserter + .capture_target_for_session(session_id) + { Some(captured) => (captured.inserter, captured.host_context), None => ( Arc::clone(&self.deps.text_inserter), @@ -8639,8 +8895,11 @@ impl OpenLessBackend { // Shift and stop options are sealed before deferred preparation. // Use this session's submitted context, never the next capture's. let insertion_context = if defer_preparation { - preparation_state.read().expect("backend state lock poisoned") - .session_context(session_id).cloned() + preparation_state + .read() + .expect("backend state lock poisoned") + .session_context(session_id) + .cloned() .ok_or_else(VoiceCaptureLifecycle::cancelled_error)? } else { insertion_context @@ -8673,58 +8932,60 @@ impl OpenLessBackend { .insert(session_id, preparation.clone()); } if !defer_preparation { - let prepared = preparation.await; - let still_active = self - .state - .read() - .expect("backend state lock poisoned") - .dictation - .session_id - == Some(session_id); - if !still_active { - let cleanup_result = self.cancel_text_insertion(session_id).await; - self.schedule_pending_audio_capture_discard(pending_capture.take()); - return match cleanup_result { - Ok(()) => Err(BackendError::new( - BackendErrorCode::Cancelled, - "dictation session was cancelled while insertion was starting", - )), - Err(error) => Err(error), - }; - } - match prepared { - Ok(_) => {} - Err(error) => { - self.text_insertions - .lock() - .expect("text insertion registry lock poisoned") - .remove(&session_id); - self.mark_dictation_failed(session_id, &error); - self.persist_failed_dictation( - &context, - session_id, - if error.code == BackendErrorCode::OutcomeUnknown { - "insertOutcomeUnknown" - } else if error.is_target_unavailable() { - "insertTargetChanged" - } else { "insertFailed" }, - String::new(), - String::new(), - None, - None, - None, - None, - None, - false, - None, - None, - ); - let _ = self.hide_dictation_feedback(session_id); + let prepared = preparation.await; + let still_active = self + .state + .read() + .expect("backend state lock poisoned") + .dictation + .session_id + == Some(session_id); + if !still_active { + let cleanup_result = self.cancel_text_insertion(session_id).await; self.schedule_pending_audio_capture_discard(pending_capture.take()); - self.reset_dictation_session(session_id); - return Err(error); + return match cleanup_result { + Ok(()) => Err(BackendError::new( + BackendErrorCode::Cancelled, + "dictation session was cancelled while insertion was starting", + )), + Err(error) => Err(error), + }; + } + match prepared { + Ok(_) => {} + Err(error) => { + self.text_insertions + .lock() + .expect("text insertion registry lock poisoned") + .remove(&session_id); + self.mark_dictation_failed(session_id, &error); + self.persist_failed_dictation( + &context, + session_id, + if error.code == BackendErrorCode::OutcomeUnknown { + "insertOutcomeUnknown" + } else if error.is_target_unavailable() { + "insertTargetChanged" + } else { + "insertFailed" + }, + String::new(), + String::new(), + None, + None, + None, + None, + None, + false, + None, + None, + ); + let _ = self.hide_dictation_feedback(session_id); + self.schedule_pending_audio_capture_discard(pending_capture.take()); + self.reset_dictation_session(session_id); + return Err(error); + } } - } } } if context.output_target != DictationOutputTarget::ForegroundApp { @@ -8828,13 +9089,19 @@ impl OpenLessBackend { /// Terminal result/history/events still use this session's identity; dropping /// an IPC reply cannot abandon that work. Legacy stop APIs keep awaiting it. pub async fn submit_dictation_session( - self: &Arc, session_id: SessionId, options: DictationStopOptions, + self: &Arc, + session_id: SessionId, + options: DictationStopOptions, ) -> Result { let backend = Arc::clone(self); let (send, receive) = tokio::sync::oneshot::channel(); self.deps.task_spawner.spawn(Box::pin(async move { - let result = backend.stop_dictation_session_with_options(Some(session_id), options, None).await; - if let Err(error) = &result { log::warn!("[dictation] submitted segment {session_id}: {error}"); } + let result = backend + .stop_dictation_session_with_options(Some(session_id), options, None) + .await; + if let Err(error) = &result { + log::warn!("[dictation] submitted segment {session_id}: {error}"); + } let _ = send.send(result); })); tokio::select! { @@ -8960,10 +9227,8 @@ impl OpenLessBackend { state.dictation_context = Some(Arc::clone(&context)); state.dictation.translation_active = context.polish.translation_active; state.dictation.phase = DictationPhase::Transcribing; - self.main_dictation_trace.record( - session_id, - format_args!("stage=finalization_started"), - ); + self.main_dictation_trace + .record(session_id, format_args!("stage=finalization_started")); self.events.publish( Some(session_id), BackendEventKind::DictationStateChanged(state.dictation.clone()), @@ -9063,24 +9328,38 @@ impl OpenLessBackend { // Native stop joins the audio producer before capture can be reassigned. // An error cannot prove release; keep the capture lease through cleanup. - let capture_released = self.deps.dictation_engine.stop_recording(session_id).await.unwrap_or(false); + let capture_released = self + .deps + .dictation_engine + .stop_recording(session_id) + .await + .unwrap_or(false); if capture_released { - let mut hotkey = self.hotkey.lock().expect("hotkey interpreter lock poisoned"); + let mut hotkey = self + .hotkey + .lock() + .expect("hotkey interpreter lock poisoned"); let mut state = self.state.write().expect("backend state lock poisoned"); ensure_active_session(&state, session_id)?; let snapshot = std::mem::take(&mut state.dictation); - state.processing_dictations.insert(session_id, SubmittedDictation { - snapshot: snapshot.clone(), context: Arc::clone(&context), - submitted_at: std::time::Instant::now(), - }); + state.processing_dictations.insert( + session_id, + SubmittedDictation { + snapshot: snapshot.clone(), + context: Arc::clone(&context), + submitted_at: std::time::Instant::now(), + }, + ); state.dictation_context = None; state.dictation_start_output_target = None; state.silence_monitor = None; hotkey.submitted(); self.voice_sessions.submit(session_id); // Reuse the semantic event; consumers re-read the capture and job snapshots. - self.events.publish(Some(session_id), BackendEventKind::DictationJobsChanged( - state.processing_snapshots())); + self.events.publish( + Some(session_id), + BackendEventKind::DictationJobsChanged(state.processing_snapshots()), + ); self.phase_changed.notify_waiters(); } // Queue final ASR/polish/insertion work, including unsafe local models. @@ -9089,8 +9368,12 @@ impl OpenLessBackend { // Prepare the captured destination only after the predecessor has fully // delivered. This enables stable polish streaming/TSF composition without // acquiring native input resources during an overlapping recording. - let preparation = self.text_insertions.lock() - .expect("text insertion registry lock poisoned").get(&session_id).cloned(); + let preparation = self + .text_insertions + .lock() + .expect("text insertion registry lock poisoned") + .get(&session_id) + .cloned(); if let Some(preparation) = preparation { // Final insertion reports preparation errors after retaining the transcript. let _ = preparation.await; @@ -9251,7 +9534,10 @@ impl OpenLessBackend { let state = self.state.read().expect("backend state lock poisoned"); state.session(session_id).is_none() || !matches!( - state.session(session_id).map(|snapshot| snapshot.phase).unwrap_or(DictationPhase::Idle), + state + .session(session_id) + .map(|snapshot| snapshot.phase) + .unwrap_or(DictationPhase::Idle), DictationPhase::Transcribing | DictationPhase::Polishing ) }; @@ -9303,7 +9589,9 @@ impl OpenLessBackend { "insertOutcomeUnknown" } else if error.is_target_unavailable() { "insertTargetChanged" - } else { "insertFailed" }, + } else { + "insertFailed" + }, engine_result.raw_text.clone(), engine_result.polished_text.clone(), engine_result.polish_source.clone(), @@ -9348,7 +9636,10 @@ impl OpenLessBackend { let session_replaced = { let mut state = self.state.write().expect("backend state lock poisoned"); let replaced = state.session(session_id).is_none() - || state.session(session_id).map(|snapshot| snapshot.phase).unwrap_or(DictationPhase::Idle) + || state + .session(session_id) + .map(|snapshot| snapshot.phase) + .unwrap_or(DictationPhase::Idle) != if context.insertion.enabled { DictationPhase::Inserting } else { @@ -9356,10 +9647,8 @@ impl OpenLessBackend { }; if !replaced { state.session_mut(session_id).unwrap().phase = DictationPhase::Completed; - self.main_dictation_trace.record( - session_id, - format_args!("stage=terminal phase=completed"), - ); + self.main_dictation_trace + .record(session_id, format_args!("stage=terminal phase=completed")); state.session_mut(session_id).unwrap().message = Some(match insert_outcome { Some(InsertOutcome::Inserted) => "inserted".to_string(), Some(InsertOutcome::PasteSent) => "paste_sent".to_string(), @@ -9381,7 +9670,9 @@ impl OpenLessBackend { ); self.events.publish( Some(session_id), - BackendEventKind::DictationStateChanged(state.session(session_id).unwrap().clone()), + BackendEventKind::DictationStateChanged( + state.session(session_id).unwrap().clone(), + ), ); self.phase_changed.notify_waiters(); } @@ -9423,8 +9714,10 @@ impl OpenLessBackend { } fn persist_recording_started(&self, context: &DictationContext, session_id: SessionId) { - if matches!(context.output_target, DictationOutputTarget::CloudNote | DictationOutputTarget::AskComposer) - || self.is_cloud_note(session_id) + if matches!( + context.output_target, + DictationOutputTarget::CloudNote | DictationOutputTarget::AskComposer + ) || self.is_cloud_note(session_id) { return; } @@ -9580,7 +9873,10 @@ impl OpenLessBackend { polish_ms: attribution.polish_ms, }; let activity_app = session.app_name.clone(); - if matches!(insert_outcome, Some(InsertOutcome::Inserted | InsertOutcome::PasteSent)) { + if matches!( + insert_outcome, + Some(InsertOutcome::Inserted | InsertOutcome::PasteSent) + ) { if let Some(app) = &context.input_app { if let Err(error) = self.app_styles.observe(app) { log::warn!("failed to persist input application: {error}"); @@ -9595,7 +9891,10 @@ impl OpenLessBackend { log::warn!("failed to persist completed dictation history: {error}"); } self.trace_main_dictation_history(result.session_id, "completed"); - if let Err(error) = self.activity.bump_app(&self.clock.today_local().format("%Y-%m-%d").to_string(), activity_app.as_deref()) { + if let Err(error) = self.activity.bump_app( + &self.clock.today_local().format("%Y-%m-%d").to_string(), + activity_app.as_deref(), + ) { log::warn!("failed to persist application activity: {error}"); } if let Err(error) = self.record_activity( @@ -9624,8 +9923,10 @@ impl OpenLessBackend { asr_call_label: Option, llm_call_label: Option, ) { - if matches!(context.output_target, DictationOutputTarget::CloudNote | DictationOutputTarget::AskComposer) - || self.is_cloud_note(session_id) + if matches!( + context.output_target, + DictationOutputTarget::CloudNote | DictationOutputTarget::AskComposer + ) || self.is_cloud_note(session_id) { return; } @@ -9690,7 +9991,10 @@ impl OpenLessBackend { .dictation .session_id .is_some_and(|current| current != session_id) - || state.processing_dictations.keys().any(|id| *id != session_id) + || state + .processing_dictations + .keys() + .any(|id| *id != session_id) { return Ok(()); } @@ -9716,12 +10020,16 @@ impl OpenLessBackend { if state.processing_dictations.remove(&session_id).is_some() { state.transcripts.remove(&session_id); self.voice_sessions.release(session_id); - self.events.publish(Some(session_id), BackendEventKind::DictationJobsChanged( - state.processing_snapshots())); + self.events.publish( + Some(session_id), + BackendEventKind::DictationJobsChanged(state.processing_snapshots()), + ); self.phase_changed.notify_waiters(); drop(state); drop(hotkey); - if let Err(error) = self.cleanup_cloud_note(session_id, false) { log::warn!("{error}"); } + if let Err(error) = self.cleanup_cloud_note(session_id, false) { + log::warn!("{error}"); + } return; } if state.dictation.session_id != Some(session_id) { @@ -9834,7 +10142,11 @@ impl OpenLessBackend { { insertions.remove(&session_id); } - return if error.code == BackendErrorCode::Cancelled { Ok(()) } else { Err(error) }; + return if error.code == BackendErrorCode::Cancelled { + Ok(()) + } else { + Err(error) + }; } }; let result = insertion.cancel().await; @@ -10004,9 +10316,14 @@ impl OpenLessBackend { let mut state = self.state.write().expect("backend state lock poisoned"); if let Some(task) = state.processing_dictations.get_mut(&id) { task.snapshot.phase = DictationPhase::Cancelled; - self.events.publish(Some(id), BackendEventKind::DictationStateChanged(task.snapshot.clone())); + self.events.publish( + Some(id), + BackendEventKind::DictationStateChanged(task.snapshot.clone()), + ); Some(task.context.output_target == DictationOutputTarget::QuickNote) - } else { None } + } else { + None + } }; if let Some(preserve_quick_note) = submitted { let result = self.cancel_session_adapters(id).await; @@ -10015,12 +10332,16 @@ impl OpenLessBackend { self.cleanup_voice_activation_after_dictation(id).await; if preserve_quick_note { if let Ok(entries) = self.list_history() { - if let Some(mut entry) = entries.into_iter().find(|entry| entry.id == id.to_string()) { + if let Some(mut entry) = + entries.into_iter().find(|entry| entry.id == id.to_string()) + { entry.error_code = Some("cancelled".into()); let _ = self.update_history_entry(entry); } } - } else { let _ = self.delete_history(&id.to_string()); } + } else { + let _ = self.delete_history(&id.to_string()); + } return result; } } @@ -10044,10 +10365,8 @@ impl OpenLessBackend { .as_ref() .is_some_and(|context| context.output_target == DictationOutputTarget::QuickNote); state.dictation.phase = DictationPhase::Cancelled; - self.main_dictation_trace.record( - active, - format_args!("stage=terminal phase=cancelled"), - ); + self.main_dictation_trace + .record(active, format_args!("stage=terminal phase=cancelled")); self.events.publish( Some(active), BackendEventKind::DictationStateChanged(state.dictation.clone()), @@ -10143,7 +10462,11 @@ impl OpenLessBackend { ( Vec::new(), crate::app_style_routing::input_scene_prefix( - None, None, None, None, input_location.as_deref(), + None, + None, + None, + None, + input_location.as_deref(), ), ) }); @@ -10198,7 +10521,10 @@ impl OpenLessBackend { .flatten(); let providers = match warmed { Some(providers) => providers, - None => self.resolve_dictation_providers(&preferences, purpose, pipeline_mode).await?, + None => { + self.resolve_dictation_providers(&preferences, purpose, pipeline_mode) + .await? + } }; let deferred_llm_error = providers.llm_error; let recent_history = if options.output_target == DictationOutputTarget::AskComposer @@ -10222,11 +10548,7 @@ impl OpenLessBackend { let mut context = DictationContext::capture( &preferences, &style_pack, - DictationProviderInvocations::new( - providers.asr, - providers.llm, - providers.omni, - ), + DictationProviderInvocations::new(providers.asr, providers.llm, providers.omni), hotwords, recent_history, options, @@ -10238,7 +10560,6 @@ impl OpenLessBackend { context.pipeline_mode = pipeline_mode; if purpose == DictationContextPurpose::Dictation && options.output_target != DictationOutputTarget::AskComposer - && !context.polish.translation_active && preferences.expression_learning_enabled { if let Ok(_guard) = self.settings_write_gate.try_lock() { @@ -10316,14 +10637,17 @@ impl OpenLessBackend { ) } - fn warmed_dictation_providers(&self, revision: (u64, u64)) -> Option { + fn warmed_dictation_providers( + &self, + revision: (u64, u64), + ) -> Option { let warm = self.dictation_provider_warmth.lock().unwrap(); let warm = warm.as_ref()?; (warm.revision == revision && self.dictation_provider_revision() == revision && warm.until > std::time::Instant::now()) - .then(|| warm.providers.clone()) - .flatten() + .then(|| warm.providers.clone()) + .flatten() } pub async fn warm_dictation_provider(self: &Arc) { @@ -10331,9 +10655,10 @@ impl OpenLessBackend { let until = std::time::Instant::now() + DICTATION_PROVIDER_WARMTH; let token = { let mut warm = self.dictation_provider_warmth.lock().unwrap(); - if let Some(existing) = warm.as_mut().filter(|warm| { - warm.revision == revision && warm.until > std::time::Instant::now() - }) { + if let Some(existing) = warm + .as_mut() + .filter(|warm| warm.revision == revision && warm.until > std::time::Instant::now()) + { existing.until = until; self.expire_dictation_warmth(until); return; @@ -10355,27 +10680,44 @@ impl OpenLessBackend { ); let result = tokio::time::timeout( DICTATION_PROVIDER_WARMTH, - self.resolve_dictation_providers(&preferences, DictationContextPurpose::Dictation, mode), + self.resolve_dictation_providers( + &preferences, + DictationContextPurpose::Dictation, + mode, + ), ) .await; let mut slot = self.dictation_provider_warmth.lock().unwrap(); - if slot.as_ref().is_some_and(|warm| Arc::ptr_eq(&warm.token, &token)) { + if slot + .as_ref() + .is_some_and(|warm| Arc::ptr_eq(&warm.token, &token)) + { match (result, self.dictation_provider_revision() == revision) { (Ok(Ok(providers)), true) => slot.as_mut().unwrap().providers = Some(providers), - _ => { slot.take(); } + _ => { + slot.take(); + } } } } pub fn retain_dictation_warmth(self: &Arc) { - let Some(until) = self.dictation_provider_warmth.lock().unwrap().as_mut().and_then(|warm| { - let now = std::time::Instant::now(); - if warm.until <= now || warm.revision != self.dictation_provider_revision() { - return None; - } - warm.until = now + DICTATION_PROVIDER_WARMTH; - Some(warm.until) - }) else { return }; + let Some(until) = self + .dictation_provider_warmth + .lock() + .unwrap() + .as_mut() + .and_then(|warm| { + let now = std::time::Instant::now(); + if warm.until <= now || warm.revision != self.dictation_provider_revision() { + return None; + } + warm.until = now + DICTATION_PROVIDER_WARMTH; + Some(warm.until) + }) + else { + return; + }; self.expire_dictation_warmth(until); } @@ -10385,7 +10727,10 @@ impl OpenLessBackend { tokio::time::sleep_until(until.into()).await; if let Some(backend) = backend.upgrade() { let mut warm = backend.dictation_provider_warmth.lock().unwrap(); - if warm.as_ref().is_some_and(|warm| warm.until <= std::time::Instant::now()) { + if warm + .as_ref() + .is_some_and(|warm| warm.until <= std::time::Instant::now()) + { warm.take(); } } @@ -10409,7 +10754,10 @@ impl OpenLessBackend { let llm = if mode == PipelineMode::Deepseek { crate::deepseek_suite::invocation(false) } else if traditional && purpose != DictationContextPurpose::AuxiliaryVoice { - match self.resolve_session_provider(ProviderSlot::Llm, &preferences.active_llm_provider).await { + match self + .resolve_session_provider(ProviderSlot::Llm, &preferences.active_llm_provider) + .await + { Ok(provider) => provider, Err(error) => { llm_error = Some(error); @@ -10422,9 +10770,15 @@ impl OpenLessBackend { let omni = if traditional { ProviderInvocation::for_provider(&preferences.active_omni_provider) } else { - self.resolve_session_provider(ProviderSlot::Omni, &preferences.active_omni_provider).await? + self.resolve_session_provider(ProviderSlot::Omni, &preferences.active_omni_provider) + .await? }; - Ok(ResolvedDictationProviders { asr, llm, omni, llm_error }) + Ok(ResolvedDictationProviders { + asr, + llm, + omni, + llm_error, + }) } async fn resolve_session_provider( @@ -10449,13 +10803,20 @@ impl OpenLessBackend { error.message ); let mut state = self.state.write().expect("backend state lock poisoned"); - let Some(snapshot) = state.session_mut(session_id) else { return; }; + let Some(snapshot) = state.session_mut(session_id) else { + return; + }; snapshot.phase = DictationPhase::Failed; - snapshot.message = Some(if error.message == "transcription provider returned an empty transcript" { - "empty_transcript".to_string() - } else if error.code == BackendErrorCode::InvalidState && error.is_target_unavailable() { - "input_target_changed".to_string() - } else { format!("{:?}", error.code) }); + snapshot.message = Some( + if error.message == "transcription provider returned an empty transcript" { + "empty_transcript".to_string() + } else if error.code == BackendErrorCode::InvalidState && error.is_target_unavailable() + { + "input_target_changed".to_string() + } else { + format!("{:?}", error.code) + }, + ); self.main_dictation_trace.record( session_id, format_args!("stage=terminal phase=failed code={:?}", error.code), @@ -10482,16 +10843,27 @@ fn ensure_running(state: &MutableState) -> Result<(), BackendError> { fn ensure_capture_session(state: &MutableState, session_id: SessionId) -> Result<(), BackendError> { ensure_active_session(state, session_id)?; - if state.dictation.session_id == Some(session_id) { Ok(()) } else { - Err(BackendError::new(BackendErrorCode::Cancelled, "recording progress belongs to a submitted segment")) + if state.dictation.session_id == Some(session_id) { + Ok(()) + } else { + Err(BackendError::new( + BackendErrorCode::Cancelled, + "recording progress belongs to a submitted segment", + )) } } fn ensure_active_session(state: &MutableState, session_id: SessionId) -> Result<(), BackendError> { ensure_running(state)?; - if state.session(session_id).is_some_and(|snapshot| !matches!(snapshot.phase, - DictationPhase::Idle | DictationPhase::Completed | DictationPhase::Cancelled | DictationPhase::Failed)) - { + if state.session(session_id).is_some_and(|snapshot| { + !matches!( + snapshot.phase, + DictationPhase::Idle + | DictationPhase::Completed + | DictationPhase::Cancelled + | DictationPhase::Failed + ) + }) { Ok(()) } else { Err(BackendError::new( @@ -10699,7 +11071,9 @@ mod tests { fn expression_observation_obeys_generation_and_never_persists_text() { let directory = TestDataDir::new("expression-observation"); let path = directory.path().join("profile.json"); - let profile = Arc::new(crate::expression_observation::ExpressionProfileStore::open(path.clone()).unwrap()); + let profile = Arc::new( + crate::expression_observation::ExpressionProfileStore::open(path.clone()).unwrap(), + ); let generation = Arc::new(AtomicU64::new(4)); let gate = Arc::new(Mutex::new(())); let sink = CombinedEditObservationSink { @@ -10736,24 +11110,49 @@ mod tests { #[tokio::test] async fn expression_prompt_requires_consent_and_clear_removes_stable_directions() { let (backend, _) = backend(); - assert!(Arc::ptr_eq(&backend.expression_profile, &backend.repositories().expression_profile)); - backend.set_credential( - crate::CredentialKey::new(crate::CredentialNamespace::Llm, Some("ark".into()), crate::credentials::LLM_API_KEY_ACCOUNT).unwrap(), - crate::SecretValue::new("fixture-key"), - ).await.unwrap(); - let profile = backend.expression_profile.lock().unwrap().as_ref().unwrap().clone(); + assert!(Arc::ptr_eq( + &backend.expression_profile, + &backend.repositories().expression_profile + )); + backend + .set_credential( + crate::CredentialKey::new( + crate::CredentialNamespace::Llm, + Some("ark".into()), + crate::credentials::LLM_API_KEY_ACCOUNT, + ) + .unwrap(), + crate::SecretValue::new("fixture-key"), + ) + .await + .unwrap(); + let profile = backend + .expression_profile + .lock() + .unwrap() + .as_ref() + .unwrap() + .clone(); let signal = crate::expression_observation::ExpressionSignal { line_breaks: 1, exclamations: 0, terminal_punctuation: 0, }; for index in 0..10 { - profile.record(uuid::Uuid::new_v4(), 100 + index % 4, signal).unwrap(); + profile + .record(uuid::Uuid::new_v4(), 100 + index % 4, signal) + .unwrap(); } assert_eq!(profile.stable_directions().unwrap().len(), 1); let options = DictationStartOptions::default(); - let capture = || backend.capture_dictation_context(&options, DictationContextPurpose::Dictation); - assert!(!capture().await.unwrap().polish.style_system_prompt.contains("用户经多次编辑")); + let capture = + || backend.capture_dictation_context(&options, DictationContextPurpose::Dictation); + assert!(!capture() + .await + .unwrap() + .polish + .style_system_prompt + .contains("用户经多次编辑")); let mut prefs = backend.get_preferences(); prefs.expression_learning_enabled = true; prefs.translation_target_language = "English".into(); @@ -10761,11 +11160,25 @@ mod tests { backend.set_preferences(prefs).unwrap(); assert!(backend.get_preferences().expression_learning_enabled); let context = capture().await.unwrap(); - assert!(context.polish.style_system_prompt.contains("用户经多次编辑"), "translation={} prompt={:?}", context.polish.translation_active, context.polish.style_system_prompt); + assert!( + context + .polish + .style_system_prompt + .contains("用户经多次编辑"), + "translation={} prompt={:?}", + context.polish.translation_active, + context.polish.style_system_prompt + ); let translated = context.with_translation_requested(true); - assert!(!translated.polish.style_system_prompt.contains("用户经多次编辑")); + assert!(!translated + .polish + .style_system_prompt + .contains("用户经多次编辑")); let normal = translated.with_translation_requested(false); - assert_eq!(normal.polish.style_system_prompt, context.polish.style_system_prompt); + assert_eq!( + normal.polish.style_system_prompt, + context.polish.style_system_prompt + ); let mut translated_options = options.clone(); translated_options.translation_requested = true; // Enable an effective target while keeping the original profile frozen. @@ -10773,13 +11186,28 @@ mod tests { prefs.translation_target_language = "English".into(); prefs.working_languages = vec!["简体中文".into()]; backend.set_preferences(prefs).unwrap(); - let translated_start = backend.capture_dictation_context(&translated_options, DictationContextPurpose::Dictation).await.unwrap(); + let translated_start = backend + .capture_dictation_context(&translated_options, DictationContextPurpose::Dictation) + .await + .unwrap(); assert!(translated_start.polish.translation_active); - assert!(!translated_start.polish.style_system_prompt.contains("用户经多次编辑")); + assert!(!translated_start + .polish + .style_system_prompt + .contains("用户经多次编辑")); backend.clear_expression_profile().unwrap(); - assert!(translated_start.with_translation_requested(false).polish.style_system_prompt.contains("用户经多次编辑")); + assert!(translated_start + .with_translation_requested(false) + .polish + .style_system_prompt + .contains("用户经多次编辑")); assert!(backend.expression_profile_directions().unwrap().is_empty()); - assert!(!capture().await.unwrap().polish.style_system_prompt.contains("用户经多次编辑")); + assert!(!capture() + .await + .unwrap() + .polish + .style_system_prompt + .contains("用户经多次编辑")); } #[tokio::test] @@ -10796,15 +11224,23 @@ mod tests { locked_tx.send(()).unwrap(); let _ = release_rx.recv(); }); - locked_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + locked_rx + .recv_timeout(std::time::Duration::from_secs(2)) + .unwrap(); let options = DictationStartOptions::default(); let context = tokio::time::timeout( std::time::Duration::from_secs(2), backend.capture_dictation_context(&options, DictationContextPurpose::Dictation), - ).await.expect("busy settings must not block capture").unwrap(); + ) + .await + .expect("busy settings must not block capture") + .unwrap(); release_tx.send(()).unwrap(); holder.join().unwrap(); - assert!(!context.polish.style_system_prompt.contains("用户经多次编辑")); + assert!(!context + .polish + .style_system_prompt + .contains("用户经多次编辑")); } #[test] @@ -10814,9 +11250,13 @@ mod tests { std::fs::create_dir_all(directory.path()).unwrap(); std::fs::write(&path, b"unknown profile").unwrap(); let backend = OpenLessBackend::new( - BackendConfig { data_dir: directory.path().to_path_buf(), ..BackendConfig::default() }, + BackendConfig { + data_dir: directory.path().to_path_buf(), + ..BackendConfig::default() + }, BackendDependencies::unsupported(), - ).unwrap(); + ) + .unwrap(); assert!(backend.expression_profile_directions().is_err()); assert_eq!(std::fs::read(&path).unwrap(), b"unknown profile"); backend.clear_expression_profile().unwrap(); @@ -10830,9 +11270,17 @@ mod tests { prefs.expression_learning_enabled = true; prefs.vocabulary_learning_enabled = true; backend.set_preferences(prefs.clone()).unwrap(); - backend.queue_pending_correction("原词".into(), "新词".into()).unwrap(); + backend + .queue_pending_correction("原词".into(), "新词".into()) + .unwrap(); prefs.expression_learning_enabled = false; - backend.update_settings(prefs, crate::SettingsUpdateOptions::STRICT, &crate::NoopSettingsRuntime).unwrap(); + backend + .update_settings( + prefs, + crate::SettingsUpdateOptions::STRICT, + &crate::NoopSettingsRuntime, + ) + .unwrap(); assert_eq!(backend.pending_corrections().len(), 1); } @@ -12120,13 +12568,16 @@ mod tests { session.feed_pcm(&[1]).unwrap_err().code, BackendErrorCode::InvalidArgument ); - session.feed_pcm(&[1, 0, 2, 0]).unwrap(); + session.feed_pcm(&[1u8, 0, 2, 0].repeat(800)).unwrap(); let LessComputerVoiceFinish::Submitted(result) = session.finish().await.unwrap() else { panic!("hotkey-mode capture must submit an Agent turn"); }; assert_eq!(result.session_id, session_id); - assert_eq!(*transcription.pcm.lock().unwrap(), vec![1, 0, 2, 0]); + assert_eq!( + *transcription.pcm.lock().unwrap(), + [1u8, 0, 2, 0].repeat(800) + ); assert_eq!(transcription.starts.load(Ordering::Acquire), 1); assert!(runtime.request.lock().unwrap().is_some()); let transcript_events = std::iter::from_fn(|| events.try_recv().ok()) @@ -12324,7 +12775,7 @@ mod tests { offset: 0, }) .unwrap(); - session.feed_pcm(&[1, 0]).unwrap(); + session.feed_pcm(&[1u8, 0, 2, 0].repeat(800)).unwrap(); assert_eq!( session.finish().await.unwrap(), @@ -12394,7 +12845,7 @@ mod tests { .await .unwrap(); // Valid quiet PCM reaches ASR; an empty transcript is distinct from a missing microphone input. - silent.feed_pcm(&[1, 0]).unwrap(); + silent.feed_pcm(&[1u8, 0, 2, 0].repeat(800)).unwrap(); assert_eq!( silent.finish().await.unwrap(), LessComputerVoiceFinish::Dictated { @@ -12522,7 +12973,7 @@ mod tests { async fn qa_voice_capture_owns_recorder_and_transcription_lifecycle() { let data_dir = TestDataDir::new("qa-voice-capture"); let recorder = Arc::new( - crate::testing::FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![]) + crate::testing::FixtureAudioRecorder::new(vec![[1u8, 0, 2, 0].repeat(800)], vec![]) .with_archived_recording(true), ); let transcription = Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -12567,7 +13018,7 @@ mod tests { assert!(result.audio_wav.is_none()); assert_eq!(result.duration_ms, 120); assert_eq!(recorder.stop_count(), 1); - assert_eq!(transcription.pcm(), vec![1, 0, 2, 0]); + assert_eq!(transcription.pcm(), [1u8, 0, 2, 0].repeat(800)); let mut preferences = backend.get_preferences(); preferences.multimodal_pipeline_enabled = true; @@ -12596,7 +13047,7 @@ mod tests { async fn selection_voice_capture_respects_pipeline_mode() { let data_dir = TestDataDir::new("selection-voice-pipeline-mode"); let recorder = Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![], )); let transcription = Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -12614,11 +13065,18 @@ mod tests { ..BackendConfig::default() }, BackendDependencies { - selection_polisher: Some(Arc::new(crate::testing::FixtureTextPolisher::successful("unused"))), - selection_runtime: Some(Arc::new(crate::testing::FixtureSelectionRuntime::successful( - crate::SelectionCapture { text: "fixture".into(), source_app: None }, - InsertOutcome::Inserted, - ))), + selection_polisher: Some(Arc::new( + crate::testing::FixtureTextPolisher::successful("unused"), + )), + selection_runtime: Some(Arc::new( + crate::testing::FixtureSelectionRuntime::successful( + crate::SelectionCapture { + text: "fixture".into(), + source_app: None, + }, + InsertOutcome::Inserted, + ), + )), voice_activation_runtime: None, dictation_engine: Arc::new(engine), ..BackendDependencies::unsupported() @@ -12646,7 +13104,7 @@ mod tests { .await .unwrap(); assert_eq!(traditional.finish().await.unwrap(), "edit this"); - assert_eq!(transcription.pcm(), vec![1, 0, 2, 0]); + assert_eq!(transcription.pcm(), [1u8, 0, 2, 0].repeat(800)); backend .services() .selection_voice @@ -13082,7 +13540,7 @@ mod tests { // host Stop. The fixture timestamps make this deterministic without a // wall-clock sleep. let recorder = Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![(10, 0.1), (20, 0.1), (30, 0.1), (1_100, 0.0), (2_000, 0.0)], )); let engine = crate::PipelineDictationEngine::new( @@ -13099,11 +13557,18 @@ mod tests { ..BackendConfig::default() }, BackendDependencies { - selection_polisher: Some(Arc::new(crate::testing::FixtureTextPolisher::successful("unused"))), - selection_runtime: Some(Arc::new(crate::testing::FixtureSelectionRuntime::successful( - crate::SelectionCapture { text: "fixture".into(), source_app: None }, - InsertOutcome::Inserted, - ))), + selection_polisher: Some(Arc::new( + crate::testing::FixtureTextPolisher::successful("unused"), + )), + selection_runtime: Some(Arc::new( + crate::testing::FixtureSelectionRuntime::successful( + crate::SelectionCapture { + text: "fixture".into(), + source_app: None, + }, + InsertOutcome::Inserted, + ), + )), voice_activation_runtime: None, dictation_engine: Arc::new(engine), ..BackendDependencies::unsupported() @@ -13287,42 +13752,17 @@ mod tests { let start = backend.clock.now_utc() - chrono::Duration::days(1); let entries = [ - ( - "completed-local", - 0, - "sherpa-onnx-local", - None, - ), - ( - "recording-draft", - 1, - "volcengine", - Some("recording"), - ), - ( - "cancelled", - 2, - "sherpa-onnx-local", - Some("cancelled"), - ), - ( - "recording-failed", - 3, - "volcengine", - Some("recordingFailed"), - ), + ("completed-local", 0, "sherpa-onnx-local", None), + ("recording-draft", 1, "volcengine", Some("recording")), + ("cancelled", 2, "sherpa-onnx-local", Some("cancelled")), + ("recording-failed", 3, "volcengine", Some("recordingFailed")), ( "transcribe-failed", 4, "sherpa-onnx-local", Some("transcribeFailed"), ), - ( - "empty-transcript", - 5, - "volcengine", - Some("emptyTranscript"), - ), + ("empty-transcript", 5, "volcengine", Some("emptyTranscript")), ( "insert-failed-after-asr", 6, @@ -13429,7 +13869,10 @@ mod tests { .unwrap() .unwrap(); assert_eq!(first.observation_id, None); - assert!(serde_json::to_value(&first).unwrap().get("observationId").is_none()); + assert!(serde_json::to_value(&first) + .unwrap() + .get("observationId") + .is_none()); assert!(backend .queue_pending_correction("扣的爱思".into(), "Codex".into()) .unwrap() @@ -15000,16 +15443,22 @@ mod tests { services.edit_observation = observation.clone(); let text = "今天我们先完成这个工作然后再讨论"; let backend = OpenLessBackend::new( - BackendConfig { data_dir: data_dir.path().to_path_buf(), ..BackendConfig::default() }, + BackendConfig { + data_dir: data_dir.path().to_path_buf(), + ..BackendConfig::default() + }, BackendDependencies { host_actions: Arc::new(FakeHost::default()), text_inserter: Arc::new(FakeInserter), - dictation_engine: Arc::new(crate::testing::FixtureDictationEngine::successful(text, text)), + dictation_engine: Arc::new(crate::testing::FixtureDictationEngine::successful( + text, text, + )), credential_store: Arc::new(crate::credentials::InMemoryCredentialStore::default()), services, ..BackendDependencies::unsupported() }, - ).unwrap(); + ) + .unwrap(); let mut prefs = backend.get_preferences(); assert!(!prefs.expression_learning_enabled); prefs.expression_learning_enabled = true; @@ -15025,8 +15474,10 @@ mod tests { } assert_eq!(observation.typed_texts.lock().unwrap().as_slice(), [text]); let edit = crate::host_document::EditPair { - source: String::new(), target: "\n".into(), - before: "今天我们先完成这个工作".into(), after: "然后再讨论".into(), + source: String::new(), + target: "\n".into(), + before: "今天我们先完成这个工作".into(), + after: "然后再讨论".into(), }; observation.publish(0, edit.clone()); let path = data_dir.path().join("expression-profile.json"); @@ -15035,7 +15486,13 @@ mod tests { assert!(backend.pending_corrections().is_empty()); let mut prefs = backend.get_preferences(); prefs.expression_learning_enabled = false; - backend.update_settings(prefs, crate::SettingsUpdateOptions::STRICT, &crate::NoopSettingsRuntime).unwrap(); + backend + .update_settings( + prefs, + crate::SettingsUpdateOptions::STRICT, + &crate::NoopSettingsRuntime, + ) + .unwrap(); observation.publish(0, edit); assert_eq!(std::fs::read_to_string(&path).unwrap(), saved); backend.shutdown().await.unwrap(); @@ -15048,7 +15505,10 @@ mod tests { let mut services = crate::domains::BackendServices::unsupported(); services.edit_observation = observation.clone(); let backend = OpenLessBackend::new( - BackendConfig { data_dir: data_dir.path().to_path_buf(), ..BackendConfig::default() }, + BackendConfig { + data_dir: data_dir.path().to_path_buf(), + ..BackendConfig::default() + }, BackendDependencies { host_actions: Arc::new(FakeHost::default()), text_inserter: Arc::new(FakeInserter), @@ -15057,7 +15517,8 @@ mod tests { services, ..BackendDependencies::unsupported() }, - ).unwrap(); + ) + .unwrap(); let mut prefs = backend.get_preferences(); prefs.expression_learning_enabled = true; backend.set_preferences(prefs).unwrap(); @@ -15065,7 +15526,13 @@ mod tests { backend.start_dictation().await.unwrap(); let mut prefs = backend.get_preferences(); prefs.expression_learning_enabled = false; - backend.update_settings(prefs, crate::SettingsUpdateOptions::STRICT, &crate::NoopSettingsRuntime).unwrap(); + backend + .update_settings( + prefs, + crate::SettingsUpdateOptions::STRICT, + &crate::NoopSettingsRuntime, + ) + .unwrap(); backend.stop_dictation().await.unwrap(); assert!(observation.typed_texts.lock().unwrap().is_empty()); assert!(!data_dir.path().join("expression-profile.json").exists()); @@ -15164,7 +15631,10 @@ mod tests { ) -> BoxFuture<'static, Result<(), BackendError>> { FakeEngine.start(id, context, progress) } - fn stop_recording(&self, _: SessionId) -> BoxFuture<'static, Result> { + fn stop_recording( + &self, + _: SessionId, + ) -> BoxFuture<'static, Result> { boxed(async { Ok(true) }) } fn finish( @@ -15333,25 +15803,50 @@ mod tests { #[tokio::test] async fn question_prefix_handoff_cancels_dictation_and_discards_its_late_release() { let data_dir = TestDataDir::new("question-prefix-handoff"); - let engine = crate::testing::FixtureDictationEngine::successful("must not insert", "unused"); + let engine = + crate::testing::FixtureDictationEngine::successful("must not insert", "unused"); let qa = Arc::new(FakeQaControl::default()); let mut deps = BackendDependencies::unsupported(); deps.dictation_engine = Arc::new(engine.clone()); deps.host_actions = Arc::new(FakeHost::default()); - deps.text_inserter = Arc::new(crate::testing::FixtureTextInserter::with_outcome(InsertOutcome::Inserted)); + deps.text_inserter = Arc::new(crate::testing::FixtureTextInserter::with_outcome( + InsertOutcome::Inserted, + )); deps.credential_store = llm_configured_credentials(); deps.services.qa = qa.clone(); - let backend = OpenLessBackend::new(BackendConfig {data_dir:data_dir.path().to_path_buf(), ..Default::default()}, deps).unwrap(); + let backend = OpenLessBackend::new( + BackendConfig { + data_dir: data_dir.path().to_path_buf(), + ..Default::default() + }, + deps, + ) + .unwrap(); backend.start().await.unwrap(); let mut prefs = backend.get_preferences(); prefs.hotkey.mode = crate::HotkeyMode::Hold; backend.set_preferences(prefs).unwrap(); let at = std::time::Instant::now(); - backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Pressed {press_id:7,at}).await.unwrap(); - assert_eq!(backend.snapshot().dictation.phase, DictationPhase::Recording); - backend.start_voice_question_from_recording_key().await.unwrap(); + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Pressed { press_id: 7, at }) + .await + .unwrap(); + assert_eq!( + backend.snapshot().dictation.phase, + DictationPhase::Recording + ); + backend + .start_voice_question_from_recording_key() + .await + .unwrap(); assert_eq!(qa.starts.load(Ordering::Acquire), 1); - backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released {press_id:7,at:std::time::Instant::now()}).await.unwrap(); + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { + press_id: 7, + at: std::time::Instant::now(), + }) + .await + .unwrap(); assert_eq!(backend.snapshot().dictation.phase, DictationPhase::Idle); assert!(backend.list_history().unwrap().is_empty()); backend.shutdown().await.unwrap(); @@ -15361,28 +15856,44 @@ mod tests { async fn translation_picker_updates_current_engine_and_remembers_only_the_language() { let data_dir = TestDataDir::new("translation-picker-current"); let engine = crate::testing::FixtureDictationEngine::successful("raw", "translated"); - let backend = backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine.clone())); + let backend = + backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine.clone())); backend.start().await.unwrap(); let mut prefs = backend.get_preferences(); prefs.translation_target_language = "English".into(); prefs.working_languages = vec!["简体中文".into()]; prefs.microphone_device_name = "captured microphone".into(); backend.set_preferences(prefs).unwrap(); - let session = backend.start_dictation_with_options(DictationStartOptions { - translation_requested: true, ..Default::default() - }).await.unwrap(); + let session = backend + .start_dictation_with_options(DictationStartOptions { + translation_requested: true, + ..Default::default() + }) + .await + .unwrap(); let mut changed = backend.get_preferences(); changed.microphone_device_name = "next microphone".into(); backend.set_preferences(changed).unwrap(); - let selected = backend.select_dictation_translation_target(session, "ja".into()).unwrap(); + let selected = backend + .select_dictation_translation_target(session, "ja".into()) + .unwrap(); assert_eq!(selected.target_language, "日本語"); - assert_eq!(backend.get_preferences().translation_target_language, "日本語"); - assert_eq!(backend.get_preferences().microphone_device_name, "next microphone"); + assert_eq!( + backend.get_preferences().translation_target_language, + "日本語" + ); + assert_eq!( + backend.get_preferences().microphone_device_name, + "next microphone" + ); backend.stop_dictation().await.unwrap(); let contexts = engine.contexts(); let last = contexts.last().unwrap(); assert_eq!(last.polish.translation_target_language, "日本語"); - assert_eq!(last.recording.microphone_device_name.as_deref(), Some("captured microphone")); + assert_eq!( + last.recording.microphone_device_name.as_deref(), + Some("captured microphone") + ); assert!(last.polish.translation_active); backend.shutdown().await.unwrap(); } @@ -15391,21 +15902,37 @@ mod tests { async fn translation_picker_save_failure_keeps_active_and_saved_targets() { let data_dir = TestDataDir::new("translation-picker-save-failure"); let engine = crate::testing::FixtureDictationEngine::successful("raw", "translated"); - let backend = backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine)); + let backend = + backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine)); backend.start().await.unwrap(); let mut prefs = backend.get_preferences(); prefs.translation_target_language = "English".into(); prefs.working_languages = vec!["简体中文".into()]; backend.set_preferences(prefs).unwrap(); - let session = backend.start_dictation_with_options(DictationStartOptions { - translation_requested: true, ..Default::default() - }).await.unwrap(); + let session = backend + .start_dictation_with_options(DictationStartOptions { + translation_requested: true, + ..Default::default() + }) + .await + .unwrap(); let file = backend.preferences.persistence_path().to_path_buf(); std::fs::remove_file(&file).unwrap(); std::fs::create_dir(&file).unwrap(); - assert!(backend.select_dictation_translation_target(session, "日本語".into()).is_err()); - assert_eq!(backend.dictation_translation_target().unwrap().target_language, "English"); - assert_eq!(backend.get_preferences().translation_target_language, "English"); + assert!(backend + .select_dictation_translation_target(session, "日本語".into()) + .is_err()); + assert_eq!( + backend + .dictation_translation_target() + .unwrap() + .target_language, + "English" + ); + assert_eq!( + backend.get_preferences().translation_target_language, + "English" + ); std::fs::remove_dir(&file).unwrap(); backend.cancel_dictation(Some(session)).await.unwrap(); backend.shutdown().await.unwrap(); @@ -15415,23 +15942,47 @@ mod tests { async fn translation_picker_rejects_stale_sessions_finalization_and_redundant_targets() { let data_dir = TestDataDir::new("translation-picker-stale"); let engine = crate::testing::FixtureDictationEngine::successful("raw", "translated"); - let backend = backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine)); + let backend = + backend_with_dictation_engine(data_dir.path().to_path_buf(), Arc::new(engine)); backend.start().await.unwrap(); let mut prefs = backend.get_preferences(); prefs.translation_target_language = "English".into(); prefs.working_languages = vec!["简体中文".into()]; backend.set_preferences(prefs).unwrap(); - let options = DictationStartOptions { translation_requested: true, ..Default::default() }; - let first = backend.start_dictation_with_options(options.clone()).await.unwrap(); + let options = DictationStartOptions { + translation_requested: true, + ..Default::default() + }; + let first = backend + .start_dictation_with_options(options.clone()) + .await + .unwrap(); backend.cancel_dictation(Some(first)).await.unwrap(); let second = backend.start_dictation_with_options(options).await.unwrap(); - assert!(backend.select_dictation_translation_target(first, "日本語".into()).is_err()); - assert!(backend.select_dictation_translation_target(second, "简体中文".into()).is_err()); - assert!(backend.select_dictation_translation_target(second, "unknown".into()).is_err()); - assert_eq!(backend.dictation_translation_target().unwrap().target_language, "English"); + assert!(backend + .select_dictation_translation_target(first, "日本語".into()) + .is_err()); + assert!(backend + .select_dictation_translation_target(second, "简体中文".into()) + .is_err()); + assert!(backend + .select_dictation_translation_target(second, "unknown".into()) + .is_err()); + assert_eq!( + backend + .dictation_translation_target() + .unwrap() + .target_language, + "English" + ); backend.stop_dictation().await.unwrap(); - assert!(backend.select_dictation_translation_target(second, "日本語".into()).is_err()); - assert_eq!(backend.get_preferences().translation_target_language, "English"); + assert!(backend + .select_dictation_translation_target(second, "日本語".into()) + .is_err()); + assert_eq!( + backend.get_preferences().translation_target_language, + "English" + ); backend.shutdown().await.unwrap(); } @@ -15609,7 +16160,10 @@ mod tests { let data = TestDataDir::new("ask-composer-history-cap"); let backend = backend_with_dictation_engine( data.path().to_owned(), - Arc::new(FixtureDictationEngine::successful("spoken sentinel", "ordinary polish")), + Arc::new(FixtureDictationEngine::successful( + "spoken sentinel", + "ordinary polish", + )), ); let mut preferences = backend.get_preferences(); preferences.history_max_entries = Some(5); @@ -15624,18 +16178,33 @@ mod tests { backend.shutdown().await.unwrap(); for (engine, succeeds) in [ - (FixtureDictationEngine::successful("Ask-only speech", "Ask-only composer text"), true), - (FixtureDictationEngine::failing(BackendError::new(BackendErrorCode::Provider, "fixture failure")), false), + ( + FixtureDictationEngine::successful("Ask-only speech", "Ask-only composer text"), + true, + ), + ( + FixtureDictationEngine::failing(BackendError::new( + BackendErrorCode::Provider, + "fixture failure", + )), + false, + ), ] { let backend = backend_with_dictation_engine(data.path().to_owned(), Arc::new(engine)); backend.start().await.unwrap(); let id = SessionId::new(); - backend.start_dictation_for_ask_composer(id, || true).await.unwrap(); + backend + .start_dictation_for_ask_composer(id, || true) + .await + .unwrap(); assert_eq!(backend.list_history().unwrap(), original); assert_eq!(backend.stop_dictation_session(id).await.is_ok(), succeeds); assert_eq!(backend.list_history().unwrap(), original); let cancelled_id = SessionId::new(); - backend.start_dictation_for_ask_composer(cancelled_id, || true).await.unwrap(); + backend + .start_dictation_for_ask_composer(cancelled_id, || true) + .await + .unwrap(); backend.cancel_dictation(Some(cancelled_id)).await.unwrap(); assert_eq!(backend.list_history().unwrap(), original); backend.shutdown().await.unwrap(); @@ -15827,17 +16396,28 @@ mod tests { backend.set_preferences(prefs).unwrap(); let id = backend.start_dictation().await.unwrap(); for _ in 0..2 { - backend.toggle_dictation_translation_for_session(id).unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); assert!(!backend.snapshot().dictation.translation_active); } backend.stop_dictation().await.unwrap(); let next = backend.start_dictation().await.unwrap(); - assert!(backend.toggle_dictation_translation_for_session(id).is_err()); + assert!(backend + .toggle_dictation_translation_for_session(id) + .is_err()); assert!(!backend.snapshot().dictation.translation_active); backend.cancel_dictation(Some(next)).await.unwrap(); } - assert!(engine.contexts().iter().all(|context| !context.polish.translation_active)); - assert!(backend.list_history().unwrap().iter().all(|entry| !entry.translation_active)); + assert!(engine + .contexts() + .iter() + .all(|context| !context.polish.translation_active)); + assert!(backend + .list_history() + .unwrap() + .iter() + .all(|entry| !entry.translation_active)); backend.shutdown().await.unwrap(); } @@ -15896,8 +16476,12 @@ mod tests { entered.notified().await; if requested { let id = backend.snapshot().dictation.session_id.unwrap(); - backend.toggle_dictation_translation_for_session(id).unwrap(); - backend.toggle_dictation_translation_for_session(id).unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); let result = backend.toggle_dictation_translation_for_session(id); release.notify_one(); assert!( @@ -16079,7 +16663,10 @@ mod tests { let polisher = Arc::new(FixtureTextPolisher::successful("完整正文")); let inserter = Arc::new(FixtureTextInserter::with_outcome(InsertOutcome::Inserted)); let engine = crate::PipelineDictationEngine::new( - Arc::new(FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![])), + Arc::new(FixtureAudioRecorder::new( + vec![[1u8, 0, 2, 0].repeat(800)], + vec![], + )), Arc::new(FixtureTranscriptionEngine::successful( format!("开始语音录入 {body} 完成语音录入"), 1000, @@ -16321,12 +16908,12 @@ mod tests { BackendErrorCode::InvalidState ); backend - .feed_external_pcm(session_id, &[1, 0, 2, 0]) + .feed_external_pcm(session_id, &[1u8, 0, 2, 0].repeat(800)) .unwrap(); - assert_eq!(backend.snapshot().dictation.elapsed_ms, 0); + assert_eq!(backend.snapshot().dictation.elapsed_ms, 100); let result = backend.stop_dictation_session(session_id).await.unwrap(); assert_eq!(result.polished_text, "polished"); - assert_eq!(transcription.pcm(), vec![1, 0, 2, 0]); + assert_eq!(transcription.pcm(), [1u8, 0, 2, 0].repeat(800)); assert_eq!( backend .feed_external_pcm(session_id, &[3, 0]) @@ -16958,7 +17545,7 @@ mod tests { let polisher = Arc::new(crate::testing::FixtureTextPolisher::successful("10例")); let engine = crate::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![], )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -16990,7 +17577,7 @@ mod tests { )); let engine = crate::dictation_engine::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![(40, 0.25)], )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -17123,8 +17710,11 @@ mod tests { )); let engine = crate::dictation_engine::PipelineDictationEngine::new( Arc::new( - crate::testing::FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![(25, 0.5)]) - .with_archived_recording(true), + crate::testing::FixtureAudioRecorder::new( + vec![[1u8, 0, 2, 0].repeat(800)], + vec![(25, 0.5)], + ) + .with_archived_recording(true), ), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( "raw fallback", @@ -17197,8 +17787,11 @@ mod tests { )); let engine = crate::dictation_engine::PipelineDictationEngine::new( Arc::new( - crate::testing::FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![(25, 0.5)]) - .with_archived_recording(true), + crate::testing::FixtureAudioRecorder::new( + vec![[1u8, 0, 2, 0].repeat(800)], + vec![(25, 0.5)], + ) + .with_archived_recording(true), ), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( "raw fallback", @@ -17338,7 +17931,7 @@ mod tests { }); let engine = crate::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![(25, 0.5)], )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -17436,10 +18029,14 @@ mod tests { uuid::Uuid::new_v4().simple() )); let polisher = Arc::new(crate::testing::FixtureTextPolisher::failing( - BackendError::new(BackendErrorCode::InvalidArgument, "polish input must not be empty"))); + BackendError::new( + BackendErrorCode::InvalidArgument, + "polish input must not be empty", + ), + )); let engine = crate::dictation_engine::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], vec![(40, 0.25)], )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -17474,7 +18071,9 @@ mod tests { prefs.polish_skip_max_chars = 0; backend.set_preferences(prefs).unwrap(); backend.start().await.unwrap(); - backend.activate_style_pack(crate::style_packs::BUILTIN_STYLE_PACK_STRUCTURED_ID).unwrap(); + backend + .activate_style_pack(crate::style_packs::BUILTIN_STYLE_PACK_STRUCTURED_ID) + .unwrap(); let session_id = backend.start_dictation().await.unwrap(); let error = backend @@ -17516,7 +18115,10 @@ mod tests { InsertOutcome::Inserted, )), dictation_engine: Arc::new(crate::testing::FixtureDictationEngine::failing( - BackendError::new(BackendErrorCode::Provider, "fixture ASR timeout after release"), + BackendError::new( + BackendErrorCode::Provider, + "fixture ASR timeout after release", + ), )), task_spawner: Arc::new(TokioTaskSpawner), credential_store: Arc::new(crate::credentials::InMemoryCredentialStore::default()), @@ -17615,7 +18217,7 @@ mod tests { let data_dir = TestDataDir::new("raw-real-pipeline"); let polisher = crate::testing::FixtureTextPolisher::successful("must not run"); let recorder = Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], Vec::new(), )); let engine = Arc::new(crate::PipelineDictationEngine::new( @@ -17741,7 +18343,7 @@ mod tests { data_dir.path().to_path_buf(), Arc::new(crate::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], Vec::new(), )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -17796,7 +18398,7 @@ mod tests { data_dir.path().to_path_buf(), Arc::new(crate::PipelineDictationEngine::new( Arc::new(crate::testing::FixtureAudioRecorder::new( - vec![vec![1, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], Vec::new(), )), Arc::new(crate::testing::FixtureTranscriptionEngine::successful( @@ -17956,8 +18558,11 @@ mod tests { )); let engine = crate::dictation_engine::PipelineDictationEngine::new( Arc::new( - crate::testing::FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![(80, 0.5)]) - .with_archived_recording(true), + crate::testing::FixtureAudioRecorder::new( + vec![[1u8, 0, 2, 0].repeat(800)], + vec![(80, 0.5)], + ) + .with_archived_recording(true), ), Arc::new(crate::testing::FixtureTranscriptionEngine::failing( BackendError::new(BackendErrorCode::Provider, "fixture ASR failure"), @@ -20094,7 +20699,7 @@ mod tests { let entered = Arc::new(tokio::sync::Notify::new()); let release = Arc::new(tokio::sync::Notify::new()); let recorder = FixtureAudioRecorder::new( - vec![vec![1, 0, 2, 0]], + vec![[1u8, 0, 2, 0].repeat(800)], if publish_level { vec![(1, 0.1)] } else { @@ -20193,7 +20798,7 @@ mod tests { let result = result.unwrap(); assert_eq!(result.session_id, session_id); assert_eq!(result.polished_text, "captured prefix"); - assert_eq!(transcriber.pcm(), vec![1, 0, 2, 0]); + assert_eq!(transcriber.pcm(), [1u8, 0, 2, 0].repeat(800)); assert_eq!( backend.list_history().unwrap()[0].error_code.as_deref(), None, @@ -21071,7 +21676,10 @@ mod tests { file.join("unusable-placeholder"), ); assert_eq!(backend.startup_error().unwrap().code, error.code); - assert_eq!(backend.local_migration_store().err().unwrap().code, error.code); + assert_eq!( + backend.local_migration_store().err().unwrap().code, + error.code + ); assert_eq!(backend.start().await.unwrap_err().code, error.code); assert_eq!(backend.ensure_runtime_ready().unwrap_err().code, error.code); assert!(!original.exists()); @@ -21130,4 +21738,120 @@ mod tests { ); assert!(!data_dir.path().exists()); } + + #[tokio::test] + async fn captured_duration_ms_updates_session_elapsed_ms_for_long_recording_threshold() { + struct DualClockEngine { + entered: Arc, + release: Arc, + } + + impl DictationEngine for DualClockEngine { + fn start( + &self, + session_id: SessionId, + _context: Arc, + progress: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { + boxed(async move { + progress.publish(session_id, EngineProgress::CaptureReady)?; + progress.publish( + session_id, + EngineProgress::RecordingLevel { + elapsed_ms: 299_500, + level: 0.1, + }, + )?; + Ok(()) + }) + } + + fn finish( + &self, + session_id: SessionId, + progress: Arc, + ) -> BoxFuture<'static, Result> { + let entered = Arc::clone(&self.entered); + let release = Arc::clone(&self.release); + boxed(async move { + progress + .publish(session_id, EngineProgress::CapturedDurationMs(300_001)) + .map_err(EngineFailure::from)?; + progress + .publish( + session_id, + EngineProgress::TranscriptDelta(crate::types::TranscriptDelta { + text: "long recovered text".to_string(), + offset: 0, + is_final: true, + }), + ) + .map_err(EngineFailure::from)?; + progress + .publish(session_id, EngineProgress::Stage(EngineStage::Polishing)) + .map_err(EngineFailure::from)?; + entered.notify_one(); + release.notified().await; + Ok(EngineResult { + raw_text: "long recovered text".to_string(), + asr_transcript: None, + polished_text: "long polished text".to_string(), + polish_source: None, + duration_ms: 300_001, + polish_failed: false, + asr_ms: Some(50), + polish_ms: Some(25), + has_audio_recording: Some(true), + asr_call_label: None, + llm_call_label: None, + }) + }) + } + + fn cancel( + &self, + _session_id: SessionId, + ) -> BoxFuture<'static, Result<(), BackendError>> { + boxed(async { Ok(()) }) + } + } + + let data_dir = TestDataDir::new("captured-duration-ms-long-recording"); + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let engine = Arc::new(DualClockEngine { + entered: Arc::clone(&entered), + release: Arc::clone(&release), + }); + let backend = Arc::new(backend_with_dictation_engine( + data_dir.path().to_path_buf(), + engine, + )); + backend.start().await.unwrap(); + + let session_id = backend.start_dictation().await.unwrap(); + assert_eq!(backend.snapshot().dictation.elapsed_ms, 299_500); + + let stop = tokio::spawn({ + let backend = Arc::clone(&backend); + async move { backend.stop_dictation().await } + }); + entered.notified().await; + + let mid_history = backend.list_history().unwrap(); + assert_eq!(mid_history.len(), 1); + assert_eq!(mid_history[0].id, session_id.to_string()); + assert_eq!(mid_history[0].error_code.as_deref(), Some("recording")); + assert_eq!(mid_history[0].raw_transcript, "long recovered text"); + assert_eq!(mid_history[0].duration_ms, Some(300_001)); + + release.notify_one(); + let result = stop.await.unwrap().unwrap(); + assert_eq!(result.polished_text, "long polished text"); + + let final_history = backend.list_history().unwrap(); + assert_eq!(final_history.len(), 1); + assert_eq!(final_history[0].error_code, None); + assert_eq!(final_history[0].final_text, "long polished text"); + } } diff --git a/openless-all/app/crates/openless-core/src/ask_search.rs b/openless-all/app/crates/openless-core/src/ask_search.rs index 32413ad1a..69a4f6f02 100644 --- a/openless-all/app/crates/openless-core/src/ask_search.rs +++ b/openless-all/app/crates/openless-core/src/ask_search.rs @@ -570,10 +570,8 @@ fn relevant_title(title: &str, query: &str) -> bool { let title = title.to_lowercase(); let query = query.to_lowercase(); let about_tools = ["web search settings", "enable web search", "怎么开启搜索", "如何启用搜索", "如何开通搜索"]; - if about_tools.iter().any(|cue| title.contains(cue)) && !about_tools.iter().any(|cue| query.contains(cue)) { - return false; - } - true + !about_tools.iter().any(|cue| title.contains(cue)) + || about_tools.iter().any(|cue| query.contains(cue)) } fn budgeted_evidence(entries: Vec, budget: usize) -> String { diff --git a/openless-all/app/crates/openless-core/src/asr/bailian.rs b/openless-all/app/crates/openless-core/src/asr/bailian.rs index ec8b36294..c2140f7c9 100644 --- a/openless-all/app/crates/openless-core/src/asr/bailian.rs +++ b/openless-all/app/crates/openless-core/src/asr/bailian.rs @@ -13,17 +13,17 @@ use futures_util::{SinkExt, StreamExt}; use parking_lot::Mutex as ParkingMutex; use serde_json::{json, Value}; use tokio::net::{lookup_host, TcpStream}; -use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex, Notify}; +use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex, Notify}; use tokio_tungstenite::client_async_tls; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::http::header::HeaderValue; use tokio_tungstenite::tungstenite::Error as WsError; use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; use uuid::Uuid; use crate::config::{TaskSpawner, TokioTaskSpawner}; +use super::stream_send::{send_ws_message_with_timeout, PacedSendClock, SharedWriter, WsStream}; use super::{AudioConsumer, RawTranscript}; use crate::ports::{TextStreamChunk, TextStreamSink}; @@ -36,6 +36,7 @@ pub const TARGET_AUDIO_CHUNK_BYTES: usize = 3_200; const TARGET_AUDIO_CHUNK_BYTES_8K: usize = 1_600; const BYTES_PER_MS: u64 = 32; const FINAL_RESULT_TIMEOUT: Duration = Duration::from_secs(12); +const FRAME_SEND_TIMEOUT: Duration = Duration::from_secs(5); /// Cap on the WebSocket handshake (TCP + TLS + HTTP upgrade) itself. Without it /// `connect_async` waits forever, and `open_session` is awaited with `block_on` on /// the serial hotkey bridge thread — a hang means hotkeys are completely dead @@ -134,10 +135,6 @@ async fn connect_ws_prefer_ipv4( connect_ws_to_addrs(request, order_connect_addrs(addrs)).await } -type WsStream = WebSocketStream>; -type WsSink = futures_util::stream::SplitSink; -type SharedWriter = Arc>>; - #[derive(Clone, Debug)] pub struct BailianCredentials { pub api_key: String, @@ -175,7 +172,7 @@ pub fn endpoint_scheme_is_websocket(endpoint: &str) -> bool { lower.starts_with("wss://") || lower.starts_with("ws://") } -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum BailianASRError { #[error("credentials missing")] CredentialsMissing, @@ -192,7 +189,7 @@ pub enum BailianASRError { } enum SendItem { - Audio(Vec), + Audio { payload: Vec, input_bytes: u64 }, Finish(oneshot::Sender>), } @@ -203,11 +200,16 @@ struct SyncState { audio_scratch: Vec, downsample_remainder: Vec, bytes_received: u64, + bytes_sent_input: u64, task_started: bool, task_finished: bool, + finish_sent: bool, + ending: bool, + send_error: Option, start: Option, final_tx: Option>>, send_tx: Option>, + cancel_tx: Option>, /// sentence_id -> text; joined in sentence_id order to form the final text. A /// later result for the same sentence_id overwrites the previous one, eliminating /// the duplication caused by cumulative text. @@ -221,6 +223,7 @@ struct SyncState { pub struct BailianRealtimeASR { credentials: BailianCredentials, + frame_send_timeout: Duration, task_spawner: Arc, state: ParkingMutex, writer: SharedWriter, @@ -240,6 +243,7 @@ impl BailianRealtimeASR { ) -> Self { Self { credentials, + frame_send_timeout: FRAME_SEND_TIMEOUT, task_spawner, state: ParkingMutex::new(SyncState::default()), writer: Arc::new(AsyncMutex::new(None)), @@ -249,6 +253,29 @@ impl BailianRealtimeASR { } } + #[cfg(test)] + pub(crate) fn with_frame_send_timeout(mut self, timeout: Duration) -> Self { + self.frame_send_timeout = timeout; + self + } + + fn is_8k_model(&self) -> bool { + model_is_8k(&self.credentials.normalized_model()) + } + + pub fn audio_coverage(&self) -> (u64, u64) { + let st = self.state.lock(); + (st.bytes_sent_input, st.bytes_received) + } + + pub fn is_stream_complete(&self) -> bool { + let st = self.state.lock(); + let max_tail_discard = if self.is_8k_model() { 2 } else { 0 }; + st.send_error.is_none() + && st.finish_sent + && st.bytes_received.saturating_sub(st.bytes_sent_input) <= max_tail_discard + } + pub fn set_partial_sink(&self, sink: Arc) { *self.partial_sink.lock() = Some(sink); } @@ -283,6 +310,7 @@ impl BailianRealtimeASR { let (final_tx, final_rx) = oneshot::channel(); let (send_tx, mut send_rx) = mpsc::unbounded_channel::(); + let (cancel_tx, mut cancel_rx) = watch::channel(false); { let mut st = self.state.lock(); *st = SyncState::default(); @@ -290,32 +318,84 @@ impl BailianRealtimeASR { st.start = Some(Instant::now()); st.final_tx = Some(final_tx); st.send_tx = Some(send_tx); + st.cancel_tx = Some(cancel_tx); } *self.final_rx.lock() = Some(final_rx); let writer_for_worker = Arc::clone(&self.writer); + let weak_self_for_worker = Arc::downgrade(self); let task_id_for_worker = task_id.clone(); + let frame_send_timeout = self.frame_send_timeout; let task_spawner = Arc::clone(&self.task_spawner); task_spawner.spawn(Box::pin(async move { + let mut clock = PacedSendClock::new(); while let Some(item) = send_rx.recv().await { match item { - SendItem::Audio(chunk) => { - if let Err(e) = send_binary(&writer_for_worker, chunk).await { - log::error!("[bailian-asr] audio frame send failed: {e}"); + SendItem::Audio { + payload, + input_bytes, + } => { + let Some(scheduled_start) = clock.wait_slot(&mut cancel_rx).await else { + break; + }; + if let Err(ws_err) = send_ws_message_with_timeout( + &writer_for_worker, + Message::Binary(payload.into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + { + let err = BailianASRError::SendFailed( + ws_err.into_message("websocket writer not available"), + ); + log::error!("[bailian-asr] audio frame send failed: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err); + } + // Abort before finish-task can overtake incomplete audio. + break; + } + if let Some(this) = weak_self_for_worker.upgrade() { + let mut st = this.state.lock(); + st.bytes_sent_input = st.bytes_sent_input.saturating_add(input_bytes); } + clock.mark_sent(scheduled_start, input_bytes as usize, BYTES_PER_MS, 2); } SendItem::Finish(done) => { - let result = - send_text(&writer_for_worker, finish_task_message(&task_id_for_worker)) - .await - .map_err(|e| BailianASRError::SendFailed(e.to_string())); + let result = send_ws_message_with_timeout( + &writer_for_worker, + Message::Text(finish_task_message(&task_id_for_worker).into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + .map_err(|ws_err| { + BailianASRError::SendFailed( + ws_err.into_message("websocket writer not available"), + ) + }); + match &result { + Ok(()) => { + if let Some(this) = weak_self_for_worker.upgrade() { + this.state.lock().finish_sent = true; + } + } + Err(err) => { + log::error!("[bailian-asr] finish-task send failed: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err.clone()); + } + } + } let _ = done.send(result); + break; } } } })); - send_text( + if let Err(error) = send_text( &self.writer, run_task_message( &task_id, @@ -323,7 +403,11 @@ impl BailianRealtimeASR { self.credentials.vocabulary_id.as_deref(), ), ) - .await?; + .await + { + self.cancel(); + return Err(error); + } let weak_self = Arc::downgrade(self); let task_spawner = Arc::clone(&self.task_spawner); @@ -364,43 +448,66 @@ impl BailianRealtimeASR { started.as_mut().enable(); let ready = { let st = self.state.lock(); - st.task_started || st.task_finished + st.task_started || st.task_finished || st.send_error.is_some() }; if !ready { tokio::time::timeout(Duration::from_secs(5), started) .await .map_err(|_| BailianASRError::FinalResultTimeout)?; } - let (send_tx, tail_chunks) = { + let model = self.credentials.normalized_model(); + let input_scale = if model_is_8k(&model) { 2u64 } else { 1u64 }; + let (done_tx, done_rx) = oneshot::channel(); + { let mut st = self.state.lock(); - if model_is_8k(&self.credentials.normalized_model()) { + if let Some(ref error) = st.send_error { + return Err(error.clone()); + } + let Some(send_tx) = st.send_tx.take() else { + return Err(BailianASRError::SendFailed( + "websocket session is not open".to_string(), + )); + }; + st.ending = true; + if model_is_8k(&model) { clear_downsample_tail(&mut st.downsample_remainder); } - let send_tx = st.send_tx.clone(); if !st.pending_audio.is_empty() { let pending = std::mem::take(&mut st.pending_audio); st.audio_scratch.extend_from_slice(&pending); } - let tail = if st.audio_scratch.is_empty() { - Vec::new() - } else { - vec![std::mem::take(&mut st.audio_scratch)] - }; - (send_tx, tail) - }; - let Some(send_tx) = send_tx else { - return Ok(()); - }; - for chunk in tail_chunks { - let _ = send_tx.send(SendItem::Audio(chunk)); + let mut tail_chunks = drain_audio_chunks_for_model(&mut st.audio_scratch, &model); + if !st.audio_scratch.is_empty() { + tail_chunks.push(std::mem::take(&mut st.audio_scratch)); + } + for payload in tail_chunks { + let input_bytes = (payload.len() as u64).saturating_mul(input_scale); + if send_tx + .send(SendItem::Audio { + payload, + input_bytes, + }) + .is_err() + { + return Err(st.send_error.clone().unwrap_or_else(|| { + BailianASRError::SendFailed("send worker closed".to_string()) + })); + } + } + if send_tx.send(SendItem::Finish(done_tx)).is_err() { + return Err(st.send_error.clone().unwrap_or_else(|| { + BailianASRError::SendFailed("send worker closed".to_string()) + })); + } + } + match done_rx.await { + Ok(inner) => inner, + Err(_) => { + Err(self.state.lock().send_error.clone().unwrap_or_else(|| { + BailianASRError::SendFailed("finish ack dropped".to_string()) + })) + } } - let (done_tx, done_rx) = oneshot::channel(); - send_tx - .send(SendItem::Finish(done_tx)) - .map_err(|_| BailianASRError::SendFailed("send worker closed".to_string()))?; - done_rx - .await - .map_err(|_| BailianASRError::SendFailed("finish ack dropped".to_string()))? } pub async fn await_final_result(&self) -> Result { @@ -422,7 +529,11 @@ impl BailianRealtimeASR { st.send_tx.take(); st.final_tx.take(); st.task_finished = true; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } drop(st); + self.task_started.notify_waiters(); let writer = Arc::clone(&self.writer); self.task_spawner.spawn(Box::pin(async move { let _ = close_writer(&writer).await; @@ -470,6 +581,8 @@ impl BailianRealtimeASR { } fn mark_task_started(&self) { + let model = self.credentials.normalized_model(); + let input_scale = if model_is_8k(&model) { 2u64 } else { 1u64 }; let (send_tx, chunks) = { let mut st = self.state.lock(); st.task_started = true; @@ -478,15 +591,16 @@ impl BailianRealtimeASR { st.audio_scratch.extend_from_slice(&pending); } let send_tx = st.send_tx.clone(); - let chunks = drain_audio_chunks_for_model( - &mut st.audio_scratch, - &self.credentials.normalized_model(), - ); + let chunks = drain_audio_chunks_for_model(&mut st.audio_scratch, &model); (send_tx, chunks) }; if let Some(tx) = send_tx { - for chunk in chunks { - let _ = tx.send(SendItem::Audio(chunk)); + for payload in chunks { + let input_bytes = (payload.len() as u64).saturating_mul(input_scale); + let _ = tx.send(SendItem::Audio { + payload, + input_bytes, + }); } } self.task_started.notify_waiters(); @@ -568,6 +682,9 @@ impl BailianRealtimeASR { } st.task_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } let text = if st.final_segments.is_empty() { st.last_result_text.clone() } else { @@ -586,34 +703,82 @@ impl BailianRealtimeASR { if let Some(tx) = tx { let _ = tx.send(Ok(RawTranscript { text, duration_ms })); } + self.task_started.notify_waiters(); self.close_on_runtime(); } fn finish_with_partial_or_error(&self, error: BailianASRError) { - let has_partial = { - let st = self.state.lock(); - !st.last_result_text.trim().is_empty() - || !st.final_segments.is_empty() - || !st.partial_segments.is_empty() + self.resolve_partial_or_error(error, false); + } + + fn record_send_failure(&self, error: BailianASRError) { + self.resolve_partial_or_error(error, true); + } + + fn resolve_partial_or_error(&self, error: BailianASRError, clear_scratch: bool) { + let (tx, outcome) = { + let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } + st.send_tx.take(); + if clear_scratch { + st.pending_audio.clear(); + st.audio_scratch.clear(); + } + if st.task_finished { + (None, None) + } else { + st.task_finished = true; + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } + let has_partial = !st.last_result_text.trim().is_empty() + || !st.final_segments.is_empty() + || !st.partial_segments.is_empty(); + let tx = st.final_tx.take(); + let outcome = if has_partial { + let text = if st.final_segments.is_empty() { + st.last_result_text.clone() + } else { + let segments: Vec = st.final_segments.values().cloned().collect(); + merge_segments(&segments) + }; + let duration_ms = if st.bytes_received > 0 { + st.bytes_received / BYTES_PER_MS + } else { + st.start + .map(|start| start.elapsed().as_millis() as u64) + .unwrap_or_default() + }; + Ok(RawTranscript { text, duration_ms }) + } else { + Err(error) + }; + (tx, Some(outcome)) + } }; - if has_partial { - // Consistent with Volcengine: when the connection breaks but a partial - // already exists, return it rather than the error, so recognized text is - // not lost. - self.finish_success(); - } else { - self.finish_error(error); + if let (Some(tx), Some(outcome)) = (tx, outcome) { + let _ = tx.send(outcome); } + self.task_started.notify_waiters(); + self.close_on_runtime(); } fn finish_error(&self, error: BailianASRError) { let tx = { let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } if st.task_finished { return; } st.task_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } st.final_tx.take() }; if let Some(tx) = tx { @@ -637,9 +802,16 @@ impl AudioConsumer for BailianRealtimeASR { return; } let model = self.credentials.normalized_model(); + let input_scale = if model_is_8k(&model) { 2u64 } else { 1u64 }; let (send_tx, chunks) = { let mut st = self.state.lock(); + if st.ending { + return; + } st.bytes_received = st.bytes_received.saturating_add(pcm.len() as u64); + if st.task_finished || st.send_error.is_some() { + return; + } let audio = if model_is_8k(&model) { st.downsample_remainder.extend_from_slice(pcm); let complete_len = st.downsample_remainder.len() / 4 * 4; @@ -658,8 +830,17 @@ impl AudioConsumer for BailianRealtimeASR { (st.send_tx.clone(), chunks) }; if let Some(tx) = send_tx { - for chunk in chunks { - let _ = tx.send(SendItem::Audio(chunk)); + for payload in chunks { + let input_bytes = (payload.len() as u64).saturating_mul(input_scale); + if tx + .send(SendItem::Audio { + payload, + input_bytes, + }) + .is_err() + { + break; + } } } } @@ -793,18 +974,6 @@ async fn send_text(writer: &SharedWriter, text: String) -> Result<(), BailianASR .map_err(|e| BailianASRError::SendFailed(e.to_string())) } -async fn send_binary(writer: &SharedWriter, data: Vec) -> Result<(), BailianASRError> { - let mut guard = writer.lock().await; - let Some(ws) = guard.as_mut() else { - return Err(BailianASRError::ConnectionFailed( - "websocket writer not available".to_string(), - )); - }; - ws.send(Message::Binary(data.into())) - .await - .map_err(|e| BailianASRError::SendFailed(e.to_string())) -} - async fn close_writer(writer: &SharedWriter) -> Result<(), BailianASRError> { let mut guard = writer.lock().await; if let Some(mut ws) = guard.take() { @@ -1337,4 +1506,237 @@ mod tests { assert_eq!(chunks[1].len(), TARGET_AUDIO_CHUNK_BYTES); assert_eq!(buffer.len(), 17); } + + #[tokio::test] + async fn buffered_audio_paces_and_tracks_coverage_across_worker() { + let frames = Arc::new(ParkingMutex::new(Vec::<(Instant, Vec)>::new())); + let finish_seen = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let frames_srv = Arc::clone(&frames); + let finish_seen_srv = Arc::clone(&finish_seen); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!( + "ws://{}/api-ws/v1/inference/", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + while let Some(Ok(msg)) = ws.next().await { + match msg { + Message::Text(text) => { + let v: Value = serde_json::from_str(&text).unwrap(); + let task_id = v["header"]["task_id"].as_str().unwrap_or("").to_string(); + match v["header"]["action"].as_str().unwrap_or_default() { + "run-task" => { + ws.send(Message::text( + json!({ + "header": {"event": "task-started", "task_id": task_id}, + "payload": {} + }) + .to_string(), + )) + .await + .unwrap(); + } + "finish-task" => { + finish_seen_srv.store(true, std::sync::atomic::Ordering::Release); + ws.send(Message::text( + json!({ + "header": {"event": "result-generated", "task_id": task_id}, + "payload": { + "output": { + "sentence": { + "sentence_id": 0, + "text": "百炼完成。", + "sentence_end": true, + "end_time": 1000 + } + } + } + }) + .to_string(), + )) + .await + .unwrap(); + ws.send(Message::text( + json!({ + "header": {"event": "task-finished", "task_id": task_id}, + "payload": {} + }) + .to_string(), + )) + .await + .unwrap(); + let _ = ws.close(None).await; + break; + } + _ => {} + } + } + Message::Binary(data) => { + frames_srv.lock().push((Instant::now(), data.to_vec())); + } + Message::Close(_) => break, + _ => {} + } + } + }); + + let asr = Arc::new(BailianRealtimeASR::new(BailianCredentials { + api_key: "sk-test".into(), + endpoint, + model: "fun-asr-flash-8k-realtime".into(), + vocabulary_id: None, + })); + asr.open_session().await.unwrap(); + + // Feed 16 kHz PCM that downsamples cleanly + 2 lone tail bytes (<= 2 B allowance). + let input_len = TARGET_AUDIO_CHUNK_BYTES * 5 + 2; + asr.consume_pcm_chunk(&vec![0x22u8; input_len]); + asr.send_last_frame().await.unwrap(); + let res = asr.await_final_result().await.unwrap(); + assert_eq!(res.text, "百炼完成。"); + assert!(finish_seen.load(std::sync::atomic::Ordering::Acquire)); + assert!(asr.is_stream_complete()); + assert_eq!( + asr.audio_coverage(), + ((TARGET_AUDIO_CHUNK_BYTES * 5) as u64, input_len as u64) + ); + + { + let recorded = frames.lock(); + assert_eq!(recorded.len(), 5); + let span = recorded + .last() + .unwrap() + .0 + .saturating_duration_since(recorded[0].0); + assert!( + span >= Duration::from_millis(140), + "expected >= 2x pacing across 4 intervals (~200ms), got {span:?}" + ); + } + server.await.unwrap(); + } + + #[tokio::test] + async fn send_last_frame_fails_when_closed_or_write_times_out() { + let unopened = Arc::new(BailianRealtimeASR::new(BailianCredentials { + api_key: "sk-test".into(), + endpoint: String::new(), + model: DEFAULT_MODEL.into(), + vocabulary_id: None, + })); + unopened.mark_task_started(); + assert!(unopened.send_last_frame().await.is_err()); + assert!(!unopened.is_stream_complete()); + + let finish_seen = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let finish_seen_srv = Arc::clone(&finish_seen); + let frame0_seen = Arc::new(Notify::new()); + let frame0_seen_srv = Arc::clone(&frame0_seen); + let shutdown = Arc::new(Notify::new()); + let shutdown_srv = Arc::clone(&shutdown); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!( + "ws://{}/api-ws/v1/inference/", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Text(text))) => { + let v: Value = serde_json::from_str(&text).unwrap(); + let task_id = v["header"]["task_id"].as_str().unwrap_or("").to_string(); + match v["header"]["action"].as_str().unwrap_or_default() { + "run-task" => { + ws.send(Message::text( + json!({ + "header": {"event": "task-started", "task_id": task_id}, + "payload": {} + }) + .to_string(), + )) + .await + .unwrap(); + } + "finish-task" => { + finish_seen_srv.store(true, std::sync::atomic::Ordering::Release); + } + _ => {} + } + } + Some(Ok(Message::Binary(_))) => { + frame0_seen_srv.notify_waiters(); + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_srv.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }); + + let asr = Arc::new( + BailianRealtimeASR::new(BailianCredentials { + api_key: "sk-test".into(), + endpoint, + model: DEFAULT_MODEL.into(), + vocabulary_id: None, + }) + .with_frame_send_timeout(Duration::from_millis(60)), + ); + asr.open_session().await.unwrap(); + asr.consume_pcm_chunk(&vec![0x33u8; TARGET_AUDIO_CHUNK_BYTES]); + tokio::time::timeout(Duration::from_secs(2), frame0_seen.notified()) + .await + .unwrap(); + + let writer_guard = asr.writer.lock().await; + asr.consume_pcm_chunk(&vec![0x44u8; TARGET_AUDIO_CHUNK_BYTES]); + assert!(asr.send_last_frame().await.is_err()); + drop(writer_guard); + + assert!(!finish_seen.load(std::sync::atomic::Ordering::Acquire)); + assert!(!asr.is_stream_complete()); + assert_eq!( + asr.audio_coverage(), + ( + TARGET_AUDIO_CHUNK_BYTES as u64, + (TARGET_AUDIO_CHUNK_BYTES * 2) as u64 + ) + ); + shutdown.notify_waiters(); + server.await.unwrap(); + } + + #[tokio::test] + async fn record_send_failure_preserves_partial_across_concurrent_cancel() { + let asr = create_test_asr(); + let (tx, rx) = oneshot::channel(); + { + let mut st = asr.state.lock(); + st.task_started = true; + st.last_result_text = "百炼前缀".into(); + st.final_tx = Some(tx); + } + *asr.final_rx.lock() = Some(rx); + + asr.record_send_failure(BailianASRError::SendFailed("broken".into())); + asr.cancel(); + + let transcript = asr + .await_final_result() + .await + .expect("partial transcript must survive concurrent cancel"); + assert_eq!(transcript.text, "百炼前缀"); + assert!(!asr.is_stream_complete()); + } } diff --git a/openless-all/app/crates/openless-core/src/asr/mod.rs b/openless-all/app/crates/openless-core/src/asr/mod.rs index 1f77ec9a0..8a7c7bd2d 100644 --- a/openless-all/app/crates/openless-core/src/asr/mod.rs +++ b/openless-all/app/crates/openless-core/src/asr/mod.rs @@ -32,6 +32,129 @@ pub use xfyun::{XfyunCredentials, XfyunStreamingASR}; /// What a provider yielded after the stream or batch request completed. pub type RawTranscript = crate::ports::TranscriptOutput; +pub(super) mod stream_send { + use std::sync::Arc; + use std::time::Duration; + + use futures_util::SinkExt; + use tokio::net::TcpStream; + use tokio::sync::{watch, Mutex as AsyncMutex}; + use tokio_tungstenite::tungstenite::Message; + use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + + pub(in crate::asr) type WsStream = WebSocketStream>; + pub(in crate::asr) type WsSink = futures_util::stream::SplitSink; + pub(in crate::asr) type SharedWriter = Arc>>; + + pub(in crate::asr) enum WsSendError { + NotOpen, + Cancelled, + Timeout(u128), + Transport(String), + } + + impl WsSendError { + pub(in crate::asr) fn into_message(self, closed_msg: &str) -> String { + match self { + Self::NotOpen => closed_msg.to_string(), + Self::Cancelled => "session cancelled".to_string(), + Self::Timeout(ms) => format!("audio frame send timed out after {ms} ms"), + Self::Transport(msg) => msg, + } + } + } + + /// Tracks non-drifting per-frame send slots for streaming ASR workers. + pub(in crate::asr) struct PacedSendClock { + next_send_at: Option, + } + + impl PacedSendClock { + pub(in crate::asr) fn new() -> Self { + Self { next_send_at: None } + } + + /// Sleeps until the next scheduled slot unless `cancel_rx` fires first. + pub(in crate::asr) async fn wait_slot( + &self, + cancel_rx: &mut watch::Receiver, + ) -> Option { + if *cancel_rx.borrow_and_update() { + return None; + } + let now = tokio::time::Instant::now(); + let Some(deadline) = self.next_send_at else { + return Some(now); + }; + if deadline <= now { + return Some(now); + } + loop { + if *cancel_rx.borrow_and_update() { + return None; + } + tokio::select! { + _ = tokio::time::sleep_until(deadline) => { + return (!*cancel_rx.borrow_and_update()).then_some(deadline); + } + changed = cancel_rx.changed() => { + if changed.is_err() || *cancel_rx.borrow_and_update() { + return None; + } + } + } + } + } + + pub(in crate::asr) fn mark_sent( + &mut self, + scheduled_start: tokio::time::Instant, + byte_len: usize, + bytes_per_ms: u64, + rate_multiplier: u64, + ) { + let denom = bytes_per_ms.saturating_mul(rate_multiplier).max(1); + let micros = (byte_len as u64) + .saturating_mul(1_000) + .div_ceil(denom) + .max(1); + let interval = Duration::from_micros(micros); + self.next_send_at = Some((scheduled_start + interval).max(tokio::time::Instant::now())); + } + } + + pub(in crate::asr) async fn send_ws_message_with_timeout( + writer: &SharedWriter, + msg: Message, + timeout: Duration, + cancel_rx: &mut watch::Receiver, + ) -> Result<(), WsSendError> { + if *cancel_rx.borrow_and_update() { + return Err(WsSendError::Cancelled); + } + tokio::select! { + result = tokio::time::timeout(timeout, async { + let mut guard = writer.lock().await; + let Some(ws) = guard.as_mut() else { + return Err(WsSendError::NotOpen); + }; + ws.send(msg) + .await + .map_err(|e| WsSendError::Transport(e.to_string())) + }) => { + match result { + Ok(inner) => inner, + Err(_) => Err(WsSendError::Timeout(timeout.as_millis())), + } + } + changed = cancel_rx.changed() => { + let _ = changed; + Err(WsSendError::Cancelled) + } + } + } +} + /// User-defined hotword used to bias providers that expose that capability. #[derive(Debug, Clone)] pub struct DictionaryHotword { diff --git a/openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs b/openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs index 48faff141..6fa7818fa 100644 --- a/openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs +++ b/openless-all/app/crates/openless-core/src/asr/qwen_realtime.rs @@ -26,16 +26,16 @@ use base64::Engine; use futures_util::{SinkExt, StreamExt}; use parking_lot::Mutex as ParkingMutex; use serde_json::{json, Value}; -use tokio::net::TcpStream; -use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex, Notify}; +use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex, Notify}; +use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::http::header::HeaderValue; use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use uuid::Uuid; use crate::config::{TaskSpawner, TokioTaskSpawner}; +use super::stream_send::{send_ws_message_with_timeout, PacedSendClock, SharedWriter}; use super::{AudioConsumer, RawTranscript}; use crate::ports::{TextStreamChunk, TextStreamSink}; @@ -50,6 +50,7 @@ const BYTES_PER_MS: u64 = 32; const FINAL_RESULT_TIMEOUT: Duration = Duration::from_secs(12); const SESSION_READY_TIMEOUT: Duration = Duration::from_secs(5); const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +const FRAME_SEND_TIMEOUT: Duration = Duration::from_secs(5); /// Cap on the WebSocket handshake (TCP + TLS + HTTP upgrade) itself. Without it /// `connect_async` waits forever, and `open_session` is awaited with `block_on` on /// the serial hotkey bridge thread — a hang means hotkeys are completely dead @@ -60,10 +61,6 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// lowers the chance of cutting a sentence on a mid-speech breath. const VAD_SILENCE_DURATION_MS: u32 = 500; -type WsStream = WebSocketStream>; -type WsSink = futures_util::stream::SplitSink; -type SharedWriter = Arc>>; - #[derive(Clone, Debug)] pub struct Qwen3RealtimeCredentials { pub api_key: String, @@ -105,7 +102,7 @@ impl Qwen3RealtimeCredentials { } } -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum Qwen3ASRError { #[error("credentials missing")] CredentialsMissing, @@ -131,12 +128,17 @@ struct SyncState { pending_audio: Vec, audio_scratch: Vec, bytes_received: u64, + bytes_sent_input: u64, session_started: bool, session_finished: bool, + finish_sent: bool, + ending: bool, + send_error: Option, session_start_error: Option, start: Option, final_tx: Option>>, send_tx: Option>, + cancel_tx: Option>, /// Completed segments (completed.transcript) accumulated in arrival order after /// VAD segmentation. completed_segments: Vec, @@ -150,6 +152,7 @@ struct SyncState { pub struct Qwen3RealtimeASR { credentials: Qwen3RealtimeCredentials, + frame_send_timeout: Duration, task_spawner: Arc, state: ParkingMutex, writer: SharedWriter, @@ -170,6 +173,7 @@ impl Qwen3RealtimeASR { ) -> Self { Self { credentials, + frame_send_timeout: FRAME_SEND_TIMEOUT, task_spawner, state: ParkingMutex::new(SyncState::default()), writer: Arc::new(AsyncMutex::new(None)), @@ -180,6 +184,22 @@ impl Qwen3RealtimeASR { } } + #[cfg(test)] + pub(crate) fn with_frame_send_timeout(mut self, timeout: Duration) -> Self { + self.frame_send_timeout = timeout; + self + } + + pub fn audio_coverage(&self) -> (u64, u64) { + let st = self.state.lock(); + (st.bytes_sent_input, st.bytes_received) + } + + pub fn is_stream_complete(&self) -> bool { + let st = self.state.lock(); + st.send_error.is_none() && st.finish_sent && st.bytes_sent_input == st.bytes_received + } + pub fn set_partial_sink(&self, sink: Arc) { *self.partial_sink.lock() = Some(sink); } @@ -216,37 +236,82 @@ impl Qwen3RealtimeASR { let (final_tx, final_rx) = oneshot::channel(); let (send_tx, mut send_rx) = mpsc::unbounded_channel::(); + let (cancel_tx, mut cancel_rx) = watch::channel(false); { let mut st = self.state.lock(); *st = SyncState::default(); st.start = Some(Instant::now()); st.final_tx = Some(final_tx); st.send_tx = Some(send_tx); + st.cancel_tx = Some(cancel_tx); } *self.final_rx.lock() = Some(final_rx); let writer_for_worker = Arc::clone(&self.writer); let weak_self_for_worker = Arc::downgrade(self); + let frame_send_timeout = self.frame_send_timeout; let task_spawner = Arc::clone(&self.task_spawner); task_spawner.spawn(Box::pin(async move { + let mut clock = PacedSendClock::new(); while let Some(item) = send_rx.recv().await { match item { SendItem::Audio(chunk) => { - if let Err(e) = - send_text(&writer_for_worker, append_audio_message(&chunk)).await + let Some(scheduled_start) = clock.wait_slot(&mut cancel_rx).await else { + break; + }; + let chunk_len = chunk.len(); + if let Err(ws_err) = send_ws_message_with_timeout( + &writer_for_worker, + Message::Text(append_audio_message(&chunk).into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await { - log::error!("[qwen3-asr] audio frame send failed: {e}"); + let err = Qwen3ASRError::SendFailed( + ws_err.into_message("websocket writer not available"), + ); + log::error!("[qwen3-asr] audio frame send failed: {err}"); if let Some(this) = weak_self_for_worker.upgrade() { - this.finish_error(e); + this.record_send_failure(err); } break; } + if let Some(this) = weak_self_for_worker.upgrade() { + let mut st = this.state.lock(); + st.bytes_sent_input = + st.bytes_sent_input.saturating_add(chunk_len as u64); + } + clock.mark_sent(scheduled_start, chunk_len, BYTES_PER_MS, 2); } SendItem::Finish(done) => { - let result = send_text(&writer_for_worker, finish_session_message()) - .await - .map_err(|e| Qwen3ASRError::SendFailed(e.to_string())); + let result = send_ws_message_with_timeout( + &writer_for_worker, + Message::Text(finish_session_message().into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + .map_err(|ws_err| { + Qwen3ASRError::SendFailed( + ws_err.into_message("websocket writer not available"), + ) + }); + match &result { + Ok(()) => { + if let Some(this) = weak_self_for_worker.upgrade() { + this.state.lock().finish_sent = true; + } + } + Err(err) => { + log::error!("[qwen3-asr] finish frame send failed: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err.clone()); + } + } + } let _ = done.send(result); + break; } } } @@ -319,51 +384,70 @@ impl Qwen3RealtimeASR { } pub async fn send_last_frame(&self) -> Result<(), Qwen3ASRError> { - let result = tokio::time::timeout(FINAL_RESULT_TIMEOUT, async { - let finished = self.session_finished.notified(); - tokio::pin!(finished); - finished.as_mut().enable(); - let (send_tx, tail_chunks) = { - let mut st = self.state.lock(); - let send_tx = st.send_tx.clone(); - if !st.pending_audio.is_empty() { - let pending = std::mem::take(&mut st.pending_audio); - st.audio_scratch.extend_from_slice(&pending); - } - let tail = if st.audio_scratch.is_empty() { - Vec::new() - } else { - vec![std::mem::take(&mut st.audio_scratch)] - }; - (send_tx, tail) - }; - let Some(send_tx) = send_tx else { - return Ok(()); + let finished = self.session_finished.notified(); + tokio::pin!(finished); + finished.as_mut().enable(); + let (done_tx, done_rx) = oneshot::channel(); + { + let mut st = self.state.lock(); + if let Some(ref error) = st.send_error { + return Err(error.clone()); + } + let Some(send_tx) = st.send_tx.take() else { + return Err(Qwen3ASRError::SendFailed( + "websocket session is not open".to_string(), + )); }; + st.ending = true; + if !st.pending_audio.is_empty() { + let pending = std::mem::take(&mut st.pending_audio); + st.audio_scratch.extend_from_slice(&pending); + } + let mut tail_chunks = drain_audio_chunks(&mut st.audio_scratch); + if !st.audio_scratch.is_empty() { + tail_chunks.push(std::mem::take(&mut st.audio_scratch)); + } for chunk in tail_chunks { - send_tx - .send(SendItem::Audio(chunk)) - .map_err(|_| Qwen3ASRError::SendFailed("send worker closed".to_string()))?; + if send_tx.send(SendItem::Audio(chunk)).is_err() { + return Err(st.send_error.clone().unwrap_or_else(|| { + Qwen3ASRError::SendFailed("send worker closed".to_string()) + })); + } } - let (done_tx, done_rx) = oneshot::channel(); - send_tx - .send(SendItem::Finish(done_tx)) - .map_err(|_| Qwen3ASRError::SendFailed("send worker closed".to_string()))?; - done_rx - .await - .map_err(|_| Qwen3ASRError::SendFailed("finish ack dropped".to_string()))??; + if send_tx.send(SendItem::Finish(done_tx)).is_err() { + return Err(st.send_error.clone().unwrap_or_else(|| { + Qwen3ASRError::SendFailed("send worker closed".to_string()) + })); + } + } + let drain_result = + match done_rx.await { + Ok(inner) => inner, + Err(_) => Err(self.state.lock().send_error.clone().unwrap_or_else(|| { + Qwen3ASRError::SendFailed("finish ack dropped".to_string()) + })), + }; + if let Err(err) = drain_result { + self.cancel(); + return Err(err); + } + + // Wait for server finalization outside the upload pacing loop so large buffered + // uploads cannot consume FINAL_RESULT_TIMEOUT while draining frames. + let waited = tokio::time::timeout(FINAL_RESULT_TIMEOUT, async { if !self.state.lock().session_finished { finished.await; } - Ok(()) }) - .await - .map_err(|_| Qwen3ASRError::FinalResultTimeout) - .and_then(|result| result); - if result.is_err() { - self.cancel(); + .await; + if waited.is_err() { + self.finish_with_partial_or_error(Qwen3ASRError::FinalResultTimeout); + return Err(Qwen3ASRError::FinalResultTimeout); + } + if let Some(error) = self.state.lock().send_error.clone() { + return Err(error); } - result + Ok(()) } pub async fn await_final_result(&self) -> Result { @@ -384,7 +468,12 @@ impl Qwen3RealtimeASR { st.send_tx.take(); st.final_tx.take(); st.session_finished = true; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } drop(st); + self.session_started.notify_waiters(); + self.session_finished.notify_waiters(); let writer = Arc::clone(&self.writer); self.task_spawner.spawn(Box::pin(async move { let _ = close_writer(&writer).await; @@ -552,6 +641,9 @@ impl Qwen3RealtimeASR { } st.session_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } let mut segments = std::mem::take(&mut st.completed_segments); // If an interim tail is still un-completed before session.finished (finish // should flush it out; defensive backstop), append it last. @@ -576,28 +668,86 @@ impl Qwen3RealtimeASR { } fn finish_with_partial_or_error(&self, error: Qwen3ASRError) { - let has_partial = { - let st = self.state.lock(); - !st.completed_segments.is_empty() || !st.partial_text.trim().is_empty() + self.resolve_partial_or_error(error, false); + } + + fn record_send_failure(&self, error: Qwen3ASRError) { + self.resolve_partial_or_error(error, true); + } + + fn resolve_partial_or_error(&self, error: Qwen3ASRError, clear_scratch: bool) { + let (tx, outcome, started_failed) = { + let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } + st.send_tx.take(); + if clear_scratch { + st.pending_audio.clear(); + st.audio_scratch.clear(); + } + let has_partial = + !st.completed_segments.is_empty() || !st.partial_text.trim().is_empty(); + let started_failed = + if !has_partial && !st.session_started && st.session_start_error.is_none() { + st.session_start_error = Some(error.to_string()); + true + } else { + false + }; + if st.session_finished { + (None, None, started_failed) + } else { + st.session_finished = true; + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } + let tx = st.final_tx.take(); + let outcome = if has_partial { + let mut segments = std::mem::take(&mut st.completed_segments); + if !st.partial_text.is_empty() { + segments.push(std::mem::take(&mut st.partial_text)); + } + let text = join_segments(&segments); + let duration_ms = if st.bytes_received > 0 { + st.bytes_received / BYTES_PER_MS + } else { + st.start + .map(|start| start.elapsed().as_millis() as u64) + .unwrap_or_default() + }; + Ok(RawTranscript { text, duration_ms }) + } else { + Err(error) + }; + (tx, Some(outcome), started_failed) + } }; - if has_partial { - // Consistent with Bailian / Volcengine: on error with an existing result, - // fall back to returning it. - self.finish_success(); - } else { - self.finish_error(error); + if started_failed { + self.session_started.notify_waiters(); + } + if let (Some(tx), Some(outcome)) = (tx, outcome) { + let _ = tx.send(outcome); } + self.session_finished.notify_waiters(); + self.close_on_runtime(); } fn finish_error(&self, error: Qwen3ASRError) { self.fail_session_start(&error.to_string()); let tx = { let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } if st.session_finished { return; } st.session_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } st.final_tx.take() }; if let Some(tx) = tx { @@ -622,7 +772,13 @@ impl AudioConsumer for Qwen3RealtimeASR { } let (send_tx, chunks) = { let mut st = self.state.lock(); + if st.ending { + return; + } st.bytes_received = st.bytes_received.saturating_add(pcm.len() as u64); + if st.session_finished || st.send_error.is_some() { + return; + } if !st.session_started { st.pending_audio.extend_from_slice(pcm); return; @@ -633,7 +789,9 @@ impl AudioConsumer for Qwen3RealtimeASR { }; if let Some(tx) = send_tx { for chunk in chunks { - let _ = tx.send(SendItem::Audio(chunk)); + if tx.send(SendItem::Audio(chunk)).is_err() { + break; + } } } } @@ -1093,4 +1251,147 @@ mod tests { assert_eq!(chunks.len(), 2); assert_eq!(buffer.len(), 17); } + + #[tokio::test] + async fn buffered_audio_tracks_coverage_and_paces_before_finish() { + let frames = Arc::new(ParkingMutex::new(Vec::::new())); + let finish_seen = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let frames_srv = Arc::clone(&frames); + let finish_seen_srv = Arc::clone(&finish_seen); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("ws://{}/api-ws/v1/realtime", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + while let Some(Ok(Message::Text(text))) = ws.next().await { + let value: Value = serde_json::from_str(&text).unwrap(); + match value["type"].as_str().unwrap_or_default() { + "session.update" => { + ws.send(Message::text( + json!({"type": "session.updated"}).to_string(), + )) + .await + .unwrap(); + } + "input_audio_buffer.append" => { + frames_srv.lock().push(Instant::now()); + } + "session.finish" => { + finish_seen_srv.store(true, std::sync::atomic::Ordering::Release); + ws.send(Message::text(completed_event("你好世界").to_string())) + .await + .unwrap(); + ws.send(Message::text( + json!({"type": "session.finished"}).to_string(), + )) + .await + .unwrap(); + let _ = ws.close(None).await; + break; + } + _ => {} + } + } + }); + + let asr = Arc::new(Qwen3RealtimeASR::new(Qwen3RealtimeCredentials { + api_key: "sk-test".into(), + endpoint, + model: DEFAULT_MODEL.into(), + })); + asr.open_session().await.unwrap(); + + let total_bytes = TARGET_AUDIO_CHUNK_BYTES * 5 + 300; + asr.consume_pcm_chunk(&vec![0x12u8; total_bytes]); + asr.send_last_frame().await.unwrap(); + let res = asr.await_final_result().await.unwrap(); + assert_eq!(res.text, "你好世界"); + assert!(asr.is_stream_complete()); + assert_eq!( + asr.audio_coverage(), + (total_bytes as u64, total_bytes as u64) + ); + assert!(finish_seen.load(std::sync::atomic::Ordering::Acquire)); + + { + let recorded = frames.lock(); + assert_eq!(recorded.len(), 6); + let span = recorded + .last() + .unwrap() + .saturating_duration_since(recorded[0]); + assert!( + span >= Duration::from_millis(180), + "expected >= 2x pacing (~250ms across 5 intervals), got {span:?}" + ); + } + server.await.unwrap(); + } + + #[tokio::test] + async fn send_last_frame_fails_when_session_broken_or_unwritten_audio_grows() { + let asr = Arc::new(create_test_asr()); + assert!(asr.send_last_frame().await.is_err()); + + let first_append = Arc::new(Notify::new()); + let first_append_srv = Arc::clone(&first_append); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("ws://{}/api-ws/v1/realtime", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + while let Some(Ok(Message::Text(text))) = ws.next().await { + let value: Value = serde_json::from_str(&text).unwrap(); + match value["type"].as_str().unwrap_or_default() { + "session.update" => { + ws.send(Message::text( + json!({"type": "session.updated"}).to_string(), + )) + .await + .unwrap(); + } + "input_audio_buffer.append" => { + ws.send(Message::text(completed_event("已识别").to_string())) + .await + .unwrap(); + ws.send(Message::text( + json!({"type": "error", "error": {"message": "server drop"}}) + .to_string(), + )) + .await + .unwrap(); + first_append_srv.notify_waiters(); + let _ = ws.close(None).await; + break; + } + _ => {} + } + } + }); + + let asr = Arc::new( + Qwen3RealtimeASR::new(Qwen3RealtimeCredentials { + api_key: "sk-test".into(), + endpoint, + model: DEFAULT_MODEL.into(), + }) + .with_frame_send_timeout(Duration::from_millis(80)), + ); + asr.open_session().await.unwrap(); + asr.consume_pcm_chunk(&vec![0x33u8; TARGET_AUDIO_CHUNK_BYTES]); + tokio::time::timeout(Duration::from_secs(2), first_append.notified()) + .await + .unwrap(); + // Let the server error transition complete, then feed trailing audio that cannot be sent. + tokio::time::sleep(Duration::from_millis(40)).await; + asr.consume_pcm_chunk(&vec![0x44u8; 40_000]); + + assert!(asr.send_last_frame().await.is_err()); + assert!(!asr.is_stream_complete()); + let (sent, received) = asr.audio_coverage(); + assert_eq!(sent, TARGET_AUDIO_CHUNK_BYTES as u64); + assert_eq!(received, (TARGET_AUDIO_CHUNK_BYTES + 40_000) as u64); + server.await.unwrap(); + } } diff --git a/openless-all/app/crates/openless-core/src/asr/stepfun_realtime.rs b/openless-all/app/crates/openless-core/src/asr/stepfun_realtime.rs index 392ff58d6..db579c2da 100644 --- a/openless-all/app/crates/openless-core/src/asr/stepfun_realtime.rs +++ b/openless-all/app/crates/openless-core/src/asr/stepfun_realtime.rs @@ -27,17 +27,17 @@ use base64::Engine; use futures_util::{SinkExt, StreamExt}; use parking_lot::Mutex as ParkingMutex; use serde_json::{json, Value}; -use tokio::net::TcpStream; -use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex, Notify}; +use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex, Notify}; +use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::http::header::HeaderValue; use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use uuid::Uuid; use crate::config::{TaskSpawner, TokioTaskSpawner}; use super::qwen_realtime::join_segments; +use super::stream_send::{send_ws_message_with_timeout, PacedSendClock, SharedWriter}; use super::{AudioConsumer, RawTranscript}; use crate::ports::{TextStreamChunk, TextStreamSink}; @@ -56,6 +56,7 @@ const BYTES_PER_MS: u64 = 32; const FINAL_RESULT_TIMEOUT: Duration = Duration::from_secs(12); const SESSION_READY_TIMEOUT: Duration = Duration::from_secs(5); const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +const FRAME_SEND_TIMEOUT: Duration = Duration::from_secs(5); /// Upper bound on the WebSocket handshake itself (TCP + TLS + HTTP upgrade). /// /// Without it, `connect_async` waits forever: a mid-handshake disconnect, a corporate @@ -90,10 +91,6 @@ const FINISH_POLL_INTERVAL: Duration = Duration::from_millis(100); /// FINAL_RESULT_TIMEOUT (12s). const FINISH_HARD_DEADLINE: Duration = Duration::from_millis(3_000); -type WsStream = WebSocketStream>; -type WsSink = futures_util::stream::SplitSink; -type SharedWriter = Arc>>; - #[derive(Clone, Debug)] pub struct StepfunRealtimeCredentials { pub api_key: String, @@ -146,7 +143,7 @@ impl StepfunRealtimeCredentials { } } -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum StepfunASRError { #[error("credentials missing")] CredentialsMissing, @@ -165,10 +162,12 @@ pub enum StepfunASRError { enum SendItem { Audio { chunk: Vec, + /// Pre-silence-padding PCM bytes represented by this frame (`0`..`chunk.len()`). + input_bytes: u64, contains_non_silent_audio: bool, /// Lets `send_last_frame` confirm the tail frame was actually written to the /// WebSocket by the write worker. - written_tx: Option>>, + written_tx: Option>>, }, } @@ -177,16 +176,21 @@ struct SyncState { pending_audio: Vec, audio_scratch: Vec, bytes_received: u64, + bytes_sent_input: u64, /// Last time the write worker successfully wrote non-silent PCM to the WebSocket. last_non_silent_audio_written_at: Option, /// Last time a server-side completed event arrived. last_completed_at: Option, session_started: bool, session_finished: bool, + tail_written: bool, + ending: bool, + send_error: Option, session_start_error: Option, start: Option, final_tx: Option>>, send_tx: Option>, + cancel_tx: Option>, /// Completed segments (completed.transcript) accumulated in arrival order after /// VAD segmentation. completed_segments: Vec, @@ -209,6 +213,7 @@ struct SyncState { pub struct StepfunRealtimeASR { credentials: StepfunRealtimeCredentials, + frame_send_timeout: Duration, task_spawner: Arc, state: ParkingMutex, writer: SharedWriter, @@ -229,6 +234,7 @@ impl StepfunRealtimeASR { ) -> Self { Self { credentials, + frame_send_timeout: FRAME_SEND_TIMEOUT, task_spawner, state: ParkingMutex::new(SyncState::default()), writer: Arc::new(AsyncMutex::new(None)), @@ -239,6 +245,22 @@ impl StepfunRealtimeASR { } } + #[cfg(test)] + pub(crate) fn with_frame_send_timeout(mut self, timeout: Duration) -> Self { + self.frame_send_timeout = timeout; + self + } + + pub fn audio_coverage(&self) -> (u64, u64) { + let st = self.state.lock(); + (st.bytes_sent_input, st.bytes_received) + } + + pub fn is_stream_complete(&self) -> bool { + let st = self.state.lock(); + st.send_error.is_none() && st.tail_written && st.bytes_sent_input == st.bytes_received + } + pub fn set_partial_sink(&self, sink: Arc) { *self.partial_sink.lock() = Some(sink); } @@ -272,43 +294,83 @@ impl StepfunRealtimeASR { let (final_tx, final_rx) = oneshot::channel(); let (send_tx, mut send_rx) = mpsc::unbounded_channel::(); + let (cancel_tx, mut cancel_rx) = watch::channel(false); { let mut st = self.state.lock(); *st = SyncState::default(); st.start = Some(Instant::now()); st.final_tx = Some(final_tx); st.send_tx = Some(send_tx); + st.cancel_tx = Some(cancel_tx); } *self.final_rx.lock() = Some(final_rx); let writer_for_worker = Arc::clone(&self.writer); let weak_self_for_worker = Arc::downgrade(self); + let frame_send_timeout = self.frame_send_timeout; let task_spawner = Arc::clone(&self.task_spawner); task_spawner.spawn(Box::pin(async move { + let mut clock = PacedSendClock::new(); while let Some(SendItem::Audio { chunk, + input_bytes, contains_non_silent_audio, written_tx, }) = send_rx.recv().await { - match send_text(&writer_for_worker, append_audio_message(&chunk)).await { + let Some(scheduled_start) = clock.wait_slot(&mut cancel_rx).await else { + if let Some(tx) = written_tx { + let _ = tx.send(Err(StepfunASRError::SendFailed( + "session cancelled".to_string(), + ))); + } + break; + }; + let is_tail = written_tx.is_some(); + match send_ws_message_with_timeout( + &writer_for_worker, + Message::Text(append_audio_message(&chunk).into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + { Ok(()) => { - if contains_non_silent_audio { - if let Some(this) = weak_self_for_worker.upgrade() { + if let Some(this) = weak_self_for_worker.upgrade() { + { + let mut st = this.state.lock(); + st.bytes_sent_input = + st.bytes_sent_input.saturating_add(input_bytes); + if is_tail { + st.tail_written = true; + st.tail_write_pending = false; + } + } + if contains_non_silent_audio { this.mark_non_silent_audio_written(); } } if let Some(tx) = written_tx { let _ = tx.send(Ok(())); + break; } + clock.mark_sent( + scheduled_start, + input_bytes.max(1) as usize, + BYTES_PER_MS, + 2, + ); } - Err(error) => { - if let Some(tx) = written_tx { - let _ = tx.send(Err(error.to_string())); - } + Err(ws_err) => { + let error = StepfunASRError::SendFailed( + ws_err.into_message("websocket writer not available"), + ); log::error!("[stepfun-asr] audio frame send failed: {error}"); if let Some(this) = weak_self_for_worker.upgrade() { - this.finish_error(error); + this.record_send_failure(error.clone()); + } + if let Some(tx) = written_tx { + let _ = tx.send(Err(error)); } break; } @@ -394,129 +456,165 @@ impl StepfunRealtimeASR { /// Pure-silence sessions (no speech_started at all) are covered by the /// FINISH_GRACE backstop and return successfully with empty text. pub async fn send_last_frame(self: &Arc) -> Result<(), StepfunASRError> { - let result = tokio::time::timeout(FINAL_RESULT_TIMEOUT, async { - let finished = self.session_finished.notified(); - tokio::pin!(finished); - finished.as_mut().enable(); - let (send_tx, tail, contains_non_silent_audio) = { - let mut st = self.state.lock(); - let send_tx = st.send_tx.clone(); - if !st.pending_audio.is_empty() { - let pending = std::mem::take(&mut st.pending_audio); - st.audio_scratch.extend_from_slice(&pending); - } - let mut tail = std::mem::take(&mut st.audio_scratch); - // Only the real recording counts as "voiced". The appended silence is a - // close-out tool; counting it would push last_non_silent_audio_written_at - // past the last completed, making has_audio_after_last_completed - // permanently true. - let contains_non_silent_audio = contains_non_silent_pcm(&tail); - // Merge tail audio and silence frames into one append to save a write. - tail.resize(tail.len() + (SILENCE_TAIL_MS * BYTES_PER_MS) as usize, 0); - st.finishing = true; - st.tail_write_pending = send_tx.is_some(); - (send_tx, tail, contains_non_silent_audio) - }; - let Some(send_tx) = send_tx else { - return Ok(()); + let finished = self.session_finished.notified(); + tokio::pin!(finished); + finished.as_mut().enable(); + let (written_tx, written_rx) = oneshot::channel(); + { + let mut st = self.state.lock(); + if let Some(ref err) = st.send_error { + return Err(err.clone()); + } + let Some(send_tx) = st.send_tx.take() else { + return Err(StepfunASRError::SendFailed( + "audio writer is not available".to_string(), + )); }; - let (written_tx, written_rx) = oneshot::channel(); - send_tx + st.ending = true; + if !st.pending_audio.is_empty() { + let pending = std::mem::take(&mut st.pending_audio); + st.audio_scratch.extend_from_slice(&pending); + } + let full_chunks = drain_audio_chunks(&mut st.audio_scratch); + let mut tail = std::mem::take(&mut st.audio_scratch); + let tail_input_bytes = tail.len() as u64; + // Only the real recording counts as "voiced". The appended silence is a + // close-out tool; counting it would push last_non_silent_audio_written_at + // past the last completed, making has_audio_after_last_completed + // permanently true. + let contains_non_silent_audio = contains_non_silent_pcm(&tail); + // Merge tail audio and silence frames into one append to save a write. + tail.resize(tail.len() + (SILENCE_TAIL_MS * BYTES_PER_MS) as usize, 0); + st.finishing = true; + st.tail_write_pending = true; + + for chunk in full_chunks { + let input_bytes = chunk.len() as u64; + let contains_non_silent_audio = contains_non_silent_pcm(&chunk); + if send_tx + .send(SendItem::Audio { + chunk, + input_bytes, + contains_non_silent_audio, + written_tx: None, + }) + .is_err() + { + st.tail_write_pending = false; + return Err(st.send_error.clone().unwrap_or_else(|| { + StepfunASRError::SendFailed("audio writer is not available".to_string()) + })); + } + } + if send_tx .send(SendItem::Audio { chunk: tail, + input_bytes: tail_input_bytes, contains_non_silent_audio, written_tx: Some(written_tx), }) - .map_err(|_| { + .is_err() + { + st.tail_write_pending = false; + return Err(st.send_error.clone().unwrap_or_else(|| { StepfunASRError::SendFailed("audio writer is not available".to_string()) - })?; - written_rx - .await - .map_err(|_| { - StepfunASRError::SendFailed( - "audio writer stopped before the tail frame was sent".to_string(), - ) - })? - .map_err(StepfunASRError::SendFailed)?; + })); + } + } + + let write_result = match written_rx.await { + Ok(inner) => inner, + Err(_) => Err(self.state.lock().send_error.clone().unwrap_or_else(|| { + StepfunASRError::SendFailed( + "audio writer stopped before the tail frame was sent".to_string(), + ) + })), + }; + if let Err(err) = write_result { self.state.lock().tail_write_pending = false; + self.cancel(); + return Err(err); + } - // Grace task: the tail frame is written and the client sends no more audio; - // all that remains is waiting for the server to turn the tail audio into - // completed events. Once FINISH_GRACE has elapsed with no open segments, - // finish. - // - // Must poll: this used to check once at FINISH_GRACE expiry, and a single - // failed check left no second chance — after the tail frame the server may - // send no further events at all (when the pause before release already - // exceeded the VAD threshold, the last segment's completed arrived before - // the tail), so the session idled until FINAL_RESULT_TIMEOUT. Measured at - // ~13% of dictations waiting the full 12 seconds this way. (The direct - // cause of that 13% was contains_non_silent_pcm treating room tone as - // speech, see that function; polling + the hard deadline are the second - // line of defense ensuring any finish failure never degrades to 12s again.) - // - // The finish precondition is still "no open segments, and no unconfirmed - // real audio after the last completed" — that guard is correct and must not - // be dropped to fix the stall. The real backstop is FINISH_HARD_DEADLINE: - // when the server never closes the last segment, worst-case wait is 3s - // instead of idling until FINAL_RESULT_TIMEOUT. - let weak = Arc::downgrade(self); - let task_spawner = Arc::clone(&self.task_spawner); - task_spawner.spawn(Box::pin(async move { - let since_tail = Instant::now(); - loop { - tokio::time::sleep(FINISH_POLL_INTERVAL).await; - let Some(this) = weak.upgrade() else { - return; - }; - let waited = since_tail.elapsed(); - let expired = waited >= FINISH_HARD_DEADLINE; - let should_finish = { - let st = this.state.lock(); - if st.session_finished { - return; - } - if expired { - should_force_finish_at_hard_deadline(&st) - } else { - waited >= FINISH_GRACE - && st.open_segments == 0 - && !has_audio_after_last_completed(&st) - } - }; - if should_finish { - if expired { - log::warn!( - "[stepfun-asr] server did not settle within {FINISH_HARD_DEADLINE:?} \ - (open segments); finishing with what we have" - ); - } - this.finish_success(); + // Grace task: the tail frame is written and the client sends no more audio; + // all that remains is waiting for the server to turn the tail audio into + // completed events. Once FINISH_GRACE has elapsed with no open segments, + // finish. + // + // Must poll: this used to check once at FINISH_GRACE expiry, and a single + // failed check left no second chance — after the tail frame the server may + // send no further events at all (when the pause before release already + // exceeded the VAD threshold, the last segment's completed arrived before + // the tail), so the session idled until FINAL_RESULT_TIMEOUT. Measured at + // ~13% of dictations waiting the full 12 seconds this way. (The direct + // cause of that 13% was contains_non_silent_pcm treating room tone as + // speech, see that function; polling + the hard deadline are the second + // line of defense ensuring any finish failure never degrades to 12s again.) + // + // The finish precondition is still "no open segments, and no unconfirmed + // real audio after the last completed" — that guard is correct and must not + // be dropped to fix the stall. The real backstop is FINISH_HARD_DEADLINE: + // when the server never closes the last segment, worst-case wait is 3s + // instead of idling until FINAL_RESULT_TIMEOUT. + let weak = Arc::downgrade(self); + let task_spawner = Arc::clone(&self.task_spawner); + task_spawner.spawn(Box::pin(async move { + let since_tail = Instant::now(); + loop { + tokio::time::sleep(FINISH_POLL_INTERVAL).await; + let Some(this) = weak.upgrade() else { + return; + }; + let waited = since_tail.elapsed(); + let expired = waited >= FINISH_HARD_DEADLINE; + let should_finish = { + let st = this.state.lock(); + if st.session_finished { return; } + if expired { + should_force_finish_at_hard_deadline(&st) + } else { + waited >= FINISH_GRACE + && st.open_segments == 0 + && !has_audio_after_last_completed(&st) + } + }; + if should_finish { + if expired { + log::warn!( + "[stepfun-asr] server did not settle within {FINISH_HARD_DEADLINE:?} \ + (open segments); finishing with what we have" + ); + } + this.finish_success(); + return; } - })); + } + })); + let result = tokio::time::timeout(FINAL_RESULT_TIMEOUT, async { if !self.state.lock().session_finished { finished.await; } - Ok(()) }) .await; match result { - Ok(inner) => inner, + Ok(()) => { + if let Some(error) = self.state.lock().send_error.clone() { + return Err(error); + } + Ok(()) + } Err(_) => { - // Timeout backstop: return the partial result if one exists, error - // otherwise — same as the disconnect path. Reaching here means the - // grace task above failed to finish (it has its own FINISH_HARD_DEADLINE - // backstop and normally should not get here), and the user has already - // waited the full 12 seconds — this must be logged. + // Timeout backstop: keep partial text if one exists for short sessions, + // while returning an error so long/incomplete sessions trigger recovery. log::warn!( "[stepfun-asr] finish stalled for {:?}, falling back to partial transcript", FINAL_RESULT_TIMEOUT ); self.finish_with_partial_or_error(StepfunASRError::FinalResultTimeout); - Ok(()) + Err(StepfunASRError::FinalResultTimeout) } } } @@ -539,7 +637,12 @@ impl StepfunRealtimeASR { st.send_tx.take(); st.final_tx.take(); st.session_finished = true; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } drop(st); + self.session_started.notify_waiters(); + self.session_finished.notify_waiters(); let writer = Arc::clone(&self.writer); self.task_spawner.spawn(Box::pin(async move { let _ = close_writer(&writer).await; @@ -620,9 +723,11 @@ impl StepfunRealtimeASR { }; if let Some(tx) = send_tx { for chunk in chunks { + let input_bytes = chunk.len() as u64; let _ = tx.send(SendItem::Audio { contains_non_silent_audio: contains_non_silent_pcm(&chunk), chunk, + input_bytes, written_tx: None, }); } @@ -724,6 +829,9 @@ impl StepfunRealtimeASR { } st.session_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } let mut segments = std::mem::take(&mut st.completed_segments); // At close, if an interim tail is still un-completed (the silence frames // should flush it out; defensive backstop), append it last. @@ -748,28 +856,86 @@ impl StepfunRealtimeASR { } fn finish_with_partial_or_error(&self, error: StepfunASRError) { - let has_result = { - let st = self.state.lock(); - has_transcript(&st) + self.resolve_partial_or_error(error, false); + } + + fn record_send_failure(&self, error: StepfunASRError) { + self.resolve_partial_or_error(error, true); + } + + fn resolve_partial_or_error(&self, error: StepfunASRError, is_send_failure: bool) { + let (tx, outcome, started_failed) = { + let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } + if is_send_failure { + st.tail_write_pending = false; + st.pending_audio.clear(); + st.audio_scratch.clear(); + } + st.send_tx.take(); + let has_result = has_transcript(&st); + let started_failed = + if !has_result && !st.session_started && st.session_start_error.is_none() { + st.session_start_error = Some(error.to_string()); + true + } else { + false + }; + if st.session_finished { + (None, None, started_failed) + } else { + st.session_finished = true; + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } + let tx = st.final_tx.take(); + let outcome = if has_result { + let mut segments = std::mem::take(&mut st.completed_segments); + if !st.partial_text.is_empty() { + segments.push(std::mem::take(&mut st.partial_text)); + } + let text = join_segments(&segments); + let duration_ms = if st.bytes_received > 0 { + st.bytes_received / BYTES_PER_MS + } else { + st.start + .map(|start| start.elapsed().as_millis() as u64) + .unwrap_or_default() + }; + Ok(RawTranscript { text, duration_ms }) + } else { + Err(error) + }; + (tx, Some(outcome), started_failed) + } }; - if has_result { - // Consistent with Bailian / Qwen / Volcengine: on error with an existing - // result, fall back to returning it. - self.finish_success(); - } else { - self.finish_error(error); + if started_failed { + self.session_started.notify_waiters(); + } + if let (Some(tx), Some(outcome)) = (tx, outcome) { + let _ = tx.send(outcome); } + self.session_finished.notify_waiters(); + self.close_on_runtime(); } fn finish_error(&self, error: StepfunASRError) { self.fail_session_start(&error.to_string()); let tx = { let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(error.clone()); + } if st.session_finished { return; } st.session_finished = true; st.send_tx.take(); + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } st.final_tx.take() }; if let Some(tx) = tx { @@ -798,7 +964,13 @@ impl AudioConsumer for StepfunRealtimeASR { } let (send_tx, chunks) = { let mut st = self.state.lock(); + if st.ending { + return; + } st.bytes_received = st.bytes_received.saturating_add(pcm.len() as u64); + if st.session_finished || st.send_error.is_some() { + return; + } if !st.session_started { st.pending_audio.extend_from_slice(pcm); return; @@ -809,11 +981,18 @@ impl AudioConsumer for StepfunRealtimeASR { }; if let Some(tx) = send_tx { for chunk in chunks { - let _ = tx.send(SendItem::Audio { - contains_non_silent_audio: contains_non_silent_pcm(&chunk), - chunk, - written_tx: None, - }); + let input_bytes = chunk.len() as u64; + if tx + .send(SendItem::Audio { + contains_non_silent_audio: contains_non_silent_pcm(&chunk), + chunk, + input_bytes, + written_tx: None, + }) + .is_err() + { + break; + } } } } @@ -1553,4 +1732,79 @@ mod tests { started.elapsed() ); } + + #[tokio::test] + async fn audio_coverage_excludes_closeout_silence_and_rejects_broken_stream() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!( + "ws://{}/v1/realtime/asr/stream", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + let mut append_count = 0usize; + while let Some(Ok(message)) = ws.next().await { + match message { + Message::Text(text) => { + let value: Value = serde_json::from_str(&text).unwrap(); + match value["type"].as_str().unwrap_or_default() { + "session.update" => { + ws.send(Message::text( + json!({ "type": "session.updated" }).to_string(), + )) + .await + .unwrap(); + } + "input_audio_buffer.append" => { + append_count += 1; + if append_count == 3 { + ws.send(Message::text(speech_started_event())) + .await + .unwrap(); + ws.send(Message::text(completed_event("覆盖率测试。"))) + .await + .unwrap(); + } + } + _ => {} + } + } + Message::Close(_) => break, + _ => {} + } + } + }); + + let asr = Arc::new(StepfunRealtimeASR::new(StepfunRealtimeCredentials { + api_key: "sk-test".to_string(), + endpoint, + model: DEFAULT_MODEL.to_string(), + prompt: None, + })); + asr.open_session().await.unwrap(); + let total_input = TARGET_AUDIO_CHUNK_BYTES * 2 + 640; + asr.consume_pcm_chunk(&speech_pcm(total_input)); + asr.send_last_frame().await.unwrap(); + let transcript = asr.await_final_result().await.unwrap(); + assert_eq!(transcript.text, "覆盖率测试。"); + assert!(asr.is_stream_complete()); + assert_eq!( + asr.audio_coverage(), + (total_input as u64, total_input as u64) + ); + server.await.unwrap(); + + let closed_asr = Arc::new( + StepfunRealtimeASR::new(StepfunRealtimeCredentials { + api_key: "sk-test".to_string(), + endpoint: String::new(), + model: DEFAULT_MODEL.to_string(), + prompt: None, + }) + .with_frame_send_timeout(Duration::from_millis(80)), + ); + assert!(closed_asr.send_last_frame().await.is_err()); + assert!(!closed_asr.is_stream_complete()); + } } diff --git a/openless-all/app/crates/openless-core/src/asr/volcengine.rs b/openless-all/app/crates/openless-core/src/asr/volcengine.rs index 42b55b2fb..a916adbbf 100644 --- a/openless-all/app/crates/openless-core/src/asr/volcengine.rs +++ b/openless-all/app/crates/openless-core/src/asr/volcengine.rs @@ -5,24 +5,23 @@ //! final response. A `definite=true` utterance commits that segment only; it does //! not end the stream or prevent later audio from being sent. -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; use futures_util::{SinkExt, StreamExt}; use parking_lot::Mutex as ParkingMutex; use serde_json::{json, Value}; -use tokio::net::TcpStream; -use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex, Notify}; +use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex}; +use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::http::header::HeaderValue; use tokio_tungstenite::tungstenite::{handshake::client::Request as WebSocketRequest, Message}; -use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use uuid::Uuid; use crate::config::{TaskSpawner, TokioTaskSpawner}; use super::frame::{self, Flags, MessageType, Serialization}; +use super::stream_send::{send_ws_message_with_timeout, PacedSendClock, SharedWriter, WsStream}; use super::{AudioConsumer, DictionaryHotword, RawTranscript}; use crate::ports::{TextStreamChunk, TextStreamSink}; @@ -38,6 +37,8 @@ const ENDPOINT_AGENT_PLAN: &str = "wss://openspeech.bytedance.com/api/v3/plan/sa pub const TARGET_AUDIO_CHUNK_BYTES: usize = 6_400; /// 16 kHz · 16-bit · mono = 32 000 bytes/sec → 32 bytes/ms. const BYTES_PER_MS: f64 = 32.0; +const BYTES_PER_MS_U64: u64 = 32; +const FRAME_SEND_TIMEOUT: Duration = Duration::from_secs(5); const HOTWORD_CAP: usize = 80; const FINAL_RESULT_TIMEOUT: Duration = Duration::from_secs(12); @@ -161,7 +162,7 @@ impl VolcengineCredentials { } } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, Clone, thiserror::Error)] pub enum VolcengineASRError { #[error("credentials missing")] CredentialsMissing, @@ -193,10 +194,16 @@ pub enum VolcengineASRError { DecodeFailed(String), } -type WsStream = WebSocketStream>; -type WsSink = futures_util::stream::SplitSink; -type SharedWriter = Arc>>; -type AudioFrameSender = mpsc::UnboundedSender<(i32, Vec)>; +enum SendItem { + Audio { + seq: i32, + chunk: Vec, + }, + End { + final_seq: i32, + done: oneshot::Sender>, + }, +} /// Sync state shared across the receive loop, the public API, and the /// audio-consumer fast path. @@ -204,9 +211,15 @@ type AudioFrameSender = mpsc::UnboundedSender<(i32, Vec)>; struct SyncState { pending_audio: Vec, next_sequence: i32, - bytes_sent: usize, - frames_sent: usize, + bytes_received: u64, + bytes_written: u64, + frames_written: usize, is_connected: bool, + ending: bool, + final_frame_sent: bool, + send_tx: Option>, + send_error: Option, + cancel_tx: Option>, final_tx: Option>>, start: Option, /// Accumulated transcript of the latest partial (non-final). Returned to the @@ -218,6 +231,9 @@ struct SyncState { pub struct VolcengineStreamingASR { credentials: VolcengineCredentials, + #[cfg(test)] + endpoint_override: Option, + frame_send_timeout: Duration, task_spawner: Arc, hotwords: Vec, state: ParkingMutex, @@ -226,18 +242,6 @@ pub struct VolcengineStreamingASR { /// of the lifetime of any particular `&self` borrow. writer: SharedWriter, final_rx: ParkingMutex>>>, - /// Single-worker mode: consume_pcm_chunk enqueues (seq, chunk) into this channel - /// and the single worker spawned in open_session serially recvs and send_binary, - /// guaranteeing seq order equals actual send order. At session end the sender is - /// take()n; the worker's recv() returns None and it exits. - audio_tx: ParkingMutex>, - /// Total audio frames queued plus in flight in the worker. consume adds N, the - /// worker subtracts 1 after sending a frame. send_last_frame must wait for this - /// to reach 0 before sending the final frame, otherwise the server could receive - /// the final frame first and treat later chunks as data after "stream ended", - /// dropping them — losing the tail sentence. - pending_sends: Arc, - send_done: Arc, partial_sink: ParkingMutex>>, } @@ -253,18 +257,40 @@ impl VolcengineStreamingASR { ) -> Self { Self { credentials, + #[cfg(test)] + endpoint_override: None, + frame_send_timeout: FRAME_SEND_TIMEOUT, task_spawner, hotwords, state: ParkingMutex::new(SyncState::default()), writer: Arc::new(AsyncMutex::new(None)), final_rx: ParkingMutex::new(None), - audio_tx: ParkingMutex::new(None), - pending_sends: Arc::new(AtomicUsize::new(0)), - send_done: Arc::new(Notify::new()), partial_sink: ParkingMutex::new(None), } } + #[cfg(test)] + pub(crate) fn with_endpoint(mut self, endpoint: impl Into) -> Self { + self.endpoint_override = Some(endpoint.into()); + self + } + + #[cfg(test)] + pub(crate) fn with_frame_send_timeout(mut self, timeout: Duration) -> Self { + self.frame_send_timeout = timeout; + self + } + + pub fn audio_coverage(&self) -> (u64, u64) { + let st = self.state.lock(); + (st.bytes_written, st.bytes_received) + } + + pub fn is_stream_complete(&self) -> bool { + let st = self.state.lock(); + st.send_error.is_none() && st.final_frame_sent && st.bytes_written == st.bytes_received + } + pub fn set_partial_sink(&self, sink: Arc) { *self.partial_sink.lock() = Some(sink); } @@ -283,47 +309,117 @@ impl VolcengineStreamingASR { let (write, read) = ws.split(); let (tx, rx) = oneshot::channel(); + let (send_tx, mut send_rx) = mpsc::unbounded_channel::(); + let (cancel_tx, mut cancel_rx) = watch::channel(false); // Reset sync state for the new session. { let mut st = self.state.lock(); - st.pending_audio.clear(); + *st = SyncState::default(); st.next_sequence = 1; - st.bytes_sent = 0; - st.frames_sent = 0; st.is_connected = true; st.final_tx = Some(tx); + st.send_tx = Some(send_tx); + st.cancel_tx = Some(cancel_tx); st.start = Some(Instant::now()); - st.last_partial_text.clear(); } - self.pending_sends.store(0, Ordering::SeqCst); *self.final_rx.lock() = Some(rx); *self.writer.lock().await = Some(write); - // Spawn the single audio worker: consume_pcm_chunk pushes (seq, chunk) into - // audio_tx; the worker FIFO-recvs and sends serially. At session end the - // caller (cancel / handle_frame error / fallback_to_partial_or_error) takes - // self.audio_tx, closing the channel so the worker exits naturally. - let (audio_tx, mut audio_rx) = mpsc::unbounded_channel::<(i32, Vec)>(); - *self.audio_tx.lock() = Some(audio_tx); + // Spawn the single FIFO audio worker: drains queued audio with 2x realtime + // pacing before sending the NegativeSequence terminal frame. let writer_for_worker = Arc::clone(&self.writer); - let pending_for_worker = Arc::clone(&self.pending_sends); - let notify_for_worker = Arc::clone(&self.send_done); + let weak_self_for_worker = Arc::downgrade(self); + let frame_send_timeout = self.frame_send_timeout; let task_spawner = Arc::clone(&self.task_spawner); task_spawner.spawn(Box::pin(async move { - while let Some((seq, chunk)) = audio_rx.recv().await { - let frame = frame::build( - MessageType::AudioOnlyRequest, - Flags::PositiveSequence, - Serialization::None, - &chunk, - Some(seq), - ); - if let Err(e) = send_binary(&writer_for_worker, frame).await { - log::error!("[asr] audio frame seq={} send 失败: {}", seq, e); - } - if pending_for_worker.fetch_sub(1, Ordering::SeqCst) == 1 { - notify_for_worker.notify_one(); + let mut clock = PacedSendClock::new(); + loop { + let item = tokio::select! { + maybe_item = send_rx.recv() => match maybe_item { + Some(item) => item, + None => break, + }, + changed = cancel_rx.changed() => { + if changed.is_err() || *cancel_rx.borrow_and_update() { + break; + } + continue; + } + }; + match item { + SendItem::Audio { seq, chunk } => { + let Some(slot) = clock.wait_slot(&mut cancel_rx).await else { + break; + }; + let chunk_len = chunk.len(); + let frame = frame::build( + MessageType::AudioOnlyRequest, + Flags::PositiveSequence, + Serialization::None, + &chunk, + Some(seq), + ); + if let Err(ws_err) = send_ws_message_with_timeout( + &writer_for_worker, + Message::Binary(frame.into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + { + let err = VolcengineASRError::ConnectionFailed( + ws_err.into_message("websocket not open"), + ); + log::error!("[asr] audio frame seq={} send 失败: {}", seq, err); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err); + } + break; + } + if let Some(this) = weak_self_for_worker.upgrade() { + let mut st = this.state.lock(); + st.bytes_written = st.bytes_written.saturating_add(chunk_len as u64); + st.frames_written = st.frames_written.saturating_add(1); + } + clock.mark_sent(slot, chunk_len, BYTES_PER_MS_U64, 2); + } + SendItem::End { final_seq, done } => { + let frame = frame::build( + MessageType::AudioOnlyRequest, + Flags::NegativeSequence, + Serialization::None, + &[], + Some(final_seq), + ); + let result = send_ws_message_with_timeout( + &writer_for_worker, + Message::Binary(frame.into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + .map_err(|ws_err| { + VolcengineASRError::ConnectionFailed( + ws_err.into_message("websocket not open"), + ) + }); + match &result { + Ok(()) => { + if let Some(this) = weak_self_for_worker.upgrade() { + this.state.lock().final_frame_sent = true; + } + } + Err(err) => { + log::error!("[asr] final frame send 失败: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err.clone()); + } + } + } + let _ = done.send(result); + break; + } } } })); @@ -340,7 +436,10 @@ impl VolcengineStreamingASR { &payload_bytes, Some(first_seq), ); - send_binary(&self.writer, frame).await?; + if let Err(err) = send_binary(&self.writer, frame).await { + self.cancel(); + return Err(err); + } // Spawn the receive loop. Holds a Weak so it doesn't keep // the struct alive forever if callers drop their Arcs. @@ -396,6 +495,25 @@ impl VolcengineStreamingASR { .credentials .service .auth_mode(self.credentials.auth_mode.clone()); + #[cfg(test)] + if let Some(ref endpoint) = self.endpoint_override { + let mut request = endpoint + .as_str() + .into_client_request() + .map_err(|e| VolcengineASRError::ConnectionFailed(e.to_string()))?; + let headers = request.headers_mut(); + headers.insert( + "X-Api-Connect-Id", + HeaderValue::from_str(connect_id) + .map_err(|e| VolcengineASRError::ConnectionFailed(e.to_string()))?, + ); + headers.insert( + "X-Api-Request-Id", + HeaderValue::from_str(request_id) + .map_err(|e| VolcengineASRError::ConnectionFailed(e.to_string()))?, + ); + return Ok(request); + } let endpoint = match (self.credentials.service, &auth_mode) { (VolcengineService::AgentPlan, _) => ENDPOINT_AGENT_PLAN, (_, VolcengineAuthMode::AppIdToken) => ENDPOINT_APP_ID_TOKEN, @@ -525,78 +643,70 @@ impl VolcengineStreamingASR { } pub async fn send_last_frame(&self) -> Result<(), VolcengineASRError> { - // Wait for all fire-and-forget sends to complete. Otherwise the final frame - // (NegativeSequence) could reach the server before the tail chunks, which are - // then treated as data after "stream ended" and dropped = tail sentence lost. - // A stalled writer must fail instead of overtaking queued audio. - let drain_deadline = Instant::now() + CONNECT_TIMEOUT; - while self.pending_sends.load(Ordering::SeqCst) > 0 { - let remaining = drain_deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { + let (done_tx, done_rx) = oneshot::channel(); + { + let mut st = self.state.lock(); + if let Some(ref err) = st.send_error { + return Err(err.clone()); + } + let Some(tx) = st.send_tx.take() else { return Err(VolcengineASRError::ConnectionFailed( - "Timed out draining the audio queue".into(), + "websocket closed before final frame".into(), )); + }; + st.ending = true; + if !st.pending_audio.is_empty() { + let leftover = std::mem::take(&mut st.pending_audio); + let seq = st.next_sequence; + st.next_sequence += 1; + if tx + .send(SendItem::Audio { + seq, + chunk: leftover, + }) + .is_err() + { + return Err(st.send_error.clone().unwrap_or_else(|| { + VolcengineASRError::ConnectionFailed("audio send queue closed".into()) + })); + } } - // notified() returns a future; wrapped in timeout -> wait for sends to - // drain or time out. - let _ = tokio::time::timeout(remaining, self.send_done.notified()).await; - } - - // Drain leftover audio (if any) into one final positive-sequence frame. - let leftover = { - let mut st = self.state.lock(); - if st.pending_audio.is_empty() { - None - } else { - Some(std::mem::take(&mut st.pending_audio)) - } - }; - - if let Some(buf) = leftover { - let seq = self.allocate_positive_seq(); - let len = buf.len(); - let frame = frame::build( - MessageType::AudioOnlyRequest, - Flags::PositiveSequence, - Serialization::None, - &buf, - Some(seq), - ); + let final_seq = -st.next_sequence; + st.next_sequence += 1; + if tx + .send(SendItem::End { + final_seq, + done: done_tx, + }) + .is_err() { - let mut st = self.state.lock(); - st.bytes_sent += len; - st.frames_sent += 1; + return Err(st.send_error.clone().unwrap_or_else(|| { + VolcengineASRError::ConnectionFailed("audio send queue closed".into()) + })); } - send_binary(&self.writer, frame).await?; } - // Final frame: negativeSequence + negative seq number signals stream end. - // Final frame uses negativeSequence + negative seq number to tell the server - // "the stream ends here". - let final_seq = { - let mut st = self.state.lock(); - let s = -st.next_sequence; - st.next_sequence += 1; - s - }; - let frame = frame::build( - MessageType::AudioOnlyRequest, - Flags::NegativeSequence, - Serialization::None, - &[], - Some(final_seq), - ); - send_binary(&self.writer, frame).await?; + match done_rx.await { + Ok(inner) => inner?, + Err(_) => { + return Err(self.state.lock().send_error.clone().unwrap_or_else(|| { + VolcengineASRError::ConnectionFailed( + "audio send worker stopped before final frame".into(), + ) + })); + } + } - let (total_bytes, total_frames) = { + let (written_frames, written_bytes, received_bytes) = { let st = self.state.lock(); - (st.bytes_sent, st.frames_sent) + (st.frames_written, st.bytes_written, st.bytes_received) }; - let duration_ms = (total_bytes as f64 / BYTES_PER_MS) as u64; + let duration_ms = (written_bytes as f64 / BYTES_PER_MS) as u64; log::info!( - "[asr] 发送总结:{} audio frames, {} bytes (~{} ms)", - total_frames, - total_bytes, + "[asr] 发送总结:{} written frames, {}/{} bytes (~{} ms)", + written_frames, + written_bytes, + received_bytes, duration_ms ); Ok(()) @@ -634,10 +744,11 @@ impl VolcengineStreamingASR { let mut st = self.state.lock(); st.is_connected = false; st.pending_audio.clear(); + st.send_tx = None; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } } - // Dropping the audio sender -> worker.recv() returns None -> worker exits and - // stops holding the writer. - *self.audio_tx.lock() = None; // Close the writer asynchronously so the receive loop sees EOF. The // host-provided spawner also handles synchronous teardown callers. let writer = Arc::clone(&self.writer); @@ -649,6 +760,10 @@ impl VolcengineStreamingASR { self.signal_error(VolcengineASRError::NoFinalResult); } + fn record_send_failure(&self, err: VolcengineASRError) { + self.resolve_with_partial_or_error(err, true); + } + // ---- internals ---- fn build_first_frame_payload(&self, connect_id: &str) -> Value { @@ -694,11 +809,19 @@ impl VolcengineStreamingASR { if parsed.message_type == Some(MessageType::ErrorMessage) { let code = parsed.error_code.unwrap_or(0); log::error!("[asr] Volcengine error frame code={code}"); - self.signal_error(VolcengineASRError::ConnectionFailed(format!( - "Volcengine ASR error {code}" - ))); - self.state.lock().is_connected = false; - *self.audio_tx.lock() = None; + let err = VolcengineASRError::ConnectionFailed(format!("Volcengine ASR error {code}")); + { + let mut st = self.state.lock(); + if st.send_error.is_none() { + st.send_error = Some(err.clone()); + } + st.is_connected = false; + st.send_tx = None; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } + } + self.signal_error(err); return false; } @@ -810,8 +933,14 @@ impl VolcengineStreamingASR { duration_ms, }; self.signal_success(transcript); - self.state.lock().is_connected = false; - *self.audio_tx.lock() = None; + { + let mut st = self.state.lock(); + st.is_connected = false; + st.send_tx = None; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } + } return false; } true @@ -836,75 +965,77 @@ impl VolcengineStreamingASR { /// `last_partial_text` to guarantee "at least no loss of already-recognized /// speech". fn fallback_to_partial_or_error(&self, err: VolcengineASRError) { - let (partial, duration_ms) = { - let st = self.state.lock(); - ( - st.last_partial_text.clone(), - st.start - .map(|s| s.elapsed().as_millis() as u64) - .unwrap_or(0), - ) - }; - if !partial.is_empty() { - log::warn!( - "[asr] {}; 使用 partial 兜底({} 字)", - err, - partial.chars().count() - ); - self.signal_success(RawTranscript { - text: partial, - duration_ms, - }); - } else { - self.signal_error(err); - } - self.state.lock().is_connected = false; - *self.audio_tx.lock() = None; + self.resolve_with_partial_or_error(err, false); } -} -impl AudioConsumer for VolcengineStreamingASR { - fn consume_pcm_chunk(&self, pcm: &[u8]) { - // Single-worker serial send mode: drain and allocate seq inside the state lock - // (seq monotonic), then push (seq, chunk) into the mpsc. The worker sends in - // enqueue order, so even across multiple consume calls and spawns there is no - // writer lock contention. - let chunks: Vec<(i32, Vec)> = { + fn resolve_with_partial_or_error(&self, err: VolcengineASRError, clear_pending: bool) { + let (tx, outcome, partial_chars) = { let mut st = self.state.lock(); - if !st.is_connected { - return; + if st.send_error.is_none() { + st.send_error = Some(err.clone()); } - st.pending_audio.extend_from_slice(pcm); - - let mut out: Vec<(i32, Vec)> = Vec::new(); - while st.pending_audio.len() >= TARGET_AUDIO_CHUNK_BYTES { - let chunk: Vec = st.pending_audio.drain(..TARGET_AUDIO_CHUNK_BYTES).collect(); - let seq = st.next_sequence; - st.next_sequence += 1; - st.bytes_sent += chunk.len(); - st.frames_sent += 1; - out.push((seq, chunk)); + st.is_connected = false; + st.send_tx = None; + if clear_pending { + st.pending_audio.clear(); + } + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } + let partial = st.last_partial_text.clone(); + let duration_ms = st + .start + .map(|s| s.elapsed().as_millis() as u64) + .unwrap_or(0); + let tx = st.final_tx.take(); + if !partial.is_empty() { + let chars = partial.chars().count(); + ( + tx, + Ok(RawTranscript { + text: partial, + duration_ms, + }), + Some(chars), + ) + } else { + (tx, Err(err.clone()), None) } - out }; + if let Some(chars) = partial_chars { + log::warn!("[asr] {}; 使用 partial 兜底({} 字)", err, chars); + } + if let Some(tx) = tx { + let _ = tx.send(outcome); + } + } +} - if chunks.is_empty() { +impl AudioConsumer for VolcengineStreamingASR { + fn consume_pcm_chunk(&self, pcm: &[u8]) { + let mut st = self.state.lock(); + if st.ending || (!st.is_connected && st.bytes_received == 0 && st.send_tx.is_none()) { + return; + } + st.bytes_received = st.bytes_received.saturating_add(pcm.len() as u64); + if !st.is_connected || st.send_error.is_some() { return; } - let Some(tx) = self.audio_tx.lock().as_ref().cloned() else { + let Some(tx) = st.send_tx.clone() else { return; }; + st.pending_audio.extend_from_slice(pcm); - for entry in chunks { - // pending_sends must be incremented before tx.send: otherwise the worker - // could recv + send + decrement first, underflowing the usize counter. - self.pending_sends.fetch_add(1, Ordering::SeqCst); - if tx.send(entry).is_err() { - // The worker already exited (cancel / error path took audio_tx). - // Undo the increment so send_last_frame's wait can reach 0. - if self.pending_sends.fetch_sub(1, Ordering::SeqCst) == 1 { - self.send_done.notify_one(); - } + let mut chunks: Vec<(i32, Vec)> = Vec::new(); + while st.pending_audio.len() >= TARGET_AUDIO_CHUNK_BYTES { + let chunk: Vec = st.pending_audio.drain(..TARGET_AUDIO_CHUNK_BYTES).collect(); + let seq = st.next_sequence; + st.next_sequence += 1; + chunks.push((seq, chunk)); + } + + for (seq, chunk) in chunks { + if tx.send(SendItem::Audio { seq, chunk }).is_err() { log::warn!("[asr] audio queue closed; dropping subsequent frames"); return; } @@ -1062,7 +1193,8 @@ mod tests { "text": text, "utterances": [{ "text": text, "definite": packet % 20 == 0 }], }, - })).unwrap(); + })) + .unwrap(); let bytes = frame::build( MessageType::FullServerResponse, Flags::PositiveSequence, @@ -1375,4 +1507,283 @@ mod tests { Err(VolcengineASRError::FinalResultTimeout) )); } + + async fn spawn_loopback_ws(handler: F) -> (String, tokio::task::JoinHandle<()>) + where + F: FnOnce(tokio_tungstenite::WebSocketStream) -> Fut + + Send + + 'static, + Fut: std::future::Future + Send + 'static, + { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + handler(ws).await; + }); + (format!("ws://{addr}"), handle) + } + + fn loopback_volcengine(endpoint: String) -> Arc { + Arc::new( + VolcengineStreamingASR::new( + VolcengineCredentials { + service: VolcengineService::Standard, + auth_mode: VolcengineAuthMode::ApiKey, + app_id: String::new(), + access_token: "test-key".into(), + resource_id: VolcengineCredentials::default_resource_id().into(), + }, + Vec::new(), + ) + .with_endpoint(endpoint), + ) + } + + fn volc_final_response(text: &str) -> Vec { + let payload = serde_json::to_vec(&json!({ "result": { "text": text } })).unwrap(); + frame::build( + MessageType::FullServerResponse, + Flags::NegativeSequence, + Serialization::Json, + &payload, + Some(-1), + ) + } + + #[tokio::test] + async fn audio_frame_write_failure_stops_worker_and_fails_send_last_frame() { + let received_frames = Arc::new(ParkingMutex::new(Vec::::new())); + let first_audio_seen = Arc::new(tokio::sync::Notify::new()); + let shutdown_srv = Arc::new(tokio::sync::Notify::new()); + let received_srv = Arc::clone(&received_frames); + let first_audio_srv = Arc::clone(&first_audio_seen); + let shutdown_srv_task = Arc::clone(&shutdown_srv); + + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Binary(data))) => { + let parsed = frame::parse(&data).unwrap(); + let is_audio = parsed.message_type == Some(MessageType::AudioOnlyRequest) + && !parsed.is_final(); + received_srv.lock().push(parsed); + if is_audio { + first_audio_srv.notify_waiters(); + } + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_srv_task.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = Arc::new( + VolcengineStreamingASR::new( + VolcengineCredentials { + service: VolcengineService::Standard, + auth_mode: VolcengineAuthMode::ApiKey, + app_id: String::new(), + access_token: "test-key".into(), + resource_id: VolcengineCredentials::default_resource_id().into(), + }, + Vec::new(), + ) + .with_endpoint(endpoint) + .with_frame_send_timeout(Duration::from_millis(60)), + ); + asr.open_session().await.unwrap(); + + asr.consume_pcm_chunk(&vec![0x11u8; TARGET_AUDIO_CHUNK_BYTES]); + tokio::time::timeout(Duration::from_secs(2), first_audio_seen.notified()) + .await + .unwrap(); + assert_eq!( + asr.audio_coverage(), + ( + TARGET_AUDIO_CHUNK_BYTES as u64, + TARGET_AUDIO_CHUNK_BYTES as u64 + ) + ); + assert_eq!(asr.state.lock().frames_written, 1); + + let writer_guard = asr.writer.lock().await; + asr.consume_pcm_chunk(&vec![0x22u8; TARGET_AUDIO_CHUNK_BYTES + 200]); + let err = asr + .send_last_frame() + .await + .expect_err("must fail on write timeout"); + assert!(matches!(err, VolcengineASRError::ConnectionFailed(_))); + drop(writer_guard); + + tokio::time::sleep(Duration::from_millis(60)).await; + assert_eq!( + asr.audio_coverage(), + ( + TARGET_AUDIO_CHUNK_BYTES as u64, + (TARGET_AUDIO_CHUNK_BYTES * 2 + 200) as u64 + ) + ); + assert_eq!(asr.state.lock().frames_written, 1); + assert!(!asr.is_stream_complete()); + assert!( + received_frames.lock().iter().all(|f| !f.is_final()), + "NegativeSequence must never be transmitted after failed audio write" + ); + + shutdown_srv.notify_waiters(); + server_handle.await.unwrap(); + } + + #[tokio::test] + async fn buffered_audio_is_paced_and_precedes_negative_sequence() { + let frames = Arc::new(ParkingMutex::new( + Vec::<(Instant, frame::ParsedFrame)>::new(), + )); + let frames_srv = Arc::clone(&frames); + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + while let Some(Ok(Message::Binary(data))) = ws.next().await { + let parsed = frame::parse(&data).unwrap(); + let is_final = parsed.is_final(); + frames_srv.lock().push((Instant::now(), parsed)); + if is_final { + ws.send(Message::Binary(volc_final_response("火山完成").into())) + .await + .unwrap(); + let _ = ws.close(None).await; + break; + } + } + }) + .await; + + let asr = loopback_volcengine(endpoint); + asr.open_session().await.unwrap(); + let payload = vec![0x33u8; TARGET_AUDIO_CHUNK_BYTES * 3 + 320]; + asr.consume_pcm_chunk(&payload); + asr.send_last_frame().await.unwrap(); + + let transcript = asr.await_final_result().await.unwrap(); + assert_eq!(transcript.text, "火山完成"); + assert!(asr.is_stream_complete()); + assert_eq!( + asr.audio_coverage(), + (payload.len() as u64, payload.len() as u64) + ); + server_handle.await.unwrap(); + + let recorded = frames.lock(); + // FullClientRequest + 3 chunks + 1 leftover + 1 NegativeSequence = 6 frames. + assert_eq!(recorded.len(), 6); + assert_eq!( + recorded[0].1.message_type, + Some(MessageType::FullClientRequest) + ); + for i in 1..=4 { + assert_eq!( + recorded[i].1.message_type, + Some(MessageType::AudioOnlyRequest) + ); + assert!(!recorded[i].1.is_final()); + } + assert!(recorded[5].1.is_final()); + // 3 full chunks = 3 * 100ms intervals at 2x realtime -> total span across frames 1..=4 >= 220ms. + let pacing_span = recorded[4].0.saturating_duration_since(recorded[1].0); + assert!( + pacing_span >= Duration::from_millis(220), + "expected ~300 ms 2x realtime pacing, got {pacing_span:?}" + ); + } + + #[tokio::test] + async fn cancel_wakes_paced_send_worker_promptly() { + let frames = Arc::new(ParkingMutex::new(0usize)); + let first_audio = Arc::new(tokio::sync::Notify::new()); + let shutdown = Arc::new(tokio::sync::Notify::new()); + let frames_srv = Arc::clone(&frames); + let first_audio_srv = Arc::clone(&first_audio); + let shutdown_srv = Arc::clone(&shutdown); + + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Binary(data))) => { + let parsed = frame::parse(&data).unwrap(); + if parsed.message_type == Some(MessageType::AudioOnlyRequest) { + *frames_srv.lock() += 1; + first_audio_srv.notify_waiters(); + } + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_srv.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = loopback_volcengine(endpoint); + asr.open_session().await.unwrap(); + asr.consume_pcm_chunk(&vec![0x55u8; TARGET_AUDIO_CHUNK_BYTES * 40]); + tokio::time::timeout(Duration::from_secs(2), first_audio.notified()) + .await + .unwrap(); + + let started = Instant::now(); + asr.cancel(); + let res = tokio::time::timeout(Duration::from_millis(250), asr.await_final_result()) + .await + .expect("cancel must wake await_final_result promptly"); + assert!(matches!(res, Err(VolcengineASRError::NoFinalResult))); + assert!(started.elapsed() < Duration::from_millis(250)); + assert!(*frames.lock() <= 3); + + shutdown.notify_waiters(); + server_handle.await.unwrap(); + } + + #[tokio::test] + async fn record_send_failure_preserves_partial_across_concurrent_cancel() { + let asr = VolcengineStreamingASR::new( + VolcengineCredentials { + service: VolcengineService::Standard, + auth_mode: VolcengineAuthMode::AppIdToken, + app_id: "app".into(), + access_token: "token".into(), + resource_id: VolcengineCredentials::default_resource_id().into(), + }, + Vec::new(), + ); + let (tx, rx) = oneshot::channel(); + { + let mut st = asr.state.lock(); + st.is_connected = true; + st.last_partial_text = "已识别前缀".into(); + st.final_tx = Some(tx); + } + *asr.final_rx.lock() = Some(rx); + + asr.record_send_failure(VolcengineASRError::ConnectionFailed("broken".into())); + asr.cancel(); + + let transcript = asr + .await_final_result() + .await + .expect("partial transcript must survive concurrent cancel"); + assert_eq!(transcript.text, "已识别前缀"); + assert!(!asr.is_stream_complete()); + } } diff --git a/openless-all/app/crates/openless-core/src/asr/wav.rs b/openless-all/app/crates/openless-core/src/asr/wav.rs index 5ca5ede2f..2c2358c3d 100644 --- a/openless-all/app/crates/openless-core/src/asr/wav.rs +++ b/openless-all/app/crates/openless-core/src/asr/wav.rs @@ -1,17 +1,14 @@ //! WAV helpers for ASR providers that accept complete audio files. -/// Encode 16 kHz / mono / 16-bit little-endian PCM samples as a RIFF WAV file. -pub fn encode_wav_16k_mono(samples: &[i16]) -> Vec { +fn write_wav_16k_mono_header(wav: &mut Vec, data_size: u32) { let sample_rate: u32 = 16_000; let num_channels: u16 = 1; let bits_per_sample: u16 = 16; let bytes_per_sample = bits_per_sample as u32 / 8; let byte_rate = sample_rate * num_channels as u32 * bytes_per_sample; let block_align = num_channels * (bits_per_sample / 8); - let data_size = samples.len() as u32 * bytes_per_sample; - let chunk_size = 36 + data_size; + let chunk_size = 36u32.saturating_add(data_size); - let mut wav = Vec::with_capacity(44 + data_size as usize); wav.extend_from_slice(b"RIFF"); wav.extend_from_slice(&chunk_size.to_le_bytes()); wav.extend_from_slice(b"WAVE"); @@ -25,14 +22,33 @@ pub fn encode_wav_16k_mono(samples: &[i16]) -> Vec { wav.extend_from_slice(&bits_per_sample.to_le_bytes()); wav.extend_from_slice(b"data"); wav.extend_from_slice(&data_size.to_le_bytes()); +} + +/// Encode 16 kHz / mono / 16-bit little-endian PCM samples as a RIFF WAV file. +pub fn encode_wav_16k_mono(samples: &[i16]) -> Vec { + let data_size = samples.len() as u32 * 2; + let mut wav = Vec::with_capacity(44 + data_size as usize); + write_wav_16k_mono_header(&mut wav, data_size); for sample in samples { wav.extend_from_slice(&sample.to_le_bytes()); } wav } + +/// Encode canonical 16 kHz / mono / 16-bit little-endian PCM bytes as a RIFF WAV +/// without allocating an intermediate `Vec`. Any trailing odd byte is ignored. +pub fn encode_wav_16k_mono_pcm_bytes(pcm: &[u8]) -> Vec { + let aligned_len = (pcm.len() & !1).min((u32::MAX - 36) as usize); + let data_size = aligned_len as u32; + let mut wav = Vec::with_capacity(44 + aligned_len); + write_wav_16k_mono_header(&mut wav, data_size); + wav.extend_from_slice(&pcm[..aligned_len]); + wav +} + #[cfg(test)] mod tests { - use super::encode_wav_16k_mono; + use super::{encode_wav_16k_mono, encode_wav_16k_mono_pcm_bytes}; #[test] fn wav_header_matches_16k_mono_pcm() { @@ -57,4 +73,15 @@ mod tests { &[0x01, 0x00, 0xff, 0x7f, 0x00, 0x80, 0xfe, 0xff] ); } + + #[test] + fn pcm_bytes_encoding_matches_i16_samples_and_ignores_odd_tail() { + let samples = [1i16, i16::MAX, i16::MIN, -2i16]; + let mut bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + let expected = encode_wav_16k_mono(&samples); + assert_eq!(encode_wav_16k_mono_pcm_bytes(&bytes), expected); + + bytes.push(0xAB); + assert_eq!(encode_wav_16k_mono_pcm_bytes(&bytes), expected); + } } diff --git a/openless-all/app/crates/openless-core/src/asr/whisper.rs b/openless-all/app/crates/openless-core/src/asr/whisper.rs index 3b637c14d..d5af3ca11 100644 --- a/openless-all/app/crates/openless-core/src/asr/whisper.rs +++ b/openless-all/app/crates/openless-core/src/asr/whisper.rs @@ -5,7 +5,7 @@ use anyhow::{Context, Result}; use base64::Engine; use parking_lot::Mutex; -use crate::asr::wav::encode_wav_16k_mono; +use crate::asr::wav::encode_wav_16k_mono_pcm_bytes; use crate::asr::RawTranscript; const PCM_SAMPLE_RATE_HZ: u64 = 16_000; @@ -137,11 +137,8 @@ impl WhisperBatchASR { } /// The buffer must survive a failed transcribe: draining it up front - /// would lose the recording on credential or network errors. pub async fn transcribe(&self) -> Result { - // Clone instead of take: ~30s of 16 kHz 16-bit audio is ~960 KB, - // called once per session — acceptable. - let pcm = self.buffer.lock().clone(); + let pcm = std::mem::take(&mut *self.buffer.lock()); if pcm.is_empty() { return Ok(RawTranscript { text: String::new(), @@ -150,10 +147,19 @@ impl WhisperBatchASR { } let result = self.transcribe_inner(&pcm).await; - // Clear the buffer only on success. On failure the PCM stays: the - // coordinator gets Err, but a re-triggered stop can send again. - if result.is_ok() { - self.buffer.lock().clear(); + // Restore the buffer on failure (prepending ahead of any newly arrived + // audio) so a re-triggered stop can retry without losing PCM, while + // avoiding a full-buffer clone on the success path. + if result.is_err() { + let mut guard = self.buffer.lock(); + if guard.is_empty() { + *guard = pcm; + } else { + let trailing = std::mem::take(&mut *guard); + let mut combined = pcm; + combined.extend_from_slice(&trailing); + *guard = combined; + } } result } @@ -174,13 +180,7 @@ impl WhisperBatchASR { } async fn transcribe_chunk(&self, pcm: &[u8]) -> Result { - let samples: Vec = pcm - .as_chunks::<2>() - .0 - .iter() - .map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]])) - .collect(); - let wav = encode_wav_16k_mono(&samples); + let wav = encode_wav_16k_mono_pcm_bytes(pcm); let url = transcription_url(&self.base_url, self.endpoint_path.as_deref())?; let client = crate::net::http(); diff --git a/openless-all/app/crates/openless-core/src/asr/xfyun.rs b/openless-all/app/crates/openless-core/src/asr/xfyun.rs index 0b7c5335b..4c4b2fe45 100644 --- a/openless-all/app/crates/openless-core/src/asr/xfyun.rs +++ b/openless-all/app/crates/openless-core/src/asr/xfyun.rs @@ -18,7 +18,6 @@ //! enablement plus a `lang` param; initially fixed to Mandarin Chinese (`cn`). use std::collections::BTreeMap; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -29,14 +28,14 @@ use md5::{Digest as Md5Digest, Md5}; use parking_lot::Mutex as ParkingMutex; use serde_json::Value; use sha1::Sha1; -use tokio::net::TcpStream; -use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex, Notify}; +use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex}; +use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use crate::config::{TaskSpawner, TokioTaskSpawner}; +use super::stream_send::{send_ws_message_with_timeout, PacedSendClock, SharedWriter}; use super::{AudioConsumer, RawTranscript}; use crate::ports::{TextStreamChunk, TextStreamSink}; @@ -46,6 +45,7 @@ pub const DEFAULT_ENDPOINT: &str = "wss://rtasr.xfyun.cn/v1/ws"; pub const TARGET_AUDIO_CHUNK_BYTES: usize = 1_280; /// 16 kHz / 16-bit / mono = 32000 bytes/sec -> 32 bytes/ms. const BYTES_PER_MS: u64 = 32; +const FRAME_SEND_TIMEOUT: Duration = Duration::from_secs(5); const FINAL_RESULT_TIMEOUT: Duration = Duration::from_secs(12); /// Cap on the WebSocket handshake (TCP + TLS + HTTP upgrade) so a poor network cannot /// hang the hotkey thread. @@ -58,9 +58,10 @@ const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5); /// enablement and a corresponding `lang` param. const DEFAULT_LANG: &str = "cn"; -type WsStream = WebSocketStream>; -type WsSink = futures_util::stream::SplitSink; -type SharedWriter = Arc>>; +enum SendItem { + Audio(Vec), + End(oneshot::Sender>), +} #[derive(Clone, Debug)] pub struct XfyunCredentials { @@ -100,11 +101,20 @@ pub enum XfyunASRError { #[derive(Default)] struct SyncState { pending_audio: Vec, - bytes_sent: u64, + bytes_received: u64, + bytes_written: u64, started: bool, + ending: bool, + end_sent: bool, finished: bool, start: Option, final_tx: Option>>, + /// FIFO send queue shared across audio frames and the final end sentinel. + send_tx: Option>, + /// First send worker error, preserved so send_last_frame fails reliably instead + /// of sending an out-of-order end marker after an incomplete stream. + send_error: Option, + cancel_tx: Option>, /// seg_id -> final (type=0) segment text. A later result for the same seg_id /// overwrites the previous one. final_segments: BTreeMap, @@ -116,6 +126,8 @@ struct SyncState { pub struct XfyunStreamingASR { credentials: XfyunCredentials, + endpoint: String, + frame_send_timeout: Duration, task_spawner: Arc, state: ParkingMutex, writer: SharedWriter, @@ -123,14 +135,6 @@ pub struct XfyunStreamingASR { /// Handshake result channel: the receive loop sends Ok on `action=started` and Err /// on error. `open_session` awaits it to fail fast on auth rejection. handshake_tx: ParkingMutex>>>, - /// Audio send queue: consume_pcm_chunk enqueues, a single worker sends serially to - /// preserve ordering. - audio_tx: ParkingMutex>>>, - /// Total audio frames queued plus in flight in the worker. send_last_frame must - /// wait for this to reach zero before sending `{"end": true}`, otherwise the end - /// frame arrives first and the server drops the tail audio as data after "end". - pending_sends: Arc, - send_done: Arc, partial_sink: ParkingMutex>>, } @@ -145,18 +149,39 @@ impl XfyunStreamingASR { ) -> Self { Self { credentials, + endpoint: DEFAULT_ENDPOINT.to_string(), + frame_send_timeout: FRAME_SEND_TIMEOUT, task_spawner, state: ParkingMutex::new(SyncState::default()), writer: Arc::new(AsyncMutex::new(None)), final_rx: ParkingMutex::new(None), handshake_tx: ParkingMutex::new(None), - audio_tx: ParkingMutex::new(None), - pending_sends: Arc::new(AtomicUsize::new(0)), - send_done: Arc::new(Notify::new()), partial_sink: ParkingMutex::new(None), } } + #[cfg(test)] + pub(crate) fn with_endpoint(mut self, endpoint: impl Into) -> Self { + self.endpoint = endpoint.into(); + self + } + + #[cfg(test)] + pub(crate) fn with_frame_send_timeout(mut self, timeout: Duration) -> Self { + self.frame_send_timeout = timeout; + self + } + + pub fn audio_coverage(&self) -> (u64, u64) { + let st = self.state.lock(); + (st.bytes_written, st.bytes_received) + } + + pub fn is_stream_complete(&self) -> bool { + let st = self.state.lock(); + st.send_error.is_none() && st.end_sent && st.bytes_written == st.bytes_received + } + pub fn set_partial_sink(&self, sink: Arc) { *self.partial_sink.lock() = Some(sink); } @@ -164,7 +189,7 @@ impl XfyunStreamingASR { /// Builds the WebSocket URL with auth params: /// `wss://rtasr.xfyun.cn/v1/ws?appid=..&ts=..&signa=..&lang=cn`. pub fn connect_url(&self) -> String { - connect_url(&self.credentials) + connect_url_at(&self.endpoint, &self.credentials) } pub async fn open_session(self: &Arc) -> Result<(), XfyunASRError> { @@ -189,31 +214,101 @@ impl XfyunStreamingASR { *self.writer.lock().await = Some(write); let (final_tx, final_rx) = oneshot::channel(); - let (audio_tx, mut audio_rx) = mpsc::unbounded_channel::>(); + let (send_tx, mut send_rx) = mpsc::unbounded_channel::(); let (handshake_tx, handshake_rx) = oneshot::channel(); + let (cancel_tx, mut cancel_rx) = watch::channel(false); { let mut st = self.state.lock(); *st = SyncState::default(); st.start = Some(Instant::now()); st.final_tx = Some(final_tx); + st.send_tx = Some(send_tx); + st.cancel_tx = Some(cancel_tx); } *self.final_rx.lock() = Some(final_rx); - *self.audio_tx.lock() = Some(audio_tx); *self.handshake_tx.lock() = Some(handshake_tx); - self.pending_sends.store(0, Ordering::SeqCst); - // Audio worker: FIFO recv + serial send_binary, preserving chunk order. + // Send worker: drains audio chunks in strict FIFO order with realtime pacing + // before processing the end sentinel, so `{"end": true}` never overtakes audio. let writer_for_worker = Arc::clone(&self.writer); - let pending_for_worker = Arc::clone(&self.pending_sends); - let notify_for_worker = Arc::clone(&self.send_done); + let weak_self_for_worker = Arc::downgrade(self); + let frame_send_timeout = self.frame_send_timeout; let task_spawner = Arc::clone(&self.task_spawner); task_spawner.spawn(Box::pin(async move { - while let Some(chunk) = audio_rx.recv().await { - if let Err(e) = send_binary(&writer_for_worker, chunk).await { - log::error!("[xfyun-asr] audio frame send failed: {e}"); - } - if pending_for_worker.fetch_sub(1, Ordering::SeqCst) == 1 { - notify_for_worker.notify_waiters(); + let mut clock = PacedSendClock::new(); + loop { + let item = tokio::select! { + maybe_item = send_rx.recv() => match maybe_item { + Some(item) => item, + None => break, + }, + changed = cancel_rx.changed() => { + if changed.is_err() || *cancel_rx.borrow_and_update() { + break; + } + continue; + } + }; + + match item { + SendItem::Audio(chunk) => { + let Some(scheduled_start) = clock.wait_slot(&mut cancel_rx).await else { + break; + }; + let chunk_len = chunk.len(); + if let Err(ws_err) = send_ws_message_with_timeout( + &writer_for_worker, + Message::Binary(chunk.into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + { + let err = XfyunASRError::ConnectionFailed( + ws_err.into_message("websocket not open"), + ); + log::error!("[xfyun-asr] audio frame send failed: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err); + } + // Stop immediately on failure so SendItem::End is never written + // over an incomplete audio stream. + break; + } + if let Some(this) = weak_self_for_worker.upgrade() { + this.state.lock().bytes_written += chunk_len as u64; + } + clock.mark_sent(scheduled_start, chunk_len, BYTES_PER_MS, 1); + } + SendItem::End(ack_tx) => { + let result = send_ws_message_with_timeout( + &writer_for_worker, + Message::Binary(br#"{"end": true}"#.to_vec().into()), + frame_send_timeout, + &mut cancel_rx, + ) + .await + .map_err(|ws_err| { + XfyunASRError::ConnectionFailed( + ws_err.into_message("websocket not open"), + ) + }); + match &result { + Ok(()) => { + if let Some(this) = weak_self_for_worker.upgrade() { + this.state.lock().end_sent = true; + } + } + Err(err) => { + log::error!("[xfyun-asr] end frame send failed: {err}"); + if let Some(this) = weak_self_for_worker.upgrade() { + this.record_send_failure(err.clone()); + } + } + } + let _ = ack_tx.send(result); + break; + } } } })); @@ -277,58 +372,42 @@ impl XfyunStreamingASR { } pub async fn send_last_frame(&self) -> Result<(), XfyunASRError> { - // Wait for all in-flight audio frames, then send `{"end": true}` (800ms cap - // avoids waiting forever on an extreme network). - let drain_deadline = Instant::now() + Duration::from_millis(800); - while self.pending_sends.load(Ordering::SeqCst) > 0 { - let remaining = drain_deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - log::warn!( - "[xfyun-asr] send_last_frame: pending {} 帧未发送完,超时强制继续", - self.pending_sends.load(Ordering::SeqCst) - ); - break; - } - let _ = tokio::time::timeout(remaining, self.send_done.notified()).await; - } - - // Flush the tail audio shorter than one chunk. - let leftover = { + let (end_tx, end_rx) = oneshot::channel(); + { let mut st = self.state.lock(); - if st.pending_audio.is_empty() { - None - } else { - Some(std::mem::take(&mut st.pending_audio)) + if let Some(ref error) = st.send_error { + return Err(error.clone()); } - }; - if let Some(buf) = leftover { - let len = buf.len() as u64; - self.state.lock().bytes_sent += len; - let Some(tx) = self.audio_tx.lock().as_ref().cloned() else { + let Some(tx) = st.send_tx.take() else { return Err(XfyunASRError::ConnectionFailed("websocket not open".into())); }; - self.pending_sends.fetch_add(1, Ordering::SeqCst); - if tx.send(buf).is_err() { - self.pending_sends.fetch_sub(1, Ordering::SeqCst); + st.ending = true; + if !st.pending_audio.is_empty() { + let leftover = std::mem::take(&mut st.pending_audio); + if tx.send(SendItem::Audio(leftover)).is_err() { + return Err(st.send_error.clone().unwrap_or_else(|| { + XfyunASRError::ConnectionFailed("audio send queue closed".into()) + })); + } + } + if tx.send(SendItem::End(end_tx)).is_err() { + return Err(st.send_error.clone().unwrap_or_else(|| { + XfyunASRError::ConnectionFailed("audio send queue closed".into()) + })); } } - // Wait for the tail audio to be sent too, then send the end marker (contents - // per the docs; must be a binary message). - let drain_deadline = Instant::now() + Duration::from_millis(800); - while self.pending_sends.load(Ordering::SeqCst) > 0 { - let remaining = drain_deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - log::warn!( - "[xfyun-asr] send_last_frame: tail {} 帧未发送完,超时强制结束", - self.pending_sends.load(Ordering::SeqCst) - ); - break; + match end_rx.await { + Ok(result) => result, + Err(_) => { + let error = self.state.lock().send_error.clone().unwrap_or_else(|| { + XfyunASRError::ConnectionFailed( + "audio send worker stopped before end frame".into(), + ) + }); + Err(error) } - let _ = tokio::time::timeout(remaining, self.send_done.notified()).await; } - - send_binary(&self.writer, br#"{"end": true}"#.to_vec()).await } pub async fn await_final_result(&self) -> Result { @@ -359,20 +438,18 @@ impl XfyunStreamingASR { } pub fn cancel(&self) { - self.state.lock().pending_audio.clear(); + { + let mut st = self.state.lock(); + st.pending_audio.clear(); + st.send_tx = None; + if let Some(tx) = st.cancel_tx.as_ref() { + let _ = tx.send(true); + } + } // Release the handshake channel: if open_session is still waiting for started, // it immediately receives Err and returns. *self.handshake_tx.lock() = None; - // Closing the audio queue -> worker.recv() returns None -> exits, no longer - // holding the writer. - *self.audio_tx.lock() = None; - let writer = Arc::clone(&self.writer); - self.task_spawner.spawn(Box::pin(async move { - let mut guard = writer.lock().await; - if let Some(mut ws) = guard.take() { - let _ = ws.close().await; - } - })); + self.close_writer(); self.signal_error(XfyunASRError::NoFinalResult); } @@ -505,45 +582,92 @@ impl XfyunStreamingASR { /// otherwise error — consistent with the Volcengine / Bailian policy of "not /// losing recognized text when the server disconnects before final". fn finish_with_partial_or_error(&self, error: XfyunASRError) { - let has_partial = { - let st = self.state.lock(); - !st.last_result_text.trim().is_empty() || !st.partial_segments.is_empty() - }; - if has_partial { - self.finish_success(); - } else { - self.finish_error(error); - } + self.finish_with_partial_or_error_inner(error, false); } - fn finish_success(&self) { - let (tx, text, duration_ms) = { + fn finish_with_partial_or_error_inner(&self, error: XfyunASRError, is_send_failure: bool) { + enum Outcome { + AlreadyFinished, + Partial { + tx: Option>>, + text: String, + duration_ms: u64, + }, + Error { + tx: Option>>, + error: XfyunASRError, + }, + } + // Resolve state, send_error, finished flag, and final_tx in one critical section so + // concurrent cancel() cannot intercept final_tx ahead of partial salvage. + let outcome = { let mut st = self.state.lock(); - if st.finished { - return; + if is_send_failure && st.send_error.is_none() { + st.send_error = Some(error.clone()); } - st.finished = true; - st.pending_audio.clear(); - let text = if st.final_segments.is_empty() { - st.last_result_text.clone() - } else { - let segments: Vec = st.final_segments.values().cloned().collect(); - super::mimo::join_transcript_chunks(&segments) - }; - let duration_ms = if st.bytes_sent > 0 { - st.bytes_sent / BYTES_PER_MS + if st.finished { + st.send_tx = None; + if is_send_failure { + st.pending_audio.clear(); + } + Outcome::AlreadyFinished } else { - st.start - .map(|start| start.elapsed().as_millis() as u64) - .unwrap_or_default() - }; - (st.final_tx.take(), text, duration_ms) + st.finished = true; + st.pending_audio.clear(); + st.send_tx = None; + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } + let has_partial = + !st.last_result_text.trim().is_empty() || !st.partial_segments.is_empty(); + let tx = st.final_tx.take(); + if has_partial { + let text = if st.final_segments.is_empty() { + st.last_result_text.clone() + } else { + let segments: Vec = st.final_segments.values().cloned().collect(); + super::mimo::join_transcript_chunks(&segments) + }; + let audio_bytes = st.bytes_written.max(st.bytes_received); + let duration_ms = if audio_bytes > 0 { + audio_bytes / BYTES_PER_MS + } else { + st.start + .map(|start| start.elapsed().as_millis() as u64) + .unwrap_or_default() + }; + Outcome::Partial { + tx, + text, + duration_ms, + } + } else { + Outcome::Error { tx, error } + } + } }; - *self.audio_tx.lock() = None; - if let Some(tx) = tx { - let _ = tx.send(Ok(RawTranscript { text, duration_ms })); + match outcome { + Outcome::AlreadyFinished => {} + Outcome::Partial { + tx, + text, + duration_ms, + } => { + if let Some(tx) = tx { + let _ = tx.send(Ok(RawTranscript { text, duration_ms })); + } + self.close_writer(); + } + Outcome::Error { tx, error } => { + if let Some(handshake_tx) = self.handshake_tx.lock().take() { + let _ = handshake_tx.send(Err(error.clone())); + } + if let Some(tx) = tx { + let _ = tx.send(Err(error)); + } + self.close_writer(); + } } - self.close_writer(); } fn signal_error(&self, error: XfyunASRError) { @@ -553,14 +677,21 @@ impl XfyunStreamingASR { return; } st.finished = true; + st.send_tx = None; + if let Some(cancel_tx) = st.cancel_tx.as_ref() { + let _ = cancel_tx.send(true); + } st.final_tx.take() }; - *self.audio_tx.lock() = None; if let Some(tx) = tx { let _ = tx.send(Err(error)); } } + fn record_send_failure(&self, error: XfyunASRError) { + self.finish_with_partial_or_error_inner(error, true); + } + fn finish_error(&self, error: XfyunASRError) { // If an error occurs before the handshake completes (receive-loop network // interruption, server error message), it must reach open_session's handshake @@ -587,34 +718,25 @@ impl XfyunStreamingASR { impl AudioConsumer for XfyunStreamingASR { fn consume_pcm_chunk(&self, pcm: &[u8]) { - let chunks: Vec> = { - let mut st = self.state.lock(); - if !st.started || st.finished { - return; - } - st.pending_audio.extend_from_slice(pcm); - let mut out = Vec::new(); - while st.pending_audio.len() >= TARGET_AUDIO_CHUNK_BYTES { - let chunk: Vec = st.pending_audio.drain(..TARGET_AUDIO_CHUNK_BYTES).collect(); - st.bytes_sent += chunk.len() as u64; - out.push(chunk); - } - out - }; - if chunks.is_empty() { + let mut st = self.state.lock(); + if !st.started || st.ending { return; } - let Some(tx) = self.audio_tx.lock().as_ref().cloned() else { + st.bytes_received = st.bytes_received.saturating_add(pcm.len() as u64); + if st.finished || st.send_error.is_some() { + return; + } + let Some(tx) = st.send_tx.clone() else { return; }; + st.pending_audio.extend_from_slice(pcm); + let mut chunks = Vec::new(); + while st.pending_audio.len() >= TARGET_AUDIO_CHUNK_BYTES { + let chunk: Vec = st.pending_audio.drain(..TARGET_AUDIO_CHUNK_BYTES).collect(); + chunks.push(chunk); + } for chunk in chunks { - // pending_sends must be incremented before enqueueing: otherwise the worker - // could recv + send + decrement first, underflowing the usize counter. - self.pending_sends.fetch_add(1, Ordering::SeqCst); - if tx.send(chunk).is_err() { - if self.pending_sends.fetch_sub(1, Ordering::SeqCst) == 1 { - self.send_done.notify_waiters(); - } + if tx.send(SendItem::Audio(chunk)).is_err() { log::warn!("[xfyun-asr] audio queue closed; dropping subsequent frames"); return; } @@ -622,22 +744,10 @@ impl AudioConsumer for XfyunStreamingASR { } } -async fn send_binary(writer: &SharedWriter, data: Vec) -> Result<(), XfyunASRError> { - let mut guard = writer.lock().await; - let Some(ws) = guard.as_mut() else { - return Err(XfyunASRError::ConnectionFailed( - "websocket not open".to_string(), - )); - }; - ws.send(Message::Binary(data.into())) - .await - .map_err(|e| XfyunASRError::ConnectionFailed(e.to_string())) -} - -fn connect_url(credentials: &XfyunCredentials) -> String { +fn connect_url_at(endpoint: &str, credentials: &XfyunCredentials) -> String { let ts = chrono::Utc::now().timestamp().to_string(); let signa = compute_signa(&credentials.app_id, &credentials.api_key, &ts); - let mut url = url::Url::parse(DEFAULT_ENDPOINT).expect("static endpoint parses"); + let mut url = url::Url::parse(endpoint).expect("endpoint parses"); url.query_pairs_mut() .append_pair("appid", credentials.app_id.trim()) .append_pair("ts", &ts) @@ -646,6 +756,11 @@ fn connect_url(credentials: &XfyunCredentials) -> String { url.to_string() } +#[cfg(test)] +fn connect_url(credentials: &XfyunCredentials) -> String { + connect_url_at(DEFAULT_ENDPOINT, credentials) +} + /// `signa = Base64(HmacSHA1(MD5(appid + ts), apiKey))`, matching the Xfyun Open /// Platform docs formula. pub fn compute_signa(app_id: &str, api_key: &str, ts: &str) -> String { @@ -935,4 +1050,392 @@ mod tests { asr.finish_error(XfyunASRError::ConnectionFailed("again".into())); assert!(asr.handshake_tx.lock().is_none()); } + + async fn spawn_loopback_ws(handler: F) -> (String, tokio::task::JoinHandle<()>) + where + F: FnOnce(tokio_tungstenite::WebSocketStream) -> Fut + + Send + + 'static, + Fut: std::future::Future + Send + 'static, + { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind loopback listener"); + let addr = listener.local_addr().expect("local addr"); + let handle = tokio::spawn(async move { + let (stream, _) = listener.accept().await.expect("accept client"); + let ws = tokio_tungstenite::accept_async(stream) + .await + .expect("accept ws handshake"); + handler(ws).await; + }); + (format!("ws://{addr}"), handle) + } + + fn loopback_asr(endpoint: String) -> Arc { + Arc::new( + XfyunStreamingASR::new(XfyunCredentials { + app_id: "test-app".into(), + api_key: "test-key".into(), + }) + .with_endpoint(endpoint), + ) + } + + fn xfyun_result_json(text: &str, is_final: bool) -> String { + let data = serde_json::json!({ + "seg_id": 0, + "cn": { + "st": { + "type": if is_final { "0" } else { "1" }, + "rt": [{"ws": [{"cw": [{"w": text}]}]}] + } + } + }); + serde_json::json!({ + "action": "result", + "code": "0", + "data": data.to_string() + }) + .to_string() + } + + #[tokio::test] + async fn buffered_audio_is_paced_and_precedes_end_frame() { + let frames = Arc::new(ParkingMutex::new(Vec::<(Instant, Vec)>::new())); + let frames_srv = Arc::clone(&frames); + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + ws.send(Message::Text(r#"{"action":"started","code":"0"}"#.into())) + .await + .unwrap(); + while let Some(Ok(msg)) = ws.next().await { + if let Message::Binary(data) = msg { + let bytes = data.to_vec(); + let is_end = bytes == br#"{"end": true}"#; + frames_srv.lock().push((Instant::now(), bytes)); + if is_end { + ws.send(Message::Text(xfyun_result_json("测试完成", true).into())) + .await + .unwrap(); + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = loopback_asr(endpoint); + asr.open_session().await.expect("open session"); + + let mut payload = vec![0x11u8; TARGET_AUDIO_CHUNK_BYTES * 5 + 400]; + for (idx, byte) in payload.iter_mut().enumerate() { + *byte = (idx % 251) as u8; + } + asr.consume_pcm_chunk(&payload); + asr.send_last_frame().await.expect("send_last_frame"); + + let transcript = asr.await_final_result().await.expect("final transcript"); + assert_eq!(transcript.text, "测试完成"); + server_handle.await.expect("server join"); + + let recorded = frames.lock(); + assert_eq!(recorded.len(), 7, "5 chunks + 1 leftover + 1 end marker"); + for i in 0..5 { + assert_eq!(recorded[i].1.len(), TARGET_AUDIO_CHUNK_BYTES); + } + assert_eq!(recorded[5].1.len(), 400); + assert_eq!(recorded[6].1.as_slice(), br#"{"end": true}"#); + + let total_pacing_elapsed = recorded[5].0.saturating_duration_since(recorded[0].0); + assert!( + total_pacing_elapsed >= Duration::from_millis(140), + "expected ~200 ms pacing across 6 audio frames, got {total_pacing_elapsed:?}" + ); + for i in 0..4 { + let delta = recorded[i + 1].0.saturating_duration_since(recorded[i].0); + assert!( + delta >= Duration::from_millis(25), + "expected ~40 ms pacing between frame {i} and {}, got {delta:?}", + i + 1 + ); + } + } + + #[tokio::test] + async fn end_frame_waits_for_delayed_send_worker_instead_of_overtaking_audio() { + let frames = Arc::new(ParkingMutex::new(Vec::>::new())); + let frames_srv = Arc::clone(&frames); + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + ws.send(Message::Text(r#"{"action":"started","code":"0"}"#.into())) + .await + .unwrap(); + while let Some(Ok(msg)) = ws.next().await { + if let Message::Binary(data) = msg { + let bytes = data.to_vec(); + let is_end = bytes == br#"{"end": true}"#; + frames_srv.lock().push(bytes); + if is_end { + ws.send(Message::Text(xfyun_result_json("长缓冲完成", true).into())) + .await + .unwrap(); + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = loopback_asr(endpoint); + asr.open_session().await.expect("open session"); + + // 25 full chunks + 320 B tail spans ~1,000 ms of realtime pacing (> old 800 ms cap). + let payload = vec![0x22u8; TARGET_AUDIO_CHUNK_BYTES * 25 + 320]; + asr.consume_pcm_chunk(&payload); + asr.send_last_frame().await.expect("send_last_frame"); + + let transcript = asr.await_final_result().await.expect("final transcript"); + assert_eq!(transcript.text, "长缓冲完成"); + server_handle.await.expect("server join"); + + let recorded = frames.lock(); + assert_eq!(recorded.len(), 27, "25 chunks + leftover + end marker"); + assert_eq!(recorded.last().unwrap().as_slice(), br#"{"end": true}"#); + let audio_bytes: usize = recorded[..26].iter().map(Vec::len).sum(); + assert_eq!(audio_bytes, payload.len()); + } + + #[tokio::test] + async fn audio_frame_send_failure_stops_worker_and_fails_send_last_frame_without_end() { + let frames = Arc::new(ParkingMutex::new(Vec::>::new())); + let frame0_seen = Arc::new(tokio::sync::Notify::new()); + let shutdown_srv = Arc::new(tokio::sync::Notify::new()); + + let frames_srv = Arc::clone(&frames); + let frame0_seen_srv = Arc::clone(&frame0_seen); + let shutdown_srv_task = Arc::clone(&shutdown_srv); + + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + ws.send(Message::Text(r#"{"action":"started","code":"0"}"#.into())) + .await + .unwrap(); + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Binary(data))) => { + let bytes = data.to_vec(); + frames_srv.lock().push(bytes); + frame0_seen_srv.notify_waiters(); + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_srv_task.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = Arc::new( + XfyunStreamingASR::new(XfyunCredentials { + app_id: "test-app".into(), + api_key: "test-key".into(), + }) + .with_endpoint(endpoint) + .with_frame_send_timeout(Duration::from_millis(60)), + ); + asr.open_session().await.expect("open session"); + + asr.consume_pcm_chunk(&vec![0x33u8; TARGET_AUDIO_CHUNK_BYTES]); + tokio::time::timeout(Duration::from_secs(2), frame0_seen.notified()) + .await + .expect("frame 0 arrives"); + + // Case A: fail during send_last_frame without partial text -> both send_last_frame and + // await_final_result error, and `{"end": true}` is never transmitted even after lock release. + let writer_guard = asr.writer.lock().await; + asr.consume_pcm_chunk(&vec![0x44u8; TARGET_AUDIO_CHUNK_BYTES + 256]); + let send_err = asr + .send_last_frame() + .await + .expect_err("stalled frame must fail send_last_frame"); + assert!(matches!(send_err, XfyunASRError::ConnectionFailed(_))); + drop(writer_guard); + + tokio::time::sleep(Duration::from_millis(80)).await; + assert!(asr.await_final_result().await.is_err()); + { + let recorded = frames.lock(); + assert_eq!(recorded.len(), 1); + assert!( + recorded.iter().all(|f| f.as_slice() != br#"{"end": true}"#), + "end marker must not be sent after audio frame failure" + ); + } + shutdown_srv.notify_waiters(); + server_handle.await.expect("server join"); + + // Case B: when interim text already arrived before frame write failure, send_last_frame + // still returns Err (so long recordings replay) while await_final_result salvages partial. + let frames_b = Arc::new(ParkingMutex::new(Vec::>::new())); + let frame0_b = Arc::new(tokio::sync::Notify::new()); + let shutdown_b = Arc::new(tokio::sync::Notify::new()); + let frames_b_srv = Arc::clone(&frames_b); + let frame0_b_srv = Arc::clone(&frame0_b); + let shutdown_b_srv = Arc::clone(&shutdown_b); + + let (endpoint_b, server_handle_b) = spawn_loopback_ws(move |mut ws| async move { + ws.send(Message::Text(r#"{"action":"started","code":"0"}"#.into())) + .await + .unwrap(); + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Binary(data))) => { + frames_b_srv.lock().push(data.to_vec()); + ws.send(Message::Text(xfyun_result_json("部分文本", false).into())) + .await + .unwrap(); + frame0_b_srv.notify_waiters(); + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_b_srv.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr_b = Arc::new( + XfyunStreamingASR::new(XfyunCredentials { + app_id: "test-app".into(), + api_key: "test-key".into(), + }) + .with_endpoint(endpoint_b) + .with_frame_send_timeout(Duration::from_millis(60)), + ); + struct PartialSignalSink { + notify: Arc, + texts: ParkingMutex>, + } + impl TextStreamSink for PartialSignalSink { + fn publish(&self, chunk: TextStreamChunk) -> Result<(), crate::BackendError> { + self.texts.lock().push(chunk.text); + self.notify.notify_waiters(); + Ok(()) + } + } + let partial_seen = Arc::new(tokio::sync::Notify::new()); + let sink_b = Arc::new(PartialSignalSink { + notify: Arc::clone(&partial_seen), + texts: ParkingMutex::new(Vec::new()), + }); + asr_b.set_partial_sink(sink_b.clone()); + asr_b.open_session().await.expect("open session B"); + + asr_b.consume_pcm_chunk(&vec![0x55u8; TARGET_AUDIO_CHUNK_BYTES]); + tokio::time::timeout(Duration::from_secs(2), frame0_b.notified()) + .await + .expect("frame 0 B arrives"); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + if sink_b.texts.lock().last().map(String::as_str) == Some("部分文本") { + break; + } + partial_seen.notified().await; + } + }) + .await + .expect("partial snapshot recorded"); + + let writer_guard_b = asr_b.writer.lock().await; + asr_b.consume_pcm_chunk(&vec![0x66u8; TARGET_AUDIO_CHUNK_BYTES]); + assert!(asr_b.send_last_frame().await.is_err()); + drop(writer_guard_b); + + let salvaged = asr_b + .await_final_result() + .await + .expect("short session fallback salvages partial"); + assert_eq!(salvaged.text, "部分文本"); + assert!(frames_b + .lock() + .iter() + .all(|f| f.as_slice() != br#"{"end": true}"#)); + shutdown_b.notify_waiters(); + server_handle_b.await.expect("server join B"); + } + + #[tokio::test] + async fn cancel_wakes_paced_send_worker_promptly() { + let frames = Arc::new(ParkingMutex::new(Vec::>::new())); + let frame0_seen = Arc::new(tokio::sync::Notify::new()); + let shutdown_srv = Arc::new(tokio::sync::Notify::new()); + let frames_srv = Arc::clone(&frames); + let frame0_seen_srv = Arc::clone(&frame0_seen); + let shutdown_srv_task = Arc::clone(&shutdown_srv); + + let (endpoint, server_handle) = spawn_loopback_ws(move |mut ws| async move { + ws.send(Message::Text(r#"{"action":"started","code":"0"}"#.into())) + .await + .unwrap(); + loop { + tokio::select! { + msg = ws.next() => match msg { + Some(Ok(Message::Binary(data))) => { + frames_srv.lock().push(data.to_vec()); + frame0_seen_srv.notify_waiters(); + } + Some(Ok(Message::Close(_))) | None => break, + _ => {} + }, + _ = shutdown_srv_task.notified() => { + let _ = ws.close(None).await; + break; + } + } + } + }) + .await; + + let asr = loopback_asr(endpoint); + asr.open_session().await.expect("open session"); + + // 100 chunks = ~4,000 ms of paced audio queued; cancel must interrupt pacing promptly. + asr.consume_pcm_chunk(&vec![0x77u8; TARGET_AUDIO_CHUNK_BYTES * 100]); + tokio::time::timeout(Duration::from_secs(2), frame0_seen.notified()) + .await + .expect("frame 0 arrives"); + + let started_cancel = Instant::now(); + asr.cancel(); + let res = tokio::time::timeout(Duration::from_millis(250), asr.await_final_result()) + .await + .expect("cancel resolves await_final_result promptly"); + assert!(matches!(res, Err(XfyunASRError::NoFinalResult))); + assert!(started_cancel.elapsed() < Duration::from_millis(250)); + assert!(asr.send_last_frame().await.is_err()); + + tokio::time::sleep(Duration::from_millis(80)).await; + let received_count = frames.lock().len(); + assert!( + received_count <= 5, + "expected worker to stop promptly after cancel, received {received_count} frames" + ); + assert!(frames + .lock() + .iter() + .all(|f| f.as_slice() != br#"{"end": true}"#)); + + shutdown_srv.notify_waiters(); + server_handle.await.expect("server join"); + } } diff --git a/openless-all/app/crates/openless-core/src/assistant/budget.rs b/openless-all/app/crates/openless-core/src/assistant/budget.rs index 6ea7b28fb..3b1ac99ef 100644 --- a/openless-all/app/crates/openless-core/src/assistant/budget.rs +++ b/openless-all/app/crates/openless-core/src/assistant/budget.rs @@ -516,6 +516,7 @@ fn intent_text(message: &AskModelMessage) -> &str { } } +#[cfg(test)] fn message_text(message: &AskModelMessage) -> String { message .parts diff --git a/openless-all/app/crates/openless-core/src/audio.rs b/openless-all/app/crates/openless-core/src/audio.rs index 9c4e3431c..782315cd9 100644 --- a/openless-all/app/crates/openless-core/src/audio.rs +++ b/openless-all/app/crates/openless-core/src/audio.rs @@ -49,9 +49,18 @@ impl FarEndQueue { } let clean: Vec = samples .iter() - .map(|sample| if sample.is_finite() { sample.clamp(-1.0, 1.0) } else { 0.0 }) + .map(|sample| { + if sample.is_finite() { + sample.clamp(-1.0, 1.0) + } else { + 0.0 + } + }) .collect(); - let mut queue = self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut queue = self + .inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); queue.push_back(FarEndFrame { rate, channels, @@ -59,14 +68,19 @@ impl FarEndQueue { }); let mut total: usize = queue.iter().map(|frame| frame.samples.len()).sum(); while total > FAR_END_QUEUE_LIMIT { - let Some(dropped) = queue.pop_front() else { break }; + let Some(dropped) = queue.pop_front() else { + break; + }; total -= dropped.samples.len(); } } /// DSP 线程调用:取走全部待处理参考帧(保持到达顺序)。 fn drain(&self) -> Vec { - let mut queue = self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut queue = self + .inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); queue.drain(..).collect() } @@ -223,9 +237,8 @@ impl AudioProcessor { let key = (frame.rate, rate); if self.light_reference_rate != Some(key) { self.light_reference_rate = Some(key); - self.light_reference_resampler = Some( - crate::audio_dsp::SpeechResampler::new(frame.rate, rate), - ); + self.light_reference_resampler = + Some(crate::audio_dsp::SpeechResampler::new(frame.rate, rate)); } let mono = downmix_to_mono(&frame.samples, frame.channels); if let Some(resampler) = self.light_reference_resampler.as_mut() { @@ -239,12 +252,7 @@ impl AudioProcessor { Some(self.light_reference_pending.drain(..take).collect()) } - fn apply_light_aec( - &mut self, - input: &[f32], - channels: usize, - reference: &[f32], - ) -> Vec { + fn apply_light_aec(&mut self, input: &[f32], channels: usize, reference: &[f32]) -> Vec { if channels <= 1 { return self .light_aec @@ -505,7 +513,6 @@ impl EnhancedStream { self.dsp.set_far_end_audio(&reference); } - fn frames(&mut self, finish: bool) -> &[f32] { self.pending.extend(&self.working); if finish { @@ -556,10 +563,85 @@ fn pcm_chunk(samples: &[f32]) -> Option { /// Native adapters convert their device sample format to `f32` and pass each /// callback here. The output contract is always 16 kHz, mono, signed 16-bit /// little-endian PCM plus the UI level used by both hosts. +const ANTI_ALIAS_CUTOFF_RATIO: f64 = 0.42; + +#[derive(Debug, Clone, Copy)] +struct Biquad { + b0: f64, + b1: f64, + b2: f64, + a1: f64, + a2: f64, + z1: f64, + z2: f64, +} + +impl Biquad { + fn lowpass(normalized_cutoff: f64, section_index: usize, total_order: usize) -> Self { + let theta = + std::f64::consts::PI * (2 * section_index + 1) as f64 / (2 * total_order) as f64; + let alpha = 2.0 * theta.sin(); + let k = (std::f64::consts::PI * normalized_cutoff).tan(); + let k2 = k * k; + let a0 = 1.0 + alpha * k + k2; + let b0 = k2 / a0; + Self { + b0, + b1: 2.0 * b0, + b2: b0, + a1: 2.0 * (k2 - 1.0) / a0, + a2: (1.0 - alpha * k + k2) / a0, + z1: 0.0, + z2: 0.0, + } + } + + #[inline] + fn process_sample(&mut self, x: f64) -> f64 { + let y = self.b0 * x + self.z1; + self.z1 = self.b1 * x - self.a1 * y + self.z2; + self.z2 = self.b2 * x - self.a2 * y; + y + } +} + +#[derive(Debug, Clone)] +struct AntiAliasFilter { + source_rate: u32, + target_rate: u32, + sections: [Biquad; 4], +} + +impl AntiAliasFilter { + fn new(source_rate: u32, target_rate: u32) -> Self { + let normalized_cutoff = + (ANTI_ALIAS_CUTOFF_RATIO * target_rate as f64 / source_rate as f64).clamp(1e-4, 0.49); + let sections = std::array::from_fn(|idx| Biquad::lowpass(normalized_cutoff, idx, 8)); + Self { + source_rate, + target_rate, + sections, + } + } + + fn process_sample(&mut self, sample: f32) -> f32 { + let mut x = if sample.is_finite() { + sample as f64 + } else { + 0.0 + }; + for section in &mut self.sections { + x = section.process_sample(x); + } + x as f32 + } +} + #[derive(Debug, Default)] pub struct PcmNormalizer { resample_phase: f64, last_sample: f32, + anti_alias: Option, } pub fn encode_dictation_wav(pcm_i16_le: &[u8]) -> Result, crate::BackendError> { @@ -652,6 +734,68 @@ pub fn decode_dictation_wav(wav: &[u8]) -> Result<&[u8], crate::BackendError> { pcm.ok_or_else(invalid) } +/// Inspect only the header and metadata of an app-generated canonical WAV. +pub fn canonical_archive_pcm_len(file: &mut std::fs::File) -> Result { + use std::io::{Read, Seek, SeekFrom}; + let mut inspect = || -> std::io::Result { + file.seek(SeekFrom::Start(0))?; + let mut header = [0; 44]; + file.read_exact(&mut header)?; + let bytes = u32::from_le_bytes(header[40..44].try_into().unwrap()); + let riff = u32::from_le_bytes(header[4..8].try_into().unwrap()); + if &header[..4] != b"RIFF" + || &header[8..20] != b"WAVEfmt \x10\0\0\0" + || header[20..22] != 1u16.to_le_bytes() + || header[22..24] != 1u16.to_le_bytes() + || header[24..28] != 16_000u32.to_le_bytes() + || header[28..32] != 32_000u32.to_le_bytes() + || header[32..34] != 2u16.to_le_bytes() + || header[34..36] != 16u16.to_le_bytes() + || &header[36..40] != b"data" + || !bytes.is_multiple_of(2) + || bytes.checked_add(36) != Some(riff) + || file.metadata()?.len() != 44 + u64::from(bytes) + { + return Err(std::io::Error::other( + "recording archive is not a complete canonical PCM WAV", + )); + } + Ok(u64::from(bytes)) + }; + inspect().map_err(|error| { + crate::BackendError::new(crate::BackendErrorCode::Persistence, error.to_string()) + }) +} + +/// Read one PCM range without allocating or scanning the rest of the archive. +pub fn read_canonical_archive_pcm_range( + file: &mut std::fs::File, + offset: u64, + len: usize, +) -> Result, crate::BackendError> { + use std::io::{Read, Seek, SeekFrom}; + let bytes = canonical_archive_pcm_len(file)?; + if !offset.is_multiple_of(2) + || !len.is_multiple_of(2) + || offset > bytes + || len as u64 > bytes - offset + { + return Err(crate::BackendError::new( + crate::BackendErrorCode::Persistence, + "recording PCM range is out of bounds", + )); + } + let mut read = || -> std::io::Result> { + file.seek(SeekFrom::Start(44 + offset))?; + let mut pcm = vec![0; len]; + file.read_exact(&mut pcm)?; + Ok(pcm) + }; + read().map_err(|error| { + crate::BackendError::new(crate::BackendErrorCode::Persistence, error.to_string()) + }) +} + impl PcmNormalizer { pub fn process( &mut self, @@ -679,35 +823,60 @@ impl PcmNormalizer { return Vec::new(); } if source_rate == target_rate { + self.anti_alias = None; self.last_sample = *samples.last().unwrap_or(&0.0); return samples.to_vec(); } + let filtered; + let interpolation_input: &[f32] = if source_rate > target_rate { + let filter = match self.anti_alias.as_mut() { + Some(existing) + if existing.source_rate == source_rate + && existing.target_rate == target_rate => + { + existing + } + _ => { + self.anti_alias = Some(AntiAliasFilter::new(source_rate, target_rate)); + self.anti_alias.as_mut().expect("anti-alias filter set") + } + }; + filtered = samples + .iter() + .map(|&sample| filter.process_sample(sample)) + .collect::>(); + &filtered + } else { + self.anti_alias = None; + samples + }; + let step = source_rate as f64 / target_rate as f64; let mut phase = self.resample_phase; let mut output = Vec::with_capacity( - ((samples.len() as f64) / step).ceil() as usize + usize::from(step < 1.0), + ((interpolation_input.len() as f64) / step).ceil() as usize + usize::from(step < 1.0), ); - while phase < samples.len() as f64 { + while phase < interpolation_input.len() as f64 { let floor = phase.floor() as isize; let fraction = (phase - phase.floor()) as f32; let left = if floor < 0 { self.last_sample } else { - samples[floor as usize] + interpolation_input[floor as usize] }; let right_index = (floor + 1) as usize; - if right_index >= samples.len() { + if right_index >= interpolation_input.len() { output.push(left); phase += step; break; } - let right = samples[right_index]; + let right = interpolation_input[right_index]; output.push(left + (right - left) * fraction); phase += step; } - self.resample_phase = (phase - samples.len() as f64).max(0.0); - self.last_sample = *samples.last().unwrap_or(&0.0); + self.resample_phase = (phase - interpolation_input.len() as f64).max(0.0); + self.last_sample = *interpolation_input.last().unwrap_or(&0.0); output } } @@ -763,6 +932,41 @@ mod tests { .collect() } + #[test] + fn canonical_archive_reads_sparse_tail_with_bounded_buffer_and_rejects_corruption() { + use std::io::{Seek, SeekFrom, Write}; + let path = + std::env::temp_dir().join(format!("openless-range-{}.wav", uuid::Uuid::new_v4())); + let bytes = 32_000 * 31 * 60u32; + let mut header = encode_dictation_wav(&[]).unwrap(); + header[4..8].copy_from_slice(&(36 + bytes).to_le_bytes()); + header[40..44].copy_from_slice(&bytes.to_le_bytes()); + let mut file = std::fs::OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .open(&path) + .unwrap(); + file.write_all(&header).unwrap(); + file.set_len(44 + u64::from(bytes)).unwrap(); + file.seek(SeekFrom::End(-4)).unwrap(); + file.write_all(&[1, 2, 3, 4]).unwrap(); + assert_eq!( + canonical_archive_pcm_len(&mut file).unwrap(), + u64::from(bytes) + ); + assert_eq!( + read_canonical_archive_pcm_range(&mut file, u64::from(bytes) - 4, 4).unwrap(), + [1, 2, 3, 4] + ); + assert!(read_canonical_archive_pcm_range(&mut file, u64::from(bytes) - 2, 4).is_err()); + assert!(read_canonical_archive_pcm_range(&mut file, 1, 2).is_err()); + file.set_len(46).unwrap(); + assert!(canonical_archive_pcm_len(&mut file).is_err()); + drop(file); + std::fs::remove_file(path).unwrap(); + } + #[test] fn normalizer_downmixes_quantizes_and_scales_level() { let mut normalizer = PcmNormalizer::default(); @@ -804,9 +1008,7 @@ mod tests { let first = processor.light_reference_at(&queue, 48_000, 480).unwrap(); assert_eq!(first.len(), 480); assert!(!processor.light_reference_pending.is_empty()); - let second = processor - .light_reference_at(&queue, 48_000, 480) - .unwrap(); + let second = processor.light_reference_at(&queue, 48_000, 480).unwrap(); assert!(!second.is_empty()); } @@ -839,7 +1041,10 @@ mod tests { }; for mode in [crate::AecMode::Light, crate::AecMode::Model] { let mut selected = AudioProcessor::new(AudioProcessingConfig { - dsp: crate::AudioDspConfig { aec_mode: mode, ..config.dsp }, + dsp: crate::AudioDspConfig { + aec_mode: mode, + ..config.dsp + }, ..config }); let mut standalone = AudioProcessor::new(config); @@ -847,7 +1052,9 @@ mod tests { assert_eq!(selected.config.dsp.aec_mode, crate::AecMode::Off); let microphone = vec![0.2; 480]; let reference = vec![0.1; 240]; - for input_reference in [Some(reference.as_slice()), None, Some(reference.as_slice())] { + for input_reference in + [Some(reference.as_slice()), None, Some(reference.as_slice())] + { assert_eq!( selected.process_with_reference(µphone, 2, 48_000, input_reference), standalone.process_with_reference(µphone, 2, 48_000, input_reference), @@ -955,4 +1162,149 @@ mod tests { assert!(decode_dictation_wav(&wav).is_err()); } } + + fn dft_magnitude(samples: &[f32], sample_rate: u32, freq_hz: f32) -> f64 { + let mut cos_sum = 0.0f64; + let mut sin_sum = 0.0f64; + let w = 2.0 * std::f64::consts::PI * freq_hz as f64 / sample_rate as f64; + for (idx, &sample) in samples.iter().enumerate() { + let angle = w * idx as f64; + cos_sum += sample as f64 * angle.cos(); + sin_sum += sample as f64 * angle.sin(); + } + (cos_sum.hypot(sin_sum) * 2.0) / samples.len().max(1) as f64 + } + + fn downsampled_f32(input: &[f32], source_rate: u32, chunk_len: usize) -> Vec { + let mut normalizer = PcmNormalizer::default(); + let mut out = Vec::new(); + for chunk in input.chunks(chunk_len.max(1)) { + if let Some(normalized) = normalizer.process(chunk, 1, source_rate) { + out.extend( + decode(&normalized.pcm_i16_le) + .into_iter() + .map(|s| s as f32 / i16::MAX as f32), + ); + } + } + out + } + + #[test] + fn normalizer_downsampling_suppresses_out_of_band_aliasing() { + for source_rate in [44_100u32, 48_000, 96_000] { + let len = source_rate as usize / 2; // 0.5 s -> 8,000 samples @ 16 kHz + let chunk_len = source_rate as usize / 50; // ~20 ms callbacks + let mix: Vec = (0..len) + .map(|i| { + let t = i as f64 / source_rate as f64; + let pass = 0.4 * (2.0 * std::f64::consts::PI * 1_000.0 * t).sin(); + let alias = 0.4 * (2.0 * std::f64::consts::PI * 12_000.0 * t).sin(); + (pass + alias) as f32 + }) + .collect(); + + let output = downsampled_f32(&mix, source_rate, chunk_len); + let steady = &output[1_600..]; + let mag_1k = dft_magnitude(steady, DICTATION_SAMPLE_RATE, 1_000.0); + let mag_alias_4k = dft_magnitude(steady, DICTATION_SAMPLE_RATE, 4_000.0); + assert!( + mag_1k > 0.30, + "expected 1 kHz passband retention at {source_rate} Hz, got {mag_1k}" + ); + assert!( + mag_alias_4k < 0.01, + "expected 12 kHz -> 4 kHz alias suppression at {source_rate} Hz, got {mag_alias_4k}" + ); + + // Verify upper speech band (4 kHz) itself remains essentially unattenuated. + let speech_4k: Vec = (0..len) + .map(|i| { + let t = i as f64 / source_rate as f64; + (0.4 * (2.0 * std::f64::consts::PI * 4_000.0 * t).sin()) as f32 + }) + .collect(); + let speech_out = downsampled_f32(&speech_4k, source_rate, chunk_len); + let mag_speech_4k = dft_magnitude(&speech_out[1_600..], DICTATION_SAMPLE_RATE, 4_000.0); + assert!( + mag_speech_4k > 0.35, + "expected 4 kHz passband preservation at {source_rate} Hz, got {mag_speech_4k}" + ); + } + } + + #[test] + fn normalizer_48k_to_16k_matches_across_callback_boundaries() { + let input: Vec = (0..9_600) + .map(|i| { + let t = i as f64 / 48_000.0; + (0.25 * (2.0 * std::f64::consts::PI * 1_000.0 * t).sin() + + 0.25 * (2.0 * std::f64::consts::PI * 3_000.0 * t).sin() + + 0.25 * (2.0 * std::f64::consts::PI * 11_000.0 * t).sin()) + as f32 + }) + .collect(); + + let mut single = PcmNormalizer::default(); + let whole = decode( + &single + .process(&input, 1, 48_000) + .expect("single chunk") + .pcm_i16_le, + ); + + let mut chunked_normalizer = PcmNormalizer::default(); + let mut chunked = Vec::new(); + let sizes = [480, 123, 960, 77, 1_024, 333]; + let mut offset = 0; + let mut idx = 0; + while offset < input.len() { + let take = sizes[idx % sizes.len()].min(input.len() - offset); + idx += 1; + if let Some(out) = chunked_normalizer.process(&input[offset..offset + take], 1, 48_000) + { + chunked.extend(decode(&out.pcm_i16_le)); + } + offset += take; + } + + assert_eq!(whole.len(), 3_200); + assert_eq!(chunked, whole); + } + + #[test] + fn normalizer_anti_alias_filter_survives_non_finite_samples() { + let mut normalizer = PcmNormalizer::default(); + let mut dirty = vec![0.0f32; 480]; + dirty[12] = f32::NAN; + dirty[87] = f32::INFINITY; + dirty[201] = f32::NEG_INFINITY; + let _ = normalizer.process(&dirty, 1, 48_000); + + // Next clean 1 kHz buffer at 48 kHz must remain finite and recover steady tone. + let clean: Vec = (0..19_200) + .map(|i| { + let t = i as f64 / 48_000.0; + (0.4 * (2.0 * std::f64::consts::PI * 1_000.0 * t).sin()) as f32 + }) + .collect(); + let out = normalizer.process(&clean, 1, 48_000).expect("clean chunk"); + let decoded: Vec = decode(&out.pcm_i16_le) + .into_iter() + .map(|s| s as f32 / i16::MAX as f32) + .collect(); + assert!(decoded.iter().all(|s| s.is_finite())); + let mag_1k = dft_magnitude(&decoded[1_600..], DICTATION_SAMPLE_RATE, 1_000.0); + assert!( + mag_1k > 0.35, + "expected recovery after NaN/Inf, got {mag_1k}" + ); + + // Switching to passthrough (16 kHz) clears the anti-alias filter cleanly. + assert!(normalizer.anti_alias.is_some()); + let pass = vec![0.25f32; 320]; + let pass_out = normalizer.process(&pass, 1, 16_000).expect("16k pass"); + assert_eq!(decode(&pass_out.pcm_i16_le).len(), 320); + assert!(normalizer.anti_alias.is_none()); + } } diff --git a/openless-all/app/crates/openless-core/src/auxiliary.rs b/openless-all/app/crates/openless-core/src/auxiliary.rs index bfd491f35..092156505 100644 --- a/openless-all/app/crates/openless-core/src/auxiliary.rs +++ b/openless-all/app/crates/openless-core/src/auxiliary.rs @@ -74,6 +74,21 @@ pub trait AuxiliaryApi: Send + Sync { &self, pcm: Vec, ) -> BoxFuture<'static, Result>; + + fn retranscribe_archive( + &self, + _archive: Arc, + ) -> BoxFuture<'static, Result> { + Box::pin(async { + Err(RetranscriptionFailure { + error: BackendError::new( + BackendErrorCode::Unsupported, + "archive retranscription is not supported", + ), + attempted_asr: None, + }) + }) + } } pub(crate) struct AuxiliaryService { @@ -284,73 +299,166 @@ impl AuxiliaryApi for AuxiliaryService { duration_ms: 0, asr: fallback_label.clone(), }; - for pcm in pcm.chunks(chunk_bytes) { - let session_id = SessionId::new(); - let pace_replay = context.asr.provider_type == "volcengine"; - let session = service - .transcription - .start( - session_id, - Arc::clone(&context), - Arc::new(DiscardTextStream), - ) + for chunk in pcm.chunks(chunk_bytes) { + let output = + retranscribe_segment(&service, &context, &fallback_label, chunk).await?; + if !combined.text.is_empty() && !output.text.is_empty() { + combined.text.push('\n'); + } + combined.text.push_str(&output.text); + combined.duration_ms += output.duration_ms; + combined.asr = output.asr; + } + if long_recording { + combined.duration_ms = crate::long_recording::duration_ms(pcm.len() as u64); + } + Ok(combined) + }) + } + + fn retranscribe_archive( + &self, + archive: Arc, + ) -> BoxFuture<'static, Result> { + let service = self.clone_for_future(); + Box::pin(async move { + if let Some(error) = archive.write_error() { + return Err(RetranscriptionFailure { + error: BackendError::new(BackendErrorCode::Persistence, error), + attempted_asr: None, + }); + } + let total_bytes = + archive + .pcm_byte_len() .await - .map_err(|mut error| { - error.retryable = !is_terminal_foundry_error(&error); - RetranscriptionFailure { - error, - attempted_asr: Some(fallback_label.clone()), - } + .map_err(|error| RetranscriptionFailure { + error, + attempted_asr: None, })?; - let attempted_asr = session - .asr_call_label() - .unwrap_or_else(|| fallback_label.clone()); - let mut guard = RetranscriptionCancelGuard::new( - Arc::clone(&session), - Arc::clone(&service.task_spawner), - ); - if pace_replay { - // The realtime endpoint expects audio over time, including when - // playback is sourced from an archived recording. - let mut chunks = pcm.chunks(crate::asr::volcengine::TARGET_AUDIO_CHUNK_BYTES); - if let Some(first) = chunks.next() { - session.consume_pcm_chunk(first); - } - for chunk in chunks { - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - session.consume_pcm_chunk(chunk); - } - } else { - session.consume_pcm_chunk(pcm); + if total_bytes == 0 || !total_bytes.is_multiple_of(2) { + return Err(RetranscriptionFailure { + error: BackendError::new( + BackendErrorCode::InvalidArgument, + "PCM must contain 16-bit little-endian samples", + ), + attempted_asr: None, + }); + } + let context = service + .capture_retranscription_context() + .await + .map_err(|error| RetranscriptionFailure { + error, + attempted_asr: None, + })?; + let fallback_label = + AsrCallLabel::new(context.asr.provider_type.clone(), context.asr.model.clone()); + let long_recording = crate::long_recording::duration_ms(total_bytes) + > crate::long_recording::THRESHOLD_MS; + let chunk_bytes = if long_recording { + crate::long_recording::RECOVERY_CHUNK_BYTES as u64 + } else { + total_bytes + }; + let mut combined = RetranscriptionResult { + text: String::new(), + duration_ms: 0, + asr: fallback_label.clone(), + }; + let mut offset = 0u64; + while offset < total_bytes { + let seg_len = chunk_bytes.min(total_bytes - offset) as usize; + let pcm = archive + .read_pcm_range(offset, seg_len) + .await + .map_err(|error| RetranscriptionFailure { + error, + attempted_asr: Some(fallback_label.clone()), + })?; + if pcm.len() != seg_len { + return Err(RetranscriptionFailure { + error: BackendError::new( + BackendErrorCode::Persistence, + "recording archive returned an incomplete segment", + ), + attempted_asr: Some(fallback_label.clone()), + }); } - let result = session.finish().await; - guard.disarm(); - match result { - Ok(output) => { - if !combined.text.is_empty() && !output.text.is_empty() { - combined.text.push('\n'); - } - combined.text.push_str(&output.text); - combined.duration_ms += output.duration_ms; - combined.asr = attempted_asr; - } - Err(mut error) => { - error.retryable = !is_terminal_foundry_error(&error); - return Err(RetranscriptionFailure { - error, - attempted_asr: Some(attempted_asr), - }); - } + let output = + retranscribe_segment(&service, &context, &fallback_label, &pcm).await?; + if !combined.text.is_empty() && !output.text.is_empty() { + combined.text.push('\n'); } + combined.text.push_str(&output.text); + combined.duration_ms += output.duration_ms; + combined.asr = output.asr; + offset += seg_len as u64; } if long_recording { - combined.duration_ms = crate::long_recording::duration_ms(pcm.len() as u64); + combined.duration_ms = crate::long_recording::duration_ms(total_bytes); } Ok(combined) }) } } +async fn retranscribe_segment( + service: &AuxiliaryService, + context: &Arc, + fallback_label: &AsrCallLabel, + pcm: &[u8], +) -> Result { + let session_id = SessionId::new(); + let pace_replay = context.asr.provider_type == "volcengine"; + let session = service + .transcription + .start(session_id, Arc::clone(context), Arc::new(DiscardTextStream)) + .await + .map_err(|mut error| { + error.retryable = !is_terminal_foundry_error(&error); + RetranscriptionFailure { + error, + attempted_asr: Some(fallback_label.clone()), + } + })?; + let attempted_asr = session + .asr_call_label() + .unwrap_or_else(|| fallback_label.clone()); + let mut guard = + RetranscriptionCancelGuard::new(Arc::clone(&session), Arc::clone(&service.task_spawner)); + if pace_replay { + // The realtime endpoint expects audio over time, including when + // playback is sourced from an archived recording. + let mut chunks = pcm.chunks(crate::asr::volcengine::TARGET_AUDIO_CHUNK_BYTES); + if let Some(first) = chunks.next() { + session.consume_pcm_chunk(first); + } + for chunk in chunks { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + session.consume_pcm_chunk(chunk); + } + } else { + session.consume_pcm_chunk(pcm); + } + let result = session.finish().await; + guard.disarm(); + match result { + Ok(output) => Ok(RetranscriptionResult { + text: output.text, + duration_ms: output.duration_ms, + asr: attempted_asr, + }), + Err(mut error) => { + error.retryable = !is_terminal_foundry_error(&error); + Err(RetranscriptionFailure { + error, + attempted_asr: Some(attempted_asr), + }) + } + } +} + fn is_terminal_foundry_error(error: &BackendError) -> bool { error.details.as_ref().is_some_and(|details| { details.get("terminal").and_then(serde_json::Value::as_str) == Some("foundry_fallback") @@ -666,4 +774,84 @@ mod tests { assert!(transcription.pcm().is_empty()); let _ = std::fs::remove_file(path); } + + #[tokio::test] + async fn retranscribe_archive_reads_ranged_chunks_without_loading_whole_pcm() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct RangedArchive { + pcm: Vec, + read_pcm_calls: AtomicUsize, + range_calls: std::sync::Mutex>, + } + + impl crate::ports::RecordingArchive for RangedArchive { + fn is_available(&self) -> bool { + true + } + + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let len = self.pcm.len() as u64; + Box::pin(async move { Ok(len) }) + } + + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { + self.read_pcm_calls.fetch_add(1, Ordering::AcqRel); + Box::pin(async { + Err(BackendError::new( + BackendErrorCode::Internal, + "retranscribe_archive must use read_pcm_range instead of read_pcm", + )) + }) + } + + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + self.range_calls.lock().unwrap().push((offset, len)); + let start = offset as usize; + let end = start.saturating_add(len).min(self.pcm.len()); + let slice = self.pcm[start..end].to_vec(); + Box::pin(async move { Ok(slice) }) + } + + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + + let transcription = Arc::new(FixtureTranscriptionEngine::successful("chunk text", 500)); + let (mut service, path) = service( + Arc::new(FixtureTextPolisher::successful("unused")), + transcription.clone(), + ); + let preferences_path = path.with_extension("ranged-preferences.json"); + service.preferences = Arc::new(PreferencesStore::open(preferences_path.clone()).unwrap()); + service + .preferences + .update(|prefs| prefs.active_asr_provider = "groq".into()) + .unwrap(); + + let total_bytes = 301 * crate::DICTATION_SAMPLE_RATE as usize * 2; + let mut pcm = vec![2u8; total_bytes]; + pcm[total_bytes - 4..].copy_from_slice(&[7, 0, 8, 0]); + let archive = Arc::new(RangedArchive { + pcm: pcm.clone(), + read_pcm_calls: AtomicUsize::new(0), + range_calls: std::sync::Mutex::new(Vec::new()), + }); + let result = service.retranscribe_archive(archive.clone()).await.unwrap(); + + assert_eq!(archive.read_pcm_calls.load(Ordering::Acquire), 0); + let calls = archive.range_calls.lock().unwrap().clone(); + assert_eq!(calls.len(), 6); + assert_eq!(calls[0], (0, crate::long_recording::RECOVERY_CHUNK_BYTES)); + assert_eq!(transcription.pcm(), pcm); + assert_eq!(result.duration_ms, 301_000); + assert_eq!(result.text, ["chunk text"; 6].join("\n")); + let _ = std::fs::remove_file(preferences_path); + let _ = std::fs::remove_file(path); + } } diff --git a/openless-all/app/crates/openless-core/src/cloud_providers.rs b/openless-all/app/crates/openless-core/src/cloud_providers.rs index 553080cc5..91b8dcbed 100644 --- a/openless-all/app/crates/openless-core/src/cloud_providers.rs +++ b/openless-all/app/crates/openless-core/src/cloud_providers.rs @@ -247,6 +247,68 @@ impl TranscriptionEngine for SharedCloudTranscriptionEngine { } } +const STREAM_INCOMPLETE_TOLERANCE_BYTES: u64 = 32_000; + +async fn finalize_streaming_transcript( + provider_name: &str, + long_recording: bool, + stream_complete: bool, + coverage: (u64, u64), + sender_result: Result<(), E>, + cancel_fn: impl FnOnce(), + await_final: F, +) -> Result +where + E: std::fmt::Display, + F: std::future::Future>, +{ + let (sent_bytes, received_bytes) = coverage; + let unsent_bytes = received_bytes.saturating_sub(sent_bytes); + + if let Err(error) = sender_result { + cancel_fn(); + let mapped = map_asr_error(error); + if long_recording || unsent_bytes > STREAM_INCOMPLETE_TOLERANCE_BYTES { + log::warn!( + "[{provider_name}] rejecting incomplete stream (sent={sent_bytes}, received={received_bytes}, long={long_recording}): {}", + mapped.message + ); + return Err(mapped.retryable(true)); + } + let salvaged = timeout_transcription(Duration::from_secs(120), await_final) + .await + .map_err(|_| mapped.clone().retryable(true))?; + if salvaged.text.trim().is_empty() { + return Err(mapped.retryable(true)); + } + return Ok(salvaged); + } + + if !stream_complete && (long_recording || unsent_bytes > STREAM_INCOMPLETE_TOLERANCE_BYTES) { + cancel_fn(); + log::warn!( + "[{provider_name}] rejecting unverified audio coverage (sent={sent_bytes}, received={received_bytes}, long={long_recording})" + ); + return Err(BackendError::new( + BackendErrorCode::Provider, + format!("ASR stream audio incomplete ({sent_bytes}/{received_bytes} bytes written)"), + ) + .retryable(true)); + } + + let result = timeout_transcription(Duration::from_secs(120), await_final).await?; + if result.text.trim().is_empty() && !stream_complete { + return Err(BackendError::new( + BackendErrorCode::Provider, + format!( + "ASR stream produced empty text with incomplete coverage ({sent_bytes}/{received_bytes} bytes)" + ), + ) + .retryable(true)); + } + Ok(result) +} + impl AudioConsumer for CloudTranscriptionSession { fn consume_pcm_chunk(&self, pcm: &[u8]) { self.pcm_bytes @@ -304,20 +366,16 @@ impl TranscriptionSession for CloudTranscriptionSession { let transcript = match kind { CloudTranscriptionSessionKind::Volcengine(provider) => { let sender_result = provider.send_last_frame().await; - if long_recording { - if let Err(error) = sender_result { - provider.cancel(); - return Err(map_asr_error(error)); - } - } - if sender_result.is_err() { - // Stop the transport. A result already handed off by the - // receiver remains available through its oneshot channel. - provider.cancel(); - } - timeout_transcription(Duration::from_secs(120), provider.await_final_result()) - .await - .map_err(|error| sender_result.err().map(map_asr_error).unwrap_or(error))? + finalize_streaming_transcript( + "volcengine-asr", + long_recording, + provider.is_stream_complete(), + provider.audio_coverage(), + sender_result, + || provider.cancel(), + provider.await_final_result(), + ) + .await? } CloudTranscriptionSessionKind::Whisper(provider) => { let timeout = crate::provider_rules::whisper_transcribe_timeout( @@ -365,36 +423,56 @@ impl TranscriptionSession for CloudTranscriptionSession { provider.finish().await.map_err(map_asr_error)? } CloudTranscriptionSessionKind::Bailian(provider) => { - let sent = provider.send_last_frame().await; - if long_recording { - sent.map_err(map_asr_error)?; - } - timeout_transcription(Duration::from_secs(120), provider.await_final_result()) - .await? + let sender_result = provider.send_last_frame().await; + finalize_streaming_transcript( + "bailian-asr", + long_recording, + provider.is_stream_complete(), + provider.audio_coverage(), + sender_result, + || provider.cancel(), + provider.await_final_result(), + ) + .await? } CloudTranscriptionSessionKind::QwenRealtime(provider) => { - let sent = provider.send_last_frame().await; - if long_recording { - sent.map_err(map_asr_error)?; - } - timeout_transcription(Duration::from_secs(120), provider.await_final_result()) - .await? + let sender_result = provider.send_last_frame().await; + finalize_streaming_transcript( + "qwen3-asr", + long_recording, + provider.is_stream_complete(), + provider.audio_coverage(), + sender_result, + || provider.cancel(), + provider.await_final_result(), + ) + .await? } CloudTranscriptionSessionKind::StepfunRealtime(provider) => { - let sent = provider.send_last_frame().await; - if long_recording { - sent.map_err(map_asr_error)?; - } - timeout_transcription(Duration::from_secs(120), provider.await_final_result()) - .await? + let sender_result = provider.send_last_frame().await; + finalize_streaming_transcript( + "stepfun-asr", + long_recording, + provider.is_stream_complete(), + provider.audio_coverage(), + sender_result, + || provider.cancel(), + provider.await_final_result(), + ) + .await? } CloudTranscriptionSessionKind::Xfyun(provider) => { - let sent = provider.send_last_frame().await; - if long_recording { - sent.map_err(map_asr_error)?; - } - timeout_transcription(Duration::from_secs(120), provider.await_final_result()) - .await? + let sender_result = provider.send_last_frame().await; + finalize_streaming_transcript( + "xfyun-asr", + long_recording, + provider.is_stream_complete(), + provider.audio_coverage(), + sender_result, + || provider.cancel(), + provider.await_final_result(), + ) + .await? } CloudTranscriptionSessionKind::TencentCloud(provider) => { provider @@ -1116,7 +1194,7 @@ impl Drop for PolishRegistration { } } -enum CloudPolisherProvider { +pub(crate) enum CloudPolisherProvider { OpenAi(crate::polish::ActiveLLMProvider), Gemini(crate::llm_gemini::GeminiProvider), } @@ -1602,7 +1680,24 @@ async fn build_cloud_polisher_provider( credentials: &dyn CredentialStore, context: &DictationContext, ) -> Result { - if context.pipeline_mode == crate::shared_types::PipelineMode::Deepseek { + build_cloud_channel_provider( + credentials, + &context.llm, + context.pipeline_mode == crate::shared_types::PipelineMode::Deepseek, + context.polish.llm_thinking_enabled, + context.polish.polish_request_overrides.as_ref(), + ) + .await +} + +pub(crate) async fn build_cloud_channel_provider( + credentials: &dyn CredentialStore, + route: &crate::dictation_context::ProviderInvocation, + deepseek_suite: bool, + thinking: bool, + overrides: Option<&crate::polish_strategy::PolishRequestOverrides>, +) -> Result { + if deepseek_suite { let suite = crate::deepseek_suite::DeepSeekSuiteConfig::load(credentials).await?; require_configured(&suite.api_key, "DeepSeek suite API key")?; let config = crate::polish::OpenAICompatibleConfig::new( @@ -1612,23 +1707,22 @@ async fn build_cloud_polisher_provider( suite.api_key, crate::deepseek_suite::MODEL, ) - .with_thinking_enabled(context.polish.llm_thinking_enabled); + .with_thinking_enabled(thinking); return Ok(CloudPolisherProvider::OpenAi( crate::polish::ActiveLLMProvider::OpenAI( crate::polish::OpenAICompatibleLLMProvider::new(config), ), )); } - let channel_id = context.llm.provider_id.trim(); - let provider_type = context.llm.provider_type.trim(); + let channel_id = route.provider_id.trim(); + let provider_type = route.provider_type.trim(); if channel_id.is_empty() || provider_type.is_empty() { return Err(BackendError::new( BackendErrorCode::InvalidArgument, "LLM channel id and provider type must not be empty", )); } - let model = context - .llm + let model = route .model .clone() .and_then(non_blank_owned) @@ -1659,16 +1753,16 @@ async fn build_cloud_polisher_provider( )); } if provider_type == crate::polish::CODEX_OAUTH_PROVIDER_ID { - let mut config = crate::polish::CodexOAuthConfig::new(model) - .with_thinking_enabled(context.polish.llm_thinking_enabled); - if let Some(effort) = strategy_reasoning_effort(context) { + let mut config = + crate::polish::CodexOAuthConfig::new(model).with_thinking_enabled(thinking); + if let Some(effort) = overrides_reasoning_effort(overrides) { // Codex uses the Responses API, whose effort enum does not accept // `none`; omit that unsupported override rather than sending a // request that the endpoint rejects. let effort = (effort != "none").then_some(effort); config = config.with_reasoning_effort(effort); } - config = config.with_max_output_tokens(strategy_max_tokens(context)); + config = config.with_max_output_tokens(overrides.and_then(|value| value.max_tokens)); let provider = crate::polish::CodexOAuthLLMProvider::new(config); return Ok(CloudPolisherProvider::OpenAi( crate::polish::ActiveLLMProvider::Codex(provider), @@ -1706,12 +1800,12 @@ async fn build_cloud_polisher_provider( crate::endpoint_security::validate_http_endpoint(&endpoint) .map_err(|error| map_llm_error(error.to_string()))?; if provider_type == "gemini" { - let thinking_enabled = strategy_thinking_enabled(context); + let thinking_enabled = overrides_thinking_enabled(thinking, overrides); let mut config = crate::llm_gemini::GeminiConfig::new(api_key, model, endpoint.trim_end_matches('/')) .with_thinking_enabled(thinking_enabled) - .with_max_output_tokens(strategy_max_tokens(context)); - if let Some(temperature) = strategy_temperature(context) { + .with_max_output_tokens(overrides.and_then(|value| value.max_tokens)); + if let Some(temperature) = overrides.and_then(|value| value.temperature()) { config = config.with_temperature(temperature); } let provider = crate::llm_gemini::GeminiProvider::new(config); @@ -1732,11 +1826,7 @@ async fn build_cloud_polisher_provider( .map(parse_temperature) .transpose()? .flatten(); - let strategy_temperature = context - .polish - .polish_request_overrides - .as_ref() - .and_then(|overrides| overrides.temperature()); + let strategy_temperature = overrides.and_then(|overrides| overrides.temperature()); let temperature = strategy_temperature.or_else(|| { crate::polish::openai_compatible_temperature_for_provider( provider_type, @@ -1762,9 +1852,9 @@ async fn build_cloud_polisher_provider( model, ) .with_protocol(protocol) - .with_thinking_enabled(context.polish.llm_thinking_enabled) - .with_reasoning_effort(strategy_reasoning_effort(context)) - .with_max_tokens_override(strategy_max_tokens(context)) + .with_thinking_enabled(thinking) + .with_reasoning_effort(overrides_reasoning_effort(overrides)) + .with_max_tokens_override(overrides.and_then(|value| value.max_tokens)) .with_temperature(temperature) .with_extra_headers(extra_headers); Ok(CloudPolisherProvider::OpenAi( @@ -1795,11 +1885,10 @@ fn omni_temperature( }) } -fn strategy_reasoning_effort(context: &DictationContext) -> Option { - context - .polish - .polish_request_overrides - .as_ref() +fn overrides_reasoning_effort( + overrides: Option<&crate::polish_strategy::PolishRequestOverrides>, +) -> Option { + overrides .and_then(|overrides| overrides.reasoning_effort) .map(|effort| match effort { crate::polish_strategy::ReasoningEffort::None => "none", @@ -1810,14 +1899,25 @@ fn strategy_reasoning_effort(context: &DictationContext) -> Option { .map(str::to_string) } -fn strategy_thinking_enabled(context: &DictationContext) -> bool { - context - .polish - .polish_request_overrides - .as_ref() +fn overrides_thinking_enabled( + default_thinking: bool, + overrides: Option<&crate::polish_strategy::PolishRequestOverrides>, +) -> bool { + overrides .and_then(|overrides| overrides.reasoning_effort) .map(|effort| !matches!(effort, crate::polish_strategy::ReasoningEffort::None)) - .unwrap_or(context.polish.llm_thinking_enabled) + .unwrap_or(default_thinking) +} + +fn strategy_reasoning_effort(context: &DictationContext) -> Option { + overrides_reasoning_effort(context.polish.polish_request_overrides.as_ref()) +} + +fn strategy_thinking_enabled(context: &DictationContext) -> bool { + overrides_thinking_enabled( + context.polish.llm_thinking_enabled, + context.polish.polish_request_overrides.as_ref(), + ) } fn strategy_max_tokens(context: &DictationContext) -> Option { @@ -3284,6 +3384,63 @@ mod tests { ); } + #[tokio::test] + async fn strategy_overrides_reach_dictation_without_leaking_into_ask() { + let store = InMemoryCredentialStore::default(); + for (account, value) in [ + (LLM_ENDPOINT_ACCOUNT, "http://127.0.0.1:8080/v1"), + (LLM_TEMPERATURE_ACCOUNT, "1.2"), + (crate::llm_protocol::REQUEST_FORMAT_ACCOUNT, "responses"), + ] { + write_channel_secret( + &store, + CredentialNamespace::Llm, + "strategy-channel", + account, + value, + ) + .await; + } + let mut context = DictationContext { + llm: ProviderInvocation::new("strategy-channel", "custom"), + ..Default::default() + }; + context.llm.model = Some("fixture-model".into()); + context.polish.llm_thinking_enabled = true; + context.polish.polish_request_overrides = + Some(crate::polish_strategy::PolishRequestOverrides { + temperature_milli: Some(400), + max_tokens: Some(321), + reasoning_effort: Some(crate::polish_strategy::ReasoningEffort::High), + }); + let CloudPolisherProvider::OpenAi(crate::polish::ActiveLLMProvider::OpenAI(dictation)) = + build_cloud_polisher_provider(&store, &context) + .await + .unwrap() + else { + panic!("expected the configured compatible provider"); + }; + let CloudPolisherProvider::OpenAi(crate::polish::ActiveLLMProvider::OpenAI(ask)) = + build_cloud_channel_provider(&store, &context.llm, false, false, None) + .await + .unwrap() + else { + panic!("expected the same compatible channel for Ask"); + }; + let messages = vec![serde_json::json!({"role": "user", "content": "fixture"})]; + let dictation_body = + crate::llm_protocol::request_body(dictation.ask_config(), false, messages.clone()); + let ask_body = crate::llm_protocol::request_body(ask.ask_config(), false, messages); + assert_eq!(dictation.ask_config().temperature, Some(0.4)); + assert_eq!(dictation_body["max_output_tokens"], 321); + assert_eq!(dictation_body["reasoning"]["effort"], "high"); + assert_eq!(ask.ask_config().temperature, Some(1.2)); + assert_eq!(ask_body["reasoning"]["effort"], "low"); + assert!(ask_body.get("max_output_tokens").is_none()); + assert!(ask.ask_config().reasoning_effort.is_none()); + assert!(!ask.ask_config().thinking_enabled); + } + struct ObservedTranslationStream { chunks: Mutex>, arrived: tokio::sync::Semaphore, @@ -3719,8 +3876,18 @@ mod tests { let key = std::env::var("DEEPSEEK_API_KEY").expect("DEEPSEEK_API_KEY is required"); assert!(!key.trim().is_empty(), "DEEPSEEK_API_KEY is required"); let credentials = Arc::new(crate::InMemoryCredentialStore::default()); - for (account, value) in [(LLM_API_KEY_ACCOUNT, key.as_str()), (LLM_ENDPOINT_ACCOUNT, crate::deepseek_suite::ENDPOINT)] { - credentials.write(CredentialKey::new(CredentialNamespace::Llm, Some("deepseek".into()), account).unwrap(), crate::SecretValue::new(value)).await.unwrap(); + for (account, value) in [ + (LLM_API_KEY_ACCOUNT, key.as_str()), + (LLM_ENDPOINT_ACCOUNT, crate::deepseek_suite::ENDPOINT), + ] { + credentials + .write( + CredentialKey::new(CredentialNamespace::Llm, Some("deepseek".into()), account) + .unwrap(), + crate::SecretValue::new(value), + ) + .await + .unwrap(); } drop(key); let polisher = SharedCloudTextPolisher::new(credentials); @@ -3744,34 +3911,71 @@ mod tests { ("long", &structured, false, long.as_str(), "整体官网范围前置;所有独有约束、例外、术语、未决冲突与问句保留,只去重复"), ]; crate::polish::live_acceptance::begin(); - for (case, pack, translate, input, expectation) in cases.into_iter().take(if std::env::var_os("OPENLESS_LIVE_FIRST_ONLY").is_some() { 1 } else { 8 }) { - let mut prefs = crate::UserPreferences::default(); - prefs.translation_target_language = "English".into(); - prefs.working_languages = vec!["简体中文".into()]; + for (case, pack, translate, input, expectation) in + cases + .into_iter() + .take(if std::env::var_os("OPENLESS_LIVE_FIRST_ONLY").is_some() { + 1 + } else { + 8 + }) + { + let prefs = crate::UserPreferences { + translation_target_language: "English".into(), + working_languages: vec!["简体中文".into()], + ..Default::default() + }; let mut invocation = crate::ProviderInvocation::for_provider("deepseek"); invocation.model = Some(crate::deepseek_suite::MODEL.into()); - let context = DictationContext::capture(&prefs, pack, - crate::dictation_context::DictationProviderInvocations::new(crate::ProviderInvocation::for_provider("fixture-asr"), invocation, crate::ProviderInvocation::for_provider("unused")), - Vec::new(), Vec::new(), &crate::DictationStartOptions { translation_requested: translate, ..Default::default() }); + let context = DictationContext::capture( + &prefs, + pack, + crate::dictation_context::DictationProviderInvocations::new( + crate::ProviderInvocation::for_provider("fixture-asr"), + invocation, + crate::ProviderInvocation::for_provider("unused"), + ), + Vec::new(), + Vec::new(), + &crate::DictationStartOptions { + translation_requested: translate, + ..Default::default() + }, + ); let _ = crate::polish::live_acceptance::take_model(); - let result = polisher.polish(SessionId::new(), Arc::new(context), input.into(), Arc::new(IgnoreTextStreamSink)).await; + let result = polisher + .polish( + SessionId::new(), + Arc::new(context), + input.into(), + Arc::new(IgnoreTextStreamSink), + ) + .await; if let Err(error) = &result { - println!("LIVE_STYLE {}", serde_json::json!({"case":case, "endpoint":crate::deepseek_suite::ENDPOINT, + println!( + "LIVE_STYLE {}", + serde_json::json!({"case":case, "endpoint":crate::deepseek_suite::ENDPOINT, "channel":"official DeepSeek acceptance (not verified user Ark channel)", "requested_model":crate::deepseek_suite::MODEL, "response_model":crate::polish::live_acceptance::take_model(), "style_id":pack.id, "translation":translate, "input":input, "output":null, "error_code":format!("{:?}",error.code), "expected_semantics":expectation, - "semantic_review":"not evaluated: provider request failed; remaining cases not run"})); + "semantic_review":"not evaluated: provider request failed; remaining cases not run"}) + ); } - let result = result.unwrap_or_else(|error| panic!("{case}: official request failed, code={:?}", error.code)); - println!("LIVE_STYLE {}", serde_json::json!({ - "case":case, "endpoint":crate::deepseek_suite::ENDPOINT, - "channel":"official DeepSeek acceptance (not verified user Ark channel)", - "requested_model":crate::deepseek_suite::MODEL, - "response_model":crate::polish::live_acceptance::take_model(), - "style_id":pack.id,"translation":translate,"input":input, - "source_output":result.source_text,"output":result.text, - "expected_semantics":expectation,"semantic_review":"pending human/agent review; transport success is not semantic pass" - })); + let result = result.unwrap_or_else(|error| { + panic!("{case}: official request failed, code={:?}", error.code) + }); + println!( + "LIVE_STYLE {}", + serde_json::json!({ + "case":case, "endpoint":crate::deepseek_suite::ENDPOINT, + "channel":"official DeepSeek acceptance (not verified user Ark channel)", + "requested_model":crate::deepseek_suite::MODEL, + "response_model":crate::polish::live_acceptance::take_model(), + "style_id":pack.id,"translation":translate,"input":input, + "source_output":result.source_text,"output":result.text, + "expected_semantics":expectation,"semantic_review":"pending human/agent review; transport success is not semantic pass" + }) + ); assert!(!result.text.trim().is_empty(), "{case}: empty output"); } } @@ -4434,4 +4638,147 @@ mod tests { assert!(parse_extra_headers(r#"{"x-trace":"ok"}"#).is_ok()); assert!(parse_extra_headers(r#"{"Authorization":"secret"}"#).is_err()); } + + #[tokio::test] + async fn finalize_streaming_transcript_enforces_coverage_and_short_salvage_policy() { + let canceled = Arc::new(AtomicBool::new(false)); + let mark_cancel = || { + canceled.store(true, Ordering::Release); + }; + + // Long recording with failed finish/send must fail even when partial text is available. + let err = finalize_streaming_transcript( + "test-asr", + true, + false, + (32_000, 32_000), + Err("mid-stream disconnect"), + mark_cancel, + async { + Ok(crate::asr::RawTranscript { + text: "partial".into(), + duration_ms: 1000, + }) + }, + ) + .await + .unwrap_err(); + assert!(canceled.load(Ordering::Acquire)); + assert!(err.message.contains("mid-stream disconnect")); + + // Short session with >1s unsent audio must reject partial fallback (#1/#2/#3/#4) + // and mark retryable so archived replay can recover. + let canceled_short_gap = Arc::new(AtomicBool::new(false)); + let err = finalize_streaming_transcript( + "test-asr", + false, + false, + (3_200, 64_000), + Err("tail write failed"), + || canceled_short_gap.store(true, Ordering::Release), + async { + Ok(crate::asr::RawTranscript { + text: "truncated partial".into(), + duration_ms: 2000, + }) + }, + ) + .await + .unwrap_err(); + assert!(canceled_short_gap.load(Ordering::Acquire)); + assert!(err.retryable); + assert!(err.message.contains("tail write failed")); + + // Short session with complete coverage salvages non-empty partial when close-out fails. + let salvaged = finalize_streaming_transcript( + "test-asr", + false, + false, + (32_000, 32_000), + Err("finish ack dropped"), + || {}, + async { + Ok(crate::asr::RawTranscript { + text: "salvaged short text".into(), + duration_ms: 1000, + }) + }, + ) + .await + .unwrap(); + assert_eq!(salvaged.text, "salvaged short text"); + + // Short session with failed send_last_frame and empty text must surface error. + let empty_failed = finalize_streaming_transcript( + "test-asr", + false, + false, + (32_000, 32_000), + Err("finish ack dropped"), + || {}, + async { + Ok(crate::asr::RawTranscript { + text: " ".into(), + duration_ms: 1000, + }) + }, + ) + .await + .unwrap_err(); + assert!(empty_failed.message.contains("finish ack dropped")); + assert!(empty_failed.retryable); + + // Short session where salvage await fails (e.g. concurrent cancel) must stay retryable. + let await_failed = finalize_streaming_transcript( + "test-asr", + false, + false, + (32_000, 32_000), + Err("finish ack dropped"), + || {}, + async { Err::("no final result") }, + ) + .await + .unwrap_err(); + assert!(await_failed.message.contains("finish ack dropped")); + assert!(await_failed.retryable); + + // Silence with complete coverage is still allowed for connection checks. + let silent_ok = finalize_streaming_transcript::<&str, _>( + "test-asr", + false, + true, + (16_000, 16_000), + Ok(()), + || {}, + async { + Ok(crate::asr::RawTranscript { + text: "".into(), + duration_ms: 500, + }) + }, + ) + .await + .unwrap(); + assert_eq!(silent_ok.text, ""); + + // Empty text with incomplete coverage must fail. + let empty_incomplete = finalize_streaming_transcript::<&str, _>( + "test-asr", + false, + false, + (16_000, 16_000), + Ok(()), + || {}, + async { + Ok(crate::asr::RawTranscript { + text: "".into(), + duration_ms: 500, + }) + }, + ) + .await + .unwrap_err(); + assert!(empty_incomplete.retryable); + } } diff --git a/openless-all/app/crates/openless-core/src/dictation_engine.rs b/openless-all/app/crates/openless-core/src/dictation_engine.rs index d8e8d6d6c..befcd09fb 100644 --- a/openless-all/app/crates/openless-core/src/dictation_engine.rs +++ b/openless-all/app/crates/openless-core/src/dictation_engine.rs @@ -28,6 +28,8 @@ const BUFFERED_TRANSCRIPTION_STOP_HEADROOM_BYTES: usize = 1024 * 1024; const BUFFERED_TRANSCRIPTION_STOP_THRESHOLD_BYTES: usize = MAX_BUFFERED_TRANSCRIPTION_PCM_BYTES - BUFFERED_TRANSCRIPTION_STOP_HEADROOM_BYTES; const BUFFERED_TRANSCRIPTION_FORWARD_CHUNK_BYTES: usize = 64 * 1024; +const MIN_VALID_PCM_BYTES: u64 = 3_200; +const STABLE_SPILL_THRESHOLD_BYTES: usize = 8 * 1024 * 1024; #[cfg(test)] #[path = "long_recording_tests.rs"] @@ -307,6 +309,7 @@ impl DictationEngine for PipelineDictationEngine { )); } let stable = context.recording.transcribe_after_stop; + let spill_to_archive = stable && context.recording.archive_processed; let has_local_fallback = context.asr_fallback.is_some(); let transcript_partials: Arc = if stable { Arc::new(DiscardTextStream) @@ -392,6 +395,14 @@ impl DictationEngine for PipelineDictationEngine { return Err(error); } }; + if spill_to_archive { + if let Some(archive) = recording + .archive() + .filter(|archive| archive.is_available() && archive.write_error().is_none()) + { + buffered.enable_archive_spill(archive); + } + } let mut recording = Some(PipelineRecording::new(recording)); let stopping = { @@ -580,6 +591,7 @@ impl DictationEngine for PipelineDictationEngine { )); } let stable = context.recording.transcribe_after_stop; + let spill_to_archive = stable && context.recording.archive_processed; let partials = if stable { Arc::new(DiscardTextStream) as Arc } else { @@ -594,6 +606,14 @@ impl DictationEngine for PipelineDictationEngine { let recording = recorder .start(session_id, context, consumer, progress) .await?; + if spill_to_archive { + if let Some(archive) = recording + .archive() + .filter(|archive| archive.is_available() && archive.write_error().is_none()) + { + buffered.enable_archive_spill(archive); + } + } let transcription: Arc = buffered.clone(); if cancel.is_cancelled() { let (stop_result, cancel_result) = @@ -725,7 +745,6 @@ impl DictationEngine for PipelineDictationEngine { })?; let archive = recording.archive(); - let mut has_audio_recording = archive.as_ref().map(|archive| archive.is_available()); if let Err(error) = recording.stop().await { // 录音设备中途掉线(蓝牙麦欠载/节点被挂起时报 "Device disconnected") // 不应丢掉已经流进 ASR 的内容:这里降级为警告继续转写, @@ -734,6 +753,9 @@ impl DictationEngine for PipelineDictationEngine { "[dictation] recorder stop failed; transcribing the captured audio anyway: {error}" ); } + let mut has_audio_recording = archive + .as_ref() + .map(|archive| archive.is_available() && archive.write_error().is_none()); let captured_pcm_bytes = buffered .as_ref() .map_or(0, |buffer| buffer.received_pcm_bytes()); @@ -771,6 +793,12 @@ impl DictationEngine for PipelineDictationEngine { .into()); } + publish_progress( + &session, + session_id, + &progress, + EngineProgress::CapturedDurationMs(captured_duration_ms), + )?; publish_progress( &session, session_id, @@ -784,7 +812,11 @@ impl DictationEngine for PipelineDictationEngine { let standby = context .asr_fallback .is_some() - .then(|| archive.clone().filter(|archive| archive.is_available())) + .then(|| { + archive + .clone() + .filter(|archive| archive.is_available() && archive.write_error().is_none()) + }) .flatten() .map(|archive| { LocalStandby::new( @@ -884,14 +916,13 @@ impl DictationEngine for PipelineDictationEngine { | BackendErrorCode::PermissionDenied | BackendErrorCode::Cancelled ); - let retry_pcm = if !cancelled && (first_error.retryable || recover_long) { - match archive.as_ref().filter(|archive| archive.is_available()) { - Some(archive) => archive.read_pcm().await.ok().filter(|pcm| { - !pcm.is_empty() - && (!long_recording || pcm.len() as u64 == captured_pcm_bytes) - }), - None => None, - } + let retry_archive = if !cancelled && (first_error.retryable || recover_long) { + validate_retry_archive_bytes( + archive.as_ref(), + long_recording, + captured_pcm_bytes, + ) + .await } else { None }; @@ -922,39 +953,45 @@ impl DictationEngine for PipelineDictationEngine { local_fallback_used = true; transcript } else { - match retry_pcm { - Some(pcm) => match retry_transcription( - prepared, - Arc::clone(&session), - session_id, - Arc::clone(&progress), - pcm, - CLOUD_RETRY, - ) - .await - { - Ok((transcript, label, metadata)) => { - asr_call_label = label; - asr_metadata = metadata; - transcript - } - Err((error, label)) => { - asr_call_label = label.or(asr_call_label); - demote_failed_archive( - archive.as_ref(), - context.output_target, - &mut has_audio_recording, - ) - .await; - remove_session(&sessions, session_id, &session); - let mut failure = - EngineFailure::new(error, EngineFailureStage::Transcribing); - failure.asr_ms = Some(asr_started.elapsed().as_millis() as u64); - failure.has_audio_recording = has_audio_recording; - failure.asr_call_label = asr_call_label; - return Err(failure); + match retry_archive { + Some((retry_archive, retry_bytes)) => { + match retry_transcription_from_archive( + prepared, + Arc::clone(&session), + session_id, + Arc::clone(&progress), + retry_archive, + retry_bytes, + CLOUD_RETRY, + ) + .await + { + Ok((transcript, label, metadata)) => { + asr_call_label = label; + asr_metadata = metadata; + transcript + } + Err((error, label)) => { + asr_call_label = label.or(asr_call_label); + demote_failed_archive( + archive.as_ref(), + context.output_target, + &mut has_audio_recording, + ) + .await; + remove_session(&sessions, session_id, &session); + let mut failure = EngineFailure::new( + error, + EngineFailureStage::Transcribing, + ); + failure.asr_ms = + Some(asr_started.elapsed().as_millis() as u64); + failure.has_audio_recording = has_audio_recording; + failure.asr_call_label = asr_call_label; + return Err(failure); + } } - }, + } None => { demote_failed_archive( archive.as_ref(), @@ -985,36 +1022,35 @@ impl DictationEngine for PipelineDictationEngine { && transcript.text.trim().is_empty() && !session.cancelled.load(Ordering::Acquire) { - if let (Some(prepared), Some(archive)) = ( - prepared, - archive.as_ref().filter(|archive| archive.is_available()), - ) { - if let Ok(pcm) = archive.read_pcm().await { - if pcm.len() as u64 == captured_pcm_bytes { - match retry_transcription( - prepared, - Arc::clone(&session), - session_id, - Arc::clone(&progress), - pcm, - CLOUD_RETRY, - ) + if let Some(prepared) = prepared { + if let Some((retry_archive, retry_bytes)) = + validate_retry_archive_bytes(archive.as_ref(), true, captured_pcm_bytes) .await - { - Ok((recovered, label, metadata)) => { - transcript = recovered; - asr_call_label = label.or(asr_call_label); - asr_metadata = metadata; - } - Err((error, label)) => { - remove_session(&sessions, session_id, &session); - let mut failure = - EngineFailure::new(error, EngineFailureStage::Transcribing); - failure.duration_ms = Some(captured_duration_ms); - failure.has_audio_recording = has_audio_recording; - failure.asr_call_label = label.or(asr_call_label); - return Err(failure); - } + { + match retry_transcription_from_archive( + prepared, + Arc::clone(&session), + session_id, + Arc::clone(&progress), + retry_archive, + retry_bytes, + CLOUD_RETRY, + ) + .await + { + Ok((recovered, label, metadata)) => { + transcript = recovered; + asr_call_label = label.or(asr_call_label); + asr_metadata = metadata; + } + Err((error, label)) => { + remove_session(&sessions, session_id, &session); + let mut failure = + EngineFailure::new(error, EngineFailureStage::Transcribing); + failure.duration_ms = Some(captured_duration_ms); + failure.has_audio_recording = has_audio_recording; + failure.asr_call_label = label.or(asr_call_label); + return Err(failure); } } } @@ -1065,8 +1101,25 @@ impl DictationEngine for PipelineDictationEngine { transcript.duration_ms = captured_duration_ms; // Validate the saved whole recording before claiming recoverability. // The archive starts with capture, not with the five-minute transition. - let saved = match archive.as_ref().filter(|archive| archive.is_available()) { - Some(archive) => archive.pcm_byte_len().await, + let saved = match archive.as_ref() { + Some(archive) => { + if let Some(write_err) = archive.write_error() { + log::warn!( + "[long-recording] archive write failed before completeness verification: {write_err}" + ); + Err(BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveIncomplete", + )) + } else if !archive.is_available() { + Err(BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveUnavailable", + )) + } else { + archive.pcm_byte_len().await + } + } None => Err(BackendError::new( BackendErrorCode::Persistence, "longRecordingArchiveUnavailable", @@ -1651,11 +1704,14 @@ impl LocalStandby { let run = Box::pin(async move { let transcribe = async { let fallback = context.asr_fallback.clone()?; - let pcm = archive - .read_pcm() + if !archive.is_available() || archive.write_error().is_some() { + return None; + } + let total_bytes = archive + .pcm_byte_len() .await .ok() - .filter(|pcm| !pcm.is_empty())?; + .filter(|&bytes| bytes > 0)?; let mut local = (*context).clone(); local.asr = fallback; local.asr_fallback = None; @@ -1669,34 +1725,88 @@ impl LocalStandby { return None; } }; - // Partials stay private: the cloud may still win. - let transcription = match prepared.start(Arc::new(DiscardedTextStream)).await { - Ok(transcription) => transcription, - Err(error) => { - log::warn!( - "[dictation] local ASR standby failed to start: {}", - error.message - ); - return None; - } + // Long recordings (> 5 min) run through the local fallback in + // 60-second ranged slices so RAM stays bounded and long audio + // never stalls or truncates on a single batch/streaming window. + let mut combined_text = String::new(); + let mut last_label = None; + let mut last_metadata = crate::ports::TranscriptMetadata::default(); + let chunk_bytes = if crate::long_recording::duration_ms(total_bytes) + > crate::long_recording::THRESHOLD_MS + { + crate::long_recording::RECOVERY_CHUNK_BYTES as u64 + } else { + total_bytes }; - *slot.lock().expect("local standby lock poisoned") = - Some(Arc::clone(&transcription)); - let label = transcription.asr_call_label(); - transcription.consume_pcm_chunk(&pcm); - let result = transcription.finish().await; - slot.lock().expect("local standby lock poisoned").take(); - match result { - Ok(output) if output.text.trim().is_empty() => { - log::warn!("[dictation] local ASR standby returned an empty transcript"); - None + let mut offset = 0u64; + while offset < total_bytes { + if session.cancelled.load(Ordering::Acquire) { + return None; } - Ok(output) => Some((output, label, transcription.transcript_metadata())), - Err(error) => { - log::warn!("[dictation] local ASR standby failed: {}", error.message); - None + let seg_len = usize::try_from(chunk_bytes.min(total_bytes - offset)).ok()?; + let pcm = match archive.read_pcm_range(offset, seg_len).await { + Ok(pcm) if pcm.len() == seg_len => pcm, + Ok(_) => { + log::warn!( + "[dictation] local ASR standby hit short archive read at offset={offset}" + ); + return None; + } + Err(error) => { + log::warn!( + "[dictation] local ASR standby failed reading archive: {}", + error.message + ); + return None; + } + }; + offset += pcm.len() as u64; + // Partials stay private: the cloud may still win. + let transcription = match prepared.start(Arc::new(DiscardedTextStream)).await { + Ok(transcription) => transcription, + Err(error) => { + log::warn!( + "[dictation] local ASR standby failed to start: {}", + error.message + ); + return None; + } + }; + *slot.lock().expect("local standby lock poisoned") = + Some(Arc::clone(&transcription)); + let label = transcription.asr_call_label(); + transcription.consume_pcm_chunk(&pcm); + let result = transcription.finish().await; + let metadata = transcription.transcript_metadata(); + slot.lock().expect("local standby lock poisoned").take(); + match result { + Ok(output) => { + last_label = label.or(last_label); + last_metadata = metadata; + if !combined_text.is_empty() && !output.text.is_empty() { + combined_text.push('\n'); + } + combined_text.push_str(&output.text); + } + Err(error) => { + log::warn!("[dictation] local ASR standby failed: {}", error.message); + return None; + } } } + if combined_text.trim().is_empty() { + log::warn!("[dictation] local ASR standby returned an empty transcript"); + None + } else { + Some(( + crate::ports::TranscriptOutput { + text: combined_text, + duration_ms: crate::long_recording::duration_ms(total_bytes), + }, + last_label, + last_metadata, + )) + } }; tokio::select! { result = transcribe => result, @@ -1744,15 +1854,50 @@ impl TextStreamSink for DiscardedTextStream { } } -async fn retry_transcription( +async fn validate_retry_archive_bytes( + archive: Option<&Arc>, + require_exact_length: bool, + captured_pcm_bytes: u64, +) -> Option<(Arc, u64)> { + let archive = + archive.filter(|archive| archive.is_available() && archive.write_error().is_none())?; + let total_bytes = archive.pcm_byte_len().await.ok()?; + (total_bytes > 0 && (!require_exact_length || total_bytes == captured_pcm_bytes)) + .then(|| (Arc::clone(archive), total_bytes)) +} + +async fn retry_transcription_from_archive( prepared: Arc, session: Arc, session_id: SessionId, progress: Arc, - pcm: Vec, + archive: Arc, + total_bytes: u64, plan: ReplayPlan, ) -> Result)> { - if crate::long_recording::duration_ms(pcm.len() as u64) <= crate::long_recording::THRESHOLD_MS { + if crate::long_recording::duration_ms(total_bytes) <= crate::long_recording::THRESHOLD_MS { + let len = usize::try_from(total_bytes).map_err(|_| { + ( + BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveIncomplete", + ), + None, + ) + })?; + let pcm = archive + .read_pcm_range(0, len) + .await + .map_err(|error| (error, None))?; + if pcm.len() != len { + return Err(( + BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveIncomplete", + ), + None, + )); + } return retry_transcription_segment( prepared, session, session_id, progress, pcm, plan, true, ) @@ -1761,13 +1906,36 @@ async fn retry_transcription( let mut text = String::new(); let mut label = None; let mut metadata = crate::ports::TranscriptMetadata::default(); - for chunk in pcm.chunks(crate::long_recording::RECOVERY_CHUNK_BYTES) { + let mut offset = 0u64; + while offset < total_bytes { + if session.cancelled.load(Ordering::Acquire) { + return Err(( + cancelled_error("dictation was cancelled before retry segment read"), + label, + )); + } + let seg_len = + (crate::long_recording::RECOVERY_CHUNK_BYTES as u64).min(total_bytes - offset) as usize; + let chunk = archive + .read_pcm_range(offset, seg_len) + .await + .map_err(|error| (error, label.clone()))?; + if chunk.len() != seg_len { + return Err(( + BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveIncomplete", + ), + label, + )); + } + offset += chunk.len() as u64; let (part, part_label, part_metadata) = retry_transcription_segment( Arc::clone(&prepared), Arc::clone(&session), session_id, Arc::clone(&progress), - chunk.to_vec(), + chunk, plan, false, ) @@ -1782,7 +1950,7 @@ async fn retry_transcription( Ok(( crate::ports::TranscriptOutput { text, - duration_ms: crate::long_recording::duration_ms(pcm.len() as u64), + duration_ms: crate::long_recording::duration_ms(total_bytes), }, label, metadata, @@ -2120,11 +2288,16 @@ struct BufferedTranscriptionInner { has_nonzero_pcm: AtomicBool, received_pcm_bytes: AtomicU64, limit_threshold_bytes: usize, + spill_threshold_bytes: usize, + spill_archive: Mutex>>, state: Mutex, } enum BufferedTranscriptionState { Buffering(Vec), + SpilledToArchive { + archive: Arc, + }, Attaching { pcm: Vec, waiter: Arc, @@ -2134,25 +2307,51 @@ enum BufferedTranscriptionState { Cancelled, } +enum AttachSource { + Memory(Vec), + Archive { + archive: Arc, + expected_bytes: u64, + }, +} + impl BufferedTranscriptionSession { fn new( prepared: Arc, partials: Arc, progress: Arc, ) -> Self { - Self::new_with_limit( + Self::new_with_thresholds( prepared, partials, progress, BUFFERED_TRANSCRIPTION_STOP_THRESHOLD_BYTES, + STABLE_SPILL_THRESHOLD_BYTES, ) } + #[cfg(test)] fn new_with_limit( prepared: Arc, partials: Arc, progress: Arc, limit_threshold_bytes: usize, + ) -> Self { + Self::new_with_thresholds( + prepared, + partials, + progress, + limit_threshold_bytes, + STABLE_SPILL_THRESHOLD_BYTES, + ) + } + + fn new_with_thresholds( + prepared: Arc, + partials: Arc, + progress: Arc, + limit_threshold_bytes: usize, + spill_threshold_bytes: usize, ) -> Self { Self { inner: Arc::new(BufferedTranscriptionInner { @@ -2163,11 +2362,34 @@ impl BufferedTranscriptionSession { has_nonzero_pcm: AtomicBool::new(false), received_pcm_bytes: AtomicU64::new(0), limit_threshold_bytes, + spill_threshold_bytes, + spill_archive: Mutex::new(None), state: Mutex::new(BufferedTranscriptionState::Buffering(Vec::new())), }), } } + fn enable_archive_spill(&self, archive: Arc) { + if !archive.is_available() || archive.write_error().is_some() { + return; + } + *self + .inner + .spill_archive + .lock() + .expect("spill archive lock poisoned") = Some(Arc::clone(&archive)); + let mut state = self + .inner + .state + .lock() + .expect("buffered transcription lock poisoned"); + if let BufferedTranscriptionState::Buffering(buffer) = &*state { + if buffer.len() >= self.inner.spill_threshold_bytes { + *state = BufferedTranscriptionState::SpilledToArchive { archive }; + } + } + } + fn attach(&self) -> BoxFuture<'static, Result, BackendError>> { let waiter = Arc::new(tokio::sync::Notify::new()); let start = { @@ -2183,7 +2405,19 @@ impl BufferedTranscriptionSession { pcm: Vec::new(), waiter: Arc::clone(&waiter), }; - Some(pcm) + AttachSource::Memory(pcm) + } + BufferedTranscriptionState::SpilledToArchive { archive } => { + let archive = Arc::clone(archive); + let expected_bytes = self.inner.received_pcm_bytes.load(Ordering::Acquire); + *state = BufferedTranscriptionState::Attaching { + pcm: Vec::new(), + waiter: Arc::clone(&waiter), + }; + AttachSource::Archive { + archive, + expected_bytes, + } } BufferedTranscriptionState::Direct(session) => { let session = Arc::clone(session); @@ -2217,6 +2451,7 @@ impl BufferedTranscriptionSession { Err(cancelled_error("transcription buffer was cancelled")) } BufferedTranscriptionState::Buffering(_) + | BufferedTranscriptionState::SpilledToArchive { .. } | BufferedTranscriptionState::Attaching { .. } => { Err(BackendError::new( BackendErrorCode::Internal, @@ -2229,10 +2464,7 @@ impl BufferedTranscriptionSession { } }; let inner = Arc::clone(&self.inner); - Box::pin(async move { - attach_buffered_transcription(inner, start.expect("buffer attach must start"), waiter) - .await - }) + Box::pin(async move { attach_buffered_transcription(inner, start, waiter).await }) } fn attach_in_background(&self, task_spawner: Arc) { @@ -2263,7 +2495,7 @@ impl BufferedTranscriptionSession { fn attach_buffered_transcription( inner: Arc, - pcm: Vec, + source: AttachSource, waiter: Arc, ) -> BoxFuture<'static, Result, BackendError>> { Box::pin(async move { @@ -2279,6 +2511,38 @@ fn attach_buffered_transcription( "transcription cancelled before provider startup", )); } + + let archive_stream = match &source { + AttachSource::Memory(_) => None, + AttachSource::Archive { + archive, + expected_bytes, + } => { + if let Some(write_err) = archive.write_error() { + let error = BackendError::new(BackendErrorCode::Persistence, write_err); + set_buffer_failed_unless_cancelled(&inner, error.clone()); + return Err(error); + } + match archive.pcm_byte_len().await { + Ok(total_bytes) if total_bytes > 0 && total_bytes == *expected_bytes => { + Some((Arc::clone(archive), total_bytes)) + } + Ok(_) => { + let error = BackendError::new( + BackendErrorCode::Persistence, + "stableModeArchiveIncomplete", + ); + set_buffer_failed_unless_cancelled(&inner, error.clone()); + return Err(error); + } + Err(error) => { + set_buffer_failed_unless_cancelled(&inner, error.clone()); + return Err(error); + } + } + } + }; + let downstream = match inner.prepared.start(Arc::clone(&inner.partials)).await { Ok(session) => session, Err(error) => { @@ -2296,7 +2560,87 @@ fn attach_buffered_transcription( } }; - let mut first_chunk = Some(pcm); + let mut first_chunk = match source { + AttachSource::Memory(pcm) => (!pcm.is_empty()).then_some(pcm), + AttachSource::Archive { .. } => None, + }; + + if let Some((archive, total_bytes)) = archive_stream { + let mut offset = 0u64; + while offset < total_bytes { + if matches!( + &*inner + .state + .lock() + .expect("buffered transcription lock poisoned"), + BufferedTranscriptionState::Cancelled + ) { + let _ = downstream.cancel().await; + return Err(cancelled_error( + "transcription buffer was cancelled while streaming archive", + )); + } + let seg_len = (BUFFERED_TRANSCRIPTION_FORWARD_CHUNK_BYTES as u64) + .min(total_bytes - offset) as usize; + match archive.read_pcm_range(offset, seg_len).await { + Ok(chunk) if !chunk.is_empty() => { + downstream.consume_pcm_chunk(&chunk); + offset += chunk.len() as u64; + // Bound the provider queue as well as the archive read buffer. + // Send workers retain authority over individual websocket frame timing. + let rate = downstream.asr_call_label().and_then(|label| { + match label.provider.as_str() { + "iflytek" => Some(1u64), + "volcengine" + | "bailian-qwen3-realtime" + | "stepfun-realtime" + | "bailian" => Some(2), + _ => None, + } + }); + if let Some(rate) = rate { + let deadline = tokio::time::Instant::now() + + std::time::Duration::from_micros( + (chunk.len() as u64 * 1_000).div_ceil(32 * rate), + ); + while tokio::time::Instant::now() < deadline { + if matches!( + &*inner + .state + .lock() + .expect("buffered transcription lock poisoned"), + BufferedTranscriptionState::Cancelled + ) { + let _ = downstream.cancel().await; + return Err(cancelled_error( + "transcription cancelled while replaying archive", + )); + } + tokio::time::sleep_until(deadline.min( + tokio::time::Instant::now() + + std::time::Duration::from_millis(25), + )) + .await; + } + } + } + Ok(_) => { + let error = BackendError::new( + BackendErrorCode::Persistence, + "stableModeArchiveIncomplete", + ); + let _ = downstream.cancel().await; + set_buffer_failed_unless_cancelled(&inner, error.clone()); + return Err(error); + } + Err(error) => { + let _ = downstream.cancel().await; + set_buffer_failed_unless_cancelled(&inner, error.clone()); + return Err(error); + } + } + } + } loop { let chunk = if let Some(chunk) = first_chunk.take().filter(|chunk| !chunk.is_empty()) { @@ -2329,7 +2673,8 @@ fn attach_buffered_transcription( )), BufferedTranscriptionState::Failed(error) => Err(error.clone()), BufferedTranscriptionState::Direct(session) => return Ok(Arc::clone(session)), - BufferedTranscriptionState::Buffering(_) => unreachable!( + BufferedTranscriptionState::Buffering(_) + | BufferedTranscriptionState::SpilledToArchive { .. } => unreachable!( "buffered transcription cannot return to buffering while attaching" ), } @@ -2349,6 +2694,16 @@ fn attach_buffered_transcription( }) } +fn set_buffer_failed_unless_cancelled(inner: &BufferedTranscriptionInner, error: BackendError) { + let mut state = inner + .state + .lock() + .expect("buffered transcription lock poisoned"); + if !matches!(*state, BufferedTranscriptionState::Cancelled) { + *state = BufferedTranscriptionState::Failed(error); + } +} + struct NotifyOnDrop { waiter: Arc, } @@ -2376,11 +2731,32 @@ impl AudioConsumer for BufferedTranscriptionSession { .lock() .expect("buffered transcription lock poisoned"); match &mut *state { - BufferedTranscriptionState::Buffering(buffer) - | BufferedTranscriptionState::Attaching { pcm: buffer, .. } => { + BufferedTranscriptionState::Buffering(buffer) => { + buffer.extend_from_slice(pcm); + let spilled = if buffer.len() >= self.inner.spill_threshold_bytes { + self.inner + .spill_archive + .lock() + .expect("spill archive lock poisoned") + .clone() + .filter(|archive| { + archive.is_available() && archive.write_error().is_none() + }) + } else { + None + }; + if let Some(archive) = spilled { + *state = BufferedTranscriptionState::SpilledToArchive { archive }; + (None, false) + } else { + (None, buffer.len() >= self.inner.limit_threshold_bytes) + } + } + BufferedTranscriptionState::Attaching { pcm: buffer, .. } => { buffer.extend_from_slice(pcm); (None, buffer.len() >= self.inner.limit_threshold_bytes) } + BufferedTranscriptionState::SpilledToArchive { .. } => (None, false), BufferedTranscriptionState::Direct(session) => (Some(Arc::clone(session)), false), BufferedTranscriptionState::Failed(_) | BufferedTranscriptionState::Cancelled => { (None, false) @@ -2431,7 +2807,8 @@ impl TranscriptionSession for BufferedTranscriptionSession { fn finish(&self) -> BoxFuture<'static, Result> { // Inspect after the caller stops capture. Cancellation remains independent - // of audio validity, and quiet non-zero samples do not trip a speech threshold. + // of audio validity, quiet non-zero samples do not trip a speech threshold, + // and < 100 ms captures are rejected before reaching ASR. let terminal = matches!( &*self .inner @@ -2440,7 +2817,10 @@ impl TranscriptionSession for BufferedTranscriptionSession { .expect("buffered transcription lock poisoned"), BufferedTranscriptionState::Failed(_) | BufferedTranscriptionState::Cancelled ); - if !terminal && !self.inner.has_nonzero_pcm.load(Ordering::Acquire) { + if !terminal + && (!self.inner.has_nonzero_pcm.load(Ordering::Acquire) + || self.inner.received_pcm_bytes.load(Ordering::Acquire) < MIN_VALID_PCM_BYTES) + { return Box::pin(async { Err(BackendError::new( BackendErrorCode::InvalidArgument, @@ -2775,7 +3155,7 @@ mod tests { "fixture recorder failed", )); } - consumer.consume_pcm_chunk(&[1, 0, 2, 0]); + consumer.consume_pcm_chunk(&[1, 0, 2, 0].repeat(800)); progress.publish_level(25, 1.5)?; Ok(Box::new(FixtureRecording { stops, archive }) as Box) }) @@ -2795,7 +3175,7 @@ mod tests { consumer: Arc, _progress: Arc, ) -> BoxFuture<'static, Result, BackendError>> { - consumer.consume_pcm_chunk(&[1, 0]); + consumer.consume_pcm_chunk(&[1, 0].repeat(1_600)); *self.consumer.lock().unwrap() = Some(consumer); let stops = Arc::clone(&self.stops); Box::pin(async move { @@ -3057,7 +3437,7 @@ mod tests { let archive = Arc::new(FixtureArchive { available: AtomicBool::new(true), discards: Arc::clone(&archive_discards), - pcm: vec![1, 0, 2, 0], + pcm: [1, 0, 2, 0].repeat(800), }); let transcription_cancels = Arc::new(AtomicUsize::new(0)); let transcription_starts = Arc::new(AtomicUsize::new(0)); @@ -3151,7 +3531,7 @@ mod tests { archive: Arc::new(FixtureArchive { available: AtomicBool::new(true), discards: archive_discards, - pcm: vec![1, 0, 2, 0], + pcm: [1, 0, 2, 0].repeat(800), }), fail: false, }), @@ -3273,7 +3653,7 @@ mod tests { ) .await .unwrap(); - session.consume_pcm_chunk(&[1, 0, 2, 0]); + session.consume_pcm_chunk(&[1, 0, 2, 0].repeat(800)); assert_eq!(fixture.transcription_starts.load(Ordering::SeqCst), 0); assert!(fixture.pcm.lock().unwrap().is_empty()); let tasks = std::mem::take(&mut *spawner.0.lock().unwrap()); @@ -3283,11 +3663,11 @@ mod tests { } if !stable { assert_eq!(fixture.transcription_starts.load(Ordering::SeqCst), 1); - assert_eq!(*fixture.pcm.lock().unwrap(), vec![1, 0, 2, 0]); + assert_eq!(*fixture.pcm.lock().unwrap(), [1, 0, 2, 0].repeat(800)); } assert_eq!(session.finish().await.unwrap().text, "raw text"); assert_eq!(fixture.transcription_starts.load(Ordering::SeqCst), 1); - assert_eq!(*fixture.pcm.lock().unwrap(), vec![1, 0, 2, 0]); + assert_eq!(*fixture.pcm.lock().unwrap(), [1, 0, 2, 0].repeat(800)); } } @@ -3315,7 +3695,7 @@ mod tests { .await .unwrap(); - assert_eq!(&*fixture.pcm.lock().unwrap(), &[1, 0, 2, 0]); + assert_eq!(*fixture.pcm.lock().unwrap(), [1, 0, 2, 0].repeat(800)); assert_eq!(fixture.recorder_stops.load(Ordering::SeqCst), 1); assert_eq!(result.raw_text, "raw text"); assert_eq!(result.polished_text, "polished text"); @@ -3367,7 +3747,7 @@ mod tests { assert_eq!(result.raw_text, "raw text"); assert_eq!(fixture.transcription_starts.load(Ordering::Acquire), 1); - assert_eq!(&*fixture.pcm.lock().unwrap(), &[1, 0, 2, 0]); + assert_eq!(*fixture.pcm.lock().unwrap(), [1, 0, 2, 0].repeat(800)); let transcript_events: Vec<_> = fixture .progress .events @@ -3441,7 +3821,7 @@ mod tests { assert_eq!(output.text, "raw text"); assert_eq!(fixture.transcription_starts.load(Ordering::Acquire), 1); - assert_eq!(&*fixture.pcm.lock().unwrap(), &[1, 0, 2, 0]); + assert_eq!(*fixture.pcm.lock().unwrap(), [1, 0, 2, 0].repeat(800)); } #[tokio::test] @@ -3511,7 +3891,7 @@ mod tests { Arc::new(DiscardTextStream), Arc::new(LimitRecordingProgress::default()), ); - buffered.consume_pcm_chunk(&[1, 0]); + buffered.consume_pcm_chunk(&[1, 0].repeat(1_600)); assert_eq!(buffered.finish().await.unwrap().text, "raw text"); assert_eq!(starts.load(Ordering::Acquire), 1); } @@ -3761,7 +4141,9 @@ mod tests { engine.finish(session_id, progress).await.unwrap(); - assert_eq!(&*pcm.lock().unwrap(), &[1, 0, 2, 0, 3, 0]); + let mut expected = [1u8, 0].repeat(1_600); + expected.extend_from_slice(&[2, 0, 3, 0]); + assert_eq!(*pcm.lock().unwrap(), expected); assert_eq!(stops.load(Ordering::Acquire), 1); } @@ -3926,7 +4308,9 @@ mod tests { } else { result.unwrap(); engine.finish(id, progress).await.unwrap(); - assert_eq!(&*pcm.lock().unwrap(), &[1, 0, 2, 0]); + let mut expected = [1u8, 0].repeat(1_600); + expected.extend_from_slice(&[2, 0]); + assert_eq!(*pcm.lock().unwrap(), expected); } assert_eq!(calls.load(Ordering::Acquire), 1); assert_eq!(stops.load(Ordering::Acquire), 1); @@ -4064,7 +4448,7 @@ mod tests { ); release.notify_one(); assert_eq!(finishing.await.unwrap().unwrap().raw_text, "raw text"); - assert_eq!(*pcm.lock().unwrap(), vec![1, 0]); + assert_eq!(*pcm.lock().unwrap(), [1u8, 0].repeat(1_600)); } } } @@ -4283,7 +4667,10 @@ mod tests { ] { let polisher = Arc::new(FixtureTextPolisher::successful("润色结果")); let engine = PipelineDictationEngine::new( - Arc::new(FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![])), + Arc::new(FixtureAudioRecorder::new( + vec![[1, 0, 2, 0].repeat(800)], + vec![], + )), Arc::new(FixtureTranscriptionEngine::successful(input, 1_000)), polisher.clone(), ); @@ -4334,7 +4721,10 @@ mod tests { "fixture", ))); let engine = PipelineDictationEngine::new( - Arc::new(FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![])), + Arc::new(FixtureAudioRecorder::new( + vec![[1, 0, 2, 0].repeat(800)], + vec![], + )), Arc::new(FixtureTranscriptionEngine::successful( "开始语音录入 正文 完成语音录入", 1000, @@ -4559,7 +4949,7 @@ mod tests { let archive = Arc::new(FixtureArchive { available: AtomicBool::new(true), discards: Arc::new(AtomicUsize::new(0)), - pcm: vec![1, 0, 2, 0], + pcm: [1, 0, 2, 0].repeat(800), }); let starts = Arc::new(AtomicUsize::new(0)); let pcm = Arc::new(Mutex::new(Vec::new())); @@ -4605,9 +4995,10 @@ mod tests { assert_eq!(result.raw_text, "retry success"); assert_eq!(starts.load(Ordering::Acquire), 2); + let expected = [1u8, 0, 2, 0].repeat(800); assert_eq!( pcm.lock().unwrap().as_slice(), - &[vec![1, 0, 2, 0], vec![1, 0, 2, 0]] + &[expected.clone(), expected] ); } @@ -4622,7 +5013,7 @@ mod tests { let archive = Arc::new(FixtureArchive { available: AtomicBool::new(archive_available), discards: Arc::new(AtomicUsize::new(0)), - pcm: vec![1, 0, 2, 0], + pcm: [1, 0, 2, 0].repeat(800), }); let starts = Arc::new(AtomicUsize::new(0)); let engine = PipelineDictationEngine::new( @@ -4795,7 +5186,7 @@ mod tests { archive: Arc::new(FixtureArchive { available: AtomicBool::new(true), discards: Arc::new(AtomicUsize::new(0)), - pcm: vec![1, 0, 2, 0], + pcm: [1, 0, 2, 0].repeat(800), }), fail: false, }), @@ -5504,4 +5895,481 @@ mod tests { ); assert!(engine.sessions.lock().unwrap().is_empty()); } + + #[tokio::test] + async fn sub_100ms_nonzero_pcm_is_rejected_before_asr_finalization() { + let pcm = Arc::new(Mutex::new(Vec::new())); + let starts = Arc::new(AtomicUsize::new(0)); + let transcriber = Arc::new(FixtureTranscriber { + session: Arc::new(FixtureTranscriptionSession { + pcm, + cancels: Arc::new(AtomicUsize::new(0)), + finish_entered: None, + finish_release: None, + }), + starts: Arc::clone(&starts), + }); + let prepared = transcriber + .prepare(SessionId::new(), raw_dictation_context()) + .await + .unwrap(); + let buffered = BufferedTranscriptionSession::new( + prepared, + Arc::new(DiscardTextStream), + Arc::new(LimitRecordingProgress::default()), + ); + buffered.consume_pcm_chunk(&[1, 0].repeat(1_599)); + let error = buffered.finish().await.unwrap_err(); + assert_eq!(error.code, BackendErrorCode::InvalidArgument); + assert_eq!(starts.load(Ordering::Acquire), 0); + } + + #[tokio::test] + async fn stable_capture_spills_only_when_archive_matches_processed_pcm() { + struct WaveformArchive { + processed: bool, + len: usize, + reads: AtomicUsize, + } + impl RecordingArchive for WaveformArchive { + fn is_available(&self) -> bool { + true + } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let len = self.len as u64; + Box::pin(async move { Ok(len) }) + } + fn read_pcm_range( + &self, + _: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + self.reads.fetch_add(1, Ordering::AcqRel); + let value = if self.processed { 2 } else { 1 }; + Box::pin(async move { Ok(vec![value; len]) }) + } + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + struct WaveformRecorder(Arc); + struct WaveformRecording(Arc); + impl ActiveRecording for WaveformRecording { + fn archive(&self) -> Option> { + Some(self.0.clone()) + } + fn stop(self: Box) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + impl AudioRecorder for WaveformRecorder { + fn start( + &self, + _: SessionId, + _: Arc, + consumer: Arc, + _: Arc, + ) -> BoxFuture<'static, Result, BackendError>> { + let archive = self.0.clone(); + Box::pin(async move { + // Live ASR always receives enhanced PCM, even with raw-only debug retention. + consumer.consume_pcm_chunk(&vec![2; archive.len]); + Ok(Box::new(WaveformRecording(archive)) as Box) + }) + } + } + for voice_capture in [false, true] { + for processed in [false, true] { + let archive = Arc::new(WaveformArchive { + processed, + len: STABLE_SPILL_THRESHOLD_BYTES + 3_200, + reads: AtomicUsize::new(0), + }); + let delivered = Arc::new(Mutex::new(Vec::new())); + let engine = PipelineDictationEngine::new( + Arc::new(WaveformRecorder(archive.clone())), + Arc::new(FixtureTranscriber { + session: Arc::new(FixtureTranscriptionSession { + pcm: delivered.clone(), + cancels: Arc::new(AtomicUsize::new(0)), + finish_entered: None, + finish_release: None, + }), + starts: Arc::new(AtomicUsize::new(0)), + }), + noop_polisher(), + ); + let mut context = (*raw_dictation_context()).clone(); + context.recording.transcribe_after_stop = true; + context.recording.archive_processed = processed; + context.recording.archive_raw = !processed; + let context = Arc::new(context); + let id = SessionId::new(); + if voice_capture { + let capture = engine + .start_voice_capture( + id, + context, + Arc::new(DiscardTextStream), + Arc::new(NoopRecordingProgress), + crate::CancellationToken::new(), + ) + .await + .unwrap(); + capture.recording.stop().await.unwrap(); + capture.transcription.finish().await.unwrap(); + } else { + let progress = Arc::new(RecordingProgress::default()); + engine.start(id, context, progress.clone()).await.unwrap(); + engine.finish(id, progress).await.unwrap(); + } + let pcm = delivered.lock().unwrap(); + assert_eq!(pcm.len(), archive.len); + assert!(pcm.iter().all(|&sample| sample == 2), "ASR input changed to raw archive: voice={voice_capture}, processed={processed}"); + assert_eq!(archive.reads.load(Ordering::Acquire) > 0, processed); + } + } + } + + #[tokio::test] + async fn stable_mode_spills_to_archive_when_threshold_exceeded_and_replays_ranged_chunks() { + struct RangedArchive { + pcm: Vec, + read_pcm_calls: AtomicUsize, + range_calls: Mutex>, + } + impl RecordingArchive for RangedArchive { + fn is_available(&self) -> bool { + true + } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let len = self.pcm.len() as u64; + Box::pin(async move { Ok(len) }) + } + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { + self.read_pcm_calls.fetch_add(1, Ordering::AcqRel); + Box::pin(async { + Err(BackendError::new( + BackendErrorCode::Internal, + "stable spill replay must use read_pcm_range", + )) + }) + } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + self.range_calls.lock().unwrap().push((offset, len)); + let start = offset as usize; + let end = start.saturating_add(len).min(self.pcm.len()); + let slice = self.pcm[start..end].to_vec(); + Box::pin(async move { Ok(slice) }) + } + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + + let delivered = Arc::new(Mutex::new(Vec::new())); + let starts = Arc::new(AtomicUsize::new(0)); + let transcriber = Arc::new(FixtureTranscriber { + session: Arc::new(FixtureTranscriptionSession { + pcm: Arc::clone(&delivered), + cancels: Arc::new(AtomicUsize::new(0)), + finish_entered: None, + finish_release: None, + }), + starts: Arc::clone(&starts), + }); + let prepared = transcriber + .prepare(SessionId::new(), raw_dictation_context()) + .await + .unwrap(); + let full_pcm = (0..3_216u32) + .map(|i| ((i % 251) as u8) | 1) + .collect::>(); + let archive = Arc::new(RangedArchive { + pcm: full_pcm.clone(), + read_pcm_calls: AtomicUsize::new(0), + range_calls: Mutex::new(Vec::new()), + }); + let buffered = BufferedTranscriptionSession::new_with_thresholds( + prepared, + Arc::new(DiscardTextStream), + Arc::new(LimitRecordingProgress::default()), + 128 * 1024 * 1024, + 16, + ); + buffered.enable_archive_spill(archive.clone()); + buffered.consume_pcm_chunk(&full_pcm[..3_200]); + assert!(matches!( + &*buffered.inner.state.lock().unwrap(), + BufferedTranscriptionState::SpilledToArchive { .. } + )); + buffered.consume_pcm_chunk(&full_pcm[3_200..]); + assert_eq!(buffered.finish().await.unwrap().text, "raw text"); + assert_eq!(starts.load(Ordering::Acquire), 1); + assert_eq!(archive.read_pcm_calls.load(Ordering::Acquire), 0); + assert!(!archive.range_calls.lock().unwrap().is_empty()); + assert_eq!(*delivered.lock().unwrap(), full_pcm); + } + + #[tokio::test] + async fn long_recording_recovery_reads_ranged_archive_chunks_without_loading_whole_pcm() { + struct LongRangedArchive { + total_bytes: u64, + read_pcm_calls: AtomicUsize, + range_calls: Mutex>, + } + impl RecordingArchive for LongRangedArchive { + fn is_available(&self) -> bool { + true + } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let len = self.total_bytes; + Box::pin(async move { Ok(len) }) + } + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { + self.read_pcm_calls.fetch_add(1, Ordering::AcqRel); + Box::pin(async { + Err(BackendError::new( + BackendErrorCode::Internal, + "long recovery must use read_pcm_range", + )) + }) + } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + self.range_calls.lock().unwrap().push((offset, len)); + let fill = + ((offset / crate::long_recording::RECOVERY_CHUNK_BYTES as u64) as u8) + 1; + let actual = (self.total_bytes - offset).min(len as u64) as usize; + Box::pin(async move { Ok(vec![fill; actual]) }) + } + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + struct LongRecorder(Arc); + struct LongRecording(Arc); + impl ActiveRecording for LongRecording { + fn archive(&self) -> Option> { + Some(self.0.clone()) + } + fn stop(self: Box) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + impl AudioRecorder for LongRecorder { + fn start( + &self, + _: SessionId, + _: Arc, + consumer: Arc, + _: Arc, + ) -> BoxFuture<'static, Result, BackendError>> { + let total = self.0.total_bytes as usize; + consumer.consume_pcm_chunk(&vec![1; total]); + let archive = self.0.clone(); + Box::pin( + async move { Ok(Box::new(LongRecording(archive)) as Box) }, + ) + } + } + + let total_bytes = (crate::long_recording::THRESHOLD_MS / 1_000) * 32_000 + 3_200; + let archive = Arc::new(LongRangedArchive { + total_bytes, + read_pcm_calls: AtomicUsize::new(0), + range_calls: Mutex::new(Vec::new()), + }); + let pcm = Arc::new(Mutex::new(Vec::new())); + let starts = Arc::new(AtomicUsize::new(0)); + let outputs = VecDeque::from([ + Err(BackendError::new(BackendErrorCode::Provider, "temporary").retryable(true)), + Ok(TranscriptOutput { + text: "seg1".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "seg2".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "seg3".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "seg4".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "seg5".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "seg6".into(), + duration_ms: 100, + }), + ]); + let engine = PipelineDictationEngine::new( + Arc::new(LongRecorder(Arc::clone(&archive))), + Arc::new(RetryTranscriber { + outputs: Arc::new(Mutex::new(outputs)), + starts: Arc::clone(&starts), + pcm, + }), + noop_polisher(), + ); + let progress = Arc::new(RecordingProgress::default()); + let session_id = SessionId::new(); + let mut context = (*raw_dictation_context()).clone(); + context.asr.provider_type = "whisper".into(); + context.recording.transcribe_after_stop = true; + engine + .start(session_id, Arc::new(context), progress.clone()) + .await + .unwrap(); + let result = engine.finish(session_id, progress).await.unwrap(); + assert_eq!(result.raw_text, "seg1\nseg2\nseg3\nseg4\nseg5\nseg6"); + assert_eq!( + result.duration_ms, + crate::long_recording::duration_ms(total_bytes) + ); + assert_eq!(archive.read_pcm_calls.load(Ordering::Acquire), 0); + let ranges = archive.range_calls.lock().unwrap().clone(); + let spill_count = ranges + .len() + .checked_sub(6) + .expect("expected 6 recovery reads"); + assert!(spill_count > 0); + assert!(ranges[..spill_count].iter().all(|(_, len)| *len <= 65_536)); + assert_eq!( + ranges[..spill_count] + .iter() + .map(|(_, len)| *len as u64) + .sum::(), + total_bytes + ); + let recovery = &ranges[spill_count..]; + assert_eq!( + recovery[0], + (0, crate::long_recording::RECOVERY_CHUNK_BYTES) + ); + assert_eq!( + recovery[5], + ( + 5 * crate::long_recording::RECOVERY_CHUNK_BYTES as u64, + 3_200 + ) + ); + } + + #[tokio::test] + async fn local_standby_transcribes_long_archive_in_60_second_ranged_segments() { + struct StandbyRangedArchive { + total_bytes: u64, + read_pcm_calls: AtomicUsize, + range_calls: Mutex>, + } + impl RecordingArchive for StandbyRangedArchive { + fn is_available(&self) -> bool { + true + } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let len = self.total_bytes; + Box::pin(async move { Ok(len) }) + } + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { + self.read_pcm_calls.fetch_add(1, Ordering::AcqRel); + Box::pin(async { + Err(BackendError::new( + BackendErrorCode::Internal, + "local standby must use read_pcm_range", + )) + }) + } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + self.range_calls.lock().unwrap().push((offset, len)); + let actual = (self.total_bytes - offset).min(len as u64) as usize; + Box::pin(async move { Ok(vec![1u8; actual]) }) + } + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } + } + let total_bytes = (crate::long_recording::THRESHOLD_MS / 1_000) * 32_000 + 3_200; + let archive = Arc::new(StandbyRangedArchive { + total_bytes, + read_pcm_calls: AtomicUsize::new(0), + range_calls: Mutex::new(Vec::new()), + }); + let outputs = Mutex::new(std::collections::HashMap::from([( + "whisper-local".to_string(), + VecDeque::from([ + Ok(TranscriptOutput { + text: "part1".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "part2".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: String::new(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "part4".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "part5".into(), + duration_ms: 60_000, + }), + Ok(TranscriptOutput { + text: "part6".into(), + duration_ms: 100, + }), + ]), + )])); + let engine = Arc::new(RoutedTranscriber { + outputs, + started: Arc::new(Mutex::new(Vec::new())), + delays: std::collections::HashMap::new(), + }); + let mut context = (*raw_dictation_context()).clone(); + let mut fallback = context.asr.clone(); + fallback.provider_type = "whisper-local".into(); + context.asr_fallback = Some(fallback); + let context = Arc::new(context); + let session = Arc::new(PipelineSession::new(Arc::clone(&context))); + let standby = + LocalStandby::new(engine, context, session, SessionId::new(), archive.clone()); + let (output, _, _) = standby.result().await.expect("standby must succeed"); + assert_eq!(output.text, "part1\npart2\npart4\npart5\npart6"); + assert_eq!( + output.duration_ms, + crate::long_recording::duration_ms(total_bytes) + ); + assert_eq!(archive.read_pcm_calls.load(Ordering::Acquire), 0); + let ranges = archive.range_calls.lock().unwrap().clone(); + assert_eq!(ranges.len(), 6); + assert_eq!(ranges[0], (0, crate::long_recording::RECOVERY_CHUNK_BYTES)); + assert_eq!( + ranges[5], + ( + 5 * crate::long_recording::RECOVERY_CHUNK_BYTES as u64, + 3_200 + ) + ); + } } diff --git a/openless-all/app/crates/openless-core/src/external_audio/archive.rs b/openless-all/app/crates/openless-core/src/external_audio/archive.rs index 57efdfacf..bd616d841 100644 --- a/openless-all/app/crates/openless-core/src/external_audio/archive.rs +++ b/openless-all/app/crates/openless-core/src/external_audio/archive.rs @@ -171,6 +171,30 @@ impl RecordingArchive for ExternalRecordingArchive { self.available.load(Ordering::Acquire) } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let path = self.path.clone(); + Box::pin(async move { + let mut file = std::fs::File::open(path).map_err(|error| { + BackendError::new(BackendErrorCode::Persistence, error.to_string()) + })?; + crate::audio::canonical_archive_pcm_len(&mut file) + }) + } + + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + let path = self.path.clone(); + Box::pin(async move { + let mut file = std::fs::File::open(path).map_err(|error| { + BackendError::new(BackendErrorCode::Persistence, error.to_string()) + })?; + crate::audio::read_canonical_archive_pcm_range(&mut file, offset, len) + }) + } + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { let path = self.path.clone(); Box::pin(async move { @@ -218,3 +242,33 @@ impl RecordingArchive for ExternalRecordingArchive { Box::pin(async move { result }) } } + +#[cfg(test)] +mod range_tests { + use super::*; + #[tokio::test] + async fn external_archive_reads_ranges_and_refuses_truncated_payloads() { + let directory = + std::env::temp_dir().join(format!("openless-external-range-{}", uuid::Uuid::new_v4())); + let archive = ExternalRecordingArchive::create( + &directory, + SessionId::new(), + &crate::DictationContext::default().recording, + ) + .unwrap(); + archive.append(&[1, 2, 3, 4, 5, 6]); + archive.finish(); + assert_eq!(archive.pcm_byte_len().await.unwrap(), 6); + assert_eq!(archive.read_pcm_range(2, 4).await.unwrap(), [3, 4, 5, 6]); + assert!(archive.read_pcm_range(4, 4).await.is_err()); + std::fs::OpenOptions::new() + .write(true) + .open(&archive.path) + .unwrap() + .set_len(46) + .unwrap(); + assert!(archive.pcm_byte_len().await.is_err()); + archive.discard().await.unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/openless-all/app/crates/openless-core/src/ports.rs b/openless-all/app/crates/openless-core/src/ports.rs index 1c9382a45..51192e2f5 100644 --- a/openless-all/app/crates/openless-core/src/ports.rs +++ b/openless-all/app/crates/openless-core/src/ports.rs @@ -297,7 +297,11 @@ pub enum EngineStage { pub enum EngineProgress { /// The recorder is registered; provider preparation may still be pending. CaptureReady, - RecordingLevel { elapsed_ms: u64, level: f32 }, + RecordingLevel { + elapsed_ms: u64, + level: f32, + }, + CapturedDurationMs(u64), RecordingLimitReached, RecordingFault(BackendError), Notification(crate::types::NotificationPayload), @@ -359,7 +363,10 @@ pub trait DictationEngine: Send + Sync + 'static { /// Retain an early stop request, preserving PCM and stop errors for finish(). /// Returns false until the session is registered, or for legacy engines. - fn stop_recording(&self, _session_id: SessionId) -> BoxFuture<'static, Result> { + fn stop_recording( + &self, + _session_id: SessionId, + ) -> BoxFuture<'static, Result> { Box::pin(async { Ok(false) }) } @@ -606,6 +613,24 @@ pub trait RecordingArchive: Send + Sync { }) } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + let read = self.read_pcm(); + Box::pin(async move { + let pcm = read.await?; + let start = usize::try_from(offset).unwrap_or(usize::MAX).min(pcm.len()); + let end = start.saturating_add(len).min(pcm.len()); + Ok(pcm[start..end].to_vec()) + }) + } + + fn write_error(&self) -> Option { + None + } + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>>; } @@ -826,7 +851,9 @@ pub trait TextPolisher: Send + Sync { pub trait TextInserter: Send + Sync { /// Desktop keyboard/input-source preparation must run in the serialized /// processing lane, so a recording never owns another segment's native state. - fn defer_preparation_until_stop(&self) -> bool { false } + fn defer_preparation_until_stop(&self) -> bool { + false + } /// Freeze the native destination and its matching host-context reader before context or /// credentials can await. Only capture identity here; input-source changes belong to `begin` /// and its existing cancellation cleanup. Target-independent adapters use None. diff --git a/openless-all/app/crates/openless-core/src/qa_service/standalone/tests.rs b/openless-all/app/crates/openless-core/src/qa_service/standalone/tests.rs index 3feae36ef..b0629bc7d 100644 --- a/openless-all/app/crates/openless-core/src/qa_service/standalone/tests.rs +++ b/openless-all/app/crates/openless-core/src/qa_service/standalone/tests.rs @@ -173,11 +173,13 @@ impl SearchTool for Search { } } +type PdfPages = HashMap)>)>; + #[derive(Default)] struct Attachments( Mutex>, Mutex)>>, - Mutex)>)>>, + Mutex, ); impl AttachmentReader for Attachments { diff --git a/openless-all/app/crates/openless-core/src/recording_overlap_tests.rs b/openless-all/app/crates/openless-core/src/recording_overlap_tests.rs index ecc8be7fd..363dbef5a 100644 --- a/openless-all/app/crates/openless-core/src/recording_overlap_tests.rs +++ b/openless-all/app/crates/openless-core/src/recording_overlap_tests.rs @@ -42,7 +42,7 @@ async fn submitted_segments_release_capture_and_isolate_success_failure_and_canc ); let owner = self.owner.clone(); Box::pin(async move { - consumer.consume_pcm_chunk(&[index as u8, 1]); + consumer.consume_pcm_chunk(&[index as u8, 1].repeat(1_600)); consumer.consume_pcm_chunk(&[index as u8, 2]); Ok(Box::new(Recording { owner, @@ -575,8 +575,12 @@ async fn submitted_segments_release_capture_and_isolate_success_failure_and_canc sessions.iter().map(|(id, _)| *id).collect::>(), [first, second] ); - assert_eq!(*sessions[0].1.pcm.lock().unwrap(), [1, 1, 1, 2, 1, 3]); - assert_eq!(*sessions[1].1.pcm.lock().unwrap(), [2, 1, 2, 2, 2, 3]); + let mut expected_first = [1u8, 1].repeat(1_600); + expected_first.extend_from_slice(&[1, 2, 1, 3]); + let mut expected_second = [2u8, 1].repeat(1_600); + expected_second.extend_from_slice(&[2, 2, 2, 3]); + assert_eq!(*sessions[0].1.pcm.lock().unwrap(), expected_first); + assert_eq!(*sessions[1].1.pcm.lock().unwrap(), expected_second); let history = backend.list_history().unwrap(); assert!(history.iter().any(|entry| entry.id == second.to_string() && entry.raw_transcript == "second" @@ -635,7 +639,7 @@ async fn rapid_three_submissions_keep_pcm_and_join_final_input_before_the_next() _: Arc, ) -> BoxFuture<'static, Result, BackendError>> { let n = self.0.fetch_add(1, Ordering::SeqCst) + 1; - consumer.consume_pcm_chunk(&[n as u8, 1]); + consumer.consume_pcm_chunk(&[n as u8, 1].repeat(1_600)); consumer.consume_pcm_chunk(&[n as u8, 2]); Box::pin( async move { Ok(Box::new(Recording(n, consumer)) as Box) }, @@ -725,9 +729,13 @@ async fn rapid_three_submissions_keep_pcm_and_join_final_input_before_the_next() // performs only final delivery, whose ordering is asserted below. let preferences = crate::shared_types::UserPreferences::default(); assert_eq!(context.insertion.streaming, preferences.streaming_insert); - assert_eq!(context.insertion.composition_input, - cfg!(target_os = "windows") && preferences.windows_composition_input - && preferences.windows_insertion_mode == crate::shared_types::WindowsInsertionMode::Tsf); + assert_eq!( + context.insertion.composition_input, + cfg!(target_os = "windows") + && preferences.windows_composition_input + && preferences.windows_insertion_mode + == crate::shared_types::WindowsInsertionMode::Tsf + ); let session = Arc::new(Insertion { calls: self.calls.clone(), entered: self.entered.clone(), @@ -862,7 +870,9 @@ async fn rapid_three_submissions_keep_pcm_and_join_final_input_before_the_next() assert_eq!(*calls.lock().unwrap(), expected); for (index, item) in audio.lock().unwrap().iter().enumerate() { let n = index as u8 + 1; - assert_eq!(*item.pcm.lock().unwrap(), [n, 1, n, 2, n, 3]); + let mut expected = [n, 1].repeat(1_600); + expected.extend_from_slice(&[n, 2, n, 3]); + assert_eq!(*item.pcm.lock().unwrap(), expected); } let history = backend.list_history().unwrap(); for (index, id) in ids.iter().enumerate().skip(1) { diff --git a/openless-all/app/crates/openless-core/src/shared_types.rs b/openless-all/app/crates/openless-core/src/shared_types.rs index 895a65cac..b5f1fc683 100644 --- a/openless-all/app/crates/openless-core/src/shared_types.rs +++ b/openless-all/app/crates/openless-core/src/shared_types.rs @@ -435,6 +435,9 @@ pub struct UserPreferences { /// Authoritative mode established by a V2 client; absent on untouched legacy settings. #[serde(default, skip_serializing_if = "Option::is_none")] pub capsule_display_mode_v2: Option, + /// None means never chosen on this device; Some(1) is an explicit reset to the default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub translation_shift_tap_count: Option, #[serde(default = "default_true")] pub capsule_transcript_enabled: bool, #[serde(default = "default_capsule_transcript_font_size")] @@ -598,8 +601,9 @@ pub struct UserPreferences { /// Additional key held with the user-selected recording shortcut. Empty disables Ask. #[serde(default = "default_qa_companion_key")] pub qa_companion_key: String, - #[serde(default)] - pub qa_shortcut_behavior: QaShortcutBehavior, + /// Kept in the device profile for compatibility with older Ask builds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub qa_shortcut_behavior: Option, /// Standalone quick-note hotkey. None = not configured; when enabled, press once to start and again to stop. #[serde(default)] pub quick_note_hotkey: Option, @@ -973,6 +977,11 @@ pub struct UserPreferences { } impl UserPreferences { + pub fn translation_shift_tap_count(&self) -> u8 { + self.translation_shift_tap_count + .map_or(1, std::num::NonZeroU8::get) + } + pub fn less_computer_available(&self) -> bool { self.testing_features_enabled && self.coding_agent_enabled } @@ -1065,6 +1074,8 @@ struct UserPreferencesWire { #[serde(default)] capsule_display_mode: CapsuleDisplayMode, capsule_display_mode_v2: Option, + #[serde(skip_serializing_if = "Option::is_none")] + translation_shift_tap_count: Option, #[serde(default = "default_true")] capsule_transcript_enabled: bool, #[serde(default = "default_capsule_transcript_font_size")] @@ -1147,8 +1158,8 @@ struct UserPreferencesWire { qa_hotkey: Option, #[serde(default = "default_qa_companion_key")] qa_companion_key: String, - #[serde(default)] - qa_shortcut_behavior: QaShortcutBehavior, + #[serde(default, skip_serializing_if = "Option::is_none")] + qa_shortcut_behavior: Option, #[serde(default)] quick_note_hotkey: Option, /// Outer `None` means the field was absent in a pre-Selection-Polish file; @@ -1374,6 +1385,7 @@ impl Default for UserPreferencesWire { capsule_style: prefs.capsule_style, capsule_display_mode: prefs.capsule_display_mode, capsule_display_mode_v2: prefs.capsule_display_mode_v2, + translation_shift_tap_count: prefs.translation_shift_tap_count, capsule_transcript_enabled: prefs.capsule_transcript_enabled, capsule_transcript_font_size: prefs.capsule_transcript_font_size, mute_during_recording: prefs.mute_during_recording, @@ -1604,6 +1616,7 @@ impl<'de> Deserialize<'de> for UserPreferences { capsule_display_mode_v2: wire .capsule_display_mode_v2 .or_else(|| wire.capsule_display_mode.extended_sync_mode()), + translation_shift_tap_count: wire.translation_shift_tap_count, capsule_transcript_enabled: wire.capsule_transcript_enabled, capsule_transcript_font_size: wire.capsule_transcript_font_size.clamp(12, 20), mute_during_recording: wire.mute_during_recording, @@ -1652,7 +1665,11 @@ impl<'de> Deserialize<'de> for UserPreferences { translation_target_language: wire.translation_target_language, chinese_script_preference: wire.chinese_script_preference, output_language_preference: wire.output_language_preference, - qa_hotkey: if cfg!(target_os = "linux") { wire.qa_hotkey } else { None }, // retired desktop follow-up shortcut + qa_hotkey: if cfg!(target_os = "linux") { + wire.qa_hotkey + } else { + None + }, // retired desktop follow-up shortcut qa_companion_key: wire.qa_companion_key, qa_shortcut_behavior: wire.qa_shortcut_behavior, quick_note_hotkey: wire.quick_note_hotkey, @@ -1880,7 +1897,11 @@ fn salvage_without_incomplete_legacy_hotkey( } fn default_qa_hotkey() -> Option { - if cfg!(target_os = "linux") { Some(ShortcutBinding::default_qa()) } else { None } + if cfg!(target_os = "linux") { + Some(ShortcutBinding::default_qa()) + } else { + None + } } /// Initial action of the recording shortcut plus the Ask companion key. @@ -1893,7 +1914,9 @@ pub enum QaShortcutBehavior { Draft, } -fn default_qa_companion_key() -> String { "Space".into() } +fn default_qa_companion_key() -> String { + "Space".into() +} fn default_selection_polish_hotkey() -> Option { #[cfg(target_os = "windows")] @@ -2022,6 +2045,7 @@ impl Default for UserPreferences { capsule_style: CapsuleStyle::Classic, capsule_display_mode: CapsuleDisplayMode::CursorScreen, capsule_display_mode_v2: None, + translation_shift_tap_count: None, capsule_transcript_enabled: true, capsule_transcript_font_size: default_capsule_transcript_font_size(), mute_during_recording: false, @@ -2063,7 +2087,7 @@ impl Default for UserPreferences { output_language_preference: OutputLanguagePreference::Auto, qa_hotkey: default_qa_hotkey(), qa_companion_key: default_qa_companion_key(), - qa_shortcut_behavior: QaShortcutBehavior::default(), + qa_shortcut_behavior: None, quick_note_hotkey: None, selection_polish_hotkey: default_selection_polish_hotkey(), selection_polish_style_pack_id: default_active_style_pack_id(), @@ -3161,10 +3185,14 @@ mod tests { value["qaHotkey"] = serde_json::json!({"primary":";", "modifiers":["cmd","shift"]}); let migrated: UserPreferences = serde_json::from_value(value).unwrap(); assert_eq!(migrated.qa_companion_key, "Space"); - if !cfg!(target_os = "linux") { assert!(migrated.qa_hotkey.is_none()); } + if !cfg!(target_os = "linux") { + assert!(migrated.qa_hotkey.is_none()); + } for key in ["F9", ""] { - let mut prefs = migrated.clone(); prefs.qa_companion_key = key.into(); - let restored: UserPreferences = serde_json::from_value(serde_json::to_value(prefs).unwrap()).unwrap(); + let mut prefs = migrated.clone(); + prefs.qa_companion_key = key.into(); + let restored: UserPreferences = + serde_json::from_value(serde_json::to_value(prefs).unwrap()).unwrap(); assert_eq!(restored.qa_companion_key, key); } } @@ -3546,9 +3574,13 @@ mod tests { fn capsule_style_pref_defaults_to_openless_and_migrates_typeless() { let prefs: UserPreferences = serde_json::from_str("{}").unwrap(); assert_eq!(prefs.capsule_style, CapsuleStyle::Classic); - let legacy: UserPreferences = serde_json::from_str(r#"{"capsuleStyle":"typeless"}"#).unwrap(); + let legacy: UserPreferences = + serde_json::from_str(r#"{"capsuleStyle":"typeless"}"#).unwrap(); assert_eq!(legacy.capsule_style, CapsuleStyle::Classic); - assert_eq!(serde_json::to_value(legacy).unwrap()["capsuleStyle"], "classic"); + assert_eq!( + serde_json::to_value(legacy).unwrap()["capsuleStyle"], + "classic" + ); for (style, wire_name) in [ (CapsuleStyle::Siri, "siri"), diff --git a/openless-all/app/crates/openless-core/src/web_search/public_sources.rs b/openless-all/app/crates/openless-core/src/web_search/public_sources.rs index 297e49a6f..b79b96495 100644 --- a/openless-all/app/crates/openless-core/src/web_search/public_sources.rs +++ b/openless-all/app/crates/openless-core/src/web_search/public_sources.rs @@ -435,7 +435,7 @@ mod tests { let server = tokio::spawn(async move { let (mut socket, _) = listener.accept().await.unwrap(); let mut bytes = [0; 8192]; - socket.read(&mut bytes).await.unwrap(); + assert!(socket.read(&mut bytes).await.unwrap() > 0); // The client must close its pending response when the source times out. assert_eq!(socket.read(&mut bytes).await.unwrap(), 0); }); diff --git a/openless-all/app/crates/openless-core/tests/auxiliary_voice_lifecycle.rs b/openless-all/app/crates/openless-core/tests/auxiliary_voice_lifecycle.rs index f83b17ec1..a5c25303b 100644 --- a/openless-all/app/crates/openless-core/tests/auxiliary_voice_lifecycle.rs +++ b/openless-all/app/crates/openless-core/tests/auxiliary_voice_lifecycle.rs @@ -86,7 +86,7 @@ impl RecordingArchive for Archive { self.0.load(Ordering::SeqCst) == 0 } fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { - Box::pin(async { Ok(vec![0, 1]) }) + Box::pin(async { Ok([0u8, 1].repeat(1_600)) }) } fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { self.0.fetch_add(1, Ordering::SeqCst); @@ -121,7 +121,7 @@ impl AudioRecorder for Recorder { _: Arc, ) -> BoxFuture<'static, Result, BackendError>> { self.starts.fetch_add(1, Ordering::SeqCst); - consumer.consume_pcm_chunk(&[1, 0]); + consumer.consume_pcm_chunk(&[1u8, 0].repeat(1_600)); let recording = Recording { stopped: self.stopped.clone(), gate: self.stop_gate.clone(), @@ -318,6 +318,15 @@ fn backend( let mut dependencies = BackendDependencies::unsupported(); dependencies.host_actions = Arc::new(Host); dependencies.qa_runtime = Some(qa); + dependencies.selection_polisher = + Some(Arc::new(testing::FixtureTextPolisher::successful("unused"))); + dependencies.selection_runtime = Some(Arc::new(testing::FixtureSelectionRuntime::successful( + SelectionCapture { + text: String::new(), + source_app: None, + }, + InsertOutcome::Inserted, + ))); dependencies.dictation_engine = Arc::new(PipelineDictationEngine::new( recorder, asr, @@ -353,7 +362,7 @@ async fn qa_and_selection_voice_never_request_disk_archives() { "less", ] { let plans = Arc::new(Mutex::new(Vec::new())); - let recorder = testing::FixtureAudioRecorder::new(vec![vec![1; 320]], Vec::new()); + let recorder = testing::FixtureAudioRecorder::new(vec![vec![1; 3_200]], Vec::new()); let (backend, path) = backend( Arc::new(ArchivePolicyRecorder { inner: recorder.clone(), @@ -493,7 +502,7 @@ async fn stable_mode_is_shared_by_dictation_qa_selection_and_less_computer() { let starts = Arc::new(AtomicUsize::new(0)); let (backend, path) = backend( Arc::new(testing::FixtureAudioRecorder::new( - vec![vec![1; 320]], + vec![vec![1; 3_200]], Vec::new(), )), Arc::new(CountingAsr { @@ -1257,12 +1266,17 @@ async fn non_inserting_dictation_keeps_gate_while_native_stop_is_in_flight() { async move { backend.stop_dictation_session(id).await } }); stopped.acquire().await.unwrap().forget(); - backend.cancel_dictation(Some(id)).await.unwrap(); + let cancelling = tokio::spawn({ + let backend = backend.clone(); + async move { backend.cancel_dictation(Some(id)).await } + }); + tokio::task::yield_now().await; let next = SessionId::new(); let while_stopping = backend.begin_less_computer_capture(next); finishing.abort(); let _ = finishing.await; stop_gate.add_permits(1); + cancelling.await.unwrap().unwrap(); assert_eq!(while_stopping.unwrap_err().code, BackendErrorCode::Busy); tokio::time::timeout(std::time::Duration::from_secs(2), async { loop { @@ -1539,7 +1553,7 @@ async fn less_voice_finish_errors_publish_one_safe_error_but_cancellation_does_n Arc::new(StopFailure) } else { Arc::new(testing::FixtureAudioRecorder::new( - vec![vec![1, 0]], + vec![[1u8, 0].repeat(1_600)], Vec::new(), )) }; diff --git a/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs b/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs index 712fe9cdd..3cba44068 100644 --- a/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs +++ b/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs @@ -17,7 +17,6 @@ use openless_core::{ }; use tokio::sync::Notify; - #[derive(Default)] struct DelayedCredentials { store: InMemoryCredentialStore, @@ -73,7 +72,6 @@ impl CredentialStore for DelayedCredentials { } } - struct Focus { current: &'static str, captured: Vec<&'static str>, @@ -128,29 +126,49 @@ impl HostContextAdapter for FocusContextAdapter { } } -struct FocusInserter { focus: Arc>, target: Option<&'static str> } +struct FocusInserter { + focus: Arc>, + target: Option<&'static str>, +} impl TextInserter for FocusInserter { - fn defer_preparation_until_stop(&self) -> bool { true } + fn defer_preparation_until_stop(&self) -> bool { + true + } fn capture_target(&self) -> Option { let mut focus = self.focus.lock().unwrap(); let target = focus.current; focus.captured.push(target); Some(CapturedTextTarget { - inserter: Arc::new(Self { focus: self.focus.clone(), target: Some(target) }), - host_context: Arc::new(FocusContextAdapter { focus: self.focus.clone(), target }), + inserter: Arc::new(Self { + focus: self.focus.clone(), + target: Some(target), + }), + host_context: Arc::new(FocusContextAdapter { + focus: self.focus.clone(), + target, + }), }) } - fn begin(&self, _: SessionId, context: Arc) - -> BoxFuture<'static, Result, BackendError>> { + fn begin( + &self, + _: SessionId, + context: Arc, + ) -> BoxFuture<'static, Result, BackendError>> { let _ = context; let mut focus = self.focus.lock().unwrap(); let target = self.target.unwrap_or(focus.current); focus.prepared.push(target); - let session: Arc = Arc::new(FocusSession { focus: self.focus.clone(), target }); + let session: Arc = Arc::new(FocusSession { + focus: self.focus.clone(), + target, + }); Box::pin(async move { Ok(session) }) } } -struct FocusSession { focus: Arc>, target: &'static str } +struct FocusSession { + focus: Arc>, + target: &'static str, +} impl TextInsertionSession for FocusSession { fn write(&self, _: String) -> BoxFuture<'static, Result> { panic!("ordinary dictation must not stream into the target") @@ -169,7 +187,9 @@ impl TextInsertionSession for FocusSession { focus.delivered.push((self.target, text)); Box::pin(async { Ok(InsertOutcome::Inserted) }) } - fn cancel(&self) -> BoxFuture<'static, Result<(), BackendError>> { Box::pin(async { Ok(()) }) } + fn cancel(&self) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } } struct Fixture { @@ -343,25 +363,37 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() release: Arc, } impl DictationEngine for DelayedResult { - fn start(&self, id: SessionId, context: Arc, progress: Arc) - -> BoxFuture<'static, Result<(), BackendError>> { + fn start( + &self, + id: SessionId, + context: Arc, + progress: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { self.inner.start(id, context, progress) } fn stop_recording(&self, _: SessionId) -> BoxFuture<'static, Result> { Box::pin(async { Ok(true) }) } - fn finish(&self, id: SessionId, progress: Arc) - -> BoxFuture<'static, Result> { + fn finish( + &self, + id: SessionId, + progress: Arc, + ) -> BoxFuture<'static, Result> { let first = !self.finishing.swap(true, Ordering::AcqRel); let entered = self.entered.clone(); let release = self.release.clone(); let finishing = self.inner.finish(id, progress); Box::pin(async move { - if first { entered.notify_one(); release.notified().await; } + if first { + entered.notify_one(); + release.notified().await; + } finishing.await }) } - fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { self.inner.cancel(id) } + fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + self.inner.cancel(id) + } } for (initial, moved, next_capture) in [ @@ -374,14 +406,21 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() let release = Arc::new(Notify::new()); let engine = Arc::new(DelayedResult { inner: FixtureDictationEngine::successful("spoken", "retained result"), - finishing: AtomicBool::new(false), entered: entered.clone(), release: release.clone(), + finishing: AtomicBool::new(false), + entered: entered.clone(), + release: release.clone(), }); let fixture = Fixture::with_position_engine(|_| engine, true).await; fixture.credentials.waited.store(true, Ordering::Release); fixture.focus.lock().unwrap().position = initial; let first = fixture.backend.start_dictation().await.unwrap(); - let stopping = tokio::spawn({ let backend = fixture.backend.clone(); async move { backend.stop_dictation_session(first).await } }); - tokio::time::timeout(std::time::Duration::from_secs(2), entered.notified()).await.unwrap(); + let stopping = tokio::spawn({ + let backend = fixture.backend.clone(); + async move { backend.stop_dictation_session(first).await } + }); + tokio::time::timeout(std::time::Duration::from_secs(2), entered.notified()) + .await + .unwrap(); fixture.focus.lock().unwrap().position = moved; let second = if next_capture { fixture.focus.lock().unwrap().current = "B"; @@ -393,16 +432,34 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() let result = stopping.await.unwrap().unwrap(); assert_eq!(result.session_id, first); assert_eq!(fixture.focus.lock().unwrap().delivered.len(), 1); - assert_eq!(fixture.focus.lock().unwrap().delivered_positions, - moved.into_iter().collect::>()); + assert_eq!( + fixture.focus.lock().unwrap().delivered_positions, + moved.into_iter().collect::>() + ); if let Some(second) = second { - assert_eq!(fixture.backend.snapshot().dictation.session_id, Some(second)); - fixture.backend.stop_dictation_session(second).await.unwrap(); - assert_eq!(fixture.focus.lock().unwrap().delivered, [ - ("A", "retained result".into()), ("B", "retained result".into()), - ]); + assert_eq!( + fixture.backend.snapshot().dictation.session_id, + Some(second) + ); + fixture + .backend + .stop_dictation_session(second) + .await + .unwrap(); + assert_eq!( + fixture.focus.lock().unwrap().delivered, + [ + ("A", "retained result".into()), + ("B", "retained result".into()), + ] + ); } - assert!(fixture.backend.list_history().unwrap().iter().all(|row| row.error_code.is_none())); + assert!(fixture + .backend + .list_history() + .unwrap() + .iter() + .all(|row| row.error_code.is_none())); } } @@ -444,7 +501,7 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres assert_eq!(self.owner.swap(number, Ordering::SeqCst), 0); let owner = self.owner.clone(); Box::pin(async move { - consumer.consume_pcm_chunk(&[number as u8, 1]); + consumer.consume_pcm_chunk(&[number as u8, 1].repeat(1_600)); consumer.consume_pcm_chunk(&[number as u8, 2]); Ok(Box::new(Recording { owner, @@ -616,13 +673,27 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres }; let epoch = std::time::Instant::now() - std::time::Duration::from_secs(1); - let first = match backend.dispatch_dictation_hotkey_edge_with_options( - DictationHotkeyEdge::Pressed { press_id: 101, at: epoch }, options.clone()).await.unwrap() { - CliDispatchOutcome::DictationStarted(id) => id, other => panic!("{other:?}"), - }; - backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { - press_id: 101, at: epoch + std::time::Duration::from_millis(40), - }).await.unwrap(); + let first = match backend + .dispatch_dictation_hotkey_edge_with_options( + DictationHotkeyEdge::Pressed { + press_id: 101, + at: epoch, + }, + options.clone(), + ) + .await + .unwrap() + { + CliDispatchOutcome::DictationStarted(id) => id, + other => panic!("{other:?}"), + }; + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { + press_id: 101, + at: epoch + std::time::Duration::from_millis(40), + }) + .await + .unwrap(); backend .toggle_dictation_translation_for_session(first) .unwrap(); @@ -631,18 +702,47 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres .unwrap(); let stopping = tokio::spawn({ let backend = backend.clone(); - async move { backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Pressed { press_id: 102, at: epoch + std::time::Duration::from_secs(1) }).await } + async move { + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Pressed { + press_id: 102, + at: epoch + std::time::Duration::from_secs(1), + }) + .await + } }); tokio::time::timeout(std::time::Duration::from_secs(3), entered.notified()) .await .unwrap(); assert_eq!(owner.load(Ordering::SeqCst), 0); - backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { press_id: 102, at: epoch + std::time::Duration::from_millis(1040) }).await.unwrap(); - let second = match backend.dispatch_dictation_hotkey_edge_with_options( - DictationHotkeyEdge::Pressed { press_id: 103, at: epoch + std::time::Duration::from_millis(1100) }, options).await.unwrap() { - CliDispatchOutcome::DictationStarted(id) => id, other => panic!("rapid successor was lost: {other:?}"), - }; - backend.dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { press_id: 103, at: epoch + std::time::Duration::from_millis(1140) }).await.unwrap(); + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { + press_id: 102, + at: epoch + std::time::Duration::from_millis(1040), + }) + .await + .unwrap(); + let second = match backend + .dispatch_dictation_hotkey_edge_with_options( + DictationHotkeyEdge::Pressed { + press_id: 103, + at: epoch + std::time::Duration::from_millis(1100), + }, + options, + ) + .await + .unwrap() + { + CliDispatchOutcome::DictationStarted(id) => id, + other => panic!("rapid successor was lost: {other:?}"), + }; + backend + .dispatch_dictation_hotkey_edge(DictationHotkeyEdge::Released { + press_id: 103, + at: epoch + std::time::Duration::from_millis(1140), + }) + .await + .unwrap(); backend .toggle_dictation_translation_for_session(second) .unwrap(); @@ -650,9 +750,11 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres .toggle_dictation_translation_for_session(first) .is_err()); assert_eq!(owner.load(Ordering::SeqCst), 2); + let mut expected_second_prefix = [2u8, 1].repeat(1_600); + expected_second_prefix.extend_from_slice(&[2, 2]); assert_eq!( *sessions.lock().unwrap()[1].1.pcm.lock().unwrap(), - [2, 1, 2, 2] + expected_second_prefix ); release.notify_one(); let first_result = tokio::time::timeout(std::time::Duration::from_secs(3), stopping) @@ -660,7 +762,9 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres .unwrap() .unwrap() .unwrap(); - assert!(matches!(first_result, CliDispatchOutcome::DictationCompleted(ref result) if result.inserted == DictationInsertStatus::Inserted)); + assert!( + matches!(first_result, CliDispatchOutcome::DictationCompleted(ref result) if result.inserted == DictationInsertStatus::Inserted) + ); assert_eq!( fixture.focus.lock().unwrap().delivered, [("VS Code", "polished-first".into())] @@ -678,11 +782,24 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres "finishing A must not stop B's microphone" ); - if move_second { fixture.focus.lock().unwrap().position = Some((88, 0)); } - assert_eq!(backend.stop_dictation_session(second).await.unwrap().inserted, DictationInsertStatus::Inserted); - assert_eq!(fixture.focus.lock().unwrap().delivered, [ - ("VS Code", "polished-first".into()), ("VS Code", "translated-second".into()) - ]); + if move_second { + fixture.focus.lock().unwrap().position = Some((88, 0)); + } + assert_eq!( + backend + .stop_dictation_session(second) + .await + .unwrap() + .inserted, + DictationInsertStatus::Inserted + ); + assert_eq!( + fixture.focus.lock().unwrap().delivered, + [ + ("VS Code", "polished-first".into()), + ("VS Code", "translated-second".into()) + ] + ); assert_eq!(owner.load(Ordering::SeqCst), 0); { let sessions = sessions.lock().unwrap(); @@ -690,8 +807,12 @@ async fn overlapping_pipeline_preserves_audio_modes_and_confirmed_target_progres sessions.iter().map(|(id, _)| *id).collect::>(), [first, second] ); - assert_eq!(*sessions[0].1.pcm.lock().unwrap(), [1, 1, 1, 2, 1, 3]); - assert_eq!(*sessions[1].1.pcm.lock().unwrap(), [2, 1, 2, 2, 2, 3]); + let mut expected_first = [1u8, 1].repeat(1_600); + expected_first.extend_from_slice(&[1, 2, 1, 3]); + let mut expected_second = [2u8, 1].repeat(1_600); + expected_second.extend_from_slice(&[2, 2, 2, 3]); + assert_eq!(*sessions[0].1.pcm.lock().unwrap(), expected_first); + assert_eq!(*sessions[1].1.pcm.lock().unwrap(), expected_second); } assert_eq!( *calls.lock().unwrap(), @@ -747,10 +868,22 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { "polished" }; let output = if system.contains(openless_core::POLISH_TRANSLATE_TGT_MARKER) { - format!("{}\n{output}\n{}\n{output}", openless_core::POLISH_TRANSLATE_SRC_MARKER, openless_core::POLISH_TRANSLATE_TGT_MARKER) - } else { output.to_owned() }; + format!( + "{}\n{output}\n{}\n{output}", + openless_core::POLISH_TRANSLATE_SRC_MARKER, + openless_core::POLISH_TRANSLATE_TGT_MARKER + ) + } else { + output.to_owned() + }; let (mime, response) = if payload["stream"] == true { - ("text/event-stream", format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices":[{"delta":{"content":output},"finish_reason":null}]}))) + ( + "text/event-stream", + format!( + "data: {}\n\ndata: [DONE]\n\n", + serde_json::json!({"choices":[{"delta":{"content":output},"finish_reason":null}]}) + ), + ) } else { ( "application/json", @@ -766,11 +899,11 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { let fixture = Fixture::with_engine(|credentials| { Arc::new(PipelineDictationEngine::new( - Arc::new(FixtureAudioRecorder::new(vec![vec![1, 0, 2, 0]], vec![])), - Arc::new(FixtureTranscriptionEngine::successful( - USER_EXAMPLE, - 500, + Arc::new(FixtureAudioRecorder::new( + vec![[1, 0, 2, 0].repeat(800)], + vec![], )), + Arc::new(FixtureTranscriptionEngine::successful(USER_EXAMPLE, 500)), Arc::new(SharedCloudTextPolisher::new(credentials)), )) }) @@ -834,9 +967,24 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { assert_eq!(system.matches("当前应用:").count(), 1); assert!(!system.contains("# 输入场景参考")); assert!(system.find("本次输入场景:").unwrap() < system.find(marker).unwrap()); - assert!(payload["messages"].as_array().unwrap().last().unwrap()["content"].as_str().unwrap().contains(USER_EXAMPLE)); - assert_eq!(system.matches(openless_core::DICTATION_REVISION_RULES).count(), 1); - assert!(system.find(marker).unwrap() < system.find(openless_core::DICTATION_REVISION_RULES).unwrap()); + assert!( + payload["messages"].as_array().unwrap().last().unwrap()["content"] + .as_str() + .unwrap() + .contains(USER_EXAMPLE) + ); + assert_eq!( + system + .matches(openless_core::DICTATION_REVISION_RULES) + .count(), + 1 + ); + assert!( + system.find(marker).unwrap() + < system + .find(openless_core::DICTATION_REVISION_RULES) + .unwrap() + ); if marker == "CODING-STYLE" { assert!(payload["messages"][0]["content"] .as_str() @@ -868,7 +1016,8 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { assert_eq!(result.polished_text, "polished"); let first_payload = payloads.try_recv().unwrap(); let first_system = first_payload["messages"][0]["content"].as_str().unwrap(); - assert!(first_system.starts_with("当前应用:VS Code\n应用标识:macos:com.microsoft.VSCode\n应用分类:编程")); + assert!(first_system + .starts_with("当前应用:VS Code\n应用标识:macos:com.microsoft.VSCode\n应用分类:编程")); assert!(first_system.contains("应用主要用途:fixture editor context")); assert!(first_system.contains("当前输入位置:代码编辑区(可信控件标签)")); expect_request(first_payload, "CODING-STYLE"); @@ -896,21 +1045,29 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { (None, current.id.as_str(), "MANUAL-STYLE"), (Some(mail.id.clone()), mail.id.as_str(), "MAIL-STYLE"), ] { - backend.start_dictation_with_options(DictationStartOptions { - front_app: Some("Caller supplied context".into()), - style_pack_id, - ..Default::default() - }).await.unwrap(); + backend + .start_dictation_with_options(DictationStartOptions { + front_app: Some("Caller supplied context".into()), + style_pack_id, + ..Default::default() + }) + .await + .unwrap(); let result = backend.stop_dictation().await.unwrap(); let payload = payloads.try_recv().unwrap(); let system = payload["messages"][0]["content"].as_str().unwrap(); - assert!(system.starts_with("当前应用:VS Code\n应用标识:macos:com.microsoft.VSCode\n应用分类:编程")); + assert!(system.starts_with( + "当前应用:VS Code\n应用标识:macos:com.microsoft.VSCode\n应用分类:编程" + )); assert!(system.contains("当前输入位置:代码编辑区(可信控件标签)")); assert!(!system.contains("CHAT-STYLE")); assert!(!system.contains("CODING-STYLE")); expect_request(payload, marker); let history = backend.list_history().unwrap(); - let entry = history.iter().find(|entry| entry.id == result.session_id.to_string()).unwrap(); + let entry = history + .iter() + .find(|entry| entry.id == result.session_id.to_string()) + .unwrap(); assert_eq!(entry.style_pack_id.as_deref(), Some(expected_pack)); } @@ -947,23 +1104,42 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { // User membership changes affect the next capture, not an in-flight snapshot. fixture.focus.lock().unwrap().current = "VS Code"; - backend.set_app_style_assignment(AppStyleAssignment::Membership { - member_id: "catalog:vscode".into(), category: Some("email".into()), - }).unwrap(); - backend.start_dictation_with_options(DictationStartOptions { - style_pack_id: Some(current.id.clone()), ..Default::default() - }).await.unwrap(); - backend.set_app_style_assignment(AppStyleAssignment::Membership { - member_id: "catalog:vscode".into(), category: Some("coding".into()), - }).unwrap(); + backend + .set_app_style_assignment(AppStyleAssignment::Membership { + member_id: "catalog:vscode".into(), + category: Some("email".into()), + }) + .unwrap(); + backend + .start_dictation_with_options(DictationStartOptions { + style_pack_id: Some(current.id.clone()), + ..Default::default() + }) + .await + .unwrap(); + backend + .set_app_style_assignment(AppStyleAssignment::Membership { + member_id: "catalog:vscode".into(), + category: Some("coding".into()), + }) + .unwrap(); backend.stop_dictation().await.unwrap(); let payload = payloads.try_recv().unwrap(); - assert!(payload["messages"][0]["content"].as_str().unwrap().contains("应用分类:邮件")); + assert!(payload["messages"][0]["content"] + .as_str() + .unwrap() + .contains("应用分类:邮件")); expect_request(payload, "MANUAL-STYLE"); let mut preferences = backend.get_preferences(); preferences.cursor_context_enabled = false; - backend.update_settings(preferences, openless_core::SettingsUpdateOptions::SETTINGS_DOCUMENT, &openless_core::NoopSettingsRuntime).unwrap(); + backend + .update_settings( + preferences, + openless_core::SettingsUpdateOptions::SETTINGS_DOCUMENT, + &openless_core::NoopSettingsRuntime, + ) + .unwrap(); backend.start_dictation().await.unwrap(); backend.stop_dictation().await.unwrap(); let payload = payloads.try_recv().unwrap(); @@ -1080,29 +1256,57 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { .contains("fixture coding context")); while payloads.try_recv().is_ok() {} // A real opted-in profile must not turn canonical Raw into a polish request. - let profile = backend.repositories().expression_profile.lock().unwrap().as_ref().unwrap().clone(); + let profile = backend + .repositories() + .expression_profile + .lock() + .unwrap() + .as_ref() + .unwrap() + .clone(); for index in 0..10 { - profile.record(uuid::Uuid::new_v4(), 100 + index % 4, - openless_core::expression_observation::ExpressionSignal { - line_breaks: 1, exclamations: 0, terminal_punctuation: 0, - }).unwrap(); + profile + .record( + uuid::Uuid::new_v4(), + 100 + index % 4, + openless_core::expression_observation::ExpressionSignal { + line_breaks: 1, + exclamations: 0, + terminal_punctuation: 0, + }, + ) + .unwrap(); } let frozen_expression = openless_core::expression_observation::prompt_instructions( - &profile.stable_directions().unwrap()).unwrap(); + &profile.stable_directions().unwrap(), + ) + .unwrap(); let mut preferences = backend.get_preferences(); preferences.expression_learning_enabled = true; - backend.update_settings(preferences, openless_core::SettingsUpdateOptions::SETTINGS_DOCUMENT, - &openless_core::NoopSettingsRuntime).unwrap(); - backend.start_dictation_with_options(DictationStartOptions { - translation_requested: true, ..Default::default() - }).await.unwrap(); + backend + .update_settings( + preferences, + openless_core::SettingsUpdateOptions::SETTINGS_DOCUMENT, + &openless_core::NoopSettingsRuntime, + ) + .unwrap(); + backend + .start_dictation_with_options(DictationStartOptions { + translation_requested: true, + ..Default::default() + }) + .await + .unwrap(); backend.stop_dictation().await.unwrap(); let translated = payloads.try_recv().unwrap(); let translated_system = translated["messages"][0]["content"].as_str().unwrap(); assert!(translated_system.starts_with("当前应用:")); assert!(translated_system.contains(openless_core::POLISH_TRANSLATE_TGT_MARKER)); assert!(!translated_system.contains(&frozen_expression)); - assert!(payloads.try_recv().is_err(), "translation must issue exactly one request"); + assert!( + payloads.try_recv().is_err(), + "translation must issue exactly one request" + ); for live in [true, false] { backend .start_dictation_with_options(DictationStartOptions { @@ -1113,7 +1317,9 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { .unwrap(); let result = if live { let id = backend.snapshot().dictation.session_id.unwrap(); - backend.toggle_dictation_translation_for_session(id).unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); backend.stop_dictation().await.unwrap() } else { backend @@ -1134,14 +1340,23 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { &("VS Code", USER_EXAMPLE.into()) ); let history = backend.list_history().unwrap(); - let entry = history.iter().find(|entry| entry.id == result.session_id.to_string()).unwrap(); + let entry = history + .iter() + .find(|entry| entry.id == result.session_id.to_string()) + .unwrap(); assert!(!entry.translation_active); assert_eq!(entry.style_pack_id.as_deref(), Some("builtin.raw")); assert_eq!(entry.final_text, USER_EXAMPLE); } backend.start_dictation().await.unwrap(); - assert_eq!(backend.stop_dictation().await.unwrap().polished_text, USER_EXAMPLE); - assert!(payloads.try_recv().is_err(), "profile must not turn canonical Raw into a request"); + assert_eq!( + backend.stop_dictation().await.unwrap().polished_text, + USER_EXAMPLE + ); + assert!( + payloads.try_recv().is_err(), + "profile must not turn canonical Raw into a request" + ); let custom_raw = backend .create_style_pack(StylePack { name: "CUSTOM-RAW".into(), @@ -1156,32 +1371,63 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { style_pack_id: Some(custom_raw.id), }) .unwrap(); - let id = backend.start_dictation_with_options(DictationStartOptions { - translation_requested: true, ..Default::default() - }).await.unwrap(); - backend.toggle_dictation_translation_for_session(id).unwrap(); + let id = backend + .start_dictation_with_options(DictationStartOptions { + translation_requested: true, + ..Default::default() + }) + .await + .unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); assert_eq!( backend.stop_dictation().await.unwrap().polished_text, "polished" ); let custom_payload = payloads.try_recv().unwrap(); - assert!(custom_payload["messages"][0]["content"].as_str().unwrap().contains(&frozen_expression)); + assert!(custom_payload["messages"][0]["content"] + .as_str() + .unwrap() + .contains(&frozen_expression)); expect_request(custom_payload, "CUSTOM-RAW"); - assert!(payloads.try_recv().is_err(), "custom Raw must issue exactly one request"); + assert!( + payloads.try_recv().is_err(), + "custom Raw must issue exactly one request" + ); // Translation suppresses expression guidance; cancelling restores this capture's profile. - let id = backend.start_dictation_with_options(DictationStartOptions { - style_pack_id: Some(coding.id.clone()), translation_requested: true, - ..Default::default() - }).await.unwrap(); + let id = backend + .start_dictation_with_options(DictationStartOptions { + style_pack_id: Some(coding.id.clone()), + translation_requested: true, + ..Default::default() + }) + .await + .unwrap(); backend.clear_expression_profile().unwrap(); - backend.toggle_dictation_translation_for_session(id).unwrap(); + backend + .toggle_dictation_translation_for_session(id) + .unwrap(); backend.stop_dictation().await.unwrap(); let restored = payloads.try_recv().unwrap(); - assert!(restored["messages"][0]["content"].as_str().unwrap().contains(&frozen_expression)); - assert_eq!(restored["messages"][0]["content"].as_str().unwrap().matches(&frozen_expression).count(), 1); + assert!(restored["messages"][0]["content"] + .as_str() + .unwrap() + .contains(&frozen_expression)); + assert_eq!( + restored["messages"][0]["content"] + .as_str() + .unwrap() + .matches(&frozen_expression) + .count(), + 1 + ); expect_request(restored, "CODING-STYLE"); - assert!(payloads.try_recv().is_err(), "restored ordinary polish must issue exactly one request"); + assert!( + payloads.try_recv().is_err(), + "restored ordinary polish must issue exactly one request" + ); backend .set_app_style_assignment(AppStyleAssignment::App { @@ -1217,31 +1463,63 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { std::fs::read_to_string(fixture.directory.join("app-style-routing.json")).unwrap(); assert!(!local_file.contains(USER_EXAMPLE)); assert!(!local_file.contains("polished")); - let mut alias = backend.get_style_pack(openless_core::BUILTIN_INTENT_ID).unwrap(); + let mut alias = backend + .get_style_pack(openless_core::BUILTIN_INTENT_ID) + .unwrap(); alias.id = "fixture.official-alias".into(); alias.kind = openless_core::StylePackKind::Imported; let alias = backend.create_style_pack(alias).unwrap(); // Exercise the production start -> ASR -> request serialization path. // Fixture outputs only prove routing/serialization, never model semantics. - for id in ["builtin.light", "builtin.structured", "builtin.formal", openless_core::BUILTIN_INTENT_ID, &alias.id, ¤t.id] { + for id in [ + "builtin.light", + "builtin.structured", + "builtin.formal", + openless_core::BUILTIN_INTENT_ID, + &alias.id, + ¤t.id, + ] { for translation_requested in [false, true] { - backend.start_dictation_with_options(DictationStartOptions { - style_pack_id: Some(id.into()), - translation_requested, - ..Default::default() - }).await.unwrap(); + backend + .start_dictation_with_options(DictationStartOptions { + style_pack_id: Some(id.into()), + translation_requested, + ..Default::default() + }) + .await + .unwrap(); let result = backend.stop_dictation().await.unwrap(); let history = backend.list_history().unwrap(); - assert_eq!(history.iter().find(|row| row.id == result.session_id.to_string()) - .unwrap().style_pack_id.as_deref(), Some(id)); + assert_eq!( + history + .iter() + .find(|row| row.id == result.session_id.to_string()) + .unwrap() + .style_pack_id + .as_deref(), + Some(id) + ); let payload = payloads.try_recv().unwrap(); let system = payload["messages"][0]["content"].as_str().unwrap(); assert!(system.starts_with("当前应用:VS Code")); let pack = backend.get_style_pack(id).unwrap(); - assert!(system.find("本次输入场景:").unwrap() < system.find(pack.prompt.split("{{HOTWORDS}}").next().unwrap().trim()).unwrap()); - assert_eq!(system.matches(openless_core::DICTATION_REVISION_RULES).count(), 1, "{id}, translation={translation_requested}"); + assert!( + system.find("本次输入场景:").unwrap() + < system + .find(pack.prompt.split("{{HOTWORDS}}").next().unwrap().trim()) + .unwrap() + ); + assert_eq!( + system + .matches(openless_core::DICTATION_REVISION_RULES) + .count(), + 1, + "{id}, translation={translation_requested}" + ); if id == openless_core::BUILTIN_INTENT_ID || id == alias.id { - assert!(pack.prompt.ends_with(openless_core::DICTATION_REVISION_RULES)); + assert!(pack + .prompt + .ends_with(openless_core::DICTATION_REVISION_RULES)); assert_eq!(pack.version, "1.3.0"); assert_eq!(pack.prompt, pack.selection_prompt); let body = openless_core::prompt_compose::compose_system_prompt(&pack.prompt, &[]); @@ -1250,7 +1528,12 @@ async fn routed_dictation_keeps_the_frozen_pack_and_restores_captured_app() { assert!(!system.contains("输出会原样替换该选区")); assert!(!system.contains("本版排版约定(覆盖旧版五层及空层规则)")); } - assert!(payload["messages"].as_array().unwrap().last().unwrap()["content"].as_str().unwrap().contains(USER_EXAMPLE)); + assert!( + payload["messages"].as_array().unwrap().last().unwrap()["content"] + .as_str() + .unwrap() + .contains(USER_EXAMPLE) + ); if translation_requested { assert!(system.contains("[[OPENLESS_TRANSLATION]]")); } diff --git a/openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs b/openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs new file mode 100644 index 000000000..ab708fe48 --- /dev/null +++ b/openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs @@ -0,0 +1,3 @@ +// Exercise the production Linux archive adapter without loading a native audio backend. +#[path = "../../../linux-egui/src/audio/archive.rs"] +mod archive; diff --git a/openless-all/app/crates/openless-core/tests/qa_answer_replacement.rs b/openless-all/app/crates/openless-core/tests/qa_answer_replacement.rs index c5df0ada2..b69ece3ed 100644 --- a/openless-all/app/crates/openless-core/tests/qa_answer_replacement.rs +++ b/openless-all/app/crates/openless-core/tests/qa_answer_replacement.rs @@ -336,7 +336,8 @@ async fn delayed_preview_confirmation_must_not_apply_old_text_to_a_new_qa_turn() voice.preview(current.conversation_id).await.unwrap(), preview ); - assert!(backend.list_history().unwrap().is_empty()); + // Original-selection protection persists a draft before native application. + assert!(backend.list_history().unwrap().iter().all(|entry| entry.insert_status == openless_core::HistoryInsertStatus::NotRequested)); qa.dismiss().await.unwrap(); drop(backend); std::fs::remove_dir_all(data_dir).unwrap(); @@ -396,7 +397,7 @@ async fn completed_preview_confirmation_must_not_dismiss_a_reopened_qa_panel() { "old apply cleanup must not request HideQa for B" ); assert_eq!( - backend.list_history().unwrap()[0].insert_status, + backend.list_history().unwrap().iter().find(|entry| entry.id == ticket.session_id.to_string()).unwrap().insert_status, openless_core::HistoryInsertStatus::PasteSent ); qa.dismiss().await.unwrap(); @@ -433,7 +434,8 @@ async fn qa_preview_confirmation_retries_native_failure_and_closes_only_its_owne .await .unwrap() .is_some()); - assert!(backend.list_history().unwrap().is_empty()); + // Original-selection protection persists a draft before native application. + assert!(backend.list_history().unwrap().iter().all(|entry| entry.insert_status == openless_core::HistoryInsertStatus::NotRequested)); let ticket = qa .begin_edit_preview_apply(turn, "replacement".into()) diff --git a/openless-all/app/e2e/ask-anything.spec.ts b/openless-all/app/e2e/ask-anything.spec.ts index d7128b363..d4da6dc58 100644 --- a/openless-all/app/e2e/ask-anything.spec.ts +++ b/openless-all/app/e2e/ask-anything.spec.ts @@ -73,7 +73,8 @@ test('Ask history lives in General instead of the tools menu', async ({ page }) await page.goto('/'); await page.getByRole('button', { name: '设置', exact: true }).click(); const history = page.locator('[data-ol-general-entry="askHistory"]'); - await expect(page.locator('[data-ol-general-entry="recording"] + [data-ol-general-entry="askHistory"]')).toBeVisible(); + await expect(page.locator('[data-ol-general-entry="recording"]')).toBeVisible(); + await expect(history).toBeVisible(); await history.click(); await expect(page.getByRole('switch', { name: '保存历史' })).toBeVisible(); await expect(page.getByText('开启后在此设备上保存「随便问」的历史记录,默认关闭。', { exact: true }).first()).toBeVisible(); diff --git a/openless-all/app/e2e/ask-entry-settings.spec.ts b/openless-all/app/e2e/ask-entry-settings.spec.ts index 9876ec9ad..15b1b149d 100644 --- a/openless-all/app/e2e/ask-entry-settings.spec.ts +++ b/openless-all/app/e2e/ask-entry-settings.spec.ts @@ -233,7 +233,7 @@ test('permissions check once per entry and only recheck focus after opening syst await page.evaluate(() => window.dispatchEvent(new Event('focus'))); expect(await reads()).toBe(1); await page.getByRole('button', { name: 'Open System Settings', exact: true }).click(); - expect(await page.evaluate(() => window.askEntrySettingsFixture.settingsOpened())).toBe(1); + await expect.poll(() => page.evaluate(() => window.askEntrySettingsFixture.settingsOpened())).toBe(1); const beforeReturn = await reads(); await page.evaluate(() => { window.askEntrySettingsFixture.grantMicrophone(); diff --git a/openless-all/app/e2e/capsule-overlap.spec.ts b/openless-all/app/e2e/capsule-overlap.spec.ts index ae1b84597..c09e46063 100644 --- a/openless-all/app/e2e/capsule-overlap.spec.ts +++ b/openless-all/app/e2e/capsule-overlap.spec.ts @@ -30,7 +30,8 @@ test('processing lobe stays joined to recording through transcript, menu and job const upper = (await lobe.boundingBox())!; expect(upper.height).toBeCloseTo(22, 1); expect(lower.y).toBeCloseTo(anchor!.y, 1); - expect(upper.x + upper.width / 2 - (lower.x + lower.width / 2)).toBeCloseTo(0, 1); + // WebKit rounds centered, text-sized boxes to fractional CSS pixels. + expect(Math.abs(upper.x + upper.width / 2 - (lower.x + lower.width / 2))).toBeLessThanOrEqual(0.5); expect(upper.y + upper.height - lower.y).toBeCloseTo(4, 1); }; await expect(lobe).toContainText('处理中'); @@ -213,7 +214,7 @@ test('processing foreground publishes the settled rear hit region and cancels on const foreground = page.locator('.ol-default-capsule'); const r = (await rear.boundingBox())!, f = (await foreground.boundingBox())!; expect(r.height).toBeCloseTo(22, 1); - expect(r.x + r.width / 2).toBeCloseTo(f.x + f.width / 2, 1); + expect(Math.abs(r.x + r.width / 2 - (f.x + f.width / 2))).toBeLessThanOrEqual(0.5); expect(r.y + r.height - f.y).toBeCloseTo(4, 1); await rear.click({ position: { x: r.width / 2, y: 8 } }); await expect.poll(() => page.evaluate(() => (window as any).fixture.dictationActionArgs.at(-1))) diff --git a/openless-all/app/e2e/fixtures/capsule-motion.tsx b/openless-all/app/e2e/fixtures/capsule-motion.tsx index c2c4ca80e..5a971fa6e 100644 --- a/openless-all/app/e2e/fixtures/capsule-motion.tsx +++ b/openless-all/app/e2e/fixtures/capsule-motion.tsx @@ -215,7 +215,6 @@ const { InsertFallbackCard } = await import('../../src/features/capsule/InsertFa const { OpenLessPill } = await import('../../src/features/capsule/OpenLessCapsule'); const { CapsuleTranslationBadge, CapsuleTranscriptOverlay } = await import('../../src/features/capsule/LiveTranscriptPill'); -const { QaPanel } = await import('../../src/features/qa/QaPanel'); const { Capsule } = await import('../../src/features/capsule/Capsule'); if (themeSync) { localStorage.setItem('ol.theme', 'light'); @@ -285,22 +284,6 @@ createRoot(document.getElementById('root')!).render( > - ) : qa ? ( -
- - - -
) : ( diff --git a/openless-all/app/e2e/history-store.spec.ts b/openless-all/app/e2e/history-store.spec.ts index fb030b77d..6c346a83e 100644 --- a/openless-all/app/e2e/history-store.spec.ts +++ b/openless-all/app/e2e/history-store.spec.ts @@ -169,160 +169,6 @@ previewHistory.retranscribe = () => ({ }); }); -test('history switches transcripts inside a fixed frame with copy below the text', async ({ - page, -}) => { - await page.setViewportSize({ width: 980, height: 640 }); - await page.goto('/?os=mac'); - const surface = await navigate(page, 'history', '历史'); - await surface.locator('[data-history-record="mock-quick-note"]').click(); - - const steps = surface.locator('.ol-history-pipeline-chip'); - await expect(steps).toHaveCount(2); - expect((await steps.first().boundingBox())!.y).toBeCloseTo( - (await steps.last().boundingBox())!.y, - 0, - ); - const frame = surface.locator('.ol-history-content-frame'); - const content = frame.locator('.ol-history-content-scroll'); - const copy = frame.getByRole('button', { name: '复制', exact: true }); - await expect(frame.locator('.ol-history-content-footer').getByRole('button')).toHaveCount(1); - const raw = frame.getByRole('button', { name: '原文', exact: true }); - const polished = frame.getByRole('button', { name: /^润色 · / }); - await expect(content).toHaveText('Bring the notes to the planning meeting.'); - await expect(content).toHaveCSS('overflow-y', 'auto'); - const anchor = (await copy.boundingBox())!; - expect(anchor.y).toBeGreaterThan((await content.boundingBox())!.y); - - for (let attempt = 0; attempt < 3; attempt++) { - await raw.click(); - await expect(raw).toHaveAttribute('aria-pressed', 'true'); - await expect(content).toHaveText('Remember to bring the notes to the planning meeting.'); - expect((await copy.boundingBox())!.y).toBeCloseTo(anchor.y, 0); - await polished.click(); - await expect(polished).toHaveAttribute('aria-pressed', 'true'); - await expect(content).toHaveText('Bring the notes to the planning meeting.'); - } -}); - -test('a long retranscription scrolls without hiding the original transcript controls', async ({ - page, -}) => { - await page.setViewportSize({ width: 980, height: 640 }); - await page.route('**/src/preview/history.ts*', async (route) => { - const response = await route.fetch(); - await route.fulfill({ - response, - body: `${await response.text()} -previewHistory.retranscribe = () => ({ - updatedEntry: null, - text: 'Long retranscription paragraph.\\n\\n'.repeat(35) + 'End of retranscription.' -});`, - }); - }); - await page.goto(`${fixtureOrigin}/?os=mac`); - const surface = await navigate(page, 'history', '历史'); - await surface.locator('[data-history-record="mock-quick-note"]').click(); - await surface.getByRole('button', { name: '录音操作', exact: true }).click(); - await page.getByRole('menuitem', { name: '重新转录', exact: true }).click(); - - const result = surface.getByRole('region', { name: '重新转录', exact: true }); - await expect(result).toBeVisible(); - expect(await result.evaluate((node) => node.scrollHeight - node.clientHeight)).toBeGreaterThan( - 200, - ); - await result.evaluate((node) => (node.scrollTop = node.scrollHeight)); - await expect(result.getByText('End of retranscription.')).toBeInViewport({ ratio: 1 }); - - const frame = surface.locator('.ol-history-content-frame'); - const original = frame.getByRole('button', { name: '原文', exact: true }); - await expect(original).toBeInViewport({ ratio: 1 }); - await original.click(); - await expect(frame.locator('.ol-history-content-scroll')).toHaveText( - 'Remember to bring the notes to the planning meeting.', - ); - await expect(frame.getByRole('button', { name: '复制', exact: true })).toBeInViewport({ - ratio: 1, - }); -}); - -test('history switches transcripts inside a fixed frame with copy below the text', async ({ - page, -}) => { - await page.setViewportSize({ width: 980, height: 640 }); - await page.goto('/?os=mac'); - const surface = await navigate(page, 'history', '历史'); - await surface.locator('[data-history-record="mock-quick-note"]').click(); - - const steps = surface.locator('.ol-history-pipeline-chip'); - await expect(steps).toHaveCount(2); - expect((await steps.first().boundingBox())!.y).toBeCloseTo( - (await steps.last().boundingBox())!.y, - 0, - ); - const frame = surface.locator('.ol-history-content-frame'); - const content = frame.locator('.ol-history-content-scroll'); - const copy = frame.getByRole('button', { name: '复制', exact: true }); - await expect(frame.locator('.ol-history-content-footer').getByRole('button')).toHaveCount(1); - const raw = frame.getByRole('button', { name: '原文', exact: true }); - const polished = frame.getByRole('button', { name: /^润色 · / }); - await expect(content).toHaveText('Bring the notes to the planning meeting.'); - await expect(content).toHaveCSS('overflow-y', 'auto'); - const anchor = (await copy.boundingBox())!; - expect(anchor.y).toBeGreaterThan((await content.boundingBox())!.y); - - for (let attempt = 0; attempt < 3; attempt++) { - await raw.click(); - await expect(raw).toHaveAttribute('aria-pressed', 'true'); - await expect(content).toHaveText('Remember to bring the notes to the planning meeting.'); - expect((await copy.boundingBox())!.y).toBeCloseTo(anchor.y, 0); - await polished.click(); - await expect(polished).toHaveAttribute('aria-pressed', 'true'); - await expect(content).toHaveText('Bring the notes to the planning meeting.'); - } -}); - -test('a long retranscription scrolls without hiding the original transcript controls', async ({ - page, -}) => { - await page.setViewportSize({ width: 980, height: 640 }); - await page.route('**/src/preview/history.ts*', async (route) => { - const response = await route.fetch(); - await route.fulfill({ - response, - body: `${await response.text()} -previewHistory.retranscribe = () => ({ - updatedEntry: null, - text: 'Long retranscription paragraph.\\n\\n'.repeat(35) + 'End of retranscription.' -});`, - }); - }); - await page.goto(`${fixtureOrigin}/?os=mac`); - const surface = await navigate(page, 'history', '历史'); - await surface.locator('[data-history-record="mock-quick-note"]').click(); - await surface.getByRole('button', { name: '录音操作', exact: true }).click(); - await page.getByRole('menuitem', { name: '重新转录', exact: true }).click(); - - const result = surface.getByRole('region', { name: '重新转录', exact: true }); - await expect(result).toBeVisible(); - expect(await result.evaluate((node) => node.scrollHeight - node.clientHeight)).toBeGreaterThan( - 200, - ); - await result.evaluate((node) => (node.scrollTop = node.scrollHeight)); - await expect(result.getByText('End of retranscription.')).toBeInViewport({ ratio: 1 }); - - const frame = surface.locator('.ol-history-content-frame'); - const original = frame.getByRole('button', { name: '原文', exact: true }); - await expect(original).toBeInViewport({ ratio: 1 }); - await original.click(); - await expect(frame.locator('.ol-history-content-scroll')).toHaveText( - 'Remember to bring the notes to the planning meeting.', - ); - await expect(frame.getByRole('button', { name: '复制', exact: true })).toBeInViewport({ - ratio: 1, - }); -}); - for (const [font, scale] of [ ['small', 0.9], ['medium', 1], diff --git a/openless-all/app/e2e/interaction-polish.spec.ts b/openless-all/app/e2e/interaction-polish.spec.ts index e117efbaa..46afc3049 100644 --- a/openless-all/app/e2e/interaction-polish.spec.ts +++ b/openless-all/app/e2e/interaction-polish.spec.ts @@ -92,105 +92,3 @@ test('message follow yields to the reader and resumes at the bottom', async ({ p }); await expect.poll(distance).toBeLessThanOrEqual(1); }); - -test('QA jump control appears only more than 120 pixels from the latest message', async ({ - page, -}) => { - await page.goto(`${fixtureOrigin}/e2e/fixtures/capsule-motion.html?qa`); - await page.locator('.ol-default-capsule').waitFor(); - await page.evaluate(() => { - const fixture = (window as any).fixture; - fixture.emit('qa:state', { kind: 'recording', sessionId: 'follow-test', messages: [] }); - fixture.emit('qa:state', { - kind: 'answer', - sessionId: 'follow-test', - messages: Array.from({ length: 12 }, (_, index) => ({ - role: index % 2 ? 'assistant' : 'user', - content: `Message ${index}: ${'content '.repeat(30)}`, - })), - }); - }); - const viewport = page.locator('[data-slot="message-scroller-viewport"]'); - await expect(viewport).toBeVisible(); - const jump = page.getByRole('button', { name: '跳至最新' }); - await expect(jump).toHaveText('跳至最新'); - await expect - .poll(() => viewport.evaluate((node) => node.scrollHeight - node.clientHeight)) - .toBeGreaterThan(150); - await viewport.evaluate((node) => { - node.scrollTop = node.scrollHeight; - node.dispatchEvent(new Event('scroll')); - }); - // Finish the initial follow-to-bottom animation before simulating a reader scroll. - await expect(viewport).not.toHaveAttribute('data-autoscrolling'); - await expect - .poll(() => viewport.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop)) - .toBeLessThanOrEqual(1); - await expect(jump).toHaveAttribute('data-active', 'false'); - await viewport.evaluate((node) => { - node.dispatchEvent(new Event('touchmove')); - node.scrollTop = node.scrollHeight - node.clientHeight - 80; - node.dispatchEvent(new Event('scroll')); - }); - await expect(jump).toHaveAttribute('data-active', 'false'); - await viewport.evaluate((node) => { - node.scrollTop = node.scrollHeight - node.clientHeight - 140; - node.dispatchEvent(new Event('scroll')); - }); - await expect(jump).toHaveAttribute('data-active', 'true'); - await expect(jump).toHaveCSS('opacity', '1'); - await jump.click(); - await expect - .poll(() => viewport.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop)) - .toBeLessThanOrEqual(1); -}); - -for (const platform of ['mac', 'win'] as const) { - test(`QA header and scrolling follow ${platform} conventions`, async ({ page }) => { - await page.addInitScript((platform) => { - const value = platform === 'mac' ? 'MacIntel' : 'Win32'; - Object.defineProperty(navigator, 'platform', { configurable: true, value }); - Object.defineProperty(navigator, 'userAgent', { configurable: true, value }); - Object.defineProperty(navigator, 'userAgentData', { configurable: true, value: undefined }); - }, platform); - await page.goto(`${fixtureOrigin}/e2e/fixtures/capsule-motion.html?qa`); - await page.locator('.ol-default-capsule').waitFor(); - await page.evaluate(() => { - const fixture = (window as any).fixture; - fixture.emit('qa:state', { kind: 'recording', sessionId: 'chrome', messages: [] }); - fixture.emit('qa:state', { - kind: 'answer', - sessionId: 'chrome', - messages: Array.from({ length: 12 }, (_, index) => ({ - role: index % 2 ? 'assistant' : 'user', - content: `Message ${index}: ${'content '.repeat(30)}`, - })), - }); - }); - const panel = page.locator('.qa-answer-panel'); - const header = panel.locator('.qa-answer-header'); - await expect(panel).toHaveAttribute('data-platform', platform); - await expect(header.locator('h1')).toContainText('Message 0:'); - await expect(header).toHaveCSS('background-color', 'rgb(255, 255, 255)'); - await expect(header.locator('.qa-symbol')).toHaveCount(0); - const headerBox = (await header.boundingBox())!; - const closeBox = (await header.locator('.qa-close').boundingBox())!; - expect( - platform === 'mac' - ? closeBox.x - headerBox.x - : headerBox.x + headerBox.width - closeBox.x - closeBox.width, - ).toBeLessThan(25); - const viewport = panel.locator('[data-slot="message-scroller-viewport"]'); - await expect(viewport).toHaveCSS('scrollbar-width', 'none'); - await expect - .poll(() => viewport.evaluate((el) => el.scrollHeight - el.clientHeight)) - .toBeGreaterThan(150); - await viewport.evaluate((el) => { - el.scrollTop = 0; - }); - expect(await viewport.evaluate((el) => el.scrollTop)).toBe(0); - expect(await header.evaluate((el) => getComputedStyle(el, '::after').backdropFilter)).toContain( - 'blur', - ); - }); -} diff --git a/openless-all/app/e2e/shortcut-clear-dropdown.spec.ts b/openless-all/app/e2e/shortcut-clear-dropdown.spec.ts index 7b6c87586..24c6642a7 100644 --- a/openless-all/app/e2e/shortcut-clear-dropdown.spec.ts +++ b/openless-all/app/e2e/shortcut-clear-dropdown.spec.ts @@ -1,4 +1,3 @@ -import { ASK_ANYTHING_AVAILABLE } from '../src/lib/appVersion'; import { fixtureOrigin } from './support/server'; import { expect, test } from '@playwright/test'; import { openMicrophoneSettings, settleSelectDismissal } from './support/navigation'; @@ -9,11 +8,8 @@ test('every configurable shortcut can be cleared and stays clear after remount', await page.goto('/?os=mac'); await page.getByRole('button', { name: '设置', exact: true }).click(); await page.getByRole('button', { name: '快捷键', exact: true }).click(); - if (!ASK_ANYTHING_AVAILABLE) { - const ask = page.getByRole('group', { name: '随便问', exact: true }); - await expect(ask).toHaveAttribute('aria-disabled', 'true'); - await expect(ask.getByRole('button', { name: '清空', exact: true })).toBeDisabled(); - } + // Ask bindings live in their dedicated entry settings, not this legacy row. + await expect(page.getByRole('group', { name: '随便问', exact: true })).toHaveCount(0); const rows = page.locator('.ol-shortcut-row[role="group"]:not([aria-disabled="true"])'); await expect(rows.first()).toBeVisible(); const count = await rows.count(); diff --git a/openless-all/app/harmony/ipc-audit.json b/openless-all/app/harmony/ipc-audit.json index fc3e03448..227256c39 100644 --- a/openless-all/app/harmony/ipc-audit.json +++ b/openless-all/app/harmony/ipc-audit.json @@ -1,8 +1,8 @@ { "scope": "Static shared IPC and runtime adapter command coverage; excludes event subscriptions and dynamic command names.", - "total": 203, + "total": 190, "wired": 108, - "missing": 95, + "missing": 82, "commands": [ { "name": "accept_pending_correction", @@ -67,13 +67,6 @@ ], "implementation": "arkts" }, - { - "name": "cancel_selection_polish_preview", - "calledFrom": [ - "src/lib/ipc/selection-polish-preview.ts" - ], - "implementation": "unimplemented" - }, { "name": "cancel_selection_voice_intent_prompt", "calledFrom": [ @@ -305,13 +298,6 @@ ], "implementation": "unimplemented" }, - { - "name": "confirm_selection_polish_preview", - "calledFrom": [ - "src/lib/ipc/selection-polish-preview.ts" - ], - "implementation": "unimplemented" - }, { "name": "confirm_selection_voice_intent_prompt", "calledFrom": [ @@ -536,13 +522,6 @@ ], "implementation": "rust" }, - { - "name": "get_qa_hotkey_label", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, { "name": "get_remote_input_status", "calledFrom": [ @@ -550,13 +529,6 @@ ], "implementation": "unimplemented" }, - { - "name": "get_selection_polish_preview", - "calledFrom": [ - "src/lib/ipc/selection-polish-preview.ts" - ], - "implementation": "unimplemented" - }, { "name": "get_selection_voice_intent_prompt", "calledFrom": [ @@ -865,62 +837,6 @@ ], "implementation": "rust" }, - { - "name": "qa_cancel_turn", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_get_snapshot", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_set_edit_instruction_mode", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_stop_recording", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_submit_text", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_toggle_recording", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_window_dismiss", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, - { - "name": "qa_window_set_expanded", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, { "name": "read_audio_recording", "calledFrom": [ @@ -1194,13 +1110,6 @@ ], "implementation": "unimplemented" }, - { - "name": "set_qa_hotkey", - "calledFrom": [ - "src/lib/ipc/qa.ts" - ], - "implementation": "unimplemented" - }, { "name": "set_quick_note_hotkey", "calledFrom": [ diff --git a/openless-all/app/linux-egui/src/audio.rs b/openless-all/app/linux-egui/src/audio.rs index 6d63173a9..af074d550 100644 --- a/openless-all/app/linux-egui/src/audio.rs +++ b/openless-all/app/linux-egui/src/audio.rs @@ -295,51 +295,10 @@ impl Drop for LinuxActiveRecording { } } +#[cfg(any(target_os = "linux", test))] +mod archive; #[cfg(target_os = "linux")] -struct LinuxRecordingArchive { - path: std::path::PathBuf, - available: Arc, -} - -#[cfg(target_os = "linux")] -impl openless_core::RecordingArchive for LinuxRecordingArchive { - fn is_available(&self) -> bool { - self.available.load(std::sync::atomic::Ordering::Acquire) - } - - fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { - let path = self.path.clone(); - Box::pin(async move { - let wav = tokio::fs::read(path).await.map_err(|error| { - BackendError::new( - BackendErrorCode::Persistence, - format!("read Linux recording archive: {error}"), - ) - })?; - canonical_wav_pcm(&wav).map(ToOwned::to_owned) - }) - } - - fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { - let path = self.path.clone(); - let available = Arc::clone(&self.available); - Box::pin(async move { - match tokio::fs::remove_file(path).await { - Ok(()) => available.store(false, std::sync::atomic::Ordering::Release), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - available.store(false, std::sync::atomic::Ordering::Release); - } - Err(error) => { - return Err(BackendError::new( - BackendErrorCode::Persistence, - format!("discard Linux recording archive: {error}"), - )); - } - } - Ok(()) - }) - } -} +use archive::LinuxRecordingArchive; #[cfg(target_os = "linux")] impl ActiveRecording for LinuxActiveRecording { diff --git a/openless-all/app/linux-egui/src/audio/archive.rs b/openless-all/app/linux-egui/src/audio/archive.rs new file mode 100644 index 000000000..448916b18 --- /dev/null +++ b/openless-all/app/linux-egui/src/audio/archive.rs @@ -0,0 +1,111 @@ +//! Canonical Linux recording archive access, independent of native audio devices. +use futures_util::future::BoxFuture; +use openless_core::{BackendError, BackendErrorCode}; +use std::sync::Arc; + +pub(super) struct LinuxRecordingArchive { + pub(super) path: std::path::PathBuf, + pub(super) available: Arc, +} + +impl openless_core::RecordingArchive for LinuxRecordingArchive { + fn is_available(&self) -> bool { + self.available.load(std::sync::atomic::Ordering::Acquire) + } + + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let path = self.path.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || { + let mut file = std::fs::File::open(path).map_err(|error| { + BackendError::new(BackendErrorCode::Persistence, error.to_string()) + })?; + openless_core::audio::canonical_archive_pcm_len(&mut file) + }) + .await + .map_err(|error| BackendError::new(BackendErrorCode::Persistence, error.to_string()))? + }) + } + + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + let path = self.path.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || { + let mut file = std::fs::File::open(path).map_err(|error| { + BackendError::new(BackendErrorCode::Persistence, error.to_string()) + })?; + openless_core::audio::read_canonical_archive_pcm_range(&mut file, offset, len) + }) + .await + .map_err(|error| BackendError::new(BackendErrorCode::Persistence, error.to_string()))? + }) + } + + fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { + let path = self.path.clone(); + Box::pin(async move { + let wav = tokio::fs::read(path).await.map_err(|error| { + BackendError::new( + BackendErrorCode::Persistence, + format!("read Linux recording archive: {error}"), + ) + })?; + openless_core::audio::decode_dictation_wav(&wav).map(ToOwned::to_owned) + }) + } + + fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { + let path = self.path.clone(); + let available = Arc::clone(&self.available); + Box::pin(async move { + match tokio::fs::remove_file(path).await { + Ok(()) => available.store(false, std::sync::atomic::Ordering::Release), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + available.store(false, std::sync::atomic::Ordering::Release); + } + Err(error) => { + return Err(BackendError::new( + BackendErrorCode::Persistence, + format!("discard Linux recording archive: {error}"), + )); + } + } + Ok(()) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn archive_range_reads_preserve_bounds_and_validate_final_lengths() { + use openless_core::RecordingArchive; + let path = + std::env::temp_dir().join(format!("openless-linux-range-{}.wav", uuid::Uuid::new_v4())); + std::fs::write( + &path, + openless_core::audio::encode_dictation_wav(&[1, 2, 3, 4, 5, 6]).unwrap(), + ) + .unwrap(); + let archive = LinuxRecordingArchive { + path: path.clone(), + available: Arc::new(std::sync::atomic::AtomicBool::new(true)), + }; + assert_eq!(archive.pcm_byte_len().await.unwrap(), 6); + assert_eq!(archive.read_pcm_range(2, 4).await.unwrap(), [3, 4, 5, 6]); + assert!(archive.read_pcm_range(4, 4).await.is_err()); + std::fs::OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .set_len(46) + .unwrap(); + assert!(archive.pcm_byte_len().await.is_err()); + archive.discard().await.unwrap(); + } +} diff --git a/openless-all/app/scripts/ci-consolidation.test.mjs b/openless-all/app/scripts/ci-consolidation.test.mjs index 82f083dbc..ab8236f9e 100644 --- a/openless-all/app/scripts/ci-consolidation.test.mjs +++ b/openless-all/app/scripts/ci-consolidation.test.mjs @@ -23,7 +23,10 @@ for (const [id, area] of [ `${includeNonDesktop} && (github.event_name != 'workflow_dispatch' || inputs.platform != 'macos') && needs.changes.outputs.${area} != 'false'`, ); } -assert.equal(ci.jobs['ui-motion'].if, `always() && !(${desktopOnly})`); +assert.equal( + ci.jobs['ui-motion'].if, + `(github.event_name != 'workflow_dispatch' || inputs.live_acceptance == 'off') && always() && !(${desktopOnly})`, +); assert.equal( ci.jobs['windows-checks']['runs-on'], "${{ needs.changes.outputs.desktop-only == 'false' && 'ubuntu-latest' || 'macos-latest' }}", diff --git a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs index 06c4deb17..0c42fdb88 100644 --- a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs +++ b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs @@ -589,8 +589,8 @@ assert.match( ); assert.match( historyCommand, - /pub async fn retranscribe_recording\([^]*?retranscription::retranscribe_recording_with_path\(&core, session_id, existing_recording_path\)\.await/, - 'the registered history command must forward Core and the real recording resolver', + /pub async fn retranscribe_recording\([^]*?let path = existing_recording_path\(&session_id\)\?;\s*let _lease = crate::persistence::acquire_recording_archive_lease\(&path\);\s*retranscription::retranscribe_recording_with_path\(&core, session_id, \|_\| Ok\(path\)\)\.await/, + 'the registered history command must resolve and lease the recording before forwarding Core and its path', ); assert.match( historyRetranscription, diff --git a/openless-all/app/scripts/test-recorder-module.py b/openless-all/app/scripts/test-recorder-module.py index 62bd56df0..e38ac1b61 100644 --- a/openless-all/app/scripts/test-recorder-module.py +++ b/openless-all/app/scripts/test-recorder-module.py @@ -29,6 +29,7 @@ serde_json = "1" thiserror = "1" log = "0.4" +uuid = { version = "1", features = ["v4"] } """ + "cpal = { version = \"=0.15.3\", path = " + json.dumps((recorder.parents[1] / "vendor/cpal").as_posix()) + " }\n" + "micyou-dsp = { path = " + json.dumps((recorder.parents[2] / "crates/micyou-dsp").as_posix()) + " }\n" + "[build-dependencies]\ncc = \"1\"\n[target.'cfg(target_os = \"macos\")'.dependencies]\ncoreaudio-sys = \"0.2\"\n") @@ -42,7 +43,7 @@ ) (root / "src/lib.rs").write_text( "extern crate self as openless_core;\n" - "#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BackendErrorCode { InvalidArgument }\n" + "#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BackendErrorCode { InvalidArgument, Persistence }\n" "#[derive(Debug, Clone)] pub struct BackendError { pub code: BackendErrorCode, pub message: String }\n" "impl BackendError { pub fn new(code: BackendErrorCode, message: impl Into) -> Self { Self { code, message: message.into() } } }\n" + "#[path = " + json.dumps(str(recorder.parents[2] / "crates/openless-core/src/audio_dsp.rs"), ensure_ascii=False) + "]\npub mod audio_dsp;\n" diff --git a/openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs b/openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs index 82a1b7d1d..7d301e3d3 100644 --- a/openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs +++ b/openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs @@ -141,7 +141,7 @@ assert.match(ime, /Event::SubmitAck/); assert.match(ime, /error\.is_outcome_unknown\(\) => Outcome::Unknown/); assert.match(recorder, /if let Some\(handle\) = join_handle\.lock\(\)\.take\(\) \{/); assert.match(recorder, /if let Some\(handle\) = self\.join_handle\.lock\(\)\.take\(\) \{/); -assert.match(recorder, /not\(feature = "issue-1266-diagnostics"\), not\(test\)/); +assert.match(recorder, /not\(feature = "issue-1266-diagnostics"\),\s*not\(test\)/); assert.match(recorder, /issue1266_debug::legacy\(event, outcome\)/); assert.ok( lib.indexOf('issue1266_debug::initialize();') < diff --git a/openless-all/app/scripts/windows-insertion-target-contract.test.mjs b/openless-all/app/scripts/windows-insertion-target-contract.test.mjs index 685b7d131..0b288b603 100644 --- a/openless-all/app/scripts/windows-insertion-target-contract.test.mjs +++ b/openless-all/app/scripts/windows-insertion-target-contract.test.mjs @@ -24,7 +24,7 @@ const unicodeFallback = adapters.match( )?.[0]; assert.match( unicodeFallback ?? '', - /matches!\(status, crate::types::InsertStatus::Inserted \| crate::types::InsertStatus::PasteSent\)/, + /matches!\(\s*status,\s*crate::types::InsertStatus::Inserted \| crate::types::InsertStatus::PasteSent\s*\)/, 'partially dispatched Unicode input must remain uncertain instead of becoming copy-only fallback', ); diff --git a/openless-all/app/src-tauri/backend-tests/Cargo.lock b/openless-all/app/src-tauri/backend-tests/Cargo.lock index 7a8fce860..6417d80bb 100644 --- a/openless-all/app/src-tauri/backend-tests/Cargo.lock +++ b/openless-all/app/src-tauri/backend-tests/Cargo.lock @@ -373,7 +373,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", + "serde", + "wasm-bindgen", "windows-link", ] @@ -466,6 +469,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1748,6 +1761,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1862,6 +1886,8 @@ dependencies = [ "anyhow", "base64 0.22.1", "block2 0.5.1", + "chrono", + "core-foundation 0.10.1", "cpal", "dispatch2", "futures-util", @@ -1879,6 +1905,7 @@ dependencies = [ "thiserror 2.0.21", "time", "tokio", + "url", "uuid", "windows 0.58.0", "x509-parser", @@ -1903,6 +1930,9 @@ dependencies = [ "log", "md-5", "micyou-dsp", + "num-bigint", + "num-rational", + "num-traits", "once_cell", "parking_lot", "regex", @@ -2974,7 +3004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.9.4", "system-configuration-sys", ] diff --git a/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs b/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs index 391c239df..82a60eb9f 100644 --- a/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs +++ b/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs @@ -19,6 +19,23 @@ mod selection { // Selection capture is unrelated to keyboard classification in this test harness. pub fn prefetch_selection_workspace_capture() {} } +// This harness leaves Ask unconfigured so the production keyboard dispatcher +// continues through the dictation/translation route under test. +mod ask_window { + pub fn active_space_epoch() -> u64 { 0 } + pub fn foreground_pid() -> Option { None } + pub mod hotkey { + pub enum Disposition { Stock, Pass, Consume } + pub fn keyboard_edge(_: u16, _: bool, _: bool, _: bool) -> Disposition { Disposition::Stock } + pub fn reset_physical_state() {} + pub fn can_buffer_space() -> bool { false } + pub fn fn_is_held() -> bool { false } + pub fn abort_fn_companion() {} + } +} +mod unicode_keystroke { + pub fn is_secure_input_enabled() -> bool { false } +} #[path = "../../src/mobile_stubs/combo_hotkey.rs"] mod combo_hotkey; #[path = "../../src/hotkey.rs"] diff --git a/openless-all/app/src-tauri/src/commands/history.rs b/openless-all/app/src-tauri/src/commands/history.rs index 3b4819762..ca1d0961a 100644 --- a/openless-all/app/src-tauri/src/commands/history.rs +++ b/openless-all/app/src-tauri/src/commands/history.rs @@ -52,7 +52,8 @@ pub fn get_activity_stats(core: CoreState<'_>) -> Vec { #[tauri::command] pub fn get_activity_apps(core: CoreState<'_>, year: u32) -> Result, String> { - core.list_activity_apps(year).map_err(|error| error.to_string()) + core.list_activity_apps(year) + .map_err(|error| error.to_string()) } /// Resolves only the top ranked names through local native icon sources. @@ -149,6 +150,7 @@ pub async fn read_audio_recording(session_id: String) -> Result return Err("invalid session id".into()); } let path = existing_recording_path(&session_id)?; + let _lease = crate::persistence::acquire_recording_archive_lease(&path); let data = tokio::fs::read(&path).await.map_err(|e| { if e.kind() == std::io::ErrorKind::NotFound { "recording not found".into() @@ -207,6 +209,7 @@ pub async fn export_audio_recording( tokio::task::spawn_blocking(move || -> Result { let src = existing_recording_path(&session_id)?; + let _lease = crate::persistence::acquire_recording_archive_lease(&src); if configured_directory.is_empty() { let file_path = app @@ -354,7 +357,9 @@ pub async fn retranscribe_recording( if !is_valid_session_id(&session_id) { return Err("historyRetranscribeInvalidId".into()); } - retranscription::retranscribe_recording_with_path(&core, session_id, existing_recording_path).await + let path = existing_recording_path(&session_id)?; + let _lease = crate::persistence::acquire_recording_archive_lease(&path); + retranscription::retranscribe_recording_with_path(&core, session_id, |_| Ok(path)).await } #[tauri::command] diff --git a/openless-all/app/src-tauri/src/commands/history_retranscription.rs b/openless-all/app/src-tauri/src/commands/history_retranscription.rs index 8670ba48b..74ea50b63 100644 --- a/openless-all/app/src-tauri/src/commands/history_retranscription.rs +++ b/openless-all/app/src-tauri/src/commands/history_retranscription.rs @@ -35,25 +35,16 @@ pub(super) async fn retranscribe_recording_with_path( return Err("historyRetranscribeUnsupported".into()); } let path = recording_path(&session_id).map_err(|_| "historyRetranscribeMissing".to_string())?; - let wav = tokio::fs::read(&path).await.map_err(|error| { - match error.kind() { - std::io::ErrorKind::NotFound => "historyRetranscribeMissing", - std::io::ErrorKind::PermissionDenied => "historyRetranscribePermission", - _ => "historyRetranscribeStorage", - } - .to_string() - })?; - let pcm = openless_core::audio::decode_dictation_wav(&wav) - .map_err(|_| "historyRetranscribeInvalidAudio".to_string())?; - if pcm.is_empty() { - return Err("historyRetranscribeInvalidAudio".into()); - } + let archive = tokio::task::spawn_blocking(move || HistoryWavArchive::open(&path)) + .await + .map_err(|_| "historyRetranscribeStorage".to_string())??; + let pcm_bytes = archive.len; let retranscribe_started = std::time::Instant::now(); let retranscription = core .services() .auxiliary - .retranscribe_pcm(pcm.to_vec()) + .retranscribe_archive(std::sync::Arc::new(archive)) .await .map_err(|failure| { // Only bounded categories leave this command; provider bodies may contain secrets. @@ -61,7 +52,7 @@ pub(super) async fn retranscribe_recording_with_path( log::warn!( "[history] retranscribe id={} bytes={} failed reason={} code={:?}", session_id, - pcm.len(), + pcm_bytes, reason, failure.error.code ); @@ -73,7 +64,7 @@ pub(super) async fn retranscribe_recording_with_path( log::info!( "[history] retranscribe id={} bytes={} result=empty_transcript", session_id, - pcm.len() + pcm_bytes ); return Err("historyRetranscribeNoSpeech".into()); } @@ -110,3 +101,204 @@ fn retranscription_error_reason(error: &openless_core::BackendError) -> &'static _ => "historyRetranscribeProvider", } } + +// Hold the file open for the entire request; reads stay bounded to one ASR segment. +struct HistoryWavArchive { + file: std::sync::Arc>, + offset: u64, + len: u64, +} + +impl HistoryWavArchive { + fn open(path: &std::path::Path) -> Result { + use std::io::{Read, Seek, SeekFrom}; + let mut file = std::fs::File::open(path).map_err(|error| { + match error.kind() { + std::io::ErrorKind::NotFound => "historyRetranscribeMissing", + std::io::ErrorKind::PermissionDenied => "historyRetranscribePermission", + _ => "historyRetranscribeStorage", + } + .to_string() + })?; + let invalid = || "historyRetranscribeInvalidAudio".to_string(); + let size = file.metadata().map_err(|_| invalid())?.len(); + let mut riff = [0; 12]; + file.read_exact(&mut riff).map_err(|_| invalid())?; + if &riff[..4] != b"RIFF" + || &riff[8..] != b"WAVE" + || u64::from(u32::from_le_bytes(riff[4..8].try_into().unwrap())) + 8 != size + { + return Err(invalid()); + } + let mut position = 12u64; + let mut format_ok = false; + let mut data = None; + while position < size { + file.seek(SeekFrom::Start(position)) + .map_err(|_| invalid())?; + let mut header = [0; 8]; + file.read_exact(&mut header).map_err(|_| invalid())?; + let len = u64::from(u32::from_le_bytes(header[4..].try_into().unwrap())); + let end = position + 8 + len; + if end > size { + return Err(invalid()); + } + match &header[..4] { + b"fmt " => { + if len < 16 { + return Err(invalid()); + } + let mut fmt = [0; 16]; + file.read_exact(&mut fmt).map_err(|_| invalid())?; + format_ok = fmt[..2] == 1u16.to_le_bytes() + && fmt[2..4] == 1u16.to_le_bytes() + && fmt[4..8] == 16_000u32.to_le_bytes() + && fmt[8..12] == 32_000u32.to_le_bytes() + && fmt[12..14] == 2u16.to_le_bytes() + && fmt[14..16] == 16u16.to_le_bytes(); + if !format_ok { + return Err(invalid()); + } + } + b"data" => { + if data.is_some() || len == 0 || !len.is_multiple_of(2) { + return Err(invalid()); + } + data = Some((position + 8, len)); + } + _ => {} + } + position = end + len % 2; + } + if !format_ok || position != size { + return Err(invalid()); + } + let (offset, len) = data.ok_or_else(invalid)?; + Ok(Self { + file: std::sync::Arc::new(std::sync::Mutex::new(file)), + offset, + len, + }) + } +} + +impl openless_core::RecordingArchive for HistoryWavArchive { + fn is_available(&self) -> bool { + true + } + fn pcm_byte_len( + &self, + ) -> futures_util::future::BoxFuture<'static, Result> { + let len = self.len; + Box::pin(async move { Ok(len) }) + } + fn read_pcm( + &self, + ) -> futures_util::future::BoxFuture<'static, Result, openless_core::BackendError>> + { + let Ok(len) = usize::try_from(self.len) else { + return Box::pin(async { + Err(openless_core::BackendError::new( + openless_core::BackendErrorCode::Persistence, + "recording archive exceeds addressable size", + )) + }); + }; + self.read_pcm_range(0, len) + } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> futures_util::future::BoxFuture<'static, Result, openless_core::BackendError>> + { + let file = self.file.clone(); + let start = (offset.is_multiple_of(2) + && len.is_multiple_of(2) + && offset <= self.len + && len as u64 <= self.len - offset) + .then(|| self.offset.checked_add(offset)) + .flatten(); + Box::pin(async move { + let read = tokio::task::spawn_blocking(move || -> std::io::Result> { + use std::io::{Read, Seek, SeekFrom}; + let start = + start.ok_or_else(|| std::io::Error::other("PCM range out of bounds"))?; + let mut file = file + .lock() + .map_err(|_| std::io::Error::other("archive lock poisoned"))?; + file.seek(SeekFrom::Start(start))?; + let mut pcm = vec![0; len]; + file.read_exact(&mut pcm)?; + Ok(pcm) + }) + .await; + read.map_err(|error| { + openless_core::BackendError::new( + openless_core::BackendErrorCode::Persistence, + error.to_string(), + ) + })? + .map_err(|error| { + openless_core::BackendError::new( + openless_core::BackendErrorCode::Persistence, + error.to_string(), + ) + }) + }) + } + fn discard( + &self, + ) -> futures_util::future::BoxFuture<'static, Result<(), openless_core::BackendError>> { + Box::pin(async { Ok(()) }) + } +} + +#[cfg(test)] +mod archive_tests { + use super::*; + use openless_core::RecordingArchive; + use std::io::{Seek, SeekFrom, Write}; + + #[tokio::test] + async fn sparse_long_archive_reads_only_requested_tail_and_rejects_short_reads() { + let path = std::env::temp_dir().join(format!( + "openless-history-range-{}.wav", + uuid::Uuid::new_v4() + )); + let pcm_len = 31 * 60 * 32_000u32; + let mut header = openless_core::audio::encode_dictation_wav(&[0, 0]).unwrap(); + header.truncate(44); + header[4..8].copy_from_slice(&(36 + pcm_len).to_le_bytes()); + header[40..44].copy_from_slice(&pcm_len.to_le_bytes()); + let mut file = std::fs::File::create(&path).unwrap(); + file.write_all(&header).unwrap(); + file.set_len(44 + u64::from(pcm_len)).unwrap(); + file.seek(SeekFrom::End(-4)).unwrap(); + file.write_all(&[1, 2, 3, 4]).unwrap(); + let archive = HistoryWavArchive::open(&path).unwrap(); + assert_eq!(archive.pcm_byte_len().await.unwrap(), u64::from(pcm_len)); + assert_eq!( + archive + .read_pcm_range(u64::from(pcm_len) - 4, 4) + .await + .unwrap(), + [1, 2, 3, 4] + ); + assert!(archive + .read_pcm_range(u64::from(pcm_len) - 2, 4) + .await + .is_err()); + assert!(archive.read_pcm_range(1, 2).await.is_err()); + assert!(archive.read_pcm_range(0, 3).await.is_err()); + assert!(archive.read_pcm_range(u64::MAX - 1, 2).await.is_err()); + file.set_len(44).unwrap(); + assert!(archive + .read_pcm_range(u64::from(pcm_len) - 4, 4) + .await + .is_err()); + drop(archive); + drop(file); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/openless-all/app/src-tauri/src/commands/selection_voice.rs b/openless-all/app/src-tauri/src/commands/selection_voice.rs index c4c8bf35a..6b0b23317 100644 --- a/openless-all/app/src-tauri/src/commands/selection_voice.rs +++ b/openless-all/app/src-tauri/src/commands/selection_voice.rs @@ -157,7 +157,7 @@ pub async fn confirm_selection_voice_preview( .begin_edit_preview_apply(qa_turn, text) .await .map_err(selection_voice_error)?; - let outcome = match coord.apply_selection_voice_preview_ticket(&ticket).await { + let outcome = match coord.apply_selection_voice_preview_ticket(&ticket) { Ok(outcome) => outcome, Err(error) => { let _ = core @@ -176,7 +176,7 @@ pub async fn confirm_selection_voice_preview( .finish_preview_apply(ticket.ticket_id, outcome) .await .map_err(selection_voice_error)?; - coord.finish_selection_voice_preview_host(ticket.session_id, outcome, &ticket.source_text); + coord.finish_selection_voice_preview_host(ticket.session_id); if let Err(error) = core.services().qa.dismiss_session(qa_turn).await { // Native delivery has already finished. A reopened panel belongs to // another turn and cannot revoke this Inserted/PasteSent/copy receipt. diff --git a/openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs b/openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs index 41a131039..292a382d4 100644 --- a/openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs +++ b/openless-all/app/src-tauri/src/coordinator/selection_voice_session.rs @@ -795,9 +795,6 @@ impl Coordinator { if !crate::selection::reactivate_selection_insertion_target(&insertion_target) { return Err("selectionVoiceTargetUnavailable".to_string()); } - if crate::selection::is_truncated_selection_stand_in(&ticket.source_text) { - return Err("selectionVoiceSelectionTooLong".to_string()); - } // Empty source_text = caret insert (Help me write). Skip Ctrl+C content // re-validation that assumes a non-empty selection (#1014). if !ticket.source_text.trim().is_empty() { diff --git a/openless-all/app/src-tauri/src/core_adapters.rs b/openless-all/app/src-tauri/src/core_adapters.rs index 94771d0f7..7ec9bd350 100644 --- a/openless-all/app/src-tauri/src/core_adapters.rs +++ b/openless-all/app/src-tauri/src/core_adapters.rs @@ -43,6 +43,28 @@ pub(crate) fn backend_slot() -> BackendSlot { Arc::new(Mutex::new(None)) } +fn publish_archive_recording_fault( + backend: &BackendSlot, + session_id: SessionId, + progress: &Arc, + message: String, +) { + let error = BackendError::new(BackendErrorCode::Persistence, message); + let _ = progress.publish(openless_core::RecordingEvent::Fatal(error.clone())); + let backend = backend.lock().clone(); + // Never join the audio worker from its own level callback. Core owns the + // asynchronous stop, ASR cancellation, history and admission cleanup. + tauri::async_runtime::spawn(async move { + if let Some(backend) = backend.and_then(|weak| weak.upgrade()) { + if let Err(error) = backend.report_recording_fault(session_id, error).await { + if error.code != BackendErrorCode::InvalidState { + log::warn!("[recordings] archive fault cleanup failed: {error}"); + } + } + } + }); +} + /// Native audio callbacks and resource destructors do not inherit Tokio's /// thread-local context. Always enqueue on Tauri's shared executor instead of /// asking the callback thread for a runtime and silently losing its cleanup. @@ -141,8 +163,10 @@ pub(crate) fn backend_dependencies( #[cfg(target_os = "windows")] { let prefs = preferences.get(); - warm_hub.set_capture_paused(0, - prefs.voice_activation_enabled && prefs.voice_activation_hotkey_linked); + warm_hub.set_capture_paused( + 0, + prefs.voice_activation_enabled && prefs.voice_activation_hotkey_linked, + ); warm_hub.configure( crate::recorder::warm_capture_enabled(prefs.low_latency_dictation_enabled, false), (!prefs.microphone_device_name.trim().is_empty()) @@ -254,7 +278,8 @@ pub(crate) fn backend_dependencies( ) .expect("Apple system speech provider ID"); let polisher = Arc::new(openless_core::TextPolisherRouter::default()); - let production_polisher = openless_core::SharedCloudTextPolisher::new(Arc::clone(&credential_store)); + let production_polisher = + openless_core::SharedCloudTextPolisher::new(Arc::clone(&credential_store)); let production_polisher: Arc = Arc::new(match &usage_recorder { Some(recorder) => production_polisher.with_usage_recorder(Arc::clone(recorder)), None => production_polisher, @@ -3197,6 +3222,9 @@ impl PendingAudioCapture for TauriPendingAudioCapture { .flatten(); // 调试录音:主档案写处理后(或只勾处理前时写原始),需要对照时 // 同目录再存一份 `.raw.wav`。 + let archive_lease = archive_path + .as_deref() + .map(crate::persistence::acquire_recording_archive_lease); let archives = crate::recorder::ArchiveTargets { processed: archive_path.clone(), raw: (recording_plan.archive_raw && archive_path.is_some()) @@ -3208,9 +3236,28 @@ impl PendingAudioCapture for TauriPendingAudioCapture { .flatten(), write_processed: recording_plan.archive_processed, }; + let archive_status_slot: Arc>> = + Arc::new(Mutex::new(None)); + let status_for_levels = Arc::clone(&archive_status_slot); + let fault_reported = AtomicBool::new(false); + let archive_fault_backend = Arc::clone(&backend_for_recording); let started_at = Instant::now(); let level_progress = Arc::clone(&progress); let level_handler: Arc = Arc::new(move |level| { + let archive_error = status_for_levels + .lock() + .as_ref() + .and_then(|status| status.error()); + if let Some(error) = archive_error { + if !fault_reported.swap(true, Ordering::AcqRel) { + publish_archive_recording_fault( + &archive_fault_backend, + session_id, + &level_progress, + error, + ); + } + } let _ = level_progress .publish_level(started_at.elapsed().as_millis() as u64, level); }); @@ -3305,6 +3352,15 @@ impl PendingAudioCapture for TauriPendingAudioCapture { false, ), }; + let archive_status = recorder + .as_ref() + .and_then(Recorder::archive_status) + .or_else(|| { + warm_capture + .as_ref() + .and_then(WarmActiveCapture::archive_status) + }); + *archive_status_slot.lock() = archive_status.clone(); if recording_plan.archive_required && !archive_active { if let Some(recorder) = recorder { recorder.stop(); @@ -3346,8 +3402,14 @@ impl PendingAudioCapture for TauriPendingAudioCapture { resume_warm_hub, backend: Arc::clone(&backend_for_recording), reconfigure_voice_activation, - archive: archive_path - .map(|path| Arc::new(TauriRecordingArchive::new(path, archive_active))), + archive: archive_path.zip(archive_lease).map(|(path, lease)| { + Arc::new(TauriRecordingArchive::new( + path, + archive_active, + archive_status, + lease, + )) + }), _mute: mute, }) as Box; Ok((recording, runtime_errors)) @@ -3430,15 +3492,40 @@ impl PendingAudioCapture for TauriPendingAudioCapture { struct TauriRecordingArchive { path: Arc>, available: Arc, + status: Option, + lease: Arc>>, } impl TauriRecordingArchive { - fn new(path: PathBuf, available: bool) -> Self { + fn new( + path: PathBuf, + available: bool, + status: Option, + lease: crate::persistence::RecordingArchiveLease, + ) -> Self { Self { path: Arc::new(Mutex::new(path)), available: Arc::new(AtomicBool::new(available)), + status, + lease: Arc::new(Mutex::new(Some(lease))), } } + + fn checked_archive_path(&self) -> Result { + if let Some(error) = self.write_error() { + return Err(BackendError::new( + BackendErrorCode::Persistence, + format!("recording archive write failed: {error}"), + )); + } + if !self.available.load(Ordering::Acquire) { + return Err(BackendError::new( + BackendErrorCode::Persistence, + "longRecordingArchiveIncomplete", + )); + } + Ok(self.path.lock().clone()) + } } impl RecordingArchive for TauriRecordingArchive { @@ -3447,77 +3534,97 @@ impl RecordingArchive for TauriRecordingArchive { } fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { - let path = self.path.lock().clone(); + let checked = self.checked_archive_path(); Box::pin(async move { - use tokio::io::AsyncReadExt; - let read = async { - let mut file = tokio::fs::File::open(path).await?; - let size = file.metadata().await?.len(); - let mut header = [0; 44]; - file.read_exact(&mut header).await?; - Ok::<_, std::io::Error>((size, header)) - } + let path = checked?; + let lease = crate::persistence::acquire_recording_archive_lease(&path); + tauri::async_runtime::spawn_blocking(move || { + let _lease = lease; + let mut file = std::fs::File::open(&path).map_err(|error| { + BackendError::new( + BackendErrorCode::Persistence, + format!("read dictation archive header: {error}"), + ) + })?; + openless_core::audio::canonical_archive_pcm_len(&mut file) + }) .await .map_err(|error| { BackendError::new( BackendErrorCode::Persistence, - format!("read dictation archive header: {error}"), + format!("join dictation archive header task: {error}"), ) - })?; - let (size, header) = read; - let pcm_bytes = u64::from(u32::from_le_bytes(header[40..44].try_into().unwrap())); - if &header[..4] != b"RIFF" - || &header[8..12] != b"WAVE" - || &header[36..40] != b"data" - || size != 44 + pcm_bytes - || !pcm_bytes.is_multiple_of(2) - { - return Err(BackendError::new( + })? + }) + } + + fn write_error(&self) -> Option { + self.status.as_ref().and_then(|status| status.error()) + } + + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + let checked = self.checked_archive_path(); + Box::pin(async move { + let path = checked?; + let lease = crate::persistence::acquire_recording_archive_lease(&path); + tauri::async_runtime::spawn_blocking(move || { + let _lease = lease; + let mut file = std::fs::File::open(&path).map_err(|error| { + BackendError::new( + BackendErrorCode::Persistence, + format!("read recording PCM range: {error}"), + ) + })?; + openless_core::audio::read_canonical_archive_pcm_range(&mut file, offset, len) + }) + .await + .map_err(|error| { + BackendError::new( BackendErrorCode::Persistence, - "longRecordingArchiveIncomplete", - )); - } - Ok(pcm_bytes) + format!("join recording PCM range task: {error}"), + ) + })? }) } fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { - let path = self.path.lock().clone(); + let checked = self.checked_archive_path(); Box::pin(async move { + let path = checked?; + let lease = crate::persistence::acquire_recording_archive_lease(&path); let wav = tokio::fs::read(&path).await.map_err(|error| { BackendError::new( BackendErrorCode::Persistence, format!("read dictation recording archive: {error}"), ) })?; - if wav.len() <= 44 - || &wav[..4] != b"RIFF" - || &wav[8..12] != b"WAVE" - || !(wav.len() - 44).is_multiple_of(2) - { - return Err(BackendError::new( - BackendErrorCode::Persistence, - "dictation recording archive is not canonical PCM WAV", - )); - } - Ok(wav[44..].to_vec()) + drop(lease); + openless_core::audio::decode_dictation_wav(&wav).map(ToOwned::to_owned) }) } fn discard(&self) -> BoxFuture<'static, Result<(), BackendError>> { let path = self.path.lock().clone(); let available = Arc::clone(&self.available); + let lease = Arc::clone(&self.lease); Box::pin(async move { if !available.load(Ordering::Acquire) { + *lease.lock() = None; return Ok(()); } match tokio::fs::remove_file(&path).await { Ok(()) => { available.store(false, Ordering::Release); + *lease.lock() = None; Ok(()) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { available.store(false, Ordering::Release); + *lease.lock() = None; Ok(()) } Err(error) => { @@ -3536,6 +3643,7 @@ impl RecordingArchive for TauriRecordingArchive { fn promote_to_quick_note(&self) -> BoxFuture<'static, Result<(), BackendError>> { let path = Arc::clone(&self.path); + let lease = Arc::clone(&self.lease); Box::pin(async move { let current = path.lock().clone(); let Some(file_name) = current.file_name().map(|name| name.to_owned()) else { @@ -3552,6 +3660,7 @@ impl RecordingArchive for TauriRecordingArchive { if current == target { return Ok(()); } + let target_lease = crate::persistence::acquire_recording_archive_lease(&target); tokio::fs::rename(¤t, &target) .await .map_err(|error| { @@ -3561,12 +3670,14 @@ impl RecordingArchive for TauriRecordingArchive { ) })?; *path.lock() = target; + *lease.lock() = Some(target_lease); Ok(()) }) } fn demote_to_ordinary_recording(&self) -> BoxFuture<'static, Result<(), BackendError>> { let path = Arc::clone(&self.path); + let lease = Arc::clone(&self.lease); Box::pin(async move { let current = path.lock().clone(); let Some(file_name) = current.file_name().map(|name| name.to_owned()) else { @@ -3583,6 +3694,7 @@ impl RecordingArchive for TauriRecordingArchive { if current == target { return Ok(()); } + let target_lease = crate::persistence::acquire_recording_archive_lease(&target); tokio::fs::rename(¤t, &target) .await .map_err(|error| { @@ -3592,6 +3704,7 @@ impl RecordingArchive for TauriRecordingArchive { ) })?; *path.lock() = target; + *lease.lock() = Some(target_lease); Ok(()) }) } @@ -3865,9 +3978,31 @@ impl AudioRecorder for TauriAudioRecorder { recording_plan.mute_during_recording, crate::audio_mute::AudioMuteGuard::activate, ); + let archive_lease = archive_path + .as_deref() + .map(crate::persistence::acquire_recording_archive_lease); + let archive_status_slot: Arc>> = + Arc::new(Mutex::new(None)); + let status_for_levels = Arc::clone(&archive_status_slot); + let fault_reported = AtomicBool::new(false); + let archive_fault_backend = Arc::clone(&backend_for_recording); let started_at = Instant::now(); let level_progress = Arc::clone(&progress); let level_handler: Arc = Arc::new(move |level| { + let archive_error = status_for_levels + .lock() + .as_ref() + .and_then(|status| status.error()); + if let Some(error) = archive_error { + if !fault_reported.swap(true, Ordering::AcqRel) { + publish_archive_recording_fault( + &archive_fault_backend, + session_id, + &level_progress, + error, + ); + } + } let _ = level_progress .publish_level(started_at.elapsed().as_millis() as u64, level); }); @@ -3907,6 +4042,8 @@ impl AudioRecorder for TauriAudioRecorder { "速记录音文件无法创建,已阻止开始录音以避免丢失内容", )); } + let archive_status = recorder.archive_status(); + *archive_status_slot.lock() = archive_status.clone(); let recording = Box::new(TauriActiveRecording { recorder: Some(recorder), warm_capture: None, @@ -3914,8 +4051,14 @@ impl AudioRecorder for TauriAudioRecorder { resume_warm_hub: Some(worker_resume_warm_hub), backend: Arc::clone(&backend_for_recording), reconfigure_voice_activation: true, - archive: archive_path - .map(|path| Arc::new(TauriRecordingArchive::new(path, archive_active))), + archive: archive_path.zip(archive_lease).map(|(path, lease)| { + Arc::new(TauriRecordingArchive::new( + path, + archive_active, + archive_status, + lease, + )) + }), _mute: mute, }) as Box; Ok((recording, runtime_errors)) @@ -4277,7 +4420,9 @@ where } impl CoreTextInserter for TauriTextInserter { - fn defer_preparation_until_stop(&self) -> bool { true } + fn defer_preparation_until_stop(&self) -> bool { + true + } fn capture_target(&self) -> Option { let insertion_target = crate::selection::capture_selection_insertion_target(); #[cfg(target_os = "windows")] @@ -4830,10 +4975,12 @@ impl TauriTextInsertionSession { fn restore_insertion_target(&self) -> Result<(), BackendError> { crate::selection::reactivate_dictation_insertion_target(&self.insertion_target) .then_some(()) - .ok_or_else(|| BackendError::new( - BackendErrorCode::Platform, - "original text insertion target is unavailable", - )) + .ok_or_else(|| { + BackendError::new( + BackendErrorCode::Platform, + "original text insertion target is unavailable", + ) + }) } async fn write_chunk(&self, text: String) -> Result { @@ -5071,7 +5218,8 @@ impl TauriTextInsertionSession { .and_then(|b| b.upgrade()) .is_some_and(|b| { let prefs = b.get_preferences(); - prefs.vocabulary_learning_enabled || prefs.expression_learning_enabled + prefs.vocabulary_learning_enabled + || prefs.expression_learning_enabled }) }, || { @@ -5178,7 +5326,8 @@ impl TauriTextInsertionSession { if session.cancel_requested.load(Ordering::Acquire) { return Ok(MacInsertionCompletion::Cancelled); } - finish_mac_final_text(final_text, |text| session.insert_final(text)).await + finish_mac_final_text(final_text, |text| session.insert_final(text)) + .await }, || session.restore_platform_state(), ) @@ -5247,9 +5396,13 @@ fn replace_unwritten_target( impl TextInsertionSession for TauriTextInsertionSession { fn supports_streaming(&self) -> bool { #[cfg(target_os = "macos")] - { self.streaming_ready } + { + self.streaming_ready + } #[cfg(not(target_os = "macos"))] - { cfg!(target_os = "windows") } + { + cfg!(target_os = "windows") + } } fn write(&self, text: String) -> BoxFuture<'static, Result> { @@ -5407,7 +5560,10 @@ mod mac_insertion_lifecycle_tests { }) .await .unwrap(); - assert_eq!(result, MacInsertionCompletion::Finished(InsertOutcome::Inserted)); + assert_eq!( + result, + MacInsertionCompletion::Finished(InsertOutcome::Inserted) + ); assert_eq!(*calls.lock(), ["final text"]); } @@ -5418,7 +5574,10 @@ mod mac_insertion_lifecycle_tests { }) .await .unwrap(); - assert_eq!(result, MacInsertionCompletion::Finished(InsertOutcome::Inserted)); + assert_eq!( + result, + MacInsertionCompletion::Finished(InsertOutcome::Inserted) + ); assert_eq!( finish_mac_final_text(None, |_| async { panic!("cancelled text must not invoke insertion") @@ -5617,10 +5776,7 @@ mod mac_insertion_lifecycle_tests { } #[cfg(target_os = "windows")] -fn windows_unicode_fallback( - context: &DictationContext, - text: &str, -) -> crate::types::InsertStatus { +fn windows_unicode_fallback(context: &DictationContext, text: &str) -> crate::types::InsertStatus { let inserter = crate::insertion::TextInserter::new(); let status = inserter.insert_via_unicode_keystrokes( text, @@ -5628,7 +5784,11 @@ fn windows_unicode_fallback( newline_mode: context.insertion.windows_sendinput_newline_mode, }, ); - if matches!(status, crate::types::InsertStatus::Inserted | crate::types::InsertStatus::PasteSent) || !context.insertion.allow_non_tsf_fallback { + if matches!( + status, + crate::types::InsertStatus::Inserted | crate::types::InsertStatus::PasteSent + ) || !context.insertion.allow_non_tsf_fallback + { status } else { inserter.copy_fallback(text) @@ -5767,11 +5927,17 @@ impl HostActions for TauriHostActions { HostAction::ShowMain | HostAction::FocusMain => crate::show_main_window(&app), HostAction::ShowDictationFeedback | HostAction::HideDictationFeedback => {} HostAction::ShowSelectionPreview => { - return Err(BackendError::new(BackendErrorCode::Unsupported, "Selection polish preview is unavailable")); + return Err(BackendError::new( + BackendErrorCode::Unsupported, + "Selection polish preview is unavailable", + )); } HostAction::HideSelectionPreview => {} HostAction::ShowQa => { - return Err(BackendError::new(BackendErrorCode::Unsupported, "Ask is unavailable")); + return Err(BackendError::new( + BackendErrorCode::Unsupported, + "Ask is unavailable", + )); } HostAction::HideQa => { self.qa_context.set_voice_surface_active(false); @@ -5807,6 +5973,186 @@ fn map_tauri_error(error: impl std::fmt::Display) -> BackendError { #[cfg(test)] mod tests { + #[tokio::test] + async fn archive_fault_from_audio_thread_releases_capture_and_admission() { + struct Progress(std::sync::atomic::AtomicUsize); + impl RecordingProgressSink for Progress { + fn publish_level(&self, _: u64, _: f32) -> Result<(), BackendError> { + Ok(()) + } + fn publish(&self, event: openless_core::RecordingEvent) -> Result<(), BackendError> { + assert!(matches!(event, openless_core::RecordingEvent::Fatal(_))); + self.0.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + } + struct Host; + impl HostActions for Host { + fn request(&self, _: HostAction) -> Result<(), BackendError> { + Ok(()) + } + } + let directory = + std::env::temp_dir().join(format!("openless-archive-fault-{}", uuid::Uuid::new_v4())); + let engine = Arc::new(openless_core::testing::FixtureDictationEngine::successful( + "", "", + )); + let mut dependencies = openless_core::BackendDependencies::unsupported(); + dependencies.dictation_engine = engine.clone(); + dependencies.host_actions = Arc::new(Host); + let backend = Arc::new( + openless_core::OpenLessBackend::new( + openless_core::BackendConfig { + data_dir: directory.clone(), + ..Default::default() + }, + dependencies, + ) + .unwrap(), + ); + backend.start().await.unwrap(); + let id = backend + .start_dictation_with_options(openless_core::DictationStartOptions { + insert_text: false, + ..Default::default() + }) + .await + .unwrap(); + let slot = backend_slot(); + *slot.lock() = Some(Arc::downgrade(&backend)); + let progress = Arc::new(Progress(std::sync::atomic::AtomicUsize::new(0))); + let sink: Arc = progress.clone(); + // A native worker has no inherited Tokio runtime and must never block on cleanup. + std::thread::spawn(move || { + publish_archive_recording_fault(&slot, id, &sink, "disk write failed".into()) + }) + .join() + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(3), async { + while backend.snapshot().dictation.session_id.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(progress.0.load(Ordering::Acquire), 1); + assert!(engine + .actions() + .contains(&openless_core::testing::FixtureEngineAction::Cancel(id))); + assert_eq!( + backend.list_history().unwrap()[0].error_code.as_deref(), + Some("recordingFailed") + ); + let next = backend + .start_dictation_with_options(openless_core::DictationStartOptions { + insert_text: false, + ..Default::default() + }) + .await + .unwrap(); + backend.cancel_dictation(Some(next)).await.unwrap(); + drop(backend); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn tauri_recording_archive_validates_bounds_headers_and_releases_lease_on_discard() { + use openless_core::RecordingArchive; + use std::io::Write; + + let dir = + std::env::temp_dir().join(format!("openless-tauri-archive-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("sample.wav"); + let valid_wav = openless_core::audio::encode_dictation_wav(&[1, 2, 3, 4, 5, 6]).unwrap(); + std::fs::write(&path, &valid_wav).unwrap(); + + let status = crate::recorder::WavArchiveStatus::default(); + let lease = crate::persistence::acquire_recording_archive_lease(&path); + let archive = Arc::new(TauriRecordingArchive::new( + path.clone(), + true, + Some(status), + lease, + )); + assert!(crate::persistence::is_recording_archive_leased(&path)); + assert_eq!(archive.pcm_byte_len().await.unwrap(), 6); + assert_eq!( + archive.read_pcm_range(2, 4).await.unwrap(), + vec![3, 4, 5, 6] + ); + assert_eq!(archive.read_pcm().await.unwrap(), vec![1, 2, 3, 4, 5, 6]); + + assert!(archive.read_pcm_range(1, 2).await.is_err()); + assert!(archive.read_pcm_range(0, 3).await.is_err()); + assert!(archive.read_pcm_range(4, 4).await.is_err()); + + { + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap(); + file.write_all(&[0, 0]).unwrap(); + } + assert!(archive.pcm_byte_len().await.is_err()); + assert!(archive.read_pcm_range(0, 4).await.is_err()); + assert!(archive.read_pcm().await.is_err()); + + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(46) + .unwrap(); + assert!(archive.pcm_byte_len().await.is_err()); + assert!(archive.read_pcm_range(0, 2).await.is_err()); + + let mut bad_fmt = valid_wav.clone(); + bad_fmt[24..28].copy_from_slice(&8_000u32.to_le_bytes()); + std::fs::write(&path, &bad_fmt).unwrap(); + assert!(archive.pcm_byte_len().await.is_err()); + assert!(archive.read_pcm_range(0, 4).await.is_err()); + assert!(archive.read_pcm().await.is_err()); + + std::fs::write(&path, &valid_wav).unwrap(); + archive.discard().await.unwrap(); + assert!(!archive.is_available()); + assert!(!path.exists()); + assert!(!crate::persistence::is_recording_archive_leased(&path)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn tauri_recording_archive_fails_closed_when_write_error_latched() { + use openless_core::RecordingArchive; + + let dir = std::env::temp_dir().join(format!( + "openless-tauri-archive-err-{}", + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("faulty.wav"); + std::fs::write( + &path, + openless_core::audio::encode_dictation_wav(&[1, 2, 3, 4]).unwrap(), + ) + .unwrap(); + + let status = crate::recorder::WavArchiveStatus::default(); + let lease = crate::persistence::acquire_recording_archive_lease(&path); + let archive = TauriRecordingArchive::new(path.clone(), true, Some(status.clone()), lease); + status.record_error("disk full"); + + assert_eq!(archive.write_error().as_deref(), Some("disk full")); + assert!(archive.pcm_byte_len().await.is_err()); + assert!(archive.read_pcm_range(0, 4).await.is_err()); + assert!(archive.read_pcm().await.is_err()); + + archive.discard().await.unwrap(); + assert!(!crate::persistence::is_recording_archive_leased(&path)); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn live_input_retargets_only_before_any_write() { #[derive(Debug)] @@ -5818,10 +6164,12 @@ mod tests { written: false, current: false, }); - let capture = || Ok(Target { - written: false, - current: true, - }); + let capture = || { + Ok(Target { + written: false, + current: true, + }) + }; let replace = |target: &mut Target, _: &str| { if !target.current { return Err("target changed".into()); diff --git a/openless-all/app/src-tauri/src/hotkey.rs b/openless-all/app/src-tauri/src/hotkey.rs index 1fa35bd6d..3ca3809b6 100644 --- a/openless-all/app/src-tauri/src/hotkey.rs +++ b/openless-all/app/src-tauri/src/hotkey.rs @@ -940,7 +940,6 @@ mod platform { match event_type { TAP_DISABLED_BY_TIMEOUT | TAP_DISABLED_BY_USER_INPUT => { reset_shared_held_state(&ctx.shared); - crate::recording_companion::reset_held(); if let Some(pending) = ctx.pending_space.lock().take() { pending.replay(std::ptr::null_mut()); } diff --git a/openless-all/app/src-tauri/src/lib.rs b/openless-all/app/src-tauri/src/lib.rs index 23decb49e..7c244ebe9 100644 --- a/openless-all/app/src-tauri/src/lib.rs +++ b/openless-all/app/src-tauri/src/lib.rs @@ -2117,14 +2117,6 @@ pub fn log_dir_path() -> std::path::PathBuf { } } -pub(crate) fn require_ask_anything() -> Result<(), String> { - if ask_anything_available() { - Ok(()) - } else { - Err("Ask Anything is disabled in this build".into()) - } -} - pub(crate) fn show_main_window(app: &AppHandle) { activate_window_mode(app); #[cfg(not(mobile))] diff --git a/openless-all/app/src-tauri/src/persistence/paths.rs b/openless-all/app/src-tauri/src/persistence/paths.rs index b652ce9f5..510bda7ed 100644 --- a/openless-all/app/src-tauri/src/persistence/paths.rs +++ b/openless-all/app/src-tauri/src/persistence/paths.rs @@ -2,13 +2,87 @@ //! pruning), and the Windows //! Foundry Local cache roots. +use std::collections::HashMap; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::{LazyLock, Mutex}; use anyhow::{Context, Result}; use super::{data_dir, ensure_dir, HISTORY_CAP, PREFERENCES_FILE}; +static RECORDING_ARCHIVE_LEASES: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn normalized_archive_lease_key(path: &Path) -> PathBuf { + if let Ok(canonical) = fs::canonicalize(path) { + return canonical; + } + if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) { + if let Ok(canonical_parent) = fs::canonicalize(parent) { + return canonical_parent.join(name); + } + } + path.to_path_buf() +} + +/// Active lease preventing retention pruning from deleting a recording WAV +/// that is still being written, recovered, promoted, retranscribed, or read. +pub struct RecordingArchiveLease { + key: PathBuf, +} + +impl RecordingArchiveLease { + #[allow(dead_code)] + pub fn path(&self) -> &Path { + &self.key + } +} + +impl Drop for RecordingArchiveLease { + fn drop(&mut self) { + let mut leases = RECORDING_ARCHIVE_LEASES + .lock() + .expect("recording archive lease lock poisoned"); + if let Some(count) = leases.get_mut(&self.key) { + if *count <= 1 { + leases.remove(&self.key); + } else { + *count -= 1; + } + } + } +} + +pub fn acquire_recording_archive_lease(path: &Path) -> RecordingArchiveLease { + let key = normalized_archive_lease_key(path); + let mut leases = RECORDING_ARCHIVE_LEASES + .lock() + .expect("recording archive lease lock poisoned"); + *leases.entry(key.clone()).or_insert(0) += 1; + RecordingArchiveLease { key } +} + +pub fn is_recording_archive_leased(path: &Path) -> bool { + let key = normalized_archive_lease_key(path); + let leases = RECORDING_ARCHIVE_LEASES + .lock() + .expect("recording archive lease lock poisoned"); + leases.contains_key(&key) +} + +fn remove_unleased_recording(path: &Path) -> std::io::Result<()> { + let key = normalized_archive_lease_key(path); + let leases = RECORDING_ARCHIVE_LEASES + .lock() + .expect("recording archive lease lock poisoned"); + if leases.contains_key(&key) { + return Ok(()); + } + // Serialize deletion with lease acquisition, including paths not created yet. + fs::remove_file(path) +} + /// Default models root: `/models/`. pub fn default_models_root() -> Result { let dir = data_dir()?.join("models"); @@ -87,6 +161,14 @@ pub fn prune_recordings(retention_days: u32, max_entries: Option) -> Result Ok(d) => d.join("recordings"), Err(_) => return Ok(()), }; + prune_recordings_in_dir(&dir, retention_days, max_entries) +} + +fn prune_recordings_in_dir( + dir: &Path, + retention_days: u32, + max_entries: Option, +) -> Result<()> { if !dir.exists() { return Ok(()); } @@ -97,18 +179,21 @@ pub fn prune_recordings(retention_days: u32, max_entries: Option) -> Result if retention_days > 0 { let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(u64::from(retention_days) * 24 * 3600); - for entry in fs::read_dir(&dir).context("read recordings dir")?.flatten() { + for entry in fs::read_dir(dir).context("read recordings dir")?.flatten() { let path = entry.path(); if path.extension().and_then(|ext| ext.to_str()) != Some("wav") { continue; } + if is_recording_archive_leased(&path) { + continue; + } let modified = entry .metadata() .ok() .and_then(|m| m.modified().ok()) .unwrap_or(std::time::UNIX_EPOCH); if modified < cutoff { - if let Err(err) = fs::remove_file(&path) { + if let Err(err) = remove_unleased_recording(&path) { log::warn!("[recordings] prune (days) remove failed for {path:?}: {err}"); } } @@ -120,7 +205,7 @@ pub fn prune_recordings(retention_days: u32, max_entries: Option) -> Result let cap = max_entries .map(|n| (n as usize).clamp(1, HISTORY_CAP)) .unwrap_or(HISTORY_CAP); - let mut entries: Vec<(PathBuf, std::time::SystemTime)> = fs::read_dir(&dir) + let mut entries: Vec<(PathBuf, std::time::SystemTime)> = fs::read_dir(dir) .context("read recordings dir")? .flatten() .filter_map(|e| { @@ -139,7 +224,10 @@ pub fn prune_recordings(retention_days: u32, max_entries: Option) -> Result } entries.sort_by(|a, b| b.1.cmp(&a.1)); for (path, _) in entries.into_iter().skip(cap) { - if let Err(err) = fs::remove_file(&path) { + if is_recording_archive_leased(&path) { + continue; + } + if let Err(err) = remove_unleased_recording(&path) { log::warn!( "[recordings] prune (count) remove failed for {:?}: {err}", path @@ -201,9 +289,13 @@ pub fn foundry_logs_root() -> Result { #[cfg(test)] mod tests { - use super::models_root_for_base_dir; + use super::{ + acquire_recording_archive_lease, is_recording_archive_leased, models_root_for_base_dir, + prune_recordings_in_dir, + }; use std::fs; use std::path::PathBuf; + use std::time::{Duration, SystemTime}; #[test] fn custom_models_root_uses_openless_models_suffix() { @@ -217,4 +309,51 @@ mod tests { let _ = fs::remove_dir_all(&tmp); } + + #[test] + fn prune_recordings_preserves_leased_files_for_age_and_count_then_prunes_on_drop() { + let dir = + std::env::temp_dir().join(format!("openless-prune-lease-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + + let leased_path = dir.join("leased.wav"); + let expired_unleased = dir.join("expired.wav"); + let newer_unleased = dir.join("newer.wav"); + + let old_time = SystemTime::now() - Duration::from_secs(3 * 24 * 3600); + let mid_time = SystemTime::now() - Duration::from_secs(60); + + for (path, modified) in [ + (&leased_path, old_time), + (&expired_unleased, old_time), + (&newer_unleased, mid_time), + ] { + let file = fs::File::create(path).unwrap(); + file.set_modified(modified).unwrap(); + } + + // Acquire the lease before file age/count pruning runs. + let lease = acquire_recording_archive_lease(&leased_path); + assert!(is_recording_archive_leased(&leased_path)); + + // Age pruning removes expired unleased files while keeping the leased file. + prune_recordings_in_dir(&dir, 1, None).unwrap(); + assert!(leased_path.exists()); + assert!(!expired_unleased.exists()); + assert!(newer_unleased.exists()); + + // Count pruning (cap = 1) keeps both newer.wav and the older leased.wav. + prune_recordings_in_dir(&dir, 0, Some(1)).unwrap(); + assert!(leased_path.exists()); + assert!(newer_unleased.exists()); + + // Dropping the lease allows subsequent pruning to reclaim the older file. + drop(lease); + assert!(!is_recording_archive_leased(&leased_path)); + prune_recordings_in_dir(&dir, 0, Some(1)).unwrap(); + assert!(!leased_path.exists()); + assert!(newer_unleased.exists()); + + let _ = fs::remove_dir_all(&dir); + } } diff --git a/openless-all/app/src-tauri/src/recorder.rs b/openless-all/app/src-tauri/src/recorder.rs index bab86af07..7af30d889 100644 --- a/openless-all/app/src-tauri/src/recorder.rs +++ b/openless-all/app/src-tauri/src/recorder.rs @@ -38,7 +38,10 @@ use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender, TrySe use std::sync::{Arc, OnceLock}; use std::thread::{self, JoinHandle}; -use crate::issue1266_debug::{Event as DebugEvent, Facts as DebugFacts, Kind as DebugKind, Operation as DebugOperation, Outcome as DebugOutcome, Probe as DebugProbe}; +use crate::issue1266_debug::{ + Event as DebugEvent, Facts as DebugFacts, Kind as DebugKind, Operation as DebugOperation, + Outcome as DebugOutcome, Probe as DebugProbe, +}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{SampleFormat, StreamConfig}; @@ -86,7 +89,11 @@ pub(crate) fn voice_diagnostic( crate::issue1266_debug::legacy(event, outcome); let _ = (probe_id, hypothesis_ids, safe); } - #[cfg(all(target_os = "windows", not(feature = "issue-1266-diagnostics"), not(test)))] + #[cfg(all( + target_os = "windows", + not(feature = "issue-1266-diagnostics"), + not(test) + ))] { use std::io::Write; static WRITER: OnceLock>> = OnceLock::new(); @@ -144,7 +151,10 @@ pub(crate) fn voice_diagnostic( } } } - #[cfg(any(not(target_os = "windows"), all(test, not(feature = "issue-1266-diagnostics"))))] + #[cfg(any( + not(target_os = "windows"), + all(test, not(feature = "issue-1266-diagnostics")) + ))] let _ = (probe_id, hypothesis_ids, event, outcome, safe); } @@ -355,42 +365,118 @@ impl RecorderError { } } +const MAX_ARCHIVE_QUEUE_BYTES: usize = 32 * 1024 * 1024; + +#[derive(Clone, Default)] +pub(crate) struct WavArchiveStatus { + error: Arc>>, +} + +impl WavArchiveStatus { + pub(crate) fn record_error(&self, message: impl Into) { + let mut slot = self.error.lock(); + if slot.is_none() { + *slot = Some(message.into()); + } + } + + pub(crate) fn error(&self) -> Option { + self.error.lock().clone() + } + + pub(crate) fn is_ok(&self) -> bool { + self.error.lock().is_none() + } +} + enum WavArchiveMessage { Pcm(Vec), Finish, } /// WAV archive entry point off the realtime audio callback. The callback only copies PCM and -/// queues every frame without blocking on disk; file writing, seek, and sync run -/// on a dedicated thread. A temporary disk backlog must not punch holes in a -/// recoverable long recording. +/// queues frames within a bounded memory budget without blocking live ASR; file writing, +/// seek, and sync run on a dedicated thread and latch any write or overflow error. struct WavArchiveWriter { sender: Sender, join_handle: Mutex>>, queue_full_warned: AtomicBool, + queued_bytes: Arc, + max_queue_bytes: usize, + status: WavArchiveStatus, } impl WavArchiveWriter { fn create(path: &Path) -> std::io::Result { + Self::create_with_max_queue(path, MAX_ARCHIVE_QUEUE_BYTES) + } + + fn create_with_max_queue(path: &Path, max_queue_bytes: usize) -> std::io::Result { let archiver = WavArchiver::create(path)?; let (sender, receiver) = channel::(); + let queued_bytes = Arc::new(AtomicUsize::new(0)); + let worker_queued = Arc::clone(&queued_bytes); + let status = WavArchiveStatus::default(); + let worker_status = status.clone(); let join_handle = thread::Builder::new() .name("openless-wav-archive".into()) - .spawn(move || run_wav_archive_writer(archiver, receiver))?; + .spawn(move || { + run_wav_archive_writer(archiver, receiver, worker_queued, worker_status); + })?; Ok(Self { sender, join_handle: Mutex::new(Some(join_handle)), queue_full_warned: AtomicBool::new(false), + queued_bytes, + max_queue_bytes, + status, }) } + fn status(&self) -> WavArchiveStatus { + self.status.clone() + } + fn append(&self, pcm_bytes: &[u8]) { - match self.sender.send(WavArchiveMessage::Pcm(pcm_bytes.to_vec())) { - Ok(()) => {} - Err(_) => { - if !self.queue_full_warned.swap(true, Ordering::Relaxed) { - log::warn!("[recorder] wav archive writer stopped before PCM was queued"); - } + if pcm_bytes.is_empty() || !self.status.is_ok() { + return; + } + // Reserve bounded queue budget atomically so slow disk writes never block audio callbacks. + let reserved = + self.queued_bytes + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { + current + .checked_add(pcm_bytes.len()) + .filter(|&next| next <= self.max_queue_bytes) + }); + if reserved.is_err() { + const MIB: usize = 1024 * 1024; + let limit = if self.max_queue_bytes.is_multiple_of(MIB) { + format!("{} MiB", self.max_queue_bytes / MIB) + } else { + format!("{} bytes", self.max_queue_bytes) + }; + self.status + .record_error(format!("wav archive queue exceeded {limit} limit")); + if !self.queue_full_warned.swap(true, Ordering::Relaxed) { + log::warn!( + "[recorder] wav archive queue full ({} bytes limit); dropping further archive frames", + self.max_queue_bytes + ); + } + return; + } + if self + .sender + .send(WavArchiveMessage::Pcm(pcm_bytes.to_vec())) + .is_err() + { + self.queued_bytes + .fetch_sub(pcm_bytes.len(), Ordering::AcqRel); + self.status + .record_error("wav archive writer stopped before PCM was queued"); + if !self.queue_full_warned.swap(true, Ordering::Relaxed) { + log::warn!("[recorder] wav archive writer stopped before PCM was queued"); } } } @@ -402,21 +488,48 @@ impl WavArchiveWriter { fn finish_observed(&self, parent: Option) { let operation = DebugOperation::child(DebugProbe::P5, parent); let _scope = operation.scope(); - operation.record(DebugEvent::ArchiveSend, DebugOutcome::Observed, - DebugFacts { kind: DebugKind::Archive, ..DebugFacts::default() }); + operation.record( + DebugEvent::ArchiveSend, + DebugOutcome::Observed, + DebugFacts { + kind: DebugKind::Archive, + ..DebugFacts::default() + }, + ); let _ = self.sender.send(WavArchiveMessage::Finish); operation.mark(DebugEvent::ArchiveSent); operation.mark(DebugEvent::JoinLock); if let Some(handle) = self.join_handle.lock().take() { operation.mark(DebugEvent::JoinEntered); let result = handle.join(); - operation.record(DebugEvent::JoinReturned, - if result.is_ok() { DebugOutcome::Ok } else { DebugOutcome::Error }, DebugFacts::default()); + operation.record( + DebugEvent::JoinReturned, + if result.is_ok() { + DebugOutcome::Ok + } else { + DebugOutcome::Error + }, + DebugFacts::default(), + ); if let Err(error) = result { + self.status + .record_error(format!("wav archive writer join failed: {error:?}")); log::warn!("[recorder] wav archive writer join failed: {error:?}"); } } - operation.record(DebugEvent::ArchiveReturned, DebugOutcome::Returned, DebugFacts::default()); + operation.record( + DebugEvent::ArchiveReturned, + DebugOutcome::Returned, + DebugFacts::default(), + ); + } +} + +impl Drop for WavArchiveWriter { + fn drop(&mut self) { + if self.join_handle.lock().is_some() { + self.finish(); + } } } @@ -489,6 +602,7 @@ struct ForwardTarget { consumer: Arc, level_handler: Arc, archive: Option>, + raw_archive: Option>, write_processed: bool, } @@ -542,6 +656,7 @@ impl CaptureSink { ) -> Result<(), RecorderError> { // 只要处理前时,主档案由 DSP 线程写原始 PCM,这里就不能再写处理后。 let write_processed = raw_tap.as_ref().map_or(true, |tap| tap.write_processed); + let raw_archive = raw_tap.as_ref().and_then(|tap| tap.raw_writer.clone()); let mut tap_slot = self.raw_tap.lock(); let _delivery = self.delivery_gate.lock(); *tap_slot = raw_tap; @@ -563,6 +678,7 @@ impl CaptureSink { consumer, level_handler, archive, + raw_archive, write_processed, }); prefix @@ -621,6 +737,7 @@ impl AudioConsumer for CaptureSink { consumer: Arc::clone(&target.consumer), level_handler: Arc::clone(&target.level_handler), archive: target.archive.clone(), + raw_archive: target.raw_archive.clone(), write_processed: target.write_processed, }), CaptureSinkState::Discarded => None, @@ -907,6 +1024,7 @@ impl WarmCaptureSink { let mut tap_slot = self.raw_tap.lock(); let _delivery = self.delivery_gate.lock(); let write_processed = raw_tap.as_ref().map_or(true, |tap| tap.write_processed); + let raw_archive = raw_tap.as_ref().and_then(|tap| tap.raw_writer.clone()); *tap_slot = raw_tap; let (prefix, staged_level) = { let mut state = self.state.lock(); @@ -928,6 +1046,7 @@ impl WarmCaptureSink { consumer, level_handler, archive, + raw_archive, write_processed, }), ); @@ -1029,18 +1148,21 @@ impl WarmCaptureSink { } fn clear(&self) -> Vec> { + let mut tap_slot = self.raw_tap.lock(); let _delivery = self.delivery_gate.lock(); + *tap_slot = None; let mut state = self.state.lock(); let WarmCaptureSinkState::Ring { pcm, claims } = &mut *state; pcm.clear(); let claims = std::mem::take(claims); - claims - .into_values() - .filter_map(|claim| match claim { - WarmCaptureClaim::Staging { .. } => None, - WarmCaptureClaim::Promoted(target) => target.archive, - }) - .collect() + let mut archives = Vec::new(); + for claim in claims.into_values() { + if let WarmCaptureClaim::Promoted(target) = claim { + archives.extend(target.archive); + archives.extend(target.raw_archive); + } + } + archives } } @@ -1136,6 +1258,7 @@ pub(crate) struct WarmStagedRecorder { pub(crate) struct WarmActiveCapture { hub: Arc, press_id: u64, + archive_status: Option, } impl WarmStagedRecorder { @@ -1176,10 +1299,11 @@ impl WarmStagedRecorder { }); let raw_tap = Some(Arc::new(RawTap::new( archive_writer.clone(), - raw_writer, + raw_writer.clone(), archives.write_processed, ))); let archive_active = archive_writer.is_some(); + let archive_status = archive_writer.as_ref().map(|writer| writer.status()); let result = self.hub.promote( self.press_id, consumer, @@ -1193,9 +1317,17 @@ impl WarmStagedRecorder { if let Some(archive) = archive_writer { archive.finish(); } + if let Some(raw) = raw_writer { + raw.finish(); + } if let Some(path) = archive_path { let _ = std::fs::remove_file(path); } + if archives.processed.is_some() { + if let Some(raw_path) = archives.raw.as_ref() { + let _ = std::fs::remove_file(raw_path); + } + } self.consumed = true; return Err(error); } @@ -1205,6 +1337,7 @@ impl WarmStagedRecorder { WarmActiveCapture { hub: Arc::clone(&self.hub), press_id: self.press_id, + archive_status, }, runtime_errors, archive_active, @@ -1227,6 +1360,10 @@ impl Drop for WarmStagedRecorder { } impl WarmActiveCapture { + pub(crate) fn archive_status(&self) -> Option { + self.archive_status.clone() + } + pub(crate) fn stop(self) { self.hub.release_claim(self.press_id); } @@ -1370,7 +1507,11 @@ impl WarmCaptureHub { } let device = self.device_name.lock().clone(); let processing = *self.processing_config.lock(); - self.configure_locked(self.standby_requested.load(Ordering::Acquire), device, processing); + self.configure_locked( + self.standby_requested.load(Ordering::Acquire), + device, + processing, + ); } pub(crate) fn configure( @@ -1637,7 +1778,9 @@ impl WarmCaptureHub { loop { let lifecycle = self.lifecycle_gate.lock(); if self.standby_policy.lock().1 { - return Err(RecorderError::EngineFailed("standby capture is paused".into())); + return Err(RecorderError::EngineFailed( + "standby capture is paused".into(), + )); } let desired_processing = processing.unwrap_or(*self.processing_config.lock()); if *self.device_name.lock() != device_name @@ -1681,8 +1824,12 @@ impl WarmCaptureHub { if let Some(archive) = target.archive { archive.finish(); } + if let Some(raw_archive) = target.raw_archive { + raw_archive.finish(); + } } if !self.sink.has_promoted_claims() { + *self.sink.raw_tap.lock() = None; let pending_configuration = self.pending_configuration.lock().take(); if let Some((enabled, device_name, processing)) = pending_configuration { self.configure_locked(enabled, device_name, processing); @@ -1816,13 +1963,26 @@ pub(crate) fn warm_capture_hub() -> Arc { Arc::clone(WARM_CAPTURE_HUB.get_or_init(WarmCaptureHub::new)) } -fn run_wav_archive_writer(mut archiver: WavArchiver, receiver: Receiver) { +fn run_wav_archive_writer( + mut archiver: WavArchiver, + receiver: Receiver, + queued_bytes: Arc, + status: WavArchiveStatus, +) { while let Ok(message) = receiver.recv() { match message { - WavArchiveMessage::Pcm(pcm_bytes) => archiver.append(&pcm_bytes), + WavArchiveMessage::Pcm(pcm_bytes) => { + queued_bytes.fetch_sub(pcm_bytes.len(), Ordering::AcqRel); + if let Err(error) = archiver.append(&pcm_bytes) { + status.record_error(error); + } + } WavArchiveMessage::Finish => break, } } + if let Err(error) = archiver.finalize() { + status.record_error(error); + } } /// Capture handle. Dropping does not stop it — call `stop` explicitly. @@ -1830,6 +1990,7 @@ pub struct Recorder { stop_flag: Arc, join_handle: Mutex>>, archive_writer: Option>, + raw_archive_writer: Option>, state: Arc, } @@ -1968,6 +2129,9 @@ impl Recorder { if let Some(archive) = archive_writer.as_ref() { archive.finish(); } + if let Some(raw) = raw_writer.as_ref() { + raw.finish(); + } return Err(RecorderError::EngineFailed(format!( "spawn audio thread: {error}" ))); @@ -1982,6 +2146,9 @@ impl Recorder { if let Some(archive) = archive_writer.as_ref() { archive.finish(); } + if let Some(raw) = raw_writer.as_ref() { + raw.finish(); + } return Err(RecorderError::EngineFailed(format!( "audio thread vanished: {error}" ))); @@ -1992,6 +2159,9 @@ impl Recorder { if let Some(archive) = archive_writer.as_ref() { archive.finish(); } + if let Some(raw) = raw_writer.as_ref() { + raw.finish(); + } return Err(error); } @@ -2000,6 +2170,7 @@ impl Recorder { stop_flag, join_handle: Mutex::new(Some(join_handle)), archive_writer, + raw_archive_writer: raw_writer, state, }, runtime_error_rx, @@ -2007,6 +2178,10 @@ impl Recorder { )) } + pub(crate) fn archive_status(&self) -> Option { + self.archive_writer.as_ref().map(|writer| writer.status()) + } + pub(crate) fn drain_pending_audio(&self) { let sender = self.state.processor_sender.lock().clone(); let Some(sender) = sender else { @@ -2024,12 +2199,19 @@ impl Recorder { pub fn stop(self) { let operation = DebugOperation::new(DebugProbe::P5); let _scope = operation.scope(); - operation.record(DebugEvent::Entered, DebugOutcome::Observed, - DebugFacts { kind: DebugKind::Recorder, ..DebugFacts::default() }); + operation.record( + DebugEvent::Entered, + DebugOutcome::Observed, + DebugFacts { + kind: DebugKind::Recorder, + ..DebugFacts::default() + }, + ); let Recorder { stop_flag, join_handle, archive_writer, + raw_archive_writer, state, } = self; operation.mark(DebugEvent::ProcessorLock); @@ -2041,8 +2223,15 @@ impl Recorder { if let Some(handle) = join_handle.lock().take() { operation.mark(DebugEvent::JoinEntered); let result = handle.join(); - operation.record(DebugEvent::JoinReturned, - if result.is_ok() { DebugOutcome::Ok } else { DebugOutcome::Error }, DebugFacts::default()); + operation.record( + DebugEvent::JoinReturned, + if result.is_ok() { + DebugOutcome::Ok + } else { + DebugOutcome::Error + }, + DebugFacts::default(), + ); if let Err(err) = result { log::warn!("recorder 线程 join 失败: {:?}", err); } @@ -2051,7 +2240,14 @@ impl Recorder { operation.mark(DebugEvent::ArchiveFinish); archive.finish_observed(Some(operation)); } - operation.record(DebugEvent::Returned, DebugOutcome::Returned, DebugFacts::default()); + if let Some(raw_archive) = raw_archive_writer { + raw_archive.finish(); + } + operation.record( + DebugEvent::Returned, + DebugOutcome::Returned, + DebugFacts::default(), + ); } } @@ -2132,7 +2328,7 @@ impl StagedRecorder { }); let raw_tap = Some(Arc::new(RawTap::new( archive_writer.clone(), - raw_writer, + raw_writer.clone(), archives.write_processed, ))); let archive_active = archive_writer.is_some(); @@ -2143,9 +2339,17 @@ impl StagedRecorder { if let Some(archive) = archive_writer { archive.finish(); } + if let Some(raw) = raw_writer { + raw.finish(); + } if let Some(path) = archive_path { let _ = std::fs::remove_file(path); } + if archives.processed.is_some() { + if let Some(raw_path) = archives.raw.as_ref() { + let _ = std::fs::remove_file(raw_path); + } + } if let Some(recorder) = self.recorder.take() { recorder.stop(); } @@ -2155,6 +2359,7 @@ impl StagedRecorder { RecorderError::EngineFailed("provisional recorder was already stopped".into()) })?; recorder.archive_writer = archive_writer; + recorder.raw_archive_writer = raw_writer; let runtime_errors = self.runtime_errors.take().ok_or_else(|| { RecorderError::EngineFailed( "provisional recorder runtime channel was unavailable".into(), @@ -2493,7 +2698,13 @@ fn run_audio_thread( "[recorder] watchdog: 录音回调已停止 {} 秒,触发错误恢复", elapsed.as_secs() ); - state_for_watchdog.diagnostics.event("P4", "[\"H4\"]", "watchdog_fault", "callback_silent", "{}"); + state_for_watchdog.diagnostics.event( + "P4", + "[\"H4\"]", + "watchdog_fault", + "callback_silent", + "{}", + ); let _ = runtime_error_tx_for_watchdog.send(RecorderError::EngineFailed( format!("录音回调静默停止 {} 秒", elapsed.as_secs()), @@ -2509,7 +2720,13 @@ fn run_audio_thread( "[recorder] watchdog: {} 秒内未收到首次回调,触发错误恢复", elapsed.as_secs() ); - state_for_watchdog.diagnostics.event("P4", "[\"H4\"]", "watchdog_fault", "first_callback_timeout", "{}"); + state_for_watchdog.diagnostics.event( + "P4", + "[\"H4\"]", + "watchdog_fault", + "first_callback_timeout", + "{}", + ); let _ = runtime_error_tx_for_watchdog.send(RecorderError::EngineFailed( format!("录音启动后 {} 秒内未收到回调", elapsed.as_secs()), @@ -3528,12 +3745,14 @@ fn update_peak(slot: &AtomicUsize, current: f32) { /// Simple append-only writer for 16 kHz / mono / 16-bit PCM WAV. /// Writes a placeholder header with data_size=0 at construction, appends i16 PCM bytes on each -/// append, and on Drop seeks back to 0 to backfill the RIFF / data length fields — no external -/// finalize call site required. +/// append, checkpoints header sizes periodically, and finalizes/flushes RIFF and data lengths on +/// finalize or Drop while latching the first write/size error. struct WavArchiver { file: std::fs::File, - bytes_written: u32, - last_checkpoint_bytes: u32, + data_bytes: u64, + last_checkpoint_bytes: u64, + failed: Option, + finalized: bool, } impl WavArchiver { @@ -3546,54 +3765,101 @@ impl WavArchiver { file.write_all(&build_wav_header(0))?; Ok(Self { file, - bytes_written: 0, + data_bytes: 0, last_checkpoint_bytes: 0, + failed: None, + finalized: false, }) } - fn append(&mut self, pcm_bytes: &[u8]) { + fn append(&mut self, pcm_bytes: &[u8]) -> Result<(), String> { + if let Some(error) = &self.failed { + return Err(error.clone()); + } use std::io::Write; - if self.file.write_all(pcm_bytes).is_ok() { - self.bytes_written = self - .bytes_written - .saturating_add(pcm_bytes.len().min(u32::MAX as usize) as u32); - // Keep the header usable during a long meeting. Drop still does - // the final sync, but a process kill should not leave a WAV with - // data_size=0 for the entire recording. - const CHECKPOINT_INTERVAL_BYTES: u32 = 160_000; - if self - .bytes_written - .saturating_sub(self.last_checkpoint_bytes) - >= CHECKPOINT_INTERVAL_BYTES - { - self.checkpoint_header(); - } + if let Err(error) = self.file.write_all(pcm_bytes) { + // Roll back any partial frame write so the WAV ends cleanly on the last good boundary. + let _ = self.file.set_len(44 + self.data_bytes); + let _ = self.file.sync_data(); + let message = format!("wav archive write failed: {error}"); + self.failed = Some(message.clone()); + return Err(message); + } + self.data_bytes = self.data_bytes.saturating_add(pcm_bytes.len() as u64); + // Keep the header usable during a long meeting. finalize()/Drop still does + // the final sync, but a process kill should not leave data_size=0. + const CHECKPOINT_INTERVAL_BYTES: u64 = 160_000; + if self.data_bytes.saturating_sub(self.last_checkpoint_bytes) >= CHECKPOINT_INTERVAL_BYTES { + self.checkpoint_header()?; } + Ok(()) } - fn checkpoint_header(&mut self) { + fn checkpoint_header(&mut self) -> Result<(), String> { + // Repairing retained PCM is independent of whether capture already failed. + // Append remains disabled by the latched error, even after this succeeds. + let Some(header) = checked_wav_header(self.data_bytes) else { + let message = "wav archive exceeds 4 GiB RIFF limit".to_string(); + return Err(self.failed.get_or_insert(message).clone()); + }; use std::io::{Seek, SeekFrom, Write}; - if self.file.seek(SeekFrom::Start(0)).is_ok() { - if self - .file - .write_all(&build_wav_header(self.bytes_written)) - .is_ok() - { - let _ = self.file.seek(SeekFrom::End(0)); - let _ = self.file.sync_data(); - self.last_checkpoint_bytes = self.bytes_written; + let result = (|| -> std::io::Result<()> { + self.file.seek(SeekFrom::Start(0))?; + self.file.write_all(&header)?; + self.file.seek(SeekFrom::Start(44 + self.data_bytes))?; + self.file.sync_data()?; + Ok(()) + })(); + match result { + Ok(()) => { + self.last_checkpoint_bytes = self.data_bytes; + Ok(()) + } + Err(error) => { + let message = format!("wav archive header update failed: {error}"); + Err(self.failed.get_or_insert(message).clone()) } } } + + fn finalize(&mut self) -> Result<(), String> { + if self.finalized { + return self.failed.clone().map_or(Ok(()), Err); + } + self.finalized = true; + if self.failed.is_some() + && self.file.metadata().map(|metadata| metadata.len()).ok() + != Some(44 + self.data_bytes) + { + // Retry a failed partial-append rollback before declaring retained sizes. + if let Err(error) = self.file.set_len(44 + self.data_bytes) { + log::warn!("[recordings] failed to truncate retained PCM: {error}"); + return self.failed.clone().map_or(Ok(()), Err); + } + } + let _ = self.checkpoint_header(); + if let Err(error) = self.file.sync_all() { + self.failed + .get_or_insert_with(|| format!("wav archive sync failed: {error}")); + } + self.failed.clone().map_or(Ok(()), Err) + } } impl Drop for WavArchiver { fn drop(&mut self) { - self.checkpoint_header(); - let _ = self.file.sync_all(); + if !self.finalized { + let _ = self.finalize(); + } } } +fn checked_wav_header(data_bytes: u64) -> Option<[u8; 44]> { + let data_size = u32::try_from(data_bytes).ok()?; + let _total_size = data_size.checked_add(36)?; + Some(build_wav_header(data_size)) +} + fn build_wav_header(data_size: u32) -> [u8; 44] { // Standard 44-byte RIFF/WAVE PCM header, hardcoded for 16 kHz / mono / 16-bit. let total_size = data_size.saturating_add(36); @@ -3634,14 +3900,21 @@ mod tests { let (sender, receiver) = channel(); let start = Arc::new(std::sync::Barrier::new(2)); let worker_start = start.clone(); + let queued_bytes = Arc::new(AtomicUsize::new(0)); + let worker_queued = Arc::clone(&queued_bytes); + let status = WavArchiveStatus::default(); + let worker_status = status.clone(); let join_handle = thread::spawn(move || { worker_start.wait(); - run_wav_archive_writer(archiver, receiver); + run_wav_archive_writer(archiver, receiver, worker_queued, worker_status); }); let writer = WavArchiveWriter { sender, join_handle: Mutex::new(Some(join_handle)), queue_full_warned: AtomicBool::new(false), + queued_bytes, + max_queue_bytes: MAX_ARCHIVE_QUEUE_BYTES, + status, }; let mut expected = Vec::new(); for index in 0..1024_u16 { @@ -3769,14 +4042,26 @@ mod tests { let writer = Arc::new(WavArchiveWriter::create(&path).unwrap()); let consumer = Arc::new(RecordingConsumer::default()); let (worker, sender) = AudioProcessingWorker::start_with_targets( - Default::default(), consumer.clone(), Arc::new(|_| {}), Some(writer.clone()), None, - Arc::new(StreamState::new()), false, None, None, - ).unwrap(); + Default::default(), + consumer.clone(), + Arc::new(|_| {}), + Some(writer.clone()), + None, + Arc::new(StreamState::new()), + false, + None, + None, + ) + .unwrap(); for _ in 0..2 { - sender.send(AudioProcessingMessage::Frame(RawAudioFrame { - captured_at: std::time::Instant::now(), samples: vec![0.3; 1001], - channels: 1, input_sample_rate: 44_100, - })).unwrap(); + sender + .send(AudioProcessingMessage::Frame(RawAudioFrame { + captured_at: std::time::Instant::now(), + samples: vec![0.3; 1001], + channels: 1, + input_sample_rate: 44_100, + })) + .unwrap(); let (done, ack) = channel(); sender.send(AudioProcessingMessage::Flush(done)).unwrap(); ack.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); @@ -3928,41 +4213,69 @@ mod tests { #[test] fn playback_reference_uses_capture_times_after_an_early_start() { - let epoch=std::time::Instant::now(); - let state=Arc::new(StreamState::new()); - let reference=Arc::new(openless_core::ReferenceAudioBuffer::new(16_000)); - reference.push_interleaved_at(&[0.9;160],1,epoch); - reference.push_interleaved_at(&[0.0;1280],1,epoch+std::time::Duration::from_millis(10)); - *state.reference.lock()=Some(reference); - let consumer=Arc::new(RecordingConsumer::default()); - let (worker,sender)=AudioProcessingWorker::start( - openless_core::AudioProcessingConfig {echo_cancellation_enabled:true,..Default::default()}, - Arc::clone(&consumer) as Arc,Arc::new(|_|{}),None,state, - ).unwrap(); + let epoch = std::time::Instant::now(); + let state = Arc::new(StreamState::new()); + let reference = Arc::new(openless_core::ReferenceAudioBuffer::new(16_000)); + reference.push_interleaved_at(&[0.9; 160], 1, epoch); + reference.push_interleaved_at( + &[0.0; 1280], + 1, + epoch + std::time::Duration::from_millis(10), + ); + *state.reference.lock() = Some(reference); + let consumer = Arc::new(RecordingConsumer::default()); + let (worker, sender) = AudioProcessingWorker::start( + openless_core::AudioProcessingConfig { + echo_cancellation_enabled: true, + ..Default::default() + }, + Arc::clone(&consumer) as Arc, + Arc::new(|_| {}), + None, + state, + ) + .unwrap(); for index in 1..=8 { - sender.send(AudioProcessingMessage::Frame(RawAudioFrame { - captured_at:epoch+std::time::Duration::from_millis(index*10),samples:vec![0.25;160],channels:1,input_sample_rate:16_000, - })).unwrap(); + sender + .send(AudioProcessingMessage::Frame(RawAudioFrame { + captured_at: epoch + std::time::Duration::from_millis(index * 10), + samples: vec![0.25; 160], + channels: 1, + input_sample_rate: 16_000, + })) + .unwrap(); } - drop(sender);worker.finish(); - let chunks=consumer.chunks.lock().unwrap();assert_eq!(chunks.len(),8); - assert!(chunks.iter().all(|chunk|decode_i16_le(chunk)==vec![8191;160])); + drop(sender); + worker.finish(); + let chunks = consumer.chunks.lock().unwrap(); + assert_eq!(chunks.len(), 8); + assert!(chunks + .iter() + .all(|chunk| decode_i16_le(chunk) == vec![8191; 160])); } #[test] fn diagnostics_and_microphone_errors_stay_capture_scoped() { - let first=StreamState::new();let second=StreamState::new(); - assert_ne!(first.diagnostics.run_id,second.diagnostics.run_id); - let (sender,receiver)=channel(); - first.accepting_audio.store(false,Ordering::Release); - handle_microphone_stream_error(&first,cpal::StreamError::DeviceNotAvailable,&sender); - assert!(receiver.try_recv().is_err());assert_eq!(first.diagnostics.microphone.errors.load(Ordering::Relaxed),0); - first.accepting_audio.store(true,Ordering::Release); - handle_microphone_stream_error(&first,cpal::StreamError::DeviceNotAvailable,&sender); - assert!(matches!(receiver.try_recv(),Ok(RecorderError::EngineFailed(_)))); - assert_eq!(first.diagnostics.microphone.record_callback(),(1,true)); - assert_eq!(first.diagnostics.reference.record_callback(),(1,false)); - assert_eq!(second.diagnostics.microphone.record_callback(),(1,false)); + let first = StreamState::new(); + let second = StreamState::new(); + assert_ne!(first.diagnostics.run_id, second.diagnostics.run_id); + let (sender, receiver) = channel(); + first.accepting_audio.store(false, Ordering::Release); + handle_microphone_stream_error(&first, cpal::StreamError::DeviceNotAvailable, &sender); + assert!(receiver.try_recv().is_err()); + assert_eq!( + first.diagnostics.microphone.errors.load(Ordering::Relaxed), + 0 + ); + first.accepting_audio.store(true, Ordering::Release); + handle_microphone_stream_error(&first, cpal::StreamError::DeviceNotAvailable, &sender); + assert!(matches!( + receiver.try_recv(), + Ok(RecorderError::EngineFailed(_)) + )); + assert_eq!(first.diagnostics.microphone.record_callback(), (1, true)); + assert_eq!(first.diagnostics.reference.record_callback(), (1, false)); + assert_eq!(second.diagnostics.microphone.record_callback(), (1, false)); } #[test] @@ -4189,7 +4502,9 @@ mod tests { assert!(hub.recorder.lock().is_none()); hub.set_capture_paused(0, false); assert!(hub.standby_policy.lock().1); - assert!(hub.arm(99, None, openless_core::AudioProcessingConfig::default()).is_err()); + assert!(hub + .arm(99, None, openless_core::AudioProcessingConfig::default()) + .is_err()); } #[test] @@ -4198,14 +4513,18 @@ mod tests { let key = voice_capture_key(9); let consumer = Arc::new(RecordingConsumer::default()); let body = [0x00, 0x40].repeat(160); - hub.sink.arm_with_limit(key, false, STAGED_CAPTURE_MAX_BYTES).unwrap(); + hub.sink + .arm_with_limit(key, false, STAGED_CAPTURE_MAX_BYTES) + .unwrap(); hub.sink.consume_pcm_chunk(&body); hub.enabled.store(true, Ordering::Release); hub.set_capture_paused(1, true); hub.configure(true, None, openless_core::AudioProcessingConfig::default()); assert!(hub.sink.staging_claim_ids().contains(&key)); assert!(!hub.runtime_fallback_claims.lock().contains(&key)); - hub.sink.promote(key, consumer.clone(), Arc::new(|_| {}), None, None).unwrap(); + hub.sink + .promote(key, consumer.clone(), Arc::new(|_| {}), None, None) + .unwrap(); assert_eq!(consumer.chunks.lock().unwrap().concat(), body); hub.release_claim(key); assert!(!hub.enabled.load(Ordering::Acquire)); @@ -4216,8 +4535,12 @@ mod tests { fn linked_pause_preserves_promoted_recording_until_its_claim_releases() { let hub = WarmCaptureHub::new(); let consumer = Arc::new(RecordingConsumer::default()); - hub.sink.arm_with_limit(7, false, STAGED_CAPTURE_MAX_BYTES).unwrap(); - hub.sink.promote(7, consumer, Arc::new(|_| {}), None, None).unwrap(); + hub.sink + .arm_with_limit(7, false, STAGED_CAPTURE_MAX_BYTES) + .unwrap(); + hub.sink + .promote(7, consumer, Arc::new(|_| {}), None, None) + .unwrap(); hub.enabled.store(true, Ordering::Release); hub.set_capture_paused(1, true); assert!(hub.sink.has_promoted_claims()); @@ -4230,7 +4553,10 @@ mod tests { #[test] fn saved_default_microphone_skips_the_full_input_list() { - assert!(default_input_matches_preference(None, Some("MacBook Air麦克风"))); + assert!(default_input_matches_preference( + None, + Some("MacBook Air麦克风") + )); assert!(default_input_matches_preference( Some(" MacBook Air麦克风 "), Some("MacBook Air麦克风") @@ -4799,4 +5125,132 @@ mod tests { assert!(hub.pending_configuration.lock().is_none()); } } + + #[test] + fn wav_archive_queue_overflow_never_blocks_and_latches_status() { + let path = archive_test_path("openless-archive-overflow"); + let archiver = WavArchiver::create(&path).unwrap(); + let (sender, receiver) = channel(); + let start = Arc::new(std::sync::Barrier::new(2)); + let worker_start = Arc::clone(&start); + let queued_bytes = Arc::new(AtomicUsize::new(0)); + let worker_queued = Arc::clone(&queued_bytes); + let status = WavArchiveStatus::default(); + let worker_status = status.clone(); + let join_handle = thread::spawn(move || { + worker_start.wait(); + run_wav_archive_writer(archiver, receiver, worker_queued, worker_status); + }); + let writer = WavArchiveWriter { + sender, + join_handle: Mutex::new(Some(join_handle)), + queue_full_warned: AtomicBool::new(false), + queued_bytes, + max_queue_bytes: 1024, + status: status.clone(), + }; + + let first = [1u8, 2u8].repeat(512); + writer.append(&first); + assert!(status.is_ok()); + + // Exceeding the bounded queue drops further archive chunks without blocking and latches an error. + writer.append(&[3, 4]); + assert!(!status.is_ok()); + assert!(status.error().is_some()); + writer.append(&[5, 6]); + + start.wait(); + writer.finish(); + let wav = std::fs::read(&path).unwrap(); + assert_eq!(&wav[44..], first.as_slice()); + assert_eq!(u32::from_le_bytes(wav[40..44].try_into().unwrap()), 1024); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn wav_archiver_write_failure_truncates_partial_frame_and_latches_error() { + let path = archive_test_path("openless-archiver-fail"); + { + let mut archiver = WavArchiver::create(&path).unwrap(); + archiver.append(&[1, 2, 3, 4]).unwrap(); + // Swap in a read-only handle so the next write fails cleanly across platforms. + archiver.file = std::fs::File::open(&path).unwrap(); + let err = archiver.append(&[5, 6, 7, 8]).unwrap_err(); + assert!(!err.is_empty()); + assert_eq!(archiver.append(&[9, 10]).unwrap_err(), err); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 48); + } + assert!(checked_wav_header(u64::from(u32::MAX) - 35).is_none()); + assert!(checked_wav_header(u64::from(u32::MAX) - 36).is_some()); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn wav_archiver_failure_finalizes_retained_prefix_without_clearing_error() { + use std::io::{Seek, SeekFrom, Write}; + for explicit_finalize in [false, true] { + let path = archive_test_path("openless-archive-retained-prefix"); + let pcm = [1u8, 2].repeat(1_600); + let mut archiver = WavArchiver::create(&path).unwrap(); + archiver.append(&pcm).unwrap(); + let before = std::fs::read(&path).unwrap(); + assert_eq!(&before[40..44], &0u32.to_le_bytes()); + archiver.file = std::fs::File::open(&path).unwrap(); + let original_error = archiver.append(&[3, 4]).unwrap_err(); + archiver.file = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + // Model a partial tail whose immediate rollback could not complete. + archiver.file.seek(SeekFrom::End(0)).unwrap(); + archiver.file.write_all(&[0x7f]).unwrap(); + assert_eq!(archiver.append(&[5, 6]).unwrap_err(), original_error); + if explicit_finalize { + assert_eq!(archiver.finalize().unwrap_err(), original_error); + assert_eq!(archiver.finalize().unwrap_err(), original_error); + assert_eq!(archiver.failed.as_deref(), Some(original_error.as_str())); + } + drop(archiver); + let wav = std::fs::read(&path).unwrap(); + assert_eq!( + openless_core::audio::decode_dictation_wav(&wav).unwrap(), + pcm + ); + assert_eq!(wav.len(), 44 + pcm.len()); + std::fs::remove_file(path).unwrap(); + } + } + + #[test] + fn wav_archiver_header_repair_keeps_the_first_failure() { + let path = archive_test_path("openless-archive-header-repair"); + let mut archiver = WavArchiver::create(&path).unwrap(); + archiver.append(&[1, 2, 3, 4]).unwrap(); + archiver.file = std::fs::File::open(&path).unwrap(); + let original_error = archiver.append(&[5, 6]).unwrap_err(); + assert_eq!(archiver.checkpoint_header().unwrap_err(), original_error); + archiver.file = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + assert_eq!(archiver.finalize().unwrap_err(), original_error); + drop(archiver); + let wav = std::fs::read(&path).unwrap(); + assert_eq!( + openless_core::audio::decode_dictation_wav(&wav).unwrap(), + [1, 2, 3, 4] + ); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn wav_archive_writer_drop_finishes_and_backfills_wav_header() { + let path = archive_test_path("openless-archive-drop"); + let status = { + let writer = WavArchiveWriter::create(&path).unwrap(); + let status = writer.status(); + writer.append(&[11, 22, 33, 44, 55, 66]); + status + }; + assert!(status.is_ok()); + let wav = std::fs::read(&path).unwrap(); + assert_eq!(&wav[44..], &[11, 22, 33, 44, 55, 66]); + assert_eq!(u32::from_le_bytes(wav[40..44].try_into().unwrap()), 6); + std::fs::remove_file(path).unwrap(); + } } diff --git a/openless-all/app/src-tauri/src/selection.rs b/openless-all/app/src-tauri/src/selection.rs index bc8886c93..461cf3ee7 100644 --- a/openless-all/app/src-tauri/src/selection.rs +++ b/openless-all/app/src-tauri/src/selection.rs @@ -1360,7 +1360,6 @@ mod macos_ax { #[link(name = "ApplicationServices", kind = "framework")] extern "C" { - fn CFEqual(a: CFTypeRef, b: CFTypeRef) -> u8; fn AXUIElementCreateSystemWide() -> AxUiElementRef; fn AXUIElementCreateApplication(pid: i32) -> AxUiElementRef; fn AXUIElementSetMessagingTimeout(element: AxUiElementRef, seconds: f32) -> AxError; diff --git a/openless-all/app/src/api/dictation.ts b/openless-all/app/src/api/dictation.ts index 771e52498..b1ce2c4c9 100644 --- a/openless-all/app/src/api/dictation.ts +++ b/openless-all/app/src/api/dictation.ts @@ -21,11 +21,17 @@ export function reportMainCaptionTrace(sessionId: string, sequence: number, stag return invokeOrPreview('report_main_caption_trace', { sessionId, sequence, stage }, () => {}); } +export interface CapsuleProcessingJob { + sessionId: string; + translationActive?: boolean; +} + export function getCapsuleAuxiliarySnapshot() { return invokeOrPreview<{ suggestions: PendingCorrection[]; fallback: InsertFallbackCardPayload | null; - }>('get_capsule_auxiliary_snapshot', undefined, () => ({ suggestions: [], fallback: null })); + processing: CapsuleProcessingJob[]; + }>('get_capsule_auxiliary_snapshot', undefined, () => ({ suggestions: [], fallback: null, processing: [] })); } export function createCapsuleSubscriptions() { @@ -35,6 +41,8 @@ export function createCapsuleSubscriptions() { dispose: events.dispose, state: (onPayload: (payload: CapsulePayload) => void) => events.listen('capsule:state', onPayload, 'window'), + jobs: (onPayload: (payload: CapsuleProcessingJob[]) => void) => + events.listen('dictation:jobs', onPayload, 'app'), transcript: (onPayload: (payload: BackendEvent) => void) => events.listen('backend:event', onPayload, 'app'), preferences: (onPayload: (payload: UserPreferences) => void) => diff --git a/openless-all/app/src/app/shell/navigation.ts b/openless-all/app/src/app/shell/navigation.ts index dcc74c614..48cf1ad3b 100644 --- a/openless-all/app/src/app/shell/navigation.ts +++ b/openless-all/app/src/app/shell/navigation.ts @@ -1,5 +1,4 @@ import { useEffect, useState } from 'react'; -import { ASK_ANYTHING_AVAILABLE } from '../../lib/appVersion'; import { getShortcutPlatform } from '../../runtime/environment'; export type AppTab = @@ -20,7 +19,7 @@ export function isTabAvailable(tab: AppTab): boolean { const platform = getShortcutPlatform(); return platform.isMac || platform.isWindows; } - return tab !== 'selectionAsk' || ASK_ANYTHING_AVAILABLE; + return true; } export interface AppState { diff --git a/openless-all/app/src/features/capsule/Capsule.tsx b/openless-all/app/src/features/capsule/Capsule.tsx index b62c519b1..30045aa6a 100644 --- a/openless-all/app/src/features/capsule/Capsule.tsx +++ b/openless-all/app/src/features/capsule/Capsule.tsx @@ -187,7 +187,6 @@ function SelectionPolishNotice({ state, message }: SelectionPolishNoticeProps) { interface ClassicCapsuleProps { sessionId?: string; os: OS; - sessionId?: string; state: CapsuleState; level: number; insertedChars: number; @@ -210,7 +209,6 @@ interface ClassicCapsuleProps { function ClassicCapsule({ sessionId, os, - sessionId, state, level, insertedChars, @@ -234,7 +232,7 @@ function ClassicCapsule({ const reduced = useReducedMotion(); // The top floating translation badge reflects only the current foreground session, // never background processing jobs (which show their own status on the rear satellite). - const translating = translation && isActiveCapsuleState(state); + const translating = translation && (state === 'recording' || state === 'transcribing' || state === 'polishing'); const liveText = transcript?.trim() ?? ''; const classicGeometry = getClassicCapsuleGeometry( os, @@ -987,7 +985,6 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { } {item.id === 'webSearch' && } {item.id === 'intentRouting' && } - {item.id === 'polishStrategy' && } {item.id === 'startupDiagnostics' && } {item.id === 'customSyncServer' && page === item.id && } {item.id === 'debug' && } diff --git a/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch b/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch index bad725d5f..ee625dd83 100644 --- a/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch +++ b/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch @@ -1,12 +1,12 @@ diff --git a/crates/openless-core/src/api.rs b/crates/openless-core/src/api.rs -index 14d0521..dc54279 100644 --- a/crates/openless-core/src/api.rs +++ b/crates/openless-core/src/api.rs -@@ -5754,7 +5754,13 @@ impl OpenLessBackend { +@@ -6539,8 +6539,13 @@ }; // Keep finalization outside this critical section. A failed save changes neither // the active target nor the remembered choice, and no other preference is overwritten. -- self.preferences.update(|preferences| preferences.translation_target_language = target)?; +- self.preferences +- .update(|preferences| preferences.translation_target_language = target)?; + self.preferences.update(|preferences| { + if !preferences.translation_target_languages.contains(&target) { + preferences.translation_target_languages.push(target.clone()); @@ -17,7 +17,7 @@ index 14d0521..dc54279 100644 state.dictation_context = Some(Arc::new(updated)); // The common stop boundary must also send the changed context to a streaming engine. state.dictation_translation_requested = Some(true); -@@ -6590,6 +6596,146 @@ impl OpenLessBackend { +@@ -7414,6 +7419,146 @@ self.preferences.get() } @@ -164,7 +164,7 @@ index 14d0521..dc54279 100644 /// Consumes the "first launch of this major version" splash PV marker: /// returns false when the config's `splash_seen_version` matches the /// given current major (no replay); on mismatch it writes back the major -@@ -6717,6 +6863,7 @@ impl OpenLessBackend { +@@ -7541,6 +7686,7 @@ }; crate::sync_dictation_hotkey_legacy_fields(&mut previous); crate::sync_dictation_hotkey_legacy_fields(&mut preferences); @@ -172,7 +172,7 @@ index 14d0521..dc54279 100644 // The splash marker may only advance via take_splash_playback: when a // whole-document submit (old frontend, or a request that hasn't read // the marker back) omits the field, serde's default would write the -@@ -7701,10 +7848,42 @@ impl OpenLessBackend { +@@ -8745,10 +8891,42 @@ self.start_reserved_dictation(reservation, options).await } @@ -215,18 +215,11 @@ index 14d0521..dc54279 100644 ) -> Result { let DictationReservation { session_id, -@@ -7721,14 +7900,25 @@ impl OpenLessBackend { +@@ -8765,7 +8943,17 @@ return Err(error); } } - let context = match self -- .capture_dictation_context_with_host( -- &options, -- DictationContextPurpose::Dictation, -- host_context.as_ref(), -- ) -- .await -- { + let captured = match raw_provider { + Some(provider) => async { + let context = self.capture_local_raw_context(&options, provider)?; @@ -237,19 +230,22 @@ index 14d0521..dc54279 100644 + Ok(context) + }.await, + None => { -+ self.capture_dictation_context_with_host( -+ &options, -+ DictationContextPurpose::Dictation, -+ host_context.as_ref(), -+ ) -+ .await ++ self + .capture_dictation_context_with_host( + &options, + DictationContextPurpose::Dictation, +@@ -8776,7 +8964,9 @@ + }, + ) + .await +- { + } + }; + let context = match captured { Ok(context) => Arc::new(context), Err(error) => { self.schedule_pending_audio_capture_discard(pending_capture.take()); -@@ -9189,6 +9379,36 @@ impl OpenLessBackend { +@@ -10418,6 +10608,36 @@ } } @@ -286,7 +282,8 @@ index 14d0521..dc54279 100644 async fn capture_dictation_context( &self, options: &DictationStartOptions, -@@ -9210,5 +9430,10 @@ impl OpenLessBackend { +@@ -10480,6 +10700,11 @@ + .style_packs .get_for_dictation(assigned_ids.iter().map(String::as_str), active_id)?; let mut captured_options = options.clone(); + if let Some(target) = &options.translation_target_language { @@ -297,11 +294,10 @@ index 14d0521..dc54279 100644 if !preferences.cursor_context_enabled { // This switch controls document text, including text supplied by // callers. Front-application metadata is still needed for history, -@@ -12208,6 +12433,285 @@ mod tests { - let _ = std::fs::remove_dir_all(data_dir); +@@ -14018,6 +14243,285 @@ } -+ #[test] + #[test] + fn translation_targets_business_apis_persist_order_selection_and_events() { + let (backend, _) = backend(); + let mut events = backend.subscribe(); @@ -580,24 +576,25 @@ index 14d0521..dc54279 100644 + backend.shutdown().await.unwrap(); + } + - #[test] ++ #[test] fn focused_microphone_selection_persists_and_publishes_once() { let (backend, _) = backend(); -@@ -13893,6 +14397,10 @@ mod tests { - let selected = backend.select_dictation_translation_target(session, "ja".into()).unwrap(); - assert_eq!(selected.target_language, "日本語"); - assert_eq!(backend.get_preferences().translation_target_language, "日本語"); -+ assert_eq!( -+ backend.get_preferences().translation_target_languages, -+ vec!["English", "日本語"] -+ ); - assert_eq!(backend.get_preferences().microphone_device_name, "next microphone"); - backend.stop_dictation().await.unwrap(); - let contexts = engine.contexts(); -@@ -13903,6 +14411,35 @@ mod tests { - backend.shutdown().await.unwrap(); - } - + let mut events = backend.subscribe(); +@@ -15882,6 +16386,7 @@ + backend.get_preferences().translation_target_language, + "日本語" + ); ++ assert_eq!(backend.get_preferences().translation_target_languages, vec!["English", "日本語"]); + assert_eq!( + backend.get_preferences().microphone_device_name, + "next microphone" +@@ -15895,6 +16400,35 @@ + Some("captured microphone") + ); + assert!(last.polish.translation_active); ++ backend.shutdown().await.unwrap(); ++ } ++ + #[tokio::test] + async fn translation_picker_remembers_target_after_configured_choices_are_cleared() { + let data_dir = TestDataDir::new("translation-picker-cleared-choices"); @@ -624,17 +621,13 @@ index 14d0521..dc54279 100644 + assert_eq!(saved.translation_target_languages, vec!["日本語"]); + assert_eq!(backend.get_preferences().translation_target_languages, vec!["日本語"]); + backend.cancel_dictation(Some(session)).await.unwrap(); -+ backend.shutdown().await.unwrap(); -+ } -+ - #[tokio::test] - async fn translation_picker_save_failure_keeps_active_and_saved_targets() { - let data_dir = TestDataDir::new("translation-picker-save-failure"); + backend.shutdown().await.unwrap(); + } + diff --git a/crates/openless-core/src/auxiliary.rs b/crates/openless-core/src/auxiliary.rs -index 75c9c3c..55a7de2 100644 --- a/crates/openless-core/src/auxiliary.rs +++ b/crates/openless-core/src/auxiliary.rs -@@ -64,7 +64,106 @@ impl RetranscriptionFailure { +@@ -64,7 +64,106 @@ } } @@ -741,7 +734,7 @@ index 75c9c3c..55a7de2 100644 fn repolish( &self, request: RepolishRequest, -@@ -212,6 +311,62 @@ impl AuxiliaryService { +@@ -227,6 +326,62 @@ } impl AuxiliaryApi for AuxiliaryService { @@ -804,11 +797,10 @@ index 75c9c3c..55a7de2 100644 fn repolish( &self, request: RepolishRequest, -@@ -474,6 +629,50 @@ mod tests { - } +@@ -633,6 +788,50 @@ } -+ #[tokio::test] + #[tokio::test] + async fn voice_compose_is_lazy_one_shot_and_cancellation_prevents_provider_start() { + let polisher = Arc::new(FixtureTextPolisher::successful("draft")); + let (service, path) = service( @@ -852,14 +844,14 @@ index 75c9c3c..55a7de2 100644 + let _ = std::fs::remove_file(path); + } + - #[tokio::test] ++ #[tokio::test] async fn untouched_builtin_raw_repolish_is_a_true_passthrough() { let (service, path) = service( + Arc::new(FixtureTextPolisher::successful("must not be used")), diff --git a/crates/openless-core/src/cloud_providers.rs b/crates/openless-core/src/cloud_providers.rs -index 05c6421..82d23c7 100644 --- a/crates/openless-core/src/cloud_providers.rs +++ b/crates/openless-core/src/cloud_providers.rs -@@ -1081,7 +1081,91 @@ fn usage_purpose(context: &DictationContext) -> crate::usage_ledger::ServicePurp +@@ -1217,7 +1217,91 @@ } } @@ -952,31 +944,30 @@ index 05c6421..82d23c7 100644 &self, session_id: SessionId, diff --git a/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs b/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs -index fef46cc..7aa8d22 100644 --- a/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs +++ b/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs -@@ -368,6 +368,13 @@ pub const PREFERENCE_FIELDS: &[PreferenceField] = &[ - shape: PreferenceShape::TextList, - reason: "portable_setting", - }, -+ PreferenceField { -+ rust_name: "translation_target_languages", -+ key: "translationTargetLanguages", +@@ -378,6 +378,13 @@ + PreferenceField { + rust_name: "working_languages", + key: "workingLanguages", + class: PreferenceClass::Portable, + shape: PreferenceShape::TextList, + reason: "portable_setting", + }, - PreferenceField { - rust_name: "translation_target_language", - key: "translationTargetLanguage", ++ PreferenceField { ++ rust_name: "translation_target_languages", ++ key: "translationTargetLanguages", + class: PreferenceClass::Portable, + shape: PreferenceShape::TextList, + reason: "portable_setting", diff --git a/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs b/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs -index 369ccf8..c28048f 100644 --- a/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs +++ b/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs -@@ -108,6 +108,22 @@ fn all_current_preference_fields_have_an_explicit_registration() { +@@ -107,6 +107,22 @@ + .and_then(|s| s.split_once(':')) .map(|(name, _)| name) }) - .collect(); ++ .collect(); + // Wire-presence metadata is not persisted or synced. Verify the explicit + // exception against actual serialization rather than exempting new fields. + let metadata = ["translation_target_languages_present", "translation_target_language_input"]; @@ -992,15 +983,13 @@ index 369ccf8..c28048f 100644 + let names: std::collections::BTreeSet<_> = names + .into_iter() + .filter(|name| !metadata.contains(name)) -+ .collect(); + .collect(); let registered: std::collections::BTreeSet<_> = registry::PREFERENCE_FIELDS .iter() - .map(|field| field.rust_name) diff --git a/crates/openless-core/src/dictation_context.rs b/crates/openless-core/src/dictation_context.rs -index e997f55..64fdd74 100644 --- a/crates/openless-core/src/dictation_context.rs +++ b/crates/openless-core/src/dictation_context.rs -@@ -43,6 +43,9 @@ pub enum DictationOutputTarget { +@@ -44,6 +44,9 @@ #[derive(Debug, Clone, PartialEq, Eq)] pub struct DictationStartOptions { pub translation_requested: bool, @@ -1010,7 +999,7 @@ index e997f55..64fdd74 100644 pub audio_source: DictationAudioSource, pub insert_text: bool, pub output_target: DictationOutputTarget, -@@ -55,6 +58,7 @@ impl Default for DictationStartOptions { +@@ -56,6 +59,7 @@ fn default() -> Self { Self { translation_requested: false, @@ -1018,7 +1007,7 @@ index e997f55..64fdd74 100644 audio_source: DictationAudioSource::Microphone, insert_text: true, output_target: DictationOutputTarget::ForegroundApp, -@@ -128,6 +132,8 @@ pub struct DictationPolishContext { +@@ -131,6 +135,8 @@ pub hotwords: Vec, pub working_languages: Vec, pub translation_target_language: String, @@ -1027,7 +1016,7 @@ index e997f55..64fdd74 100644 pub translation_active: bool, pub edit_plan_input: bool, /// Selected text uses its own prompt envelope, separate from voice transcripts. -@@ -259,8 +265,12 @@ impl DictationContext { +@@ -281,8 +287,12 @@ omni, } = providers; let hotwords = normalize_hotwords(hotwords); @@ -1042,7 +1031,7 @@ index e997f55..64fdd74 100644 let translation_active = translation_effective( options.translation_requested, &translation_target_language, -@@ -382,6 +392,7 @@ impl DictationContext { +@@ -409,6 +419,7 @@ hotwords, working_languages: preferences.working_languages.clone(), translation_target_language, @@ -1050,11 +1039,10 @@ index e997f55..64fdd74 100644 translation_active, edit_plan_input: false, selection_input: false, -@@ -852,6 +863,56 @@ mod tests { - assert_eq!(local_asr_fallback(&no_model, &cloud_asr(), true), None); +@@ -949,6 +960,56 @@ } -+ #[test] + #[test] + fn explicit_translation_target_preserves_working_language_suppression_and_raw_mode() { + let preferences = UserPreferences { + default_mode: PolishMode::Raw, @@ -1104,14 +1092,14 @@ index e997f55..64fdd74 100644 + assert!(legacy.polish.translation_active); + } + - #[test] ++ #[test] fn selection_polish_uses_the_selected_text_envelope() { let mut context = DictationContext::default(); + context.polish.selection_input = true; diff --git a/crates/openless-core/src/dictation_engine.rs b/crates/openless-core/src/dictation_engine.rs -index 3a95c61..3657e6f 100644 --- a/crates/openless-core/src/dictation_engine.rs +++ b/crates/openless-core/src/dictation_engine.rs -@@ -1016,7 +1016,14 @@ impl DictationEngine for PipelineDictationEngine { +@@ -1217,6 +1217,13 @@ let skips_polish_for_short_text = context.skips_polish_for_short_text(&transcript.text); // Optional polish may be skipped after fallback; an explicit translation is still required. let translation_active = context.polish.translation_active; @@ -1125,8 +1113,9 @@ index 3a95c61..3657e6f 100644 let uses_polisher = !strategy_skips && context.uses_llm_polisher() && !transcript.text.trim().is_empty() - && !skips_polish_for_short_text -@@ -1068,4 +1075,14 @@ impl DictationEngine for PipelineDictationEngine { +@@ -1288,6 +1295,16 @@ + ) + .await }; + let output = output.and_then(|value| { + if require_translation && value.text.trim().is_empty() { @@ -1141,11 +1130,10 @@ index 3a95c61..3657e6f 100644 let result = match output { Ok(text) => (text, false), // Offline after local recognition: the raw transcript is the -@@ -3817,6 +3834,37 @@ mod tests { - assert_eq!(result.polished_text, "raw text"); +@@ -4561,6 +4578,37 @@ } -+ #[tokio::test] + #[tokio::test] + async fn requested_translation_failure_never_becomes_successful_source_text() { + for output in [ + Err(BackendError::new( @@ -1176,14 +1164,14 @@ index 3a95c61..3657e6f 100644 + } + } + - #[tokio::test] ++ #[tokio::test] async fn custom_strategy_skip_bypasses_the_polisher() { let fixture = fixture_engine( + false, diff --git a/crates/openless-core/src/language_catalog.rs b/crates/openless-core/src/language_catalog.rs -index 6bcfcf2..b8ac2f0 100644 --- a/crates/openless-core/src/language_catalog.rs +++ b/crates/openless-core/src/language_catalog.rs -@@ -43,6 +43,14 @@ pub fn language_code(value: &str) -> Option { +@@ -43,6 +43,14 @@ language(value).map(|language| language.code.clone()) } @@ -1198,10 +1186,11 @@ index 6bcfcf2..b8ac2f0 100644 pub fn asr_language_code(native_name: &str) -> Option { language(native_name).map(|language| language.asr_code.clone()) } -@@ -55,6 +63,22 @@ pub fn apple_speech_locale(native_name: &str) -> Option { +@@ -54,6 +62,22 @@ + #[cfg(test)] mod tests { use super::*; - ++ + #[test] + fn translation_names_and_aliases_share_the_existing_catalog() { + let names = translation_language_names(); @@ -1217,15 +1206,13 @@ index 6bcfcf2..b8ac2f0 100644 + ); + assert_eq!(native_language_name("unknown"), None); + } -+ + #[test] fn extended_names_route_to_iso_and_apple_identifiers() { - for (name, code, locale) in [ diff --git a/crates/openless-core/src/ports.rs b/crates/openless-core/src/ports.rs -index 66dfa69..e5c8e58 100644 --- a/crates/openless-core/src/ports.rs +++ b/crates/openless-core/src/ports.rs -@@ -780,6 +780,15 @@ impl PreparedTranscription for DeferredDictationPre +@@ -837,6 +837,15 @@ } pub trait TextPolisher: Send + Sync { @@ -1242,10 +1229,9 @@ index 66dfa69..e5c8e58 100644 &self, session_id: SessionId, diff --git a/crates/openless-core/src/preference_patch.rs b/crates/openless-core/src/preference_patch.rs -index 411a4b5..07e176e 100644 --- a/crates/openless-core/src/preference_patch.rs +++ b/crates/openless-core/src/preference_patch.rs -@@ -18,7 +18,9 @@ pub fn patch_preferences( +@@ -23,7 +23,9 @@ if let Some(mode) = edits.get("/capsuleDisplayMode") { document["capsuleDisplayModeV2"] = mode.clone(); } @@ -1256,7 +1242,7 @@ index 411a4b5..07e176e 100644 } fn invalid(error: impl std::fmt::Display) -> BackendError { -@@ -52,6 +54,24 @@ pub fn update_fields( +@@ -57,6 +59,24 @@ #[cfg(test)] mod tests { use super::*; @@ -1282,10 +1268,9 @@ index 411a4b5..07e176e 100644 fn capsule_display_edits_establish_v2_without_opt_in_from_unrelated_edits() { let mut current = UserPreferences::default(); diff --git a/crates/openless-core/src/preferences.rs b/crates/openless-core/src/preferences.rs -index a76f075..38f3af8 100644 --- a/crates/openless-core/src/preferences.rs +++ b/crates/openless-core/src/preferences.rs -@@ -268,6 +268,7 @@ impl PreferencesStore { +@@ -268,6 +268,7 @@ } pub fn set(&self, mut preferences: UserPreferences) -> Result<(), BackendError> { @@ -1293,7 +1278,7 @@ index a76f075..38f3af8 100644 self.update(|current| { // The sync transaction owns this field; stale whole-document saves cannot reroute its token. preferences.sync_custom_server_origin = current.sync_custom_server_origin.clone(); -@@ -376,6 +377,7 @@ impl PreferencesStore { +@@ -376,6 +377,7 @@ &self, mut preferences: UserPreferences, ) -> Result<(), BackendError> { @@ -1302,10 +1287,9 @@ index a76f075..38f3af8 100644 preferences.preserve_style_preferences_from(current); preferences.sync_custom_server_origin = current.sync_custom_server_origin.clone(); diff --git a/crates/openless-core/src/provider_registry.rs b/crates/openless-core/src/provider_registry.rs -index 3f5c973..1112e0f 100644 --- a/crates/openless-core/src/provider_registry.rs +++ b/crates/openless-core/src/provider_registry.rs -@@ -136,6 +136,17 @@ impl TextPolisherRouter { +@@ -136,6 +136,17 @@ } impl TextPolisher for TextPolisherRouter { @@ -1324,13 +1308,14 @@ index 3f5c973..1112e0f 100644 &self, session_id: SessionId, diff --git a/crates/openless-core/src/settings.rs b/crates/openless-core/src/settings.rs -index 51600f8..ad33194 100644 --- a/crates/openless-core/src/settings.rs +++ b/crates/openless-core/src/settings.rs -@@ -19,6 +19,125 @@ pub(crate) fn ensure_testing_features_enabled( +@@ -17,6 +17,125 @@ + ) + .retryable(false)) } - } - ++} ++ +/// Preserve historical custom names on load, while canonicalizing catalog aliases. +pub(crate) fn canonical_translation_target(value: &str) -> String { + crate::language_catalog::native_language_name(value).unwrap_or_else(|| value.trim().to_string()) @@ -1448,12 +1433,10 @@ index 51600f8..ad33194 100644 + )); + } + Ok(target) -+} -+ + } + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] - #[serde(rename_all = "snake_case")] - pub enum SettingsCollisionPolicy { -@@ -292,3 +411,141 @@ mod tests { +@@ -292,3 +411,141 @@ assert!(!tsf_with_hidden_pref.windows_show_openless_in_keyboard_list); } } @@ -1596,10 +1579,9 @@ index 51600f8..ad33194 100644 + } +} diff --git a/crates/openless-core/src/shared_types.rs b/crates/openless-core/src/shared_types.rs -index e441d45..2f231aa 100644 --- a/crates/openless-core/src/shared_types.rs +++ b/crates/openless-core/src/shared_types.rs -@@ -552,12 +552,21 @@ pub struct UserPreferences { +@@ -572,12 +572,21 @@ /// model knows which languages the user works in. See issue #4. #[serde(default = "default_working_languages")] pub working_languages: Vec, @@ -1625,7 +1607,7 @@ index e441d45..2f231aa 100644 /// Chinese output script preference (not exposed as a UI switch): /// - Simplified: prefer simplified for Chinese output /// - Traditional: prefer traditional for Chinese output -@@ -1108,6 +1117,8 @@ struct UserPreferencesWire { +@@ -1152,6 +1161,8 @@ windows_show_openless_in_keyboard_list: bool, working_languages: Vec, translation_target_language: String, @@ -1634,7 +1616,7 @@ index e441d45..2f231aa 100644 chinese_script_preference: ChineseScriptPreference, #[serde(default)] output_language_preference: OutputLanguagePreference, -@@ -1367,6 +1378,7 @@ impl Default for UserPreferencesWire { +@@ -1423,6 +1434,7 @@ windows_show_openless_in_keyboard_list: prefs.windows_show_openless_in_keyboard_list, working_languages: prefs.working_languages, translation_target_language: prefs.translation_target_language, @@ -1642,7 +1624,7 @@ index e441d45..2f231aa 100644 chinese_script_preference: prefs.chinese_script_preference, output_language_preference: prefs.output_language_preference, qa_hotkey: prefs.qa_hotkey, -@@ -1494,6 +1506,15 @@ impl<'de> Deserialize<'de> for UserPreferences { +@@ -1555,6 +1567,15 @@ selection_polish_hotkey = None; } } @@ -1658,7 +1640,7 @@ index e441d45..2f231aa 100644 let streaming_insert_default_migrated = wire.streaming_insert_default_migrated; let streaming_insert = if streaming_insert_default_migrated { wire.streaming_insert -@@ -1599,7 +1620,10 @@ impl<'de> Deserialize<'de> for UserPreferences { +@@ -1662,7 +1683,10 @@ ), windows_show_openless_in_keyboard_list: wire.windows_show_openless_in_keyboard_list, working_languages: wire.working_languages, @@ -1669,8 +1651,8 @@ index e441d45..2f231aa 100644 + translation_target_language_input, chinese_script_preference: wire.chinese_script_preference, output_language_preference: wire.output_language_preference, - qa_hotkey: if cfg!(target_os = "linux") { wire.qa_hotkey } else { None }, // retired desktop follow-up shortcut -@@ -1993,6 +2017,9 @@ impl Default for UserPreferences { + qa_hotkey: if cfg!(target_os = "linux") { +@@ -2083,6 +2107,9 @@ windows_show_openless_in_keyboard_list: true, working_languages: default_working_languages(), translation_target_language: String::new(), diff --git a/openless-all/ios/CoreHost/src/recording_maintenance_tests.rs b/openless-all/ios/CoreHost/src/recording_maintenance_tests.rs index d90d10be9..8f821dbc9 100644 --- a/openless-all/ios/CoreHost/src/recording_maintenance_tests.rs +++ b/openless-all/ios/CoreHost/src/recording_maintenance_tests.rs @@ -476,3 +476,19 @@ fn maintenance_bounds_directory_scan_before_any_mutation() { assert!(read_journal(&owner.recordings_directory, &id).unwrap() == Some(Journal::Capturing)); ol_ios_destroy(handle); } + +#[tokio::test] +async fn archive_range_reads_keep_pcm_bounds_and_secure_open_validation() { + let directory = std::env::temp_dir() + .canonicalize() + .unwrap() + .join(format!("openless-ios-range-{}", uuid::Uuid::new_v4())); + let archive = WavArchive::create(&directory, SessionId::new()).unwrap(); + archive.append(&[1, 2, 3, 4, 5, 6]); + archive.finish(); + assert_eq!(archive.pcm_byte_len().await.unwrap(), 6); + assert_eq!(archive.read_pcm_range(2, 4).await.unwrap(), [3, 4, 5, 6]); + assert!(archive.read_pcm_range(4, 4).await.is_err()); + archive.discard().await.unwrap(); + std::fs::remove_dir_all(directory).unwrap(); +} diff --git a/openless-all/ios/CoreHost/src/recordings.rs b/openless-all/ios/CoreHost/src/recordings.rs index 534b71df8..ef326c2e0 100644 --- a/openless-all/ios/CoreHost/src/recordings.rs +++ b/openless-all/ios/CoreHost/src/recordings.rs @@ -234,6 +234,26 @@ impl RecordingArchive for WavArchive { fn is_available(&self) -> bool { self.state.lock().is_ok_and(|state| state.bytes > 0) && self.path.is_file() } + fn pcm_byte_len(&self) -> BoxFuture<'static, Result> { + let path = self.path.clone(); + Box::pin(async move { + prepare_directory(path.parent().ok_or_else(storage_error)?)?; + let (_, bytes) = open_wav(&path, false)?; + Ok(u64::from(bytes)) + }) + } + fn read_pcm_range( + &self, + offset: u64, + len: usize, + ) -> BoxFuture<'static, Result, BackendError>> { + let path = self.path.clone(); + Box::pin(async move { + prepare_directory(path.parent().ok_or_else(storage_error)?)?; + let (mut file, _) = open_wav(&path, false)?; + openless_core::audio::read_canonical_archive_pcm_range(&mut file, offset, len) + }) + } fn read_pcm(&self) -> BoxFuture<'static, Result, BackendError>> { let path = self.path.clone(); Box::pin(async move { diff --git a/openless-all/ios/scripts/prepare-core.py b/openless-all/ios/scripts/prepare-core.py index ee24d0f02..b2bc699d2 100644 --- a/openless-all/ios/scripts/prepare-core.py +++ b/openless-all/ios/scripts/prepare-core.py @@ -69,7 +69,7 @@ def main(): if sibling.name != "openless-core" and sibling.is_dir(): (staging / "crates" / sibling.name).symlink_to(sibling, target_is_directory=True) # Core integration tests also compile the production target-range helper. - for name in ["assets", "contract", "src", "src-tauri"]: + for name in ["assets", "contract", "src", "src-tauri", "linux-egui"]: (staging / name).symlink_to(APP / name, target_is_directory=True) environment = os.environ.copy() for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]: