diff --git a/.aoci/baseline.json b/.aoci/baseline.json index 22048337d..87ef6b33c 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-26T08:16:43Z", "files": { ".gitattributes": { "role": "index", @@ -149,21 +149,21 @@ }, "USAGE.md": { "role": "index", - "sha256": "57a1030a99256e9e1645b7be8bb61627473de240113aa4ebce63f7df08d08a77", - "size": 13284, - "normalized_sha256": "57a1030a99256e9e1645b7be8bb61627473de240113aa4ebce63f7df08d08a77" + "sha256": "54f5ac436d29669cdfb309a18e2eb69e063534c52a17a645f7cb2bc523644a4d", + "size": 13183, + "normalized_sha256": "54f5ac436d29669cdfb309a18e2eb69e063534c52a17a645f7cb2bc523644a4d" }, "USAGE.zh.md": { "role": "index", - "sha256": "ad9a1ae600e23cf4da25298a1760d504b38807c2d76c1de1b3ad3e9dbe6ad0a3", - "size": 12318, - "normalized_sha256": "ad9a1ae600e23cf4da25298a1760d504b38807c2d76c1de1b3ad3e9dbe6ad0a3" + "sha256": "8cdd633e583c6a1f2ae0a9b2290c828a11af500ff6e29261b3097f12e3a7cbca", + "size": 12253, + "normalized_sha256": "8cdd633e583c6a1f2ae0a9b2290c828a11af500ff6e29261b3097f12e3a7cbca" }, "aoci.code.txt": { "role": "index", - "sha256": "3c775951f3d312349357d51dbae70a0583d3161c3599a479d89d14e6e8a0f0f0", - "size": 768615, - "normalized_sha256": "3c775951f3d312349357d51dbae70a0583d3161c3599a479d89d14e6e8a0f0f0" + "sha256": "6ccc20b4906783d6040a3d627d91b7b57e2238b61160f6fbd4b563e8811bb6ab", + "size": 775586, + "normalized_sha256": "6ccc20b4906783d6040a3d627d91b7b57e2238b61160f6fbd4b563e8811bb6ab" }, "aoci.meta.txt": { "role": "index", @@ -216,9 +216,9 @@ }, "docs/ATTRIBUTION.md": { "role": "index", - "sha256": "e4195c2714e3008569bd2ba72b58c68ea8f105917e9b8b2d9e5f9f9d21ed4076", - "size": 2095, - "normalized_sha256": "e4195c2714e3008569bd2ba72b58c68ea8f105917e9b8b2d9e5f9f9d21ed4076" + "sha256": "abb27c11c12c6241be765e7b7194adc56dcf24b1de74f54ffc4cfadc36dff031", + "size": 3047, + "normalized_sha256": "abb27c11c12c6241be765e7b7194adc56dcf24b1de74f54ffc4cfadc36dff031" }, "docs/android-ime.md": { "role": "index", @@ -240,9 +240,9 @@ }, "docs/architecture.md": { "role": "index", - "sha256": "784630f5946050dd6c51a70c156e70b765f3ca17d8aea2a97d52e2b14fbf0fb3", - "size": 9849, - "normalized_sha256": "784630f5946050dd6c51a70c156e70b765f3ca17d8aea2a97d52e2b14fbf0fb3" + "sha256": "19a3de332ed1920c4de49965c9a92b1643e71a2a0f402103246b21739b8e7c77", + "size": 10173, + "normalized_sha256": "19a3de332ed1920c4de49965c9a92b1643e71a2a0f402103246b21739b8e7c77" }, "docs/ask-assistant-backend-handoff.md": { "role": "index", @@ -370,6 +370,12 @@ "size": 8128, "normalized_sha256": "beeadd3e9a1992d66b12d00284fa0a5485fc584e501ada38d22915f7fbd1dfc1" }, + "docs/development/ask.md": { + "role": "index", + "sha256": "6dbd00e90a89ee9281875c2eb847ebe79b666d1a6909cf905ad69179c527c7f8", + "size": 13159, + "normalized_sha256": "6dbd00e90a89ee9281875c2eb847ebe79b666d1a6909cf905ad69179c527c7f8" + }, "docs/development/cloud-sync.md": { "role": "index", "sha256": "e85261809276fd7c732b902e539da0bf09d0a7704091ed0b2d14bbc3ccefda23", @@ -414,9 +420,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", @@ -496,6 +502,12 @@ "size": 1518, "normalized_sha256": "a416e94a71f43ca9db041d7ecc890455af8d054b0ff44feb2cfac51689cefba2" }, + "docs/encrypted-cloud-sync-limited-scope.md": { + "role": "index", + "sha256": "8ff1f359ccfef38a26e8388ebb3337ecaaf8c20409eb4cc543519b3b8d424bb6", + "size": 21006, + "normalized_sha256": "8ff1f359ccfef38a26e8388ebb3337ecaaf8c20409eb4cc543519b3b8d424bb6" + }, "docs/encrypted-cloud-sync.md": { "role": "index", "sha256": "cfb1b572d2924cd23b52624e4b6cd7e7d1ae7703f16e667778d5477e623e7fb9", @@ -717,9 +729,9 @@ }, "docs/index.md": { "role": "index", - "sha256": "60ed63a94b293023b69233bf191eefadcfa0957e731336cff7c4785b7b763aa3", - "size": 2912, - "normalized_sha256": "60ed63a94b293023b69233bf191eefadcfa0957e731336cff7c4785b7b763aa3" + "sha256": "0a3b5b7b1e4f147d0ba756f84e4847ef7dd02775561b864b90f670a4d1452517", + "size": 2992, + "normalized_sha256": "0a3b5b7b1e4f147d0ba756f84e4847ef7dd02775561b864b90f670a4d1452517" }, "docs/issue-1223-aec-feasibility.md": { "role": "index", @@ -2024,9 +2036,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 +2102,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 +2114,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 +2222,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 +2234,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 +2258,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 +2288,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 +2330,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 +2354,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 +2378,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", @@ -2378,9 +2390,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/adapter.rs": { "role": "index", - "sha256": "110b89b686fb2f713bb61af9ba1c084f726e843718468a57f815ebe80fdeb8c0", - "size": 14283, - "normalized_sha256": "110b89b686fb2f713bb61af9ba1c084f726e843718468a57f815ebe80fdeb8c0" + "sha256": "b2d1a080325e991db6379476c58cc60fb6e8547a1f96177d286380f585e1da23", + "size": 14789, + "normalized_sha256": "b2d1a080325e991db6379476c58cc60fb6e8547a1f96177d286380f585e1da23" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/api.rs": { "role": "index", @@ -2394,6 +2406,12 @@ "size": 6639, "normalized_sha256": "1303c4b453752f6c1ce7cde92e170840f783235db01c0748e0d6e1305c46cd81" }, + "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs": { + "role": "index", + "sha256": "6174b2f37ea7318993f537aa982c3020c8f829ba62fe3e59e834772f0d541ca4", + "size": 7436, + "normalized_sha256": "6174b2f37ea7318993f537aa982c3020c8f829ba62fe3e59e834772f0d541ca4" + }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/local.rs": { "role": "index", "sha256": "bb18289d7a95fc20e5973f0e5a687c722a2cbd10af0d1027ea83ea2268bae8d3", @@ -2402,9 +2420,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/mod.rs": { "role": "index", - "sha256": "7dd7784ab99ca21f7881804e5d0dee17943a9b29b9ce7b6fd11bd211b8564406", - "size": 3716, - "normalized_sha256": "7dd7784ab99ca21f7881804e5d0dee17943a9b29b9ce7b6fd11bd211b8564406" + "sha256": "d0d564eb3fedc1c8e7a72012c4b9fdce91be951cffccb6a31ecb14432f22b78a", + "size": 3957, + "normalized_sha256": "d0d564eb3fedc1c8e7a72012c4b9fdce91be951cffccb6a31ecb14432f22b78a" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs": { "role": "index", @@ -2426,9 +2444,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee/tests.rs": { "role": "index", - "sha256": "e5b2f3ad7901f19aeb08fb51dc778415acd46b466a7d280c253fbde0c836c6b1", - "size": 102269, - "normalized_sha256": "e5b2f3ad7901f19aeb08fb51dc778415acd46b466a7d280c253fbde0c836c6b1" + "sha256": "502517cf39882dfa1d3a52cf05d3bfb7195020b5d82882eb3739072000a97bc2", + "size": 103730, + "normalized_sha256": "502517cf39882dfa1d3a52cf05d3bfb7195020b5d82882eb3739072000a97bc2" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/export.rs": { "role": "index", @@ -2436,6 +2454,18 @@ "size": 16077, "normalized_sha256": "39022528a38332f384e7bb978c00f062e6d53804c33e32c86fbc94864ead2a5f" }, + "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs": { + "role": "index", + "sha256": "590f4235fd1d870911e496d2d1af279a2939e7b44fa3406c8114eef0b51abbf9", + "size": 19775, + "normalized_sha256": "590f4235fd1d870911e496d2d1af279a2939e7b44fa3406c8114eef0b51abbf9" + }, + "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited_tests.rs": { + "role": "index", + "sha256": "3d3bf6a9b74560b2276ea4ad41bbf414e2438cdd7506fd40e0417ccbcc6be500", + "size": 8996, + "normalized_sha256": "3d3bf6a9b74560b2276ea4ad41bbf414e2438cdd7506fd40e0417ccbcc6be500" + }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/merge.rs": { "role": "index", "sha256": "5c36e833ee52bddc1be07ab1c7a70952a2f33a2fac49152827496adbacc73755", @@ -2444,9 +2474,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/mod.rs": { "role": "index", - "sha256": "4973328117ce62ee78f3daa294bf4f35060da2e76b1007630c27bc2ba390c932", - "size": 3833, - "normalized_sha256": "4973328117ce62ee78f3daa294bf4f35060da2e76b1007630c27bc2ba390c932" + "sha256": "be570551142996327586a3b398b511b608cebc0e4ae2e5173bb5832178848d7b", + "size": 4085, + "normalized_sha256": "be570551142996327586a3b398b511b608cebc0e4ae2e5173bb5832178848d7b" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs": { "role": "index", @@ -2504,15 +2534,15 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs": { "role": "index", - "sha256": "7a239c96f0aef9a312565e943ee4398b487f26e69f93ef076427e5cb2320f551", - "size": 93020, - "normalized_sha256": "7a239c96f0aef9a312565e943ee4398b487f26e69f93ef076427e5cb2320f551" + "sha256": "ae5794661b61c547a6126036349bb291a2694f1e798d9ff9e6776242d2683262", + "size": 94297, + "normalized_sha256": "ae5794661b61c547a6126036349bb291a2694f1e798d9ff9e6776242d2683262" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs": { "role": "index", - "sha256": "ffb272f48291eb3cb567601ce93256df804e0b5fd91b2857424acb385da48ef3", - "size": 41758, - "normalized_sha256": "ffb272f48291eb3cb567601ce93256df804e0b5fd91b2857424acb385da48ef3" + "sha256": "b1432f045c25693f6022c88a339e211940cfa4be19b9e11b07e26a841b2520e1", + "size": 41956, + "normalized_sha256": "b1432f045c25693f6022c88a339e211940cfa4be19b9e11b07e26a841b2520e1" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types/tests.rs": { "role": "index", @@ -2534,9 +2564,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs": { "role": "index", - "sha256": "91ccce6be1156ae7ef446dc95701fed7b4daee3acb066d29722159c60d885ee5", - "size": 44107, - "normalized_sha256": "91ccce6be1156ae7ef446dc95701fed7b4daee3acb066d29722159c60d885ee5" + "sha256": "46e2d179f1166b97263b864c2f6efb74ab43c477accf0696ce7afa55141d3713", + "size": 45586, + "normalized_sha256": "46e2d179f1166b97263b864c2f6efb74ab43c477accf0696ce7afa55141d3713" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/journal.rs": { "role": "index", @@ -2544,6 +2574,12 @@ "size": 5606, "normalized_sha256": "ebb709843465fa534936c085c9295cdf494ae975fd44f8ad9d668ae02b7187f4" }, + "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/limited_tests.rs": { + "role": "index", + "sha256": "12eba9113bfbaff617489baff06d61e016ee6c6f7719d6e206cff8682da784bd", + "size": 18134, + "normalized_sha256": "12eba9113bfbaff617489baff06d61e016ee6c6f7719d6e206cff8682da784bd" + }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs": { "role": "index", "sha256": "7ad3d53f52c6173a53733027c98eaf38b4e2f440405e5192f72ac21e97bb33c3", @@ -2564,9 +2600,9 @@ }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs": { "role": "index", - "sha256": "9a84802a20dcaf0a4707b2696c29c1747300238e870623c7d618a14031a68755", - "size": 67896, - "normalized_sha256": "9a84802a20dcaf0a4707b2696c29c1747300238e870623c7d618a14031a68755" + "sha256": "4c69616001bdaa5f1562409ed7988cb6443715850a7c80c37d62660ff4ad7646", + "size": 67944, + "normalized_sha256": "4c69616001bdaa5f1562409ed7988cb6443715850a7c80c37d62660ff4ad7646" }, "openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests/local_migration.rs": { "role": "observe", @@ -2660,9 +2696,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 +2774,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 +2972,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 +3110,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 +3152,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 +3296,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 +3332,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 +3348,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 +3386,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 +3482,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 +3530,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 +3620,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 +3758,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 +4434,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 +4795,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", @@ -5452,11 +5500,17 @@ "size": 3514, "normalized_sha256": "65b9d2e9bbc52b3bd5b5b557c1667bddac3d723d68c411b5f0b9645b8436ca44" }, + "openless-all/app/scripts/audio-cue-listener-contract.test.mjs": { + "role": "index", + "sha256": "5c335d6878c0f452096bed29d42012636fc36ecec19eaf072ed52faf28be00bd", + "size": 1133, + "normalized_sha256": "5c335d6878c0f452096bed29d42012636fc36ecec19eaf072ed52faf28be00bd" + }, "openless-all/app/scripts/audio-cue-runtime.test.mjs": { "role": "index", - "sha256": "a6bd75cbf8bd3d7c259b55cd22d6420873f7fb330f64a5b1d1cfc93eb7bcd4f1", - "size": 5258, - "normalized_sha256": "a6bd75cbf8bd3d7c259b55cd22d6420873f7fb330f64a5b1d1cfc93eb7bcd4f1" + "sha256": "0c9b921d6dca3050a6dd0c1b1056bbb8722999eb96de10db421d444bf0ede082", + "size": 9345, + "normalized_sha256": "0c9b921d6dca3050a6dd0c1b1056bbb8722999eb96de10db421d444bf0ede082" }, "openless-all/app/scripts/audio-cue-window-contract.test.mjs": { "role": "index", @@ -5514,9 +5568,9 @@ }, "openless-all/app/scripts/capsule-ready-replay.test.mjs": { "role": "index", - "sha256": "93bbf8dbe6e6c5a6299db1942027403c57f0ffb1875d54765dbddc7d538f0fb9", - "size": 24488, - "normalized_sha256": "93bbf8dbe6e6c5a6299db1942027403c57f0ffb1875d54765dbddc7d538f0fb9" + "sha256": "5d240313f94fd6f67a22b66ea98761227e80734a91e21068a9684f43b2b5b391", + "size": 24969, + "normalized_sha256": "5d240313f94fd6f67a22b66ea98761227e80734a91e21068a9684f43b2b5b391" }, "openless-all/app/scripts/capsule-stacking-webkit.swift": { "role": "index", @@ -5634,9 +5688,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 +6420,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 +6528,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", @@ -6564,9 +6618,15 @@ }, "openless-all/app/scripts/voice-edit-open-dispatch-contract.test.mjs": { "role": "index", - "sha256": "9c0f89a0aebd81706d877f2358cb367be2cdad33054d966b99e9f6424ea81d6f", - "size": 3061, - "normalized_sha256": "9c0f89a0aebd81706d877f2358cb367be2cdad33054d966b99e9f6424ea81d6f" + "sha256": "7b71a3a61f743fc4347127481bf68f7f70737221cae92cca1dad14b69fbd3695", + "size": 3149, + "normalized_sha256": "7b71a3a61f743fc4347127481bf68f7f70737221cae92cca1dad14b69fbd3695" + }, + "openless-all/app/scripts/voice-edit-window-open-contract.test.mjs": { + "role": "index", + "sha256": "721d4fd4ce347645add117920afe9f74c3225707891dfa23a01b397bd43c3c9d", + "size": 1987, + "normalized_sha256": "721d4fd4ce347645add117920afe9f74c3225707891dfa23a01b397bd43c3c9d" }, "openless-all/app/scripts/windows-artifact-acceptance.ps1": { "role": "index", @@ -6606,9 +6666,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 +6720,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 +6899,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 +7061,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", @@ -7025,9 +7085,9 @@ }, "openless-all/app/src-tauri/backend-tests/tests/voice_edit_host.rs": { "role": "observe", - "sha256": "4a1c94a1a262fc7e12bba429de0bfda3e1353620a0968f48104692eda1f1f077", - "size": 24595, - "normalized_sha256": "4a1c94a1a262fc7e12bba429de0bfda3e1353620a0968f48104692eda1f1f077" + "sha256": "762811a57cdb176dde987632f3d347d863a5271240ec1f585445bd083a18c67f", + "size": 24704, + "normalized_sha256": "762811a57cdb176dde987632f3d347d863a5271240ec1f585445bd083a18c67f" }, "openless-all/app/src-tauri/backend-tests/tests/windows_edit_settle.rs": { "role": "observe", @@ -7889,15 +7949,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 +8021,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", @@ -7991,15 +8051,15 @@ }, "openless-all/app/src-tauri/src/commands/voice_edit.rs": { "role": "index", - "sha256": "ed1ab1cc8e4675a2f052c5f272358b56196387253675f61a855c586dc4e42fd0", - "size": 3634, - "normalized_sha256": "ed1ab1cc8e4675a2f052c5f272358b56196387253675f61a855c586dc4e42fd0" + "sha256": "7302f1592630e5e3414dc733a7e0114d822c6efdddab450d89f58c1c6e2549cb", + "size": 3767, + "normalized_sha256": "7302f1592630e5e3414dc733a7e0114d822c6efdddab450d89f58c1c6e2549cb" }, "openless-all/app/src-tauri/src/coordinator.rs": { "role": "index", - "sha256": "15e84b32a7c9c7c5e6c85da360ecc3a0cd88bc51ee88d19dbab011718348bb23", - "size": 80647, - "normalized_sha256": "15e84b32a7c9c7c5e6c85da360ecc3a0cd88bc51ee88d19dbab011718348bb23" + "sha256": "0575534a851709a8000f828352518429944cea6ebd14255436caeee3c99c5ecf", + "size": 80973, + "normalized_sha256": "0575534a851709a8000f828352518429944cea6ebd14255436caeee3c99c5ecf" }, "openless-all/app/src-tauri/src/coordinator/capsule_focus.rs": { "role": "index", @@ -8033,15 +8093,15 @@ }, "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", - "sha256": "153f45f85915ff58e09c3d792d6bc62aedc1240ed6d7b90fd5824805fa704b22", - "size": 25742, - "normalized_sha256": "153f45f85915ff58e09c3d792d6bc62aedc1240ed6d7b90fd5824805fa704b22" + "sha256": "672449c523afd70200cf9be25eabb0c5b06319986a1a270df6a21765f3bd11e5", + "size": 25750, + "normalized_sha256": "672449c523afd70200cf9be25eabb0c5b06319986a1a270df6a21765f3bd11e5" }, "openless-all/app/src-tauri/src/coordinator_state.rs": { "role": "index", @@ -8051,9 +8111,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 +8183,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 +8207,9 @@ }, "openless-all/app/src-tauri/src/lib.rs": { "role": "index", - "sha256": "0a0a62d0e79baff2f8dd76333d17ffb51a3e5f032d9f51f0e35bd60f424cd006", - "size": 168109, - "normalized_sha256": "0a0a62d0e79baff2f8dd76333d17ffb51a3e5f032d9f51f0e35bd60f424cd006" + "sha256": "894233759f022cce02654e45ff203e9ce8933d9551c25d4a23063886906222f8", + "size": 168764, + "normalized_sha256": "894233759f022cce02654e45ff203e9ce8933d9551c25d4a23063886906222f8" }, "openless-all/app/src-tauri/src/llm_gemini.rs": { "role": "index", @@ -8351,9 +8411,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 +8483,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 +8519,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", @@ -8507,9 +8567,9 @@ }, "openless-all/app/src-tauri/src/tauri_coordinator_host.rs": { "role": "index", - "sha256": "f7827b06901965f9c1b7789412d9a07d098e932a1cb830ff21376a082a5c01b4", - "size": 117525, - "normalized_sha256": "f7827b06901965f9c1b7789412d9a07d098e932a1cb830ff21376a082a5c01b4" + "sha256": "ebf1042494da51db79f845edc5bcb1ce038351b4d362a2fa0438a20037a989fd", + "size": 117611, + "normalized_sha256": "ebf1042494da51db79f845edc5bcb1ce038351b4d362a2fa0438a20037a989fd" }, "openless-all/app/src-tauri/src/tauri_events.rs": { "role": "index", @@ -9155,9 +9215,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 +9437,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", @@ -9803,15 +9863,15 @@ }, "openless-all/app/src/features/capsule/AudioCue.tsx": { "role": "index", - "sha256": "37134886252e1eed341ca64dc4b5740ba098d4ee4b286b572786ab39ada590b0", - "size": 2126, - "normalized_sha256": "37134886252e1eed341ca64dc4b5740ba098d4ee4b286b572786ab39ada590b0" + "sha256": "c483118e6c952a453517ddf5adc5b2c7d784da2fc707ae933a93e1f1437f9521", + "size": 2258, + "normalized_sha256": "c483118e6c952a453517ddf5adc5b2c7d784da2fc707ae933a93e1f1437f9521" }, "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", @@ -10073,9 +10133,9 @@ }, "openless-all/app/src/features/input/SelectionWorkspaceSection.tsx": { "role": "index", - "sha256": "911a8a935f67d50851b6d53847522ee3692d4ba39bdd6cf29e5540409404a72e", - "size": 6000, - "normalized_sha256": "911a8a935f67d50851b6d53847522ee3692d4ba39bdd6cf29e5540409404a72e" + "sha256": "e41e9708ff0f2bbc0cf09febfe2f2e982c0a3b48113391d7adbbc2384c693b81", + "size": 6791, + "normalized_sha256": "e41e9708ff0f2bbc0cf09febfe2f2e982c0a3b48113391d7adbbc2384c693b81" }, "openless-all/app/src/features/input/ShortcutsSection.tsx": { "role": "index", @@ -10679,9 +10739,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", @@ -11093,9 +11153,9 @@ }, "openless-all/app/src/lib/audioCue.ts": { "role": "index", - "sha256": "f1d433c8441ceba0b972efcbe183d09b86d916162593a3350a05753269669307", - "size": 14790, - "normalized_sha256": "f1d433c8441ceba0b972efcbe183d09b86d916162593a3350a05753269669307" + "sha256": "e4573776a9d41a3f569508ed34aa264f4fc688ffb22aaaea7ad2bc03c097cdc4", + "size": 15317, + "normalized_sha256": "e4573776a9d41a3f569508ed34aa264f4fc688ffb22aaaea7ad2bc03c097cdc4" }, "openless-all/app/src/lib/audioDsp.ts": { "role": "index", @@ -13279,9 +13339,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 +13405,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 +17206,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/USAGE.md b/USAGE.md index 022ca2040..058635006 100644 --- a/USAGE.md +++ b/USAGE.md @@ -144,7 +144,7 @@ Switch the mode from the capsule in the main window or under Settings: ## Ask Anything (desktop) -On macOS or Windows, press the recording shortcut with Space to open Ask Anything. Type a question or dictate into the draft, then send it when ready. Answers expand in the same window. Write and edit requests can deliver to a verified external input target. If OpenLess cannot confirm the write, the result stays available in Ask for manual copying. See the [desktop Ask contract](docs/ask-unified-entry-contract.md) for routing and delivery details. +On macOS or Windows, press the recording shortcut with Space to open Ask Anything. Type a question or dictate into the draft, then send it when ready. Answers expand in the same window. Write and edit requests can deliver to a verified external input target. If OpenLess cannot confirm the write, the result stays available in Ask for manual copying. ## Dictionary diff --git a/USAGE.zh.md b/USAGE.zh.md index c2a6540a6..4f9c9681b 100644 --- a/USAGE.zh.md +++ b/USAGE.zh.md @@ -144,7 +144,7 @@ Linux 使用原生 egui 宿主,不依赖 Tauri 或 WebKitGTK。 ## 随便问(桌面端) -在 macOS 或 Windows 按录音快捷键和空格打开「随便问」。可以输入问题,也可以使用录音胶囊把转写填入草稿,确认后再发送。问题在同一个窗口展开答案。写作或编辑指令只有在应用核实原输入目标后才写回。未能确认写入时,生成内容会留在「随便问」,可手动复制。详见[桌面入口契约](docs/ask-unified-entry-contract.md)。 +在 macOS 或 Windows 按录音快捷键和空格打开「随便问」。可以输入问题,也可以使用录音胶囊把转写填入草稿,确认后再发送。问题在同一个窗口展开答案。写作或编辑指令只有在应用核实原输入目标后才写回。未能确认写入时,生成内容会留在「随便问」,可手动复制。 ## 词典 diff --git a/aoci.code.txt b/aoci.code.txt index 757849c70..118e70525 100644 --- a/aoci.code.txt +++ b/aoci.code.txt @@ -8,8 +8,8 @@ README.md[SG6L]: F:Introduces OpenLess platforms, voice input, Ask, privacy and README.zh.md[SG5L]: F:Introduces the OpenLess platform and feature boundaries in Chinese and routes readers to user, build and contribution guides | R:code:README.md,code:USAGE.zh.md,code:RELEASING.zh.md,code:openless-all/README.zh.md | A:平台支持,功能现状,贡献流程,架构 | S:Cursor context collection is off by default. RELEASING.md[SV7M]: F:Defines release authority, channel and version gates, shared draft artifacts, signing, publication and attribution | R:code:RELEASING.zh.md,code:.github/workflows/release-tauri.yml,code:.github/workflows/android-apk.yml,code:.github/workflows/release-harmony.yml | A:Authority,Channels and tags,Version-sync gate,Pre-release checklist,Process summary | S:Only administrators tag and publish. Draft repair requires an existing draft. Linux assets require L01-L12 evidence for the reviewed release candidate. RELEASING.zh.md[SV6M]: F:Maintains the Chinese channel, version, signing, shared draft and release maintenance policy | R:code:RELEASING.md,code:.github/workflows/release-tauri.yml,code:.github/workflows/release-harmony.yml | A:权限,渠道与标签,版本同步闸门,流程摘要 | S:Published notes edits recheck asset identity and channel flags without rebuilding. Draft repair is restricted to a release that remains a draft. -USAGE.md[SU5M]: F:Guides platform installation, permissions, provider setup, dictation, desktop Ask, vocabulary and history use | R:code:USAGE.zh.md,code:README.md,code:docs/ask-unified-entry-contract.md | A:Installation,First-time setup,Ask Anything (desktop),Dictionary | S:iOS device installation requires a personally signed build. An unconfirmed Ask write leaves its result available for copy. -USAGE.zh.md[SU4M]: F:Guides Chinese users through installation, permissions, providers, dictation, desktop Ask and daily editing controls | R:code:USAGE.md,code:README.zh.md,code:docs/ask-unified-entry-contract.md | A:安装,首次设置,随便问(桌面端),词典 | S:Voice in Ask fills the draft and waits for explicit submission. +USAGE.md[SU5M]: F:Guides installation, permissions, provider setup, dictation, desktop Ask, vocabulary and history use | R:code:USAGE.zh.md,code:docs/guides/speech-services.md | A:Installation,First-time setup,Ask Anything (desktop),Dictionary | S:iOS requires a personally signed build. Unconfirmed Ask writes leave results available for copying. +USAGE.zh.md[SU4M]: F:Guides Chinese users through installation, permissions, providers, dictation, desktop Ask and editing controls | R:code:USAGE.md,code:docs/guides/speech-services.md | A:安装,首次配置,随便问(桌面端),词典 | S:Ask voice input fills the draft and waits for explicit submission. ===/Users/lvbaiqing/project/openless/.github/ISSUE_TEMPLATE/=== bug.yml[FQ3T]: F:Defines the Chinese bug issue form with separate fields for symptoms, impact, acceptance and open questions | R:code:.github/ISSUE_TEMPLATE/config.yml | A:impact, acceptance, todo | S:- @@ -40,17 +40,18 @@ sync-micyou.yml[OV5S]: F:Checks pinned MicYou DSP updates, runs regression evide openless.rb[FV5T]: F:Defines the macOS OpenLess cask with architecture-specific DMGs and digests, install requirements and optional cleanup paths | R:code:.github/workflows/sync-homebrew-cask.yml | A:cask, livecheck, zap | S:The build suffix stays in asset filenames but is excluded from the release tag in the download URL. ===/Users/lvbaiqing/project/openless/docs/=== -ATTRIBUTION.md[SC4T]: F:Records the upstream origins, licenses and adapted sources for Rare UI components and Open Runde fonts | R:code:openless-all/app/public/licenses/rare-ui-LICENSE.txt,code:openless-all/app/public/licenses/open-runde-OFL.txt | A:Rare UI GitHub Activity,Rare UI AI Prompt Box and Streaming Response | S:- -architecture.md[SG8T]: F:Defines OpenLess host and Core boundaries, frontend data ownership, Ask and other windows, and validation entry points | R:code:openless-all/app/Cargo.toml,code:openless-all/app/contract/backend-2.0.json,code:docs/structure.md,code:docs/ask-unified-entry-contract.md | A:分层与工作区,React 运行边界,Host 注入点,窗口体系 | S:Tauri and backend-tests resolve independently from the shared workspace. A history query subscribes before reading and discards a result invalidated during the read. +ATTRIBUTION.md[SC4T]: F:Credits adapted Rare UI components and Open Runde fonts and links their upstream sources and licenses | R:code:openless-all/app/public/licenses/rare-ui-LICENSE.txt | A:Rare UI Toast,Rare UI AI Prompt Box and Streaming Response | S:- +architecture.md[SG8T]: F:Maps platform hosts, shared Core, frontend ownership and voice, Ask, sync and delivery boundaries | R:code:openless-all/app/Cargo.toml,code:docs/development/ask.md,code:docs/development/recording-overlap.md | A:分层与工作区,主要调用链,从功能定位源码 | S:Tauri and backend-tests resolve independently. History subscribes before reading and discards invalidated results; stopped capture can release the next recording while its frozen job continues. ask-standalone-contract.md[SB7T]: F:Specifies scoped context, attachment admission and cancellable tools shared by Ask entries | R:code:docs/ask-assistant-rewrite-contract.md,code:docs/ask-unified-entry-contract.md,code:openless-all/app/ask-window/composer.tsx | A:ContextProvider,AttachmentReader,SearchTool,PromptBox | S:Assistant replacement overrides obsolete chat restrictions. Attachment labels resolve by ID; external facts stay untrusted, and verified selection and context grants remain turn-scoped. ask-unified-entry-contract.md[SB7T]: F:Specifies desktop Ask admission, per-submit intent routing, same-window expansion and native delivery ownership | R:code:docs/ask-assistant-rewrite-contract.md,code:openless-all/app/src-tauri/src/ask_window/chat.rs,code:openless-all/app/src-tauri/src/ask_window/entry_settings.rs | A:Open and submit,Settings and routing,Native target and delivery,IPC and verification | S:Bind macOS writes to opening A and edits to verified B. Reclassify every submit; answer routes use AssistantRuntime. Generate write/edit once and retain uncertain delivery without retry. -index.md[SG4T]: F:Routes readers to usage, builds, architecture, platform contracts, speech services and release documentation | R:code:docs/architecture.md,code:docs/structure.md,code:docs/polish-strategy.md | A:使用与构建,架构、契约与验收,语音与服务,发布与署名 | S:- +index.md[SG4T]: F:Routes users and developers to usage, architecture, voice, Ask, sync, platform, release and unfinished-work documents | R:code:docs/architecture.md,code:docs/development/ask.md,code:docs/requirements.md | A:使用 OpenLess,开发 OpenLess,查未完成工作 | S:- linux-egui-command-event-baseline.json[FM5L]: F:Captures the historical Tauri command and event compatibility inventory, Core event kinds and Linux interface ownership for contract 2.0.0 | R:code:openless-all/app/contract/backend-2.0.json,code:docs/linux-egui-backend-contract.md | A:commands,events,coreEventKinds,compatibilityRules,implementationStatus | S:The M0 inventory records its own source date. Current Linux product release requires separate device and install evidence. ask-assistant-backend-handoff.md[SB6T]: F:Defines the independent personal-assistant runtime brief, ownership boundaries and acceptance evidence | R:code:docs/ask-assistant-rewrite-contract.md,code:openless-all/app/crates/openless-core/src/assistant_api.rs | A:AssistantRuntime,AssistantContextProvider,shared UsageRecorder | S:Agent-development settings are not product model configuration. Own only assistant execution, reuse shared UsageRecorder, and leave entry, GUI and native writing to the lead. ask-assistant-rewrite-contract.md[SB8S]: F:Defines the replacement assistant boundary, request lifecycle, authorized context, native target separation and manual acceptance status | R:code:docs/ask-unified-entry-contract.md,code:openless-all/app/crates/openless-core/src/assistant_api.rs,code:openless-all/app/src-tauri/src/ask_window/context.rs | A:Frontend wire,Rust boundary,Entry and native delivery,Acceptance | S:Overrides legacy single-search, marker/review and expanded-routing bypass rules. Assistant answer routes never receive write authority. Browser and voice-history grants default off independently. Reported fixture and native-target successes do not establish the unverified full GUI/model/microphone workflow. ask-error-codes.md[SU6T]: F:Documents stable public Ask error codes and compact versus expanded presentation | R:code:openless-all/app/ask-window/client.ts,code:openless-all/app/ask-window/notices.tsx | A:ASK error-code catalogue,compact placeholder,expanded notification | S:Unknown or private provider errors map to a generic public code. Preserve drafts and window geometry; never surface raw backend messages as user-facing failure text. aoci-code.md[SG5T]: F:Documents OpenLess AOCI Code index files, workspace setup, MCP tools, FRAS fields, and incremental update workflow | R:code:aoci.txt,code:aoci.meta.txt,code:aoci.code.txt,code:AGENTS.md | A:aoci_rules,aoci_overview,aoci_maintain,aoci_update_entry,aoci verify | S:Each Git worktree validates against its own source and baseline; copied indexes must preserve manifest, volume, config, and baseline consistency. requirements.md[SB5T]: F:Tracks unfinished OpenLess development, platform verification, learning, remote-input, and encrypted sync release tasks | R:code:docs/architecture.md,code:docs/development/linux.md,code:docs/development/cloud-sync.md | A:- | S:Lists only open implementation and device-evidence items; completed behavior belongs in architecture.md. +encrypted-cloud-sync-limited-scope.md[SS7S]: F:Defines the experimental limited sync domain, confirmation, local restore seams and unfinished transport and iOS requirements | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs | A:Confirmation is explicit,Why no remote sync method is exposed,Validation boundary | S:V1 has a singleton vault, so limited remote upload is blocked. Local seams do not prove iOS, cloud or two-device acceptance; full and limited factories are alternatives. ===/Users/lvbaiqing/project/openless/docs/cloud-sync-agreement/=== agreement-draft.zh-CN.md[SS5T]: F:Provides the proposed Chinese encrypted sync terms and privacy disclosure, including scope, passwords, operation outcomes and rights | R:code:docs/cloud-sync-agreement/facts-and-legal-review.md, code:docs/cloud-sync-agreement/user-summary.zh-CN.md | A:开启前的选择与同步范围, 同步和恢复, 正式版本 | S:The draft is pending review and effective date. The current local scope confirmation cannot be used as acceptance of future formal terms. @@ -76,9 +77,6 @@ openless-client-startup-recording-flow.zh-CN.svg[SA2T]: F:Renders the Chinese st ===/Users/lvbaiqing/project/openless/docs/references/=== polish-reference-examples.sample.jsonl[SA3T]: F:Shows three human reference examples for structured and light polishing, including preserving a question as user input | R:- | A:id, raw, polished, tags | S:Polishing must leave a question unanswered. -===/Users/lvbaiqing/project/openless/docs/releases/=== -2.0.2-release-notes.md[SV4T]: F:Summarizes the stable 2.0.2 changes over 2.0.1 using the released Beta.7 source, including transcription, usage, sync and mobile updates | R:code:docs/releases/2.0.1-release-notes.md, code:docs/releases/2.0.2-Beta.6-release-notes.md | A:相对 2.0.1 的变化, 已知范围, 下载与升级 | S:The note ties stable content to Beta.7 source plus version identity changes. Local changes outside that tag are excluded. - ===/Users/lvbaiqing/project/openless/openless-all/=== README.md[SV5S]: F:Locates cross-platform sources and maintains desktop toolchain, local build and packaging instructions and native mobile guide links | R:code:openless-all/README.zh.md,code:openless-all/app/scripts/build-mac.sh,code:openless-all/app/scripts/windows-package-msvc.ps1,code:openless-all/ios/README.md | A:App Directory,macOS Build,Windows Build,Android Build,iOS Build | S:INSTALL=0 packages macOS without replacing the installed app. The separate iOS project owns its own version and signing. README.zh.md[SV4S]: F:Documents the cross-platform app tree and local macOS, Windows and Linux builds in Chinese, with native mobile build and signing links | R:code:openless-all/README.md,code:docs/index.md,code:openless-all/ios/README.zh.md | A:应用目录,macOS 构建,Windows 构建,Android 构建,iOS 构建 | S:The GNU helper needs a space-free build path for native import libraries. Linux distribution requires separate device evidence. @@ -298,15 +296,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 +319,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 +349,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 +367,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 +411,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. @@ -447,32 +445,35 @@ dsp_tests.rs[TH5M]: F:Checks denoiser sample-count preservation, invalid sample echo.rs[KH6L]: F:Aligns timestamped playback reference and adaptively suppresses acoustic echo while preserving microphone speech | R:code:openless-all/app/crates/openless-core/src/audio.rs | A:EchoCanceller, invalidate, process | S:Reference is invalidated when ownership or format changes. Double-talk must retain the near-end signal. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/=== -adapter.rs[IS7M]: F:Wires encrypted sync transport, credentials, device identity and local document repositories to the Core sync service | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs, code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs | A:build, build_local_store, load_device_id | S:Local Android migration binds its own protected storage namespace and the same data-directory gate. +adapter.rs[IS7L]: F:Composes protected local sync stores, device identity, repositories and the optional full encrypted sync service | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs | A:build,build_store,build_local_store,load_device_id | S:Limited storage has a separate root and device identity but shares the data-directory gate. Missing identity over retained protected data requires recovery, never replacement. api.rs[ES6M]: F:Exposes encrypted sync status and operations, Android migration, account actions and revision-checked UI preferences through Core | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:cloud_sync_e2ee_status, cloud_sync_e2ee_apply_restore, cloud_sync_e2ee_set_ui_preferences_checked | S:Setup prompt lookup can defer while the runtime is busy and reports a poisoned runtime lock as recovery required. dto.rs[LS6M]: F:Defines public encrypted sync auth, vault, restore preview and consent representations shared with host IPC | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/api.rs | A:EncryptedSyncStatus, RestorePreview, ConsentScope, CONSENT_VERSION | S:Secret document fields are not part of the public DTO. Conflicts expose opaque identities and summaries. local.rs[PS7L]: F:Persists encrypted local sync settings, baselines, pending operations and UI revisions and stores remembered keys through host credentials | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:LocalStorage, account_namespace, read, write, remember | S:Keep wrapping keys in the system vault, never beside local files. Origin and account determine the encrypted namespace. -mod.rs[LS5S]: F:Exports encrypted sync configuration and public DTOs and translates service, protocol and document failures into backend errors | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:EncryptedSyncConfig, error, protocol_error, document_error | S:Error details expose stable reasons without private document contents. +mod.rs[LS5S]: F:Exports full and limited encrypted sync APIs and converts protocol and document failures into stable backend reasons | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs | A:EncryptedSyncConfig,LimitedSyncStore,error,protocol_error,document_error | S:Error details carry stable value-free reasons; exporting the limited facade does not enable remote synchronization. service.rs[AS9L]: F:Orchestrates encrypted sync sign-in, scope confirmation, vault actions, conflicts, restore and automatic scheduling | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/local.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/restore.rs | A:SyncServiceData,EncryptedSyncService,prepare_enable_scoped,change_password,definite_rejection | S:Reconcile unresolved operation IDs before retrying. Bind preview to local generation, account and vault, and trigger automatic sync once at startup plus debounced persistent changes. setup_prompt.rs[AU5T]: F:Claims the local encrypted-sync invitation once after an eligible configured speech pipeline is ready | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:claim_setup_prompt | S:Claim is local only and does not establish an authenticated session, export documents or enable sync. setup_prompt_tests.rs[TS4M]: F:Exercises readiness, one-time setup prompting, restart and contention in encrypted sync with a loopback provider | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/setup_prompt.rs | A:setup_prompt_claim_is_once_per_installation_and_survives_restart_without_http | S:Prompt claiming must finish with zero sync HTTP traffic and leave provider credentials untouched. -tests.rs[TS5L]: F:Exercises encrypted sync service behavior, credentials, contention, restore, pending operations and local failure paths | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:Fixture,Server,create_requires_valid_confirmation_and_a_committed_remote_backup_to_enable | S:Uses loopback OAuth and sync plus an in-memory vault. Creating an enabled vault requires a committed remote backup. +tests.rs[TS5L]: F:Exercises encrypted sync lifecycle, consent, identity, pending operations, restore and local failure behavior | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:Fixture,Server,public_verified_account_facade_does_not_enable_or_authenticate_full_sync | S:Loopback authorities and in-memory vaults do not prove production acceptance. The account facade exposes only immutable numeric identity, without enabling full sync. +limited.rs[AS7S]: F:Exposes verified account identity and an opt-in local facade for limited document export and journalled restore | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs | A:VerifiedSyncAccount,SyncAccountProvider,LimitedSyncStore | S:No remote upload exists. Require explicit limited permission, dedicated store identity and fresh account checks; restore uses the existing exclusive gate and exact generation. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/=== export.rs[DS7L]: F:Projects a coherent Core capture into registered sync documents and scoped provider and device data | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs | A:export_sync_documents,export_snapshot,export_provider_credentials_for_sync | S:Only export explicitly admitted fields and credentials. Non-legacy builtin style packs export as imported kind, and retained v1 settings stay authoritative until native overrides apply. merge.rs[KD7L]: F:Performs three-way logical document merge, redacts conflicts and derives tombstones for missing local baseline records | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/validate.rs | A:diff_sync_documents, diff_local_replace_documents, record_missing_tombstones | S:Group a channel and its credentials as an atomic unit. Timestamps never pick winners, and missing baseline identity is not a deletion. -mod.rs[LD5T]: F:Exports encrypted sync document types and parsed, validated and redacted serialization paths | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/validate.rs | A:parse_redacted_sync_documents,parse_sync_documents,serialize_sync_documents | S:Redacted bundles undergo normalization and validation before becoming restorable documents. +mod.rs[LD5S]: F:Exports full and limited sync document contracts and validated parsing and serialization entry points | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/validate.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs | A:parse_redacted_sync_documents,parse_sync_documents,serialize_sync_documents,LimitedSyncDocuments | S:Redacted bundles are normalized and validated before restoration. Limited envelopes retain their separate namespace and validation path. registry.rs[FS8L]: F:Classifies preference and credential fields as portable, device-bound or excluded from encrypted sync | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/export.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/validate.rs | A:PREFERENCE_FIELDS,PreferenceShape,excluded_extension_key,credential_accounts,is_device_channel | S:Credential accounts require explicit registration and unknown extensions remain subject to exclusions. Local ASR stays device-bound; the strategy script and enable switch are portable preferences that can execute on a receiving device. restore.rs[AR8L]: F:Prepares, applies and recovers logical restores using sealed journals, source checks and durable commit decisions | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/journal.rs, code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/types.rs | A:RestorePlan, SealedJournal, JournalProtector, prepare_sync_restore, apply_sync_restore | S:Require current scope and observed revision before starting. After the journal is durable, finish transaction or recover from the persisted phase instead of dropping the write on cancellation. restore_tests.rs[TR5L]: F:Injects restore capture, journal and write faults to exercise rollback, recovery and generation advancement | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/restore.rs | A:restore_verifies_all_logical_data_and_advances_one_generation, journal_prepare_failure_never_starts_a_data_write | S:Failed durable journal preparation must precede all data writes. tests.rs[TS5L]: F:Exercises encrypted document allowlists, credential and device boundaries, schema checks, tombstones and collection ordering | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/merge.rs | A:controlled_export_keeps_real_service_keys_but_excludes_local_secrets_and_grants,collection_order_is_preserved_independently_of_stable_id_sorting | S:Stable identity sorting must not change user-defined collection order. types.rs[LS7L]: F:Defines secret-bearing logical records, coherent export sources, restore scopes and storage lease contracts | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/export.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/restore.rs | A:SecretJson,ExportSnapshot,SyncScope,RestoreContext | S:Secret-bearing types redact Debug output and stay native. Credential read failures must surface rather than be modeled as absent data. validate.rs[DS7L]: F:Validates decrypted document identities, schemas, structured values, credential ownership and collection order before effects | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs | A:validate_sync_documents, value_depth, validate_channel, validate_profile | S:Reject forbidden extension keys, mismatched IDs and excessive depth before local restore. Collection order is derived separately from stable IDs. +limited.rs[DS8L]: F:Projects and validates confirmed vocabulary, mode settings and style references and overlays explicit limited restore decisions | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/merge.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs | A:ConfirmedVocabularySelection,LimitedSyncDocuments,LimitedMergePreview | S:Empty confirmation selects nothing and binds exact scope and generation. Exclude secrets, history and style contents; preserve receiver-local notes and hits. Authenticated scope is external to plaintext. Missing installed style identity or deletion tombstones fails before writes. +limited_tests.rs[TS5M]: F:Checks limited sync field exclusion, manifest binding, confirmation freshness and explicit conflict and deletion semantics | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs | A:limited_export_never_contains_full_snapshot_secrets_or_unconfirmed_vocabulary,limited_conflicts_and_deletions_reuse_core_three_way_rules | S:Full and limited envelopes reject each other; duplicate keys, forbidden fields and stale confirmation fail closed. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/=== crypto.rs[KS8M]: F:Implements normalized sync password handling, Argon2 derivation and authenticated encryption with bound snapshot metadata | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs | A:NormalizedPassword, DerivedKey, EncryptContext, decrypt_snapshot_with_password | S:Password derivation must run off UI and async workers. Secure-store and journal users bind exported key bytes to origin, account, vault and key identity. mod.rs[LN5T]: F:Defines the native encrypted sync wire modules and types of transport, conflict and cryptographic failures | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs | A:Error, Result | S:Scheduling and retries belong to callers. The wire layer does not apply downloaded documents. -transport.rs[IN8L]: F:Implements capability-checked encrypted sync HTTPS, OAuth, conditional snapshot requests and prepared idempotent mutations | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs, code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:snapshot | S:Credentials are origin-bound and capabilities must match configured OAuth identity. After uncertain completion preserve the exact prepared write for receipt lookup or retry. -types.rs[LN7L]: F:Defines strict v1 revision, identity, key, snapshot and operation wire types and canonical serialization | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs, code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/crypto.rs | A:Revision, EncodedBytes, SnapshotUpload, ErrorBody | S:Large revisions travel as canonical strings. Reject duplicate JSON keys and noncanonical encodings before authenticated metadata is used. +transport.rs[IN8L]: F:Implements capability-checked encrypted sync HTTPS, OAuth, conditional snapshots and idempotent prepared mutations | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs | A:snapshot,metadata | S:Credentials are origin-bound and capabilities must match OAuth identity. Preserve exact uncertain writes for receipt reconciliation. V1 addresses one vault and rejects unnegotiated collection capabilities. +types.rs[LN7L]: F:Defines strict v1 wire identities, revisions, snapshots and canonical JSON validation for authenticated sync data | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs | A:Revision,EncodedBytes,SnapshotUpload,validate_secret_json | S:Large revisions use canonical strings. Reject duplicate keys, depth and size overflow before authenticated metadata is used; secret validation erases its temporary tree. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/crypto/=== tests.rs[TS5M]: F:Checks independent KDF and ciphertext vectors, fresh randomized packets and failure on altered authenticated inputs | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/crypto.rs | A:independent_reference_argon2_libsodium_vectors_match_every_byte, wrong_nonce_length_and_permuted_aad_never_authenticate | S:Known-answer primitive vectors complement wire-profile interoperability checks. @@ -483,18 +484,19 @@ tests.rs[TN4S]: F:Tests canonical sync wire values, strict null and metadata rul ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/=== capture.rs[PD7M]: F:Captures coherent Core repositories and native extensions, exports documents and applies scoped baseline tombstones | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs, code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/export.rs | A:capture_readonly, capture_native, baseline_locked | S:Check generation around a read-only capture and require an exclusive permit for transactional capture. Failures expose stage and code only. extensions.rs[LS5T]: F:Defines the protected sync extension store for device values, scoped state and journal encryption | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/local.rs | A:DeviceExtensionKey, ProtectedExtensionStore | S:Scope state is keyed by origin, owner, vault and device. Journal protection requires a key from native secure storage. -gate.rs[MD8L]: F:Controls per-directory mutation and exclusive restore permits, persistent generations, write events and recovery fencing | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs, code:openless-all/app/crates/openless-core/src/persistence.rs | A:SyncWriteGate, open_for_data_dir, begin_mutation, MutationPermit | S:Permits survive asynchronous work without holding the mutex across await. A symlink into another managed root cannot borrow the current permit. +gate.rs[MD8L]: F:Controls per-directory mutations, exclusive restore permits, persistent generations, change events and recovery fencing | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs,code:openless-all/app/crates/openless-core/src/persistence.rs | A:SyncWriteGate,open_for_data_dir,begin_mutation,MutationPermit | S:Permits survive async work without holding mutexes across await; symlinks cannot borrow another root's permit. A missing generation counter over full or limited owned state requires recovery, while foreign decoy files do not prevent first initialization. journal.rs[PR7S]: F:Stores and loads bounded encrypted crash journals and reconciles their file lifecycle with the write gate | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/restore.rs | A:FileJournalStore, load, clear | S:Look up a journal by scope. Malformed or mismatched persisted state fails closed with recovery required. mod.rs[AS8L]: F:Connects encrypted restore and capture to Core repositories, native migration state, journal and host runtime effects | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/native.rs | A:CoreSyncStore,bind_runtime_effects,begin_runtime_restore | S:Keep runtime admission fenced through repository and host-effect convergence. Failed or missing effects cannot certify a successful restore. native.rs[PD7L]: F:Preflights and materializes validated sync documents into native stores and restores local-only rollback metadata | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs | A:preflight_native,replace_native,restore_local_rollback_state | S:Preflight all replacements before any write. Cloud flags cannot invent local recording availability, and imported device paths cannot activate runtime permissions. state.rs[PD5T]: F:Encodes scoped sync extension state and derives its opaque storage identity | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/extensions.rs | A:ScopeState, decode, scope_id | S:A missing scope starts empty. Invalid persisted state or a binding mismatch requires recovery. -tests.rs[TS5L]: F:Exercises native encrypted sync repository capture, mutation fencing, rollback and extensions with isolated data stores | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs | A:Fixture,every_preference_save_preserves_top_level_and_nested_unknown_values | S:Restore retains local media availability and preserves allowed unknown preference values. +tests.rs[TS5L]: F:Exercises native encrypted sync capture, mutation fencing, rollback and protected extensions with isolated stores | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/mod.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/limited_tests.rs | A:Fixture,every_preference_save_preserves_top_level_and_nested_unknown_values | S:Restore retains receiver-local media availability and allowed unknown preferences. Limited-policy tests reuse the real shared gate and runtime-effects fixture. +limited_tests.rs[TS6L]: F:Exercises limited local export, whitelisted restore, conflict rejection, exclusive mutation fencing and encrypted rollback and recovery | R:code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs,code:openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs | A:seeded,facade,limited_partial_failure_uses_existing_encrypted_rollback_and_recovery | S:Fixtures use canonical channel records and actual installed style identity. Tests retain unrelated private data and reject unconfirmed collisions; no remote limited transport is exercised. ===/Users/lvbaiqing/project/openless/openless-all/app/crates/openless-core/src/experimental_asr/=== 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 +755,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. @@ -876,7 +878,7 @@ android-insert-tier-fallback-contract.test.mjs[TU4S]: F:Checks ordered Android n android-ipc-import-boundary.test.mjs[TQ4T]: F:Checks that Android permission UI imports platform operations from the narrow Android IPC module | R:code:openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx | A:moduleFor | S:The shared IPC barrel is forbidden at this boundary. android-overlay-never-contract.test.mjs[TU4T]: F:Checks that disabling Android overlays also hides and refreshes vocabulary cards across processes | R:code:openless-all/app/android/kotlin/OpenLessAccessibilityService.kt | A:- | S:Never mode blocks existing card display as well as future overlay creation. android-ui-verify.ps1[XQ4T]: F:Optionally retrieves an Android debug APK, installs it on a connected device and captures local screenshots and logs | R:code:.github/workflows/android-apk.yml | A:Require-Command, Capture-Screen | S:Requires an active adb device. SkipBuild uses an existing local APK. -audio-cue-runtime.test.mjs[TH5S]: F:Simulates browser audio contexts and time to check cue resume, recreation, interruption and stop boundaries | R:code:openless-all/app/src/features/capsule/AudioCue.tsx | A:FakeContext, tick | S:Late recovery cannot replay a cue whose original stop boundary passed. +audio-cue-runtime.test.mjs[TH5M]: F:Simulates audio contexts and time to verify playback recovery, interruption, stop and disposal boundaries | R:code:openless-all/app/src/lib/audioCue.ts | A:FakeContext,tick | S:Late resume cannot replay a superseded cue. Completion, disabled ownership and unmount close output; stopped and late requests retain their original time boundary. audio-cue-window-contract.test.mjs[TH3T]: F:Checks that only the resident capsule window listens for and cleans up recording cue events | R:code:openless-all/app/src/app/windowRoutes.tsx | A:- | S:- audit-harmony-ipc.mjs[XQ4T]: F:Scans static frontend commands and Rust or ArkTS dispatchers to produce or check the Harmony IPC audit | R:code:openless-all/app/harmony/ipc-audit.json | A:- | S:Check mode compares the snapshot without rewriting it. Dynamic calls and event subscriptions are outside its scan. bailian-protocol-h5.mjs[XQ4S]: F:Runs an isolated browser fixture for Bailian provider protocol form interactions and blocked changes | R:code:openless-all/app/src/features/providers/BailianProtocolField.tsx | A:- | S:Uses a temporary source fixture and Chrome instance and removes them after the action checks. @@ -885,7 +887,7 @@ build-harmony-backend.sh[OV5T]: F:Cross-compiles the Rust host for arm64 Harmony build-harmony-frontend.sh[OV6S]: F:Builds and stages the Harmony WebView and native assets into a disposable Hvigor project and optionally signs the HAP | R:code:openless-all/app/scripts/build-harmony-backend.sh, code:openless-all/app/harmony/entry/src/main/module.json5 | A:- | S:Apply optional manifest and resource changes only in the staged build copy. Signing requires available certificate and profile material. build-mac.sh[OV6S]: F:Builds, validates and optionally installs the architecture-selected macOS Tauri app and DMG | R:code:.github/workflows/release-tauri.yml | A:- | S:Retain Cargo caches when replacing deliverables. INSTALL=0 avoids replacing the installed app or resetting its permission state. build-mobile-rime.py[OV6M]: F:Builds pinned librime and shared dictionary assets for Android and HarmonyOS in external staging | R:code:openless-all/app/mobile-ime/CMakeLists.txt | A:fetch, build, main | S:Android packaging needs the matching C++ runtime beside the native libraries. Both hosts consume the same pinned dictionary data. -capsule-ready-replay.test.mjs[TU5L]: F:Exercises capsule replay, readiness, subscription ordering, retries, cleanup and mirror isolation with extracted frontend logic | R:code:openless-all/app/src/features/capsule/Capsule.tsx | A:compileStandalone | S:Re-execute the production listener logic in a controlled script context so stale or failed subscriptions are observable. +capsule-ready-replay.test.mjs[TU5L]: F:Exercises capsule replay ordering, bounded readiness retries, mirror isolation and owned cue subscriptions and teardown | R:code:openless-all/app/src/features/capsule/Capsule.tsx,code:openless-all/app/src/features/capsule/AudioCue.tsx | A:compileStandalone,eventBus | S:Runs extracted production listener logic. Mirror events cannot drive the primary cue; mounting opens no output and only its owner disposes output. capsule-style-label-contract.test.mjs[TL3T]: F:Checks each locale defines a Classic capsule style name without repeating the product name | R:code:openless-all/app/src/i18n/en.ts | A:- | S:- check-android-updater-pubkey.mjs[TV4T]: F:Verifies that the Android updater public verification key matches shared Tauri configuration | R:code:openless-all/app/src-tauri/src/android/updater_logic.rs | A:- | S:Missing or divergent declarations fail before packaging. check-command-event-baseline.ps1[TM5S]: F:Validates observed commands and events against the compatibility inventory and canonical Core fixture | R:code:docs/linux-egui-command-event-baseline.json, code:openless-all/app/contract/backend-2.0.json | A:Assert-CamelCaseObjectFields | S:Checks fixture cardinality and camelCase wire fields as well as names and enum values. @@ -904,7 +906,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 +1012,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 +1030,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:- @@ -1040,7 +1042,7 @@ verify-harmony-hap.sh[TV5T]: F:Validates package metadata, native library and ve verify-linux-egui-packages.sh[TV5T]: F:Checks Linux egui DEB and RPM checksums, executable dependencies, desktop metadata, and installed Fcitx addon files. | R:code:openless-all/app/scripts/package-linux-egui.sh | A:CARGO_TARGET_DIR | S:Validate the staged artifacts directly without a GUI or AppImage. verify-release-ci.mjs[TV5T]: F:Validates a complete CI job report for the release source and requires macOS, Windows, and Android gates. | R:code:openless-all/app/scripts/verify-release-ci.test.mjs | A:verifyReleaseCi; REQUIRED_RELEASE_GATES; report path | S:Reject a partial job list even if it happens to include all named gates. verify-release-ci.test.mjs[TV4T]: F:Tests release CI acceptance logic for required platform checks, incomplete reports, and unsuccessful jobs. | R:code:openless-all/app/scripts/verify-release-ci.mjs | A:- | S:- -voice-edit-open-dispatch-contract.test.mjs[TU5T]: F:Checks main-window authorization and Windows dispatch for opening the Voice Edit webview. | R:code:openless-all/app/src-tauri/src/commands/voice_edit.rs | A:- | S:Reject invalid callers before creating the window. A source assertion cannot prove native message-loop liveness. +voice-edit-open-dispatch-contract.test.mjs[TU5T]: F:Checks main-window authorization, Windows blocking-task dispatch and non-Windows synchronous Voice Edit opening | R:code:openless-all/app/src-tauri/src/commands/voice_edit.rs | A:openCommand | S:Reject callers before creating a window and propagate worker errors. Source assertions cannot prove native event-loop liveness. windows-build-gnu.ps1[OV5S]: F:Builds Windows GNU Tauri in a source mirror, prepares both TSF IME architectures, and gathers executable and installer outputs. | R:code:openless-all/app/scripts/windows-ime-build.ps1 | A:MirrorRoot; ArtifactsRoot; KeepMirror | S:Installer inputs include explicit x64 and x86 IME DLL paths. Mirror cleanup checks the resolved location. windows-capsule-lifecycle-smoke.ps1[TU5M]: F:Injects dry-run Windows dictation hotkeys and checks native capsule window visibility before start, during recording, and after stop. | R:- | A:ExePath; TimeoutSeconds | S:Send an extra stop only when logs show an extra dry-run session; otherwise it could hide a single-session regression. windows-capsule-watch.ps1[XU3T]: F:Samples the OpenLess Capsule native Windows window and prints visibility transitions during manual dictation. | R:- | A:DurationSeconds | S:- @@ -1085,6 +1087,8 @@ macos-artifact-acceptance.swift[TQ5S]: F:Runs isolated CI macOS acceptance on an macos-initialized-style-acceptance.py[TB5T]: F:Verifies initialized openless.intent-reconstruction style pack 1.3.0 in Application Support matches Core canonical rules | R:code:openless-all/app/crates/openless-core/src/style_packs.rs,code:openless-all/app/crates/openless-core/src/builtin_styles/intent-reconstruction-shared-v1.md | A:- | S:Requires CI=true; asserts prompt equals selectionPrompt and contains DICTATION_REVISION_RULES exactly once. runtime-notification-contract.test.mjs[TI5T]: F:Tests Android runtime notification wording, IME foreground lease calls, and isolated debug manifest merging | R:code:openless-all/app/scripts/copy-android-scaffolding.mjs,code:openless-all/app/android/kotlin/OpenLessRuntimeService.kt | A:- | S:Asserts idempotent mergeRuntimeServiceDebugManifest across LF and CRLF inputs and verifies no unrelated service classes leak into the test manifest. windows-artifact-acceptance.ps1[TQ5S]: F:Runs isolated CI Windows acceptance on an NSIS installer via UIAutomation, verifying onboarding, Ask disabled, and About version | R:code:openless-all/app/scripts/windows-ime-install-smoke.ps1,code:openless-all/app/scripts/beta2-artifact-source.py | A:Get-Tree,Wait-Content,Press,Capture | S:Requires CI=true; delegates install to windows-ime-install-smoke.ps1 and always runs silent uninstall in finally. +audio-cue-listener-contract.test.mjs[TH4T]: F:Checks lazy cue output, primary capsule ownership and disabled-preference disposal in the production listener | R:code:openless-all/app/src/features/capsule/AudioCue.tsx | A:- | S:Mounting must not prime the audio device. +voice-edit-window-open-contract.test.mjs[TU5T]: F:Checks Voice Edit open authorization, worker and host error propagation and settings busy and error presentation | R:code:openless-all/app/src-tauri/src/commands/voice_edit.rs,code:openless-all/app/src/features/input/SelectionWorkspaceSection.tsx | A:- | S:Source checks do not establish installed native-window acceptance. ===/Users/lvbaiqing/project/openless/openless-all/app/scripts/linux-fcitx5-plugin/=== CMakeLists.txt[FV5S]: F:Configures the Linux Fcitx5 OpenLess addon, its Wayland selection protocol bindings, installation, and contract test executables. | R:code:openless-all/app/scripts/linux-fcitx5-plugin/openless.cpp,code:openless-all/app/scripts/linux-fcitx5-plugin/protocols/ext-data-control-v1.xml | A:openless module target; hotkey_match_contract; input_target_contract | S:Declare both C and CXX because wayland-scanner emits a C translation unit that must be linked into the module. @@ -1120,7 +1124,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. @@ -1165,9 +1169,9 @@ capsule_mirrors.rs[IU6L]: F:Chooses the capsule display and manages native capsu capsule_snapshot.rs[DU7L]: F:Stores revisioned capsule payload and transcript state for faithful replay independently of Tauri window lifetime. | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/capsule_mirrors.rs | A:CapsuleSnapshotState,claim_ask,record_backend_event,expire_terminal_capsule | S:A pending revision is not a rendered payload. Reject mismatched revisions or session identity and expire only the committed presentation. cli.rs[CE3T]: F:Re-exports the shared Core CLI intent parser and types for Tauri callers. | R:- | A:parse_cli_intent; CliIntent | S:- 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.rs[AG8L]: F:Assembles Core host ports, native lifecycle, shortcuts, auxiliary windows and service-usage notifications | R:code:openless-all/app/src-tauri/src/tauri_coordinator_host.rs,code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs | A:Coordinator,backend,present_core_capsule,start_hotkey_supervisors_when_ready | S:Core owns business sessions and supervisors use committed registrations. Usage events carry no payload and follow persistence changes. Restore capsule hit testing after auxiliary cards hide. Overlay panel failure cannot turn an already consumed recording into retryable capture. 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. @@ -1177,7 +1181,7 @@ global_hotkey_runtime.rs[RH6S]: F:Owns the process-wide global-hotkey manager an hotkey.rs[IH7L]: F:Captures global native shortcut edges with macOS event taps and Windows keyboard hooks and handles modifier-only and companion arbitration. | R:code:openless-all/app/src-tauri/src/ask_window/hotkey.rs,code:openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs | A:Native hotkey monitor and edge types | S:Retain physical press, release, and cancel identity so held modifiers and aborted companion chords do not produce an extra dictation action. insertion.rs[IH7L]: F:Implements platform text delivery, clipboard copy fallback, native paste keystrokes, and delayed clipboard restoration. | R:code:openless-all/app/src-tauri/src/core_adapters.rs,code:openless-all/app/src-tauri/src/android/insert.rs | A:TextInserter,InsertStatus | S:Wait for slow paste consumers before restoring clipboard state. Fence pending restores so older deliveries cannot overwrite newer clipboard contents. issue1266_debug.rs[RO6L]: F:Captures feature-gated Windows hang-diagnostic dispatch and queue observations with a distinct asynchronous sink. | R:code:openless-all/app/scripts/windows-hang-diagnostics-contract.test.mjs,code:openless-all/app/src-tauri/src/tauri_coordinator_host.rs | A:initialize; Probe; ATTEMPT | S:Producers never serialize, wait for capacity, use the normal logger, or write files. Keep operation context local to the executing thread. -lib.rs[EG9L]: F:Bootstraps Tauri, Core services, desktop windows, scoped Ask/read-permission commands, tracing and shutdown | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/commands/mod.rs,code:openless-all/app/src-tauri/src/ask_window/chat.rs | A:run,run_desktop,app_invoke_handler_desktop | S:Dispatch PDF-worker mode before Tauri and enforce Ask window-label restrictions, including main-only read-permission settings. Main dictation tracing requires a desktop debug build and OPENLESS_MAIN_DICTATION_TRACE=1; release Dev bundles do not enable it through this environment flag. +lib.rs[EG9L]: F:Bootstraps Tauri, Core services, desktop windows, scoped Ask and permission commands, tracing and shutdown | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/commands/mod.rs,code:openless-all/app/src-tauri/src/ask_window/chat.rs | A:run,run_desktop,app_invoke_handler_desktop,show_voice_edit_window | S:Dispatch PDF-worker mode before Tauri and enforce window-label restrictions. Main dictation tracing requires desktop debug plus OPENLESS_MAIN_DICTATION_TRACE=1. Voice Edit creation and dispatch errors propagate; successful dispatch does not prove a visible macOS panel. llm_gemini.rs[CB3T]: F:Re-exports the shared Gemini LLM provider for Tauri modules. | R:code:openless-all/app/crates/openless-core/src/llm_gemini.rs | A:- | S:- macos_capsule_input.rs[IU6S]: F:Updates native macOS capsule mouse passthrough using measured action regions from the corresponding webview. | R:code:openless-all/app/src-tauri/examples/capsule-interaction.rs,code:openless-all/app/src/features/capsule/Capsule.tsx | A:InputRect; capsule input region commands | S:Allow only capsule and capsule mirror labels and ignore transparent and transcript areas outside action controls. macos_card_panel.rs[IU6S]: F:Constructs disposable native Tauri card NSPanels while preserving Tao delegate and event behavior. | R:code:openless-all/app/src-tauri/src/desktop_resources.rs | A:CardInitializer | S:Install panel initialization before AppKit KVO, delegate, or webview setup. Reclassifying an initialized Tao window can abort on destruction. @@ -1197,12 +1201,12 @@ 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. style_zip_transfer.rs[ID5T]: F:Routes style ZIP export to an Android content URI or a filesystem target while leaving encoding to Core. | R:code:openless-all/app/src-tauri/src/commands/style_packs.rs | A:export_zip | S:A SAF content URI is a document handle, not a local path. -tauri_coordinator_host.rs[IG8L]: F:Owns Tauri application handles, managed state, main-thread dispatch, and native capsule, rail, and auxiliary window operations | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/capsule_hit_test.rs,code:openless-all/app/src-tauri/src/capsule_mirrors.rs | A:TauriCoordinatorHost,apply_capsule_payload,native window ports | S:Keep native handles out of the shared backend. Capsule input, geometry, and window operations belong on the native host; Classic translation picker sits in hit rect above the click-through transcript rail. +tauri_coordinator_host.rs[IG8L]: F:Owns Tauri handles, managed state, main-thread dispatch and native capsule, rail and auxiliary-window operations | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/capsule_hit_test.rs,code:openless-all/app/src-tauri/src/capsule_mirrors.rs | A:TauriCoordinatorHost,apply_capsule_payload,show_voice_edit | S:Keep native handles outside Core. Capsule geometry and hit testing belong to the host; Classic translation controls remain above the click-through rail. Voice Edit opening returns missing-handle, creation and dispatch errors to callers. tauri_events.rs[IM7L]: F:Bridges Core events into React and native capsule presentation while sampling main-caption delivery diagnostics | R:code:openless-all/app/src-tauri/src/coordinator.rs,code:openless-all/app/src-tauri/src/capsule_snapshot.rs | A:start | S:Recover snapshots after receiver lag and retain newer capsule ownership. Emitting backend:event is only host delivery; trace success does not establish WebView acceptance or rendering. tls_crypto.rs[RS5T]: F:Installs the process-wide Rustls cryptographic provider before constructing desktop or mobile network clients. | R:code:openless-all/app/src-tauri/src/lib.rs | A:install_tls_crypto_provider | S:Repeated setup leaves an existing default provider intact. types.rs[CG4T]: F:Re-exports Core Android and shared host contract types for Tauri compatibility. | R:- | A:android_types; shared_types | S:- @@ -1301,7 +1305,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 +1316,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. +voice_edit.rs[EU6S]: F:Exposes Voice Edit presentation, recording finalization, guarded commit and state commands through 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:Only main may open the panel. Windows creates it in a blocking task; other platforms keep a synchronous entry. Propagate opening failures without starting a session. +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,8 +1330,8 @@ 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. -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. +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,start,commit | S:Fence async results by originating session and reserve commits before native writes. Preserve insertion outcomes; Android recovery presentation cannot replace the original commit error. ===/Users/lvbaiqing/project/openless/openless-all/app/src-tauri/src/host_document/=== macos.rs[IH7L]: F:Implements bounded macOS AX document probes, edit observation, Voice Edit targets, and native streaming text delivery. | R:code:openless-all/app/src-tauri/src/host_document/mod.rs,code:openless-all/app/src-tauri/src/ask_window/target/macos.rs | A:AX FFI,native document and edit adapters | S:Set AX messaging timeouts and check secure input, editor identity, and baseline before reading or writing. Observe selected ranges separately from whole document text. @@ -1354,7 +1358,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 +1527,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:- @@ -1645,8 +1649,8 @@ usage.ts[DA5T]: F:Shares service-usage snapshots through subscribed change inval GithubLoginModal.tsx[AI6M]: F:Runs the shared marketplace GitHub device login UI, shows the code and browser steps, and polls until authorization or expiry. | R:code:openless-all/app/src/lib/ipc/github-oauth.ts,code:openless-all/app/src/ui/overlays/Modal.tsx | A:GithubLoginModal | S:Fence begin and poll responses by the active modal generation. Keep the content height consistent across authorization phases. ===/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. +AudioCue.tsx[AU5T]: F:Observes owned capsule state and preferences and lazily plays recording-start cues on supported runtimes | R:code:openless-all/app/src/api/dictation.ts,code:openless-all/app/src/lib/audioCue.ts | A:AudioCueListener | S:Only primary capsule owns playback. Never open audio on mount; newer preference events beat initial reads. Disabling or unmounting disposes pending resumes and output. +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. @@ -1700,7 +1704,7 @@ MicrophoneSelect.tsx[AU6S]: F:Presents microphone choices with a live level indi PermissionsSection.tsx[AU6L]: F:Renders platform permissions, hotkey/IME and connectivity state with passive entry checks and explicit recovery actions | R:code:openless-all/app/src/api/permissions.ts,code:openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx | A:PermissionsSection | S:Wait for platform capabilities and read permissions once per entry. Ordinary focus does not re-probe the microphone; only explicit System Settings return does. Discard unmounted results. RecordingInputSection.tsx[AU7L]: F:Composes microphone, voice activation, capsule, and text insertion configuration surfaces with native device and preference integration. | R:code:openless-all/app/src/features/input/MicrophoneSelect.tsx,code:openless-all/app/src/features/input/AudioDspSettings.tsx,code:openless-all/app/src/data/preferences.tsx | A:RecordingInputSection,RecordingSurface | S:Own device subscriptions in one mount and keep secondary capsule and text configuration separate from active microphone capture controls. SelectionWorkspaceExtraControlsDialog.tsx[AU5M]: F:Collects advanced selection workspace intent routing, edit-plan, and prompt configuration in a settings modal. | R:code:openless-all/app/src/features/input/SelectionWorkspaceSection.tsx | A:SelectionWorkspaceExtraControlsDialog | S:Keep advanced editing in the dialog and persist each field through shared preference updates. -SelectionWorkspaceSection.tsx[AU5S]: F:Presents selection polish and selection voice workspace settings, capability gating, shortcut and advanced dialog entry. | R:code:openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx,code:openless-all/app/src/components/ShortcutRecorder.tsx | A:SelectionWorkspaceSection | S:Keep advanced prompt editing out of the primary section. +SelectionWorkspaceSection.tsx[AU5S]: F:Presents capability-gated selection polish and voice settings, shortcuts, advanced controls and Voice Edit opening feedback | R:code:openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx,code:openless-all/app/src/api/voice-edit.ts | A:SelectionWorkspaceSection,openPanel | S:Keep advanced prompts in the separate dialog. An in-flight open disables the button and failures remain visible instead of becoming unhandled promises. ShortcutsSection.tsx[AU7M]: F:Lists and records shortcuts with shared sliding category/status filters, native save policies and per-style hotkeys | R:code:openless-all/app/src/components/ShortcutRecorder.tsx,code:openless-all/app/src/api/hotkeys.ts,code:openless-all/app/src/ui/controls/Segmented.tsx | A:ShortcutsSection | S:Use command-specific save policies and refresh preferences after native changes. Active dictation and ordinary action bindings have different capability gates. VocabularyLearningSection.tsx[AU5S]: F:Edits vocabulary learning enablement, observation duration, and suggestion thresholds through shared preferences. | R:code:openless-all/app/src/data/preferences.tsx | A:VocabularyLearningSection | S:Bound displayed numeric controls and prevent overlapping saves. useMicrophoneAccess.ts[AS5T]: F:Manages platform-aware microphone permission reads, explicit access requests, system settings handoff, and return-focus rechecks | R:code:openless-all/app/src/api/permissions.ts,code:openless-all/app/src/runtime/platform.ts | A:useMicrophoneAccess | S:Passive reads never prompt or open Settings; awaits getPlatformCapabilities before branching to Android vs desktop permission APIs and discards stale revisions. @@ -1820,7 +1824,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. @@ -1896,7 +1900,7 @@ activityMetrics.ts[KA6T]: F:Builds dated overview period buckets and totals from advancedAsrConfig.ts[CB5T]: F:Parses and serializes advanced generic OpenAI-compatible and ZenMux ASR settings. | R:code:openless-all/app/src/features/providers/ProvidersSection.tsx | A:AdvancedAsrConfig; parseAdvancedAsrConfig; serializeAdvancedAsrConfig | S:Invalid or missing fields select conservative defaults shared with the native parser. appVersion.ts[CV5T]: F:Exposes manifest version labels, development and beta classification, and detection of a switch to stable. | R:code:openless-all/app/package.json | A:APP_VERSION,APP_VERSION_LABEL,IS_DEV_BUILD,IS_BETA_BUILD,isStableChannelSwitch | S:Development prerelease builds do not display the Beta badge. assistantText.ts[KU6S]: F:Plans streamed text glyph reveals and adjusts wrapping for prose tails using grapheme-aware segmentation and DOM ranges. | R:code:openless-all/app/src/lib/insertTextAnimation.ts,code:openless-all/app/src/features/qa/chat/markdown.tsx | A:keepProseTailsTogether; planTextReveal; mountTextReveals | S:Use native wrapping on older webviews without grapheme support so a cluster is not broken. Cancel outstanding animations on teardown. -audioCue.ts[RH6M]: F:Synthesizes and schedules a two-tone recording start cue through a reusable Web Audio context. | R:code:openless-all/app/src/features/capsule/AudioCue.tsx | A:playRecordStartCue; stopAudioCue; primeAudioCue | S:A resolved resume is insufficient if audio time still cannot run. Recreate once, avoid scheduling an obsolete cue, and never block recording on cue failure. +audioCue.ts[RH6M]: F:Lazily synthesizes recording-start tones and manages bounded audio-context recovery and disposal | R:code:openless-all/app/src/features/capsule/AudioCue.tsx | A:playRecordStartCue,stopAudioCue,disposeAudioCue | S:Resume success is insufficient if the audio clock stalls. Retry recreation once, discard superseded or late requests and never block recording. Close output after the cue tail or disposal. audioDsp.ts[FC4T]: F:Defines frontend capture DSP defaults, stage order, equalizer presets, and frequency band labels. | R:code:openless-all/app/src/features/input/AudioDspSettings.tsx | A:defaultAudioDsp; audioEqualizerPresets; equalizerFrequencies | S:- backendEvent.ts[CM7M]: F:Defines frontend backend event and transcript snapshot types and reduces sequenced deltas into session-scoped text state. | R:code:openless-all/app/src/features/capsule/LiveTranscriptPill.tsx,code:openless-all/app/src-tauri/src/capsule_snapshot.rs | A:BackendEvent,TranscriptDelta,TranscriptSnapshot,applyTranscriptEvent,shouldRetryTranscriptSnapshot | S:Apply offsets by Unicode code point and ignore wrong-session or out-of-order deltas. Do not count the normal starting and recording pair as two generations. bailianProtocol.ts[CB5T]: F:Validates and edits the Bailian ASR protocol field in a shared JSON credential config. | R:code:openless-all/app/src/features/providers/BailianProtocolField.tsx | A:bailianProtocols; readBailianProtocol; writeBailianProtocol | S:Automatic mode removes its field while preserving unrelated advanced config. @@ -2262,8 +2266,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 +2956,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 +2989,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. @@ -2999,6 +3003,7 @@ sync-v1-compatibility.md[SD6S]: F:Defines the encrypted sync v1 client extension web-search.md[SN5S]: F:Documents free aggregated search (FreeSerp/Keenable), DeepSeek hybrid search, and UI config fixes | R:code:openless-all/app/crates/openless-core/src/web_search.rs,code:openless-all/app/src/features/settings/sections/webSearchConfig.ts | A:FreeSerp,Keenable,DeepSeek | S:Preserves per-provider configs across switches and merges duplicate URLs across providers before capping at 5. webview-security.md[SS6T]: F:Documents the desktop Tauri WebView Content Security Policy directives and allowed origins | R:code:openless-all/app/src-tauri/tauri.conf.json | A:CSP | S:Restricts script-src to self and blocks object-src, base-uri, form-action, and frame-ancestors. windows-diagnostics.md[SO4T]: F:Documents Windows hang/silent-exit diagnostic logging and issue1266_health probe | R:code:.github/workflows/release-tauri.yml | A:issue1266_health | S:Logs append to %TEMP%/openless-issue-1266-2e2c7a47-session.ndjson. +ask.md[SB7T]: F:Specifies desktop Ask admission, intent routing, native delivery, attachment validation and cancellable assistant tools | R:code:docs/ask-assistant-rewrite-contract.md,code:openless-all/app/src-tauri/src/ask_window/chat.rs | A:Open and submit,Native target and delivery,PromptBox | S:Expected native targets and one-shot claims stay host-owned. Uncertain writes are retained, never retried automatically; external material is untrusted data. ===/Users/lvbaiqing/project/openless/docs/development/evidence/=== style-diagnostic-45057806632.json[SQ3T]: F:Records CI DeepSeek style-diagnostic HTTP 401 run evidence for commit 4d450e6e | R:code:docs/development/official-style-packs.md | A:LIVE_HTTP,LIVE_ERROR,LIVE_STYLE | S:Single bounded HTTP request; platform CI skipped. @@ -3022,3 +3027,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/ATTRIBUTION.md b/docs/ATTRIBUTION.md index 75f214232..1bfe30bb5 100644 --- a/docs/ATTRIBUTION.md +++ b/docs/ATTRIBUTION.md @@ -17,3 +17,17 @@ Rare UI Password Input is the visual reference for OpenLess's shared input field ## Rare UI Toast The shared toast surface adapts Rare UI's Toast panel, glyphs, and tile transitions from [toast.tsx](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/toast.tsx) (Copyright (c) 2026 Swami Malode, [MIT + Commons Clause + Attribution](../openless-all/app/public/licenses/rare-ui-LICENSE.txt)). OpenLess uses its existing per-window notification controller and viewport instead of Sonner's global store. `useToast()` exposes non-modal variants and task updates; `confirm`, `warn`, and `openDialog` remain separate modal APIs. The credit appears in Settings → About and updates → Component credits. + +## Rare UI AI Prompt Box and Streaming Response + +[AI Prompt Box](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/prompt-box.tsx) and +[Streaming Response](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/streaming-response.tsx) are the +interaction references for OpenLess Ask Anything. The OpenLess implementation uses +its own native shortcut, voice, and streaming contracts rather than the demo's mock backend. + +The upstream Prompt Box files in `openless-all/app/third_party/rare-ui` come from +[`33f7ce51`](https://github.com/swamimalode07/rare-ui/tree/33f7ce51e5a41fb7caef66b7aad0812b5bb2ab17) +and are included as part of the app, not offered as a component library. + +- Rare UI code: Copyright (c) 2026 Swami Malode, [MIT + Commons Clause + Attribution](../openless-all/app/public/licenses/rare-ui-LICENSE.txt). +- Open Runde fonts: [SIL Open Font License 1.1](../openless-all/app/public/licenses/open-runde-OFL.txt). diff --git a/docs/architecture.md b/docs/architecture.md index 0151902ff..de4b10f2b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,6 +47,8 @@ flowchart LR ### 问答与选区 +桌面独立 Ask 窗口由 [ask-window](../openless-all/app/ask-window/) 与 [原生 Ask 宿主](../openless-all/app/src-tauri/src/ask_window/) 管理。提交、工具、附件及安全写回见[随便问接口](development/ask.md);公开 Beta 的入口是否开放仍取决于[构建标记](development/delivery.md)。 + 桌面问答窗口由 [windowRoutes.tsx](../openless-all/app/src/app/windowRoutes.tsx) 分派。界面发送 `qa_submit_text` 等命令给 [Tauri 问答适配](../openless-all/app/src-tauri/src/commands/qa.rs),由 [Core 问答服务](../openless-all/app/crates/openless-core/src/qa_service.rs) 管理会话、请求和结果事件。[选区语音服务](../openless-all/app/crates/openless-core/src/selection_voice_service.rs) 根据语音意图生成编辑预览或问答,确认写回时由宿主复核原输入目标。Linux 的问答界面经 Linux 宿主调用同一业务层。 系统选区润色/翻译保留完整选中文字,先写入同一历史记录的 `rawTranscript`,再保护原文剪贴板,最后发送完整模型请求。原文、原控件和原范围分别核对;服务拒绝或输出不完整不能替换选区。剪贴板兜底、原位置续接和平台验收边界见[选区全文与原文保护](development/selection-originals.md)。 diff --git a/docs/development/ask.md b/docs/development/ask.md new file mode 100644 index 000000000..644deca9a --- /dev/null +++ b/docs/development/ask.md @@ -0,0 +1,70 @@ +# 随便问:提交、附件与原生写回 + +## 桌面窗口与提交 + +The desktop host validates the invocation and native target. Core owns intent routing, model calls and turn state. The composer and the expanded chat share the same window. + +### Open and submit + +The current recording shortcut plus Space opens or focuses the compact `ask-anything` composer. The same window expands around the composer after an explicit submission resolves to `answer` or `selectionAnswer`. `write`, `edit` and `clarify` stay compact. Expansion requires the matching acknowledged turn and current visibility generation. Replay can reconcile a live submission but cannot expand a dismissed window. Escape dismisses the composer and cancels pending voice input. An accepted turn retains its own cancellation and result lifecycle. + +The recording chord can start voice input after the current composer acknowledges focus. `autoVoiceOnOpen` defaults to `true` and does not apply to opening from Settings. Dictation into Ask only fills the current draft. It does not send automatically. The recording ID, conversation, editor revision and focus generation prevent delayed transcription from editing a different draft. Repeated chords during active recording focus the composer. Each recording controls only its own capsule and audio lifecycle. + +| Route | Result | +| --- | --- | +| `answer` | Answers the question in chat, independent of any incidental selection. | +| `selectionAnswer` | Answers about the relevant verified selection. An explicit reference without a verified selection requests clarification. | +| `write` | Generates new text for a verified collapsed external caret. | +| `edit` | Replaces the verified original selection. A missing selection requests clarification. | +| `clarify` | Requests input in the composer, with no external write. | + +Explicit send prepares the native target and freezes the chosen mode, channel and validated attachments after admission. An identical request ID and payload reuse the original turn. A different payload with the same ID conflicts. Busy work is rejected before another target read. Once chat has expanded, later turns remain in that conversation and use the answer path. The backend reviews output before publishing or delivering it. + +### Settings and routing + +Machine-local `ask-entry-settings.json` stores `{ autoVoiceOnOpen, intentMode }`. A new store and explicit recovery use `{true, separateModel}`. Saved valid selections persist. Turning off the active Beta routing option returns to `semanticHybrid`. The native main window uses `ask_get_entry_settings` and `ask_set_entry_settings`, which return the committed settings or a typed failure. + +- `semanticHybrid` uses local intent signals and asks the main model for a small decision when uncertain. +- `separateModel` makes an isolated classifier request that produces no transcript output. +- `mainModelTool` requires the main model to call the local `resolve_intent` tool and continues that logical conversation with the validated decision. + +Classifier input is limited to the user's instruction and minimal selection or reference signals. Full selection, attachments and conversation history are turn data only where authorized. Invalid or unsupported decisions surface an error and preserve the selected strategy. Web search uses a validated public query. Its indicator follows actual turn-scoped tool activity. + +### Native target and delivery + +On macOS, inserting new text binds to the original eligible caret recorded when Ask opened. Reading or replacing a selection binds to the verified target captured at send. Windows uses its current external target capture. Native capture distinguishes no selection, a verified selection and unavailable evidence. AppKit or UI Automation handles, document fingerprints and write leases stay in the host. Unknown or protected controls are unavailable. Read-only selection may be usable as context and cannot authorize a write. + +Before delivery, the host revalidates the original editor and expected caret or UTF-16 range. A one-shot claim immediately precedes a possible write. Outcomes distinguish a confirmed write, retained result and uncertain write. Never replay an uncertain native write or replace a different control. The full retained result remains copyable in Ask. On macOS, native write failures leave it for manual copy. The Windows path has a separate once-per-turn clipboard fallback. Cancellation before a claim prevents its effect. An already issued write is reported by observation, with no rollback claim. + +### IPC and verification + +`ask-window/client.ts` and the native `ask_window` command and event adapter define the wire. Events and replay are ordered per conversation. The non-chat projection exposes the accepted turn, authoritative route, delivery status and optional retained text. Conversation, turn and attachment identities gate late updates. No external write occurs for answer or clarification routes. + +Check the Core routing, tool and replay tests in `qa_service/standalone/`, the browser Ask specs, and the platform-specific [native target tests](../../openless-all/app/src-tauri/src/ask_window/target/README.md). Installed macOS and Windows acceptance separately covers the shortcut, composer and capsule focus, changing selection, selection answer, caret insert, selection replacement, and a changed editor during generation. + +## 附件、上下文与工具 + +以下约定适用于已接纳的 Ask 回合。 + +### 后端端口与上下文来源 + +- **桌面 App 元数据 → ContextProvider**:在切到 Ask 前冻结显式唤起时的来源 `{ invocationId, capturedAt, foregroundApp?, desktopApps? }`。当前真正接收键盘输入的只有前台对象;后台用可见/最小化窗口所属 App 或已打开的用户 App 元数据表达,按平台能力区分 `unknown`。不把后台当成另一份前台焦点,不读取后台窗口内容、标题、浏览历史或所有进程;不假设能跨虚拟桌面枚举。Ask 已前台的后续轮使用该对话最近一次有效外部来源及时间,不把主窗/胶囊当成用户正在工作的 App。 +- **`ContextProvider`**:按轮提供 `staticInstructions`(固定且版本化)和带 `source/asOf` 的 `facts`,缺失单独标原因。用户“今天在做什么”只来自已授权的本地信息或用户指定的公开检索,搜索不等于能看见本机活动。时间使用设备时钟;天气只查询用户明确给定或授权的地点,保留观测/预报的时间与来源;无地点、禁止搜索或离线时不猜。现有用量记录未提供可用的 Ask 实际金额,首版显示「无数据」,不拿 token 乘现价,也不访问个人账单或外部账户。App/用量范围须有 Ask 专属授权;开启联网、保存历史或操作系统授予可读权限不算授权。被撤销的隐藏事实不能作为后续请求或 Compact 的输入;这不等于抹掉用户已看到的聊天消息。 +- **`SearchTool`**:输入限定为模型 `web_search` 工具调用中的短公开查询和调用 ID,每轮至多一次;全局搜索设置仍可关闭。默认「免费搜索」在客户端合并 FreeSerp 与 Keenable 的免 Key 结果,遵守端点限流,不通过 OpenLess 服务转发。「混合搜索」额外使用用户单独配置的 DeepSeek Search API Key,可能计费;原有 Bing 或支持 JSON 的 SearXNG 地址仍可按需选择。结果通过供应商协议的工具消息返回,不混入普通提示词;私有附件和应用上下文不参与搜索决策。复用超时、网络保护和取消;不把整个 Prompt、历史、选区、附件、账单或 App 清单发给搜索服务。实际发出请求才进入 `searching`,实际读取才进入 `reading`,只有成功取回可用正文才标 `read`。搜索发现的来源和读取状态随活会话回放;部分读取失败不抹掉已发现来源。返回给模型的证据正文有预算,不放进公开事件或额外的持久化记录。模型读取的网页、选区、PDF 与动态事实始终是数据,不是系统指令。 +- **`AttachmentReader`**:按 `{ conversationId, turnId, attachmentIds }` 一次性取得所有已就绪附件的只读引用,解析为选区原文、带真实页码(从 1 开始)的 PDF 文本或经验证的图像。选区完整保留到 4,000 个 Unicode 标量或 16 KiB;预览先显示前 280 个标量,展开看原文,超限提示、不静默截断。大图片优先在本机压缩;保留 48 MiB / 40 MP 的解码保护。PDF 本地处理最多 48 MiB / 100 页 / 512 KiB 提取文本,不上传原件。每轮最多 4 件。可恢复的操作错误复用主界面的弹窗 API。PDF 首版只本地提取有文字层的文档,解析器必须有可中止的资源限制;扫描件、加密、损坏和超限分开报错,不执行脚本、访问外链或做 OCR。图片首版验证 JPG/PNG,通过实际协议和模型能力双重校验后才能发送;能力不明也保留草稿并报告,不探测上传、不换渠道、不当空附件。首版可在内部按页读取,不把页范围放到公开 `submit`。文件使用选取时有界读取的内容,不在发送时重开源路径。结束对话清理临时资源,不自动删除用户原文件或既有 opt-in 历史行;「保存历史」沿用旧的文本记录范围,不新增长期保存附件原件、原文、缩略图或路径。 +- **模型和 Compact**:复用现有 QA 生命周期的所有权检查及供应商底层传输,旧单槽/选区润色接口不直接接新窗口。每轮冻结已配置渠道、模型及能力;不假冒深度思考、视觉和工具支持,不静默切换供应商。固定指令与稳定历史放在前,动态事实和本轮材料放在后;遵守 [现有缓存策略](speech.md#提示词缓存与用量)。**256K 指总窗最多 256,000 tokens**,取与供应商确认的模型限额较小者,再扣除输出、未计入的工具结果和安全余量。未知窗口使用明确的保守限制,不把输出 `max_tokens` 当成总窗;搜索回填后再计量。Compact 只替换模型输入中的旧完整轮次,保留 UI 全量消息和来源、新近完成轮及当前轮。摘要有对话与版本边界,必须完整、更小且在当前轮有效时才替换;过大附件不静默裁剪,压缩失败不修改旧摘要。KV 命中率按 provider 可比实测 `Σ缓存读入 tokens / Σ输入 tokens`,在同服务/渠道/模型/协议内聚合;缺字段显示未知,不写死百分比,不为预热多发请求。按实际调用归档已知用量,不把答复、压缩等多次请求算作同一次;聊天视图可把辅助请求与答复分开。 +- **工具扩展**:聊天核心定义可取消、按 `{ conversationId, turnId, toolCallId }` 跟踪的类型化工具分派接口;常规任务注册 `web_search` 与 `calculator`,主模型工具判定阶段单独开放 `resolve_intent`。提示词优先核实时效性强或易变的公开事实;需要计算时先核实公开输入,再用本地 Rust 计算器。计算器只接受有界的数值表达式,返回精确整数或最简分数及最多 50 位小数,每轮最多三次,关闭联网仍可用;计算结果作为工具消息,不随搜索查询外发。不写锁屏、切用户、开 App 或切换主题的实现,不给模型通用 Shell、系统控制或调用特权。未来的系统操作需独立权限、用户确认及审计契约。 + +### PromptBox 内的附件呈现 + +预览、引用标签和编辑区同属一个 PromptBox。移除附件时同步移除它的引用标签。 + +| 类型 | 框内呈现 | +| --- | --- | +| 图片 | 显示真实图片缩略图,角标如 `#1`,右上角有移除按钮;编辑区前可见对应的「图片 #1」引用标签,光标可以接着输入。图片加载失败时显示原因,不把空白方框当作成功预览。 | +| PDF | 用同一框内样式显示 PDF 图标、文件名和移除按钮,已知时可显示页数;编辑区的引用标签能识别这是哪个 PDF,不冒充图片预览。 | +| 选中文字 | 经提交时验证且本轮确实使用的原文可作为本轮私有材料;不在唤起时自动添加草稿卡片,也不把原文塞进可编辑的问题草稿。普通粘贴不变。 | + +标签是附件的视觉引用,不是发给模型的字面文本;提交仍用 `attachmentIds`。卡片与标签指向同一附件,移除后两者同步消失,同时保留草稿与光标。布局可以加高框内内容,但不改变独立窗口尺寸。 + +同一个 PromptBox 边框内提供预览和引用,优先保留原组件自身的边框与样式。拖入图片时只接收浏览器提供的文件内容,不接受或转发本机路径;后端与原生选择器共用验证和登记逻辑。拖放只添加附件,不发送,不打开本地文件网页。纯附件用同一个发送入口;中文输入法选词回车不触发。不显示联网按钮或确认面板。模型调用工具时在答复旁显示 Websearch;完成后仍可查看来源。用户消息下不显示档位标签,开启思考后按钮始终为蓝色。 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/docs/encrypted-cloud-sync-limited-scope.md b/docs/encrypted-cloud-sync-limited-scope.md new file mode 100644 index 000000000..122898874 --- /dev/null +++ b/docs/encrypted-cloud-sync-limited-scope.md @@ -0,0 +1,164 @@ +# Opt-in limited sync domain (SYNC-01/02/04/07/08) + +Status: **local domain/store seam implemented; remote synchronization blocked by the current singleton-vault contract.** This is not iOS, cloud deployment, platform-vault, two-device, or runtime acceptance. No Host/Swift changes are included. + +## Development checkpoint (2026-10-23) + +This unfinished experiment was moved onto Beta `60f67a9b` for a Draft PR. The transfer includes only the limited-sync domain/store implementation, its tests, and this document. Latest Beta local-migration storage and document parsing APIs are retained. Translation-target changes already live in the iOS Core patch and are not copied from the old worktree. + +Remote collection negotiation, authenticated transport, the iOS secure-vault adapter, confirmation metadata/UI, and real two-device acceptance remain unfinished. iOS continues to report `sync_scope_unavailable`; this branch does not enable remote synchronization. Keep the PR in Draft; do not merge this checkpoint. + +### Validation after the Beta transfer + +- `rustup run 1.99.0 cargo test --manifest-path openless-all/app/Cargo.toml -p openless-core --locked --offline --lib cloud_sync_e2ee --no-fail-fast`: compilation succeeded; **200 passed, 6 failed, 1201 filtered out**. +- All six failures occur in the limited-store tests at the shared `seeded()` fixture's full-store restore, with `RestoreRolledBack`, before the limited operation under test. Investigate compatibility with the current Beta restore/fixture contract; do not treat the original worktree's green result as validation of this branch. +- `python3 openless-all/ios/scripts/prepare-core.py`: passed; the existing isolated iOS Core patch still applies. +- `git diff --cached --check`: passed. +- No iOS device build, remote sync, real user-data restore, or two-device acceptance was performed for this checkpoint. + +## Unchanged default + +The desktop `EncryptedSyncConfig`, full service, consent `encrypted-full-snapshot-v1`, v1 wire DTOs/crypto, and full exporter retain their existing behavior. The only production change on the desktop construction path factors the same local-store composition into a shared helper; its root remains `encrypted-sync`. Full export still includes provider credentials, channels, private prompts, history and activity, as before. **Do not enable that service for the limited iOS requirement.** + +`AllowedSyncScope::default()` is `FullSnapshot`. Constructing the limited facade without the explicit `ConfirmedVocabularyModeStyleReferences` permission fails; it never falls back to full export. + +## Public contracts + +Existing public modules export these seams (no root `lib.rs` edit is needed): + +- `cloud_sync_e2ee::{LimitedSyncStore, LimitedSyncExport, SyncAccountProvider, VerifiedSyncAccount}`. +- `cloud_sync_e2ee_documents::{AllowedSyncScope, ConfirmedVocabularySelection, LimitedSyncDocuments, LimitedMergePreview, LIMITED_SYNC_NAMESPACE}`. +- The document module also re-exports its existing public argument types `Revision`, `SourceDevice`, `DocumentSet`, `LogicalDocument`, `Tombstone`, `DocumentKind`; callers no longer need inaccessible protocol-module paths. + +`MarketplaceService::verified_sync_account().await -> Result` reuses the existing verified `/user` identity routine. `github_id() -> &str` returns the canonical positive numeric ID. Serialization is only `{"githubId":"42"}`. There is no public constructor/deserializer, login authority, token accessor, or full-sync enablement. Every call rechecks the stored login token; previously returned values are immutable observations, not cached authorization. + +`SyncAccountProvider::verified_sync_account(&self) -> BoxFuture<'_, Result>` is implemented by `MarketplaceService`. Hosts normally inject the existing `Arc`, or an authority adapter delegating to it. The limited facade verifies the current account before/after capture and before restore. Host account-switch/sign-out orchestration must serialize/cancel its own in-flight operations; this domain facade does not replace that lifecycle. + +`LimitedSyncStore::build(config: EncryptedSyncConfig, data_dir: &Path, repositories: BackendRepositories, credentials: Arc, tasks: Arc, allowed: AllowedSyncScope, accounts: Arc) -> Result` composes **actual Core** local encryption, write gate, protected extension storage and journal backend without constructing the full service or starting network/automatic synchronization. It uses `encrypted-sync-limited-v1`, with its own durable device ID and hence distinct local key AAD, extension and journal identity. A Host selects one policy per repository instance: activity and credential stores bind the exact gate/device identity. Running both factories on the same already-bound repository is not an automatic migration path. Missing device IDs over existing protected ciphertext fail closed via the existing loader. Lost generation-state detection also checks the retained limited root; loss of the shared gate directory cannot silently reset the counter over limited protected state. + +`LimitedSyncStore::new(CoreSyncStore, AllowedSyncScope, Arc) -> DocumentResult` is the custom composition seam. Its injected store must have a dedicated limited-policy local device identity, not the full service's identity. Prefer `build`. + +Other facade methods: + +- `generation() -> DocumentResult`; `device() -> SourceDevice`. +- `bind_runtime_idle_probe(...)`, `bind_runtime_effects(...)`, `is_recovering()`, `recover_registered().await`: delegate to existing Core fences/recovery. Bind real runtime adapters before recovery/restore. +- `export(scope: SyncScope, confirmed: ConfirmedVocabularySelection).await -> DocumentResult`. +- `restore(desired: LimitedSyncDocuments, context: RestoreContext, confirmed: ConfirmedVocabularySelection).await -> DocumentResult`. +- `LimitedSyncExport { generation: Revision, documents: LimitedSyncDocuments }` contains no full snapshot accessor. + +### Confirmation is explicit, not inferred + +There is currently no universal confirmation bit in `DictionaryEntry`. In particular, the exact `LEARNED_VOCAB_NOTE` marker identifies auto-collected provenance, **not user consent**. `ConfirmedVocabularySelection::new(scope, generation, Vec)` takes the Host's explicit confirmed IDs; an empty list means none, never all. It rejects duplicate/invalid IDs and binds the exact origin/account/vault/key/device plus generation. Export/restore reject stale scope/generation (`StalePreview`) and selected IDs missing from that coherent local image (`SourceChanged`). After a local deletion, the Host supplies the remaining live confirmed IDs and materializes deletion marks from the separately protected limited baseline. + +**Required parent/Host work:** durable account/scope-bound confirmation metadata, confirmation UI, atomic/recoverable reconciliation of that metadata after import/deletion, and protected limited baseline persistence. Supplying IDs to this API alone is not completed confirmed-vocabulary synchronization. No ledger is invented in this component. + +## Limited plaintext domain format + +`LIMITED_SYNC_NAMESPACE = "confirmed-vocabulary-mode-style-references-v1"`. + +`LimitedSyncDocuments::to_secret_json() -> DocumentResult>>` emits a bounded **plaintext domain envelope for future authenticated encryption, never an HTTP request body**: + +```json +{ + "manifest": { + "schemaVersion": 1, + "namespace": "confirmed-vocabulary-mode-style-references-v1", + "serviceOrigin": "https://sync.example.test", + "ownerGithubId": "42", + "vaultId": "", + "keyId": "" + }, + "documents": { + "schemaVersion": 1, + "exportedAt": "", + "sourceDevice": {"id":"...","os":"...","arch":"...","appVersion":"..."}, + "documents": [ + {"kind":"dictionary","id":"word-id","schemaVersion":1, + "value":{"id":"word-id","phrase":"confirmed word","enabled":true,"createdAt":"...","sortIndex":0}}, + {"kind":"preferences","id":"defaultMode","schemaVersion":1,"value":"raw"}, + {"kind":"preferences","id":"enabledModes","schemaVersion":1,"value":["raw","light"]}, + {"kind":"preferences","id":"marketStyleReference","schemaVersion":1, + "value":{"id":"builtin.light","version":"2.0.0","originPackId":null}} + ], + "tombstones": [] + } +} +``` + +`marketStyleReference` is null for explicit no-selection, otherwise installed ID/version/optional upstream marketplace `originPackId`. It never carries prompts, examples, icons, model/provider/channel settings, author login, or style contents. No translation-target/private preference expansion is implied. The mode enum is the existing Core enum; duplicate mode entries are rejected. + +The dictionary whitelist is exactly ID, phrase, enabled, createdAt, sortIndex. Notes (including the learned marker), usage counts, and unconfirmed rows are excluded. New remote rows get `note = null`, `hits = 0`; matching local IDs retain their receiver-local note/count. Thus learned provenance is not transferred as implied confirmation; Host metadata integration remains required. Phrase equality across different stable IDs does not silently deduplicate or discard a user's row; existing stable-ID merge semantics remain authoritative. + +`LimitedSyncDocuments::from_authenticated_json(bytes, &scope, observed_revision)` is **post-authenticated-decryption** input, not a decryption/authentication API. The expected scope and revision must come from the future authenticated transport, never the untrusted envelope. Strict duplicate-key/depth/size decoding and manifest equality precede validation. Wrong namespace/schema/origin/account/vault/key and unknown envelope fields fail; all other document kinds, dictionary extension fields, private preferences and preference tombstones fail. Full `DocumentSet` input is not accepted as a limited envelope, nor is the limited envelope accepted by the current full protocol decoder. No migration/downgrade is automatic. + +## Merge, apply, and recovery semantics + +- `local.diff(optional_baseline, remote)` delegates to the existing Core three-way logical merge and returns `LimitedMergePreview` with redacted conflicts. It rejects differing manifests (including account/key); key-rotation baseline migration is not silently guessed. +- `preview.conflicts()` and `preview.resolve(&[ConflictChoice])` preserve the existing explicit-choice rules: stable IDs, no timestamp winner, edit/edit and delete/edit conflicts, missing tombstones rejected. `record_local_deletions(&baseline, deleted_at)` delegates to the existing tombstone ledger, scoped only to previously confirmed limited IDs. Full-snapshot tombstones are never treated as confirmation evidence. +- Restore overlays the selected dictionary IDs and exactly `defaultMode`, `enabledModes`, `activeStylePackId` onto a coherent **local-only full before image**. Every unselected local row and all unrelated preferences/history/activity/styles/channels/credentials are retained. A live remote ID or delete mark colliding with an unselected local row fails before writes. A selected local row omitted without an explicit remote tombstone fails `MissingTombstone` rather than being silently deleted. +- Style selection requires an installed, enabled pack with matching ID/version/origin reference. Missing/mismatched/disabled packs fail `InvalidReference` before writes; the Host may offer the existing marketplace download/verification and then capture a fresh preview. No fallback pack, provider switch, or raw prompt import occurs. This is reference/version identity, not a content-hash guarantee for locally edited packages. +- The final full local image uses existing `CoreSyncStore::restore_scope`: preflight, exact generation, runtime fence, exclusive shared gate, encrypted before/after journal, real runtime effects, complete read-back verification, rollback and startup recovery. It does not perform a sequence of independent settings saves. All settings outside the three whitelisted keys are preserved; the local full image **never becomes a limited remote payload**. +- An intervening ordinary mutation fails the preview generation check (and the existing restore lease checks again after overlay). Once restoring, normal repository/credential mutation permits are blocked. Partial credential/effect failure rolls back; rollback failure retains recovery-required and encrypted material. Wrong recovery keys cannot replay or clear the pending journal. + +## iOS secure-vault requirements (not implemented here) + +Even a limited restore journals/reapplies a complete **local** coherent before/after image to preserve unrelated data. Therefore the actual iOS `CredentialStore` must implement the existing fail-closed hooks, not enable full remote sync or return empty credentials: + +1. `bind_sync_gate`: retain the exact shared gate; reject rebinding to another gate. Every ordinary credential/channel mutation must hold and complete its registered mutation permit through actual asynchronous persistence, including uncertain results. +2. `export_sync_credentials_readonly`: one atomic vault/channel batch; missing/denied vault reads are errors. Core discards a mixed generation rather than exporting it. +3. `export_sync_credentials(&ExclusivePermit)` and `replace_sync_credentials(SyncCredentials, &ExclusivePermit)`: verify permit ownership, operate on the complete registered provider/channel batch, preserve unrelated OAuth/application entries, and surface partial/uncertain failure for the existing rollback/read-back path. Never return success from a no-op implementation. +4. `read_sync_secret`, `write_sync_secret`, `remove_sync_secret`: real app-private Keychain handling for the existing restricted `SyncSecretAccount` names. Local wrapping keys and remembered keys stay out of preference files, keyboard/shared containers, plaintext logs, backups-as-config, and remote payloads. Existing ciphertext with a missing key remains recovery-required; never generate a replacement over it. +5. Bind real runtime idle/effects adapters, recover before ordinary writes/recording, and keep account switch/sign-out serialized with in-flight Host operations. A platform-vault test and real device lifecycle verification remain separate acceptance gates. + +## Why no remote sync method is exposed + +Evidence in current client contract: + +- `cloud_sync_e2ee_protocol/transport.rs` hardcodes metadata `/v1/me/vault`, snapshot `/v1/me/vault/snapshot`, delete `/v1/me/vault`, receipts `/v1/me/operations/{id}`. There is no named collection parameter/header. +- `types.rs` makes `Capabilities` and `SnapshotUpload` strict unknown-field-rejecting DTOs. Snapshot `payloadSchemaVersion` is fixed at 1; capability negotiation does not advertise namespaces. Opaque ciphertext is still stored under the one vault/CAS identity. +- Local mock test `v1_contract_has_a_singleton_vault_and_no_named_scope_capability` records the actual singleton request and rejects an unnegotiated `collections` extension before auth. Existing mock upload/crypto tests establish v1 CAS/receipt/opaque encrypted-frame client behavior, **not** an actual server's acceptance of this new envelope. + +Therefore sending a limited encrypted payload to the current endpoint could replace the desktop full snapshot. A new consent string or encrypted manifest alone does not isolate that storage. This component deliberately has **no limited upload/sync-now/auto-sync path or success status**, and does not call the full service as a substitute. No real cloud was contacted and no server deployment is claimed. + +### Exact server/protocol work required + +A separately negotiated collection contract (e.g. a new v2 endpoint family) must specify all of: + +- Explicit namespace/schema advertisement and request selection; never default an unknown namespace to full. +- Account + namespace isolated vault allocation, metadata, CAS revision/ETag, snapshot create/read/replace, password rotation, delete and retention; existing full routes and remote data unchanged. +- Namespace-bound operations/idempotency keys/receipts and retries; a receipt from a different collection must not reconcile a pending operation. +- Namespace/schema bound into authenticated crypto context and the encrypted manifest; reuse the actual Core crypto algorithms/framing/auth/transport/recovery machinery, with vectors and wrong-scope tests. No ad-hoc new crypto. +- Distinct local baseline/pending/key/device bindings. Standard limited local construction already separates its root/device identity; the full baseline must never be reused as a limited confirmation/deletion baseline. Define key-rotation and any user-approved migration explicitly. +- Local mock contracts proving independent full and limited snapshots, conflicts, delete/rotation/unknown outcomes and rejection of wrong scope/account/key. Then independent deployment and real two-device/platform acceptance. + +The endpoint example is a required design shape, **not an invented claim that a server implements it**. Backend ownership/negotiation is still external to this component. + +## Parent/root integration and desktop opt-in + +- No shared root entry patch is needed for Core `lib.rs`: existing modules are public. Integrate only the changed E2EE files and new scope document; do not replace inherited dirty `credentials.rs`, `lib.rs`, desktop, Android or iOS files from this checkout. +- Optional documentation entry, parent-owned: append a link from `docs/encrypted-cloud-sync.md` to this file, explicitly labeled domain-only / remote blocked. +- Parent-owned T integration: review/register `translation_target_languages` for the existing full policy and exclude serde-skipped `translation_target_languages_present` from the persistent-field coverage scanner. Do not serialize the marker or add either field to this limited whitelist. T files are not copied or modified here; this checkout's scoped test result predates their integration. +- Do not set the existing backend `encrypted_sync` option to enable iOS limited sync. The account facade can be consumed independently now; limited local domain composition additionally requires the real vault/effects/confirmation seams above. +- A future desktop opt-in consumer must explicitly choose the limited policy/factory instead of the full factory for that repository lifetime, keep its limited confirmed ledger/baseline separate, and negotiate the new namespace. Existing desktop users remain on the full default without wire/local-store migration. + +## Remaining domain limitations + +The minimal adapter deliberately captures the existing complete coherent local image before projecting the whitelist. Thus excluded-store readability, existing full-capture size limits, real vault hooks and platform effects are still prerequisites; an oversized/unreadable history can block limited capture rather than being silently truncated or bypassed. Narrow read-only capture optimization is not included. This does not export the excluded stores. + +The standard factories are alternatives, not simultaneous full/limited services on one already-bound repository. There is no automatic migration of an active full local store/journal, and no transport/key-rotation baseline migration. The custom `new` seam requires the caller to respect the dedicated-identity contract. Imported confirmation/provenance metadata and account lifecycle still require parent/Host integration. None of these gaps is represented as cloud success. + +## Validation boundary + +Tests use temporary repositories, memory/test vaults, real local Core encryption/journals and loopback protocol/account servers. They do not use user data, real cloud, microphone, simulator, permissions, or immutable dependency inputs. Test/build success is not product/runtime acceptance; the parent owns integration, independent review and final acceptance. + +Historical validation in the source worktree, before the Beta transfer (not the result for this branch): + +```sh +RUSTC="$(rustup which --toolchain 1.98.0 rustc)" \ +RUSTDOC="$(rustup which --toolchain 1.98.0 rustdoc)" \ +CARGO_TARGET_DIR="$PWD/target/scoped-sync" \ +cargo test --manifest-path openless-all/app/Cargo.toml -p openless-core \ + --locked --offline --lib cloud_sync_e2ee --no-fail-fast +``` + +Result: **181 passed, 0 failed, 0 ignored; 997 unrelated tests filtered**. Includes 14 new source-named tests across limited document/store tests, numeric identity, singleton protocol mock and retained-limited-root lost-counter regression. Existing full default service/crypto/vector/transport/restore tests remain green. Separate `cargo test --doc` passed with **0 doctests** (not extra behavioral coverage). `git diff --check` and empty staged diff passed. Full unfiltered Core/Host/iOS and the combined T registration seam were not validated in this lane. diff --git a/docs/index.md b/docs/index.md index 71f1a8d67..81c356b59 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,6 +21,7 @@ - **听写与模型**:[语音链路与服务渠道](development/speech.md) · [本地模型管理](development/local-models.md) - **录音翻译**:[同段 Shift 开关、次数与验收范围](development/shift-translation.md) - **长录音**:[超过 5 分钟的整段保留与中断恢复](development/long-recording.md) +- **随便问**:[提交、工具、附件与原生写回](development/ask.md) - **文字处理**:[问答与选区调用](architecture.md#问答与选区) · [转写后的自定义润色策略](development/polish-strategy.md) · [按输入应用选择风格包](development/app-style-routing.md) - **应用与模型目录**:[Agent 客户端、Harness 与模型研究表](research/agent-app-model-catalog.md) · [外部目录与分类接口](development/app-style-routing.md#分类目录-api) - **数据与安全**:[云同步与旧快照协议](development/cloud-sync.md) · [v1 扩展与跨版本保留](development/sync-v1-compatibility.md) · [远程输入协议](development/remote-input.md) · [WebView 内容安全策略](development/webview-security.md) diff --git a/docs/releases/2.0.2-release-notes.md b/docs/releases/2.0.2-release-notes.md deleted file mode 100644 index a75aaadbc..000000000 --- a/docs/releases/2.0.2-release-notes.md +++ /dev/null @@ -1,65 +0,0 @@ -# OpenLess 2.0.2+build.20261115 - -本页是正式版(Stable)。源码即已发布的 [`v2.0.2-Beta.7-tauri`](https://github.com/Open-Less/openless/releases/tag/v2.0.2-Beta.7-tauri)(提交 `e9ff403d258ab86d0d92ef1251e8797d5e15fdd9`),只把版本身份从 `2.0.2-Beta.7+build.20261113-6a7b5bb` 改为 `2.0.2+build.20261115`。版本号不含 `-` 预发布段,因此未手动选择更新渠道时走 Stable 更新源。没有加入该标签之后的功能或修复。 - -比较范围:上一公开正式版 **`v2.0.1-tauri` → 本正式版**。下面汇总已发布的 2.0.2 Beta.1 至 Beta.7 说明。不包含 2026-11-15 尚未进入该标签的本地改动。正式版标签 `v2.0.2-tauri` 须由管理员在本变更合入 `main` 并核对构建后再创建;本说明不创建该标签。 - -## 相对 2.0.1 的变化 - -### 录音、胶囊与输入 - -- 多屏胶囊可选择跟随鼠标或在所有屏幕显示,默认跟随鼠标;镜像与主胶囊共用同一识别会话。 -- 本地模型加载与麦克风解耦:停止先释放麦克风再转写,取消不回放已取消音频。录音在识别器准备完成前开始,并用有界缓冲保留开头音频。 -- 限制部分本地模型的空闲缓存和推理线程,降低驻留与反复重载。 -- 可选低内存后台模式和一次性原生录音胶囊。语音处理接入 MicYou,降噪、增益、AGC 和噪声门在实验页的第三级里调整。 -- Windows 支持本地语音唤醒、TSF 组合输入,以及纯文本插入切换(Shift+Insert)。胶囊可选择显示目标,关闭时保持无边框。 -- 修复打开语音编辑面板后 Windows 主窗口可能卡死的问题。macOS 终稿插入不再误入复制兜底;输入目标失效时保留已完成转写并进入复制兜底。 -- 新增 macOS 辅助功能授权浮动引导。远程输入可选转发本会话的实时识别文字。 -- 兼容型长录音在未单独限制时默认分段,并尽量在较安静处切开;显式要求整段上传的设置不会被默认分段覆盖。 - -### 识别、模型与词典 - -- Android arm64 可使用本地识别,并支持云端回退、自动切换和本地/云端竞速。 -- 支持 Gemini Live 实时逐字与智能转写、火山方舟思考开关,以及自定义服务的温度。 -- 可使用官方 ChatGPT 计划登录渠道。渠道指针悬空导致的未配置状态可以自愈;已启用渠道的顺序与当前凭据对齐。 -- 词典只从「新词」添加。手改纠正可恢复完整词。风格市场的赞在重复打开后仍然保留。 -- 光标上下文在 macOS、Windows 和 Android 首次使用时默认开启。密码输入、安全输入、已知密码管理器和终端仍然排除;用户可以关闭。 -- 实验性感知(光标上下文、手改学词、表达格式学习)集中在「高级功能 → 感知」。表达格式学习默认关闭,证据只留在本机。 - -### 设置、概览与用量 - -- 今日概览保持一屏,最近识别在卡片内滚动。 -- 设置按任务分组。高级功能使用独立子页。启动诊断留在实验页卡片内。 -- 调整界面圆角,以及缩放后的切换控件、快捷键搜索框、下拉菜单和焦点轮廓。 -- 侧栏提供用量入口,保存服务商明确返回的 Token,并按服务、渠道、模型和协议显示可比较的缓存占比。固定提示词规则放在动态应用和光标上下文之前。该账本不覆盖全部请求,不能当作完整账单。 -- 已经允许的麦克风在启动时不再重复请求权限。 - -### 同步、Android 与更新 - -- 加密同步覆盖更多设置。同步事件带服务来源,旧服务器或旧账户的事件不能覆盖当前同步服务的本地状态。 -- 首次启动时忽略安全软件放在同步目录里的普通诱饵文件,避免误判为损坏数据而闪退。已有加密状态的恢复保护继续生效。 -- Android 增加本地配置迁移、云笔记草稿条,以及提交失败时保留口述。英文键盘调整了上滑符号,并可以永不显示悬浮窗。设置向导中的超高卡片可以滚动。Android 与鸿蒙共用 Rime 输入法后端。 -- Android 同时检查 GitHub 与 CDN 的同渠道更新,选择可验证的更高版本,并对同一版本和架构做有界测速。回退仍须通过签名校验。 -- 桌面 Less Computer / 编码 Agent 和 Claude Console 已下线。 -- 默认更新渠道由版本号是否含 `-` 决定。本正式版走 Stable。Beta 安装包只提供给明确加入 Beta 渠道的用户。 - -## 已知范围 - -- 用量统计不是完整账单。感知功能仍是实验性的。 -- 缓存占比不能用来承诺固定命中率。 -- Linux 安装包不随本次自动附带,仍须独立设备验收。HarmonyOS 仓库包由后续流程附加。 -- 自动构建和安装检查不能代替具体设备上的实机测试。局域网输入安全、多模态听写和 macOS 提示音等在 Beta.7 发布时仍在审查的改动,不在本标签内。 - -## 下载与升级 - -- 已发布的 Beta.7 页面:[`v2.0.2-Beta.7-tauri`](https://github.com/Open-Less/openless/releases/tag/v2.0.2-Beta.7-tauri)。 -- 管理员将本变更合入 `main` 并确认检查通过后,再推送标签 `v2.0.2-tauri`。标签工作流只创建草稿;核对安装包后,再由管理员发布为 Latest。本说明不创建、不推送该标签。 -- macOS 需要 14 Sonoma 或更新版本。Apple Silicon 使用 `aarch64.dmg`,Intel 使用 `x64.dmg`。若包为临时签名且被 Gatekeeper 拦截,拖入「应用程序」后按既有发行方式执行 `xattr -cr /Applications/OpenLess.app`。 -- Windows 提供 x64 安装包。Android 提供四种 ABI 的签名 APK。 -- Stable 更新源要等 `v2.0.2-tauri` 发布并同步清单后,才会向 2.0.1 用户提供本版本。用户已经显式选择的更新渠道保持不变。 - -## 来源 - -- 基线标签 `v2.0.2-Beta.7-tauri`,提交 [`e9ff403d`](https://github.com/Open-Less/openless/commit/e9ff403d258ab86d0d92ef1251e8797d5e15fdd9)。 -- 上一正式版 [`v2.0.1-tauri`](https://github.com/Open-Less/openless/releases/tag/v2.0.1-tauri)(`2.0.1+build.20261016`)。 -- 分项说明见仓库内 Beta.1、Beta.3、Beta.4、Beta.5、Beta.6 发布说明,以及 Beta.2、Beta.7 的 GitHub Release。Beta.5 曾作为草稿,其界面与用量改动由 Beta.6 公开发布汇总。 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/cloud_sync_e2ee/adapter.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/adapter.rs index 3d672f55d..8b7a7177b 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/adapter.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/adapter.rs @@ -29,6 +29,37 @@ pub(crate) fn build( events: crate::events::BackendEventPublisher, tasks: Arc, ) -> SyncResult<(super::EncryptedSyncService, Arc)> { + let credential_store_for_service = credentials.clone(); + let (origin, local, store) = build_store( + config, + data_dir, + repositories, + credentials, + tasks, + "encrypted-sync", + )?; + let service = super::EncryptedSyncService::new( + super::SyncServiceConfig { + origin, + github_client_id, + }, + marketplace, + local, + store.clone(), + credential_store_for_service, + events, + ); + Ok((service, store)) +} + +pub(super) fn build_store( + config: super::EncryptedSyncConfig, + data_dir: &Path, + repositories: crate::BackendRepositories, + credentials: Arc, + tasks: Arc, + root_name: &str, +) -> SyncResult<(String, LocalStorage, Arc)> { let origin = url::Url::parse(&config.service_origin) .map_err(|_| super::error("unsupported_protocol"))?; if origin.scheme() != "https" @@ -42,7 +73,7 @@ pub(crate) fn build( return Err(super::error("unsupported_protocol")); } let origin = origin.origin().ascii_serialization(); - let root = data_dir.join("encrypted-sync"); + let root = data_dir.join(root_name); log::debug!( "[e2ee-adapter] build start data_dir={} root={}", data_dir.display(), @@ -80,7 +111,6 @@ pub(crate) fn build( credentials.clone(), ); log::debug!("[e2ee-adapter] stage=store_new"); - let credential_store_for_service = credentials.clone(); let store = Arc::new( CoreSyncStore::new( repositories, @@ -97,18 +127,7 @@ pub(crate) fn build( })?, ); log::debug!("[e2ee-adapter] stage=store_ok"); - let service = super::EncryptedSyncService::new( - super::SyncServiceConfig { - origin, - github_client_id, - }, - marketplace, - local, - store.clone(), - credential_store_for_service, - events, - ); - Ok((service, store)) + Ok((origin, local, store)) } /// Build the native document store without requiring a configured sync account. diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs new file mode 100644 index 000000000..cbb2de793 --- /dev/null +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/limited.rs @@ -0,0 +1,194 @@ +//! Narrow Host injection seam for opt-in limited domain data. Deliberately has +//! no upload method: the existing remote protocol exposes a singleton full vault. + +use crate::cloud_sync_e2ee_documents::{ + AllowedSyncScope, ConfirmedVocabularySelection, DocumentError, DocumentResult, + LimitedSyncDocuments, RestoreContext, Revision, SyncScope, +}; +use crate::cloud_sync_e2ee_store::CoreSyncStore; +use crate::{marketplace::MarketplaceService, BackendError}; +use futures_util::future::BoxFuture; +use std::sync::Arc; + +/// Verified immutable numeric identity. Display login and OAuth secrets are not exposed. +/// Obtain a fresh value from MarketplaceService; do not persist it as authorization. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VerifiedSyncAccount { + github_id: String, +} +impl VerifiedSyncAccount { + pub fn github_id(&self) -> &str { + &self.github_id + } +} + +/// Inject the actual account authority, without constructing/enabling full sync. +/// Implementations must revalidate sign-out/account switch on every call; never use a +/// cached display login. Hosts normally inject their existing MarketplaceService. +pub trait SyncAccountProvider: Send + Sync { + fn verified_sync_account(&self) -> BoxFuture<'_, Result>; +} +impl MarketplaceService { + pub async fn verified_sync_account(&self) -> Result { + let (_, account) = self.sync_identity().await?; + Ok(VerifiedSyncAccount { + github_id: account.github_id.as_str().into(), + }) + } +} +impl SyncAccountProvider for MarketplaceService { + fn verified_sync_account(&self) -> BoxFuture<'_, Result> { + Box::pin(MarketplaceService::verified_sync_account(self)) + } +} + +#[derive(Debug, Clone)] +pub struct LimitedSyncExport { + pub generation: Revision, + pub documents: LimitedSyncDocuments, +} + +#[derive(Clone)] +pub struct LimitedSyncStore { + store: CoreSyncStore, + accounts: Arc, +} +impl LimitedSyncStore { + /// Compose the actual Core protected local store without constructing or enabling the + /// full-snapshot service. Choose one policy per repository instance: its activity/vault + /// gate binds one device identity. The limited root has a separate durable device ID, + /// wrapping-key AAD, extension buckets and journal identity from desktop full sync. + #[allow(clippy::too_many_arguments)] + pub fn build( + config: super::EncryptedSyncConfig, + data_dir: &std::path::Path, + repositories: crate::BackendRepositories, + credentials: Arc, + tasks: Arc, + allowed: AllowedSyncScope, + accounts: Arc, + ) -> Result { + if allowed != AllowedSyncScope::ConfirmedVocabularyModeStyleReferences { + return Err(super::error("unsupported_protocol")); + } + let (_, _, store) = super::adapter::build_store( + config, + data_dir, + repositories, + credentials, + tasks, + super::LIMITED_LOCAL_ROOT, + )?; + Self::new((*store).clone(), allowed, accounts).map_err(super::document_error) + } + + /// Inject an already composed, dedicated limited-policy store. Do not reuse a full + /// service's local device identity; use `build` for the standard protected composition. + pub fn new( + store: CoreSyncStore, + allowed: AllowedSyncScope, + accounts: Arc, + ) -> DocumentResult { + if allowed != AllowedSyncScope::ConfirmedVocabularyModeStyleReferences { + return Err(DocumentError::Unsupported); + } + Ok(Self { store, accounts }) + } + + pub fn generation(&self) -> DocumentResult { + self.store.generation() + } + pub fn device(&self) -> crate::cloud_sync_e2ee_documents::SourceDevice { + self.store.device() + } + pub fn bind_runtime_idle_probe( + &self, + probe: Arc bool + Send + Sync>, + ) -> DocumentResult<()> { + self.store.bind_runtime_idle_probe(probe) + } + pub fn bind_runtime_effects( + &self, + effects: Arc, + ) -> DocumentResult<()> { + self.store.bind_runtime_effects(effects) + } + pub async fn recover_registered(&self) -> DocumentResult<()> { + self.store.recover_registered().await + } + pub fn is_recovering(&self) -> bool { + self.store.is_recovering() + } + + async fn check_account(&self, scope: &SyncScope) -> DocumentResult<()> { + let account = self + .accounts + .verified_sync_account() + .await + .map_err(|_| DocumentError::Locked)?; + if account.github_id() != scope.owner_github_id { + return Err(DocumentError::InvalidReference); + } + Ok(()) + } + + /// Coherent local capture, projected before being returned to Host. No sync-vault I/O; + /// the account provider may perform authentication I/O. Capture still requires real + /// credential gate/batch hooks, never an empty-vault fallback. + pub async fn export( + &self, + scope: SyncScope, + confirmed: ConfirmedVocabularySelection, + ) -> DocumentResult { + self.check_account(&scope).await?; + let full = self.store.export_scope(scope.clone()).await?; + self.check_account(&scope).await?; + Ok(LimitedSyncExport { + generation: full.generation, + documents: LimitedSyncDocuments::project(&full, &scope, &confirmed)?, + }) + } + + /// Explicit restore/merge result, not last-writer-wins. Caller supplies the generation + /// reviewed in its preview; all later local mutations cause StalePreview. Existing Core + /// exclusive gate, encrypted before/after journal, recovery and rollback remain authoritative. + pub async fn restore( + &self, + desired: LimitedSyncDocuments, + context: RestoreContext, + confirmed: ConfirmedVocabularySelection, + ) -> DocumentResult { + self.check_account(&context.scope).await?; + let full = self.store.export_scope(context.scope.clone()).await?; + if full.generation != context.local_generation { + return Err(DocumentError::StalePreview); + } + let overlaid = + desired.overlay(&full, &context.scope, context.observed_revision, &confirmed)?; + self.check_account(&context.scope).await?; + let scope = context.scope.clone(); + let restored = self.store.restore_scope(overlaid, context).await?; + Ok(LimitedSyncExport { + generation: restored.generation, + documents: desired.project_restored(&restored, &scope)?, + }) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + pub(crate) struct TestAccount(pub(crate) &'static str); + impl SyncAccountProvider for TestAccount { + fn verified_sync_account( + &self, + ) -> BoxFuture<'_, Result> { + Box::pin(async { + Ok(VerifiedSyncAccount { + github_id: self.0.into(), + }) + }) + } + } +} diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/mod.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/mod.rs index 6cfc6ddc7..0539071b0 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/mod.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/mod.rs @@ -3,7 +3,11 @@ mod adapter; mod dto; +mod limited; mod local; +#[cfg(test)] +pub(crate) use limited::tests::TestAccount; +pub use limited::{LimitedSyncExport, LimitedSyncStore, SyncAccountProvider, VerifiedSyncAccount}; mod service; #[cfg(test)] mod tests; @@ -13,6 +17,7 @@ pub use dto::*; pub(crate) use service::{EncryptedSyncService, SyncServiceConfig}; pub const DEFAULT_SYNC_SERVICE_ORIGIN: &str = "https://apic.openless.top:9443"; +pub(crate) const LIMITED_LOCAL_ROOT: &str = "encrypted-sync-limited-v1"; #[derive(Debug, Clone)] pub struct EncryptedSyncConfig { diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/tests.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/tests.rs index 5da8916e6..487d262d4 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/tests.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/tests.rs @@ -2696,3 +2696,43 @@ async fn create_requires_valid_confirmation_and_a_committed_remote_backup_to_ena assert!(created.enabled); assert_eq!(created.remote_revision.as_deref(), Some("1")); } + +#[tokio::test] +async fn public_verified_account_facade_does_not_enable_or_authenticate_full_sync() { + use crate::domains::MarketplaceApi; + let server = Server::start().await; + let fixture = Fixture::new(&server).await; + let account = fixture.marketplace.verified_sync_account().await.unwrap(); + assert_eq!(account.github_id(), OWNER); + assert_eq!( + serde_json::to_value(&account).unwrap(), + json!({"githubId": OWNER}) + ); + assert!(!fixture.service.status().enabled); + { + let state = server.state.lock().unwrap(); + assert_eq!( + state.requests, 1, + "only the real account /user authority was contacted" + ); + assert_eq!(state.github_auth_requests, 0); + assert_eq!(state.token_auth_requests, 0); + assert!(state.puts.is_empty()); + } + server.state.lock().unwrap().owner = "999".into(); + assert_eq!( + fixture + .marketplace + .verified_sync_account() + .await + .unwrap() + .github_id(), + "999" + ); + // The previously returned immutable value remains 42, never a mutable display-login alias. + assert_eq!(account.github_id(), OWNER); + fixture.marketplace.logout().await.unwrap(); + let requests = server.state.lock().unwrap().requests; + assert!(fixture.marketplace.verified_sync_account().await.is_err()); + assert_eq!(server.state.lock().unwrap().requests, requests); +} diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs new file mode 100644 index 000000000..6379cb8bd --- /dev/null +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited.rs @@ -0,0 +1,540 @@ +//! Opt-in domain format, not a second remote protocol. V1's singleton vault +//! cannot safely transport this alongside the desktop full snapshot. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeSet; +use zeroize::Zeroizing; + +use super::*; +use crate::cloud_sync_e2ee_protocol::types::{DocumentKind, DocumentSet, Revision}; + +pub const LIMITED_SYNC_NAMESPACE: &str = "confirmed-vocabulary-mode-style-references-v1"; +const STYLE_REFERENCE: &str = "marketStyleReference"; + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StyleReference { + id: String, + version: String, + origin_pack_id: Option, +} +impl StyleReference { + fn from_style(doc: &LogicalDocument) -> DocumentResult { + let record: StylePackRecord = serde_json::from_value(doc.value.clone()) + .map_err(|_| DocumentError::InvalidDocument)?; + let pack = record.pack.expose(); + let reference = Self { + id: doc.id.clone(), + version: pack + .get("version") + .and_then(Value::as_str) + .ok_or(DocumentError::InvalidDocument)? + .into(), + origin_pack_id: pack + .get("originPackId") + .filter(|value| !value.is_null()) + .map(|value| { + value + .as_str() + .map(str::to_owned) + .ok_or(DocumentError::InvalidDocument) + }) + .transpose()?, + }; + reference.validate()?; + Ok(reference) + } + fn validate(&self) -> DocumentResult<()> { + super::validate::identifier(&self.id)?; + if self.version.is_empty() + || self.version.len() > 128 + || self.version.chars().any(char::is_control) + { + return Err(DocumentError::InvalidDocument); + } + if let Some(origin) = &self.origin_pack_id { + super::validate::identifier(origin)?; + } + Ok(()) + } +} +fn style_reference(value: &Value) -> DocumentResult> { + let reference: Option = + serde_json::from_value(value.clone()).map_err(|_| DocumentError::InvalidDocument)?; + if let Some(reference) = &reference { + reference.validate()?; + } + Ok(reference) +} + +/// Host permission, not a remote capability. Existing desktop behavior remains the default. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum AllowedSyncScope { + #[default] + FullSnapshot, + ConfirmedVocabularyModeStyleReferences, +} + +/// Explicit Host confirmation decision, bound to the exact local capture. Empty means +/// no confirmed local rows, NEVER all rows. The Host owns durable confirmation metadata. +#[derive(Clone)] +pub struct ConfirmedVocabularySelection { + scope: SyncScope, + generation: Revision, + ids: BTreeSet, +} +impl ConfirmedVocabularySelection { + pub fn new(scope: SyncScope, generation: Revision, ids: Vec) -> DocumentResult { + super::validate::validate_scope(&scope)?; + if ids.len() > MAX_DOCUMENTS { + return Err(DocumentError::PayloadTooLarge); + } + let mut unique = BTreeSet::new(); + for id in ids { + super::validate::identifier(&id)?; + if !unique.insert(id) { + return Err(DocumentError::DuplicateId); + } + } + Ok(Self { + scope, + generation, + ids: unique, + }) + } + pub(crate) fn check(&self, full: &ExportedDocuments, scope: &SyncScope) -> DocumentResult<()> { + if self.scope != *scope || self.generation != full.generation { + return Err(DocumentError::StalePreview); + } + if self.ids.iter().any(|id| { + !full + .documents + .documents() + .documents + .iter() + .any(|doc| doc.kind == DocumentKind::Dictionary && doc.id == *id) + }) { + return Err(DocumentError::SourceChanged); + } + Ok(()) + } +} +impl std::fmt::Debug for ConfirmedVocabularySelection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ConfirmedVocabularySelection([REDACTED])") + } +} + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Manifest { + schema_version: u32, + namespace: String, + service_origin: String, + owner_github_id: String, + vault_id: String, + key_id: String, +} +impl Manifest { + fn for_scope(scope: &SyncScope) -> DocumentResult { + super::validate::validate_scope(scope)?; + Ok(Self { + schema_version: 1, + namespace: LIMITED_SYNC_NAMESPACE.into(), + service_origin: scope.service_origin.clone(), + owner_github_id: scope.owner_github_id.clone(), + vault_id: scope.vault_id.clone(), + key_id: scope.key_id.clone(), + }) + } +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Envelope { + manifest: Manifest, + documents: DocumentSet, +} + +/// Only validated limited data can be serialized; no full snapshot accessor is exposed. +#[derive(Clone)] +pub struct LimitedSyncDocuments { + manifest: Manifest, + documents: ValidatedSyncDocuments, +} +impl std::fmt::Debug for LimitedSyncDocuments { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LimitedSyncDocuments([REDACTED])") + } +} + +fn allowed(kind: DocumentKind, id: &str) -> bool { + kind == DocumentKind::Dictionary + || kind == DocumentKind::Preferences + && matches!(id, "defaultMode" | "enabledModes" | STYLE_REFERENCE) +} + +fn validate_limited( + set: DocumentSet, + revision: Revision, +) -> DocumentResult { + for doc in &set.documents { + if !allowed(doc.kind, &doc.id) { + return Err(DocumentError::ExcludedField); + } + if doc.kind == DocumentKind::Dictionary { + let row = doc + .value + .as_object() + .ok_or(DocumentError::InvalidDocument)?; + if row.keys().any(|key| { + !matches!( + key.as_str(), + "id" | "phrase" | "enabled" | "createdAt" | "sortIndex" + ) + }) { + return Err(DocumentError::ExcludedField); + } + if row.get("enabled").and_then(Value::as_bool).is_none() + || row.get("createdAt").and_then(Value::as_str).is_none() + { + return Err(DocumentError::InvalidDocument); + } + } else if doc.id == STYLE_REFERENCE { + style_reference(&doc.value)?; + } else if doc.id == "defaultMode" { + serde_json::from_value::(doc.value.clone()) + .map_err(|_| DocumentError::InvalidDocument)?; + } else if doc.id == "enabledModes" { + let modes = serde_json::from_value::>(doc.value.clone()) + .map_err(|_| DocumentError::InvalidDocument)?; + if modes + .iter() + .enumerate() + .any(|(index, mode)| modes[..index].contains(mode)) + { + return Err(DocumentError::DuplicateId); + } + } + } + for mark in &set.tombstones { + // These native settings cannot be deleted; selecting an empty style is explicit. + if mark.kind != DocumentKind::Dictionary { + return Err(DocumentError::ExcludedField); + } + } + for id in ["defaultMode", "enabledModes", STYLE_REFERENCE] { + if !set + .documents + .iter() + .any(|doc| doc.kind == DocumentKind::Preferences && doc.id == id) + { + return Err(DocumentError::InvalidDocument); + } + } + validate_sync_documents(set, revision) +} + +impl LimitedSyncDocuments { + /// Project only committed vocabulary rows, never unconfirmed candidate stores. + /// Notes and usage counters are receiver-local; prompts and style contents are absent. + pub(crate) fn project( + full: &ExportedDocuments, + scope: &SyncScope, + confirmed: &ConfirmedVocabularySelection, + ) -> DocumentResult { + confirmed.check(full, scope)?; + let mut set = full.documents.documents().clone(); + let selected_id = set + .documents + .iter() + .find(|doc| doc.kind == DocumentKind::Preferences && doc.id == "activeStylePackId") + .and_then(|doc| doc.value.as_str()) + .ok_or(DocumentError::InvalidDocument)?; + let reference = if selected_id.is_empty() { + None + } else { + Some(StyleReference::from_style( + set.documents + .iter() + .find(|doc| doc.kind == DocumentKind::StylePacks && doc.id == selected_id) + .ok_or(DocumentError::InvalidReference)?, + )?) + }; + let reference = + serde_json::to_value(reference).map_err(|_| DocumentError::InvalidDocument)?; + set.documents.retain(|doc| { + doc.kind == DocumentKind::Dictionary && confirmed.ids.contains(&doc.id) + || doc.kind == DocumentKind::Preferences + && matches!( + doc.id.as_str(), + "defaultMode" | "enabledModes" | "activeStylePackId" + ) + }); + for doc in &mut set.documents { + if doc.kind == DocumentKind::Dictionary { + let row = doc + .value + .as_object_mut() + .ok_or(DocumentError::InvalidDocument)?; + row.retain(|key, _| { + matches!( + key.as_str(), + "id" | "phrase" | "enabled" | "createdAt" | "sortIndex" + ) + }); + } else if doc.id == "activeStylePackId" { + doc.id = STYLE_REFERENCE.into(); + doc.value = reference.clone(); + } + } + // Only the separately protected limited baseline may establish confirmed deletions. + // Full-snapshot tombstones do not prove that an entry was ever confirmed. + set.tombstones.clear(); + Ok(Self { + manifest: Manifest::for_scope(scope)?, + documents: validate_limited(set, full.documents.observed_revision())?, + }) + } + + /// Plaintext domain bytes for a future namespaced encrypted transport, NEVER an HTTP body. + pub fn to_secret_json(&self) -> DocumentResult>> { + let bytes = serde_json::to_vec(&Envelope { + manifest: self.manifest.clone(), + documents: self.documents.documents().clone(), + }) + .map(Zeroizing::new) + .map_err(|_| DocumentError::InvalidDocument)?; + if bytes.len() > MAX_JSON_BYTES { + return Err(DocumentError::PayloadTooLarge); + } + Ok(bytes) + } + + /// Call only after authenticated decryption. Scope/revision come from authenticated metadata, + /// not fields supplied by the remote plaintext. Strict decoding rejects duplicate keys. + pub fn from_authenticated_json( + bytes: &[u8], + scope: &SyncScope, + revision: Revision, + ) -> DocumentResult { + crate::cloud_sync_e2ee_protocol::types::validate_secret_json(bytes, MAX_JSON_BYTES) + .map_err(|_| DocumentError::InvalidDocument)?; + let envelope: Envelope = + serde_json::from_slice(bytes).map_err(|_| DocumentError::InvalidDocument)?; + if envelope.manifest != Manifest::for_scope(scope)? { + return Err(DocumentError::InvalidReference); + } + Ok(Self { + manifest: envelope.manifest, + documents: validate_limited(envelope.documents, revision)?, + }) + } + + pub(crate) fn project_restored( + &self, + full: &ExportedDocuments, + scope: &SyncScope, + ) -> DocumentResult { + let ids = self + .documents + .documents() + .documents + .iter() + .filter(|doc| doc.kind == DocumentKind::Dictionary) + .map(|doc| doc.id.clone()) + .collect(); + let confirmed = ConfirmedVocabularySelection::new(scope.clone(), full.generation, ids)?; + let mut projected = Self::project(full, scope, &confirmed)?; + let mut set = projected.documents.documents().clone(); + set.tombstones = self.documents.documents().tombstones.clone(); + projected.documents = validate_limited(set, self.documents.observed_revision())?; + Ok(projected) + } + + pub fn diff( + &self, + baseline: Option<&Self>, + remote: &Self, + ) -> DocumentResult { + if self.manifest != remote.manifest + || baseline.is_some_and(|base| base.manifest != self.manifest) + { + return Err(DocumentError::InvalidReference); + } + Ok(LimitedMergePreview { + manifest: self.manifest.clone(), + preview: diff_sync_documents( + baseline.map(|base| &base.documents), + &self.documents, + &remote.documents, + )?, + }) + } + + /// Keep a limited baseline separately from the desktop full baseline. Missing IDs require + /// explicit tombstones; timestamps never decide which device wins. + pub fn record_local_deletions( + &self, + baseline: &Self, + deleted_at: &str, + ) -> DocumentResult { + if self.manifest != baseline.manifest { + return Err(DocumentError::InvalidReference); + } + let documents = record_missing_tombstones( + self.documents.documents().clone(), + &baseline.documents, + deleted_at, + )?; + Ok(Self { + manifest: self.manifest.clone(), + documents: validate_limited( + documents.documents().clone(), + documents.observed_revision(), + )?, + }) + } + + pub(crate) fn overlay( + &self, + full: &ExportedDocuments, + scope: &SyncScope, + revision: Revision, + confirmed: &ConfirmedVocabularySelection, + ) -> DocumentResult { + confirmed.check(full, scope)?; + if self.manifest != Manifest::for_scope(scope)? + || self.documents.observed_revision() != revision + { + return Err(DocumentError::StalePreview); + } + let mut set = full.documents.documents().clone(); + let old_rows = set + .documents + .iter() + .filter(|doc| doc.kind == DocumentKind::Dictionary) + .map(|doc| (doc.id.clone(), doc.value.clone())) + .collect::>(); + for id in self + .documents + .documents() + .documents + .iter() + .filter(|doc| doc.kind == DocumentKind::Dictionary) + .map(|doc| &doc.id) + .chain( + self.documents + .documents() + .tombstones + .iter() + .map(|mark| &mark.id), + ) + { + if old_rows.contains_key(id) && !confirmed.ids.contains(id) { + return Err(DocumentError::InvalidReference); + } + } + set.documents.retain(|doc| { + !(doc.kind == DocumentKind::Dictionary && confirmed.ids.contains(&doc.id)) + && !(doc.kind == DocumentKind::Preferences + && matches!( + doc.id.as_str(), + "defaultMode" | "enabledModes" | "activeStylePackId" + )) + }); + let remote_ids: BTreeSet<_> = self + .documents + .documents() + .documents + .iter() + .filter(|doc| doc.kind == DocumentKind::Dictionary) + .map(|doc| &doc.id) + .chain( + self.documents + .documents() + .tombstones + .iter() + .map(|mark| &mark.id), + ) + .collect(); + if confirmed.ids.iter().any(|id| !remote_ids.contains(id)) { + return Err(DocumentError::MissingTombstone); + } + set.tombstones.retain(|mark| { + mark.kind != DocumentKind::Dictionary + || !confirmed.ids.contains(&mark.id) && !remote_ids.contains(&mark.id) + }); + for source in &self.documents.documents().documents { + let mut doc = source.clone(); + if doc.kind == DocumentKind::Dictionary { + let row = doc + .value + .as_object_mut() + .ok_or(DocumentError::InvalidDocument)?; + row.insert( + "note".into(), + old_rows + .get(&doc.id) + .and_then(|old| old.get("note")) + .cloned() + .unwrap_or(Value::Null), + ); + row.insert( + "hits".into(), + old_rows + .get(&doc.id) + .and_then(|old| old.get("hits")) + .cloned() + .unwrap_or(Value::from(0)), + ); + } else if doc.id == STYLE_REFERENCE { + let reference = style_reference(&doc.value)?; + if let Some(reference) = &reference { + let installed = set + .documents + .iter() + .find(|style| { + style.kind == DocumentKind::StylePacks && style.id == reference.id + }) + .ok_or(DocumentError::InvalidReference)?; + if StyleReference::from_style(installed)? != *reference + || installed.value["pack"]["enabled"] != true + { + return Err(DocumentError::InvalidReference); + } + } + doc.id = "activeStylePackId".into(); + doc.value = + Value::String(reference.map(|reference| reference.id).unwrap_or_default()); + } + set.documents.push(doc); + } + set.tombstones + .extend(self.documents.documents().tombstones.clone()); + // Full validation requires the referenced style to be installed. Missing styles fail + // without changing settings; Host can download/verify via the existing marketplace. + validate_sync_documents(set, revision) + } +} + +pub struct LimitedMergePreview { + manifest: Manifest, + preview: MergePreview, +} +impl LimitedMergePreview { + pub fn conflicts(&self) -> &[RedactedConflict] { + self.preview.conflicts() + } + pub fn resolve(self, choices: &[ConflictChoice]) -> DocumentResult { + let documents = self.preview.resolve(choices)?; + Ok(LimitedSyncDocuments { + manifest: self.manifest, + documents: validate_limited( + documents.documents().clone(), + documents.observed_revision(), + )?, + }) + } +} diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited_tests.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited_tests.rs new file mode 100644 index 000000000..b44183845 --- /dev/null +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/limited_tests.rs @@ -0,0 +1,245 @@ +use super::*; +use serde_json::{json, Value}; + +fn scope() -> SyncScope { + SyncScope { + service_origin: "https://sync.example.test".into(), + owner_github_id: "42".into(), + vault_id: uuid::Uuid::new_v4().to_string(), + key_id: uuid::Uuid::new_v4().to_string(), + device_id: "device-a".into(), + } +} +fn full() -> ExportedDocuments { + let mut snapshot = super::tests::channel_snapshot(); + snapshot.preferences = SecretJson::new( + json!({"defaultMode":"raw", "enabledModes":["raw","light"], "activeStylePackId":"", "styleSystemPrompts":{"light":"PRIVATE-PROMPT"}, "themeMode":"dark"}), + ); + snapshot.dictionary = vec![ + SecretJson::new( + json!({"id":"confirmed", "phrase":"approved-word", "enabled":true, "note":"PRIVATE-NOTE", "hits":999, "createdAt":"2026-10-16T00:00:00Z"}), + ), + SecretJson::new( + json!({"id":"candidate", "phrase":"UNCONFIRMED-WORD", "enabled":true, "note":crate::shared_types::LEARNED_VOCAB_NOTE, "createdAt":"2026-10-16T00:00:00Z"}), + ), + ]; + snapshot.history = vec![SecretJson::new( + json!({"id":"history", "rawTranscript":"PRIVATE-HISTORY", "finalText":"PRIVATE-HISTORY", "mode":"raw", "insertStatus":"notRequested", "createdAt":"2026-10-16T00:00:00Z"}), + )]; + export_snapshot(snapshot).unwrap() +} +fn limited(full: &ExportedDocuments, scope: &SyncScope) -> LimitedSyncDocuments { + let selection = + ConfirmedVocabularySelection::new(scope.clone(), full.generation, vec!["confirmed".into()]) + .unwrap(); + LimitedSyncDocuments::project(full, scope, &selection).unwrap() +} +fn value(documents: &LimitedSyncDocuments) -> Value { + serde_json::from_slice(&documents.to_secret_json().unwrap()).unwrap() +} +fn parse(value: Value, scope: &SyncScope) -> DocumentResult { + LimitedSyncDocuments::from_authenticated_json( + &serde_json::to_vec(&value).unwrap(), + scope, + Revision::new(3), + ) +} + +#[test] +fn limited_export_never_contains_full_snapshot_secrets_or_unconfirmed_vocabulary() { + assert_eq!(AllowedSyncScope::default(), AllowedSyncScope::FullSnapshot); + let full = full(); + let scope = scope(); + let raw_full = serde_json::to_string(full.documents.documents()).unwrap(); + for marker in [ + "fixture-secret-original", + "PRIVATE-HISTORY", + "PRIVATE-PROMPT", + "PRIVATE-NOTE", + "UNCONFIRMED-WORD", + ] { + assert!( + raw_full.contains(marker), + "full default must remain unchanged: {marker}" + ); + } + let raw_limited = + String::from_utf8(limited(&full, &scope).to_secret_json().unwrap().to_vec()).unwrap(); + for marker in [ + "fixture-secret-original", + "PRIVATE-HISTORY", + "PRIVATE-PROMPT", + "PRIVATE-NOTE", + "UNCONFIRMED-WORD", + "hits", + "channels", + "styleSystemPrompts", + "device_profile", + ] { + assert!(!raw_limited.contains(marker), "excluded: {marker}"); + } + assert!(raw_limited.contains("approved-word")); + let none = ConfirmedVocabularySelection::new(scope.clone(), full.generation, vec![]).unwrap(); + assert!(!String::from_utf8( + LimitedSyncDocuments::project(&full, &scope, &none) + .unwrap() + .to_secret_json() + .unwrap() + .to_vec() + ) + .unwrap() + .contains("approved-word")); +} + +#[test] +fn wrong_manifest_scope_account_key_version_and_forbidden_documents_fail_closed() { + let full = full(); + let scope = scope(); + let original = limited(&full, &scope); + for (key, wrong) in [ + ("namespace", json!("encrypted-full-snapshot-v1")), + ("schemaVersion", json!(2)), + ("ownerGithubId", json!("999")), + ("keyId", json!(uuid::Uuid::new_v4().to_string())), + ("vaultId", json!(uuid::Uuid::new_v4().to_string())), + ("serviceOrigin", json!("https://other.example.test")), + ] { + let mut changed = value(&original); + changed["manifest"][key] = wrong; + assert!(parse(changed, &scope).is_err(), "{key}"); + } + let mut changed = value(&original); + changed["documents"]["documents"].as_array_mut().unwrap().push(json!({"id":"styleSystemPrompts", "kind":"preferences", "schemaVersion":1, "value":{"light":"private"}})); + assert_eq!( + parse(changed, &scope).unwrap_err(), + DocumentError::ExcludedField + ); + for kind in [ + DocumentKind::ProviderCredentials, + DocumentKind::Channels, + DocumentKind::History, + DocumentKind::Activity, + DocumentKind::StylePacks, + DocumentKind::VocabularyPresets, + DocumentKind::DeviceProfile, + DocumentKind::UiPreferences, + DocumentKind::Corrections, + ] { + let mut changed = value(&original); + changed["documents"]["documents"] + .as_array_mut() + .unwrap() + .push(json!({"id":"forbidden", "kind":kind, "schemaVersion":1, "value":null})); + assert_eq!( + parse(changed, &scope).unwrap_err(), + DocumentError::ExcludedField + ); + } + for key in ["note", "hits", "rawAudio", "apiKey"] { + let mut changed = value(&original); + let dictionary = changed["documents"]["documents"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|doc| doc["id"] == "confirmed") + .unwrap(); + dictionary["value"][key] = json!("private"); + assert_eq!( + parse(changed, &scope).unwrap_err(), + DocumentError::ExcludedField + ); + } + assert!( + DocumentSet::from_json_bytes(&original.to_secret_json().unwrap()).is_err(), + "the full protocol must not silently accept the limited envelope" + ); + let raw_full = serde_json::to_vec(full.documents.documents()).unwrap(); + assert!( + LimitedSyncDocuments::from_authenticated_json(&raw_full, &scope, Revision::new(3)).is_err() + ); + let bytes = original.to_secret_json().unwrap(); + let duplicate = String::from_utf8(bytes.to_vec()).unwrap().replacen( + "\"schemaVersion\":1", + "\"schemaVersion\":1,\"schemaVersion\":1", + 1, + ); + assert!(LimitedSyncDocuments::from_authenticated_json( + duplicate.as_bytes(), + &scope, + Revision::new(3) + ) + .is_err()); +} + +#[test] +fn confirmation_selection_requires_exact_scope_generation_and_existing_ids() { + let full = full(); + let scope = scope(); + for selection in [ + ConfirmedVocabularySelection::new( + scope.clone(), + Revision::new(0), + vec!["confirmed".into()], + ) + .unwrap(), + ConfirmedVocabularySelection::new( + super::limited_tests::scope(), + full.generation, + vec!["confirmed".into()], + ) + .unwrap(), + ] { + assert_eq!( + LimitedSyncDocuments::project(&full, &scope, &selection).unwrap_err(), + DocumentError::StalePreview + ); + } + let missing = + ConfirmedVocabularySelection::new(scope.clone(), full.generation, vec!["missing".into()]) + .unwrap(); + assert_eq!( + LimitedSyncDocuments::project(&full, &scope, &missing).unwrap_err(), + DocumentError::SourceChanged + ); +} + +#[test] +fn limited_conflicts_and_deletions_reuse_core_three_way_rules() { + let full = full(); + let scope = scope(); + let baseline = limited(&full, &scope); + let mut left = value(&baseline); + let mut right = value(&baseline); + for (set, phrase) in [(&mut left, "left"), (&mut right, "right")] { + for doc in set["documents"]["documents"].as_array_mut().unwrap() { + if doc["id"] == "confirmed" { + doc["value"]["phrase"] = json!(phrase); + } + } + } + let left = parse(left, &scope).unwrap(); + let right = parse(right, &scope).unwrap(); + let preview = left.diff(Some(&baseline), &right).unwrap(); + assert_eq!(preview.conflicts().len(), 1); + let choice = ConflictChoice { + conflict_id: preview.conflicts()[0].conflict_id.clone(), + side: ConflictSide::Remote, + }; + let merged = preview.resolve(&[choice]).unwrap(); + assert!(String::from_utf8(merged.to_secret_json().unwrap().to_vec()) + .unwrap() + .contains("right")); + let selection = + ConfirmedVocabularySelection::new(scope.clone(), full.generation, vec![]).unwrap(); + let deleted = LimitedSyncDocuments::project(&full, &scope, &selection) + .unwrap() + .record_local_deletions(&baseline, "2026-10-16T00:00:00Z") + .unwrap(); + let json = value(&deleted); + assert_eq!(json["documents"]["tombstones"].as_array().unwrap().len(), 1); + assert_eq!(json["documents"]["tombstones"][0]["id"], "confirmed"); + assert_eq!( + deleted.diff(Some(&baseline), &right).unwrap().conflicts()[0].reason, + ConflictReason::DeleteModify + ); +} diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/mod.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/mod.rs index 9763c4c82..1989e8899 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/mod.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/mod.rs @@ -2,17 +2,24 @@ mod export; pub(crate) use export::legacy_builtin_style_id; +mod limited; mod merge; pub mod registry; mod restore; mod types; mod validate; -pub use crate::cloud_sync_e2ee_protocol::types::{DocumentKind, Revision}; +pub use crate::cloud_sync_e2ee_protocol::types::{ + DocumentKind, DocumentSet, LogicalDocument, Revision, SourceDevice, Tombstone, +}; pub use export::{ activity_record, export_provider_credentials_for_sync, export_snapshot, export_style_packs, export_sync_documents, secret_rows, ui_preferences, vocabulary_records, }; +pub use limited::{ + AllowedSyncScope, ConfirmedVocabularySelection, LimitedMergePreview, LimitedSyncDocuments, + LIMITED_SYNC_NAMESPACE, +}; pub use merge::{ diff_local_replace_documents, diff_sync_documents, record_missing_tombstones, ConflictChoice, ConflictReason, ConflictSide, MergePreview, RedactedConflict, @@ -91,6 +98,8 @@ pub fn serialize_sync_documents(documents: &ValidatedSyncDocuments) -> DocumentR serde_json::to_vec(documents.documents()).map_err(|_| DocumentError::InvalidDocument) } +#[cfg(test)] +mod limited_tests; #[cfg(test)] mod restore_tests; #[cfg(test)] diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs index 36bbe2a2b..4e5476dbd 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/transport.rs @@ -1487,6 +1487,36 @@ mod tests { assert_eq!(requests[1].headers["accept-encoding"], "identity"); } + #[tokio::test] + async fn v1_contract_has_a_singleton_vault_and_no_named_scope_capability() { + let server = FakeServer::start(vec![ + caps_reply(), + Reply::json("200 OK", empty_metadata()).header("ETag", "\"zero\""), + ]) + .await; + let transport = Transport::for_test(&server.origin, CLIENT_ID) + .await + .unwrap(); + transport + .metadata(&session(&transport, OWNER), None) + .await + .unwrap(); + let requests = server.finish().await; + assert_eq!(requests[1].path, "/v1/me/vault"); + assert!(!requests[1].headers.contains_key("x-sync-namespace")); + + // A scope-aware server requires a new negotiated wire contract. Merely sending + // opaque bytes to this route would still replace the desktop's single vault. + let mut extended = capabilities(); + extended["collections"] = json!(["confirmed-vocabulary-mode-style-references-v1"]); + let server = FakeServer::start(vec![Reply::json("200 OK", extended)]).await; + assert!(matches!( + Transport::for_test(&server.origin, CLIENT_ID).await, + Err(Error::InvalidWire(_)) + )); + assert_eq!(server.finish().await.len(), 1); + } + #[tokio::test] async fn wrong_oauth_capability_or_duplicate_wire_key_prevents_authentication() { let mut wrong = capabilities(); diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs index 001525ac0..5b6af30c7 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_protocol/types.rs @@ -1168,6 +1168,11 @@ fn parse_strict_json(bytes: &[u8], limit: usize) -> Result { .map_err(|_| Error::InvalidWire("json trailing data"))?; Ok(value) } +pub(crate) fn validate_secret_json(bytes: &[u8], limit: usize) -> Result<()> { + // StrictValue erases the validation tree on every return path. + parse_strict_json(bytes, limit).map(|_| ()) +} + pub(crate) fn parse_wire(bytes: &[u8], limit: usize) -> Result { if bytes.len() > limit { return Err(Error::PayloadTooLarge); diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs index 2b89affdc..b80731a55 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/gate.rs @@ -382,6 +382,27 @@ pub struct SyncWriteGate { runtime_blocked: AtomicBool, } +fn contains_existing_sync_state(directory: &Path) -> DocumentResult { + for root in [ + directory.to_path_buf(), + directory.with_file_name(crate::cloud_sync_e2ee::LIMITED_LOCAL_ROOT), + ] { + match std::fs::read_dir(root) { + Ok(entries) => { + for entry in entries { + let entry = entry.map_err(|_| DocumentError::JournalUnavailable)?; + if entry.file_name().to_str().is_none_or(is_owned_sync_entry) { + return Ok(true); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(DocumentError::JournalUnavailable), + } + } + Ok(false) +} + impl SyncWriteGate { /// An unreadable/corrupt counter is an error, never a reset to zero. pub fn open(state_path: PathBuf) -> DocumentResult> { @@ -395,7 +416,7 @@ impl SyncWriteGate { if initialized_path.exists() || (directory.file_name().and_then(|name| name.to_str()) == Some("encrypted-sync") - && contains_owned_sync_entry(directory)?) + && contains_existing_sync_state(directory)?) { return Err(DocumentError::RecoveryRequired); } @@ -1124,6 +1145,24 @@ mod tests { } } + #[test] + fn lost_counter_never_resets_over_a_retained_limited_policy_root() { + let temp = Temp::new(); + let limited = temp.0.join(crate::cloud_sync_e2ee::LIMITED_LOCAL_ROOT); + std::fs::create_dir_all(&limited).unwrap(); + let ciphertext = limited.join("fixture.enc"); + std::fs::write(&ciphertext, b"retained-limited-ciphertext").unwrap(); + assert!(matches!( + open_for_data_dir(&temp.0), + Err(DocumentError::RecoveryRequired) + )); + assert!(!temp.0.join("encrypted-sync/generation.json").exists()); + assert_eq!( + std::fs::read(ciphertext).unwrap(), + b"retained-limited-ciphertext" + ); + } + #[test] fn runtime_recovery_flag_does_not_wait_for_state_lock_or_file_io() { let temp = Temp::new(); diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/limited_tests.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/limited_tests.rs new file mode 100644 index 000000000..81d4eeb0b --- /dev/null +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/limited_tests.rs @@ -0,0 +1,523 @@ +use super::*; +use crate::cloud_sync_e2ee::{LimitedSyncStore, TestAccount}; + +fn facade(f: &Fixture, account: &'static str) -> LimitedSyncStore { + LimitedSyncStore::new( + f.store.clone(), + AllowedSyncScope::ConfirmedVocabularyModeStyleReferences, + Arc::new(TestAccount(account)), + ) + .unwrap() +} +fn selection(f: &Fixture, generation: Revision, ids: &[&str]) -> ConfirmedVocabularySelection { + ConfirmedVocabularySelection::new( + f.scope.clone(), + generation, + ids.iter().map(|id| (*id).into()).collect(), + ) + .unwrap() +} +async fn seeded() -> Fixture { + let f = Fixture::new(); + let before = f.store.export_scope(f.scope.clone()).await.unwrap(); + let mut set = before.documents.documents().clone(); + for (kind, id, value) in [ + ( + DocumentKind::Dictionary, + "confirmed", + json!({"id":"confirmed","phrase":"Approved","enabled":true,"note":"PRIVATE-NOTE","hits":17,"createdAt":"2026-10-16T00:00:00Z","sortIndex":0}), + ), + ( + DocumentKind::Dictionary, + "unconfirmed", + json!({"id":"unconfirmed","phrase":"Candidate","enabled":true,"note":crate::shared_types::LEARNED_VOCAB_NOTE,"hits":3,"createdAt":"2026-10-16T00:00:00Z","sortIndex":1}), + ), + ( + DocumentKind::History, + "private-history", + json!({"id":"private-history","createdAt":"2026-10-16T00:00:00Z","source":"quick_note","rawTranscript":"PRIVATE-HISTORY","finalText":"PRIVATE-HISTORY","mode":"raw","insertStatus":"notRequested","hasAudioRecording":false,"sortIndex":0}), + ), + ( + DocumentKind::Channels, + "llm:fixture", + json!({"id":"fixture","namespace":"llm","providerType":"requesty","name":"Private channel","enabled":true,"order":0,"active":true,"configuration":{}}), + ), + ( + DocumentKind::ProviderCredentials, + "llm:fixture", + json!({"channelId":"fixture","namespace":"llm","accounts":{"ark.api_key":"PRIVATE-API-KEY"}}), + ), + ] { + set_doc(&mut set, kind, id, value); + } + f.store + .restore_scope(validate(set), f.context(&before)) + .await + .unwrap(); + f +} +fn changed( + remote: &LimitedSyncDocuments, + f: &Fixture, + change: impl FnOnce(&mut Value), +) -> LimitedSyncDocuments { + let mut value: Value = serde_json::from_slice(&remote.to_secret_json().unwrap()).unwrap(); + change(&mut value); + LimitedSyncDocuments::from_authenticated_json( + &serde_json::to_vec(&value).unwrap(), + &f.scope, + Revision::new(3), + ) + .unwrap() +} +fn set_phrase(value: &mut Value, phrase: &str) { + for doc in value["documents"]["documents"].as_array_mut().unwrap() { + if doc["id"] == "confirmed" { + doc["value"]["phrase"] = json!(phrase); + } + } +} + +#[tokio::test] +async fn limited_restore_changes_only_confirmed_vocabulary_and_reference_preferences() { + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + assert!(LimitedSyncStore::new( + f.store.clone(), + AllowedSyncScope::default(), + Arc::new(TestAccount("42")) + ) + .is_err()); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let raw = String::from_utf8(limited.documents.to_secret_json().unwrap().to_vec()).unwrap(); + for marker in [ + "PRIVATE-HISTORY", + "PRIVATE-API-KEY", + "PRIVATE-NOTE", + "Candidate", + ] { + assert!(!raw.contains(marker)); + } + let installed = full + .documents + .documents() + .documents + .iter() + .find(|doc| doc.kind == DocumentKind::StylePacks && doc.id == "builtin.light") + .unwrap(); + let style_reference = json!({ + "id": installed.id, + "version": installed.value["pack"]["version"], + "originPackId": installed.value["pack"].get("originPackId").cloned().unwrap_or(Value::Null), + }); + let remote = changed(&limited.documents, &f, |value| { + set_phrase(value, "Remote approved"); + for doc in value["documents"]["documents"].as_array_mut().unwrap() { + if doc["id"] == "defaultMode" { + doc["value"] = json!("formal"); + } + if doc["id"] == "marketStyleReference" { + doc["value"] = style_reference.clone(); + } + } + }); + api.restore( + remote, + f.context(&full), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let rows = f.repo.vocabulary.list().unwrap(); + assert_eq!( + rows.iter() + .find(|row| row.id == "confirmed") + .unwrap() + .phrase, + "Remote approved" + ); + assert_eq!( + rows.iter() + .find(|row| row.id == "confirmed") + .unwrap() + .note + .as_deref(), + Some("PRIVATE-NOTE") + ); + assert_eq!( + rows.iter().find(|row| row.id == "confirmed").unwrap().hits, + 17 + ); + assert_eq!( + rows.iter() + .find(|row| row.id == "unconfirmed") + .unwrap() + .phrase, + "Candidate" + ); + let after = f.store.export_scope(f.scope.clone()).await.unwrap(); + let untouched = |set: &DocumentSet| { + set.documents + .iter() + .filter(|doc| { + doc.kind != DocumentKind::Dictionary + && !(doc.kind == DocumentKind::Preferences + && matches!(doc.id.as_str(), "defaultMode" | "activeStylePackId")) + }) + .cloned() + .collect::>() + }; + assert_eq!( + untouched(full.documents.documents()), + untouched(after.documents.documents()) + ); +} + +#[tokio::test] +async fn limited_wrong_account_key_generation_missing_style_and_unconfirmed_collision_do_not_write() +{ + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let remote = changed(&limited.documents, &f, |value| { + set_phrase(value, "Must not write") + }); + assert_eq!( + facade(&f, "999") + .restore( + remote.clone(), + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::InvalidReference + ); + let mut context = f.context(&full); + context.scope.key_id = uuid::Uuid::new_v4().to_string(); + assert!(api + .restore( + remote.clone(), + context, + selection(&f, full.generation, &["confirmed"]) + ) + .await + .is_err()); + let stale = selection(&f, Revision::new(full.generation.get() - 1), &["confirmed"]); + assert_eq!( + api.restore(remote.clone(), f.context(&full), stale) + .await + .unwrap_err(), + DocumentError::StalePreview + ); + let missing_style = changed(&limited.documents, &f, |value| { + for doc in value["documents"]["documents"].as_array_mut().unwrap() { + if doc["id"] == "marketStyleReference" { + doc["value"] = json!({"id":"not-installed","version":"1.0.0","originPackId":null}); + } + } + }); + assert_eq!( + api.restore( + missing_style, + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::InvalidReference + ); + let omitted = changed(&limited.documents, &f, |value| { + value["documents"]["documents"] + .as_array_mut() + .unwrap() + .retain(|doc| doc["id"] != "confirmed"); + }); + assert_eq!( + api.restore( + omitted, + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::MissingTombstone + ); + for tombstone in [false, true] { + let collision = changed(&limited.documents, &f, |value| { + if tombstone { + value["documents"]["tombstones"] = json!([{"id":"unconfirmed","kind":"dictionary","deletedAt":"2026-10-16T00:00:00Z","baseRevision":"3"}]); + } else { + value["documents"]["documents"].as_array_mut().unwrap().push(json!({"id":"unconfirmed","kind":"dictionary","schemaVersion":1,"value":{"id":"unconfirmed","phrase":"bad overwrite","enabled":true,"createdAt":"2026-10-16T00:00:00Z","sortIndex":1}})); + } + }); + assert_eq!( + api.restore( + collision, + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::InvalidReference + ); + } + let after = f.store.export_scope(f.scope.clone()).await.unwrap(); + assert_eq!( + after.documents.documents().documents, + full.documents.documents().documents + ); + assert_eq!(after.generation, full.generation); + // A real ordinary write after preview is retained, never overwritten by stale restore. + f.repo + .preferences + .update(|prefs| prefs.show_capsule = !prefs.show_capsule) + .unwrap(); + assert_eq!( + api.restore( + remote, + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::StalePreview + ); +} + +#[tokio::test] +async fn limited_deletion_removes_only_confirmed_rows_and_keeps_unconfirmed_rows() { + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let remote = changed(&limited.documents, &f, |value| { + value["documents"]["documents"] + .as_array_mut() + .unwrap() + .retain(|doc| doc["id"] != "confirmed"); + value["documents"]["tombstones"] = json!([{"id":"confirmed","kind":"dictionary","deletedAt":"2026-10-16T00:00:00Z","baseRevision":"3"}]); + }); + let restored = api + .restore( + remote, + f.context(&full), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let returned: Value = + serde_json::from_slice(&restored.documents.to_secret_json().unwrap()).unwrap(); + assert_eq!(returned["documents"]["tombstones"][0]["id"], "confirmed"); + let rows = f.repo.vocabulary.list().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].id, "unconfirmed"); +} + +#[tokio::test] +async fn limited_partial_failure_uses_existing_encrypted_rollback_and_recovery() { + for failures in [vec![true, false], vec![true, true, false]] { + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let remote = changed(&limited.documents, &f, |value| { + set_phrase(value, "Roll back me") + }); + f.credentials + .failures + .lock() + .unwrap() + .extend(failures.clone()); + let error = api + .restore( + remote, + f.context(&full), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap_err(); + assert_eq!( + error, + if failures.len() == 2 { + DocumentError::RestoreRolledBack + } else { + DocumentError::RecoveryRequired + } + ); + if failures.len() == 3 { + f.store.recover_registered().await.unwrap(); + } + let after = f.store.export_scope(f.scope.clone()).await.unwrap(); + assert_eq!( + after.documents.documents().documents, + full.documents.documents().documents + ); + assert_eq!(after.generation, full.generation); + } +} + +#[tokio::test] +async fn limited_restore_blocks_concurrent_repository_and_credential_mutations() { + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let remote = changed(&limited.documents, &f, |value| { + set_phrase(value, "Gated update") + }); + let barrier = Arc::new(tokio::sync::Barrier::new(2)); + *f.effects.wait.lock().unwrap() = Some(barrier.clone()); + let context = f.context(&full); + let confirmed = selection(&f, full.generation, &["confirmed"]); + let restore = tokio::spawn(async move { api.restore(remote, context, confirmed).await }); + barrier.wait().await; + assert!(!restore.is_finished()); + assert!(f.repo.vocabulary.add("Concurrent".into(), None).is_err()); + assert!(f.store.inner.gate.begin_mutation().is_err()); + // Fixture effects also assert that the credential store's exact shared gate is held. + barrier.wait().await; + restore.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn limited_wrong_journal_key_cannot_replay_or_clear_pending_local_recovery() { + let f = seeded().await; + let full = f.store.export_scope(f.scope.clone()).await.unwrap(); + let api = facade(&f, "42"); + let limited = api + .export( + f.scope.clone(), + selection(&f, full.generation, &["confirmed"]), + ) + .await + .unwrap(); + let remote = changed(&limited.documents, &f, |value| { + set_phrase(value, "Pending image") + }); + f.credentials.failures.lock().unwrap().extend([true, true]); + assert_eq!( + api.restore( + remote, + f.context(&full), + selection(&f, full.generation, &["confirmed"]) + ) + .await + .unwrap_err(), + DocumentError::RecoveryRequired + ); + let dictionary_path = f._temp.0.join("dictionary.json"); + // Snapshot real local file bytes even when the normal API is recovery-fenced. + let dictionary_before = std::fs::read(&dictionary_path).unwrap(); + let preferences_before = std::fs::read(f._temp.0.join("preferences.json")).unwrap(); + let pending_before = f.store.inner.gate.registered_recovery_scopes().unwrap(); + let wrong_extensions = Arc::new(Extensions { + values: Mutex::new(f.extensions.values.lock().unwrap().clone()), + protector: Arc::new(CryptoJournalProtector::new(Arc::new( + DerivedKey::from_secret_bytes(Zeroizing::new([99; 32])), + ))), + key_requested: AtomicBool::new(false), + ui_revision: Mutex::new(f.extensions.ui_revision.lock().unwrap().clone()), + }); + let wrong_store = CoreSyncStore::new( + f.repo.clone(), + Arc::new(f.credentials.clone()), + f._temp.0.clone(), + f.store.device(), + f.store.inner.gate.clone(), + wrong_extensions, + Arc::new(crate::TokioTaskSpawner), + ) + .unwrap(); + wrong_store + .bind_runtime_idle_probe(Arc::new(|| true)) + .unwrap(); + wrong_store + .bind_runtime_effects(Arc::new(f.effects.clone())) + .unwrap(); + assert!(wrong_store.recover_registered().await.is_err()); + assert_eq!(std::fs::read(&dictionary_path).unwrap(), dictionary_before); + assert_eq!( + std::fs::read(f._temp.0.join("preferences.json")).unwrap(), + preferences_before + ); + assert_eq!( + f.store.inner.gate.registered_recovery_scopes().unwrap(), + pending_before + ); + assert!(f.store.is_recovering()); + f.store.recover_registered().await.unwrap(); + let recovered = f.store.export_scope(f.scope.clone()).await.unwrap(); + assert_eq!( + recovered.documents.documents().documents, + full.documents.documents().documents + ); +} + +#[tokio::test] +async fn limited_public_factory_uses_core_local_storage_without_full_service_or_remote_requests() { + let source = Fixture::new(); + let temp = Temp::new(); + let credentials = TestCredentials { + bound_gate: Arc::new(Mutex::new(None)), + ..source.credentials.clone() + }; + let store = LimitedSyncStore::build( + crate::cloud_sync_e2ee::EncryptedSyncConfig { + service_origin: "https://sync.example.test".into(), + app_version: "test".into(), + }, + &temp.0, + BackendRepositories::open(&temp.0).unwrap(), + Arc::new(credentials), + Arc::new(crate::TokioTaskSpawner), + AllowedSyncScope::ConfirmedVocabularyModeStyleReferences, + Arc::new(TestAccount("42")), + ) + .unwrap(); + assert!(temp.0.join("encrypted-sync-limited-v1/device-id").is_file()); + assert!(!temp.0.join("encrypted-sync/device-id").exists()); + let scope = SyncScope { + device_id: store.device().id.clone(), + ..source.scope.clone() + }; + let confirmed = + ConfirmedVocabularySelection::new(scope.clone(), store.generation().unwrap(), vec![]) + .unwrap(); + store.export(scope, confirmed).await.unwrap(); + assert!(!store.is_recovering()); + // Production export above needed no crypto key yet. Restore still requires the real + // platform effects + secure vault hooks; this fixture cannot silently substitute them. +} diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs index 26da05a0f..0a10c9fd6 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_store/tests.rs @@ -1,4 +1,6 @@ #![cfg(test)] +#[path = "limited_tests.rs"] +mod limited_tests; // Seam scanner looks for #[cfg(test)] (inner attr alone is not enough). #[cfg(test)] mod __runtime_seam_test_marker {} 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/audio-cue-listener-contract.test.mjs b/openless-all/app/scripts/audio-cue-listener-contract.test.mjs new file mode 100644 index 000000000..57660efbf --- /dev/null +++ b/openless-all/app/scripts/audio-cue-listener-contract.test.mjs @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const source = await readFile( + new URL('../src/features/capsule/AudioCue.tsx', import.meta.url), + 'utf8', +); + +// The always-alive capsule listener must never open output just by mounting, even when +// the persisted preference is disabled. Runtime playback/recovery is covered separately. +assert.doesNotMatch(source, /primeAudioCue/); +assert.equal((source.match(/playRecordStartCue\(\)/g) ?? []).length, 1); +assert.match(source, /if \(audioCueEnabledRef\.current\) playRecordStartCue\(\)/); +assert.match(source, /state === 'recording' && previous !== 'recording'/); +assert.match(source, /host === 'tauri' && os !== 'android'/); +assert.match(source, /await events\.label\(\)\) !== 'capsule'/); +assert.equal( + (source.match(/if \(!audioCueEnabledRef\.current\) disposeAudioCue\(\)/g) ?? []).length, + 2, + 'both initial settings and live preference changes must dispose disabled audio', +); +assert.match(source, /if \(owned\) disposeAudioCue\(\)/); +console.log('[audioCue.listener.test] lazy startup, preference and ownership contracts passed'); diff --git a/openless-all/app/scripts/audio-cue-runtime.test.mjs b/openless-all/app/scripts/audio-cue-runtime.test.mjs index f854901b2..3472ba603 100644 --- a/openless-all/app/scripts/audio-cue-runtime.test.mjs +++ b/openless-all/app/scripts/audio-cue-runtime.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { mock } from 'node:test'; import { tsImport } from 'tsx/esm/api'; -const { playRecordStartCue, stopAudioCue } = await tsImport( +const { disposeAudioCue, playRecordStartCue, stopAudioCue } = await tsImport( '../src/lib/audioCue.ts', import.meta.url, ); @@ -21,6 +21,7 @@ class FakeContext { this.state = FakeContext.initialState; this.frozen = false; this.voices = 0; + this.oscillators = []; this.closeCalls = 0; this.resumeImpl = FakeContext.initialResumeImpl; this.destination = {}; @@ -36,13 +37,15 @@ class FakeContext { } createOscillator() { this.voices++; - return { + const oscillator = { frequency: { setValueAtTime() {} }, connect: (gain) => gain, start() {}, stop() {}, disconnect() {}, }; + this.oscillators.push(oscillator); + return oscillator; } createGain() { return { @@ -80,7 +83,6 @@ try { releaseOldResume(); await Promise.resolve(); assert.equal(stuck.voices, 0, 'late resolution cannot play through a discarded context'); - tick(315); // Every request invalidates old work, including a new synchronous playback. healthy.state = 'suspended'; let releaseSuperseded; @@ -91,14 +93,12 @@ try { releaseSuperseded(); await Promise.resolve(); assert.equal(healthy.voices, 4, 'a superseded resume must not duplicate the newer cue'); - tick(315); healthy.frozen = true; playRecordStartCue(); tick(315); const recovered = FakeContext.instances[2]; assert.equal(healthy.closeCalls, 1, 'running with a frozen clock must recover'); assert.equal(recovered.voices, 2); - tick(315); // The original stop/time boundary survives recreation, so a late retry stays silent. recovered.state = 'suspended'; playRecordStartCue(); @@ -109,7 +109,6 @@ try { playRecordStartCue(); const next = FakeContext.instances[3]; assert.equal(next.voices, 2, 'the next recording still works after a dropped cue'); - tick(315); next.state = 'suspended'; next.resumeImpl = () => { throw new Error('audio interrupted'); @@ -132,21 +131,116 @@ try { releaseRetry(); await Promise.resolve(); assert.equal(retry.voices, 0, 'a recreated context cannot reset the late-cue deadline'); + assert.equal(retry.closeCalls, 1, 'a late successful resume must release its silent output'); + FakeContext.initialState = 'running'; playRecordStartCue(); - assert.equal(retry.voices, 2, 'dropping the old cue must not disable the next recording'); - tick(315); + const fresh = FakeContext.instances[7]; + assert.equal(fresh.voices, 2, 'dropping the old cue must not disable the next recording'); - retry.state = 'suspended'; - retry.resumeImpl = () => Promise.reject(new Error('device changed')); + fresh.state = 'suspended'; + fresh.resumeImpl = () => Promise.reject(new Error('device changed')); FakeContext.initialState = 'running'; playRecordStartCue(); await Promise.resolve(); - assert.equal(retry.closeCalls, 1, 'asynchronous resume rejection also releases the context'); - assert.equal(FakeContext.instances[7].voices, 2, 'device-change recovery plays only one cue'); + assert.equal(fresh.closeCalls, 1, 'asynchronous resume rejection also releases the context'); + const finalCue = FakeContext.instances[8]; + assert.equal(finalCue.voices, 2, 'device-change recovery plays only one cue'); tick(315); + assert.equal(finalCue.closeCalls, 1, 'natural cue completion releases the output device'); + + // No startup priming: import/disposal does not create a context. Every new preview or + // recording can still play after the previous context was closed. + const idleCount = FakeContext.instances.length; + disposeAudioCue(); + tick(1000); + assert.equal(FakeContext.instances.length, idleCount, 'idle cleanup never creates audio'); + playRecordStartCue(); + const stopped = FakeContext.instances.at(-1); + assert.equal(stopped.voices, 2); + stopAudioCue(); + tick(30); + assert.equal(stopped.closeCalls, 1, 'stopping a playing cue releases output after its ramp'); + + playRecordStartCue(); + const rapid = FakeContext.instances.at(-1); + stopAudioCue(); + tick(10); + playRecordStartCue(); + tick(20); + assert.equal(rapid.closeCalls, 0, 'old stop cleanup cannot close a newer cue'); + tick(295); + assert.equal(rapid.closeCalls, 1, 'the newer cue also releases output when finished'); + + // Disabling the preference / unmounting is stronger than a recording stop: a pending + // resume must never revive audio or start a recovery retry after disposal. + let releaseDisposed; + FakeContext.initialState = 'suspended'; + FakeContext.initialResumeImpl = () => new Promise((resolve) => (releaseDisposed = resolve)); + playRecordStartCue(); + const disposed = FakeContext.instances.at(-1); + disposeAudioCue(); + const disposedCount = FakeContext.instances.length; + disposed.state = 'running'; + releaseDisposed(); + await Promise.resolve(); + tick(1000); + assert.equal(disposed.closeCalls, 1); + assert.equal(disposed.voices, 0, 'disabled/unmounted listeners cannot play a late cue'); + assert.equal(FakeContext.instances.length, disposedCount, 'disposal cancels recovery timers'); + + // A quick recording still gets feedback when resume settles within the original deadline. + let releaseQuick; + FakeContext.initialResumeImpl = () => new Promise((resolve) => (releaseQuick = resolve)); + playRecordStartCue(); + const quick = FakeContext.instances.at(-1); + stopAudioCue(); + tick(100); + quick.state = 'running'; + releaseQuick(); + await Promise.resolve(); + assert.equal(quick.voices, 2, 'quick recordings keep start feedback without startup priming'); + tick(315); + assert.equal(quick.closeCalls, 1); + + FakeContext.initialState = 'running'; + playRecordStartCue(); + const ended = FakeContext.instances.at(-1); + ended.oscillators[0].onended(); + assert.equal(ended.closeCalls, 0, 'one ending tone cannot cut off the remaining tone'); + ended.oscillators[1].onended(); + assert.equal(ended.closeCalls, 1, 'the final tone releases output without waiting for a timer'); + + playRecordStartCue(); + const superseded = FakeContext.instances.at(-1); + const oldVoices = [...superseded.oscillators]; + playRecordStartCue(); + for (const voice of oldVoices) voice.onended(); + assert.equal(superseded.closeCalls, 0, 'old onended callbacks cannot close a newer cue'); + tick(315); + assert.equal(superseded.closeCalls, 1); + + playRecordStartCue(); + const disabledWhilePlaying = FakeContext.instances.at(-1); + disposeAudioCue(); + assert.equal(disabledWhilePlaying.closeCalls, 1, 'disabling an active cue releases immediately'); + tick(1000); + assert.equal(disabledWhilePlaying.closeCalls, 1, 'stale timers cannot dispose twice'); + + const originalCreateOscillator = FakeContext.prototype.createOscillator; + FakeContext.prototype.createOscillator = () => { + throw new Error('audio node creation failed'); + }; + try { + assert.doesNotThrow(playRecordStartCue); + const failedSynthesis = FakeContext.instances.at(-1); + tick(315); + assert.equal(failedSynthesis.closeCalls, 1, 'failed synthesis cannot leak a silent output'); + } finally { + FakeContext.prototype.createOscillator = originalCreateOscillator; + } console.log('[audioCue.runtime.test] playback recovery assertions passed'); } finally { - stopAudioCue(); + disposeAudioCue(); mock.restoreAll(); mock.timers.reset(); if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow); diff --git a/openless-all/app/scripts/capsule-ready-replay.test.mjs b/openless-all/app/scripts/capsule-ready-replay.test.mjs index dc9c38c8b..cd7a1d0ac 100644 --- a/openless-all/app/scripts/capsule-ready-replay.test.mjs +++ b/openless-all/app/scripts/capsule-ready-replay.test.mjs @@ -313,7 +313,9 @@ function transcript(view, sequence, text, sessionId = 'session') { transcript(view, 11, 'updated text'); assert.equal(view.values.setLocalAsrText, 'updated text'); assert.deepEqual(view.traceCalls.at(-1), { - sequence: 11, before: 'existing text', after: 'updated text', + sequence: 11, + before: 'existing text', + after: 'updated text', }); view.emit('capsule:state', { state: 'done', sessionId: 'session' }); assert.equal(view.values.setLocalAsrText, ''); @@ -675,6 +677,7 @@ for (const overlay of [false, true]) { let plays = 0; let primes = 0; let stops = 0; + let disposals = 0; const scope = { audioCueRuntimeEnabled: true, prevStateRef: { current: 'idle' }, @@ -683,6 +686,7 @@ for (const overlay of [false, true]) { primeAudioCue: () => primes++, playRecordStartCue: () => plays++, stopAudioCue: () => stops++, + disposeAudioCue: () => disposals++, require(name) { if (name === '@tauri-apps/api/webviewWindow') return { getCurrentWebviewWindow: () => ({ label }) }; @@ -698,7 +702,7 @@ for (const overlay of [false, true]) { await tick(); const primary = label === 'capsule'; assert.equal(bus.size, primary ? 2 : 0, 'only the resident capsule may own cue subscriptions'); - assert.equal(primes, primary ? 1 : 0, 'opening another WebView must not prime the cue'); + assert.equal(primes, 0, 'mounting any WebView must leave the output device closed'); assert.equal(plays, 0, 'mounting cannot replay a recording edge'); bus.emit('capsule-mirror-0', 'capsule:state', { state: 'recording' }); assert.equal(plays, 0, 'a mirror event cannot play the primary capsule cue'); @@ -707,8 +711,13 @@ for (const overlay of [false, true]) { assert.equal(plays, primary ? 1 : 0, 'only a fresh primary recording edge may play'); bus.emit('capsule', 'capsule:state', { state: 'done' }); assert.equal(stops, primary ? 1 : 0); + bus.emit('capsule', 'prefs:changed', { audioCueOnRecord: false }); + assert.equal(disposals, primary ? 1 : 0, 'disabling cues disposes the owned output'); + bus.emit('capsule', 'capsule:state', { state: 'recording' }); + assert.equal(plays, primary ? 1 : 0, 'disabled cues cannot play on a new recording'); cleanup(); assert.equal(bus.size, 0); + assert.equal(disposals, primary ? 2 : 0, 'only the cue owner disposes output on unmount'); } } { 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/voice-edit-open-dispatch-contract.test.mjs b/openless-all/app/scripts/voice-edit-open-dispatch-contract.test.mjs index d0e1ba283..23278ec78 100644 --- a/openless-all/app/scripts/voice-edit-open-dispatch-contract.test.mjs +++ b/openless-all/app/scripts/voice-edit-open-dispatch-contract.test.mjs @@ -29,7 +29,8 @@ test('voice edit creation leaves the synchronous IPC handler and retains main-on command, /#\[cfg\(target_os = "windows"\)\]\s*#\[tauri::command\]\s*pub async fn voice_edit_window_open\(/, ); - assert.match(body, /show_voice_edit\(\);[\s\S]*Ok\(\(\)\)/); + assert.match(body, /spawn_blocking\(move \|\| host\.show_voice_edit\(\)\)/); + assert.match(body, /\.await\s*\.map_err\([\s\S]*\)\?/); assert.doesNotMatch( body, /start_voice_edit_session\(/, @@ -48,7 +49,7 @@ test('non-Windows keeps its synchronous command and main-only presentation contr const body = command.slice(start, end); assert.match(body, /window\.label\(\) != "main"/); assert.ok(body.indexOf('return Err(') < body.indexOf('show_voice_edit()')); - assert.match(body, /show_voice_edit\(\);\s*Ok\(\(\)\)/); + assert.match(body, /coord\.tauri_host\(\)\.show_voice_edit\(\)\s*\}/); assert.doesNotMatch(body, /start_voice_edit_session\(|commit_voice_edit/); }); diff --git a/openless-all/app/scripts/voice-edit-window-open-contract.test.mjs b/openless-all/app/scripts/voice-edit-window-open-contract.test.mjs new file mode 100644 index 000000000..efd023fcc --- /dev/null +++ b/openless-all/app/scripts/voice-edit-window-open-contract.test.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const appRoot = fileURLToPath(new URL('..', import.meta.url)); +const read = (relativePath) => readFile(join(appRoot, relativePath), 'utf8'); + +const commands = await read('src-tauri/src/commands/voice_edit.rs'); +const openStart = commands.indexOf('pub async fn voice_edit_window_open'); +const openEnd = commands.indexOf('#[tauri::command]', openStart); +const openCommand = commands.slice(openStart, openEnd); +assert(openStart !== -1, 'Voice Edit must open through an async Tauri command'); +assert( + openCommand.includes('window.label() != "main"') && + openCommand.indexOf('window.label() != "main"') < openCommand.indexOf('spawn_blocking'), + 'Voice Edit open stays restricted to the main window before creating a WebView', +); +assert( + openCommand.includes('tauri::async_runtime::spawn_blocking(move || host.show_voice_edit())') && + /\.await\s*\n\s*\.map_err\(/.test(openCommand), + 'Windows WebView creation must leave the IPC thread and return worker errors', +); + +const host = await read('src-tauri/src/tauri_coordinator_host.rs'); +const showStart = host.indexOf('pub(crate) fn show_voice_edit('); +const showEnd = host.indexOf('pub(crate) fn ', showStart + 1); +const show = host.slice(showStart, showEnd); +assert( + show.includes('Result<(), String>') && show.includes('crate::show_voice_edit_window(&app)'), + 'Voice Edit window creation failures must propagate to the caller', +); + +const settings = await read('src/features/input/SelectionWorkspaceSection.tsx'); +assert( + settings.includes('openPanelBusy') && + settings.includes('aria-busy={openPanelBusy}') && + settings.includes("t('common.operationFailed')") && + settings.includes('setOpenPanelError'), + 'the Voice Edit open button must show a busy state and surface window errors', +); + +console.log('voice-edit-window-open-contract.test.mjs passed'); 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/backend-tests/tests/voice_edit_host.rs b/openless-all/app/src-tauri/backend-tests/tests/voice_edit_host.rs index 9aa58cde6..67ee04e02 100644 --- a/openless-all/app/src-tauri/backend-tests/tests/voice_edit_host.rs +++ b/openless-all/app/src-tauri/backend-tests/tests/voice_edit_host.rs @@ -81,6 +81,10 @@ impl FakeHost { fn set_voice_edit_interactive(&self, interactive: bool) { self.0.store(interactive, Ordering::SeqCst); } + #[cfg(target_os = "android")] + fn show_voice_edit(&self) -> Result<(), String> { + Ok(()) + } } #[derive(Default)] struct FakeInserter(Arc>); 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/commands/voice_edit.rs b/openless-all/app/src-tauri/src/commands/voice_edit.rs index 370ae4a3b..c985e4bc1 100644 --- a/openless-all/app/src-tauri/src/commands/voice_edit.rs +++ b/openless-all/app/src-tauri/src/commands/voice_edit.rs @@ -3,8 +3,6 @@ use super::CoordinatorState; /// Opens the desktop Voice Edit panel or asks Android's main WebView to show /// its embedded equivalent. The session starts only after the panel invokes /// `start_voice_edit_session`. -// WebView2 creation from a synchronous IPC callback can deadlock on Windows. -// An async command lets that callback return before creating the panel. #[cfg(target_os = "windows")] #[tauri::command] pub async fn voice_edit_window_open( @@ -14,8 +12,12 @@ pub async fn voice_edit_window_open( if window.label() != "main" { return Err("Voice Edit can only be opened from the main window".to_string()); } - coord.tauri_host().show_voice_edit(); - Ok(()) + let host = coord.tauri_host(); + // Windows WebView2 creation deadlocks inside a synchronous IPC handler. + // The first open builds the panel, so it must leave the UI thread. + tauri::async_runtime::spawn_blocking(move || host.show_voice_edit()) + .await + .map_err(|error| format!("Voice Edit window task failed: {error}"))? } #[cfg(not(target_os = "windows"))] @@ -27,8 +29,7 @@ pub fn voice_edit_window_open( if window.label() != "main" { return Err("Voice Edit can only be opened from the main window".to_string()); } - coord.tauri_host().show_voice_edit(); - Ok(()) + coord.tauri_host().show_voice_edit() } #[tauri::command] diff --git a/openless-all/app/src-tauri/src/coordinator.rs b/openless-all/app/src-tauri/src/coordinator.rs index c5e5bc1e4..74815b611 100644 --- a/openless-all/app/src-tauri/src/coordinator.rs +++ b/openless-all/app/src-tauri/src/coordinator.rs @@ -985,7 +985,12 @@ impl Coordinator { } pub(crate) async fn finalize_voice_edit_from_overlay(&self) -> Result<(), String> { voice_edit_session::from_overlay(&self.inner).await?; - self.inner.host.show_voice_edit(); + // The recording is already owned by the session. A panel show failure + // must not be reported as a failed capture, or Android offers a retry + // that the consumed recording can no longer satisfy. + if let Err(error) = self.inner.host.show_voice_edit() { + log::warn!("[voice-edit] overlay panel show failed: {error}"); + } Ok(()) } pub(crate) async fn finish_voice_edit_dictation( 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/coordinator/voice_edit_session.rs b/openless-all/app/src-tauri/src/coordinator/voice_edit_session.rs index d66903f91..5870b2f18 100644 --- a/openless-all/app/src-tauri/src/coordinator/voice_edit_session.rs +++ b/openless-all/app/src-tauri/src/coordinator/voice_edit_session.rs @@ -399,7 +399,7 @@ pub(super) async fn commit(inner: &Arc, id: SessionId) -> Result { let _ = session.recover_commit(); #[cfg(target_os = "android")] - inner.host.show_voice_edit(); + let _ = inner.host.show_voice_edit(); return Err(error); } }; 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..0a0743e42 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))] @@ -3080,9 +3072,9 @@ const VOICE_EDIT_WINDOW_HEIGHT: f64 = 620.0; #[cfg(not(any(target_os = "android", target_os = "ios")))] fn ensure_voice_edit_window( app: &AppHandle, -) -> Option> { +) -> Result, String> { if let Some(window) = app.get_webview_window("voice-edit") { - return Some(window); + return Ok(window); } match WebviewWindowBuilder::new( app, @@ -3107,28 +3099,25 @@ fn ensure_voice_edit_window( #[cfg(target_os = "macos")] { let window_clone = window.clone(); - let _ = app.run_on_main_thread(move || { + app.run_on_main_thread(move || { make_chat_window_panel_macos(&window_clone, "voice-edit"); make_chat_window_draggable_macos(&window_clone, "voice-edit"); - }); + }) + .map_err(|error| { + log::warn!("[voice-edit] panel setup dispatch failed: {error}"); + format!("Voice Edit panel setup dispatch failed: {error}") + })?; } - Some(window) + Ok(window) } Err(error) => { log::warn!("[voice-edit] create panel failed: {error}"); - None + Err(format!("Voice Edit window creation failed: {error}")) } } } -#[cfg(any(target_os = "android", target_os = "ios"))] -fn ensure_voice_edit_window( - app: &AppHandle, -) -> Option> { - app.get_webview_window("voice-edit") -} - -pub(crate) fn show_voice_edit_window(app: &AppHandle) { +pub(crate) fn show_voice_edit_window(app: &AppHandle) -> Result<(), String> { #[cfg(target_os = "android")] if let Err(error) = crate::android::jni::android::with_android_env(|env, context| { crate::android::jni::android::open_qa_host(env, context) @@ -3138,39 +3127,53 @@ pub(crate) fn show_voice_edit_window(app: &AppHandle) { #[cfg(any(target_os = "android", target_os = "ios"))] { let _ = app.emit_to("main", "voice-edit:show", serde_json::json!({})); - return; + return Ok(()); } - let Some(window) = ensure_voice_edit_window(app) else { - return; - }; - #[cfg(target_os = "macos")] + #[cfg(not(any(target_os = "android", target_os = "ios")))] { - let window_clone = window.clone(); - let _ = app.run_on_main_thread(move || { - use objc2::msg_send; - use objc2::runtime::AnyObject; - match window_clone.ns_window() { - Ok(handle) if !handle.is_null() => unsafe { - let ns = handle as *mut AnyObject; - let _: () = msg_send![ns, orderFrontRegardless]; - }, - _ => { - let _ = window_clone.show(); + let window = ensure_voice_edit_window(app)?; + #[cfg(target_os = "macos")] + { + let window_clone = window.clone(); + app.run_on_main_thread(move || { + use objc2::msg_send; + use objc2::runtime::AnyObject; + match window_clone.ns_window() { + Ok(handle) if !handle.is_null() => unsafe { + let ns = handle as *mut AnyObject; + let _: () = msg_send![ns, orderFrontRegardless]; + }, + _ => { + let _ = window_clone.show(); + } } + }) + .map_err(|error| { + log::warn!("[voice-edit] show dispatch failed: {error}"); + format!("Voice Edit window show dispatch failed: {error}") + })?; + } + #[cfg(target_os = "windows")] + { + // Preserve the external editor until capture; QA's helper deliberately focuses its WebView. + if let Err(error) = window.set_focusable(false) { + log::warn!("[voice-edit] set_focusable failed: {error}"); } - }); + window.show().map_err(|error| { + log::warn!("[voice-edit] show failed: {error}"); + format!("Voice Edit window show failed: {error}") + })?; + } + #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] + window.show().map_err(|error| { + log::warn!("[voice-edit] show failed: {error}"); + format!("Voice Edit window show failed: {error}") + })?; + VOICE_EDIT_PANEL_EPOCH.fetch_add(1, Ordering::SeqCst); + let _ = app.emit_to("voice-edit", "voice-edit:shown", serde_json::json!({})); + Ok(()) } - #[cfg(target_os = "windows")] - { - // Preserve the external editor until capture; QA's helper deliberately focuses its WebView. - let _ = window.set_focusable(false); - let _ = window.show(); - } - #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] - let _ = window.show(); - VOICE_EDIT_PANEL_EPOCH.fetch_add(1, Ordering::SeqCst); - let _ = app.emit_to("voice-edit", "voice-edit:shown", serde_json::json!({})); } pub(crate) fn set_voice_edit_interactive(app: &AppHandle, interactive: bool) { 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-tauri/src/tauri_coordinator_host.rs b/openless-all/app/src-tauri/src/tauri_coordinator_host.rs index f02937d4a..0b47543f1 100644 --- a/openless-all/app/src-tauri/src/tauri_coordinator_host.rs +++ b/openless-all/app/src-tauri/src/tauri_coordinator_host.rs @@ -2581,10 +2581,11 @@ impl TauriCoordinatorHost { } } - pub(crate) fn show_voice_edit(&self) { - if let Some(app) = self.app() { - crate::show_voice_edit_window(&app); - } + pub(crate) fn show_voice_edit(&self) -> Result<(), String> { + let app = self + .app() + .ok_or_else(|| "Tauri AppHandle is not bound yet".to_string())?; + crate::show_voice_edit_window(&app) } pub(crate) fn hide_voice_edit(&self) { 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/AudioCue.tsx b/openless-all/app/src/features/capsule/AudioCue.tsx index b1608d671..ef7cb8098 100644 --- a/openless-all/app/src/features/capsule/AudioCue.tsx +++ b/openless-all/app/src/features/capsule/AudioCue.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'; import { createCapsuleSubscriptions } from '../../api/dictation'; import { getSettings } from '../../api/preferences'; import { getRuntimeEnvironment } from '../../runtime/environment'; -import { playRecordStartCue, primeAudioCue, stopAudioCue } from '../../lib/audioCue'; +import { disposeAudioCue, playRecordStartCue, stopAudioCue } from '../../lib/audioCue'; import type { CapsuleState } from '../../api/contracts'; export function AudioCueListener() { @@ -23,11 +23,13 @@ export function AudioCueListener() { if ((await events.label()) !== 'capsule' || disposed) return; owned = true; prevStateRef.current = 'idle'; - primeAudioCue(); if ( !(await events.preferences((next) => { preferenceRevision += 1; - if (next) audioCueEnabledRef.current = next.audioCueOnRecord !== false; + if (next) { + audioCueEnabledRef.current = next.audioCueOnRecord !== false; + if (!audioCueEnabledRef.current) disposeAudioCue(); + } })) ) return; @@ -47,13 +49,14 @@ export function AudioCueListener() { const preferences = await getSettings(); if (!disposed && observed === preferenceRevision) { audioCueEnabledRef.current = preferences.audioCueOnRecord !== false; + if (!audioCueEnabledRef.current) disposeAudioCue(); } })().catch(() => {}); return () => { disposed = true; events.dispose(); - if (owned) stopAudioCue(); + if (owned) disposeAudioCue(); }; }, [audioCueRuntimeEnabled]); 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 = {}) { (null); const [extraControlsOpen, setExtraControlsOpen] = useState(false); + const [openPanelBusy, setOpenPanelBusy] = useState(false); + const [openPanelError, setOpenPanelError] = useState(''); + + const openPanel = async () => { + if (openPanelBusy) return; + setOpenPanelBusy(true); + setOpenPanelError(''); + try { + await openVoiceEditWindow(); + } catch (error) { + setOpenPanelError(error instanceof Error ? error.message : String(error)); + } finally { + setOpenPanelBusy(false); + } + }; useEffect(() => { void getPlatformCapabilities().then(setPlatformCaps); @@ -51,7 +66,7 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu {showVoice && ( -
+
@@ -60,8 +75,9 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu /> + {openPanelError ? ( +
+ {t('common.operationFailed')}: {openPanelError} +
+ ) : null}
)} diff --git a/openless-all/app/src/features/settings/shell/tabs.tsx b/openless-all/app/src/features/settings/shell/tabs.tsx index d11e5eb96..21fa72471 100644 --- a/openless-all/app/src/features/settings/shell/tabs.tsx +++ b/openless-all/app/src/features/settings/shell/tabs.tsx @@ -741,7 +741,6 @@ export function AdvancedTab({ {item.id === 'polishStrategy' && } {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/app/src/lib/audioCue.ts b/openless-all/app/src/lib/audioCue.ts index 967fd6a34..f3787a415 100644 --- a/openless-all/app/src/lib/audioCue.ts +++ b/openless-all/app/src/lib/audioCue.ts @@ -69,6 +69,12 @@ let stopSeq = 0; const DEFERRED_CUE_LATE_THRESHOLD_MS = 400; const RESUME_TIMEOUT_MS = 250; let recoveryTimer: ReturnType | undefined; +let stopTimer: ReturnType | undefined; + +function clearStopTimer(): void { + clearTimeout(stopTimer); + stopTimer = undefined; +} function clearRecoveryTimer(): void { clearTimeout(recoveryTimer); @@ -217,13 +223,34 @@ function stopVoices(): void { /** Close/stop the cue: stop playing nodes and mark "a stop happened meanwhile" so pending resume callbacks can judge lateness. */ export function stopAudioCue(): void { stopSeq++; + const ctx = sharedCtx; + const wasPlaying = activeVoices.length > 0; stopVoices(); + // Allow the short release ramp to finish. A pending resume keeps its existing bounded + // recovery window so quick recordings still receive their start feedback. + if (ctx && wasPlaying) { + clearRecoveryTimer(); + clearStopTimer(); + const myPlay = playSeq; + stopTimer = setTimeout(() => { + if (myPlay === playSeq && sharedCtx === ctx) discardContext(ctx); + }, 30); + } +} + +/** Disable/unmount: cancel even pending resumes, without creating an audio context. */ +export function disposeAudioCue(): void { + playSeq++; + stopSeq++; + clearRecoveryTimer(); + clearStopTimer(); + if (sharedCtx) discardContext(sharedCtx); } // Actually schedule the synthesis nodes. Must be called while the AudioContext is running // (not suspended): when suspended, currentTime is frozen at the pause moment, so nodes would // be scheduled at stale timestamps -> silent and piling up. -function scheduleCueVoices(ctx: AudioContext): void { +function scheduleCueVoices(ctx: AudioContext, onComplete: () => void): void { // On rapid hotkey presses, stop the previous round first to keep overlap from building up. // Use stopVoices, not stopAudioCue: this must not invalidate its own generation. stopVoices(); @@ -255,6 +282,7 @@ function scheduleCueVoices(ctx: AudioContext): void { } catch { // noop } + if (activeVoices.length === 0) onComplete(); }; } catch { // One tone failing to create/schedule must not affect the rest. @@ -262,32 +290,10 @@ function scheduleCueVoices(ctx: AudioContext): void { } } -/** - * Prime the AudioContext: create and resume early so the ctx is already running when recording - * actually starts and playRecordStartCue can schedule synchronously, bypassing the - * suspended->resume async race — the root cause of lost cues on quick recordings. - * Note: under a strict autoplay policy a resume without a user gesture may be rejected - * (silently degraded), in which case priming does nothing and the playSeq/stopSeq + late - * threshold fallback in playRecordStartCue applies. Tauri WebViews are usually lenient about - * the first resume, so priming typically lets the common path take the synchronous branch. - * Call once when the capsule window mounts. - */ -export function primeAudioCue(): void { - // getContext already rebuilds a closed ctx; here we only need to wake suspended/interrupted. - const ctx = getContext(); - if (!ctx) return; - if (audioContextActionForState(ctx.state) === 'resume') { - try { - void ctx.resume().catch(() => undefined); - } catch { - discardContext(ctx); - } - } -} - /** Play the "recording started" cue. Silently degrades when Web Audio is unavailable or the context is suspended and cannot be resumed. */ export function playRecordStartCue(): void { clearRecoveryTimer(); + clearStopTimer(); const myPlay = ++playSeq; const stopAtRequest = stopSeq; const requestedAt = nowMs(); @@ -318,12 +324,21 @@ function playRecordStartCueOnce( }; const schedule = () => { const startedAt = ctx.currentTime; - scheduleCueVoices(ctx); + scheduleCueVoices(ctx, () => { + if (myPlay !== playSeq || sharedCtx !== ctx) return; + clearRecoveryTimer(); + discardContext(ctx); + }); // Some audio interruptions still report running while the audio clock is frozen; // proactively retire the ctx before the next keypress. recoveryTimer = setTimeout( () => { + if (myPlay !== playSeq || sharedCtx !== ctx) return; if (ctx.currentTime <= startedAt) recover(); + // A connected, silent AudioContext still holds the system output device (and on + // macOS prevents idle sleep). Close after the cue tail and clock-health check, + // including when onended is delayed or synthesis failed. Next play is lazy. + else discardContext(ctx); }, cueTotalDurationMs(recordStartCueTones()) + 50, ); @@ -351,6 +366,9 @@ function playRecordStartCueOnce( } else if (!runningAfterResume) { // Even if this round is already late, clear the bad context so the next recording can recover. recover(); + } else { + // A resumed but already-late cue must not leave a silent output stream alive. + discardContext(ctx); } }; 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"]: