diff --git a/.aoci/baseline.json b/.aoci/baseline.json index 3708d08fc..b23d3d49e 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-27T08:38:30Z", + "updated_at": "2026-11-29T14:50:58Z", "files": { ".gitattributes": { "role": "index", @@ -101,9 +101,9 @@ }, ".gitignore": { "role": "index", - "sha256": "21b69dc58a35d2491c9a9a718cbf8ab67ceefff2a3885ae3bf4443c2f8562bbc", - "size": 4031, - "normalized_sha256": "21b69dc58a35d2491c9a9a718cbf8ab67ceefff2a3885ae3bf4443c2f8562bbc" + "sha256": "8e1573f614c0fda748cad2f3b5d314c192855c4d6ac31094a2bac540c12be1f3", + "size": 4128, + "normalized_sha256": "8e1573f614c0fda748cad2f3b5d314c192855c4d6ac31094a2bac540c12be1f3" }, "Casks/openless.rb": { "role": "index", @@ -2749,9 +2749,9 @@ }, "openless-all/app/crates/openless-core/tests/dictation_target_capture.rs": { "role": "observe", - "sha256": "866235a04f2c3e6d7baf1f2e80ad6f7a134c45ca50a419fff79d51fbd61c503b", - "size": 57930, - "normalized_sha256": "866235a04f2c3e6d7baf1f2e80ad6f7a134c45ca50a419fff79d51fbd61c503b" + "sha256": "7e4750466687e8717ac37dfdd2f486f70d61f09b517119b4d34cbd5b6d214172", + "size": 83282, + "normalized_sha256": "7e4750466687e8717ac37dfdd2f486f70d61f09b517119b4d34cbd5b6d214172" }, "openless-all/app/crates/openless-core/tests/gemini_live_dictation.rs": { "role": "observe", @@ -2839,9 +2839,9 @@ }, "openless-all/app/crates/openless-core/tests/selection_contract.rs": { "role": "observe", - "sha256": "f198918269cfe9deb2068a44c0a77857ed02df446926931387ddc47b1ae401d4", - "size": 54166, - "normalized_sha256": "f198918269cfe9deb2068a44c0a77857ed02df446926931387ddc47b1ae401d4" + "sha256": "4cc66cb5f3aefa060cd3fa56672dbf31c6fd7af261c56f521a350ec2e368129b", + "size": 54148, + "normalized_sha256": "4cc66cb5f3aefa060cd3fa56672dbf31c6fd7af261c56f521a350ec2e368129b" }, "openless-all/app/crates/openless-core/tests/selection_voice_contract.rs": { "role": "observe", @@ -2855,6 +2855,12 @@ "size": 7466, "normalized_sha256": "fcf2305d3af79b9e0badd9179ff0191e9176d3c67d6378df951d1b4505247876" }, + "openless-all/app/crates/openless-core/tests/skip_auto_style.rs": { + "role": "observe", + "sha256": "e76288026a6f95ea38b8aac17d3d8f0a75b8705f389f345a14a2ef1aa4d0d495", + "size": 6757, + "normalized_sha256": "e76288026a6f95ea38b8aac17d3d8f0a75b8705f389f345a14a2ef1aa4d0d495" + }, "openless-all/app/crates/openless-core/tests/style_icon_contract.rs": { "role": "observe", "sha256": "3ed9930b3ca3dd588aa2774b695af89522300f0376e70b94ab9396117716d0b8", @@ -3041,6 +3047,24 @@ "size": 3700, "normalized_sha256": "6d8fe670fc10e530199c9f08f63f911a8942aea5c9eca3f4582292b2e71e1272" }, + "openless-all/app/e2e/linux-desktop-repairs.spec.ts": { + "role": "observe", + "sha256": "bc87afae7f78e53ea3c622f3f8381da7ee25ae1190223f054c61b81b0fcd6211", + "size": 2364, + "normalized_sha256": "bc87afae7f78e53ea3c622f3f8381da7ee25ae1190223f054c61b81b0fcd6211" + }, + "openless-all/app/e2e/linux-surface-transparency.spec.ts": { + "role": "observe", + "sha256": "067c027f675318777d2e803eebd238b295a138762113b34d2f9012340483eabc", + "size": 1391, + "normalized_sha256": "067c027f675318777d2e803eebd238b295a138762113b34d2f9012340483eabc" + }, + "openless-all/app/e2e/linux-system-interactions.spec.ts": { + "role": "observe", + "sha256": "cd50531ed12b5c8fbadf3574509377605e6af8886318798b100a62983dee306a", + "size": 4172, + "normalized_sha256": "cd50531ed12b5c8fbadf3574509377605e6af8886318798b100a62983dee306a" + }, "openless-all/app/e2e/live-input-settings.spec.ts": { "role": "observe", "sha256": "e2775f37cab53d15445fdf24a6ed8cef55ecf42d59e0d5b534d0ed59fb529097", @@ -4479,12 +4503,24 @@ "size": 66, "normalized_sha256": "3ecff2d17db9a4e56bfd37a6e703dc0c49d96657d32b0e2250a15d83755bc0fb" }, + "openless-all/app/src-tauri/backend-tests/tests/skip_auto_style_restore.rs": { + "role": "observe", + "sha256": "3247a80de6ecc5870ffc7300af2325cad09dba7946a24f34840236ac8c8db6a1", + "size": 334, + "normalized_sha256": "3247a80de6ecc5870ffc7300af2325cad09dba7946a24f34840236ac8c8db6a1" + }, "openless-all/app/src-tauri/backend-tests/tests/style_zip_transfer.rs": { "role": "observe", "sha256": "1b04a2272ed8bceb208bd8b1b41ea87b2a1cd8fa179a8c90210fb8480883bfc3", "size": 2017, "normalized_sha256": "1b04a2272ed8bceb208bd8b1b41ea87b2a1cd8fa179a8c90210fb8480883bfc3" }, + "openless-all/app/src-tauri/backend-tests/tests/support/translation_ask_host.rs": { + "role": "observe", + "sha256": "7d206203f4ee140986cff3cabce95056c1e64ec5a9097b2ae01af31c7aa616d3", + "size": 2113, + "normalized_sha256": "7d206203f4ee140986cff3cabce95056c1e64ec5a9097b2ae01af31c7aa616d3" + }, "openless-all/app/src-tauri/backend-tests/tests/textstream_process.rs": { "role": "observe", "sha256": "a5b7c071618d695a7c2c2e17898b6ecc9dcf5f6cec564981517f9a4fdf45db5e", @@ -4505,9 +4541,9 @@ }, "openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs": { "role": "observe", - "sha256": "2faf7dd6abce62d2cdcd068c7e4f08b41ad7c41b848cdfd8c8466f0f4867c0be", - "size": 1791, - "normalized_sha256": "2faf7dd6abce62d2cdcd068c7e4f08b41ad7c41b848cdfd8c8466f0f4867c0be" + "sha256": "e8823d15d1320b7186b94441e11fd0cac3c6c07faaa5895ce60a5e84be61756d", + "size": 2815, + "normalized_sha256": "e8823d15d1320b7186b94441e11fd0cac3c6c07faaa5895ce60a5e84be61756d" }, "openless-all/app/src-tauri/backend-tests/tests/uia_cursor_text.rs": { "role": "observe", @@ -7327,9 +7363,9 @@ }, "openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts": { "role": "observe", - "sha256": "e76081c595fcf42b16daa1682abde185ac5467874b822e97372988c49e8ede9e", - "size": 25466, - "normalized_sha256": "e76081c595fcf42b16daa1682abde185ac5467874b822e97372988c49e8ede9e" + "sha256": "a5ca779e12c942435eea458fc308341d6c019913f1d92af5c9806f584ee01180", + "size": 25474, + "normalized_sha256": "a5ca779e12c942435eea458fc308341d6c019913f1d92af5c9806f584ee01180" }, "openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx": { "role": "index", @@ -7729,9 +7765,9 @@ }, "openless-all/app/src/features/providers/ChannelList.test.ts": { "role": "observe", - "sha256": "71cd87fc4cd2e356cc470a69543ddd29b56ed68abe7739f5ab612119272fb783", - "size": 6176, - "normalized_sha256": "71cd87fc4cd2e356cc470a69543ddd29b56ed68abe7739f5ab612119272fb783" + "sha256": "53b3dc88b78a76b212a11b692d5e5f1f00d09efca4228e9fa0de9cd5ba0e05bc", + "size": 6276, + "normalized_sha256": "53b3dc88b78a76b212a11b692d5e5f1f00d09efca4228e9fa0de9cd5ba0e05bc" }, "openless-all/app/src/features/providers/ChannelList.tsx": { "role": "index", @@ -8683,9 +8719,9 @@ }, "openless-all/app/src/lib/history-retranscribe.test.ts": { "role": "observe", - "sha256": "06638232e42c1b3b933ed9e2453a6a8e90c0bd86de9f4ceae8879d7cfa6e6683", - "size": 1946, - "normalized_sha256": "06638232e42c1b3b933ed9e2453a6a8e90c0bd86de9f4ceae8879d7cfa6e6683" + "sha256": "d3bc5ab5173207d3242f8bfe91c4c084845552f251f565c976426d726b1f913e", + "size": 2286, + "normalized_sha256": "d3bc5ab5173207d3242f8bfe91c4c084845552f251f565c976426d726b1f913e" }, "openless-all/app/src/lib/history-retranscribe.ts": { "role": "index", @@ -9961,9 +9997,9 @@ }, "openless-all/app/src/ui/overlays/interactionController.test.ts": { "role": "observe", - "sha256": "83f9dc0b9f7fd16261db1a11a1674c70b78b81bfd232139bce46e31ff7036d1a", - "size": 2455, - "normalized_sha256": "83f9dc0b9f7fd16261db1a11a1674c70b78b81bfd232139bce46e31ff7036d1a" + "sha256": "9a4128bbd1c44dee3a3eeaf9e796c38468c22514a20a2bb904305fc5140cbb17", + "size": 3936, + "normalized_sha256": "9a4128bbd1c44dee3a3eeaf9e796c38468c22514a20a2bb904305fc5140cbb17" }, "openless-all/app/src/ui/overlays/interactionController.ts": { "role": "index", @@ -12963,54 +12999,6 @@ "size": 2520, "normalized_sha256": "00dbce44f95d3ec2d275c1d24808817b55610816d5642586888f7566ce9ca046" }, - "openless-all/linux/egui/tests/cpal_contract.rs": { - "role": "observe", - "sha256": "464bd2534c939f18d31bfbd1f05dbacabd2029aedfe81bb99f827a92a71de4c7", - "size": 1791, - "normalized_sha256": "464bd2534c939f18d31bfbd1f05dbacabd2029aedfe81bb99f827a92a71de4c7" - }, - "openless-all/linux/egui/tests/fcitx5_config_contract.rs": { - "role": "observe", - "sha256": "1a89dd0aa5d78e7079ad84b955fab81aa261e36562dd00348c6880817d425b87", - "size": 4178, - "normalized_sha256": "1a89dd0aa5d78e7079ad84b955fab81aa261e36562dd00348c6880817d425b87" - }, - "openless-all/linux/egui/tests/fcitx5_contract.rs": { - "role": "observe", - "sha256": "e012577063ce0e554426b69dd2b6c25b6bc2d8bacaf30c44c2e7f16d3163b5de", - "size": 3020, - "normalized_sha256": "e012577063ce0e554426b69dd2b6c25b6bc2d8bacaf30c44c2e7f16d3163b5de" - }, - "openless-all/linux/egui/tests/host_contract.rs": { - "role": "observe", - "sha256": "0b0c8a8cd0477705e56c73b785aa10f55264adc6cbc5a23c39c8e7fa9a60cfdc", - "size": 27907, - "normalized_sha256": "0b0c8a8cd0477705e56c73b785aa10f55264adc6cbc5a23c39c8e7fa9a60cfdc" - }, - "openless-all/linux/egui/tests/localization_contract.rs": { - "role": "observe", - "sha256": "ba34fd75d45e1f6c2c2f0cad3ed37a7b39d277235053760104fe41169a4c1a95", - "size": 11311, - "normalized_sha256": "ba34fd75d45e1f6c2c2f0cad3ed37a7b39d277235053760104fe41169a4c1a95" - }, - "openless-all/linux/egui/tests/provider_surface_contract.rs": { - "role": "observe", - "sha256": "d7f188ce2d4f9384f93d856e18ccb7ed6aef37e85940caef90a7969e199d329e", - "size": 2629, - "normalized_sha256": "d7f188ce2d4f9384f93d856e18ccb7ed6aef37e85940caef90a7969e199d329e" - }, - "openless-all/linux/egui/tests/secret_service_contract.rs": { - "role": "observe", - "sha256": "edaa58804da6db89d8770f6626ce2eedab46755ff4c5cb1b5a8070ed1d442572", - "size": 2064, - "normalized_sha256": "edaa58804da6db89d8770f6626ce2eedab46755ff4c5cb1b5a8070ed1d442572" - }, - "openless-all/linux/egui/tests/zh_user_visible_baseline.txt": { - "role": "observe", - "sha256": "2e201247f99e31910e64e6a67183cd9b59d52d362cc8d4120f53ff686f90c9ed", - "size": 5700, - "normalized_sha256": "2e201247f99e31910e64e6a67183cd9b59d52d362cc8d4120f53ff686f90c9ed" - }, "openless-all/linux/fcitx5-plugin/CMakeLists.txt": { "role": "index", "sha256": "441758e5c550eff47bf6c04dbd792aeb58e5b50f2abe1a07e85a3c9c0a18894e", @@ -13083,6 +13071,54 @@ "size": 12029, "normalized_sha256": "293deba5dfdb974fbcf8dcf891a30a51a36a8bba0047dc6bdf6a03194089b7fb" }, + "openless-all/linux/host/tests/cpal_contract.rs": { + "role": "observe", + "sha256": "12b03747b75788de311c631011f1f3677220c80d7246c5ab5284a70a5e350c4a", + "size": 1791, + "normalized_sha256": "12b03747b75788de311c631011f1f3677220c80d7246c5ab5284a70a5e350c4a" + }, + "openless-all/linux/host/tests/fcitx5_config_contract.rs": { + "role": "observe", + "sha256": "c3fb799407cf6b87250966264444ef632d0815ae435292d51c2a324fc5eb56a0", + "size": 4178, + "normalized_sha256": "c3fb799407cf6b87250966264444ef632d0815ae435292d51c2a324fc5eb56a0" + }, + "openless-all/linux/host/tests/fcitx5_contract.rs": { + "role": "observe", + "sha256": "ac18217fa259ea523667255acde5682d009e390be60f800fc4c762c3c7305aea", + "size": 3716, + "normalized_sha256": "ac18217fa259ea523667255acde5682d009e390be60f800fc4c762c3c7305aea" + }, + "openless-all/linux/host/tests/input_probe_contract.rs": { + "role": "observe", + "sha256": "cd6eeab0c238cc75e42b701f453ebb76889a61079ce3ea504f0bafffd3603a8c", + "size": 2255, + "normalized_sha256": "cd6eeab0c238cc75e42b701f453ebb76889a61079ce3ea504f0bafffd3603a8c" + }, + "openless-all/linux/host/tests/localization_contract.rs": { + "role": "observe", + "sha256": "e33e2a20eb5294f8c1b014ac99de449c3e2686254aa24dfa0be1d61b4361850e", + "size": 10112, + "normalized_sha256": "e33e2a20eb5294f8c1b014ac99de449c3e2686254aa24dfa0be1d61b4361850e" + }, + "openless-all/linux/host/tests/native_adapters_contract.rs": { + "role": "observe", + "sha256": "7e2aaf7230009e3d6a723b5d227b3159f117cbf6fb40a595e070aeabd0385620", + "size": 15275, + "normalized_sha256": "7e2aaf7230009e3d6a723b5d227b3159f117cbf6fb40a595e070aeabd0385620" + }, + "openless-all/linux/host/tests/secret_service_contract.rs": { + "role": "observe", + "sha256": "ebaa9435f7a7e5f9204dd136019bd0a98f07879cb8cb7c03d2b5b24e211848f7", + "size": 2064, + "normalized_sha256": "ebaa9435f7a7e5f9204dd136019bd0a98f07879cb8cb7c03d2b5b24e211848f7" + }, + "openless-all/linux/host/tests/zh_user_visible_baseline.txt": { + "role": "observe", + "sha256": "701b02012d8e8fd0811f0a1703b1d92f40bc01e9234def990b5a38082143c034", + "size": 5702, + "normalized_sha256": "701b02012d8e8fd0811f0a1703b1d92f40bc01e9234def990b5a38082143c034" + }, "openless-all/linux/scripts/check-linux-public-surface.ps1": { "role": "index", "sha256": "76fa76ae720bd5417d85836ec48a3c31bb8ee99c1b5a6f1c25801cda3e3845cf", diff --git a/.aoci/config.json b/.aoci/config.json index 6d5c8a9da..42341bc01 100644 --- a/.aoci/config.json +++ b/.aoci/config.json @@ -205,7 +205,8 @@ ] }, "installed_agents": [ - "codex" + "codex", + "pi" ], "automation": { "mode": "auto" diff --git a/.gitattributes b/.gitattributes index 632064b21..5b2e5346d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,8 +6,8 @@ *.yml text eol=lf *.desktop text eol=lf *.xml text eol=lf -openless-all/linux/egui/packaging/AppRun text eol=lf -openless-all/linux/egui/packaging/openless-desktop-integration text eol=lf +openless-all/linux/host/packaging/openless.desktop text eol=lf +openless-all/linux/host/packaging/top.openless.OpenLess.metainfo.xml text eol=lf # Keep imported model bytes and unified-diff context markers intact. *.mcy binary openless-all/app/scripts/micyou-dsp.patch text eol=lf whitespace=-blank-at-eol diff --git a/.github/actions/build-linux-packages/action.yml b/.github/actions/build-linux-packages/action.yml new file mode 100644 index 000000000..412b537d3 --- /dev/null +++ b/.github/actions/build-linux-packages/action.yml @@ -0,0 +1,167 @@ +name: Build Linux packages +description: > + Compile the Qt6 WebEngine host, the Rust backend and the React bundle, then + produce verified deb/rpm artifacts. Shared by CI and the release workflow so + the two cannot drift: exactly one definition of "how a Linux package is built". + +inputs: + revision-file: + description: Workspace-relative file holding the release revision used in the package version. + required: false + default: openless-all/linux/host/package-revision + +outputs: + version: + description: Package version (application version plus the -N revision). + value: ${{ steps.version.outputs.version }} + package-dir: + description: Absolute directory holding the deb/rpm and SHA256SUMS. + value: ${{ github.workspace }}/openless-all/app/target/linux-host-packages + +runs: + using: composite + steps: + - name: Install native build and packaging dependencies + uses: ./.github/actions/setup-linux-dependencies + + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Resolve package version + id: version + shell: bash + working-directory: openless-all/app + env: + REVISION_FILE: ${{ github.workspace }}/${{ inputs.revision-file }} + run: | + set -euo pipefail + VERSION=$(node -p "require('./package.json').version") + REVISION=$(< "$REVISION_FILE") + [[ "$REVISION" =~ ^[1-9][0-9]*$ ]] || { + echo "::error::$REVISION_FILE must hold a positive integer revision (got '$REVISION')" + exit 1 + } + echo "version=${VERSION%%+*}-$REVISION" >> "$GITHUB_OUTPUT" + + - uses: swatinem/rust-cache@v2 + with: + # Release-profile cache, separate from the test-profile one in `linux-check`. + shared-key: build-linux-host + workspaces: openless-all/app -> target + cache-on-failure: true + save-if: ${{ github.ref == 'refs/heads/beta' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} + + - name: Build the fcitx5 plugin + # 包内要装 `libopenless.so` + `openless.conf`;断言与 ctest 在 `linux-check` 里跑。 + working-directory: openless-all/linux/fcitx5-plugin + shell: bash + run: | + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr + cmake --build build --parallel + + - name: Validate Linux desktop metadata + shell: bash + run: | + desktop-file-validate openless-all/linux/host/packaging/openless.desktop + appstreamcli validate --no-net openless-all/linux/host/packaging/top.openless.OpenLess.metainfo.xml + + - name: Build the Rust backend + working-directory: openless-all/app + shell: bash + run: cargo build --locked --release -p openless-linux-host -p openless-linux-web + + - name: Install Qt6 WebEngine toolchain + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + qt6-base-dev qt6-declarative-dev qt6-webengine-dev \ + liblayershellqtinterface-dev qt6-wayland-dev \ + libqt6webenginewidgets6 libqt6webenginecore6 \ + libgtk-4-dev libwebkitgtk-6.0-dev libsoup-3.0-dev + # Older supported distro releases do not package GTK4 layer-shell yet. + if apt-cache show libgtk4-layer-shell-dev >/dev/null 2>&1; then + sudo apt-get install -y --no-install-recommends libgtk4-layer-shell-dev + fi + + # The packager always compiles Qt from source with the current distro's + # toolchain. No checkout mtimes or committed ELF influence the result. + + - name: Build the React frontend bundle + working-directory: openless-all/app + shell: bash + run: | + set -euo pipefail + # dist/ 不入库:包里的界面必须现场构建,否则会拿旧 bundle 打出 + # 「代码改了但界面没变」的包(本地踩过:dist 落后 4 天,能力屏蔽整段没生效)。 + npm ci --prefer-offline --no-audit --no-fund + VITE_OPENLESS_PLATFORM=gtk npx vite build --outDir ../linux/web/dist --emptyOutDir + + - name: Package Ubuntu deb + # This also rebuilds Rust so local packaging cannot reuse a stale cache. + working-directory: openless-all/app + shell: bash + env: + OPENLESS_LINUX_VERSION: ${{ steps.version.outputs.version }} + OPENLESS_LINUX_ARCH: x86_64 + run: | + # CI runners are disposable; ignore outputs restored by a cache. + rm -f target/linux-host-packages/*.deb target/linux-host-packages/*.rpm \ + target/linux-host-packages/SHA256SUMS + bash ../linux/scripts/package-linux-qt.sh --formats deb + bash ../linux/scripts/verify-linux-host-packages.sh --formats deb + + - name: Build Fedora RPM and verify in a clean Fedora container + shell: bash + env: + OPENLESS_LINUX_VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + artifacts="$RUNNER_TEMP/openless-fedora" + mkdir -p "$artifacts" + # All native code (including Rust) is compiled on Fedora. Only the + # architecture-independent React bundle crosses the distro boundary. + docker run --rm \ + -v "$GITHUB_WORKSPACE:/src:ro" -v "$artifacts:/artifacts" \ + -e OPENLESS_LINUX_VERSION \ + fedora:43 bash /src/openless-all/linux/scripts/fedora-host-packages.sh build + # A new container, without the build toolchain, resolves and installs + # runtime dependencies from Fedora's standard repositories. + docker run --rm \ + -v "$GITHUB_WORKSPACE:/src:ro" -v "$artifacts:/artifacts:ro" \ + fedora:43 bash /src/openless-all/linux/scripts/fedora-host-packages.sh verify + cp "$artifacts"/packages/*.rpm openless-all/app/target/linux-host-packages/ + + - name: Checksums and package verification + working-directory: openless-all/app + shell: bash + run: | + set -euo pipefail + OUTPUT=target/linux-host-packages + ( cd "$OUTPUT" && sha256sum ./*.deb ./*.rpm > SHA256SUMS ) + # 桌面与 Android 资产各有自己的 SHA256SUMS,Linux 这份换个名字。 + cp "$OUTPUT/SHA256SUMS" "$OUTPUT/SHA256SUMS-linux" + # Payload/ELF checks already ran in each native environment. Running + # Fedora ELF checks on Ubuntu would incorrectly reject its glibc/Qt ABI. + ( cd "$OUTPUT" && sha256sum --check --strict SHA256SUMS ) + + - name: Stage direct download aliases + working-directory: openless-all/app + shell: bash + run: | + set -euo pipefail + output=target/linux-host-packages + alias_dir="$RUNNER_TEMP/openless-linux-host-direct-download" + rm -rf "$alias_dir" + mkdir -p "$alias_dir" + debs=("$output"/OpenLess-Linux-*.deb) + rpms=("$output"/OpenLess-Linux-*.rpm) + test "${#debs[@]}" -eq 1 + test "${#rpms[@]}" -eq 1 + cp "${debs[0]}" "$alias_dir/OpenLess_linux_x86_64.deb" + cp "${rpms[0]}" "$alias_dir/OpenLess_linux_x86_64.rpm" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 755c1b7f8..8e487cce0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,7 @@ jobs: desktop-only: ${{ steps.detect.outputs.desktop-only }} tauri: ${{ steps.detect.outputs.tauri }} msrv: ${{ steps.detect.outputs.msrv }} + linux: ${{ steps.detect.outputs.linux }} harmony: ${{ steps.detect.outputs.harmony }} frontend: ${{ steps.detect.outputs.frontend }} android: ${{ steps.detect.outputs.android }} @@ -97,7 +98,7 @@ jobs: run: | set -euo pipefail echo "desktop-only=$DESKTOP_ONLY" | tee -a "$GITHUB_OUTPUT" - for area in tauri msrv harmony frontend android capsule ios-device; do + for area in tauri msrv linux harmony frontend android capsule ios-device; do verdict=$(bash scripts/ci-changed-areas.sh "$area" "$BASE_SHA") # 失败即运行:脚本读不到差异时返回 true,这里也只接受明确的 false。 decision=$( [ "$verdict" = 'false' ] && echo false || echo true ) @@ -664,7 +665,7 @@ jobs: # AppGallery needs a numeric versionName, so the packaging script keeps # only the numeric prefix ("2.0.2", not "2.0.2-Beta.1"). version_name=$(node -p "require('./package.json').version" | sed 's/[-+].*//') - version_code=$(cat ../linux/egui/package-revision) + version_code=$(cat ../linux/host/package-revision) bash ../harmony/scripts/verify-harmony-hap.sh \ target/harmony-packages/OpenLess_harmony_arm64.hap \ "${OPENLESS_HARMONY_TOOLCHAIN:-$HOME/.local/share/harmony/current}" \ @@ -699,24 +700,24 @@ jobs: - name: Validate locked workspace metadata run: | cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path Cargo.toml >/dev/null - cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path ../linux/egui/Cargo.toml >/dev/null + cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path ../linux/host/Cargo.toml >/dev/null - name: Test, lint and build the Linux host if: github.event_name != 'workflow_dispatch' run: | - cargo test --locked -p openless-linux-egui - cargo clippy --locked -p openless-linux-egui --all-targets -- -D warnings - cargo build --locked --release -p openless-linux-egui + cargo test --locked -p openless-linux-host + cargo clippy --locked -p openless-linux-host --all-targets -- -D warnings + cargo build --locked --release -p openless-linux-host - name: Check recording materials on the Linux host if: github.event_name == 'workflow_dispatch' run: | cargo test --locked -p openless-core --lib references_ - cargo test --locked -p openless-linux-egui --lib - cargo check --locked -p openless-linux-egui --bins + cargo test --locked -p openless-linux-host --lib + cargo check --locked -p openless-linux-web --bins - name: Exercise real X11 clipboard ownership and incremental transfers if: github.event_name == 'workflow_dispatch' run: | sudo apt-get install -y --no-install-recommends xvfb xauth xclip - xvfb-run -a cargo test --locked -p openless-linux-egui --lib references_x11_external_copies_and_app_owned_transfers_are_distinct -- --ignored --test-threads=1 + xvfb-run -a cargo test --locked -p openless-linux-host --lib references_x11_external_copies_and_app_owned_transfers_are_distinct -- --ignored --test-threads=1 - name: Build and test the Fcitx5 plugin run: | cmake -S ../linux/fcitx5-plugin -B ../linux/fcitx5-plugin/build @@ -727,10 +728,10 @@ jobs: run: | set -euo pipefail APP_VERSION=$(node -p "require('./package.json').version") - REVISION=$(cat ../linux/egui/package-revision) + REVISION=$(cat ../linux/host/package-revision) export OPENLESS_LINUX_VERSION="${APP_VERSION%%+*}-${REVISION}" - bash ../linux/scripts/package-linux-egui.sh - bash ../linux/scripts/verify-linux-egui-packages.sh + bash ../linux/scripts/package-linux-qt.sh --formats deb + bash ../linux/scripts/verify-linux-host-packages.sh --formats deb native-capsule: # The capsule crates compile into the desktop shells. They get their own macOS + Windows @@ -772,6 +773,122 @@ jobs: - run: cargo test --locked -p openless-capsule --features ui,host - run: cargo clippy --locked -p openless-native-capsule -p openless-capsule --features openless-capsule/ui,openless-capsule/host -- -D warnings + linux-check: + needs: [changes] + if: needs.changes.outputs.linux != 'false' + name: Linux checks + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + CARGO_PROFILE_DEV_DEBUG: 0 + CARGO_PROFILE_TEST_DEBUG: 0 + CARGO_TARGET_DIR: ${{ github.workspace }}/openless-all/app/target + steps: + - uses: actions/checkout@v6 + with: + submodules: false + + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Install native build and test dependencies + timeout-minutes: 10 + uses: ./.github/actions/setup-linux-dependencies + + - uses: swatinem/rust-cache@v2 + with: + shared-key: test-linux-host + workspaces: | + openless-all/app -> target + openless-all/app/src-tauri/backend-tests -> ../../target + cache-on-failure: true + save-if: ${{ github.ref == 'refs/heads/beta' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} + + - name: Build and test fcitx5 plugin + working-directory: openless-all/linux/fcitx5-plugin + run: | + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr + cmake --build build --parallel + ctest --test-dir build --output-on-failure + test -s build/libopenless.so + test -s build/openless.conf + + - name: Test Core, Linux host, and platform boundaries + timeout-minutes: 40 + working-directory: openless-all/app + run: | + set -euo pipefail + cargo test --locked -p openless-core + # 命名化重跑热键边沿门禁:上面的 cargo test 已经编好,这里几乎免费, + # 改名会在这里响,而不是悄悄丢掉门禁。 + cargo test --locked -p openless-core --lib \ + api::tests::shared_hotkey_edges_own_hold_auto_and_combo_abort_semantics -- --exact \ + | tee "$RUNNER_TEMP/openless-hotkey-edge.log" + grep -Fq 'test api::tests::shared_hotkey_edges_own_hold_auto_and_combo_abort_semantics ... ok' \ + "$RUNNER_TEMP/openless-hotkey-edge.log" + cargo test --locked -p openless-harmony-host + cargo clippy --locked -p openless-core --all-targets -- -D warnings + cargo test --locked -p openless-linux-host --all-targets + cargo clippy --locked -p openless-linux-host --all-targets -- -D warnings + node scripts/linux-host-tauri-free-contract.test.mjs + node scripts/linux-host-release-contract.test.mjs + node scripts/linux-multi-frontend.test.mjs + node scripts/ci-changed-areas.test.mjs + node scripts/ci-cache-usage.test.mjs + node scripts/ci-cache-sharing.test.mjs + node scripts/harmony-release-contract.test.mjs + node scripts/tauri-linux-free-contract.test.mjs + pwsh -NoProfile -File ./scripts/check-core-deps.ps1 + pwsh -NoProfile -File ./scripts/check-core-deps.ps1 openless-linux-host + pwsh -NoProfile -File ./scripts/check-core-secret-surface.ps1 + pwsh -NoProfile -File ./scripts/check-core-test-isolation.ps1 + pwsh -NoProfile -File ./scripts/check-core-runtime-seam.ps1 + pwsh -NoProfile -File ../linux/scripts/check-linux-public-surface.ps1 + + - name: Test remote input TLS identity and Unix key permissions + timeout-minutes: 20 + working-directory: openless-all/app + run: cargo test --locked --manifest-path src-tauri/backend-tests/Cargo.toml --test remote_tls + + linux-package: + needs: [changes] + if: needs.changes.outputs.linux != 'false' + name: Linux packages + # deb: Ubuntu 24.04 (glibc >= 2.39). The shared action builds all RPM + # native code in fedora:43 and installs/verifies it in a fresh Fedora container. + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v6 + with: + submodules: false + + - name: Build verified Ubuntu deb and Fedora RPM + uses: ./.github/actions/build-linux-packages + + - name: Upload verified packages + # push 构建只用来暖缓存,不产资产;PR 与 tag 构建才是消费者。 + if: github.event_name != 'push' + uses: actions/upload-artifact@v7 + with: + retention-days: 14 + name: openless-linux-host-x86_64 + path: openless-all/app/target/linux-host-packages/* + if-no-files-found: error + + - name: Upload direct download aliases + if: github.event_name != 'push' + uses: actions/upload-artifact@v7 + with: + retention-days: 14 + name: openless-linux-host-direct-download + path: ${{ runner.temp }}/openless-linux-host-direct-download/* + if-no-files-found: error + cross-platform: needs: [changes] # 失败即运行:只有判定脚本明确说“够不到”才跳过。 diff --git a/.github/workflows/linux-clipboard-validation.yml b/.github/workflows/linux-clipboard-validation.yml index bbdd8344b..4c9af794b 100644 --- a/.github/workflows/linux-clipboard-validation.yml +++ b/.github/workflows/linux-clipboard-validation.yml @@ -61,13 +61,13 @@ jobs: - name: Strict clippy for all Linux targets run: | set -euo pipefail - cargo clippy --locked -p openless-linux-egui --all-targets -- -D warnings 2>&1 | tee "$VALIDATION_SCRATCH/reports/clippy.log" + cargo clippy --locked -p openless-linux-host --all-targets -- -D warnings 2>&1 | tee "$VALIDATION_SCRATCH/reports/clippy.log" - name: Exercise successful and abandoned real X11 INCR transfers if: ${{ !cancelled() }} run: | set -euo pipefail sudo apt-get install -y --no-install-recommends xvfb xauth xclip - xvfb-run -a cargo test --locked -p openless-linux-egui --lib references_x11_ -- --ignored --test-threads=1 2>&1 | tee "$VALIDATION_SCRATCH/reports/x11.log" + xvfb-run -a cargo test --locked -p openless-linux-host --lib references_x11_ -- --ignored --test-threads=1 2>&1 | tee "$VALIDATION_SCRATCH/reports/x11.log" - uses: actions/upload-artifact@v4 if: always() && env.VALIDATION_SCRATCH != '' with: diff --git a/.github/workflows/release-harmony.yml b/.github/workflows/release-harmony.yml index eab9ffad5..9fdddebd4 100644 --- a/.github/workflows/release-harmony.yml +++ b/.github/workflows/release-harmony.yml @@ -322,13 +322,15 @@ jobs: # AppGallery needs a numeric versionName, so the packaging script keeps # only the numeric prefix ("2.0.2", not "2.0.2-Beta.1"). version_name=$(node -p "require('./package.json').version" | sed 's/[-+].*//') - # Historical tags may retain the app/scripts layout; prefer the checked-out new layout. - if [ -f ../linux/egui/package-revision ]; then + # Resolve the revision from the checked-out source, including older tags. + if [ -f ../linux/host/package-revision ]; then + revision_file=../linux/host/package-revision + elif [ -f ../linux/egui/package-revision ]; then revision_file=../linux/egui/package-revision elif [ -f linux-egui/package-revision ]; then revision_file=linux-egui/package-revision else - echo "::error::Missing source input: ../linux/egui/package-revision or linux-egui/package-revision" >&2 + echo "::error::Missing source input: package-revision in Linux host or historical layout" >&2 exit 1 fi version_code=$(cat "$revision_file") diff --git a/.github/workflows/release-tauri.yml b/.github/workflows/release-tauri.yml index 88245dacd..e860afcea 100644 --- a/.github/workflows/release-tauri.yml +++ b/.github/workflows/release-tauri.yml @@ -6,7 +6,7 @@ name: Release (all platforms) # # Outputs: # macOS arm64/x64 .dmg + Windows x64 .msi/.exe, uploaded automatically as GitHub Release assets. -# Linux egui CI/release is paused; local build/package scripts remain available. +# Linux is a job in this file (`linux`), gated on recorded device acceptance. # # macOS distribution: # - With APPLE_CERTIFICATE / APPLE_CERTIFICATE_PASSWORD / APPLE_ID / @@ -1221,3 +1221,66 @@ jobs: publish: true upload_to_appgallery: true secrets: inherit + + linux: + # Linux 包(Qt6 WebEngine 宿主 + openless-linux-web 后端)与桌面在同一个 + # 工作流里发布:构建 + 校验用 CI 那份 composite action,发布前要求该 tag 有 + # 真机验收记录(LINUX_ACCEPTED_RELEASE_TAG),否则整步跳过、不影响桌面/Android。 + name: Linux packages + needs: prepare-release + if: >- + github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && + endsWith(github.ref_name, '-tauri') && + vars.LINUX_ACCEPTED_RELEASE_TAG == github.ref_name + runs-on: ubuntu-24.04 + timeout-minutes: 90 + permissions: + contents: write + env: + GH_REPO: ${{ github.repository }} + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.ref_name }} + LINUX_ACCEPTED_RELEASE_TAG: ${{ vars.LINUX_ACCEPTED_RELEASE_TAG }} + steps: + - name: Verify exact-tag Linux acceptance + run: | + set -euo pipefail + if [ -z "$RELEASE_TAG" ] || [ "$LINUX_ACCEPTED_RELEASE_TAG" != "$RELEASE_TAG" ]; then + echo "::error::Linux device acceptance must be recorded for this exact release tag before publication." + exit 1 + fi + - uses: actions/checkout@v6 + with: + submodules: false + ref: ${{ github.ref_name }} + - name: Build verified deb/rpm + uses: ./.github/actions/build-linux-packages + - name: Attach Linux packages to the GitHub Release + run: | + set -euo pipefail + output=openless-all/app/target/linux-host-packages + alias_dir="$RUNNER_TEMP/openless-linux-host-direct-download" + for file in "$output"/OpenLess-Linux-*.deb "$output"/OpenLess-Linux-*.rpm \ + "$output/SHA256SUMS-linux" "$alias_dir/OpenLess_linux_x86_64.deb" \ + "$alias_dir/OpenLess_linux_x86_64.rpm"; do + [ -s "$file" ] || { echo "::error::missing Linux release asset $file"; exit 1; } + done + # 桌面作业先创建 Release,这里只等不抢。 + for attempt in $(seq 1 40); do + if gh release view "$RELEASE_TAG" --json isDraft > /dev/null 2>&1; then + break + fi + if [ "$attempt" = 40 ]; then + echo "::error::release $RELEASE_TAG was not created by the desktop workflow" + exit 1 + fi + sleep 15 + done + gh release upload "$RELEASE_TAG" \ + "$output"/OpenLess-Linux-*.deb \ + "$output"/OpenLess-Linux-*.rpm \ + "$output/SHA256SUMS-linux" \ + "$alias_dir/OpenLess_linux_x86_64.deb" \ + "$alias_dir/OpenLess_linux_x86_64.rpm" \ + --clobber + echo "attached Linux assets to $RELEASE_TAG" diff --git a/.gitignore b/.gitignore index baec5839f..2196a49a7 100644 --- a/.gitignore +++ b/.gitignore @@ -139,6 +139,8 @@ CapsWriter /openless-all/app/pnpm-workspace.yaml # Local Linux toolchains, build logs and packaging workspaces. +# Legacy in-source Qt build output must never become a packaging input again. +/openless-all/linux/qt/openless-qt openless-all/app/.cache/ __pycache__/ @@ -168,3 +170,7 @@ coverage/ /docs/test-captures/ /docs/test-results/ /openless-all/ios/docs/screenshots/ + +# AOCI agent host integration (machine-bound; do not commit) +.pi/mcp.json +.pi/mcp.json.backup.* diff --git a/docs/images/client-diagrams/openless-client-architecture.mmd b/docs/images/client-diagrams/openless-client-architecture.mmd index 7fa54cd68..bc299e2d8 100644 --- a/docs/images/client-diagrams/openless-client-architecture.mmd +++ b/docs/images/client-diagrams/openless-client-architecture.mmd @@ -38,7 +38,7 @@ flowchart LR end subgraph OTHER[Other platform hosts] - LINUX[Linux egui host\nOpenLessBackend / native UI] + LINUX[Linux Linux host host\nOpenLessBackend / native UI] ANDROID[Android native services\nJNI / Kotlin / IME] HARMONY[HarmonyOS host\nArkTS / Rust bridge] LINUX --> CORE diff --git a/docs/images/client-diagrams/openless-client-architecture.svg b/docs/images/client-diagrams/openless-client-architecture.svg index 44d4ca63d..f19ac948c 100644 --- a/docs/images/client-diagrams/openless-client-architecture.svg +++ b/docs/images/client-diagrams/openless-client-architecture.svg @@ -1 +1 @@ -

External systems

Other platform hosts

Tauri desktop and Android hosts

WebView UI

optional sync

style packs

App.tsx
window router

FloatingShell
settings / pages

DesktopOnboarding
startup guide

Capsule
resident voice surface

Capsule rail / mirrors

src/lib/ipc
Tauri bridge barrel

src-tauri/src/lib.rs
window lifecycle / commands

Coordinator
hotkeys / session ownership

tauri_events.rs
backend:event / capsule:state

desktop_resources.rs
main WebView lifecycle

commands/*
settings / permissions / credentials

recorder.rs
microphone capture

openless-core
dictation engine / provider policy

persistence
preferences / credentials / history

native capsule / platform adapters

Linux egui host
OpenLessBackend / native UI

Android native services
JNI / Kotlin / IME

HarmonyOS host
ArkTS / Rust bridge

ASR providers
cloud / local runtime

LLM / polish providers

Encrypted cloud sync

Style pack marketplace

macOS TCC / Windows permissions

\ No newline at end of file +

External systems

Other platform hosts

Tauri desktop and Android hosts

WebView UI

optional sync

style packs

App.tsx
window router

FloatingShell
settings / pages

DesktopOnboarding
startup guide

Capsule
resident voice surface

Capsule rail / mirrors

src/lib/ipc
Tauri bridge barrel

src-tauri/src/lib.rs
window lifecycle / commands

Coordinator
hotkeys / session ownership

tauri_events.rs
backend:event / capsule:state

desktop_resources.rs
main WebView lifecycle

commands/*
settings / permissions / credentials

recorder.rs
microphone capture

openless-core
dictation engine / provider policy

persistence
preferences / credentials / history

native capsule / platform adapters

Linux Linux host host
OpenLessBackend / native UI

Android native services
JNI / Kotlin / IME

HarmonyOS host
ArkTS / Rust bridge

ASR providers
cloud / local runtime

LLM / polish providers

Encrypted cloud sync

Style pack marketplace

macOS TCC / Windows permissions

\ No newline at end of file diff --git a/docs/images/client-diagrams/openless-client-architecture.zh-CN.mmd b/docs/images/client-diagrams/openless-client-architecture.zh-CN.mmd index 5a61889a7..da1b54170 100644 --- a/docs/images/client-diagrams/openless-client-architecture.zh-CN.mmd +++ b/docs/images/client-diagrams/openless-client-architecture.zh-CN.mmd @@ -38,7 +38,7 @@ flowchart LR end subgraph OTHER[其他平台宿主] - LINUX[Linux egui 宿主\nOpenLessBackend / 原生界面] + LINUX[Linux Linux host 宿主\nOpenLessBackend / 原生界面] ANDROID[Android 原生服务\nJNI / Kotlin / 输入法] HARMONY[HarmonyOS 宿主\nArkTS / Rust 桥接] LINUX --> CORE diff --git a/docs/images/client-diagrams/openless-client-architecture.zh-CN.svg b/docs/images/client-diagrams/openless-client-architecture.zh-CN.svg index 9a608d1e8..985b4a168 100644 --- a/docs/images/client-diagrams/openless-client-architecture.zh-CN.svg +++ b/docs/images/client-diagrams/openless-client-architecture.zh-CN.svg @@ -1 +1 @@ -

外部系统

其他平台宿主

Tauri 桌面与 Android 宿主

WebView 界面

可选同步

风格包目录

App.tsx
窗口路由

主界面
设置与业务页面

桌面首次引导
DesktopOnboarding

语音胶囊
常驻交互面

胶囊轨道与镜像

前端 IPC
Tauri 桥接门面

src-tauri/src/lib.rs
命令与窗口生命周期

Coordinator
快捷键与会话所有权

tauri_events.rs
语义事件与胶囊状态

desktop_resources.rs
主窗口生命周期

commands/*
设置、权限与凭据

recorder.rs
麦克风采集

openless-core
听写引擎与服务策略

persistence
偏好、凭据与历史

原生胶囊与平台适配

Linux egui 宿主
OpenLessBackend / 原生界面

Android 原生服务
JNI / Kotlin / 输入法

HarmonyOS 宿主
ArkTS / Rust 桥接

语音识别服务
云端或本地运行时

大语言模型与润色服务

加密云同步

风格包市场

macOS TCC / Windows 权限

\ No newline at end of file +

外部系统

其他平台宿主

Tauri 桌面与 Android 宿主

WebView 界面

可选同步

风格包目录

App.tsx
窗口路由

主界面
设置与业务页面

桌面首次引导
DesktopOnboarding

语音胶囊
常驻交互面

胶囊轨道与镜像

前端 IPC
Tauri 桥接门面

src-tauri/src/lib.rs
命令与窗口生命周期

Coordinator
快捷键与会话所有权

tauri_events.rs
语义事件与胶囊状态

desktop_resources.rs
主窗口生命周期

commands/*
设置、权限与凭据

recorder.rs
麦克风采集

openless-core
听写引擎与服务策略

persistence
偏好、凭据与历史

原生胶囊与平台适配

Linux Linux host 宿主
OpenLessBackend / 原生界面

Android 原生服务
JNI / Kotlin / 输入法

HarmonyOS 宿主
ArkTS / Rust 桥接

语音识别服务
云端或本地运行时

大语言模型与润色服务

加密云同步

风格包市场

macOS TCC / Windows 权限

\ No newline at end of file diff --git a/docs/linux-backend-api-plan-p0-p3.md b/docs/linux-backend-api-plan-p0-p3.md new file mode 100644 index 000000000..ac48e1d32 --- /dev/null +++ b/docs/linux-backend-api-plan-p0-p3.md @@ -0,0 +1,584 @@ +# OpenLess Linux 后端 API 全量清单与 Agent 执行总方案(P0–P3) + +> 版本:2026-11-29 · **当前工作树校准版** · **任务范围仅 Linux 后端** · 不负责 Windows/macOS 与 iced 前端。 +> +> 源码基准:当前工作树 `feat/linux-qt-host`(HEAD 及未提交改动)优先;Linux PR #1446(`d47443a26f98d4712b2b14bb784e28029a1c521c`)仅作为历史审查材料。当前已验证的发布基线为 package revision 244。旧 PR 问题必须先在当前工作树复核,不能直接按照旧提交改代码。 + +> **全量索引:** 第 12 章列 S01–S12 / B01–B09;第 13 章补全 S13–S28;第 14 章补全 B10–B17;第 15 章覆盖旧 PR 的 P0/P1/P2 全部已审查问题;第 16 章覆盖 Ask Host / 全字段 Voice Edit / 本地 ASR / Voice Activation / 应用路由等业务缺口;第 17–19 章覆盖 TTY/CLI、依赖打包、故障测试及所有 P0–P3 工作包;第 20 章为明确删除项;第 21 章是可直接粘贴给 Agent 的最终指令。**所有项目都进入跟踪表,但不是要求无条件引入所有候选库或一次性写完。** + +## 0. 目标和硬性边界 + +**目标:** 在其他人开发 iced 前端期间,独立完善 Linux 的 Core Host 适配、录音、输入法/选区、系统集成、CLI/TTY 和稳定性,做到后续 iced 可以复用成熟的后端接口,且当前无 GUI 也能进行自动化和真实系统测试。 + +**绝对不做:** + +- 不写 iced 组件、页面、样式、窗口、动画、主题、控件;不修改其他人负责的前端代码。 +- 不研究或修补 iced 内部剪贴板、wgpu、winit、layer-shell 渲染逻辑;这些归前端负责人。若确实需要交互,只输出接口需求文档。 +- 对处于迁移期的 Qt6 WebEngine、QWebEngine、React HTTP/SSE UI Bridge、Qt 剪贴板 alert、自定义 Scheme、CMake/Qt 打包与渲染逻辑不新增产品功能;若仍在发布链中,只做必要的安全、构建和退出修复,直到明确标记为 `Retired`。 +- 不移植 Windows/macOS 平台 API,不把跨平台通用重构扩大成三端项目。 +- 不重做现有 Core 的 ASR/LLM/历史/配置业务逻辑,不重复实现已存在的远程语音输入功能。 +- 不新增需要 root 的常驻键盘监听,不将 `uinput`/`evdev`/XTest 作为中文输入主路径,不在 TTY 截获或模拟快捷键。 +- 不引入大而全的后台桌面服务/新前端,只引入有明确收益的依赖。 + +**需要区分:** + +1. **Linux 后端文本输出/外部应用插入**:本项目负责,包括 Fcitx5、AT-SPI、剪贴板回退、stdout。 +2. **iced 窗口里的复制粘贴**:前端负责人负责,本项目只提供可选的 Host 接口契约。 +3. **现存 Qt/HTTP 服务**:不做长期增强;如仍会向用户发布,应先禁用未鉴权的敏感 API 或补最小安全阻断,不能带漏洞过渡到新架构。 + +## 1. 实施前的必要审计(W0;先做) + +### 1.1 当前工作树审查 + +- 记录 `git status --short`、`git branch --show-current`、`git rev-parse HEAD`、与目标基线的差异。不要覆盖未提交更改。 +- 对照用户的 Linux API 清单,逐项验证 `openless-all/linux/web/src/ctl.rs`、`host/src/text_access.rs`、`clipboard_fallback.rs`、`native_insertion.rs`、Portal/IBus/TTY 等路径是否已经在**当前工作树**。PR #1446 的 GitHub 快照不含上述全部文件,切忌把「GitHub 上不存在」当成「本地未实现」。 +- 追踪 `Core -> LinuxBackendBuilder -> LinuxNativeRuntime/Host -> 系统适配 -> CLI/IPC` 的实际控制流,记录谁持有 Tokio runtime、录音会话、输入焦点票据、socket 生命周期。 +- 清理任务列表:标记 `已完成且验证 / 已实现但未测试 / 部分实现 / 不存在 / 前端相关跳过 / 旧宿主可删`。 +- 检查 #1495 的平台抽取方案是否有本地 cherry-pick;该 PR GitHub 状态为 closed、未合并,不能假定主分支已有 `openless-platform`。 + +### 1.2 交付审查结果 + +输出 `docs/linux/backend-compat-audit.md`:每个问题附**文件:行号、现状证据、用户影响、改法、风险、测试路径**,不要直接一口气重构。 + +### 1.3 当前工作树已冻结的事实 + +以下结果已经在当前工作树和 package revision 244 上完成验证,不应作为新功能重复实现: + +- CLI/API 矩阵 38 项通过;Web backend 26/26 通过;Clippy 通过。 +- 多 UID 运行通过:不同 UID 使用独立 socket 和数据目录,跨 UID 私有数据访问被拒绝。 +- GlobalShortcuts Portal 的 enable/status/disable 已实际运行成功。 +- PipeWire 虚拟麦克风真实 ASR 已成功完成,包含中文转写、润色和历史持久化。 +- 空麦克风/ASR 路径安全返回 `emptyTranscript`,不崩溃。 +- `dictate --tty --json` 的错误结果已经输出为 stdout JSON,非 JSON TTY 保持安静。 +- package 244 已构建并通过解包、生命周期、TTY、Bash/tmux、依赖和元数据检查。 + +冻结事实只说明当前实现和已执行证据;它不等于所有桌面环境都已兼容。后续状态必须使用 `Present+Tested / Present+Untested / Partial / Missing / Blocked / Deferred / Retired`,旧 PR 观察必须与当前源码证据分开记录。 + +## 2. P0:先处理会伤害用户数据、隐私或阻塞运行的可靠性问题 + +### 2.1 外部应用插入安全与结果一致性 + +**已有源码位置**:`linux/host/src/fcitx5.rs` (`Fcitx5InsertionSession`, `CaptureDictationTarget`, `CommitDictationTarget`);`linux/fcitx5-plugin/openless.cpp`(dictationTargets/selectionTargets);本地可能另有 `native_insertion.rs`。 + +- 目标必须绑定稳定的 session/ticket 和对应输入上下文,不得在 ASR 结束时重新选择**当前**焦点应用以替代原目标。 +- 目标已销毁、切换会话、密码上下文、屏幕锁定、进程退出:明确拒绝危险插入,可回退为复制或 stdout,但不得误写其他应用。 +- 定义 `Inserted`、`CopiedFallback`、`NotInserted`、`OutcomeUnknown`,必要时附原因。**D-Bus 超时或连接中断不等于目标绝对没插入**,`OutcomeUnknown` 不得自动重试提交/粘贴以免重复文本。 +- 选区替换前复核 ticket、目标、焦点(若要求)、选区内容及 surrounding 快照;失败应提示并保留可恢复文本,不得静默误改。 +- 处理字符串 Unicode 字符位移、组合字符、中文、Emoji、UTF-8/UTF-16/码点偏移差异;涉及删除/替换时必须按目标 API 的单位转换,不凭字节长度进行编辑。 + +**验收**:ASR 阶段主动切换到其他窗口、目标应用关闭、Fcitx5 重启、D-Bus 故障、重复 stop/cancel、输入前焦点丢失;所有情况不得插入错误窗口或重复插入。 + +### 2.2 剪贴板的安全回退(不是 iced 内部剪贴板) + +**源码位置**:`linux/fcitx5-plugin/openless.cpp` 的 `copySelectionFromClient()`、`readSelectionText()`,`linux/host/src/selection.rs` 和本地回退模块。 + +- 优先用与**同一目标上下文**绑定的 surrounding/selection 或无障碍可编辑文本接口。 +- 通过转发复制快捷键取选区只能是**显式允许的最后回退**;无法仅凭剪贴板内容变化认定读取到本次选区;应设置目标/时间/数据类型检查,并提供失败状态。 +- 不承诺完整恢复用户已有剪贴板,尤其当其包含图片、HTML、文件列表或 Wayland ownership 不可恢复时。不可逆时不要伪称已恢复。 +- TTY/终端不触发 Ctrl+C;不猜测所有终端的复制快捷键,更不能影响当前 shell 的 Ctrl+C/SIGINT 语义。 +- 不为了这项任务新增一个完整的 Wayland clipboard manager;现有稳妥路径先做好。 + +**验收**:纯文本/图片/文件剪贴板、无选区、旧剪贴板内容不变、并发复制、GNOME/KDE Wayland 和 X11、焦点切换,确保不伪报成功。 + +### 2.3 敏感文档与光标上下文门禁 + +**源码位置**:`linux/host/src/host_context.rs`;`linux/fcitx5-plugin/openless.cpp` 的 `surroundingTextFor()`;`LinuxEditObservationAdapter`。 + +- 当前 PR 快照 Rust 的程序名过滤发生在 `reader.read()` 之后。Fcitx5 插件虽已检查 Password capability,但尚需在**读取敏感上下文之前**应用程序级/字段级策略,避免未经授权将文本带入进程内存。 +- 优先用 input context 的 `Password`/`Sensitive`(如果对应 Fcitx5 版本提供)等真实标志;程序名称黑名单只作附加防护,不是安全证明。没有可靠信号则限制采集,避免依赖子串匹配作为唯一防线。 +- 观察器必须绑定同一个目标及文档版本;窗口切换或 ticket 失效则停止,不继续采样另一个应用。`disarm()` 应真正停止后续采样及过期发布。 +- 日志里只记状态、错误码、长度和经过脱敏的应用标识,不记 surrounding/剪贴板内容、录音样本、token。 + +**验收**:密码字段、浏览器登录字段、终端、焦点切换、观察任务取消,不泄露采样内容;测试应证明敏感场景下 `reader.read()` 未被调用。 + +### 2.4 IPC/单实例及可发布的旧 HTTP 风险控制 + +- 检查本地已有 CLI Unix Socket:Socket 所在目录私有化、Socket mode 0600、对等 UID(`SO_PEERCRED`)检验、命令类型白名单、限流/长度限制、请求 ID、超时、取消语义。Socket 权限与鉴别互为补充;同 UID 的恶意代码仍在同一用户信任边界内。 +- 多实例不能争用同一数据目录;检查异常退出、陈旧 socket 回收时的竞态,不删除其他活跃服务的 socket。 +- 旧 PR 快照的 `linux/web/src/main.rs` 使用无鉴权 localhost HTTP `/api/invoke`、`/api/events`、CORS `*`,并按客户端 `Content-Length` 直接分配内存。**若仍可发布/运行,必须立即关闭敏感 API 或做最低安全阻断、大小/连接限制**;不要为了被弃用的 Qt 桥继续开发通用 HTTP 平台。 + +**验收**:不同用户访问拒绝、超长帧拒绝、恶意客户端断连、并发双启、崩溃后的重启、重复命令、没有 GUI 时正常运行。 + +## 3. P1:Linux 音频、输入法与会话恢复 + +### 3.1 CPAL/PipeWire 设备与录音状态机 + +**源码位置(当前实现需以 W0 标注行号)**:`openless-all/linux/host/src/audio.rs`、`audio_mute.rs`、`audio_cue.rs`、`capabilities.rs`、`terminal_vad.rs`,以及 `openless-all/linux/web/src/main.rs` / `system.rs` 的设备监控。 + +- **不要重复升级 CPAL**:当前 Host 已使用 `cpal = 0.18.2`,显式启用 `pipewire` 和 `pulseaudio`。不要据此宣称 ALSA-only 已实现;ALSA 路径必须以当前 Cargo feature、实际枚举结果和实机证据为准。 +- #1446 快照仅用 `/dev/snd` inotify 检测设备变化,无法覆盖蓝牙音频、虚拟 PipeWire 节点、默认音频源变更、PipeWire/WirePlumber 重启。引入 PipeWire registry/metadata 监听或 Pulse 兼容层订阅,保留 `/dev/snd` 和低频轮询作为兜底;避免新增常驻高频扫描。 +- 不使用 `cpal:{index}:{name}` 作为持久化设备唯一身份;优先使用 HostId/设备原生 ID,设备被替换或跨后端时明确失效并回到「系统默认」,防止同名设备选错。 +- 列表过滤基于已识别的 monitor/source 属性,不能以 `channels > 2` 断定不是麦克风;支持多通道 USB 接口并在录音链路中正确下混。 +- 采集流断开要自动停止,并准确向 Core 报告 `RecordingEvent::Fatal` / 相应故障;在会话未明确终止前不要静默切换到另一麦克风继续录制。 +- 遵守「先真正打开麦克风,再给用户开始提示」和「先停止采集,再播放结束提示」以防提示音被录进去;不要因提示音或网络握手丢失第一秒语音。 +- 既有录音归档写失败不能只记日志后让上层以为保存成功;按录音类型区分必需归档与可选调试归档,并走 Core 故障/降级策略。 +- 系统输出静音 guard 要在 sink/default 变化和异常停止后恢复**对应原始设备**,不能盲目把后来切换的默认输出改成旧状态。 + +**验收**:内置麦、USB 多通道、蓝牙耳机切入切出、虚拟麦、显示器音频 monitor、默认设备切换、PipeWire 重启、权限拒绝、磁盘写满、快速开始/取消、首次词不丢。 + +### 3.2 Fcitx5 插件/监听恢复 + +**源码位置**:`linux/host/src/hotkeys.rs`、`fcitx5.rs`、`linux/web/src/hotkeys.rs`、`linux/fcitx5-plugin/openless.cpp`。 + +- #1446 快照中热键监听收到 D-Bus 处理错误后退出,而上层 `spawn_headless` 也退出;需要为连接丢失/NameOwnerChanged/插件重启建立明确生命周期:`Disconnected → Reconnecting → Ready`。 +- 重连后幂等恢复热键配置,不重复监听/重放旧按键,也不把一次长按拆成两次会话。 +- 插件版本不匹配、未安装、后台服务不存在要可探测;状态检查不能自动激活用户未使用的 Fcitx5。 +- 插件安装/更新时,不自动切换系统默认输入法、不覆盖用户已有非 OpenLess 配置;需要升级并重启服务时遵循明确告知与安全触发。 + +**验收**:`fcitx5 -r`、D-Bus 重连、插件安装/卸载、X11/Wayland、按下未松开时掉线、会话退出清理。 + +### 3.3 系统会话与权限变化 + +- 接入 `org.freedesktop.login1`:会话锁定/解锁、`PrepareForSleep`、active session 状态;按实际 logind 信号与会话对象语义实现,不能假设单一信号对所有桌面一致。 +- 锁屏、睡眠、用户切换时停止/取消麦克风捕获,失效输入上下文票据,并清理或暂停敏感后续动作;恢复后重新检测设备和 D-Bus 所有者,而不是盲目延续旧会话。 +- 遇到 systemd user bus 不存在(TTY/非 systemd 环境)时可返回 `Unavailable`,不能使 CLI 普通功能全部崩溃。 +- Secret Service/钱包仍须显式解锁,状态探测不应弹框、自动解密或触发迁移。 + +**验收**:锁屏/解锁、睡眠/唤醒、切换用户、无 DBus、远程 SSH、密码库未解锁。 + +### 3.4 能力探测与错误语义 + +- 统一 Linux 独立能力状态:`Ready / Unsupported / NotInstalled / PermissionRequired / PermissionDenied / Disconnected / Reconnecting / Degraded`;每种状态附可选原因、后端名称、无敏感信息的诊断。 +- #1446 的 `supports_overlay` 静态按 X11/Wayland 赋值,不能代表真实合成器支持。该能力属于 iced 窗口集成;Host **只报告可测到的协议可用性**,不负责实现 UI 悬浮窗。 +- `supports_ime_input` 不能仅等于 Fcitx5 存在。要区分 `fcitx5-native / ibus-native / at-spi / clipboard-only / stdout-only` 实际可用通道。 +- 诊断命令只读、低副作用,默认不访问敏感文档、录音、密码库内容。 + +**验收**:无桌面、GNOME IBus、KDE Fcitx5、没有麦克风、权限拒绝,均有准确提示、不能出现虚假成功。 + +## 4. P2:补齐可选的 Linux 系统 API(条件触发,不盲目加依赖) + +### 4.1 IBus + +- 当 Fcitx5 之外的用户需求明确时,实现 IBus Engine 集成方案,核实 `CommitText`、`SetSurroundingText`、`FocusIn/Out` 等接口与 Engine 激活机制;**不能向任意 IBus D-Bus 进程发一条 `CommitText` 就宣称可向目标应用输入**。 +- 如果必须成为用户当前输入引擎才能工作,就把「安装/启用独立 IBus engine」作为可选方案,并先在 GNOME IBus 上完成最小闭环。不能强行切换用户输入法。 +- 不允许因为 IBus 未实现导致 OpenLess 无法在 GNOME 安装、启动、录音、输出到 stdout。若 rpm/deb 当前 `Depends: fcitx5` 属强制依赖,应审视是否改为推荐依赖/可选特性。 + +### 4.2 AT-SPI 文本访问 + +- 仅作为当前真实目标可访问时的回退路径,按 `EditableText`/焦点/角色/只读/敏感状态判定。 +- 严禁无目标身份地向无障碍树中寻找“任意可编辑组件”;无障碍 API 与 Fcitx5 目标身份需做一致性校验。 +- 对不支持的应用明确返回 `Unsupported`,禁止强制改写其他控件。 + +### 4.3 Portal/桌面环境 + +- XDG Desktop Portal 用于 FileChooser、GlobalShortcuts、Notification 等**确有 Host 需求**的能力;GUI 按钮、窗口生命周期、渲染能力不在本项目。 +- GlobalShortcuts Portal 要处理授权撤销、会话重建和桌面不支持;保留 Fcitx5/X11 可用路径,不添加不可移植的全局低层键盘钩子。 +- `xdg-desktop-portal` 不存在时,文件选择可按用户设置回退 `kdialog`/`zenity`,或者让 CLI 接收显式文件路径;不要因对话框失败阻塞纯 CLI 操作。 +- 可选系统通知可通过 Portal/通知 D-Bus,必须尊重 TTY、DND、无桌面状态,不把通知当录音流程必要条件。 +- 应用识别使用 XDG Desktop Entry `StartupWMClass`、Desktop ID、Flatpak/Snap 标识,避免依赖进程显示名的脆弱匹配;但不为此引入整套新桌面框架。 + +## 5. P1:CLI / TTY / SSH(现有能力优先修复,不重复开发) + +**据本地 Agent 清单,待核实已实现的命令:** + +```bash +openless ctl dictate +openless ctl dictate --tty +openless ctl dictate --json +openless ctl toggle +openless ctl start +openless ctl stop +openless ctl cancel +openless ctl mics --json +openless ctl mic default +``` + +- `--tty` 不得注册全局快捷键、不注入终端输入、不覆盖正在执行的 shell 命令;使用明确的 CLI 启动方式及**提示音 + 长时间静默自动停止**。 +- 录音提示音不能混入录音;如果声音输出不可用,应有明确定义的错误或静默策略,而不是伪报已提示。不要擅自追加用户已经拒绝的常驻 TTY 状态栏。 +- `--json` 保证 stdout 仅完整机器可解析 JSON;提示/日志/音效状态送 stderr 或其他指定通道。错误要有非零退出码和可辨认的错误类型。 +- SSH / tty 无 `DISPLAY`、`WAYLAND_DISPLAY`、`XDG_RUNTIME_DIR` 或远端没有麦克风时,不应尝试 GUI 能力,也不能假装访问到了本地客户端的麦克风。已经存在的远程语音输入保持原实现,不重复开发。 +- `SIGINT`/`SIGTERM`、意外断线、重复 stop/cancel、超时都要释放音频流、锁和 socket;避免污染历史记录、留下音频文件句柄。 +- 覆盖 Bash、Zsh、Fish、tmux、Neovim、纯 tty 和 SSH;CLI 不要把 shell integration 当强制依赖。 + +## 6. 与 iced 前端团队的唯一交界:接口契约(我们只写后端) + +**建议提供** `docs/linux/backend-api-contract.md`: + +- 输入:用户动作(开始/停止/取消录音、设置更新、设备选择、权限提示)。 +- 输出:版本化 DTO / 命令结果、`dictation:state`、设备事件、热键状态、后端诊断;所有事件定义 ID、会话 ID、顺序、错误码、重连语义。 +- 权限与能力:界面只依赖 `get_capabilities`/诊断 DTO 判断支持状态,不硬编码桌面环境或猜测依赖是否安装。 +- 进程模型:明确 Backend 是进程内 Rust API、Unix socket,还是由最终宿主包装;**不要强行规定必须保留旧 HTTP/SSE**。若 iced 团队未选定传输,仅固定核心 trait/DTO 和测试桩。 +- 事件一致性:广播可能丢帧,客户端重新连接后应能读取完整当前状态快照,而不只能靠历史事件推导。 +- 测试方式:提供 headless Rust 测试/小型 CLI harness,前端未合入也能端到端验证。 + +**不做的事:** 不替 iced 团队处理 GUI 窗口句柄、渲染线程、控件焦点或前端 clipboard 命令;需跨越窗口所有权的能力写明必需的宿主参数,等待对方适配。 + +## 7. 执行节奏与 PR 拆分 + +| 阶段 | 可独立交付的工作包 | 前置条件 | 完成标准 | +|---|---|---|---| +| W0 | 本地代码盘点 + 接口契约 | 无 | 文件/调用链/已有功能真实状态表 | +| W1 | 插入票据、选区与隐私、剪贴板回退 | W0 | 无误插入、无重放、敏感文本不采集 | +| W2 | PipeWire 事件、设备身份、故障上报 | W0 | 热插拔、服务重启、错误清晰 | +| W3 | Fcitx5 重连、logind 生命周期 | W1/W2 | 恢复会话不中断正常系统操作 | +| W4 | CLI/TTY 稳定性与安全 socket | W0 | Headless 完整闭环、异常可靠退出 | +| W5 | Portal/AT-SPI/IBus 可选兼容 | W1~W4 | 逐个能力有真实环境验收 | +| W6 | Linux Host DTO/契约与 CI | 可并行 | 无 iced UI 也能稳定测试 | + +推荐 PR 小规模提交:一个工作包一个 PR/提交序列;不可用未经测试的跨平台平台重构代替修 bug。维护现有 Core 接口,必要修改仅新增非破坏性的 trait/DTO,不改 Windows/macOS 实现。 + +## 8. 必须通过的验证矩阵 + +| 环境 | 关键检验 | +|---|---| +| KDE Wayland + Fcitx5 | 真实中文听写/选区、热键恢复、剪贴板安全回退 | +| GNOME Wayland + IBus | 安装启动不依赖 Fcitx5;Host 能力准确探测;IBus 若实现则闭环 | +| Sway / Hyprland | 缺少某 Portal/IME 时稳定降级;不伪称成功 | +| X11(XFCE/KDE) | Fcitx5/剪贴板/回退目标一致性 | +| PipeWire + WirePlumber | 热插拔、蓝牙、默认源切换、服务重启 | +| PulseAudio / ALSA | 无 PipeWire 时可录音或明确拒绝 | +| 纯 tty / SSH | 无 GUI 依赖;静默停止;stdout/JSON 正确;SIGINT 清理 | +| 多用户、多实例 | 私有 socket/数据目录、无跨 UID 控制、无竞态 | +| 资源受限/故障注入 | 无设备/磁盘满/权限拒绝/超时/断网/输入法中断 | + +所有未真实执行的测试必须标注 `Not Run`,不能写“兼容”或“通过”。 + +## 9. 禁止 Agent 自行扩大的范围 + +1. 不升级/重写 iced,也不为了适配 iced 在 Rust Host 中自行创建 GUI 事件循环。 +2. 不把 Linux 平台能力抽取扩展到 Windows/macOS;这两平台由其他人负责。 +3. 不以 `uinput`、安装守护程序、提升权限规避 Wayland/桌面权限模型。 +4. 不主动修改用户默认输入法、不重启不相关系统服务、不触碰用户既有凭据。 +5. 不为 Qt/React 即将淘汰的传输层添加新产品功能。 +6. 不大规模添加 crate;新依赖要列出最低版本、license、二进制体积和系统动态库依赖。 +7. 不替换尚未确认为过时的本地实现;不重置、推送、合并用户分支,除非获得独立明确指令。 +8. 不将“预计能运行”写成实测通过。 + +## 10. 给 Agent 的启动指令(复制即用) + +> 当前任务**只做 OpenLess Linux 后端**。Windows、macOS、iced 前端及其窗口/控件/渲染/内部剪贴板全部由其他人负责,不得修改。iced 已通过评估,不需要再次选型或验证框架。先对照本地工作树、GitHub #1446 与本地 Agent 清单,核实已经实现的 CLI/Portal/AT-SPI/输入法/音频能力。不要在将被删除的 Qt/React HTTP 宿主上继续加功能;如果旧无鉴权 HTTP API 仍可能随发布包暴露,则做最小安全阻断。随后按 W1→W6 分工作包提高 Linux 的可靠性和兼容性,特别是输入目标绑定、剪贴板/隐私安全、PipeWire 设备热插拔、Fcitx5 监听重连、logind 锁屏睡眠、TTY/SSH 稳定性与 Host DTO 契约。每个改动必须说明源码证据、自动测试和实机验收结果,未验证标记 Not Run。先输出 W0 审查报告与按优先级排序的变更计划,再逐批实现。不得推送或合并,且不得破坏未提交修改。 + +## 11. 已核查的源码参考 + +- Linux PR #1446:(head: `d47443a26f98d4712b2b14bb784e28029a1c521c`) +- 平台抽取 PR #1495(已关闭、未合并): +- Linux Host 音频与状态:`openless-all/linux/host/src/audio.rs`、`audio_mute.rs`、`audio_cue.rs`、`capabilities.rs`、`terminal_vad.rs` +- Linux Host 能力与上下文:`openless-all/linux/host/src/host_context.rs`、`settings.rs`、`backend.rs` +- Fcitx5 Rust 适配:`openless-all/linux/host/src/fcitx5.rs`、`hotkeys.rs`、`global_shortcuts.rs` +- Fcitx5 插件:`openless-all/linux/fcitx5-plugin/openless.cpp` +- 光标上下文/自动学词:`openless-all/linux/host/src/host_context.rs` +- Linux 单实例、HTTP 旧桥:`openless-all/linux/web/src/host.rs`、`main.rs` +- Shared Core Host 接口:`openless-all/app/crates/openless-core/src/domains.rs` + +> 重要:这些是当时 GitHub PR 的检查位置,不代表本地当前分支拥有完全相同的文件布局。Agent 必须先检查 HEAD 与文件现状。 + +--- + +## 12. 具体要补的 Linux API 清单(2026-11-29 补充;本节是 Agent 的逐项实现/验收清单) + +> **阅读方式:** 下表的“当前状态”基于用户提供的本地 Agent 能力清单及 #1446 公开快照,尚未直接查看 Agent 本地未推送代码。`已有→增强` 表示禁止重写现有接口;`未完整` 表示优先读源码核实;`可选` 表示实际功能需要时才引入。这里的 D-Bus、Linux 接口名称是系统实际接口;下文 `LinuxHost` 的 Rust 名称是**建议增加的项目内部抽象**,不是宣称项目已存在这些函数。 + +### 12.1 操作系统级接口:真正值得在等待 iced 前端期间补齐的项目 + +> **状态语义:** 本表中已经存在的 Linux 协议、CLI 或 Rust 函数必须填写真实路径和证据;表中以 `capture_*`、`watch_*`、`begin_*` 等形式出现的名称,若当前源码不存在,只能标记为 `Proposed`,不能当作已暴露 API。建议在 `docs/linux/api-gap-matrix.md` 中分列 `Observed API`、`External Linux API`、`Proposed Host abstraction`。 + +| 序号 | 优先级 | 具体系统 API / 事件 | 本地清单状态 | Agent 要交付的行为与通过条件 | +|---|---|---|---|---| +| S01 | P1 | **IBus Engine**:`org.freedesktop.IBus.Engine` 的 `FocusIn`/`FocusOut`、`SetSurroundingText`、`CommitText`(依 Engine/输入上下文的实际方向实现);必要时安装注册 Engine | 有 `scripts/linux-ibus-plugin/`,但生产闭环未完整 | GNOME IBus 上通过合法 Engine 上下文捕获目标并提交中文;不可以随意向 ibus-daemon 发送 `CommitText` 就称已支持;不得替换用户默认输入法 | +| S02 | P0 | **PipeWire**:Registry `global`/`global_remove` 事件、Node 属性、Metadata `default.audio.source` / `default.configured.audio.source` 变化;需要时监听 WirePlumber/兼容 PulseAudio 事件 | CPAL 录音已有,设备生命周期未完整 | 蓝牙、虚拟麦、默认输入改变或 PipeWire 重启后,重新枚举并发布设备状态;正在进行的会话明确中断,不偷偷改用另一支麦克风 | +| S03 | P0 | **Fcitx5 + session D-Bus**:`org.freedesktop.DBus.NameOwnerChanged`、插件的目标票据/提交结果、D-Bus disconnect/reconnect | 插件和热键已有,缺少完整自动恢复 | Fcitx5 重启/插件升级后自动重新握手和订阅;区分提交失败与结果未知,禁止重复插入 | +| S04 | P1 | **systemd-logind**:`org.freedesktop.login1.Manager.PrepareForSleep`;真实 Session 对象的 `Lock`/`Unlock`、`Active` 等属性/会话切换事件;按实际桌面锁屏信号补充 | 未完整 | 锁屏、用户切换、睡眠前停止麦克风并令输入票据失效;恢复后重新探测;不把 logind 的 Lock/Unlock 当所有桌面可靠锁屏通知 | +| S05 | P1 | **AT-SPI**:`org.a11y.atspi.Accessible`、`Text`、`EditableText`;如 `GetState`、`GetRole`、选区读取、`InsertText`、`DeleteText`/`SetTextContents` | 已有可选路径,需核查完整程度 | 无 Fcitx5 目标时,仅对已确认的当前可编辑控件操作;校验焦点、密码属性、文本偏移、目标一致性;全字段写入必须有快照与回滚判定 | +| S06 | P1 | **Portal GlobalShortcuts**:`CreateSession`、`BindShortcuts`、`Activated`、`Deactivated`、`ShortcutsChanged`、Session `Closed` | 本地已实现且授权实测通过 | **不重新开发**;只补授权撤销、Portal 后端重启、Session Closed 的状态恢复与重新授权引导 | +| S07 | P1 | **Unix Domain Socket**:`AF_UNIX`、`SO_PEERCRED`、0600 socket、0700 runtime 目录、限长帧、请求 ID、超时 | 本地已实现多 UID 隔离;细节再审计 | **不重写**;验证 UID 认证、崩溃重启、重复 start/stop、安全退出和陈旧 socket 回收;避免复活旧 HTTP 桥 | +| S08 | P2 | **Wayland Clipboard**:标准 `wl_data_device_manager` 和 `wl_data_device`(需有效 seat/focus/serial);可选 primary selection 协议;不要误把 `ext-data-control` 当标准可用 | 现有 `wl-copy` / `wl-paste` 回退 | **暂不开发完整 manager**;若确有失败场景,先判断是无焦点权限、selection ownership 还是外部命令问题;不得为了绕过合成器限制乱引入特权服务 | +| S09 | P2 | **XDG Desktop Portal FileChooser**:`org.freedesktop.portal.FileChooser.OpenFile`、`SaveFile` | 本地 `portal_picker.rs` 已有 | **不重做**;仅检查 cancel/timeout、沙盒返回 URI 与文件权限;保证 headless CLI 使用路径参数即可运行 | +| S10 | P2 | **通知/外部链接**:`org.freedesktop.portal.Notification.AddNotification`/`RemoveNotification`;`org.freedesktop.portal.OpenURI.OpenURI` | 需确认是否有实际后台需要 | 按真实需求可选,不能成为录音/TTY 成功路径的强依赖;外部 URL 必须校验方案,不能执行 shell 拼接命令 | +| S11 | P2 | **XDG 应用身份**:Desktop Entry ID、`StartupWMClass`、Flatpak application ID、Snap 名称;X11 `_NET_ACTIVE_WINDOW` / `_NET_WM_PID` | 当前应用识别已有,多来源统一不足 | 新增可验证的 `ApplicationIdentity`,不得靠任意名称子串推断敏感字段或直接改写目标;Wayland 没有通用的全局活动窗口 API | +| S12 | P2 | **Secret Service**:`org.freedesktop.Secret.Service` 的安全读取/显式解锁(通过现有 keyring/secret-service 包) | 本地已有 wallet status/unlock 和凭据读写 | **不重做**;只补 locked/unavailable/denied 状态区别和凭据错误恢复;不可自动弹解锁框或泄露密钥 | + +**具体依赖建议:** DBus/Portal 优先沿用当前依赖树中的 `dbus` 及已有适配;只有确认无法实现时才评估 `zbus` / `ashpd`,不得无理由并存两套 D-Bus 栈。PipeWire 事件优先比较 `pipewire` Rust bindings 与已有 PulseAudio 事件路径的系统依赖/打包复杂度;AT-SPI 优先沿用现有适配,只有缺失时再评估 `atspi` / `atspi-client` 等实现;UDS 用 Rust 标准库 + 必需的 Linux socket API;X11 复用现有 XGrabKey/窗口代码。**这些是候选技术,不是要求全部新增依赖。** + +官方协议参考: + +- IBus Engine:,源码 +- PipeWire Registry:,Metadata: +- logind: +- AT-SPI EditableText: +- GlobalShortcuts: +- FileChooser: +- Notification: +- Linux UDS 凭据: + +### 12.2 OpenLess 自身尚需在 Linux 补齐的 Host / Core 功能 API + +这些不是新的 Linux 内核/桌面协议,而是**Windows/macOS 或共享 Core 已有、Linux Host 没有完整接通的产品功能**,最初的 Agent 清单明确提到了。它们不归 iced 页面开发者,但要避免把 UI 操作搬进后端。下列方法名(除已核实的通用命令外)仅是**建议的逻辑接口/任务分类**;实际名称必须以 Core 和现有 IPC contract 为准。 + +| 序号 | 优先级 | 需要实现/接通的 Linux Host API | 验收条件 | +|---|---|---|---| +| B01 | P1 | **IBus 等价 Host 通道**:`capture_target`、`commit_text`、`read_selection`、`read_surrounding`、`watch_ownership` | GNOME+IBus 真正完成中文听写、选区及焦点安全;明确要求启用可选 Engine;不假装能注入任意应用 | +| B02 | P1 | **完整字段 Voice Edit**:`capture_editable_target`、`read_full_field`、`begin_edit_transaction`、`replace_if_unchanged`、`revert_if_owned` | 不止 selection-only;原文已变化/目标不一致/不可编辑/密码字段必须拒绝,不覆盖其他用户输入 | +| B03 | P1 | **录音与运行态事件**:`watch_microphones`、`watch_default_source`、`device_removed`、`recording_fault`、`session_suspended`、`session_resumed` | 无 GUI 也能订阅稳定事件;事件带 generation/session ID;断线后能读取状态快照 | +| B04 | P1 | **输入结果语义**:`capture_text_target`、`commit_target`、`get_insert_outcome`、`cancel_target` | 返回 `Inserted` / `NotInserted` / `CopiedFallback` / `OutcomeUnknown`,不自动重试未知结果 | +| B05 | P2 | **新版 Ask Host**:会话 create/update/cancel/snapshot、受授权的 `window_context` / `browser_tab_context`、`add_attachment`、`history` | 复用共享 Core;权限逐能力/逐请求;截图/浏览器集成可能需要用户许可或外部合作接口,不能伪造已有能力;无需写 Ask 的 iced UI | +| B06 | P2 | **本地 ASR Host**:`list_local_asr_models`、`download/install/verify_model`、`prepare_runtime`、`transcribe_local`、`unload_runtime`、失败回退状态 | 复用 Core 现有 Foundry/Sherpa 接口;实际核实 Linux 平台二进制支持、动态库依赖与内存;不可把安装完成写成加载成功 | +| B07 | P2 | **应用路由**:`resolve_application_identity`、`get_app_categories`、`watch_foreground_identity`、`resolve_style_route` | Flatpak/Snap/桌面 ID 统一,窗口更换后不把旧目标身份误用于新应用 | +| B08 | P3 | **Voice Activation**:`start/stop_voice_activation`、`get_voice_activation_state`、唤醒短语/结束短语、锁屏/睡眠策略 | 用户明确启用才常驻监听;资源消耗与隐私告知;锁屏不启动危险动作;不能返回成功 no-op | +| B09 | P3 | **可选附件与截图**:Portal ScreenCast/Screenshot、文件选择/存储、浏览器上下文权限 | 先核实产品要求与 Portal 用户确认模型;不开发 GUI,不进行无授权后台截图 | + +**API 重要取舍:** B01/B02 和 S01/S05 互相依赖;可以先为 Voice Edit 做数据契约/仿真测试,再在有实际目标 API 时逐个开放。B05/B06/B08 是功能对齐项目,不应阻塞 P0/P1 的语音听写可靠性修复。如果团队暂时不计划在 Linux 上发布这些功能,应标记 `Deferred`,不能写成已实现。 + +### 12.3 明确**已经有**的 API:只查缺陷,不要新增同功能替身 + +原 Agent 清单称本地已经实现以下能力,Agent 应根据当前工作树逐个做 `Present + Tested` 或 `Present + Untested` 记录: + +- `openless ctl dictate/start/stop/cancel/toggle`、`--tty`、`--json`,静默自动停止;不能另起一个 TTY 语音输入工具。 +- `list_microphone_devices`、`start_microphone_level_monitor`、`stop_microphone_level_monitor`;只加设备变更/失效/恢复事件。 +- Fcitx5 文本提交;AT-SPI 可选文本访问;`wl-copy`/`xclip` 复制回退;只补安全性与缺失目标类型。 +- `get_linux_global_shortcuts_status`、`enable_linux_global_shortcuts`、`disable_linux_global_shortcuts`、X11 XGrabKey、Fcitx5 热键;只补重新授权、重连和状态。 +- `pick_directory`、`pick_style_pack_zip`、`export_audio_recording`、`open_external_url`;已有 Portal→kdialog→zenity 路线,禁止重做。 +- `keyring_state`、`unlock_keyring`、`read_credential`、`set_credential`;禁止新增不必要的自建明文密钥库。 +- `openless ctl daemon start/stop/status`、私有 Unix socket、UID 隔离和锁文件;只做异常/竞态测试。 + +### 12.4 可交给 Agent 的精确执行次序 + +1. **盘点**:为 S01–S12、B01–B09 逐项标记 `已实现并通过测试 / 已实现未验证 / 部分实现 / 未实现 / Deferred`,注明 `path:line`、实际 API 名称和适用桌面。 +2. **第一批 Linux API(建议优先)**:S01 IBus、S02 PipeWire 事件、S03 Fcitx5 owner/reconnect、S04 logind,外加 S07 IPC 安全复核;完成各自 headless 测试。 +3. **第二批可靠写入**:S05 AT-SPI、B02 完整字段 Voice Edit 和 B04 OutcomeUnknown 语义;必须先解决目标绑定/隐私问题,不能为了功能覆盖放宽安全检查。 +4. **第三批能力对齐**:B05 新版 Ask Host、B06 本地 ASR、B07 应用身份;每项有独立 feature gate,不影响基础听写构建。 +5. **最后按产品需求**:B08 Voice Activation、B09 截图附件;S08 原生 Wayland 剪贴板仅在有可复现真实需求时做。 +6. **交付**:`docs/linux/api-gap-matrix.md`(每条对应当前文件、API 名、依赖、权限、实测环境、失败回退、状态)和可独立运行的 `cargo test`/CLI 验收脚本。前端团队只拿契约,不需要等 iced 合入才能验证 Linux Host。 + +> **禁止误读:** “引入新的 Linux API”不等于无条件“增加 Rust crate”。已经通过 CLI/原生协议解决的问题,不要因为看到了另一套库就重新实现。对 IBus 的支持必须遵循输入法激活/目标上下文机制;对 Wayland 的支持必须遵守合成器授予的能力边界。 + +--- + +## 13. 之前讨论过但 S01–S12 尚未逐条展开的 Linux 系统 API(全部保留) + +> **重要**:下面是对第 12 章的补全,而不是推翻 S01–S12。`已提出` 不等于「本地没有」;Agent 必须按第 1 章审计。优先级用于排期,**P2、P3 同样在本计划范围内**。`条件实现` 指满足列出的真实环境需求后再实现,不是从任务清单删除。 +> +> 本节涉及 Wayland、TTY、shell、输入模拟等接口必须遵守系统授权和当前输入目标的实际权限。不能通过安装依赖来绕过 compositor 的限制。 + +| ID | 等级 / 决策 | 具体 API / 协议 / 工具 | 需做的 Linux Host 工作 | 验收与限制 | +|---|---|---|---|---| +| S13 | P2 / 评估并条件实现 | **RemoteDesktop Portal** `org.freedesktop.portal.RemoteDesktop`:`CreateSession`、`SelectDevices`、`Start`、`ConnectToEIS`;`libei` / Rust `reis` | 仅在有用户授权的远程控制/兼容回退场景建独立 adapter;维护 session、permission 和退出销毁 | **不能代替输入法提交任意中文文本**;需要 Portal 后端支持及用户授权;不能用于偷偷注入终端、密码框;已存在的 OpenLess 远程语音输入不重做 | +| S14 | P2 / 能力探测 | Wayland **`zwp_text_input_v3`**、**`zwp_input_method_v2`**、`zwp_virtual_keyboard_v1` | 梳理客户端与输入法服务的角色;普通应用不可直接充当已授权输入法;作为 Fcitx/IBus 接口原理及可选协作参考 | `text-input-v3` 主要供应用与 compositor 协作;`input-method-v2` 需要 compositor 接受的 IME;virtual keyboard 仅可用于合规按键操作,**不作为中文字符串插入主通道** | +| S15 | P2 / 按需增加 | **X11** `XGrabKey`/`XUngrabKey`,EWMH `_NET_ACTIVE_WINDOW`、`_NET_WM_PID`,X selection/PRIMARY | 保留 X11 热键、活动窗口和剪贴板路径;处理 NumLock/CapsLock 修饰符和快捷键冲突 | 真实 XFCE/KDE X11;权限与焦点切换;**XTest/uinput 不作为中文输入通道** | +| S16 | P2 / 复用已有,补准确率 | **合成器窗口识别**:Hyprland IPC `hyprctl`、Sway IPC `swaymsg`、KWin/GNOME Shell/Niri 提供的受支持接口;可选 `ext-foreign-toplevel-list-v1` | 把窗口 ID、app_id、desktop 文件和登录 session 关联到可信 `ApplicationIdentity`;能力不足返回 unknown | 不要求所有 Wayland 合成器开放全局活动窗口;不依赖无授权的任意窗口监控;不为 UI 开发 layer-shell | +| S17 | P2 / 只报能力 | **Wayland `xdg-shell`、layer-shell**(如 `zwlr_layer_shell_v1`) | Host 仅检测合成器所宣称的协议与环境可用性,形成诊断 DTO | GNOME 不支持 layer-shell 时诚实报告;窗口创建、浮层交互由 iced 团队实现,不在本任务范围 | +| S18 | P1 / 核查并增强 | **POSIX 终端控制**:`isatty`、`termios`、`tcgetpgrp`、`SIGINT`/`SIGTERM`/`SIGHUP`;Linux VT `VT_GETSTATE`、`KDGETMODE`(仅必要时) | TTY/PTY/SSH 模式识别,安全取消录音/会话并恢复终端模式;避免把输入写进活跃 shell | 默认仅显式 CLI 触发;不拦截原终端快捷键、不占命令行、不常驻 TUI/状态栏;不可把 stdout JSON 混入提示 | +| S19 | P2 / 可选用户显式配置 | **Bash Readline、Zsh ZLE、Fish `commandline`** | 为选择使用的用户提供 shell 可选命令/绑定或脚本;只在用户确认的 shell buffer 中处理结果 | Bash 不等于 Zsh/Fish,旧版 shell、不同 locale、远端 SSH 需分别测;**不能影响既有 shell 编辑/命令执行** | +| S20 | P2 / 条件实现 | **PTY / tmux / Neovim**:tmux socket/`send-keys`、Neovim RPC、Bracketed Paste `CSI ? 2004 h/l` | 只为用户明确选定的会话提供外部终端文本接入,绑定 session/pane/buffer,先核目标可写与用户授权 | 不向任意前台终端、远端 shell 自动注入;默认 stdout 或专用 buffer;括号粘贴模式由目标终端声明,不推测 | +| S21 | P2 / 排障时引入 | **剪贴板 Ownership**:标准 `wl_data_device_manager`、`wl_data_source`,`zwp_primary_selection_device_manager_v1`;可选 `zwlr_data_control`、`ext-data-control` | 调查 `wl-copy`/`wl-paste` 的 owner、session/focus/serial、时序和 MIME;必要时引入原生适配 | 遵守 compositor 权限;CLIPBOARD 和 PRIMARY 分开;不能无焦点读取任意应用、不能宣称完整保留图片/文件剪贴板;优先不重做已有后端 | +| S22 | P1 / 复用修复 | **录音音效与 VAD**:CPAL / PipeWire / PulseAudio / ALSA + 本地语音活动检测;输出 sink 控制 | 录音开始/停止提示音、静默阈值、尾音保护、短语音与环境噪声区分;真实采集失败时准确报错 | 在真实 TTY/SSH 设备测试提示音与静默结束;首字不能被初始化/握手吞掉,提示音不能被当识别内容;无声卡不伪报播放成功 | +| S23 | P1 / 现有守护进程核查 | **XDG 运行时/文件**:`XDG_RUNTIME_DIR`、`XDG_DATA_HOME`、`XDG_CONFIG_HOME`、`flock`/`fcntl`、`SO_PEERCRED`、文件权限、`inotify` | 目录分离、锁冲突处理、事件监测恢复、单实例与多 UID;不能从共享 `/tmp` 弱权限运行 | 0700 目录、0600 socket/敏感文件、路径归属/符号链接检查;数据持久化及原子写入;崩溃重启安全 | +| S24 | P2 / 条件 | **systemd --user / D-Bus activation**(若已有则复用),loginctl 与会话感知 | 有需求时支持守护进程按用户启动、状态检查、优雅 stop,不自动创建 root 系统守护程序 | 无 systemd 的发行版/TTY 能以 CLI 运行;不会因为 user bus 未启动就导致基本语音功能不可用 | +| S25 | P3 / 按 Ask 需要 | **XDG Portal Screenshot / ScreenCast**:`org.freedesktop.portal.Screenshot`、`ScreenCast` | 只提供经明确同意的附件/采集 Host 接口;ScreenCast 处理 Session 关闭与流失效 | 区分一次性截屏与持续采集,必须保留用户同意/撤销语义;禁止无提示的后台屏幕读取 | +| S26 | P3 / 按产品需要 | **Portal Background / Inhibit** | 仅在后台处理、受明确授权的前台交互或业务必须时评估;系统睡眠默认采取安全停止 | 不因为录音而私自长期阻止用户休眠;不能将 Portal 可用性误认为已获授权 | +| S27 | P2 / 必做打包核查 | **deb / rpm 依赖、插件分包与 XDG Desktop Entry** | GUI 主程序与 Fcitx5 addon 解耦;GNOME+IBus 用户不应被强制安装 Fcitx5 才能使用普通 ASR/CLI;检验动态链接与可选库 | 在 Debian/Ubuntu/Fedora 干净环境安装/卸载;不篡改默认输入法/用户数据;打包不依赖已淘汰 Qt 模块 | +| S28 | P2 / 安全增强 | **OpenURI/桌面启动**:Portal OpenURI 或符合系统约束的打开方式,desktop `Exec` 解析 | URL scheme 白名单、错误分类、权限/沙盒路径核查,拒绝 shell 拼接 | 不执行来源不明的 `.desktop` 命令;文件路径和 URL 不通过任意 shell 字符串解释 | + +### 13.1 S13/S14 的特殊判断(不要产生错误实现) + +1. **RemoteDesktop Portal 与 libei/reis**:它们提供经授权的设备事件注入通道,不保证有「发送 Unicode 文本到任意窗口」这种高层功能;Fcitx5/IBus 提交仍是中文听写的主路径。先审查是否真的需要 RemoteDesktop 回退,再决定引入依赖。 +2. **Wayland 输入协议**:`text-input-v3` 和 `input-method-v2` 的参与方和权限完全不同。即使某 crate 能连接 Wayland socket,也不意味着普通 OpenLess 后台进程能凭空控制所有应用输入框。 +3. **窗口/浮层**:Host 只输出支持能力、应用身份和目标句柄契约,不编写 iced/window 代码;不要将 `layer-shell` 的缺失当作 Linux 后端无法录音/调用 Core。 + +## 14. 之前提出的 Linux 业务/后端 API 补充(B10–B17) + +> 以下名字代表**推荐的能力边界**,不是要求改变 Core 的既有 API 形状;Agent 必须先检索现有 trait、DTO、命令及测试,保留旧版兼容接口。 + +| ID | 等级 | 需保留/补齐的 Host API 家族 | 具体工作与验收 | +|---|---|---|---| +| B10 | P1 | **CLI/Daemon/TTY API**:`dictate`、`--tty`、`--json`、`toggle/start/stop/cancel`、`daemon start/stop/status`、`tui`(已有则检查) | 不改变 shell 命令行为;TTY 提示音 + 长静默自动停止;JSON stdout 纯净;SIGINT/SIGTERM/SIGHUP 无泄漏,`tui` 可选且不强制进入 | +| B11 | P1 | **Host Diagnostics / Capability API**:`get_linux_runtime_status`、`get_linux_global_shortcuts_status`、`get_hotkey_capability` 等已有方法 | 返回后端来源、权限、状态、错误码和恢复建议;探测只读不自动解锁、安装、重启或读取文本,支持前端未来 iced 接入 | +| B12 | P1 | **持久化与事件契约**:`get_settings_snapshot`、revision-aware patch、`runtime_snapshot`、`subscribe_events`、取消 token/会话代际 | 每个事件带 sequence/generation/sessionId;断线后可 snapshot reconcile;settings 更新避免整对象覆盖;历史/风格/凭据迁移不破坏数据 | +| B13 | P2 | **应用目标与选区 Voice Intent**:`get_selection_voice_intent_prompt`、`confirm_selection_voice_intent_prompt`、`get_selection_voice_preview`、`confirm/cancel/revert_selection_voice_preview` | 复用现有 Core 会话;对 ticket 失效、选区变化、undo 归属有确定错误;Unicode 正确,不能给当前不同窗口应用结果 | +| B14 | P2 | **Provider / Config / Style / History 接口覆盖**:channel CRUD、provider models、history、vocab、correction、style packs | 不重造业务 Core;核查 Linux Host 透传字段和错误完整性,覆盖字段级更新、云同步/凭据、历史和录音导出,命令/自动测试可验证 | +| B15 | P2 | **文件/系统操作 API**:`pick_directory`、`pick_style_pack_zip`、`pick_style_pack_zip_target`、`export_audio_recording`、`open_external_url` | 既有 Portal 优先、kdialog/zenity 备选;区分用户取消/拒绝/超时/失败;导出原子写入、检查 UUID 与历史归属;CLI 可传路径免 GUI | +| B16 | P3 | **凭据错误恢复 API**:`keyring_state`、`unlock_keyring`、`get/read/set_credentials`、`validate_provider_credentials` | 已有 Secret Service 只增强错误恢复;“钱包独立密码恢复”属于独立功能,须需求明确及安全设计,不为此引入明文密钥库 | +| B17 | P2 | **可配置 Shell/Editor Output Adapter**:`stdout/json`、用户明确选择的 Bash/Zsh/Fish/tmux/Neovim 目标 | 避免劫持原命令输入;先独立测试目标 identity/pane/buffer 和安全回退;没有目标就 stdout,远端没有麦克风要明确错误 | + +### 14.1 已有命令及业务接口完整核查表(不要重写) + +Agent 必须以原始清单为准在工作树查询下列真实命令/API;不存在或名称变化则用 `实际路径/接口名` 说明,不盲目新建同名包装: + +- **CLI/录音**:`openless ctl dictate`、`dictate --tty`、`dictate --json`、`toggle`、`start`、`stop`、`cancel`;`mics --json`、`mic default`、`mic ""`;`list_microphone_devices`、`record_channel_test`、`start_microphone_level_monitor`、`stop_microphone_level_monitor`。 +- **全局热键**:`get_linux_global_shortcuts_status`、`enable_linux_global_shortcuts`、`disable_linux_global_shortcuts`、`get_hotkey_status`、`get_hotkey_capability`、`validate_shortcut_binding`、`set_dictation_hotkey`、`set_qa_hotkey`、`set_translation_hotkey`、`set_skip_auto_style_hotkey`、`set_switch_style_hotkey`、`set_open_app_hotkey`。 +- **选区及文本**:`get_selection_voice_intent_prompt`、`confirm_selection_voice_intent_prompt`、`get_selection_voice_preview`、`confirm_selection_voice_preview`、`cancel_selection_voice_preview`、`revert_selection_voice_preview`、`copy_text_to_clipboard`、`debug_read_cursor_context`。 +- **文件**:`pick_directory`、`pick_style_pack_zip`、`pick_style_pack_zip_target`、`export_audio_recording`、`open_external_url`。 +- **凭据**:`openless ctl wallet status`、`wallet unlock`;`keyring_state`、`unlock_keyring`、`get_credentials`、`read_credential`、`set_credential`、`validate_provider_credentials`。 +- **配置/风格/Provider**:`openless ctl config get/set/call`、`styles`、`style `、`history`;`get_settings`、`get_settings_snapshot`、`list_channels`、`create_channel`、`delete_channel`、`set_channel_enabled`、`list_provider_descriptors`、`list_provider_models`、`list_history`、`clear_history`、`delete_history_entry`、`list_style_packs`、`save_style_pack`、`delete_style_pack`、`set_style_pack_enabled`、`set_active_style_pack`、`list_vocab`、`add_vocab`、`remove_vocab`、`list_correction_rules`、`add_correction_rule`、`remove_correction_rule`。 +- **应用/生命周期**:`get_app_style_routing`、`get_input_app_icons`、`get_activity_app_icons`、`get_linux_runtime_status`、`restart_app`、`get_desktop_onboarding_state`、`set_desktop_onboarding_finished`;`openless ctl daemon start/stop/status`、`tui`。 +- **旧 Ask**:`qa_start_voice`、`qa_cancel`、`qa_get_snapshot`、`qa_submit_text`、`qa_toggle_recording`,对照新版 `ask_*` 差异,旧功能在迁移期间不得无故回归。 +- **远程语音输入**:原功能保留并做回归测试;**不再开发第二套远程输入通道**。 + +## 15. 之前讨论的源码问题:逐项保留,且区分迁移后是否需要执行 + +> 这是对第 2–4 章的逐项追溯。关联旧 PR 静态源码审查,**所有“确认”只限旧 PR SHA,实际修改前必须在 Agent 本地新工作树复现**。 +> +> 源码审查依据:当前工作树优先;PR #1446 head `d47443a26f98d4712b2b14bb784e28029a1c521c` 仅用于追溯历史问题。所有旧 PR 结论必须在本地重新确认;当前已完成或已修复的 IPC、TTY、Portal、Wallet 和 ASR 事实以第 1.3 节及 W0 证据为准。 + +| 旧编号 | 旧源码问题/位置 | 新计划处理方式 | 理由与测试 | +|---|---|---|---| + +> 本表中的“旧源码问题”只表示 PR #1446 的历史观察,不表示当前工作树仍存在。W0 必须增加“当前文件:行号、当前证据、当前状态”三列后再执行修复。 +| P0-1 | PR #1446 的 `linux/web/src/main.rs` loopback HTTP `/api/invoke`/`/api/events` 缺少真实认证 | **先复核当前 `request_origin.rs`、HTTP 路由和发布入口;仅对仍暴露的入口做最小安全阻断** | 当前 CLI/Unix socket 已完成 UID/权限验证;不得把旧 PR 结论直接套到当前实现,也不得继续扩展旧 HTTP/SSE 桥 | +| P0-2 | HTTP 读取不限制 body/header/连接数,按 Content-Length 直接分配 | **安全最小阻断;随后移除** | 如果仍有入口,必须限制长度、连接/等待;旧桥退出后删除对应测试与依赖 | +| P0-3 | `qt/src/main.cpp` JS alert / `openless:` scheme MainWorld bridge 信任边界不清 | **在 Qt 仍发布时做最低安全隔离;Retired 后删除** | 不移植 Qt JavaScript 桥,不构建 iced 版网页特权桥 | +| P0-4 | 旧 `web/src/host.rs` `/tmp` fallback、socket 回收竞态、Qt 启动扫描 `/proc` 同名并 kill | **先核对当前 `host.rs`/`lifecycle.rs`;保留仍存在的通用问题,Qt 专属逻辑仅在 Retired 后删除** | UID/runtime dir、PID/starttime/lock ownership;不误杀正常 headless daemon | +| P0-5 | `host/src/host_context.rs` 敏感程序过滤发生在 `reader.read()` **之后**;Fcitx 插件有原文日志风险 | **必须修** | 敏感门禁读取前执行;日志不记录 surrounding/选区/用户语音文本 | +| P1-1 | `linux/web/src/main.rs` 只监听 `/dev/snd` inotify | **必须补事件** | PipeWire Registry/Metadata 或等效后端订阅+低频恢复,检测虚拟设备/蓝牙/daemon 重启 | +| P1-2 | `host/src/capabilities.rs` `cpal:{index}:{name}` 持久 ID、过滤 channels>2、按名称去重 | **必须修** | 后端级设备 ID、旧偏好迁移、多通道麦支持、同名设备区分 | +| P1-3 | `host/src/hotkeys.rs`、`web/src/hotkeys.rs` D-Bus 监听错误就退出 | **必须修** | NameOwnerChanged、代际状态和有界退避重连 | +| P1-4 | `host/src/fcitx5.rs` 任何 commit 失败都剪贴板 fallback | **必须修** | 区分 NotInserted/OutcomeUnknown,避免未知成功后双写/向新焦点误写 | +| P1-5 | `host/src/audio.rs` 录音归档 append 失败只 warning | **必须修** | 必需归档失败通知 Core,并可靠终止/降级;损坏归档不报成功 | +| P1-6 | `host/src/audio_mute.rs` 静音后恢复默认 sink,可能不是原设备 | **必须修** | 按 sink identity + 用户中途变更检测恢复,所有 `pactl/wpctl` 调用限时 | +| P1-7 | Qt `std::_Exit`、Rust `thread::park()`、常驻后端停机状态不清 | **通用退出问题必须修;Qt 实现不再扩展** | 取消录音、归档 finalize、任务/会话/socket 清理;Qt 退出 workaround 随旧宿主淘汰 | +| P1-8 | `capabilities.rs` `supports_overlay` 静态将全部 Wayland 标为 false | **Host 只改能力报告** | 报协议与权限支持,不替 iced 开发窗口/胶囊 | +| P1-9 | Fcitx 插件发 Ctrl+C 等待 clipboard 变化来猜测选区 | **必须修** | 最后回退、明确许可、不能保证富剪贴板恢复、TTY 严禁拦截 Ctrl+C | +| P2-1 | GitHub PR 的 `web/src/system.rs` 仍 kdialog→zenity | **若本地已有 Portal picker,只做验收** | 检查 `portal_picker.rs` 是否已落地;旧 PR 不是本地事实 | +| P2-2 | GNOME Wayland 无通用 layer-shell/活动窗口访问 | **只补 Host capability/fallback** | 窗口 UI 由前端负责;不伪造支持 | +| P2-3 | deb/rpm 强制依赖 `fcitx5` 与 `fcitx5-frontend-qt6` | **必须改装包边界** | Fcitx 插件应可选;不让 GNOME+IBus 安装 Qt 运行时才能用 CLI/ASR | +| P2-4 | File/IBus/AT-SPI/Portal/窗口/clipboard API 兼容宽度不足 | **S01–S28/B01–B17 逐项执行或记录阻断** | 每项指定测试环境、已实现状态/失败回退,不以新增 API 数量作验收 | + +## 16. 所有此前提过的 Linux 功能缺口:P2/P3 不准遗漏 + +### 16.1 新版 Ask Host(B05,完整工作包,不只是函数名字) + +- **复用**共享 Core:会话 `create/update/cancel/get_snapshot`、历史、对话状态、异步流事件、取消代际;保留旧 `qa_*` 行为直至新版接口经过测试。 +- **受限上下文**:当前窗口 `window_context`、浏览器标签 `browser_tab_context`、选区/光标上下文必须逐来源授权;浏览器标签不能凭 Linux Host 直接读取网页,需浏览器端/用户授权配合。 +- **附件**:文件 URI/导入、size/MIME、持久化归属、清理、安全打开;截图和屏幕流只通过有效 Portal 授权。拒绝/取消/无 Portal 返回明确结果。 +- **测试**:文本会话、附文件、断网/取消、权限拒绝、敏感字段、切换窗口、旧 QA 回归、无 GUI/headless 的明确 Unsupported。 +- **不做**:iced Ask 页面、聊天 UI、无授权 DOM 抓取、长期后台截图。 + +### 16.2 全字段 Voice Edit(B02,完整工作包) + +- 保留 selection-only,**新增安全的 full-field capture/replace/revert**;使用 Fcitx/IBus/AT-SPI 能力按目标实际支持选择路径。 +- transaction 包含 targetId、app identity、focus generation、field snapshot/hash、selection offsets 与失效条件;既有内容被修改时不覆盖。 +- 替换与撤销需要目标仍属于本次事务;富文本/密码框/未知偏移单位不支持就拒绝,不以自动 Ctrl+A/Ctrl+V 模拟“全字段成功”。 +- 测试中文、Emoji、组合字符、超长字段、光标移动、多窗口、撤销只撤自己更改、权限拒绝。 + +### 16.3 Linux 本地 ASR(B06,完整工作包) + +- 审核 Core 已有的 Foundry / Sherpa-ONNX models API 与 Linux 支持情况;区分列出模型/下载/校验/解压/升级/删除/加载/卸载/推理,补取消及磁盘不足恢复。 +- 模型运行时架构/CPU 特性/动态库/推理线程与内存预算按 x86_64/aarch64 实际矩阵核实;CPU-only 可用路径与不支持的后端明确标注,不能依赖开发机 GPU。 +- `installed`、`runtime_ready`、`loaded`、`transcribing`、`fallback_used` 状态分离;云端回退需明确策略,不假装本地执行。 +- 测试无网络、校验失败、模型不存在、运行时启动失败、长时间运行/多会话取消、升级与清理。 + +### 16.4 Voice Activation(B08,完整工作包) + +- 支持用户主动启用的 wake phrase/finish phrase、状态、启停、模型就绪、低功耗门限、取消以及与普通快捷键录音互斥。 +- 无麦克风、锁屏、切换用户、睡眠、设备断开/恢复时按安全策略暂停/停止;**默认不开持续监听**,后台常驻前有清晰的用户同意/提示。 +- 明确隐私、资源/功耗和误触发测试;不可用时 `Unsupported`,不得始终返回成功的 no-op。 + +### 16.5 应用分类/自动风格路由(B07) + +- 将 XDG Desktop Entry (`Categories`,`StartupWMClass`,`Icon`)、Flatpak app id、Snap 名称与 Fcitx/IBus/AT-SPI/X11/合成器 app id 合并成稳定 `ApplicationIdentity`。 +- 不读取无授权文档内容,不借助易变窗口 title 猜用户具体任务;同名 App/多窗口要避免串会话,用户手工选择的风格优先。 +- 目标不可识别时可关闭自动路由并返回 unknown,而不是误用上一次窗口。 + +### 16.6 凭据、钱包及云同步(B14/B16) + +- 继续使用 Secret Service 与已有 `wallet status/unlock`;分清 `locked`、`service_unavailable`、`permission_denied`、`credential_missing`,状态探测不得弹解锁。 +- 与 Core 的 E2EE/云同步、Provider credentials、风格包、历史保持数据迁移向前兼容;不能因为 iced 迁移改变密钥命名、账户及配置目录。 +- “脱离 Wallet 的独立凭据恢复”属于此前提出的**潜在后续需求**;须先有密钥管理、安全模型、迁移与回滚方案,不能擅自新增明文持久化。 + +### 16.7 远程语音输入(回归而非重做) + +- 已有远程语音输入功能继续保留,测试 Headless/SSH/前端未来接入时的会话归属、断线、取消和来源身份。 +- **不另起新的手机→Linux 麦克风推流协议或第二套远程 ASR 服务**。RemoteDesktop Portal/libei 与此不是同一功能。 + +## 17. TTY/CLI 之前商定的所有限制与验收(详尽版) + +1. **触发方式**:用户最初希望快捷键,但最终否决了会干扰现有命令行的拦截、常驻状态栏及光标操作。默认采用**显式 CLI 命令**(用户自行配置安全的 shell binding 属可选),不实现 TTY 系统级键盘 hook,不占 stdin 影响运行中的命令。 +2. **语音开始**:识别 stdin/stdout 是否 TTY、终端前台进程组与本地音频可用性;立即建立可用的音频捕获/适当缓冲,开始提示短音;确定提示音不会被当作有效语音输入,且不能用固定延迟丢弃首字。 +3. **录音结束**:本地 VAD/静默超时判定,满足持续无语音时停止;需配置语音起始/尾部静默、最短/最长录音和环境噪声保护;播放结束短音,然后进入 ASR/LLM。 +4. **反馈**:只使用提示音和 CLI 退出结果;不实施永久占据终端的 TUI 录音状态、行内彩色动画、回车自动注入。音频无法播放时应返回状态/警告,不冒充提示成功。 +5. **输出**:默认识别文本到 stdout(由 shell 用户决定是否插入当前 buffer);`--json` stdout 必须是单个完整 JSON 对象、换行结束;提示和 debug 输出 stderr;支持 pipe/重定向与明确非零错误码。 +6. **信号**:SIGINT/SIGTERM/SIGHUP、网络断开、TTY 关闭、重复 start/stop/cancel 必须幂等释放麦克风、音效、输出静音 guard、音频归档和 socket。 +7. **SSH**:远端服务器进程只使用服务器实际可见的设备;若没有麦克风就错误或采用已有的远程语音输入功能(不再造),不能“自动调用连接者手机/电脑麦克风”。 +8. **Shell 编辑器**:Bash Readline、Zsh ZLE、Fish、tmux、Neovim 均有可选集成/验收项,**不是**让后台进程给任意 foreground command 注入字符串;目标不明确时输出 stdout/私有 buffer。 +9. **测试**:Linux VT 纯 tty、SSH 无桌面、tmux 多 pane、Neovim 多 buffer、Bash/Zsh/Fish、中文 locale、旧版 Bash、断开声卡/无音频输出、长静默/持续噪声、信号中断;原始命令及结果写入审计。 + +## 18. 依赖选择、构建、打包与跨桌面验收(P2/P3 全部包含) + +### 18.1 依赖策略(候选,不是必须全部加入) + +| 需求 | 优先选项 | 关键约束 | +|---|---|---| +| session D-Bus/Portal | 当前已有 `dbus` 及现有适配 | 先检查 Cargo.lock;只有必要时评估 `zbus`/`ashpd`,避免双 D-Bus client 栈 | +| Fcitx5 | 已有 C++ addon + Rust DBus adapter | 不重写输入法、不强制改用户默认引擎 | +| IBus | 既有 `scripts/linux-ibus-plugin/`,再比较 libibus/zbus | 原生 Engine 激活、focus/ticket、二进制依赖及可选安装 | +| 录音 | 既有 CPAL(PipeWire/Pulse/ALSA) | 不重做音频驱动,不只靠 /dev/snd inotify | +| 音频事件 | PipeWire Rust binding 或 PulseAudio subscribe | CPU/动态库/打包复杂度对比;保留低频 reconciler | +| AT-SPI | 已有 Linux text access,必要时 `atspi` | 强 target/focus/密码门禁;不能作为全文爬取接口 | +| Clipboard | 先 `wl-copy`/`wl-paste`、`xclip`、`xsel` | 若需要原生 Wayland 适配,必须先有真实 bug 与 compositor 支持证据 | +| Shell/TTY | 标准库、POSIX/termios、可选 shell scripts | 不截获命令行,不强制 GUI / libei | +| RemoteDesktop 输入 | Portal + libei/reis | 用户授权/能力检测,明确不支持任意中文提交 | +| window/app identity | XDG desktop entry、X11/Hyprland/Sway 等已存在路径 | 无统一 Wayland 活动窗口权限;可选 API 不强制安装 | +| 通知/文件 | Portal,必要时保留 kdialog/zenity | TTY 不依赖任何 GUI picker | +| 服务与生命周期 | logind + Unix Socket + SIGTERM | 不要求 root,不依赖桌面前端进程活着 | + +**新增依赖审查**:每次新增记录版本锁定、许可证、最低 Rust/GCC、链接到的系统库、flatpak/snap 与普通 deb/rpm 下行为、二进制体积、失败回退;不要将可选 API 变成基础录音强依赖。 + +### 18.2 系统/发行版/桌面测试矩阵(不得凭编译通过宣称兼容) + +| 测试组合 | 项目 | 实际结果(Agent 填) | +|---|---|---| +| Debian 13/14、Ubuntu 24.04/26.04、Fedora GNOME/KDE | 装包、可选插件、无 Qt 主依赖、无 Fcitx 可 CLI | `Not Run` | +| KDE Wayland+Fcitx5 | 中文听写、选区、热键、clipboard owner、插件重启 | `Not Run` | +| GNOME Wayland+IBus | 可安装、IBus Engine opt-in、失败回退、无强制 Fcitx | `Not Run` | +| Sway/Hyprland/Niri | compositor IPC 身份、GlobalShortcuts 支持/拒绝、缺少协议降级 | `Not Run` | +| X11/XFCE/KDE | XGrabKey、X11 clipboard/PRIMARY、焦点票据 | `Not Run` | +| PipeWire + WirePlumber | 虚拟源、蓝牙 Profile、默认源变化、重启及恢复 | `Not Run` | +| PulseAudio-only / ALSA-only | 仅存路径可用,音频故障明确上报 | `Not Run` | +| GNOME/KDE 无 Portal | FileChooser 回退、Hotkey 无假成功、headless 可用 | `Not Run` | +| 纯 tty、SSH、tmux、Bash/Zsh/Fish/Neovim | 提示音、静默停止、首字、JSON、焦点安全 | `Not Run` | +| 多 UID/双实例、数据目录锁、恶意本地客户端 | 0600/0700、SO_PEERCRED、限长、崩溃重启 | `Not Run` | +| 功能 P2/P3 | VoiceEdit full-field、Ask/附件、本地 ASR、Voice Activation | `Not Run` | + +### 18.3 故障注入完整列表 + +- **音频**:PipeWire/WirePlumber restart、USB 拔插、蓝牙 profile 变更、虚拟源热插拔、双同名麦、`channels > 2`、采样格式改变、录音 `ENOSPC`、挂起/恢复、队列溢出、ASR 连续超时。 +- **输入**:焦点在 ASR 期间变化、目标窗口关闭、文档并发更新、撤销前文本修改、D-Bus 响应丢失但文本已提交、Fcitx5/IBus 重启、密码字段、Emoji 与 Unicode 组合、Wayland clipboard owner 丢失。 +- **热键**:GlobalShortcuts Session Closed、授权撤销、Portal 后端重启、Fcitx 重启、X11 热键冲突、长按到一半 D-Bus 断线。 +- **会话**:锁屏、活动 session 切换、fast user switching、Sleep/Resume、用户注销、无 DBus/systemd、SSH 掉线。 +- **IPC**:不同 UID、同 UID 第二进程、假 socket、共享 `/tmp`、超长请求、并发大连接、破损帧、`SIGKILL` 重启、旧 HTTP 过渡路径的恶意请求。 +- **文件/凭据**:Secret Service 锁定、服务不存在、文件权限拒绝、Portal FileChooser cancel、导出路径切换、包卸载/升级、云同步与配置版本迁移。 +- **资源**:小内存、CPU 高负载、网络异常、磁盘满、超大历史、模型下载中断、无输出声卡;不得假装做过实机测试。 + +## 19. 执行拆分:P0/P1/P2/P3 都要有交付,不因排序而删除 + +| 工作包 | 涵盖 ID | 何时交付 | 必须产出 | +|---|---|---|---| +| W0 / 事实审计 | S01–S28、B01–B17、旧 PR 的所有风险 | 第一步 | `docs/linux/api-gap-matrix.md` + `docs/linux/backend-compat-audit.md`,含每项源码证据、状态/优先级/依赖 | +| W1 / 安全 | S03,S05,S07,S21,S23,B02,B04 | 先做 | 输入 ticket、隐私、unknown outcome、clipboard 回退、IPC / 最小旧 HTTP 处理 | +| W2 / 音频 | S02,S22,B03 | W0 后并行 | 设备事件、稳态 ID、归档失败、mute guard、VAD/提示音 | +| W3 / 生命周期 | S04,S06,S18,S24,B10,B11 | W1/W2 | Fcitx/Portal 重连、logind、CLI/TTY、daemon 有序退出、诊断状态 | +| W4 / IME 广度 | S01,S05,S14,S15,B01,B02,B13 | W1 之后 | GNOME IBus 真正提交、AT-SPI 安全适配、Voice Edit 全字段及 X11 测试 | +| W5 / 桌面服务 | S08–S12,S16,S17,S21,S27,S28,B07,B14,B15,B16 | 不阻塞 W1 | 应用身份、Portal、Clipboard、钱包、依赖分包和风格路由 | +| W6 / CLI/编辑器 | S18–S20,B10,B17 | 可并行 | Bash/Zsh/Fish/tmux/Neovim/SSH 证据矩阵及安全降级 | +| W7 / 业务对齐 | S25,B05,B06,B07 | 基础稳定后 | Ask Host、附件、Linux 本地 ASR、应用路由独立 PR/测试 | +| W8 / 后续能力 | S13,S25,S26,B08,B09,B16 | 最后 / 条件触发 | Voice Activation、ScreenCast/Screenshot、RemoteDesktop 评估/授权测试 | +| W9 / 交付验收 | S01–S28、B01–B17 | 每一批及收尾 | 后端契约、release/installation CI、能力表,未完成/Deferred 逐项解释 | + +**这不是让 Agent 一次性把 45 项在同一个 PR 中全部写完**:要让 Agent **全部纳入范围并逐项追踪**,但以独立可回滚小 PR 推进。可以先交付审计及现有已有能力的验收,然后实现新能力。不得因 P2/P3 优先级低就从需求文档删掉。 + +## 20. 明确“不做”的旧任务(要写在 Agent 的排除表里) + +- iced 前端任何 UI/样式/窗口、内部 clipboard/wgpu/winit/layer-shell 实现:其他开发者负责;**iced 框架已选定并通过测试,不再重复选型**。 +- Windows/macOS Host API、三端公用 GUI 工程与迁移:不由此 Agent 执行。 +- Qt6 WebEngine、旧 `QWebEnginePage` JS alert、自定义 Scheme、Qt Process Manager/CMake/渲染器、React HTTP/SSE UI Bridge 的长期维护:计划废弃;仅留对仍发布入口的最低安全修复。 +- 重造远程语音输入、重写成熟 Core ASR/LLM/Provider/历史、独立 GUI 守护进程:不做。 +- root/evdev/uinput 常驻键盘监听、无授权 Wayland 文本注入、TTY 抢占快捷键、随意改用户默认输入法、自动解锁 Secret Service:不做。 +- 未经明确授权截图/屏幕流/浏览器标签读取,或跨应用隐形监控:不做。 + +## 21. 给 Agent 的最终完整执行指令(可直接复制) + +> **任务:OpenLess Linux 后端全量兼容与 API 补齐(不开发前端)**。团队已确定 Windows、macOS、Linux 的前端统一由其他人迁移 iced,我们只负责 Linux 原生 Host/Core adapter、音频、输入法、选区与安全插入、桌面 API、CLI/TTY/SSH、后端产品功能的 Linux 对齐。**严格覆盖本文件 S01–S28 与 B01–B17(包含 P0/P1/P2/P3),以及旧代码风险表与测试矩阵;不得因低优先级删除条目。** +> +> **第一步必须审计本地工作树**,逐项寻找真实源码/测试,核对原 Agent 能力清单与 PR #1446 快照:标记 `Present+Tested / Present+Untested / Partial / Missing / Blocked / Deferred / Retired`,附文件与行号;未查证只能写 `Unverified`。不要覆盖未提交更改,不因为 GitHub PR 缺文件就重复开发。 +> +> **实现原则**:已实现只补缺陷;优先修隐私/目标误写/录音丢首字/音频热插拔/Fcitx 重连与端到端稳定性;再扩展 IBus、AT-SPI、Voice Edit、Portal、应用身份、CLI/shell;后续 Ask Host、本地 ASR、Voice Activation、附件截图、原生 Wayland Clipboard、RemoteDesktop 依本文件逐项评估、实现或留下明确阻断与测试。明确区分“实际系统 API”、“建议 Rust 抽象”和“业务 API”,不要把无权限场景的功能伪称成功。 +> +> **交付**:小 PR/小提交、可运行 headless/CLI harness、带版本号的 Host DTO/能力报告、安装依赖表、真实系统兼容矩阵、故障注入结果、未执行测试 `Not Run`、未实现项与阻断原因。不得推送、合并、修改其他开发者的 iced 代码或擅自引入 root 常驻服务。完成一批仍要保留下一批所有 P2/P3 条目,不得遗忘。 + +## 22. 原始文档、源码与事实来源(供 Agent 复核) + +1. 本文件第 0–12 章:整合此前 Linux 后端范围、S01–S12 / B01–B09,以及 CLI/安全/音频测试。 +2. 用户提供的本地 Agent 原始能力清单(2026-11-29):本地声称具备 CLI、Unix socket、Fcitx5、Portal、AT-SPI、TUI/TTY、密钥库、配置/风格、部分 Voice Edit 及音频;需本地逐项证实。 +3. 公开源码:,已核查 head `d47443a26f98d4712b2b14bb784e28029a1c521c`;#1495 已关闭未合并。 +4. 推荐 Agent 阅读:`openless-all/linux/host/src/{fcitx5.rs,host_context.rs,audio.rs,audio_mute.rs,audio_cue.rs,capabilities.rs,terminal_vad.rs,hotkeys.rs,global_shortcuts.rs}`、`openless-all/linux/fcitx5-plugin/openless.cpp`、`openless-all/linux/web/src/{main.rs,host.rs,ctl.rs,ctl_transport.rs,system.rs,request_origin.rs}`、`openless-all/app/crates/openless-core/src/{domains.rs,api.rs,dictation_engine.rs}`;本地实际 API 与行号以 W0 审计为准。 +5. **证据级别**:`GitHub 静态已核查` / `Agent 清单所述未独立验证` / `建议新增设计` / `待真实环境验证`;任何一项都不得跨级虚报。 + diff --git a/docs/linux-cli-and-fallbacks.md b/docs/linux-cli-and-fallbacks.md new file mode 100644 index 000000000..221489dac --- /dev/null +++ b/docs/linux-cli-and-fallbacks.md @@ -0,0 +1,420 @@ +# Linux CLI Mode, Multi-API Fallbacks & Dual Frontends + +## 1. Multi-API Fallback Chains + +OpenLess on Linux no longer depends on a single input method or compositor protocol at runtime. + +### Text Insertion (`LinuxTextInserter`) +1. **Fcitx5 focused ticket** (`CaptureFocusedDictationTarget` -> `CommitDictationTarget`) — zero clipboard interference, full Unicode, password-field safe. +2. **AT-SPI2 `EditableText`** (opt-in via Permissions -> Accessibility text targets) — verified editable text controls with stale-content rejection and full-field voice edit support. +3. **Session Clipboard Fallback** (`wl-copy` on Wayland -> `xclip` / `xsel` on X11/XWayland -> running Fcitx5) — returns `CopiedFallback` instead of dropping dictated text in terminals, GNOME/IBus, or non-AT-SPI apps. +4. **Terminal Direct Output** (`openless ctl dictate`) — prints recognized text straight to `stdout` for Zsh/Bash/Fish/tmux/Neovim cursor insertion. + +### Global Hotkeys +1. **XDG GlobalShortcuts Portal** (Wayland/KDE/GNOME/wlroots, explicitly authorized; uses Freedesktop Shortcuts Spec XKB keysym triggers). +2. **Pure X11 `XGrabKey`** (automatically enabled on pure X11 sessions when Fcitx5 is unavailable; runtime `dlopen("libX11.so.6")` with zero compile-time X11 dependency). +3. **Fcitx5 Plugin** (within connected Fcitx5 input contexts). +4. **CLI / Unix Control Socket** (`openless ctl toggle|dictate`) — works in any window manager (Sway, Hyprland, i3, KDE, GNOME) and over TTY/SSH. + +### Active Window Identity, Selection, Picker & Audio Fallbacks +- **Front App Detection (`active_window.rs`)**: use `printf '{}' | openless ctl config call get_active_app` for `appId`, `appName`, and nullable `windowTitle`. Resolution prefers Hyprland/Sway, native X11, or authorized GNOME Shell Introspect metadata, then an opted-in AT-SPI focus lease and the running Fcitx5 addon's focused program. KDE Wayland and GNOME sessions that deny Introspect use the latter sources; no compositor scripts or extensions are installed. XWayland's stale root focus is not used on Wayland. Window titles are read only by the explicit metadata command, not by dictation or app-style routing. If no source can verify the active app, the command returns `null`. +- **Selection Capture & Replacement (`selection.rs`, `qa.rs`, `text_access.rs`)**: `Fcitx5` -> `AT-SPI2` -> `PRIMARY selection (wl-paste --primary / xclip / xsel)`. AT-SPI compares the frozen field contents and selection, checks focus, and verifies the postimage after a direct replacement or revert. A lost reply or partial write returns non-retryable `outcome_unknown`; OpenLess does not automatically copy, recommit, or undo. Inspect the original field before capturing it again. +- **File & Directory Picker (`portal_picker.rs`, `system.rs`)**: `org.freedesktop.portal.FileChooser` D-Bus Portal first (native KDE/GNOME/wlroots dialogs) -> `kdialog` -> `zenity`. +- **Microphone Default Detection (`capabilities.rs`)**: `pactl` -> `wpctl inspect @DEFAULT_AUDIO_SOURCE@` (for minimal PipeWire systems without `pulseaudio-utils`). + +--- + +## 2. Linux release editions and GUI frontends + +Linux has two mutually exclusive package editions (they share the `openless` +command and the same user data): + +| Edition | Package name | Contents | +| --- | --- | --- | +| **CLI-only** | `openless-cli` | Rust backend/CLI, launcher, version and edition metadata. No Qt, GTK, WebEngine, React assets, Fcitx5 addon, desktop entry or icons. No mandatory GUI/Fcitx5 package dependencies. | +| **UI** | `openless` | The same backend/CLI plus Qt6 and GTK4 shells, React assets, Fcitx5 addon and desktop integration. Qt is the default; GTK is the optional alternative. | + +The CLI edition still needs native audio and D-Bus **libraries** (ALSA, PipeWire, +libdbus), not a running desktop, session bus, Secret Service, Fcitx5, or AT-SPI. +Missing session services are nonfatal; their capabilities are unavailable, not +silently emulated. Cloud credentials still require an available credential vault; +headless operation does not bypass that requirement. Headless startup disables +tray registration and GUI presentation even if a desktop session bus is inherited. +`ctl status --json` reports `headless`, presentation, adapter and credential state. + +With neither UI shell installed, `openless` (including `--frontend=auto`) starts +headless in the **foreground**, rather than failing on a missing Qt/GTK executable. +Use `openless ctl daemon start` for detached operation, `openless ctl --help` for +CLI commands, or `openless --help` for launcher help. Both editions support +`openless --headless` and every `openless ctl ...` command. Installing a UI shell +restores the normal graphical default. + +### Building packages + +```sh +# Set OPENLESS_LINUX_VERSION to the release version with the current +# openless-all/linux/host/package-revision suffix first. +bash openless-all/linux/scripts/package-linux-qt.sh --edition cli +bash openless-all/linux/scripts/package-linux-qt.sh --edition ui # default, backward compatible +bash openless-all/linux/scripts/package-linux-qt.sh --edition all # both in one output directory +bash openless-all/linux/scripts/verify-linux-host-packages.sh # detects one or both editions +``` + +Existing `OPENLESS_*` binary/build overrides and `OPENLESS_PACKAGE_OUTPUT` remain +supported. CLI packaging never builds or requires the GUI shells, React dist or +Fcitx5 addon. UI artifact names retain `OpenLess-Linux-...`; CLI artifacts use +`OpenLess-CLI-Linux-...`, in deb/rpm format. `all` writes both pairs with a shared +`SHA256SUMS`; the verifier checks metadata, payloads and dependencies, including a +strict CLI payload allowlist. RPM creation requires `rpmbuild`; full verification +requires both deb and rpm artifacts. The editions conflict rather than overwrite +each other's shared files. + +### Dual GUI frontends (UI edition) + +```sh +openless # Default: Qt6 WebEngine (auto-falls back to GTK if Qt binary is absent) +openless --frontend=qt # Explicit Qt6 WebEngine +openless --frontend=gtk # Explicit GTK4 + WebKitGTK +openless --frontend=auto # Automatic Qt -> GTK selection +``` + +Both shells share one singleton lock (`openless.lock`), one window handoff socket (`openless-host.sock`), one Rust backend (`openless-linux-web`), SSE auto-reconnect, render-process crash recovery, orphan-backend cleanup, and non-layer-shell fallback windows on GNOME Wayland and X11. + +--- + +## 3. Headless & Command-Line Mode (`openless --headless` / `openless ctl`) + +### Start & Manage Headless Daemon +```sh +openless --headless # Run in foreground (for systemd or scripts) +openless ctl daemon start # Start detached in background and wait until ready +openless ctl status # Human-readable status (keyring, style, mic, adapters) +openless ctl status --json # Machine-readable JSON status +openless ctl daemon stop # Stop cleanly (alias: openless ctl quit) +``` + +### Quiet terminal recording and volume-based automatic stop + +`openless ctl dictate --tty` uses the existing local volume-threshold detector, +not WebRTC/Silero VAD and not a cloud request. No new classifier, model download, +or VAD runtime dependency is needed. The policy is frozen for this terminal +session: ten seconds without crossing the threshold cancels; after sustained +above-threshold audio, fifteen seconds below the threshold requests stop and +processing. Noise can count as activity; this is not a claim of human-speech +recognition. Desktop/remote defaults and saved preferences are not changed. + +The quiet capture path does not print recording/status prompts, change termios, +or consume terminal keys. It returns only the explicit result on stdout, for a +shell widget to insert. A pre-capture tone completes before the microphone starts; +completion/cancel/error have best-effort tones. If the start tone cannot play, +recording does not start unless `--no-cues` was explicitly selected. The existing +native CPAL audio path is reused. `--manual` selects the old interactive path; +TTY detection defaults to quiet mode when stdin is a terminal and neither DISPLAY +nor WAYLAND_DISPLAY is set. Generated shell/editor bindings explicitly use +`--tty`. The management dashboard below is a separate, explicitly opened view. + +Client disconnect cancels its owned session. Five seconds without capture +progress cancels as an audio fault, not silence; a thirty-minute session deadline +also cancels. Text is never injected into an arbitrary terminal. Automatic +terminal stop is handled only for the owned generation, with no uncertain replay. +The tmux snippet no longer draws a popup or automatically pastes into a potentially +changed program: it records into a named `openless-` buffer for explicit +paste. Fully verified automatic tmux delivery remains follow-up work. + +### External recording-state hooks (`openless ctl events --json`) + +**OpenLess does not ship built-in terminal recording-indicator UI.** Quiet terminal +capture remains quiet; users may build an indicator in their own shell, tmux status +line, bar or notification service using this opt-in stream. The separately opened +management TUI is not an automatic terminal recording indicator. + +```sh +openless ctl events --json +# Example first line (actual IDs, sequence and time vary): +# {"schema_version":1,"event":"snapshot","seq":17,"timestamp_ms":1790000000000,"session_id":null,"phase":"idle"} +``` + +The command connects to the private same-user Unix control socket and emits +**NDJSON**: one JSON object per line, flushed immediately, until disconnect or +backend shutdown. The first line is a snapshot; subsequent transition objects +have the following schema: + +| Field | Meaning | +| --- | --- | +| `schema_version` | Integer `1`. | +| `event` | `snapshot`, or the new phase: `starting`, `recording`, `processing`, `completed`, `cancelled`, `failed`, `idle`. Also `lagged` as described below. | +| `seq` | Backend-instance event sequence/watermark, not a persistent ID. Transition sequences increase but need not be consecutive; unrelated backend events also consume sequence numbers. Snapshot/lag notices may repeat a watermark. Resets on daemon restart. | +| `timestamp_ms` | Unix wall-clock milliseconds when the hook object is emitted; not a monotonic clock. | +| `session_id` | Session UUID string, or JSON `null` when no session is associated. | +| `phase` | One of the seven phases above. Transcribing, polishing and inserting are coalesced into `processing`; repeated phase/identity updates are suppressed. | +| `error` | Optional sanitized error classification; clients must tolerate its absence, including on `failed`. Raw provider errors are not forwarded. | + +Objects are built from an explicit field allowlist: **no transcript text, +credentials, document content, snapshot messages or raw provider error text**. +This is a recording-state hook, not a transcript/history/credential export. + +Each connection consumes a bounded backend broadcast channel and has a bounded +socket-write timeout. A slow/dead subscriber cannot stall the recorder or listener. +If events are dropped, a notice with `event: "lagged"` and a positive `dropped` +count is emitted, followed by a fresh `snapshot` resynchronization. The count +covers dropped backend events, not only recording transitions; a lag notice's +phase may be stale. Consumers should adopt the following snapshot, not infer +missing transitions. A subscriber stalled beyond the write timeout is disconnected +and must reconnect for a new initial snapshot. There is no durable replay promise. +The normal same-user socket protections and concurrent-client limit still apply. + +Example **user-owned** Bash/tmux indicator (requires `jq`, tmux and a running +backend). Save as `~/.local/bin/my-openless-indicator`, run it inside tmux, and +add `#{@openless_recording}` to your existing `status-right` configuration: + +```bash +#!/usr/bin/env bash +set -euo pipefail +trap 'tmux set-option -gu @openless_recording 2>/dev/null || true' EXIT +# --unbuffered keeps jq from delaying updates when its output is piped. +openless ctl events --json | + jq --unbuffered -r 'select(.schema_version == 1) | if .event == "lagged" then "unknown" else .phase end' | + while IFS= read -r phase; do + case "$phase" in + starting|recording) label='[MIC]' ;; + processing) label='[processing]' ;; + failed) label='[failed]' ;; + unknown) label='[resync]' ;; + *) label='' ;; + esac + tmux set-option -g @openless_recording "$label" + done +``` + +This changes only a user-defined tmux status variable; it does not inject text, +consume recording keys, draw popups or modify OpenLess recording behavior. It +clears the variable on exit. Restart the script after a daemon restart/disconnect; +add your own supervised reconnect policy if desired. Never `eval` event data. + +### Shell compatibility and generated bindings + +Bash 5+ reports Readline cursor positions in characters; older Bash reports byte +offsets. Generated bindings use the matching slicing/counting behavior, preserve +the caller's locale, and append text literally, never `eval` it. A nonzero +dictation exit leaves the original command buffer unchanged. Real interactive +Bash 5 and private-tmux tests cover Chinese, emoji and multiline results; legacy +Bash, Fish and Zsh still need their own installed-version acceptance tests. +Custom binding notation is validated before generating shell/Lua configuration: +quoting, command substitutions, control characters and tmux/Fish command or +redirection injection are rejected. This is not support for arbitrary shell code +in `--key`. + +### Backend exit and cancellation + +SIGTERM, SIGINT (Ctrl+C), SIGHUP, the tray quit action and `ctl daemon stop` share +one bounded shutdown path. New control/HTTP dispatcher operations are refused, +accessibility targets are revoked, and Core shuts down recording/processing rather +than finishing/transcribing it. Microphone monitoring and authorized shortcut +sessions are released. Cleanup has a ten-second budget; a failure/timeout exits +nonzero, never retries or replays uncertain text. Signals are registered before +readiness is published. Normal completion removes only the owned runtime socket +inodes and releases the data writer lock, so the same profile can restart. + +`ctl daemon stop` acknowledges a **shutdown request**, not proof that cleanup has +already completed. A signal cannot retract a write or remote request completed +before shutdown. SIGKILL cannot perform graceful cleanup; the next start still +uses the existing safe stale-socket checks. These paths do not require systemd. + +### Low-memory interactive TTY dashboard + +```sh +openless ctl tui +``` + +Connects to an already-running backend (`openless --headless` is sufficient), +without starting another recorder, GUI, model runtime, or background polling loop. +Type a letter and press Enter: `r` records, `h` shows the ten most recent history +entries, `s` refreshes status, `p` selects a style, `m` selects a microphone, and +`q` exits **only the client**, leaving the backend running. Lists display at most +32 entries and recording-result previews at most 4096 characters; full results +remain in backend history. This bounds the client view, not the backend history +store's total memory. Ask/chat is not part of this first dashboard. + +Recording uses a session owned by this client, with direct application insertion +disabled. Enter/Space finishes, Esc/Ctrl+C/q cancels; cancellation and terminal EOF +never commit a recording. Terminal control characters in displayed backend text +are filtered. There is no automatic permission request or daemon startup just +from opening this dashboard. Scripted callers should use the existing CLI/JSON +commands instead of `tui`. + +### Local control transport safeguards + +The control socket parent must be a non-symlink directory owned by the current +user with private permissions (normally `$XDG_RUNTIME_DIR/openless`, mode `0700`). A new +fallback directory is created private; an existing public directory is rejected +rather than silently changing administrator/user-selected permissions. If an +older headless installation created `/tmp/openless-` as `0755`, inspect its +ownership and change it to `0700` explicitly before using the new control socket. +The same private-parent requirement applies to `OPENLESS_CTL_SOCKET` overrides. + +The socket uses mode `0600`, a held per-path lock and kernel peer-UID checks. +Startup refuses active sockets, symlinks and regular files; only an owned, +connection-refused stale socket can be replaced. Stale checks are nonblocking, +and cleanup only removes the socket inode created by that listener. The lock +file is intentionally retained to avoid unlink/recreate lock races. + +Requests require newline-terminated UTF-8, are limited to 64 KiB with a ten-second +whole-request deadline, and at most 32 clients are served concurrently. Normal +CLI replies are capped at 4 MiB; status/ping replies have a three-second deadline. +Existing Ask streaming has its separate transport path and is not covered by +that single-reply cap. This is local same-user IPC, not a remote API. + +### User/profile isolation and simultaneous login sessions + +The backend singleton uses `$XDG_RUNTIME_DIR/openless/openless-web.sock`, or a private +`/tmp/openless-/openless-web.sock` fallback, never a global `/tmp` socket. +It uses the same secure bind/lease mechanism as the control transport. An owned +runtime parent such as mode `0711` is allowed if other users cannot write it; +OpenLess creates only its own `0700` child and never chmods the shared runtime +parent. A live older backend at the former socket path is detected and refused, +not killed or unlinked. Separate +Linux users normally have separate HOME/XDG data directories and runtime sockets. +Data defaults to `$XDG_DATA_HOME/OpenLess` (`~/.local/share/OpenLess`). + +Before Core opens data, the backend rejects a foreign, symlink, relative or +non-private data root and acquires `.backend.lock` there. New directories are +created `0700`; existing directories must be reviewed and made private explicitly. +The lock is `0600`, no-follow, user-owned, and held for the backend lifetime. +Different profiles can run concurrently; even with different runtime directories, +two login sessions cannot write the same data directory concurrently. The second +fails clearly rather than corrupting history or credentials. This is not yet +support for two independent desktop sessions sharing one profile live. + +CLI-only `--headless` startup does not create an HTTP listener: all CLI management +uses the same-UID Unix socket. Graphical mode still has its HTTP surface; the UID +checks on the control socket must **not** be described as authenticating that +separate surface. Full cross-user graphical HTTP isolation remains follow-up work. +No claim is made that audio devices support concurrent capture by multiple users. + +### Configuration and Wallet management without a GUI + +```sh +openless ctl config get +printf '%s' '{"/autoUpdateCheck":false}' | openless ctl config set +printf '%s' '{"kind":"asr"}' | openless ctl config call list_channels +openless ctl wallet status # passive; never asks to unlock +openless ctl wallet unlock # explicit consent: may open a system dialog +``` + +`config set` accepts a JSON object mapping **JSON pointers** to edited values, +using the exact preference names returned by `config get`. Core validates the +result and applies its existing settings transaction/runtime effects. `config +call COMMAND` is a same-user administrative API escape hatch for channels, +credentials, vocabularies, styles, sync and other backend configuration commands; +it deliberately reuses the existing dispatcher and validation, not a separate +configuration implementation. Both read at most 48 KiB of JSON from stdin. +Never put secrets/passwords in shell command arguments or a shell-history literal; +use a protected input source or a future dedicated hidden prompt. Advanced calls +can expose sensitive output and perform destructive operations: they are not a +read-only status interface, and their output must not be logged casually. + +Credential reads now use bounded Secret Service `SearchItems`/`OpenSession`/ +`GetSecrets` calls without `Unlock`, `Prompt`, collection creation or implicit +keyring-library unlock. Locked collections/items, including an item locking +between search and read, return an error. `plain` is the standard authenticated +local-bus session algorithm, not a plaintext-disk fallback. Explicit unlock +remains a separate user action; writes/removals retain their existing keyring +adapter and passive persistent-vault guard. + +Cloud-password fallback is **not implemented yet**. The current sync service also +needs authentication and a Wallet-protected local key; a sync password alone does +not bypass those dependencies. No plaintext fallback, silent cloud restore, +automatic migration, or false successful cloud save has been added. An opt-in +memory-only credential mode, encrypted cloud write/receipt handling and explicit +Wallet-return migration remain required before enabling that feature. + +Fcitx hotkey configuration does not auto-activate an absent IME. When the addon is +unavailable, desired settings can still be persisted; this does not mean those +hotkeys are registered. Automatic replay after a later service restart remains a +separate recovery concern. + +### Bounded compositor metadata probes + +Optional `hyprctl activewindow -j` and `swaymsg -r -t get_tree` probes have a +250 ms budget per command and a 1 MiB stdout cap. Missing tools, nonzero exits, +invalid UTF-8, excessive output and timeouts leave identity unavailable so the +existing fallback path can proceed. Timed-out probe process groups are killed +and the direct child is reaped; no desktop or IME process is restarted. +These limits do not claim to bound all other adapters (for example X11 calls). +Raw compositor output, including unrelated tree metadata, is never logged. + +### Shared desktop adapter reliability (independent of GUI toolkit) + +The same Rust adapters are used by the current graphical host, CLI and future +iced integration; these changes do not require maintaining Qt/GTK UI code. + +- Clipboard helper writes and PRIMARY reads have a two-second budget per tool + and a 4 MiB text/output cap. A stalled writer is terminated and reaped instead + of blocking the application indefinitely. Missing/failed tools can fall back; + a timeout after delivery has started returns `OutcomeUnknown` and does **not** + blindly try another clipboard API. Successful clipboard-owner daemons remain + alive normally. Definite empty Wayland PRIMARY does not fall through to a + potentially stale X11 PRIMARY selection. +- `clipboardFallback` in control status remains the ordered **candidate** list + for compatibility. New `adapters.clipboardBackendStatus` entries report + `backend` and `toolPresent`; executable/service presence is not proof of + permission, a working compositor connection, or successful clipboard delivery. + Human CLI status labels this `clipboardTools` rather than claiming readiness. + Missing optional `xclip`/`xsel` is reported honestly; nothing is auto-installed. +- HTTP invoke command `get_linux_runtime_status` returns the same runtime status + as `openless ctl status --json`. It grants no permissions, reads no document + text and contains no credential values. It is available for new native UI + integration without modifying the old graphical frontends. +- Fcitx hotkey signals must originate from the owner of `org.fcitx.Fcitx5` at + `/openless`. A private-bus regression verifies that other senders, wrong paths + and former owners are ignored. Owner replacement releases the held generation + and assigns the next press a fresh ID; it does not invent a new toggle press or + restart/switch the user's IME. This does not claim that every desktop adapter + can automatically reauthorize or reapply all settings after a service outage. +- FileChooser Portal errors are classified: absent/unsupported API may fall + back to `kdialog`/`zenity`; access denial, ambiguous method timeout and request + failure do not open a second dialog. Explicit cancellation remains distinct + from a timed-out request, which is closed and reported as failure. + +### Dictation (CLI chat excluded; help-me-write deferred) +```sh +openless ctl dictate # Press Enter/Space to finish, Esc/Ctrl+C to cancel; prints text to stdout +openless ctl dictate --copy # Also copy result to system clipboard +openless ctl dictate --raw # Raw ASR output without polish +openless ctl dictate --translate # Dictate with translation enabled +openless ctl dictate --note # Save directly as a quick note +openless ctl dictate --json --auto-start # Auto-start daemon & output JSON +openless ctl toggle # Toggle recording (ideal for WM/DE shortcuts) +``` + +### Headless Management (No GUI Required) +```sh +openless ctl styles # List output style packs (* = active) +openless ctl style # Switch active style pack +openless ctl mics # List microphones (* = selected, d = default) +openless ctl mic "" # Select microphone (`default` resets to system default) +openless ctl history --limit 10 # Print recent dictation history +``` + +### Terminal Shortcut & Systemd Integration +```sh +# Zsh (default Alt+V; override with --key '^G') +eval "$(openless ctl init zsh)" + +# Bash (default Alt+V) +eval "$(openless ctl init bash)" + +# Fish (default Alt+V) +openless ctl init fish | source + +# tmux (default Prefix + v) +openless ctl init tmux >> ~/.tmux.conf + +# Neovim (default Alt+V) +openless ctl init nvim > ~/.config/nvim/plugin/openless.lua + +# systemd --user service for headless auto-start +mkdir -p ~/.config/systemd/user +openless ctl init systemd > ~/.config/systemd/user/openless-headless.service +systemctl --user enable --now openless-headless.service +``` diff --git a/docs/linux-egui-command-event-baseline.json b/docs/linux-egui-command-event-baseline.json deleted file mode 100644 index 91f425593..000000000 --- a/docs/linux-egui-command-event-baseline.json +++ /dev/null @@ -1,422 +0,0 @@ -{ - "schemaVersion": "1.0", - "contractVersion": "2.0.0", - "observedAt": "2026-09-04", - "purpose": "M0 compatibility baseline for the Tauri adapter and the Linux egui host", - "sourceOfTruth": { - "commands": "openless-all/app/src-tauri/src/lib.rs app_invoke_handler_* macros", - "reactEvents": "openless-all/app/src/**/*.ts openless-all/app/src/**/*.tsx", - "tauriEvents": "openless-all/app/src-tauri/src/**/*.rs", - "coreContract": "openless-all/app/contract/backend-2.0.json" - }, - "platformDecision": { - "windows": "tauri", - "macos": "tauri", - "android": "tauri-mobile", - "linux": "egui", - "coreCallModel": "in-process typed Rust calls", - "workspaceIsolation": "app workspace contains the shared Core/DSP/capsule crates, native-capsule, and the external linux/egui and harmony/rust members; Tauri and backend compatibility tests use independent manifests and lockfiles" - }, - "commands": [ - "accept_pending_correction", - "add_correction_rule", - "add_vocab", - "app_check_update_with_channel", - "app_download_and_install_android_update", - "cancel_dictation", - "cancel_selection_polish_preview", - "cancel_selection_voice_intent_prompt", - "chat_panel_focus_keyboard", - "check_accessibility_permission", - "check_microphone_permission", - "check_network", - "clear_history", - "coding_agent_cancel_test", - "coding_agent_command_risk", - "coding_agent_detect", - "coding_agent_detect_cli", - "coding_agent_detect_opencode", - "coding_agent_list_opencode_models", - "coding_agent_run_test", - "confirm_selection_polish_preview", - "confirm_selection_voice_intent_prompt", - "confirm_selection_voice_preview", - "copy_text_to_clipboard", - "create_channel", - "create_style_pack_from_template", - "debug_read_cursor_context", - "deepseek_tts_start", - "deepseek_tts_stop", - "delete_channel", - "delete_channel_if_blank", - "delete_history_entry", - "delete_style_pack", - "dismiss_insert_fallback_card", - "dismiss_vocab_suggestions", - "export_audio_recording", - "export_error_log", - "export_style_pack_to_zip", - "fetch_latest_beta_release", - "foundry_local_asr_cancel_prepare", - "foundry_local_asr_catalog", - "foundry_local_asr_delete_model", - "foundry_local_asr_model_dir", - "foundry_local_asr_prepare", - "foundry_local_asr_release", - "foundry_local_asr_reveal_model_dir", - "foundry_local_asr_set_language_hint", - "foundry_local_asr_set_keep_loaded_secs", - "foundry_local_asr_set_model", - "foundry_local_asr_set_runtime_source", - "foundry_local_asr_status", - "get_activity_stats", - "get_android_accessibility_status", - "get_android_overlay_status", - "get_android_shizuku_status", - "get_credentials", - "get_default_style_system_prompts", - "get_hotkey_capability", - "get_hotkey_status", - "get_platform_capabilities", - "get_qa_hotkey_label", - "get_remote_input_status", - "get_startup_snapshot", - "get_selection_polish_preview", - "get_selection_voice_intent_prompt", - "get_selection_voice_preview", - "get_settings", - "get_update_channel", - "get_windows_ime_status", - "github_device_flow_cancel", - "github_device_flow_poll", - "github_device_flow_start", - "handle_window_hotkey_event", - "hide_android_overlay", - "import_style_pack_from_zip", - "inject_hotkey_click_for_dev", - "less_computer_approve", - "less_computer_submit_text", - "less_computer_sync", - "less_computer_window_dismiss", - "less_computer_window_open", - "list_channels", - "list_correction_rules", - "list_history", - "list_local_ips", - "list_microphone_devices", - "list_provider_descriptors", - "list_provider_models", - "list_style_packs", - "list_vocab", - "list_vocab_presets", - "local_asr_activate", - "local_asr_cancel_download", - "local_asr_delete_model", - "local_asr_download_model", - "local_asr_engine_status", - "local_asr_fetch_hf_card", - "local_asr_fetch_remote_info", - "local_asr_get_settings", - "local_asr_list_models", - "local_asr_model_dir", - "local_asr_preload", - "local_asr_release_engine", - "local_asr_reveal_model_dir", - "local_asr_reveal_models_root", - "local_asr_set_active_model", - "local_asr_set_keep_loaded_secs", - "local_asr_set_mirror", - "local_asr_set_models_base_dir", - "local_asr_storage_settings", - "local_asr_test_model", - "log_client_error", - "marketplace_auth_status", - "marketplace_delete", - "marketplace_detail", - "marketplace_download", - "marketplace_install", - "marketplace_like", - "marketplace_list", - "marketplace_logout", - "marketplace_my_likes", - "marketplace_my_packs", - "marketplace_upload", - "open_external_url", - "open_shizuku_app", - "open_system_settings", - "preview_style_pack_runtime", - "qa_cancel_turn", - "qa_set_edit_instruction_mode", - "qa_stop_recording", - "qa_submit_text", - "qa_toggle_recording", - "qa_window_dismiss", - "read_audio_recording", - "read_credential", - "record_channel_test", - "recover_android_accessibility", - "regenerate_remote_pin", - "reject_pending_correction", - "remove_correction_rule", - "remove_vocab", - "rename_channel", - "reorder_channels", - "repolish", - "report_insert_fallback_card_height", - "request_accessibility_permission", - "request_android_accessibility_permission", - "request_android_overlay_permission", - "request_android_shizuku_permission", - "request_microphone_permission", - "reset_builtin_style_pack", - "reset_accessibility_permission_and_restart_app", - "restart_app", - "retranscribe_recording", - "revert_selection_voice_preview", - "run_selection_polish_for_dev", - "save_style_pack", - "save_vocab_presets", - "set_active_asr_provider", - "set_active_llm_provider", - "set_active_omni_provider", - "set_active_style_pack", - "set_channel_enabled", - "set_channel_provider_type", - "set_combo_hotkey", - "set_correction_rule_enabled", - "set_credential", - "set_default_polish_mode", - "set_dictation_hotkey", - "set_open_app_hotkey", - "set_qa_hotkey", - "set_remote_locale", - "set_selection_polish_hotkey", - "set_settings", - "set_shortcut_recording_active", - "set_style_enabled", - "set_style_pack_enabled", - "set_style_pack_hotkeys", - "set_switch_style_hotkey", - "set_translation_hotkey", - "set_update_channel", - "set_vocab_enabled", - "sherpa_onnx_asr_cancel_download", - "sherpa_onnx_asr_cancel_prepare", - "sherpa_onnx_asr_catalog", - "sherpa_onnx_asr_delete_model", - "sherpa_onnx_asr_download_model", - "sherpa_onnx_asr_fetch_remote_info", - "sherpa_onnx_asr_model_dir", - "sherpa_onnx_asr_prepare", - "sherpa_onnx_asr_release", - "sherpa_onnx_asr_reveal_model_dir", - "sherpa_onnx_asr_set_language_hint", - "sherpa_onnx_asr_set_model", - "sherpa_onnx_asr_status", - "show_android_overlay", - "start_dictation", - "start_microphone_level_monitor", - "stop_dictation", - "stop_microphone_level_monitor", - "trigger_microphone_prompt", - "validate_combo_hotkey", - "validate_provider_credentials", - "validate_shortcut_binding" - ], - "commandOwnershipRules": { - "coreCandidates": [ - "dictation", - "settings", - "credentials-status", - "providers", - "history", - "vocabulary", - "style-packs", - "local-asr", - "selection", - "qa", - "remote-input", - "marketplace", - "coding-agent" - ], - "hostOnly": [ - "window/tray/focus/drag", - "clipboard and system settings launch", - "permission prompts", - "Android overlay/JNI/Shizuku", - "Tauri updater/dialog/shell/autostart/single-instance" - ], - "rule": "A command is a Tauri adapter until its use-case is implemented by openless-core; UI/window side effects never move into core." - }, - "events": [ - "android-update:progress", - "capsule:state", - "chat-panel:closing", - "chat-panel:shown", - "coding-agent:test", - "credentials:changed", - "fn-shortcut-pressed", - "foundry-local-asr-prepare-progress", - "insert:fallback", - "less-computer-glow:active", - "less-computer:event", - "local-asr-download-progress", - "local-asr-token", - "local-asr:engine-changed", - "microphone:devices-changed", - "microphone:level", - "prefs:changed", - "qa:dismiss", - "qa:level", - "qa:state", - "remote-input:error", - "remote-input:running", - "remote:result", - "selection-polish-preview:shown", - "selection-voice-intent:shown", - "sherpa-onnx-asr-download-progress", - "sherpa-onnx-asr-prepare-progress", - "tauri://resize", - "vocab:suggested", - "vocab:updated" - ], - "eventOwnership": { - "coreSemantic": { - "capsule:state": "map DictationStateChanged and DictationCompleted to the legacy capsule payload", - "coding-agent:test": "map CodingAgentTest typed stream events", - "credentials:changed": "map CredentialsChanged", - "foundry-local-asr-prepare-progress": "map LocalAsrPrepareProgress for the Foundry runtime", - "insert:fallback": "map InsertFallback; Tauri retains capsule-window presentation", - "less-computer:event": "map typed LessComputerEvent payloads", - "local-asr-download-progress": "map DownloadProgress after local-ASR adapter migration", - "local-asr-token": "map session-scoped TranscriptDelta", - "local-asr:engine-changed": "map LocalAsrEngineChanged", - "microphone:devices-changed": "map MicrophoneDevicesChanged as an invalidation signal", - "prefs:changed": "map PreferencesChanged", - "qa:level": "map session-scoped QaLevel while dropping the internal session id from the legacy payload", - "qa:state": "map typed QaState payloads", - "remote-input:error": "map RemoteInputFailed without a PIN or credential value", - "remote-input:running": "map RemoteInputStatusChanged without a PIN or credential value", - "remote:result": "retired global broadcast: remote-server subscribes directly to owner-scoped Core events; the H5 result message remains compatible", - "sherpa-onnx-asr-download-progress": "map LocalAsrDownloadProgress for the sherpa-onnx runtime", - "sherpa-onnx-asr-prepare-progress": "map LocalAsrPrepareProgress for the sherpa-onnx runtime", - "vocab:suggested": "map VocabularySuggestionsChanged", - "vocab:updated": "map VocabularyChanged as an invalidation signal" - }, - "tauriHost": { - "android-update:progress": "Android Tauri updater progress", - "chat-panel:closing": "WebView exit animation", - "chat-panel:shown": "WebView entry animation", - "fn-shortcut-pressed": "physical-host shortcut capture", - "less-computer-glow:active": "WebView GPU/presentation lifecycle", - "microphone:level": "host-owned settings-page microphone monitor", - "qa:dismiss": "Android/Tauri window dismissal", - "selection-polish-preview:shown": "Tauri window presentation", - "selection-voice-intent:shown": "Tauri window presentation", - "tauri://resize": "framework window event" - }, - "migrationRequired": {} - }, - "coreEventKinds": [ - "backend_started", - "backend_stopping", - "dictation_state_changed", - "transcript_delta", - "polish_delta", - "dictation_completed", - "recording_control_requested", - "selection_state_changed", - "selection_voice_state_changed", - "insert_fallback", - "preferences_changed", - "credentials_changed", - "history_changed", - "vocabulary_changed", - "style_packs_changed", - "download_progress", - "permission_changed", - "hotkey_status_changed", - "notification", - "coding_agent_test", - "less_computer_event", - "local_asr_prepare_progress", - "local_asr_download_progress", - "local_asr_engine_changed", - "microphone_devices_changed", - "qa_level", - "qa_state", - "selection_voice_level", - "remote_input_status_changed", - "remote_input_failed", - "vocabulary_suggestions_changed", - "cloud_sync_state_changed", - "cloud_sync_conflict_detected", - "cloud_sync_restore_completed" - ], - "domainInterfaces": [ - "ProviderApi", - "LocalAsrApi", - "SelectionApi", - "QaApi", - "RemoteInputApi", - "MarketplaceApi", - "CodingAgentApi", - "PlatformApi" - ], - "capabilities": { - "coreFields": [ - "platform", - "supportsDesktopHotkey", - "supportsTray", - "supportsOverlay", - "supportsImeInput", - "supportsLocalAsr", - "supportsAutoUpdate" - ], - "hostStatusFields": [ - "microphonePermission", - "accessibilityPermission", - "microphoneDevice", - "fcitx5Insertion", - "x11OrWayland", - "resourceLayout", - "singleInstance", - "updater" - ], - "linuxMatrix": [ - "x11", - "wayland", - "fcitx5-ready", - "fcitx5-missing", - "tray-available", - "tray-unavailable", - "microphone-granted", - "microphone-denied", - "microphone-no-device", - "updater-supported", - "updater-unsupported" - ] - }, - "compatibilityRules": { - "legacyTauriNames": "remain in the Tauri adapter only", - "coreSerialization": "serde camelCase DTOs and stable snake_case event tags", - "secretHandling": "credential values, authorization headers and PINs never appear in DTOs/events/errors/logs", - "sequence": "core event sequence starts at 1 and is strictly increasing per backend instance", - "laggedSubscription": "UI must resync from snapshot/query after a lagged receiver error", - "breakingChange": "increment contractVersion and document a migration", - "additiveChange": "new optional fields require a default" - }, - "counts": { - "tauriCommandsObserved": 200, - "legacyEventsObserved": 30, - "coreEventKindsDefined": 34 - }, - "implementationStatus": { - "sharedRepositories": "preferences, history, activity, vocabulary, correction, style packs", - "sharedCredentialContract": "CredentialDirectory owns provider channel mutation, ordering and active selection; Host stores metadata and SecretValue", - "complexDomains": "stable interfaces exist; Linux production injects QA, Remote Input, Selection, Provider, Model and Coding Agent adapters", - "linuxAdapters": "credentials/provider UI, resources, packaged Qwen runtime, fcitx5 insertion/hotkeys/selection preview, capabilities, cpal recording, QA, TLS Remote Input, host actions, single-instance intent broker and native runtime lifecycle", - "releaseGate": "Linux release requires successful artifacts and real Ubuntu audio, focus/input, install, upgrade, and rollback evidence" - }, - "status": "all 30 legacy events and 34 Core events are classified under contract 2.0.0; real-platform release evidence remains gated" -} diff --git a/docs/linux-frontends-and-system-api.md b/docs/linux-frontends-and-system-api.md new file mode 100644 index 000000000..8176a68fa --- /dev/null +++ b/docs/linux-frontends-and-system-api.md @@ -0,0 +1,106 @@ +# Linux frontends and system API audit + +## Runtime selection + +- `openless` or `openless --frontend=qt`: Qt6 WebEngine (default). +- `openless --frontend=gtk`: GTK4 + WebKitGTK (secondary). +- `openless --frontend=gtk --minimized`: explicit GTK background startup. +- `openless --help`: launcher options. + +Both shells render the same React build and start the same `openless-linux-web` +backend. There is one `openless.lock` and `openless-host.sock` per runtime directory. +Starting a second frontend raises the existing window rather than registering a +second tray/hotkey listener or creating concurrent recording/data writers. To +switch toolkit, quit the current instance first. Login entries use the default +launcher (Qt), not the last toolkit used for an explicit manual launch. + +GTK is built with GTK >= 4.12, WebKitGTK 6.0 and libsoup 3. GTK4 layer-shell is +optional at build time: without it, the main window works but overlays are disabled +and a warning is logged. On desktops without the layer-shell compositor protocol, +use Qt for the full overlay experience. Missing GTK runtime libraries do not affect +the default Qt executable; distro packages recommend the GTK dependencies. + +Build from `openless-all/app`: + +```sh +cmake -S ../linux/gtk -B target/linux-gtk-build -DCMAKE_BUILD_TYPE=Release +cmake --build target/linux-gtk-build --parallel +``` + +The shared native document-start bridge is `linux/shared/web_host_bridge.h`. +Clipboard ownership and capsule hit testing are view-local native operations, +not global backend state. Qt uses QClipboard plus Wayland input masks / X11 +ShapeInput; GTK uses GdkClipboard and GdkSurface input regions. Only actual capsule +controls and open menus accept input; transparent padding and the waveform do not. +The desktop content frame is square beneath native decorations; internal cards +retain their normal corners. + +## Recent system API audit + +### Implemented in the shared Linux HTTP dispatcher + +- Application style routing: get/refresh catalog, assign style, clear seen history. + Delegates to Core with validation and persistence; no duplicate routing store. +- Input application icons and activity icons: local desktop files/PNG icons only; + no desktop `Exec` execution, arbitrary network icon fetch, or whole-system scan. + Missing icons are an empty optional map, not a fake application identity. +- Native directory and ZIP open/save pickers: `kdialog`, then `zenity` when the + former is absent. User cancellation is null; missing tools/failures are errors. +- Recording export: validate session UUID and history membership, use quick-note + export directory only for quick notes, otherwise prompt for a destination; atomic + save rejects symlink destinations. +- External HTTP(S) URLs: shared validated desktop launcher, not an unhandled popup. +- Microphone prompt: real platform adapter request, not an unconditional success. +- Restart: event to the active shell; shell stops/reaps its backend, releases the + singleton lock, and starts a replacement. Ordinary close remains close-to-tray; + explicit tray quit bypasses that veto. +- Copy buttons (including History): native clipboard of the focused Qt/GTK view. + The fcitx5 clipboard cache is a best-effort side effect, not proof of a successful + system clipboard write. Older Qt shells can use their injected writeText shim. + +### Not complete: do not advertise as supported + +1. **New Ask host**: `ask_*` session/attachment/editor/context APIs still live + in the Tauri host. Linux package 236 restores `window=qa` as a shared React + view of the existing Core QA service, with text/voice questions and cancellation, + accessible from Tools. This is not the separate newer Ask entry, whose client + still imports Tauri directly. Full parity requires extracting Tauri session and + attachment coordination behind a framework-independent host service and adding + Linux HTTP/event and native-focus adapters. Do not map missing methods to null + or claim that the basic QA view implements attachments or context permissions. +2. **Automatic per-app style selection**: Linux now freezes an fcitx5 target before + Core's asynchronous startup and supplies `linux:` identity from that + same ticket for style routing and insertion. Program metadata never reads the + document; ticket-scoped cursor reads respect the opt-in flag and sensitive-app + gate. Previously seen apps can be explicitly assigned a style in the shared UI. + Catalog category auto-classification still needs Linux identifiers; macOS bundle + or Windows executable categories must not be guessed. An old running fcitx5 + addon lacks the new metadata methods until it is reloaded. +3. Ask browser-tab/window enumeration, scoped read consent, screenshots/file + attachments and voice editor ownership need Linux-specific implementations and + privacy checks. Persisting an enabled consent switch alone is not support. +4. Local ASR, voice activation, Windows caption/TSF and mobile-only APIs remain + platform-gated; adding same-name no-op methods would mislead the shared UI. + +## Verification + +- `node scripts/linux-multi-frontend.test.mjs`: default/explicit frontend selection, + invalid arguments, shared clipboard/input bridge, shared singleton contract. +- `playwright test e2e/linux-system-interactions.spec.ts + e2e/linux-surface-transparency.spec.ts`: actual frontend copy entry, local region + publisher, square desktop content frame, preserved card corners, transparent + auxiliary roots, capsule controls/empty cleanup (Chromium + WebKit). +- `cargo test -p openless-linux-web`: real Core routing state/validation, picker + cancellation semantics, capsule payload and voice-edit arming. +- Immutable frontend asset snapshot test: replace/delete installed lazy chunks after + backend startup and prove that the running process retains its complete old build. +- Production usage initialization/notification, metadata-only frozen target capture, + credential namespace and Linux multimodal recovery regressions are covered. +- Native isolated virtual KWin test: both shells loaded pages, wrote clipboard + bytes verified with `wl-paste`, applied native input regions, accepted secondary + toolkit handoff and exited through the tray event. This is not a full desktop + dictation/Ask test or proof of every compositor's click-through geometry. + +The existing AOCI index has unresolved governance drift and is not aligned with +these changes. No index semantics were synthesized from filenames and no forced +rescan was used to erase that drift. diff --git a/docs/linux-system-api-audit.md b/docs/linux-system-api-audit.md new file mode 100644 index 000000000..196cd6f41 --- /dev/null +++ b/docs/linux-system-api-audit.md @@ -0,0 +1,87 @@ +# Linux system interaction audit (package 236) + +## Completed in this pass + +- Conflict review includes bounded local/cloud style names, not only repeated + category labels. No credentials, prompts, icon payloads or history are exposed. +- Ordinary errors and warnings expire after eight seconds. In-flight work, + action-bearing notices and explicitly pinned messages retain their lifetime. +- Permissions displays an Fcitx5 plugin diagnostic instead of claiming desktop + global shortcut registration. Disk installation, existing daemon, loaded addon, + insertion, shortcuts and metadata support are separate facts. Refresh resolves + the unique existing D-Bus owner before introspection and never calls installation, + restart, activation, input-method selection, document reads or audio capture. + The legacy get_ime_backend_status endpoint now uses the same passive probe. +- Linux application-style routing is enabled in navigation (the backend alone + was not enough while the frontend still restricted it to macOS/Windows). +- Tools -> Ask opens the native QA window. The removed `window=qa` route now + renders a real shared-React view, not the main app. The existing Core QA service + owns text questions, voice recording, streamed state, cancellation and answers. + Both shells honor panelOpen even when its phase is idle. Keyboard focus is + on-demand; opening a view does not start the microphone. +- Correction Add button is label-sized and centered rather than stretching a dark + background across its grid cell. This fixes the demonstrated layout condition; + a remaining compositor-specific black artifact requires a screenshot/native test. +- Missing set_skip_auto_style_hotkey is wired through validated preferences, + settings effects, fcitx5 registration/signal and Core's session-bound toggle. +- Capsule auxiliary replay uses real pending corrections and processing dictations. + Linux caption tracing is disabled explicitly, instead of throwing at startup. + +## Shortcut chain + +The following have preference/registration -> addon signal -> shared backend action: + +| Shortcut | Action | +| --- | --- | +| Dictation | Core press/release/combined edge dispatch | +| Quick note | Start/stop note or redirect active capture | +| Ask | Toggle QA recording | +| Selection polish | Scoped selection polish / armed voice edit | +| Translation | Arm next capture or update the active one | +| Switch style | Previous style pack | +| Skip auto style | Toggle automatic/skip-auto for the active mutable session | +| Open app | Show main window | +| Individual style pack | Select stable pack ID | + +Standalone style/skip-auto modifiers fire on release only when not combined with +another key. Repeat suppression prevents holding a combination from toggling back +and forth. Fcitx5 can observe these only in clients connected to its input context; +this is not an unconditional compositor-wide global binding. The probe says so. +Less Computer/coding-agent shortcut actions remain unavailable: their execution +runtime is not implemented on Linux, and registering no-op shortcuts is not support. + +## Remaining boundaries + +An intermediate literal-call inventory found 267 frontend command names and 81 +absent dispatcher names before the final follow-up fixes. This is an investigation aid, not a semantic assertion that +81 Linux features were broken: it includes mobile/Windows-only commands, guarded +paths and frontend-native operations. The pass fills the relevant missing endpoints +above; it does not replace missing native engines with successful empty responses. + +- New standalone Ask host (`ask_*` entry settings, browser/file/screenshot context, + attachment storage, consent and session history) is still Tauri-coupled. The QA + view restored here is explicitly the existing shared Core QA service, not a claim + that all of the new Ask host is implemented. Unsupported context-consent UI is + hidden on Linux rather than issuing missing permission commands. +- Local ASR/download/Foundry/Sherpa and voice-activation engines remain gated. +- Full-field voice-edit session creation/finalization is not implemented; Linux's + existing selection-only view gates those controls rather than invoking them. +- Android audio/update/migration, Harmony exports, Windows caption/IME and SIWC + commands are not Linux capabilities. +- set_capsule_interactive_regions is fulfilled by the injected view-local native + bridge; it must not be replaced with a backend no-op. +- handle_window_hotkey_event is not a compositor-wide Linux fallback. Full shortcut + coverage outside Fcitx5 clients would require a separate desktop/portal adapter. +- Linux app-specific assignments use linux: identity. Catalog category + classification still needs explicit Linux identifiers. + +## Regression evidence + +- Private D-Bus test with an activatable Fcitx5 service proves that diagnostics do + not run its activation executable. Neither the test nor settings refresh touches + the user's input-method selection. +- Core label tests limit disclosure to 100 display characters of style names. +- Notification fake timers cover errors, warnings, saving, actions and pinned items. +- Chromium/WebKit fixtures cover distinct conflict names, automatic warning expiry, + actual QA view dispatch/render and correction-button geometry. QA fixture answers + are simulated; they do not verify a remote model service or billable voice request. diff --git a/docs/linux/api-gap-matrix.md b/docs/linux/api-gap-matrix.md new file mode 100644 index 000000000..f315c0714 --- /dev/null +++ b/docs/linux/api-gap-matrix.md @@ -0,0 +1,69 @@ +# Linux 后端 API Gap Matrix + +> 基准:当前工作树 `feat/linux-qt-host`,package revision 244。此表只记录 Linux Host/Web/CLI 的实际接口;Core API 与建议新增抽象分开。旧 PR #1446 只作为历史证据,不作为当前状态证明。 +> +> 状态:`Present+Tested` 已有源码和本地验证;`Present+Untested` 已有源码但缺少对应实机证据;`Partial` 有回退或仅部分路径;`Missing` 当前没有 Linux 实现;`Deferred` 有意不阻塞基础后端。 + +## 1. 对外入口 + +| API 家族 | 当前入口 | 实现位置 | 状态 | Linux 机制/限制 | +|---|---|---|---|---| +| CLI 控制 | `openless ctl dictate/start/stop/cancel/toggle` | `openless-all/linux/web/src/ctl.rs:862`、`handle_request` | Present+Tested | 私有 Unix socket;TTY 不抢占 shell | +| CLI JSON | `dictate --json`、错误 JSON | `linux/web/src/ctl.rs` | Present+Tested | stdout 为单个 JSON;诊断走 stderr/TTY 非 JSON 路径 | +| daemon/status | `daemon start/stop/status`、`ping/status` | `linux/web/src/ctl.rs` | Present+Tested | 用户级进程;无 root | +| 配置 | `config_get/set/call` | `linux/web/src/ctl.rs` | Present+Tested | `config_call` 只接受 dispatcher 白名单 | +| 图形/系统 dispatcher | `get_app_style_routing`、`pick_directory`、`open_external_url`、`export_audio_recording` 等 | `linux/web/src/system.rs:243-336` | Present+Tested | Portal → 桌面工具回退;URL 需方案校验 | +| SIWC | `siwc_status/models/action` | `linux/web/src/siwc_api.rs:6-46` | Present+Untested | 浏览器/账户动作依赖外部授权 | +| TTY UI | `tui`、终端录音 | `linux/web/src/tty_ui.rs`、`ctl.rs` | Present+Tested | 线性、安静、静默阈值停止 | + +## 2. Linux 原生适配 + +| 能力 | Rust 实现 | 底层接口 | 状态 | 备注 | +|---|---|---|---|---| +| 麦克风枚举/录音 | `host/src/audio.rs`、`capabilities.rs`、`web/src/main.rs` | CPAL,PipeWire/PulseAudio features | Present+Tested | ALSA-only 不应宣称已支持;热插拔/daemon 重启仍需补强 | +| 音频提示/VAD | `host/src/audio_cue.rs`、`terminal_vad.rs`、`audio_mute.rs` | CPAL/外部音频工具/静默检测 | Present+Tested | 首字、提示音、异常恢复需继续做故障注入 | +| Fcitx5 目标提交 | `host/src/fcitx5.rs`、`native_insertion.rs`、`scripts/linux-fcitx5-plugin/openless.cpp` | Fcitx5 D-Bus/Input Context | Present+Tested | Fcitx5 优先;提交结果仍需细分 Unknown/NotInserted | +| AT-SPI 文本访问 | `host/src/text_access.rs` | AT-SPI Accessible/Text/EditableText | Partial | 仅对已确认目标操作;不等于任意窗口通用注入 | +| 剪贴板回退 | `host/src/clipboard_fallback.rs`、`fcitx5.rs` | `wl-copy`/`wl-paste`、`xclip`/`xsel`、Fcitx5 | Partial+Tested | 依赖焦点/ownership;不保证富剪贴板完整恢复 | +| 选区/全字段 | `host/src/selection.rs`、`text_access.rs` | Fcitx5 surrounding/AT-SPI | Partial | selection-only 可用;完整 full-field Voice Edit 尚未完整接通 | +| 活动应用 | `host/src/active_window.rs` | Fcitx5、AT-SPI、Hyprland/Sway、X11 | Partial+Tested | Wayland 无通用全局活动窗口 API | +| 全局快捷键 | `host/src/global_shortcuts.rs`、`x11_hotkeys.rs`、`settings.rs` | GlobalShortcuts Portal、X11 XGrabKey、Fcitx5 | Present+Tested | Portal 授权已测;重连/撤销需继续增强 | +| 文件选择 | `host/src/portal_picker.rs`、`web/src/system.rs` | FileChooser Portal、kdialog、zenity | Present+Tested | headless 应使用显式路径 | +| 外部 URL/文件 | `host/src/desktop.rs` | `xdg-open`/桌面 launcher | Present+Tested | 只允许受控 URL scheme;禁止 shell 拼接 | +| Wallet | `host/src/credentials.rs`、`linux_access.rs`、`passive_secret.rs` | Secret Service/keyring | Present+Tested | 显式 unlock;不导出明文凭据 | +| 单实例/锁 | `web/src/host.rs`、`host/src/single_instance.rs` | XDG runtime/data、lock、Unix socket | Present+Tested | 多 UID 已验证;自定义目录保持严格校验 | +| 生命周期 | `web/src/lifecycle.rs`、`host.rs`、`ctl_transport.rs` | SIGTERM/SIGINT/SIGHUP、socket cleanup | Present+Tested | logind/锁屏/睡眠感知尚未完整 | + +## 3. Core 已有但 Linux 未完整接通 + +| 能力 | Core/前端证据 | Linux 状态 | 后续动作 | +|---|---|---|---| +| 新版 Ask Host | `openless-core` QA/Ask 相关 API、前端 Ask/附件调用 | Partial | 保留旧 `qa_*`;新版 session、attachment、context consent 单独设计 | +| full-field Voice Edit | Core voice-edit/session 相关接口 | Missing/Deferred | 先完成 target transaction/快照契约,再接 AT-SPI/IME | +| 本地 ASR | Foundry/Sherpa 相关 Core API | Deferred | 独立 feature gate;区分 installed/runtime_ready/loaded | +| Voice Activation | Core `voice_activation` 与 `stop_voice_activation` | Deferred | Linux engine/权限/锁屏策略未完成;不能返回成功 no-op | +| IBus | `scripts/linux-ibus-plugin` 与 GNOME 需求 | Missing/Partial | 合法 Engine 上下文闭环;不向 ibus-daemon 随意发送 CommitText | +| PipeWire 事件 | 当前仅以设备枚举/恢复路径为主 | Partial | Registry/Metadata 或等效订阅;设备消失时明确终止,不偷偷换麦克风 | +| logind/session | 当前无完整 login1 生命周期适配 | Missing | 锁屏、睡眠、用户切换、恢复后重探测 | +| HTTP 跨 UID 认证 | Unix socket 已有 UID 边界;图形 HTTP 另有来源校验 | Partial | 不把 loopback/origin 校验描述成 SO_PEERCRED;明确发布边界 | +| Wallet-independent cloud credentials | Core 云同步需要凭据 | Missing/Deferred | 先定义密钥模型、迁移和回滚;不落明文 | + +## 4. 明确不属于 Linux Host 当前交付 + +- iced 窗口、渲染、layer-shell、wgpu/winit 和窗口内 clipboard。 +- Windows/macOS 平台 API。 +- Qt/GTK/React 迁移期间的新产品功能;仍在发布链的旧入口只做必要安全修复。 +- RemoteDesktop/libei 作为中文输入主通道。 +- 无授权截图、浏览器 DOM、屏幕流或跨应用隐形监控。 + +## 5. 证据缺口 + +优先补充而非重复实现: + +1. PipeWire/WirePlumber 重启、蓝牙 profile、默认 source 变化; +2. Fcitx5 重启、Portal Session Closed、授权撤销后的恢复; +3. logind 锁屏/睡眠/用户切换; +4. GNOME+IBus 安装和能力探测; +5. AT-SPI 密码字段、焦点切换、Unicode/Emoji; +6. Zsh/Fish/Neovim 和纯 SSH/TTY; +7. HTTP 发布入口的真实绑定、来源检查和大小限制。 diff --git a/docs/linux/backend-compat-audit.md b/docs/linux/backend-compat-audit.md new file mode 100644 index 000000000..176a00102 --- /dev/null +++ b/docs/linux/backend-compat-audit.md @@ -0,0 +1,127 @@ +# Linux Backend Compatibility Audit + +> 审计基准:当前工作树 `feat/linux-qt-host`,HEAD `e90871b9` 及工作区改动;package revision 244 的已执行验证作为补充证据。旧 PR #1446 仅作为历史对照。 +> +> 本文是 W0 事实审计,不表示所有条目已经修复。没有实机证据的项目标为 `Present+Untested`、`Partial` 或 `Not Run`。 + +## 1. 当前控制流 + +```text +openless ctl / frontend + ↓ +Linux Web control socket / dispatcher + ↓ +openless-linux-host::LinuxHost / LinuxBackendRuntime + ↓ +openless-core::OpenLessBackend + ↓ +CPAL、Fcitx5、AT-SPI、Portal、Secret Service、X11/Wayland 工具 +``` + +关键入口: + +- `openless-all/linux/web/src/ctl.rs`:CLI、控制 socket 请求、TTY/JSON 输出、配置命令白名单。 +- `openless-all/linux/web/src/ctl_transport.rs`:Unix socket 传输和生命周期。 +- `openless-all/linux/web/src/host.rs`:runtime socket、数据目录锁、单实例边界。 +- `openless-all/linux/web/src/system.rs`:系统 dispatcher 和应用/文件/录音操作。 +- `openless-all/linux/web/src/main.rs`:Web/headless host 启动、Core/Host 组装。 +- `openless-all/linux/host/src/backend.rs`、`lib.rs`:Linux Host runtime。 +- `openless-all/app/crates/openless-core/src/api.rs`:录音、听写、QA、设置和业务状态机。 + +## 2. 已确认完成 + +| 项目 | 当前证据 | 状态 | +|---|---|---| +| CLI start/stop/cancel/toggle/dictate | `linux/web/src/ctl.rs` 的 `handle_request` 和 `run_cli` | Present+Tested | +| `--json` 错误输出 | `linux/web/src/ctl.rs` | Present+Tested | +| Unix socket、私有 runtime、数据锁 | `web/src/host.rs`、`ctl_transport.rs` | Present+Tested | +| 多 UID 隔离 | 本地 multi-UID 实测记录 | Present+Tested | +| Portal GlobalShortcuts 基础授权 | enable/status/disable 实测记录 | Present+Tested | +| PipeWire 虚拟麦克风真实 ASR | package 244 验收记录 | Present+Tested | +| 空音频安全失败 | `emptyTranscript` 实测记录 | Present+Tested | +| Fcitx5 插件诊断、文本提交和热键 | `host/src/fcitx5.rs`、`global_shortcuts.rs` | Present+Tested/Partial | +| Portal/kdialog/zenity 文件选择 | `host/src/portal_picker.rs`、`web/src/system.rs` | Present+Tested | +| Secret Service status/unlock/read/write | `host/src/credentials.rs`、`linux_access.rs` | Present+Tested | +| 应用风格路由和应用图标 | `web/src/system.rs`、Core app style routing | Present+Tested | + +## 3. 需要优先补证据或修复的项目 + +### A1:输入提交结果仍需明确区分 Unknown + +- 位置:`openless-all/linux/host/src/fcitx5.rs`、`native_insertion.rs`、Core dictation completion path。 +- 风险:D-Bus 超时或连接断开时,目标应用可能已经提交文本;如果直接转 clipboard 或重试,可能造成重复文本或写入新焦点。 +- 现状:存在 Fcitx5/AT-SPI/clipboard 回退链,但需要核对每个 commit failure 的语义。 +- 处理:形成 `Inserted / CopiedFallback / NotInserted / OutcomeUnknown` 的稳定 DTO 或等效 Core error;Unknown 禁止自动重试。 +- 验证:提交后断开 D-Bus、切换焦点、重复 stop/cancel、目标进程退出。 +- 状态:`Partial`。 + +### A2:敏感上下文读取门禁 + +- 位置:`openless-all/linux/host/src/host_context.rs`、`text_access.rs`、Fcitx5 插件 `surroundingTextFor()`。 +- 风险:程序名过滤不能替代 Password/Sensitive input-context 标志;读取后再过滤仍可能把敏感内容带入进程内存和日志。 +- 处理:在调用 reader/AT-SPI read 前拒绝敏感目标;日志只保留状态、长度、脱敏 app id。 +- 验证:密码框、浏览器登录字段、焦点切换和取消观察任务,证明敏感场景不调用读取接口。 +- 状态:`Partial/需源码逐行复核`。 + +### A3:PipeWire 生命周期不是完整事件订阅 + +- 位置:`openless-all/linux/host/src/audio.rs`、`capabilities.rs`、`audio_mute.rs`、`linux/web/src/main.rs`。 +- 风险:设备枚举成功不代表可以处理蓝牙 profile、虚拟节点、默认 source 改变和 PipeWire 重启。 +- 处理:先复用当前 CPAL/Pulse 路径;必要时增加 registry/metadata 订阅或低频 reconciler。正在录音时设备消失必须明确失败,不自动换另一支麦克风。 +- 验证:虚拟源、蓝牙、默认源切换、PipeWire/WirePlumber 重启、USB 拔插。 +- 状态:`Partial`。 + +### A4:Fcitx5/GlobalShortcuts 重连 + +- 位置:`openless-all/linux/host/src/fcitx5.rs`、`global_shortcuts.rs`、`hotkeys.rs`、`web/src/hotkeys.rs`。 +- 风险:D-Bus owner 变化、插件重载或 Portal Session Closed 后,监听可能退出或状态变为假成功。 +- 处理:定义 `Disconnected → Reconnecting → Ready`;幂等恢复;授权撤销返回 `PermissionRequired`,不得自动替用户启用输入法或重启无关服务。 +- 验证:`fcitx5 -r`、Portal 后端重启、Session Closed、长按期间断线。 +- 状态:`Partial`。 + +### A5:logind/锁屏/睡眠 + +- 位置:当前 Host 尚未形成完整 login1 生命周期模块。 +- 风险:锁屏、睡眠、用户切换时,麦克风和输入 target 可能继续存活。 +- 处理:增加可选 login1 adapter;无 user/system bus 时返回 `Unavailable`,不阻塞普通 CLI;挂起前停止采集并使 target ticket 失效,恢复后重新探测。 +- 验证:锁屏/解锁、Suspend/Resume、fast user switching、SSH/无 DBus。 +- 状态:`Missing`。 + +### A6:IBus 生产闭环 + +- 位置:`openless-all/scripts/linux-ibus-plugin/`;当前生产 Host 路径主要在 `linux/host/src/fcitx5.rs`。 +- 风险:不能通过向 ibus-daemon 任意发送 `CommitText` 宣称支持 GNOME IBus。 +- 处理:合法 IBus Engine 的 FocusIn/Out、SetSurroundingText、CommitText 和可选安装注册;不得切换用户默认输入法。 +- 验证:GNOME Wayland + IBus 安装、启用 Engine、中文听写和选区。 +- 状态:`Missing/Deferred`,优先级 P1。 + +### A7:HTTP 与 Unix socket 的安全边界必须分别描述 + +- 位置:`openless-all/linux/web/src/request_origin.rs`、`main.rs`、`host.rs`、`ctl_transport.rs`。 +- 风险:loopback、Origin 和 Fetch metadata 不是跨 UID 的 `SO_PEERCRED`。旧 PR 的无鉴权结论也不能直接套用当前实现。 +- 处理:W0 记录实际绑定地址、HTTP 路由、请求大小/连接超时、发布入口;CLI 继续使用私有 Unix socket。旧 HTTP 不新增产品 API。 +- 验证:不同 UID、恶意 Origin、超长 body、断开连接、无 GUI/headless。 +- 状态:`Partial/需发布入口复核`。 + +## 4. 已有回退,不应误报为“完整原生支持” + +| 能力 | 当前真实情况 | +|---|---| +| 文本插入 | Fcitx5 → AT-SPI → clipboard → stdout;不是任意 Wayland 应用通用注入 | +| 全局热键 | Portal → X11 → Fcitx5;Portal/Fcitx5 受桌面和输入上下文限制 | +| 活动窗口 | Fcitx5/AT-SPI/Hyprland/Sway/X11;GNOME Wayland 没有通用全局活动窗口 API | +| Wayland clipboard | `wl-copy`/`wl-paste` 工具回退;不是独立 native clipboard manager | +| Voice Edit | 当前以 selection-only 为主;full-field transaction 尚未完整实现 | +| Ask | 旧 QA 能力可用;新版 Ask context/attachment/consent 尚未完整接通 | +| 本地 ASR | Core 有相关方向,但 Linux 本地模型运行时未形成发布能力 | +| Voice Activation | Core 有状态机方向,但 Linux 常驻监听引擎未完成 | + +## 5. W0 后的执行顺序 + +1. 先完成 A1/A2 的源码逐行复核和最小安全测试,不改变已验证 CLI 行为。 +2. 补 A3 音频设备生命周期和 A4 Fcitx5/Portal 重连。 +3. 增加可选 logind adapter,并保持无 DBus 的 CLI 可用。 +4. 评估 IBus Engine;只有有真实 GNOME 需求时才引入可选安装/依赖。 +5. 再处理 full-field Voice Edit、Ask Host、本地 ASR、Voice Activation 等独立工作包。 + +所有未执行的桌面测试保持 `Not Run`;不能用编译成功替代实机兼容性证据。 diff --git a/openless-all/README.md b/openless-all/README.md index 008ced248..596dd5d3d 100644 --- a/openless-all/README.md +++ b/openless-all/README.md @@ -68,6 +68,19 @@ bash ../linux/scripts/verify-linux-egui-packages.sh > Linux CI and automated release workflows remain paused while device/packaging acceptance is pending. Local scripts still produce verified `.deb` / `.rpm` packages and the Fcitx5 addon (AppImage is retired). See [`RELEASING.md`](../RELEASING.md) before distributing Linux packages. +### Linux local speech recognition + +The Linux web host and headless daemon enable Sherpa-ONNX CPU inference by default on x86-64 and AArch64. Preparing the engine or activating a Sherpa model installs pinned, SHA-256-verified Sherpa-ONNX 1.13.8 and ONNX Runtime libraries on demand. Startup does not download or link those libraries, and there is no CUDA, Candle, whisper.cpp, or Tauri dependency. Whisper models in the Sherpa catalog use ONNX; Foundry and Apple/MLX engines remain platform-specific. + +In the UI, use **Local Models** and add a **Sherpa-ONNX** ASR channel in Traditional mode. In a headless daemon, the same command arguments and results are available through `openless ctl config call`, for example: + +```bash +printf '{}\n' | openless ctl config call sherpa_onnx_asr_catalog +printf '{}\n' | openless ctl config call sherpa_engine_prepare +``` + +Build `openless-linux-web` with `--no-default-features` to omit native local inference and the X11 clipboard adapter, or enable `x11-clipboard` separately. + ## macOS Build Use the repository build script rather than invoking `tauri build` directly: diff --git a/openless-all/android/rust/src/asr/README.md b/openless-all/android/rust/src/asr/README.md index 594a7543e..ce5689659 100644 --- a/openless-all/android/rust/src/asr/README.md +++ b/openless-all/android/rust/src/asr/README.md @@ -34,7 +34,7 @@ ModelRuntimeAdapter supports inspection/status, prepare/progress/cancellation, p The extracted Rust remains under the repository's existing root GNU AGPL v3 license, with source attribution at each module header; this port grants no different license. Model weights and Sherpa/ONNX runtime dependencies retain their separate upstream license requirements and existing Core catalog notices. -The test WAV is a byte-identical copy of `app/src-tauri/assets/local-asr-test.wav` (120632 bytes, SHA-256 `9d10e65c03be8cb3c4236f3f33fd6a76d9d341093aaec9e4423c132b44e09a38`). Its most recent source-file commit is `f3127421774e87c1cb7aab142ccaac339751d48e`. No separate asset license notice was found alongside that existing fixture; this port preserves its repository provenance without asserting newly obtained third-party recording rights. +The test WAV is a byte-identical copy of `app/shared/local-asr/local-asr-test.wav` (120632 bytes, SHA-256 `9d10e65c03be8cb3c4236f3f33fd6a76d9d341093aaec9e4423c132b44e09a38`). Its most recent source-file commit is `f3127421774e87c1cb7aab142ccaac339751d48e`. No separate asset license notice was found alongside that existing fixture; this port preserves its repository provenance without asserting newly obtained third-party recording rights. ## Validation boundary diff --git a/openless-all/app/Cargo.lock b/openless-all/app/Cargo.lock index ede27a80b..8d13355b2 100644 --- a/openless-all/app/Cargo.lock +++ b/openless-all/app/Cargo.lock @@ -11,105 +11,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "accesskit_atspi_common" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4" -dependencies = [ - "accesskit", - "accesskit_consumer", - "atspi-common", - "phf 0.14.0", - "serde", - "zvariant", -] - -[[package]] -name = "accesskit_consumer" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" -dependencies = [ - "accesskit", - "hashbrown 0.17.1", -] - -[[package]] -name = "accesskit_ios" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.17.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", - "objc2-ui-kit 0.2.2", -] - -[[package]] -name = "accesskit_macos" -version = "0.27.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.17.1", - "objc2 0.5.3", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "accesskit_unix" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d" -dependencies = [ - "accesskit", - "accesskit_atspi_common", - "async-channel", - "async-executor", - "async-task", - "atspi", - "futures-lite", - "futures-util", - "serde", - "zbus", -] - -[[package]] -name = "accesskit_windows" -version = "0.35.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.17.1", - "static_assertions", - "windows 0.62.2", - "windows-core 0.62.2", -] - -[[package]] -name = "accesskit_winit" -version = "0.34.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" -dependencies = [ - "accesskit", - "accesskit_ios", - "accesskit_macos", - "accesskit_unix", - "accesskit_windows", - "raw-window-handle", - "winit", -] - [[package]] name = "adler2" version = "2.0.1" @@ -175,12 +76,6 @@ dependencies = [ "alloc-no-stdlib", ] -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - [[package]] name = "alsa" version = "0.11.0" @@ -334,15 +229,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" -[[package]] -name = "ash" -version = "0.38.0+1.3.281" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" -dependencies = [ - "libloading", -] - [[package]] name = "asn1-rs" version = "0.7.2" @@ -519,43 +405,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "atspi" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" -dependencies = [ - "atspi-common", - "atspi-proxies", -] - -[[package]] -name = "atspi-common" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" -dependencies = [ - "enumflags2", - "serde", - "static_assertions", - "zbus", - "zbus-lockstep", - "zbus-lockstep-macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "atspi-proxies" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" -dependencies = [ - "atspi-common", - "serde", - "zbus", -] - [[package]] name = "autocfg" version = "1.5.1" @@ -1475,8 +1324,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", - "block2 0.6.2", - "libc", "objc2 0.6.5", ] @@ -1615,7 +1462,6 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "pollster 1.0.1", "profiling", "raw-window-handle", "send_wrapper", @@ -1623,7 +1469,6 @@ dependencies = [ "wasm-bindgen", "web-sys", "web-time", - "wgpu", "windows-sys 0.61.2", "winit", ] @@ -1674,7 +1519,6 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4e449f4c4a2a60c7ccb4ba7fa4078417bfe1f9ddc03b5e05ce75748e33a70de" dependencies = [ - "accesskit_winit", "arboard", "block2 0.6.2", "bytemuck", @@ -1912,7 +1756,7 @@ dependencies = [ "anyhow", "ferrous-opencc-compiler", "fst", - "phf 0.13.1", + "phf", "phf_codegen", "rkyv", "serde", @@ -2014,27 +1858,6 @@ dependencies = [ "bytemuck", ] -[[package]] -name = "fontconfig-parser" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" -dependencies = [ - "roxmltree 0.20.0", -] - -[[package]] -name = "fontdb" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" -dependencies = [ - "fontconfig-parser", - "log", - "slotmap", - "tinyvec", -] - [[package]] name = "foreign-types" version = "0.5.0" @@ -2380,19 +2203,6 @@ dependencies = [ "gl_generator", ] -[[package]] -name = "gpu-allocator" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" -dependencies = [ - "ash", - "hashbrown 0.16.1", - "log", - "presser", - "thiserror 2.0.21", -] - [[package]] name = "group" version = "0.13.0" @@ -2465,17 +2275,6 @@ dependencies = [ "foldhash 0.1.5", ] -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.2.0", -] - [[package]] name = "hashbrown" version = "0.17.1" @@ -3358,7 +3157,6 @@ dependencies = [ "num-traits", "once_cell", "rustc-hash 1.1.0", - "spirv", "thiserror 2.0.21", "unicode-ident", ] @@ -3657,7 +3455,7 @@ dependencies = [ "objc2-core-data", "objc2-core-image", "objc2-foundation 0.2.2", - "objc2-quartz-core 0.2.2", + "objc2-quartz-core", ] [[package]] @@ -3794,7 +3592,7 @@ dependencies = [ "block2 0.5.1", "objc2 0.5.3", "objc2-foundation 0.2.2", - "objc2-metal 0.2.2", + "objc2-metal", ] [[package]] @@ -3876,17 +3674,6 @@ dependencies = [ "objc2-foundation 0.2.2", ] -[[package]] -name = "objc2-metal" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", - "objc2-foundation 0.3.2", -] - [[package]] name = "objc2-quartz-core" version = "0.2.2" @@ -3897,20 +3684,7 @@ dependencies = [ "block2 0.5.1", "objc2 0.5.3", "objc2-foundation 0.2.2", - "objc2-metal 0.2.2", -] - -[[package]] -name = "objc2-quartz-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-metal 0.3.2", + "objc2-metal", ] [[package]] @@ -3938,7 +3712,7 @@ dependencies = [ "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", - "objc2-quartz-core 0.2.2", + "objc2-quartz-core", "objc2-symbols", "objc2-uniform-type-identifiers", "objc2-user-notifications", @@ -4040,7 +3814,7 @@ dependencies = [ "regex", "reqwest", "rhai", - "roxmltree 0.21.1", + "roxmltree", "rsa", "serde", "serde_json", @@ -4069,50 +3843,62 @@ dependencies = [ ] [[package]] -name = "openless-linux-egui" +name = "openless-linux-host" version = "0.1.0" dependencies = [ + "anyhow", "axum", "base64 0.23.1", + "bzip2", "chrono", "cpal", "dbus", - "eframe", - "egui", "fs2", "futures-util", "hyper-util", "image", "keyring", "libc", + "libloading", "local-ip-address", "log", "openless-core", - "raw-window-handle", + "parking_lot", "rcgen", "reqwest", - "resvg", - "rfd", - "roxmltree 0.21.1", + "roxmltree", "rustls", - "semver", "serde", "serde_json", "sha2 0.11.1", "simplelog", + "tar", "tempfile", "time", "tokio", "tokio-rustls", - "unicode-segmentation", "uuid", "wayland-client", "wayland-protocols-wlr", - "wgpu", "x11rb 0.14.0", "x509-parser", ] +[[package]] +name = "openless-linux-web" +version = "0.1.0" +dependencies = [ + "futures-util", + "libc", + "log", + "openless-core", + "openless-linux-host", + "serde", + "serde_json", + "tokio", + "uuid", +] + [[package]] name = "openless-native-capsule" version = "0.1.0" @@ -4139,15 +3925,6 @@ dependencies = [ "libredox", ] -[[package]] -name = "ordered-float" -version = "5.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" -dependencies = [ - "num-traits", -] - [[package]] name = "ordered-stream" version = "0.2.0" @@ -4307,19 +4084,8 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros 0.13.1", - "phf_shared 0.13.1", - "serde", -] - -[[package]] -name = "phf" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" -dependencies = [ - "phf_macros 0.14.0", - "phf_shared 0.14.0", + "phf_macros", + "phf_shared", "serde", ] @@ -4329,8 +4095,8 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", + "phf_generator", + "phf_shared", ] [[package]] @@ -4340,17 +4106,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared 0.13.1", -] - -[[package]] -name = "phf_generator" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" -dependencies = [ - "fastrand", - "phf_shared 0.14.0", + "phf_shared", ] [[package]] @@ -4359,21 +4115,8 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "phf_macros" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" -dependencies = [ - "phf_generator 0.14.0", - "phf_shared 0.14.0", + "phf_generator", + "phf_shared", "proc-macro2", "quote", "syn 2.0.119", @@ -4388,15 +4131,6 @@ dependencies = [ "siphasher", ] -[[package]] -name = "phf_shared" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" -dependencies = [ - "siphasher", -] - [[package]] name = "pico-args" version = "0.5.0" @@ -4525,18 +4259,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "pollster" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" - -[[package]] -name = "pollster" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" - [[package]] name = "poly1305" version = "0.9.1" @@ -4601,12 +4323,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "presser" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" - [[package]] name = "primal-check" version = "0.3.4" @@ -4889,18 +4605,6 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" -[[package]] -name = "raw-window-metal" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" -dependencies = [ - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", -] - [[package]] name = "rcgen" version = "0.14.10" @@ -5073,30 +4777,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "rfd" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" -dependencies = [ - "block2 0.6.2", - "dispatch2", - "js-sys", - "libc", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "percent-encoding", - "pollster 0.4.0", - "raw-window-handle", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "windows-sys 0.61.2", -] - [[package]] name = "rgb" version = "0.8.53" @@ -5178,12 +4858,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - [[package]] name = "roxmltree" version = "0.21.1" @@ -5717,15 +5391,6 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -[[package]] -name = "spirv" -version = "0.4.0+sdk-1.4.341.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" -dependencies = [ - "bitflags 2.13.2", -] - [[package]] name = "spki" version = "0.7.3" @@ -6068,9 +5733,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -6404,24 +6069,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" -[[package]] -name = "unicode-script" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" - [[package]] name = "unicode-segmentation" version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" -[[package]] -name = "unicode-vo" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" - [[package]] name = "unicode-width" version = "0.2.2" @@ -6463,25 +6116,17 @@ version = "0.48.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" dependencies = [ - "base64 0.23.1", "data-url", - "fontdb", - "harfrust", "imagesize", "kurbo", "log", "pico-args", - "roxmltree 0.21.1", + "roxmltree", "simplecss", "siphasher", - "skrifa", "strict-num", "svgtypes", "tiny-skia-path", - "unicode-bidi", - "unicode-script", - "unicode-vo", - "xmlwriter", ] [[package]] @@ -6878,34 +6523,22 @@ version = "30.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" dependencies = [ - "android_system_properties", - "arrayvec", - "ash", "bitflags 2.13.2", - "bytemuck", "cfg-if", "cfg_aliases", - "gpu-allocator", "hashbrown 0.17.1", - "libc", "libloading", "log", "naga", "naga-types", - "ordered-float", - "parking_lot", "portable-atomic", "portable-atomic-util", - "profiling", "raw-window-handle", - "raw-window-metal", "renderdoc-sys", - "smallvec", "static_assertions", "thiserror 2.0.21", "wgpu-naga-bridge", "wgpu-types", - "windows 0.62.2", ] [[package]] @@ -7452,12 +7085,6 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" -[[package]] -name = "xmlwriter" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" - [[package]] name = "yasna" version = "0.6.0" @@ -7526,30 +7153,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus-lockstep" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" -dependencies = [ - "zbus_xml", - "zvariant", -] - -[[package]] -name = "zbus-lockstep-macros" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "zbus-lockstep", - "zbus_xml", - "zvariant", -] - [[package]] name = "zbus-secret-service-keyring-store" version = "1.0.1" @@ -7587,18 +7190,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus_xml" -version = "5.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" -dependencies = [ - "serde", - "winnow", - "zbus_names", - "zvariant", -] - [[package]] name = "zcheapstr" version = "1.1.0" diff --git a/openless-all/app/Cargo.toml b/openless-all/app/Cargo.toml index 0ab2b4a1b..ce2949507 100644 --- a/openless-all/app/Cargo.toml +++ b/openless-all/app/Cargo.toml @@ -4,10 +4,11 @@ members = [ "crates/openless-core", "crates/micyou-dsp", "crates/micyou-infer", - "../linux/egui", "crates/openless-capsule", "native-capsule", + "../linux/host", "../harmony/rust", + "../linux/web", ] exclude = [ "src-tauri", diff --git a/openless-all/app/assets/remote-input/app.js b/openless-all/app/assets/remote-input/app.js index a01c3cf69..38b9f09ff 100644 --- a/openless-all/app/assets/remote-input/app.js +++ b/openless-all/app/assets/remote-input/app.js @@ -288,7 +288,7 @@ recovering: 'El ordenador está procesando tu última grabación…', interrupted: 'Grabación interrumpida. El ordenador procesa el audio ya recibido…', offlineRecording: - 'Conexión perdida; el ordenador seguirá procesando la grabación recibida. Reconecta para ver el resultado.', + 'Conexión perdida; el ordenador sLinux hostrá procesando la grabación recibida. Reconecta para ver el resultado.', recovered: 'Última transcripción recuperada', recoveryRetry: 'La transcripción falló. La grabación está guardada en el historial del ordenador y puede reintentarse.', diff --git a/openless-all/app/contract/backend-2.0.json b/openless-all/app/contract/backend-2.0.json index b10292083..3ee750932 100644 --- a/openless-all/app/contract/backend-2.0.json +++ b/openless-all/app/contract/backend-2.0.json @@ -133,6 +133,9 @@ "running": true, "processingDictations": [], "dictation": { + "skipAutoStyle": false, + "stylePackId": null, + "stylePackName": null, "phase": "idle", "sessionId": null, "elapsedMs": 0, @@ -220,7 +223,10 @@ "level": 0.0, "message": null, "translationActive": false, - "recordingReady": false + "recordingReady": false, + "skipAutoStyle": false, + "stylePackId": null, + "stylePackName": null } } }, @@ -377,7 +383,12 @@ "localGeneration": "1", "counts": {}, "deviceSettingsToReview": [], - "conflicts": [] + "conflicts": [], + "localDeviceOs": null, + "localUpdatedAt": null, + "recommendedMode": null, + "remoteDeviceOs": null, + "remoteUpdatedAt": null } } } @@ -586,6 +597,9 @@ "running": true, "processingDictations": [], "dictation": { + "skipAutoStyle": false, + "stylePackId": null, + "stylePackName": null, "phase": "idle", "sessionId": null, "elapsedMs": 0, diff --git a/openless-all/app/crates/micyou-dsp/UPSTREAM.md b/openless-all/app/crates/micyou-dsp/UPSTREAM.md index 07cbd15e6..1bea98567 100644 --- a/openless-all/app/crates/micyou-dsp/UPSTREAM.md +++ b/openless-all/app/crates/micyou-dsp/UPSTREAM.md @@ -96,7 +96,7 @@ still require review and a deliberate patch/dependency update. ## Shared performance changes (2026-10-22) -All hosts that use `AudioProcessor` (including desktop Tauri and Linux egui) +All hosts that use `AudioProcessor` (including desktop Tauri and Linux host) reuse mono, frame and resampled output scratch buffers. Rational resampling phases are precomputed once per stream, capped at 1024 phases; unusual clocks fall back to the original kernel calculation. The output duration and filter @@ -137,13 +137,13 @@ The comparator fails on any PCM difference or duration/case-set mismatch; and a truncated output cannot pass. The probe sources must be identical in both builds. Original baseline sources/models must remain unchanged. -Desktop Tauri and Linux egui use the shared processor directly. Harmony uses +Desktop Tauri and Linux host use the shared processor directly. Harmony uses the external PCM recorder, which reuses conversion scratch per session. The iOS native recorder now optionally applies the same processor with session-frozen settings and a reused input buffer; the stop/drain barrier flushes its tail before finishing the archive. Enhancement remains off by default. Its native Swift settings page persists the same software DSP -controls as egui and Tauri, with writes blocked while a capture is active. +controls as the Linux host and Tauri, with writes blocked while a capture is active. Native iOS conversion uses a separate Swift AVAudioConverter worker; its output scratch is now actor-owned and reused with exact output capacities and a two-entry bound. diff --git a/openless-all/app/crates/openless-core/src/api.rs b/openless-all/app/crates/openless-core/src/api.rs index 6bef819cc..53ddbc5c1 100644 --- a/openless-all/app/crates/openless-core/src/api.rs +++ b/openless-all/app/crates/openless-core/src/api.rs @@ -2091,6 +2091,8 @@ struct ActiveTextInsertion { #[derive(Default)] struct ActiveTextInsertionState { stream: crate::streaming_insert::StreamingInsertState, + /// A native write may have landed. No reconciliation or clipboard fallback is safe. + uncertain_write: Option, scheduled: bool, /// Newest transcript partial not yet sent as a composition update. partial_pending: Option, @@ -2293,7 +2295,12 @@ impl ActiveTextInsertion { "host inserted only {written}/{expected} characters" )); } - Err(error) => state.stream.failed = Some(error.to_string()), + Err(error) => { + state.stream.failed = Some(error.to_string()); + if error.code == BackendErrorCode::OutcomeUnknown { + state.uncertain_write = Some(error); + } + } } if state.stream.failed.is_some() || state.stream.pending.is_empty() { state.scheduled = false; @@ -2362,6 +2369,9 @@ impl ActiveTextInsertion { log::warn!("[insertion] composition update stopped chars={chars}: {error}"); let mut state = self.state.lock().expect("text insertion lock poisoned"); state.partial_failed = true; + if error.code == BackendErrorCode::OutcomeUnknown { + state.uncertain_write = Some(error); + } state.partial_pending = None; state.partial_running = false; self.drained.notify_waiters(); @@ -2455,40 +2465,50 @@ impl ActiveTextInsertion { } async fn finish_committed(&self, final_text: String) -> Result { - let reconciliation = self - .state - .lock() - .expect("text insertion lock poisoned") - .stream - .reconcile_final(&final_text); + let (uncertain_write, reconciliation) = { + let state = self.state.lock().expect("text insertion lock poisoned"); + (state.uncertain_write.clone(), state.stream.reconcile_final(&final_text)) + }; + if let Some(error) = uncertain_write { + // Cancel only releases the native session; never send text or copy here. + let _ = self.platform.cancel().await; + return Err(error); + } use crate::streaming_insert::FinalReconciliation; match reconciliation { FinalReconciliation::InsertFinal(text) => self.finish_platform(text).await, FinalReconciliation::WriteTail(tail) => { let expected = tail.chars().count(); let written = self.write_text(tail, "tail").await; + if let Err(error) = &written { + if error.code == BackendErrorCode::OutcomeUnknown { + let _ = self.platform.cancel().await; + return Err(error.clone()); + } + } let complete = matches!(written, Ok(result) if result.written_chars >= expected); if complete { - if self.save_streamed_text_to_clipboard { - if let Err(error) = self.platform.copy(final_text).await { - log::warn!("failed to preserve streamed text on clipboard: {error}"); - } - } - self.finish_platform(String::new()).await + self.finish_streamed(final_text).await } else { self.finish_with_fallback(final_text).await } } - FinalReconciliation::Complete => { - if self.save_streamed_text_to_clipboard { - if let Err(error) = self.platform.copy(final_text).await { - log::warn!("failed to preserve streamed text on clipboard: {error}"); - } + FinalReconciliation::Complete => self.finish_streamed(final_text).await, + FinalReconciliation::CopyFallback(text) => self.finish_with_fallback(text).await, + } + } + + async fn finish_streamed(&self, text: String) -> Result { + if self.save_streamed_text_to_clipboard { + if let Err(error) = self.platform.copy(text).await { + if error.code == BackendErrorCode::OutcomeUnknown { + let _ = self.platform.cancel().await; + return Err(error); } - self.finish_platform(String::new()).await + log::warn!("failed to preserve streamed text on clipboard: {error}"); } - FinalReconciliation::CopyFallback(text) => self.finish_with_fallback(text).await, } + self.finish_platform(String::new()).await } async fn finish_with_fallback(&self, text: String) -> Result { @@ -2498,6 +2518,12 @@ impl ActiveTextInsertion { self.session_id, copied.as_ref().map_err(|error| error.code), ); + if let Err(error) = &copied { + if error.code == BackendErrorCode::OutcomeUnknown { + let _ = self.platform.cancel().await; + return Err(error.clone()); + } + } let closed = self.finish_platform(String::new()).await; copied?; closed?; @@ -9243,10 +9269,38 @@ impl OpenLessBackend { self.start_reserved_dictation(reservation, options).await } + /// Terminal-only policy: no persistent preference mutation and no effect on + /// desktop, remote-input, QA, or wake-word recordings. + pub async fn start_terminal_dictation(&self, options: DictationStartOptions) -> Result { + self.start_terminal_dictation_with_feedback(options, || async { Ok(()) }).await + } + + /// Reserve capture ownership before pre-capture feedback, preventing a + /// second start chime from leaking into another session's microphone. + pub async fn start_terminal_dictation_with_feedback(&self, mut options: DictationStartOptions, feedback: F) -> Result + where F: FnOnce() -> Fut, Fut: std::future::Future> { + options.insert_text = false; + let reservation = self.reserve_dictation_session(&options, None)?; + if let Err(error) = feedback().await { + let _ = self.cancel_dictation(Some(reservation.session_id)).await; + return Err(error); + } + self.start_reserved_dictation_policy(reservation, options, true).await + } + async fn start_reserved_dictation( &self, reservation: DictationReservation, options: DictationStartOptions, + ) -> Result { + self.start_reserved_dictation_policy(reservation, options, false).await + } + + async fn start_reserved_dictation_policy( + &self, + reservation: DictationReservation, + options: DictationStartOptions, + terminal_silence_stop: bool, ) -> Result { let DictationReservation { session_id, @@ -9285,7 +9339,12 @@ impl OpenLessBackend { ) .await { - Ok(context) => Arc::new(context), + Ok(mut context) => { + if terminal_silence_stop { + context.recording.silence_after_ms = Some(15_000); + } + Arc::new(context) + } Err(error) => { self.schedule_pending_audio_capture_discard(pending_capture.take()); self.mark_dictation_failed(session_id, &error); @@ -17625,6 +17684,58 @@ mod tests { backend.shutdown().await.unwrap(); } + #[tokio::test] + async fn terminal_silence_stop_uses_volume_and_does_not_change_desktop_preferences() { + let (backend, _) = backend(); + backend.start().await.unwrap(); + let preferences = backend.get_preferences(); + assert!(!preferences.silence_auto_stop_enabled); + let id = backend.start_terminal_dictation(DictationStartOptions::default()).await.unwrap(); + let context = backend.state.read().unwrap().dictation_context.clone().unwrap(); + assert_eq!(context.recording.silence_after_ms, Some(15_000)); + let mut events = backend.subscribe(); + let progress = backend.engine_progress_sink(); + progress.publish(id, EngineProgress::RecordingLevel { elapsed_ms: 9_000, level: 0.0 }).unwrap(); + while let Ok(event) = events.try_recv() { + assert!(!matches!(event.kind, BackendEventKind::RecordingControlRequested(_))); + } + progress.publish(id, EngineProgress::RecordingLevel { elapsed_ms: 10_000, level: 0.0 }).unwrap(); + let mut cancelled = false; + while let Ok(event) = events.try_recv() { + if let BackendEventKind::RecordingControlRequested(control) = event.kind { + assert_eq!(control.action, crate::RecordingControlAction::Cancel); + cancelled = true; + } + } + assert!(cancelled); + backend.cancel_dictation(Some(id)).await.unwrap(); + let id = backend.start_terminal_dictation(DictationStartOptions::default()).await.unwrap(); + let mut events = backend.subscribe(); + for elapsed_ms in [100, 200, 300] { + progress.publish(id, EngineProgress::RecordingLevel { elapsed_ms, level: 0.1 }).unwrap(); + } + progress.publish(id, EngineProgress::RecordingLevel { elapsed_ms: 15_299, level: 0.0 }).unwrap(); + while let Ok(event) = events.try_recv() { + assert!(!matches!(event.kind, BackendEventKind::RecordingControlRequested(_))); + } + progress.publish(id, EngineProgress::RecordingLevel { elapsed_ms: 15_300, level: 0.0 }).unwrap(); + let mut stopped = false; + while let Ok(event) = events.try_recv() { + if let BackendEventKind::RecordingControlRequested(control) = event.kind { + assert_eq!(control.action, crate::RecordingControlAction::Stop); + stopped = true; + } + } + assert!(stopped); + backend.cancel_dictation(Some(id)).await.unwrap(); + assert_eq!(backend.get_preferences().silence_auto_stop_enabled, preferences.silence_auto_stop_enabled); + backend.start_dictation_with_options(DictationStartOptions { insert_text: false, ..Default::default() }).await.unwrap(); + let context = backend.state.read().unwrap().dictation_context.clone().unwrap(); + assert_eq!(context.recording.silence_after_ms, None); + backend.cancel_dictation(None).await.unwrap(); + backend.shutdown().await.unwrap(); + } + async fn start_voice_test_session( backend: &OpenLessBackend, timeout: Option, @@ -20596,6 +20707,46 @@ mod tests { } } + #[tokio::test] + async fn uncertain_stream_or_tail_never_copies_or_recommits() { + struct LostReply(Arc>>); + impl TextInsertionSession for LostReply { + fn supports_streaming(&self) -> bool { true } + fn write(&self, _: String) -> BoxFuture<'static, Result> { + self.0.lock().unwrap().push("write"); + boxed(async { Err(BackendError::new(BackendErrorCode::OutcomeUnknown, "native reply lost")) }) + } + fn copy(&self, _: String) -> BoxFuture<'static, Result<(), BackendError>> { + self.0.lock().unwrap().push("copy"); + boxed(async { Ok(()) }) + } + fn finish(&self, _: String) -> BoxFuture<'static, Result> { + self.0.lock().unwrap().push("finish"); + boxed(async { Ok(InsertOutcome::Inserted) }) + } + fn cancel(&self) -> BoxFuture<'static, Result<(), BackendError>> { + self.0.lock().unwrap().push("cancel"); + boxed(async { Ok(()) }) + } + } + for streaming_chunk in [false, true] { + let log = Arc::new(Mutex::new(Vec::new())); + let gate = Arc::new(crate::voice_session::VoiceSessionGate::default()); + let id = SessionId::new(); + gate.acquire(id, crate::voice_session::VoiceSessionKind::Dictation).unwrap(); + let insertion = ActiveTextInsertion::new(id, Arc::new(LostReply(log.clone())), + &DictationContext::default(), Arc::new(TokioTaskSpawner), gate.hold_resources(id).unwrap()); + if streaming_chunk { + insertion.state.lock().unwrap().stream.push_delta(0, "first"); + insertion.clone().flush_loop().await; + } else { + insertion.state.lock().unwrap().stream.typed_text = "first".into(); + } + assert_eq!(insertion.finish("first and last".into()).await.unwrap_err().code, BackendErrorCode::OutcomeUnknown); + assert_eq!(*log.lock().unwrap(), ["write", "cancel"]); + } + } + struct CompositionRecorder(Arc>>); impl TextInsertionSession for CompositionRecorder { fn supports_streaming(&self) -> bool { diff --git a/openless-all/app/crates/openless-core/src/app_catalog.rs b/openless-all/app/crates/openless-core/src/app_catalog.rs index 2a71188bd..3f10ed811 100644 --- a/openless-all/app/crates/openless-core/src/app_catalog.rs +++ b/openless-all/app/crates/openless-core/src/app_catalog.rs @@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize}; use crate::app_style_routing::InputApp; use crate::errors::{BackendError, BackendErrorCode}; +mod linux; use crate::persistence::{atomic_write, read_or_default}; #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -56,11 +57,17 @@ pub struct ClientIdentifiers { pub macos_bundle_prefixes: Vec, pub windows_executable_stems: Vec, pub installed_web_app_names: Vec, + pub linux_program_names: Vec, + pub linux_desktop_ids: Vec, } impl CatalogClient { fn matches(&self, app: &InputApp) -> bool { let ids = &self.identifiers; + if let Some(program) = app.id.strip_prefix("linux:") { + return ids.linux_program_names.iter().any(|id| id == program) + || ids.linux_desktop_ids.iter().any(|id| id == program.strip_suffix(".desktop").unwrap_or(program)); + } if let Some(bundle) = app.macos_bundle_id() { return ids .macos_bundle_ids @@ -146,7 +153,9 @@ impl AppCatalogStore { } pub(crate) fn snapshot(&self) -> AppCatalog { - self.current.read().unwrap().clone() + let mut catalog = self.current.read().unwrap().clone(); + if cfg!(target_os = "linux") { linux::enrich(&mut catalog); } + catalog } pub(crate) async fn refresh(&self) -> Result { @@ -177,7 +186,7 @@ impl AppCatalogStore { atomic_write(path, &bytes)?; } *self.current.write().unwrap() = catalog.clone(); - Ok(catalog) + Ok(self.snapshot()) } } @@ -190,6 +199,23 @@ mod tests { use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; + #[test] + fn linux_classification_is_explicit_offline_and_respects_remote_categories() { + let mut catalog = AppCatalog::default(); + linux::enrich(&mut catalog); + for (program, category) in [("code", "coding"), ("firefox", "browser"), ("org.mozilla.Thunderbird", "email"), ("soffice.bin", "office"), ("obsidian", "writing"), ("signal-desktop", "chat")] { + let app = InputApp { id: format!("linux:{program}"), name: "User renamed this application".into() }; + assert_eq!(catalog.client_for(&app).unwrap().category, category); + } + assert!(catalog.client_for(&InputApp { id: "linux:unknown".into(), name: "Visual Studio Code".into() }).is_none()); + assert!(catalog.client_for(&InputApp { id: "linux:my-code-helper".into(), name: "code".into() }).is_none()); + let mut remote: AppCatalog = serde_json::from_str(include_str!("../tests/fixtures/app-catalog.json")).unwrap(); + remote.clients[0].category = "office".into(); + linux::enrich(&mut remote); + let app = InputApp { id: "linux:code".into(), name: "code".into() }; + assert_eq!(remote.client_for(&app).unwrap().category, "office"); + } + #[test] fn canonical_identity_uses_one_client_even_when_an_alias_matches_first() { let mut catalog: AppCatalog = diff --git a/openless-all/app/crates/openless-core/src/app_catalog/linux.rs b/openless-all/app/crates/openless-core/src/app_catalog/linux.rs new file mode 100644 index 000000000..b89b59f82 --- /dev/null +++ b/openless-all/app/crates/openless-core/src/app_catalog/linux.rs @@ -0,0 +1,59 @@ +//! Reviewed Linux identifiers. No matching against display names, arbitrary +//! substrings, window titles or Windows executable names. +use super::{AppCatalog, CatalogCategory, CatalogClient, ClientIdentifiers}; + +pub(super) fn enrich(catalog: &mut AppCatalog) { + if catalog.schema_version == 0 { catalog.schema_version = 1; catalog.reviewed_at = "bundled-linux-v1".into(); } + for (id, name, english) in [("coding", "编程", "Programming"), ("chat", "聊天", "Chat"), ("email", "邮件", "Email"), ("writing", "写作与笔记", "Writing and notes"), ("office", "办公", "Office"), ("browser", "浏览器", "Browser")] { + if !catalog.categories.iter().any(|category| category.id == id) { + catalog.categories.push(CatalogCategory { id: id.into(), name: english.into(), prompt_guidance: String::new(), details: std::collections::BTreeMap::from([("labels".into(), serde_json::json!({ "en": english, "zh-CN": name }))]) }); + } + } + for (id, name, category, programs, desktops) in [ + ("vscode", "Visual Studio Code", "coding", &["code", "code-insiders", "code-oss"] as &[&str], &["code", "code-insiders", "code-oss"] as &[&str]), + ("vscodium", "VSCodium", "coding", &["codium"], &["codium"]), + ("jetbrains-idea", "IntelliJ IDEA", "coding", &["idea", "jetbrains-idea"], &["jetbrains-idea", "jetbrains-idea-ce"]), + ("jetbrains-pycharm", "PyCharm", "coding", &["pycharm", "jetbrains-pycharm"], &["jetbrains-pycharm", "jetbrains-pycharm-ce"]), + ("kate", "Kate", "coding", &["kate"], &["org.kde.kate"]), + ("sublime-text", "Sublime Text", "coding", &["sublime_text"], &["sublime_text"]), + ("google-chrome", "Google Chrome", "browser", &["google-chrome", "google-chrome-stable"], &["google-chrome", "com.google.Chrome"]), + ("chromium", "Chromium", "browser", &["chromium", "chromium-browser"], &["chromium", "chromium-browser", "org.chromium.Chromium"]), + ("firefox", "Firefox", "browser", &["firefox", "firefox-esr"], &["firefox", "firefox-esr", "org.mozilla.firefox"]), + ("brave", "Brave", "browser", &["brave", "brave-browser"], &["brave-browser", "com.brave.Browser"]), + ("microsoft-edge", "Microsoft Edge", "browser", &["microsoft-edge", "microsoft-edge-stable"], &["microsoft-edge", "com.microsoft.Edge"]), + ("thunderbird", "Thunderbird", "email", &["thunderbird"], &["thunderbird", "org.mozilla.Thunderbird"]), + ("evolution", "Evolution", "email", &["evolution"], &["org.gnome.Evolution"]), + ("kmail", "KMail", "email", &["kmail"], &["org.kde.kmail2"]), + ("libreoffice-writer", "LibreOffice Writer", "office", &["libreoffice-writer"], &["libreoffice-writer"]), + ("libreoffice-calc", "LibreOffice Calc", "office", &["libreoffice-calc"], &["libreoffice-calc"]), + ("libreoffice", "LibreOffice", "office", &["soffice", "soffice.bin", "libreoffice"], &["org.libreoffice.LibreOffice", "libreoffice-startcenter"]), + ("onlyoffice", "ONLYOFFICE", "office", &["desktopeditors", "onlyoffice-desktopeditors"], &["onlyoffice-desktopeditors", "org.onlyoffice.desktopeditors"]), + ("obsidian", "Obsidian", "writing", &["obsidian"], &["obsidian", "md.obsidian.Obsidian"]), + ("joplin", "Joplin", "writing", &["joplin", "joplin-desktop"], &["joplin", "net.cozic.joplin_desktop"]), + ("gedit", "Text Editor", "writing", &["gedit", "gnome-text-editor"], &["org.gnome.gedit", "org.gnome.TextEditor"]), + ("telegram", "Telegram", "chat", &["telegram-desktop", "Telegram"], &["org.telegram.desktop", "telegramdesktop"]), + ("slack", "Slack", "chat", &["slack"], &["slack", "com.slack.Slack"]), + ("discord", "Discord", "chat", &["discord", "Discord"], &["discord", "com.discordapp.Discord"]), + ("signal", "Signal", "chat", &["signal-desktop"], &["signal-desktop", "org.signal.Signal"]), + ("element", "Element", "chat", &["element-desktop"], &["element-desktop", "im.riot.Riot"]), + ] { + let identifiers = ClientIdentifiers { + linux_program_names: programs.iter().map(|name| (*name).into()).collect(), + linux_desktop_ids: desktops.iter().map(|name| (*name).into()).collect(), + ..Default::default() + }; + if let Some(client) = catalog.clients.iter_mut().find(|client| client.id == id) { + // Remote category, name and guidance always win. Supplement only the + // explicitly reviewed Linux aliases; never copy a Windows stem. + for name in identifiers.linux_program_names { + if !client.identifiers.linux_program_names.contains(&name) { client.identifiers.linux_program_names.push(name); } + } + for name in identifiers.linux_desktop_ids { + if !client.identifiers.linux_desktop_ids.contains(&name) { client.identifiers.linux_desktop_ids.push(name); } + } + if !client.platforms.iter().any(|platform| platform == "linux") { client.platforms.push("linux".into()); } + } else { + catalog.clients.push(CatalogClient { id: id.into(), name: name.into(), role: "native".into(), category: category.into(), platforms: vec!["linux".into()], identifiers, canonical_client_id: None, prompt_guidance: String::new(), details: Default::default() }); + } + } +} diff --git a/openless-all/app/crates/openless-core/src/app_style_routing.rs b/openless-all/app/crates/openless-core/src/app_style_routing.rs index 1694fe401..7a3094157 100644 --- a/openless-all/app/crates/openless-core/src/app_style_routing.rs +++ b/openless-all/app/crates/openless-core/src/app_style_routing.rs @@ -538,6 +538,20 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[cfg(target_os = "linux")] + #[test] + fn offline_linux_categories_select_styles_and_preserve_manual_overrides() { + let store = AppStyleStore::in_memory(); + let app = InputApp { id: "linux:code".into(), name: "code".into() }; + store.set(AppStyleAssignment::Category { category: "coding".into(), style_pack_id: Some("code-style".into()) }).unwrap(); + assert_eq!(store.candidates(&app), ["code-style"]); + store.observe(&app).unwrap(); + store.set(AppStyleAssignment::App { app_id: app.id.clone(), style_pack_id: Some("explicit-style".into()) }).unwrap(); + assert_eq!(store.candidates(&app), ["explicit-style", "code-style"]); + store.set(AppStyleAssignment::Membership { member_id: "catalog:vscode".into(), category: None }).unwrap(); + assert_eq!(store.candidates(&app), ["explicit-style"]); + } + #[test] fn shared_packs_keep_one_assignment_per_target() { let dir = diff --git a/openless-all/app/crates/openless-core/src/auxiliary.rs b/openless-all/app/crates/openless-core/src/auxiliary.rs index f79befa02..2fe7f422a 100644 --- a/openless-all/app/crates/openless-core/src/auxiliary.rs +++ b/openless-all/app/crates/openless-core/src/auxiliary.rs @@ -2,7 +2,7 @@ //! //! Hosts own file selection and optional foreground-application capture. The //! core owns style selection, immutable provider snapshots, cancellation and -//! attribution so Tauri and egui cannot drift in their business behaviour. +//! attribution so the desktop host and the Linux host cannot drift in their business behaviour. use std::sync::Arc; diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/dto.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/dto.rs index e457f55f6..dc9006b52 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/dto.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/dto.rs @@ -170,6 +170,11 @@ pub struct SyncConflictItem { pub kind: String, /// A fixed reason code, never a value, path, history excerpt, or API key. pub reason: String, + /// Display-only style names. Never credentials, prompts, icon bytes or history. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_label: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cloud_label: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs index 251174224..ed596a727 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee/service.rs @@ -1843,9 +1843,15 @@ impl EncryptedSyncService { local.documents.observed_revision(), )?; let baseline = self.baseline_documents(runtime)?; - let merged = - documents::diff_sync_documents(baseline.as_ref(), &local_sync, &remote) - .map_err(document_error)?; + let merged = documents::diff_sync_documents(baseline.as_ref(), &local_sync, &remote) + .map_err(document_error)?; + // Only style names are displayable metadata. Do not forward document + // values (credentials, prompts, history or icon contents) to the review UI. + let style_label = |docs: &ValidatedSyncDocuments, id: &str| -> Option { + let doc = docs.documents().documents.iter().find(|doc| + doc.kind == DocumentKind::StylePacks && doc.id == id)?; + style_review_label(doc.kind, &doc.value) + }; let conflicts = merged .conflicts() .iter() @@ -1853,6 +1859,8 @@ impl EncryptedSyncService { id: conflict.conflict_id.clone(), kind: wire_name(&conflict.kind), reason: wire_name(&conflict.reason), + local_label: style_label(&local.documents, &conflict.document_id), + cloud_label: style_label(&remote, &conflict.document_id), }) .collect(); let mut counts = BTreeMap::new(); @@ -3005,6 +3013,28 @@ fn same_documents(left: &DocumentSet, right: &DocumentSet) -> bool { left.documents == right.documents && left.tombstones == right.tombstones } +fn style_review_label(kind: DocumentKind, value: &serde_json::Value) -> Option { + if kind != DocumentKind::StylePacks { return None; } + let name = value.pointer("/pack/name")?.as_str()?; + let name: String = name.chars().filter(|c| !c.is_control()).take(100).collect(); + let name = name.trim(); + (!name.is_empty()).then(|| name.to_string()) +} + +#[cfg(test)] +mod conflict_labels_tests { + use super::*; + #[test] + fn review_only_exposes_bounded_style_names_not_document_contents() { + let value = serde_json::json!({ "pack": { "name": "My Style", "prompt": "PRIVATE PROMPT" }, "apiKey": "PRIVATE KEY", "icon": "PRIVATE ICON" }); + assert_eq!(style_review_label(DocumentKind::StylePacks, &value).as_deref(), Some("My Style")); + assert!(style_review_label(DocumentKind::Channels, &value).is_none()); + assert!(style_review_label(DocumentKind::History, &value).is_none()); + let long = serde_json::json!({"pack": {"name": format!("\\n{}", "中".repeat(200))}}); + assert_eq!(style_review_label(DocumentKind::StylePacks, &long).unwrap().chars().count(), 100); + } +} + fn definite_rejection(error: &crate::cloud_sync_e2ee_protocol::Error) -> bool { // Only for the first submit of a freshly generated operation ID. A retry of // an older unknown request cannot use a CAS rejection as proof of failure. diff --git a/openless-all/app/crates/openless-core/src/credential_accounts.rs b/openless-all/app/crates/openless-core/src/credential_accounts.rs new file mode 100644 index 000000000..b22fa970f --- /dev/null +++ b/openless-all/app/crates/openless-core/src/credential_accounts.rs @@ -0,0 +1,188 @@ +//! 凭据账号 → 命名空间的映射(两个宿主共用)。 +//! +//! 这套表原来只住在 Tauri 命令层(`src-tauri/src/commands/credentials.rs`), +//! 于是 Linux 的 Web 宿主想读/写凭据就得抄一份 —— 抄两份必然漂移,而"凭据读错 +//! key"是静默错误。这里把它下沉到 core,宿主只调用不复制。 +use crate::credentials::{CredentialKey, CredentialNamespace}; +use crate::{BackendError, BackendErrorCode}; + +/// GitHub OAuth token 的账号名(Marketplace 用它读写)。 +pub const MARKETPLACE_GITHUB_TOKEN_ACCOUNT: &str = "github.oauth_token"; + +/// 稳定的账号标识。名字与 Swift / Tauri 侧一致,老 Keychain 条目仍可读。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CredentialAccount { + VolcengineAppKey, + VolcengineAccessKey, + VolcengineResourceId, + VolcengineService, + VolcengineAuthMode, + VolcengineApiKey, + ArkApiKey, + ArkModelId, + ArkEndpoint, + AsrApiKey, + AsrEndpoint, + AsrModel, + AsrVocabularyId, + AsrAdvancedConfig, + XfyunAppId, + XfyunApiKey, + TencentCloudAppId, + TencentCloudSecretId, + TencentCloudSecretKey, + OmniApiKey, + OmniEndpoint, + OmniModel, +} + +impl CredentialAccount { + pub fn keyring_account(self) -> &'static str { + match self { + Self::VolcengineAppKey => "volcengine.app_key", + Self::VolcengineAccessKey => "volcengine.access_key", + Self::VolcengineResourceId => "volcengine.resource_id", + Self::VolcengineService => "volcengine.service", + Self::VolcengineAuthMode => "volcengine.auth_mode", + Self::VolcengineApiKey => "volcengine.api_key", + Self::ArkApiKey => "ark.api_key", + Self::ArkModelId => "ark.model_id", + Self::ArkEndpoint => "ark.endpoint", + Self::AsrApiKey => "asr.api_key", + Self::AsrEndpoint => "asr.endpoint", + Self::AsrModel => "asr.model", + Self::AsrVocabularyId => "asr.vocabulary_id", + Self::AsrAdvancedConfig => "asr.advanced_config", + Self::XfyunAppId => "xfyun.app_id", + Self::XfyunApiKey => "xfyun.api_key", + Self::TencentCloudAppId => "tencent_cloud.app_id", + Self::TencentCloudSecretId => "tencent_cloud.secret_id", + Self::TencentCloudSecretKey => "tencent_cloud.secret_key", + Self::OmniApiKey => "omni.api_key", + Self::OmniEndpoint => "omni.endpoint", + Self::OmniModel => "omni.model", + } + } + + pub fn parse(value: &str) -> Option { + Some(match value { + "volcengine.app_key" => Self::VolcengineAppKey, + "volcengine.access_key" => Self::VolcengineAccessKey, + "volcengine.resource_id" => Self::VolcengineResourceId, + "volcengine.service" => Self::VolcengineService, + "volcengine.auth_mode" => Self::VolcengineAuthMode, + "volcengine.api_key" => Self::VolcengineApiKey, + "ark.api_key" => Self::ArkApiKey, + "ark.model_id" => Self::ArkModelId, + "ark.endpoint" => Self::ArkEndpoint, + "asr.api_key" => Self::AsrApiKey, + "asr.endpoint" => Self::AsrEndpoint, + "asr.model" => Self::AsrModel, + "asr.vocabulary_id" => Self::AsrVocabularyId, + "asr.advanced_config" => Self::AsrAdvancedConfig, + "xfyun.app_id" => Self::XfyunAppId, + "xfyun.api_key" => Self::XfyunApiKey, + "tencent_cloud.app_id" => Self::TencentCloudAppId, + "tencent_cloud.secret_id" => Self::TencentCloudSecretId, + "tencent_cloud.secret_key" => Self::TencentCloudSecretKey, + "omni.api_key" => Self::OmniApiKey, + "omni.endpoint" => Self::OmniEndpoint, + "omni.model" => Self::OmniModel, + _ => return None, + }) + } + + /// 该账号属于哪个 provider 家族 —— 决定显式 provider id 路由到哪个命名空间。 + fn namespace(self) -> CredentialNamespace { + match self { + Self::ArkApiKey | Self::ArkModelId | Self::ArkEndpoint => CredentialNamespace::Llm, + Self::OmniApiKey | Self::OmniEndpoint | Self::OmniModel => CredentialNamespace::Omni, + _ => CredentialNamespace::Asr, + } + } +} + +/// 账号名 → 凭据 key(含命名空间与可选 provider)。 +/// +/// 映射规则(与 Tauri 侧完全一致): +/// 1. LLM 协议的配置账号(`llm_protocol::CONFIG_ACCOUNTS`)→ `Llm`; +/// 2. LLM 的额外 header / temperature 账号 → `Llm`;Omni 的同名账号 → `Omni`; +/// 3. Marketplace 的 GitHub token → `Marketplace`;云同步自建 token → `Application`; +/// 4. 其余按 `CredentialAccount::namespace()`。 +pub fn credential_key( + account: &str, + provider: Option, +) -> Result { + // 1+2 都是 `Llm`,合成一个条件:clippy 会把两个相同分支报成 identical blocks。 + let namespace = if crate::llm_protocol::CONFIG_ACCOUNTS.contains(&account) + || account == crate::credentials::LLM_EXTRA_HEADERS_ACCOUNT + || account == crate::credentials::LLM_TEMPERATURE_ACCOUNT + { + CredentialNamespace::Llm + } else if account == crate::credentials::OMNI_EXTRA_HEADERS_ACCOUNT + || account == crate::credentials::OMNI_TEMPERATURE_ACCOUNT + { + CredentialNamespace::Omni + } else if account == MARKETPLACE_GITHUB_TOKEN_ACCOUNT { + CredentialNamespace::Marketplace + } else if account == crate::credentials::CLOUD_SYNC_CUSTOM_TOKEN_ACCOUNT + || account == crate::deepseek_suite::CONFIG_ACCOUNT + || account == "web_search.config" + { + CredentialNamespace::Application + } else { + CredentialAccount::parse(account) + .ok_or_else(|| { + BackendError::new( + BackendErrorCode::InvalidArgument, + format!("unknown credential account: {account}"), + ) + })? + .namespace() + }; + CredentialKey::new(namespace, provider, account) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn account_names_round_trip() { + for account in [ + "volcengine.app_key", + "ark.api_key", + "asr.api_key", + "xfyun.app_id", + "tencent_cloud.secret_key", + "omni.model", + ] { + let parsed = CredentialAccount::parse(account).expect(account); + assert_eq!(parsed.keyring_account(), account); + } + } + + #[test] + fn namespaces_follow_the_account_family() { + let llm = credential_key("ark.api_key", None).unwrap(); + let asr = credential_key("asr.api_key", None).unwrap(); + let omni = credential_key("omni.api_key", None).unwrap(); + assert_eq!(llm.namespace, CredentialNamespace::Llm); + assert_eq!(asr.namespace, CredentialNamespace::Asr); + assert_eq!(omni.namespace, CredentialNamespace::Omni); + } + + #[test] + fn application_configs_match_their_shared_service_namespace() { + for account in [crate::deepseek_suite::CONFIG_ACCOUNT, "web_search.config"] { + let key = credential_key(account, None).unwrap(); + assert_eq!(key.namespace, CredentialNamespace::Application); + assert!(key.provider_id.is_none()); + } + } + + #[test] + fn unknown_accounts_are_rejected() { + assert!(credential_key("nope.nothing", None).is_err()); + } +} diff --git a/openless-all/app/crates/openless-core/src/domains.rs b/openless-all/app/crates/openless-core/src/domains.rs index 8b952dbf0..17e8fdeb3 100644 --- a/openless-all/app/crates/openless-core/src/domains.rs +++ b/openless-all/app/crates/openless-core/src/domains.rs @@ -2,7 +2,7 @@ //! transport implementations. //! //! The traits in this module are deliberately grouped by use-case instead of -//! mirroring Tauri command names. Linux/egui code only depends on these DTOs +//! mirroring Tauri command names. Linux host code only depends on these DTOs //! and traits; Tauri remains a compatibility adapter for the legacy IPC names. use std::path::PathBuf; diff --git a/openless-all/app/crates/openless-core/src/lib.rs b/openless-all/app/crates/openless-core/src/lib.rs index 4821e520e..b3d4ff813 100644 --- a/openless-all/app/crates/openless-core/src/lib.rs +++ b/openless-all/app/crates/openless-core/src/lib.rs @@ -38,6 +38,7 @@ mod correction_observation; pub mod coding_agent_guard; pub mod config; pub mod correction; +pub mod credential_accounts; pub mod credentials; pub mod credentials_legacy; pub mod deepseek_suite; diff --git a/openless-all/app/crates/openless-core/src/testing.rs b/openless-all/app/crates/openless-core/src/testing.rs index fa9a5fbd2..d13e1d378 100644 --- a/openless-all/app/crates/openless-core/src/testing.rs +++ b/openless-all/app/crates/openless-core/src/testing.rs @@ -1,7 +1,7 @@ //! Deterministic adapters for host and UI contract tests. //! //! These fakes are deliberately small and side-effect free. They are useful -//! to the Linux egui team when developing a view model without a microphone, +//! to the Linux host team when developing a view model without a microphone, //! network provider, desktop session or credential store. use std::collections::VecDeque; diff --git a/openless-all/app/crates/openless-core/src/voice_edit_session.rs b/openless-all/app/crates/openless-core/src/voice_edit_session.rs index 0a6ae837f..47f21b637 100644 --- a/openless-all/app/crates/openless-core/src/voice_edit_session.rs +++ b/openless-all/app/crates/openless-core/src/voice_edit_session.rs @@ -50,6 +50,8 @@ pub enum VoiceEditPhase { Applying, Preview, Committing, + /// A native mutation may have landed; the captured target must not be reused. + OutcomeUnknown, Completed, Cancelled, } @@ -328,6 +330,12 @@ impl VoiceEditSession { } /// Keep the preview retryable when the host could not write to the target. + pub fn mark_commit_outcome_unknown(&mut self) -> Result<(), VoiceEditError> { + self.require_phase(VoiceEditPhase::Committing)?; + self.phase = VoiceEditPhase::OutcomeUnknown; + Ok(()) + } + pub fn recover_commit(&mut self) -> Result<(), VoiceEditError> { self.require_phase(VoiceEditPhase::Committing)?; self.restore_ready_phase() @@ -336,7 +344,7 @@ impl VoiceEditSession { pub fn cancel(&mut self) -> Result<(), VoiceEditError> { if matches!( self.phase, - VoiceEditPhase::Committing | VoiceEditPhase::Completed | VoiceEditPhase::Cancelled + VoiceEditPhase::Committing | VoiceEditPhase::OutcomeUnknown | VoiceEditPhase::Completed | VoiceEditPhase::Cancelled ) { return Err(VoiceEditError::InvalidPhase { phase: self.phase }); } 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 index 79bed5402..a46b2e562 100644 --- a/openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs +++ b/openless-all/app/crates/openless-core/tests/linux_archive_ranges.rs @@ -1,3 +1,3 @@ // Exercise the production Linux archive adapter without loading a native audio backend. -#[path = "../../../../linux/egui/src/audio/archive.rs"] +#[path = "../../../../linux/host/src/audio/archive.rs"] mod archive; diff --git a/openless-all/app/e2e/fixtures/capsule-motion.tsx b/openless-all/app/e2e/fixtures/capsule-motion.tsx index 5a971fa6e..a4fcece96 100644 --- a/openless-all/app/e2e/fixtures/capsule-motion.tsx +++ b/openless-all/app/e2e/fixtures/capsule-motion.tsx @@ -282,7 +282,9 @@ createRoot(document.getElementById('root')!).render( transform: 'translateX(-50%)', }} > - + ) : ( diff --git a/openless-all/app/e2e/fixtures/linux-desktop-repairs.html b/openless-all/app/e2e/fixtures/linux-desktop-repairs.html new file mode 100644 index 000000000..f0a608385 --- /dev/null +++ b/openless-all/app/e2e/fixtures/linux-desktop-repairs.html @@ -0,0 +1 @@ +
diff --git a/openless-all/app/e2e/fixtures/linux-desktop-repairs.tsx b/openless-all/app/e2e/fixtures/linux-desktop-repairs.tsx new file mode 100644 index 000000000..0010d409c --- /dev/null +++ b/openless-all/app/e2e/fixtures/linux-desktop-repairs.tsx @@ -0,0 +1,52 @@ +import { createRoot } from 'react-dom/client'; +import '../../src/styles/tokens.css'; +import '../../src/styles/global.css'; +import '../../src/styles/overlays.css'; +const params = new URLSearchParams(location.search); +const callbacks = new Map void>(); +const listeners = new Map(); +const calls: { command: string; args: any }[] = []; +let next = 0; +let snapshot = { phase: 'idle', messages: [] as { id: string; role: string; content: string }[] }; +Object.assign(window, { fixture: { calls, emit() { + for (const [id, listener] of listeners) if (listener.event === 'qa:state') callbacks.get(listener.handler)?.({ event: 'qa:state', id, payload: { kind: snapshot.phase } }); +} } }); +window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: 'qa' }, currentWebview: { label: 'qa' } }, + transformCallback(callback: (value: unknown) => void) { const id = ++next; callbacks.set(id, callback); return id; }, + unregisterCallback(id: number) { callbacks.delete(id); }, + async invoke(command: string, args: any) { + calls.push({ command, args }); + if (command === 'get_startup_snapshot') return { contractVersion: '2.0.0', backend: { running: true } }; + if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, { event: args.event, handler: args.handler }); return id; } + if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; } + if (command === 'qa_get_snapshot') return structuredClone(snapshot); + if (command === 'list_correction_rules') return []; + if (command === 'qa_submit_text') { + snapshot = { phase: 'completed', messages: [{ id: 'q', role: 'user', content: args.text }, { id: 'a', role: 'assistant', content: '测试回答 / test answer' }] }; + (window as any).fixture.emit(); + } + }, +} as any; +const { default: i18n, i18nReady } = await import('../../src/i18n'); +await i18nReady; +await i18n.changeLanguage('zh-CN'); +const { InteractionProvider, useInteraction } = await import('../../src/ui/overlays/InteractionProvider'); +const { LinuxQaWindow } = await import('../../src/features/qa/LinuxQaWindow'); +const { RestoreReview } = await import('../../src/features/cloud-sync/RestoreReview'); +const { Corrections } = await import('../../src/features/corrections/Corrections'); +function Notices() { + const { notify } = useInteraction(); + return ; +} +const preview = { + previewId: 'p', observedRevision: '1', localGeneration: '1', counts: {}, deviceSettingsToReview: [], unconfirmedOperationId: null, + conflicts: [ + { id: 'one', kind: 'style_packs', reason: 'both_modified', localLabel: '本地写作风格', cloudLabel: '云端写作风格' }, + { id: 'two', kind: 'style_packs', reason: 'both_modified', localLabel: '翻译风格', cloudLabel: '翻译风格' }, + ], +}; +createRoot(document.getElementById('root')!).render( + {params.get('mode') === 'review' ? {}} /> : + params.get('mode') === 'notices' ? : params.get('mode') === 'corrections' ? : } +); diff --git a/openless-all/app/e2e/linux-desktop-repairs.spec.ts b/openless-all/app/e2e/linux-desktop-repairs.spec.ts new file mode 100644 index 000000000..cca36a709 --- /dev/null +++ b/openless-all/app/e2e/linux-desktop-repairs.spec.ts @@ -0,0 +1,41 @@ +import { expect, test } from '@playwright/test'; +import { fixtureOrigin } from './support/server'; +const fixture = `${fixtureOrigin}/e2e/fixtures/linux-desktop-repairs.html`; + +test('conflict review identifies each local/cloud style without exposing the document', async ({ page }) => { + await page.goto(`${fixture}?mode=review`); + await expect(page.getByText('本地写作风格', { exact: true }).first()).toBeVisible(); + await expect(page.getByText('云端写作风格', { exact: false }).first()).toBeVisible(); + await expect(page.getByText('翻译风格', { exact: true }).first()).toBeVisible(); + const fields = page.locator('fieldset').filter({ has: page.getByRole('radio') }); + await expect(fields).toHaveCount(3); +}); + +test('ordinary warning expires without user dismissal', async ({ page }) => { + await page.clock.install(); + await page.goto(`${fixture}?mode=notices`); + await page.getByRole('button', { name: 'Warn' }).click(); + await expect(page.getByText('会自动关闭的警告')).toBeVisible(); + await page.clock.fastForward(8500); + await expect(page.getByText('会自动关闭的警告')).toHaveCount(0); +}); + +test('Linux QA view submits to Core and renders its returned answer', async ({ page }) => { + await page.goto(fixture); + await page.getByRole('textbox', { name: '问题', exact: true }).fill('测试问题'); + await page.getByRole('button', { name: '发送', exact: true }).click(); + await expect(page.getByText('测试回答 / test answer')).toBeVisible(); + const calls = await page.evaluate(() => (window as any).fixture.calls); + expect(calls.some((call: any) => call.command === 'qa_submit_text' && call.args.text === '测试问题')).toBe(true); + await page.getByRole('button', { name: '关闭', exact: true }).click(); + await expect.poll(() => page.evaluate(() => (window as any).fixture.calls.some((call: any) => call.command === 'qa_window_dismiss'))).toBe(true); +}); + +test('correction add button sizes to its label instead of stretching a dark grid cell', async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 800 }); + await page.goto(`${fixture}?mode=corrections`); + const button = page.locator('.ol-correction-add'); + await expect(button).toBeVisible(); + expect((await button.boundingBox())!.width).toBeLessThan(100); + await expect(button).toHaveCSS('justify-content', 'center'); +}); diff --git a/openless-all/app/e2e/linux-surface-transparency.spec.ts b/openless-all/app/e2e/linux-surface-transparency.spec.ts new file mode 100644 index 000000000..baaa801de --- /dev/null +++ b/openless-all/app/e2e/linux-surface-transparency.spec.ts @@ -0,0 +1,27 @@ +import { expect, test } from '@playwright/test'; +import { fixtureOrigin } from './support/server'; + +for (const colorScheme of ['light', 'dark'] as const) { + test.describe(`Linux surface backgrounds (${colorScheme})`, () => { + test.use({ colorScheme }); + for (const kind of ['capsule', 'capsule-rail', 'voice-edit']) { + test(`${kind} keeps html/body/root transparent`, async ({ page }) => { + // Exercise the actual bootstrap and stylesheet, not a duplicated CSS fixture. + await page.goto(`${fixtureOrigin}/?bridge=http&window=${kind}`); + await expect(page.locator('html')).toHaveAttribute('data-ol-platform', 'linux'); + await expect(page.locator('html')).toHaveAttribute('data-ol-aux', ''); + for (const selector of ['html', 'body', '#root']) { + await expect(page.locator(selector)).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + } + }); + } + test('main window retains an opaque background', async ({ page }) => { + await page.goto(`${fixtureOrigin}/?bridge=http`); + await expect(page.locator('html')).toHaveAttribute('data-ol-platform', 'linux'); + await expect(page.locator('html')).not.toHaveAttribute('data-ol-aux'); + for (const selector of ['html', 'body', '#root']) { + await expect(page.locator(selector)).not.toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + } + }); + }); +} diff --git a/openless-all/app/e2e/linux-system-interactions.spec.ts b/openless-all/app/e2e/linux-system-interactions.spec.ts new file mode 100644 index 000000000..48741329a --- /dev/null +++ b/openless-all/app/e2e/linux-system-interactions.spec.ts @@ -0,0 +1,101 @@ +import { expect, test } from '@playwright/test'; +import { fixtureOrigin } from './support/server'; + +test('Linux history/vocabulary copy uses the current native window, not fcitx5', async ({ + page, +}) => { + await page.goto(`${fixtureOrigin}/?bridge=http&window=capsule`); + const result = await page.evaluate(async () => { + const copied: string[] = []; + window.__openlessCopyText = async (text) => { + copied.push(text); + }; + const path = '/src/api/files.ts'; + const files = await import(/* @vite-ignore */ path); + await files.copyTextToClipboard('历史记录 中文\nsecond line'); + window.__openlessCopyText = async () => { + throw new Error('native clipboard denied'); + }; + let error = ''; + try { + await files.copyTextToClipboard('must not report success'); + } catch (reason) { + error = String(reason); + } + return { copied, error }; + }); + expect(result.copied).toEqual(['历史记录 中文\nsecond line']); + expect(result.error).toContain('native clipboard denied'); +}); + +test('Linux uses a view-local input-region bridge, including empty cleanup', async ({ page }) => { + await page.goto(`${fixtureOrigin}/?bridge=http&window=capsule`); + const writes = await page.evaluate(async () => { + const writes: unknown[] = []; + window.__openlessSetInputRegions = (rects) => { + writes.push(rects); + }; + const path = '/src/runtime/windows/capsuleInput.ts'; + const module = await import(/* @vite-ignore */ path); + await module.setCapsuleInteractiveRegions([{ left: 20, top: 10, width: 40, height: 30 }]); + await module.setCapsuleInteractiveRegions([]); + return writes; + }); + expect(writes).toEqual([[{ left: 20, top: 10, width: 40, height: 30 }], []]); +}); + +test('native Linux main frame is square without changing card corners', async ({ page }) => { + await page.goto(`${fixtureOrigin}/?bridge=http`); + // Use the production WindowChrome with its real inline CSS shape. The global + // continuous-corners selector used to override this zero radius with !important. + await page.evaluate(() => { + const chrome = document.createElement('div'); + chrome.className = 'ol-winchrome'; + chrome.style.borderRadius = 'var(--ol-window-shell-radius)'; + chrome.style.setProperty('--ol-window-shell-radius', '0px'); + const card = document.createElement('div'); + card.className = 'ol-card'; + chrome.append(card); + document.body.append(chrome); + }); + await expect(page.locator('.ol-winchrome').last()).toHaveCSS('border-top-left-radius', '0px'); + await expect(page.locator('.ol-winchrome').last()).toHaveCSS('border-top-right-radius', '0px'); + await expect(page.locator('.ol-winchrome .ol-card').last()).not.toHaveCSS( + 'border-top-left-radius', + '0px', + ); +}); + +test('Linux capsule publishes only visible controls, not the overlay canvas', async ({ page }) => { + await page.goto(`${fixtureOrigin}/e2e/fixtures/capsule-motion.html?full&os=linux`); + await page.waitForFunction(() => (window as any).fixture.hasListener('capsule:state')); + await page.evaluate(() => { + (window as any).fixture.emit('capsule:state', { + state: 'recording', + sessionId: 'linux-test', + level: 0.3, + }); + }); + await expect(page.locator('.ol-default-action').first()).toBeVisible(); + await expect + .poll(() => + page.evaluate(() => { + const regions = (window as any).fixture.inputRegions; + const button = document.querySelector('.ol-default-action')!.getBoundingClientRect(); + const x = button.left + button.width / 2, + y = button.top + button.height / 2; + return ( + regions.length > 0 && + regions.some( + (r: any) => x >= r.left && x <= r.left + r.width && y >= r.top && y <= r.top + r.height, + ) && + !regions.some( + (r: any) => 1 >= r.left && 1 <= r.left + r.width && 1 >= r.top && 1 <= r.top + r.height, + ) + ); + }), + ) + .toBe(true); + await page.evaluate(() => (window as any).fixture.emit('capsule:state', { state: 'idle' })); + await expect.poll(() => page.evaluate(() => (window as any).fixture.inputRegions)).toEqual([]); +}); diff --git a/openless-all/app/scripts/capsule-ready-replay.test.mjs b/openless-all/app/scripts/capsule-ready-replay.test.mjs index 08b9700a3..8e0ee4010 100644 --- a/openless-all/app/scripts/capsule-ready-replay.test.mjs +++ b/openless-all/app/scripts/capsule-ready-replay.test.mjs @@ -53,6 +53,7 @@ function bindNativeAdapter(scope, tauri = true) { const runtime = { exports: {}, isTauriHost: () => tauri, + isLinuxHost: () => false, requireBackendReady: async () => undefined, require: scope.require, }; @@ -187,6 +188,7 @@ function mount({ ...backend.exports, ...outputStyle.exports, isTauri: true, + isNativeDesktopHost: () => true, isTauriHost: () => true, capsuleStateFirstLogged: true, capsuleStateRef: { current: 'idle' }, diff --git a/openless-all/app/scripts/check-command-event-baseline.ps1 b/openless-all/app/scripts/check-command-event-baseline.ps1 index f5d4ab3b7..bd0c22d53 100644 --- a/openless-all/app/scripts/check-command-event-baseline.ps1 +++ b/openless-all/app/scripts/check-command-event-baseline.ps1 @@ -9,7 +9,7 @@ param( $ErrorActionPreference = "Stop" $scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path if ([string]::IsNullOrWhiteSpace($BaselinePath)) { - $BaselinePath = Join-Path $scriptRoot "../../../docs/linux-egui-command-event-baseline.json" + $BaselinePath = Join-Path $scriptRoot "../../../docs/linux-host-command-event-baseline.json" } if ([string]::IsNullOrWhiteSpace($TauriLibPath)) { $TauriLibPath = Join-Path $scriptRoot "../src-tauri/src/lib.rs" diff --git a/openless-all/app/scripts/check-core-deps.ps1 b/openless-all/app/scripts/check-core-deps.ps1 index 82e9b8d48..a742e9bb4 100644 --- a/openless-all/app/scripts/check-core-deps.ps1 +++ b/openless-all/app/scripts/check-core-deps.ps1 @@ -1,12 +1,12 @@ [CmdletBinding()] param( - [ValidateSet("openless-core", "openless-linux-egui")] + [ValidateSet("openless-core", "openless-linux-host")] [string]$Package = "openless-core" ) $appRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\")).Path $forbidden = if ($Package -eq "openless-core") { - "tauri|wry|webkit2gtk|egui|eframe" + "tauri|wry|webkit2gtk|host|eframe|egui" } else { "tauri|wry|webkit2gtk" } diff --git a/openless-all/app/scripts/check-core-runtime-seam.ps1 b/openless-all/app/scripts/check-core-runtime-seam.ps1 index d07c6e403..a7e5a08b1 100644 --- a/openless-all/app/scripts/check-core-runtime-seam.ps1 +++ b/openless-all/app/scripts/check-core-runtime-seam.ps1 @@ -25,7 +25,7 @@ while ($changed) { $changed = $false foreach ($file in $files) { $relative = Get-CoreRelativePath $file.FullName - if ($testOnly.Contains($relative)) { continue } + if ($testOnly.Contains($relative) -or $relative -match '_tests\.rs$') { continue } $stem = [System.IO.Path]::GetFileNameWithoutExtension($file.FullName) $declarations = @(Get-ChildItem -LiteralPath $file.DirectoryName -Filter "*.rs" -File) $parentDir = Split-Path -Parent $file.DirectoryName @@ -66,7 +66,7 @@ foreach ($file in $files) { # Production code must submit background work to the injected TaskSpawner. # The test modules may use #[tokio::test]/tokio::spawn to orchestrate tests. - if ($testOnly.Contains($relative)) { continue } + if ($testOnly.Contains($relative) -or $relative -match '_tests\.rs$') { continue } $testMarker = $text.IndexOf("#[cfg(test)]", [System.StringComparison]::Ordinal) $production = if ($testMarker -ge 0) { $text.Substring(0, $testMarker) } else { $text } if ($production -match "tokio::spawn\s*\(") { diff --git a/openless-all/app/scripts/check-core-secret-surface.ps1 b/openless-all/app/scripts/check-core-secret-surface.ps1 index 14fa6d000..f5d90d657 100644 --- a/openless-all/app/scripts/check-core-secret-surface.ps1 +++ b/openless-all/app/scripts/check-core-secret-surface.ps1 @@ -14,8 +14,8 @@ $violations = foreach ($file in $surfaceFiles) { Select-String -Path $file -Pattern $forbiddenPublicField -CaseSensitive:$false | Where-Object { # QA approval_token is a session-bound UI correlation handle, not a provider credential. - # It is intentionally serialized so the UI can submit an explicit approval. - $_.Line -notmatch '^\s*pub\s+approval_token\s*:' + # HistoryReference rendered_token is a dictation material display placeholder, not a credential. + $_.Line -notmatch '^\s*pub\s+(approval_token|rendered_token)\s*:' } } if ($violations) { diff --git a/openless-all/app/scripts/ci-cache-sharing.test.mjs b/openless-all/app/scripts/ci-cache-sharing.test.mjs index 38123da1a..861462589 100644 --- a/openless-all/app/scripts/ci-cache-sharing.test.mjs +++ b/openless-all/app/scripts/ci-cache-sharing.test.mjs @@ -89,18 +89,23 @@ assert.ok(sharedKeys(androidApk).some((key) => key.startsWith('android-'))); // gate and save only from beta, so a run costs ~40 s and the common PR pays no // runner for them at all. { - const capsuleJob = ci.match(/\n native-capsule:[\s\S]*?(?=\n [a-z-]+:\n)/)?.[0] ?? ''; - assert.ok(capsuleJob, 'ci.yml must run the capsule crates as the native-capsule job'); - assert.match(capsuleJob, /shared-key: native-capsule/); - assert.match(capsuleJob, /save-if: \$\{\{ github\.ref == 'refs\/heads\/beta'/); + // beta still builds the native capsule crates for macOS and Windows. The + // Linux web capsule is separate and must not change their cache policy. + const capsuleJob = ci.match(/^ native-capsule:\n(?:^ .*\n|^\n)*/m)?.[0] ?? ''; + assert.ok(capsuleJob, 'ci.yml must run the native capsule crates'); + assert.match(capsuleJob, /shared-key: native-capsule\b/); + assert.match( + capsuleJob, + /save-if: \$\{\{ github\.ref == 'refs\/heads\/beta' && \(github\.event_name == 'push' \|\| github\.event_name == 'workflow_dispatch'\) \}\}/, + ); assert.match( capsuleJob, /if: needs\.changes\.outputs\.capsule != 'false'/, - 'the capsule job must be gated on its own area, not run for every desktop change', + 'the native capsule job must stay gated on its own area', ); assert.ok( !existsSync(join(root, '.github/workflows/native-capsule.yml')), - 'native-capsule.yml must stay merged into ci.yml', + 'native-capsule.yml must stay removed', ); } diff --git a/openless-all/app/scripts/ci-cache-usage.test.mjs b/openless-all/app/scripts/ci-cache-usage.test.mjs index b241fef72..ec7b284f3 100644 --- a/openless-all/app/scripts/ci-cache-usage.test.mjs +++ b/openless-all/app/scripts/ci-cache-usage.test.mjs @@ -40,7 +40,7 @@ const fixtures = [ }, { ref: 'refs/pull/102/merge', - key: 'v0-rust-build-linux-egui-Linux-x64-32c982f2-6e438e89', + key: 'v0-rust-build-linux-host-Linux-x64-32c982f2-6e438e89', size: 1_338_000_000, created: '2026-10-03T02:00:00Z', }, diff --git a/openless-all/app/scripts/ci-changed-areas.test.mjs b/openless-all/app/scripts/ci-changed-areas.test.mjs index c953494d7..96c196bc2 100644 --- a/openless-all/app/scripts/ci-changed-areas.test.mjs +++ b/openless-all/app/scripts/ci-changed-areas.test.mjs @@ -67,7 +67,6 @@ try { 'harmony', 'frontend', 'android', - 'capsule', 'ios-device', ]; const every = (verdict) => Object.fromEntries(ALL_AREAS.map((area) => [area, verdict])); @@ -106,7 +105,7 @@ try { reset(); // The Linux host is a separate crate in its own target graph. - commit({ 'openless-all/linux/egui/src/ui/theme.rs': 'fn x() {}\n' }, 'linux host source'); + commit({ 'openless-all/linux/host/src/i18n.rs': 'fn x() {}\n' }, 'linux host source'); expect('linux host source', { tauri: 'false', msrv: 'true', @@ -118,7 +117,7 @@ try { }); reset(); - commit({ 'openless-all/linux/egui/package-revision': '81\n' }, 'shared package revision'); + commit({ 'openless-all/linux/host/package-revision': '81\n' }, 'shared package revision'); expect('shared package revision', { ...every('false'), linux: 'true', @@ -137,7 +136,7 @@ try { }); reset(); - // The Linux workflow owns Harmony Rust unit tests as well as the egui host. + // The Linux workflow owns Harmony Rust unit tests as well as the Linux host. commit({ 'openless-all/harmony/rust/src/lib.rs': 'pub fn x() {}\n' }, 'harmony rust'); expect('harmony rust', { tauri: 'false', @@ -164,7 +163,7 @@ try { // ...but its manifest moves the workspace dependency graph for everyone. commit( - { 'openless-all/linux/egui/Cargo.toml': '[package]\nname = "x"\n' }, + { 'openless-all/linux/host/Cargo.toml': '[package]\nname = "x"\n' }, 'linux host manifest', ); expect('linux host manifest', { tauri: 'true', msrv: 'true', linux: 'true', harmony: 'true' }); @@ -178,23 +177,13 @@ try { linux: 'false', harmony: 'false', android: 'true', - capsule: 'false', 'ios-device': 'false', }); reset(); - commit({ 'openless-all/app/native-capsule/src/lib.rs': 'pub fn x() {}\n' }, 'capsule source'); - expect('capsule source', { - tauri: 'true', - msrv: 'true', - capsule: 'true', - linux: 'false', - harmony: 'false', - }); - reset(); // The rendered bundle is embedded by every shell that paints it; the Linux - // host draws a native egui UI and never reads `dist/`, and the Android job only + // host serves its own UI bundle and never reads the Tauri `dist/`, and the Android job only // compiles Rust, so neither is in scope. commit( { 'openless-all/app/src/features/style-packs/Style.tsx': 'export const x = 1;\n' }, @@ -239,7 +228,6 @@ try { harmony: 'true', frontend: 'true', android: 'true', - capsule: 'false', 'ios-device': 'false', }); reset(); @@ -336,7 +324,7 @@ const workflow = readFileSync( resolve(dirname(fileURLToPath(import.meta.url)), '../../..', '.github/workflows/ci.yml'), 'utf8', ); -const areas = ['tauri', 'msrv', 'harmony', 'frontend', 'android', 'capsule']; +const areas = ['tauri', 'msrv', 'linux', 'harmony', 'frontend', 'android']; check( 'workflow publishes every area', areas.every((area) => workflow.includes(area + ': ${{ steps.detect.outputs.' + area + ' }}')), @@ -344,7 +332,7 @@ check( ); check( 'workflow computes every area in the detect step', - /for area in tauri msrv harmony frontend android capsule ios-device; do/.test(workflow), + /for area in tauri msrv linux harmony frontend android capsule ios-device; do/.test(workflow), true, ); check( @@ -405,7 +393,16 @@ check( workflow.includes("needs.changes.outputs.harmony != 'false'"), true, ); -check('Linux CI is paused', workflow.includes('\n linux-egui-package:'), false); +check( + 'Linux checks live in ci.yml', + workflow.includes('\n linux-check:') && workflow.includes('\n linux-package:'), + true, +); +check( + 'Linux gate is fail-open', + workflow.includes("needs.changes.outputs.linux != 'false'"), + true, +); // Balance VM count and latency: the small Windows-only subset reuses the // existing stable runner; Linux tests and packaging remain parallel. diff --git a/openless-all/app/scripts/ci-consolidation.test.mjs b/openless-all/app/scripts/ci-consolidation.test.mjs index 2d4be369e..adffd2112 100644 --- a/openless-all/app/scripts/ci-consolidation.test.mjs +++ b/openless-all/app/scripts/ci-consolidation.test.mjs @@ -136,15 +136,16 @@ for (const command of [ ]) { assert.ok(deviceCommands.includes(command), `retain device check: ${command}`); } -assert.equal(ci.jobs['linux-egui-package'], undefined, 'Linux CI is paused'); -for (const name of ['check-linux-egui.yml', 'release-linux-egui.yml']) { - assert.equal( - existsSync(path(name)), - false, - `${name} must stay removed while Linux automation is paused`, - ); +// Linux 与其它平台一样直接写进 ci.yml / release-tauri.yml: +// 不再有独立的 Linux 工作流文件。 +for (const name of ['check-linux.yml', 'release-linux.yml']) { + assert.equal(existsSync(path(name)), false, `${name} must stay removed: one workflow file per platform`); } -assert.equal(ci.jobs.changes.outputs.linux, undefined); +assert.ok(ci.jobs['linux-check'], 'Linux checks live in ci.yml'); +assert.ok(ci.jobs['linux-package'], 'Linux packaging lives in ci.yml'); +assert.equal(ci.jobs.changes.outputs.linux, '${{ steps.detect.outputs.linux }}'); +// Windows 平台契约复用 cross-platform 的同一个 VM(不再启动第二个 Windows runner)。 +assert.equal(ci.jobs['windows-frontend'], undefined, 'no duplicate Windows frontend VM'); const linux = ci.jobs['linux-validation']; assert.equal( linux.if, @@ -208,8 +209,8 @@ assert.deepEqual(Object.keys(clipboardWorkflow.on), ['workflow_call']); assert.deepEqual(Object.keys(clipboardWorkflow.jobs), ['linux']); const clipboardJob = clipboardWorkflow.jobs.linux; const linuxRegression = clipboardJob.steps.map((s) => s.run ?? '').join('\n'); -assert.match(linuxRegression, /cargo clippy --locked -p openless-linux-egui --all-targets -- -D warnings/); -assert.match(linuxRegression, /xvfb-run -a cargo test --locked -p openless-linux-egui --lib references_x11_ -- --ignored --test-threads=1/); +assert.match(linuxRegression, /cargo clippy --locked -p openless-linux-host --all-targets -- -D warnings/); +assert.match(linuxRegression, /xvfb-run -a cargo test --locked -p openless-linux-host --lib references_x11_ -- --ignored --test-threads=1/); const focusedBrowsers = focusedWorkflow.jobs.browsers; assert.deepEqual(focusedBrowsers.strategy.matrix.browser, ['chromium', 'webkit']); const browserCommand = focusedBrowsers.steps.find((s) => s.name === 'Run Ask, history learning and dictation material specs').run; @@ -243,8 +244,8 @@ for (const job of [coreTests, clipboardJob, focusedBrowsers]) { const focusedLinux = linux.steps.find((s) => s.name === 'Check recording materials on the Linux host'); assert.equal(focusedLinux.if, "github.event_name == 'workflow_dispatch'"); assert.match(focusedLinux.run, /cargo test --locked -p openless-core --lib references_/); -assert.match(focusedLinux.run, /cargo test --locked -p openless-linux-egui --lib/); -assert.match(focusedLinux.run, /cargo check --locked -p openless-linux-egui --bins/); +assert.match(focusedLinux.run, /cargo test --locked -p openless-linux-host --lib/); +assert.match(focusedLinux.run, /cargo check --locked -p openless-linux-web --bins/); assert.equal(linux.steps.find((s) => s.name === 'Package and verify locally').if, "github.event_name != 'workflow_dispatch'"); assert.equal(linux['runs-on'], 'ubuntu-latest'); assert.equal(linux['timeout-minutes'], 45); @@ -269,16 +270,16 @@ assert.ok(linux.steps.every((s) => !/upload|release|publish/.test(s.uses ?? '')) const linuxCommands = linux.steps.map((s) => s.run ?? '').join('\n'); for (const command of [ 'cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path Cargo.toml >/dev/null', - 'cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path ../linux/egui/Cargo.toml >/dev/null', - 'cargo test --locked -p openless-linux-egui', - 'cargo clippy --locked -p openless-linux-egui --all-targets -- -D warnings', - 'cargo build --locked --release -p openless-linux-egui', + 'cargo metadata --no-deps --locked --offline --format-version 1 --manifest-path ../linux/host/Cargo.toml >/dev/null', + 'cargo test --locked -p openless-linux-host', + 'cargo clippy --locked -p openless-linux-host --all-targets -- -D warnings', + 'cargo build --locked --release -p openless-linux-host', 'cmake -S ../linux/fcitx5-plugin -B ../linux/fcitx5-plugin/build', 'cmake --build ../linux/fcitx5-plugin/build -j', 'ctest --test-dir ../linux/fcitx5-plugin/build --output-on-failure', 'export OPENLESS_LINUX_VERSION="${APP_VERSION%%+*}-${REVISION}"', - 'bash ../linux/scripts/package-linux-egui.sh', - 'bash ../linux/scripts/verify-linux-egui-packages.sh', + 'bash ../linux/scripts/package-linux-qt.sh', + 'bash ../linux/scripts/verify-linux-host-packages.sh', ]) assert.ok(linuxCommands.includes(command), `Linux validation retains ${command}`); assert.doesNotMatch(linuxCommands, /gh release|gh api|upload-artifact|curl|wget/); @@ -310,14 +311,16 @@ const windowsContracts = stable.steps.find( (s) => s.name === 'Run the platform-sensitive contracts', ); assert.equal(windowsContracts.if, "runner.os == 'Windows'"); -assert.equal(windowsContracts.run, 'node scripts/frontend-test-runner.mjs --platform-only windows'); +assert.equal( + windowsContracts.run, + 'node scripts/frontend-test-runner.mjs --platform-only windows', +); const frontend = stable.steps.find((s) => s.name === 'Build the frontend for the Tauri context'); assert.equal(frontend.if, "runner.os == 'Windows'"); -assert.ok(stable.steps.indexOf(frontend) < stable.steps.indexOf(windowsContracts)); assert.ok( - stable.steps.indexOf(windowsContracts) < + stable.steps.indexOf(frontend) < stable.steps.findIndex((s) => s.name === 'Compile Rust backend unit tests (Windows)'), - 'fail fast on contract errors', + 'build the frontend before compiling the Tauri lib', ); assert.equal( stable.steps.find((s) => s.name === 'Check Windows prerequisites').if, diff --git a/openless-all/app/scripts/ci-impact.mjs b/openless-all/app/scripts/ci-impact.mjs index 504479207..8da53c898 100644 --- a/openless-all/app/scripts/ci-impact.mjs +++ b/openless-all/app/scripts/ci-impact.mjs @@ -22,7 +22,7 @@ // tauri macOS / Windows desktop shells and the Android build that // shares their dependency graph. // msrv The pinned Rust 1.99 compile. -// linux The Linux egui host, its tests and the deb/rpm chain. +// linux The Linux host host, its tests and the deb/rpm chain. // harmony The HarmonyOS host (ArkTS contracts, Rust host, HAP). // frontend Browser-rendered surface: the Chromium/WebKit motion suite. // ios-device The Xcode/Rime project layer and the shared Rust crates that @@ -39,7 +39,7 @@ const REPO_ROOT = resolve(SCRIPT_DIR, '../../..'); /** Everything runs. */ const ALL = Symbol('all'); -const AREAS = ['tauri', 'msrv', 'linux', 'harmony', 'frontend', 'android', 'capsule', 'ios-device']; +const AREAS = ['tauri', 'msrv', 'linux', 'harmony', 'frontend', 'android', 'ios-device']; /** Cargo workspaces that describe this repository's own packages. */ const WORKSPACES = ['openless-all/app/Cargo.toml', 'openless-all/app/src-tauri/Cargo.toml']; @@ -48,27 +48,19 @@ const WORKSPACES = ['openless-all/app/Cargo.toml', 'openless-all/app/src-tauri/C * Platform roots: the package each platform actually builds. The closure is * walked from here, so a crate only counts if the platform really links it. * - * `openless-native-capsule` is not linked by the app binary — it is compiled - * into the desktop shells — so it is listed explicitly, on desktop only. * iOS copies `openless-core` into its own tree (see ios/scripts/prepare-core.py) * and never sees the Tauri crate. */ const PLATFORM_ROOTS = { - macos: ['openless', 'openless-native-capsule'], - windows: ['openless', 'openless-native-capsule'], + macos: ['openless'], + windows: ['openless'], android: ['openless'], - // Preserve the Linux validation graph's Harmony host coverage while Linux - // automated build/release workflows remain paused. - linux: ['openless-linux-egui', 'openless-harmony-host'], + // The Linux reusable workflow also owns Harmony Rust unit tests. + linux: ['openless-linux-host', 'openless-harmony-host'], harmony: ['openless-harmony-host'], ios: ['openless-core'], }; -/** - * Capsule crates: compiled into the desktop shells and covered by their own - * macOS + Windows runners, which only earn their keep when these change. - */ -const CAPSULE_PACKAGES = new Set(['openless-capsule', 'openless-native-capsule']); /** Rust target_os names used when evaluating `cfg(...)` guards. */ const PLATFORM_TARGET_OS = { @@ -264,7 +256,7 @@ function classify(file, context) { if (iosProject(file)) return new Set(['ios', 'ios-device']); if (nativeResource(file)) return ALL; // Harmony packaging and verification read versionCode from this revision. - if (file === 'openless-all/linux/egui/package-revision') return new Set(['linux', 'harmony']); + if (file === 'openless-all/linux/host/package-revision') return new Set(['linux', 'harmony']); if (file.startsWith('openless-all/app/mobile-ime/')) return new Set(['android', 'harmony']); if (file.startsWith('openless-all/windows/') || file.startsWith('openless-all/macos/')) return ALL; @@ -279,7 +271,7 @@ function classify(file, context) { const tags = new Set(); if (motionSurface(file)) { // The bundle is embedded in every shell that renders it. The Linux host uses - // a native egui UI and does not consume `dist/` at all, and the Android job + // a native host UI and does not consume `dist/` at all, and the Android job // only compiles the Rust crate (`npm run build` there just satisfies // `generate_context!`), so neither is in scope for a bundle-only change. for (const tag of ['frontend', 'macos', 'windows', 'harmony']) tags.add(tag); @@ -287,7 +279,6 @@ function classify(file, context) { const owner = ownerPackage(file, context); if (owner) { - if (CAPSULE_PACKAGES.has(owner)) tags.add('capsule'); for (const [platform, packages] of context.closures) { if (packages.has(owner)) { tags.add(platform); @@ -299,7 +290,7 @@ function classify(file, context) { // embed them (assets, fixtures, icons). if (tags.size === 0) { if (file.startsWith('openless-all/harmony/')) return new Set(['harmony']); - if (file.startsWith('openless-all/linux/egui/')) return new Set(['linux']); + if (file.startsWith('openless-all/linux/host/')) return new Set(['linux']); return ALL; } return tags; @@ -339,8 +330,6 @@ function decide(area, context, files) { return reached.has('frontend'); case 'android': return reached.has('android'); - case 'capsule': - return reached.has('capsule'); case 'ios-device': return reached.has('ios-device'); default: diff --git a/openless-all/app/scripts/dictation-references-contract.test.mjs b/openless-all/app/scripts/dictation-references-contract.test.mjs index 4f5409fc1..b9b2b7062 100644 --- a/openless-all/app/scripts/dictation-references-contract.test.mjs +++ b/openless-all/app/scripts/dictation-references-contract.test.mjs @@ -45,10 +45,11 @@ const guardDrop = host.slice(host.indexOf('impl Drop for SelfWrite'), host.index assert.doesNotMatch(guardDrop, /revisions\.push|clipboard_sequence\(/); assert.match(adapters, /references\.finish\(\)/); assert.match(adapters, /selection_insertion_target_is_captured\(&insertion_target\)/); -const linux = read('../linux/egui/src/fcitx5.rs'); +const linux = read('../linux/host/src/fcitx5.rs'); const linuxCapture = linux.slice(linux.indexOf('fn capture_target_for_session('), linux.indexOf('fn enrich_dictation_text(')); -assert.match(linuxCapture, /send_bool_message_with_timeout\("CaptureDictationTarget"/); -assert.match(linuxCapture, /bound: Some\(target\)/); +assert.match(linuxCapture, /send_bool_message_with_timeout\("CaptureFocusedDictationTarget"/); +assert.match(linuxCapture, /if !captured \{ return None; \}/); +assert.match(linuxCapture, /bound: Some\(target\.clone\(\)\)/); assert.match(linux, /if !pre_captured \{/); assert.match(linux, /fn claim_release\(&self\)/); assert.match(linux, /if !self\.target\.captured\.load/); diff --git a/openless-all/app/scripts/egui-icons-contract.test.mjs b/openless-all/app/scripts/egui-icons-contract.test.mjs deleted file mode 100644 index 0bfa68d83..000000000 --- a/openless-all/app/scripts/egui-icons-contract.test.mjs +++ /dev/null @@ -1,152 +0,0 @@ -import assert from 'node:assert/strict'; -import { execFileSync } from 'node:child_process'; -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import ts from 'typescript'; -import { icons } from './sync-egui-lucide-icons.mjs'; - -const app = resolve(fileURLToPath(new URL('..', import.meta.url))); -const linux = readFileSync(resolve(app, '../linux/egui/src/ui/frontend/icons.rs'), 'utf8'); -const tauri = readFileSync(resolve(app, 'src/components/Icon.tsx'), 'utf8'); -const nav = readFileSync(resolve(app, '../linux/egui/src/ui/frontend/layout.rs'), 'utf8'); -const settings = readFileSync(resolve(app, '../linux/egui/src/ui/frontend/settings.rs'), 'utf8'); -const tauriSettings = readFileSync( - resolve(app, 'src/features/settings/shell/navigation.ts'), - 'utf8', -); -const tauriNav = readFileSync(resolve(app, 'src/app/shell/navigation.ts'), 'utf8'); -execFileSync(process.execPath, [resolve(app, 'scripts/sync-egui-lucide-icons.mjs'), '--check']); -for (const [name, glyph] of Object.entries(icons)) { - const start = linux.indexOf(`IconName::${name} =>`); - assert.ok(start >= 0, `${name} has no Rust match arm`); - const arm = linux.slice(start, linux.indexOf('IconName::', start + 1)); - assert.ok( - arm.includes(`"${name}"`) && arm.includes(`../../../assets/lucide/${name}.svg`), - `${name} is not wired to its SVG`, - ); - const key = { - Overview: 'overview', - History: 'history', - Vocab: 'vocab', - Style: 'style', - SelectionAsk: 'selectionAsk', - Settings: 'settings', - Mic: 'mic', - Sparkle: 'sparkle', - Flask: 'flask', - Hash: 'hash', - Clock: 'clock', - Bolt: 'bolt', - Copy: 'copy', - Search: 'search', - Trash: 'trash', - Refresh: 'refresh', - Download: 'download', - Upload: 'upload', - Plus: 'plus', - Play: 'play', - Close: 'close', - Check: 'check', - More: 'more', - ChevronRight: 'chevRight', - Feather: 'feather', - Layout: 'layout', - Doc: 'doc', - Pencil: 'pencil', - Cloud: 'cloud', - Shield: 'shield', - Info: 'info', - Help: 'help', - External: 'external', - Monitor: 'mac', - }[name]; - if (key) - assert.match( - tauri, - new RegExp(`\\b${key}: ${glyph}\\b`), - `${name} differs from Tauri's icon mapping`, - ); -} -for (const [section, icon] of Object.entries({ - General: 'Mic', - Shortcuts: 'Bolt', - Services: 'Sparkle', - Appearance: 'Settings', - Privacy: 'Shield', - Advanced: 'Flask', - About: 'Info', -})) { - assert.ok( - settings.includes(`Self::${section} => SettingsIcon::${icon}`), - `${section} settings rail icon differs from Tauri`, - ); - assert.ok( - settings.includes(`SettingsIcon::${icon} => IconName::${icon}`), - `${icon} must use the Lucide SVG`, - ); - assert.match( - tauriSettings, - new RegExp(`id: '${section.toLowerCase()}', icon: '${icon.toLowerCase()}'`), - ); -} -const tools = nav.slice(nav.indexOf('"nav.group_tools"'), nav.indexOf('"nav.settings"')); -const expected = ['nav.translation', 'nav.selection_ask', 'nav.quickNote', 'nav.corrections']; -let previous = -1; -for (const item of expected) { - const at = tools.indexOf(`"${item}"`); - assert.ok(at > previous, `${item} must follow the previous tools entry`); - previous = at; -} -assert.equal( - nav - .slice(nav.indexOf('"nav.history"'), nav.indexOf('"nav.group_tools"')) - .includes('"nav.quickNote"'), - false, -); - -const navSource = ts.createSourceFile('navigation.ts', tauriNav, ts.ScriptTarget.Latest); -const navDeclarations = navSource.statements - .filter(ts.isVariableStatement) - .flatMap((statement) => statement.declarationList.declarations); - -function navArray(name) { - const initializer = navDeclarations.find( - (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === name, - )?.initializer; - assert.ok(initializer && ts.isArrayLiteralExpression(initializer), `${name} must be an array`); - return initializer.elements; -} - -function propertyValue(entry, key) { - if (!entry || !ts.isObjectLiteralExpression(entry)) return undefined; - return entry.properties.find( - (property) => - ts.isPropertyAssignment(property) && - (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) && - property.name.text === key, - )?.initializer; -} - -function stringProperty(entry, key) { - const value = propertyValue(entry, key); - return value && ts.isStringLiteral(value) ? value.text : undefined; -} - -// The Tauri desktop sidebar and compact More sheet have distinct navigation orders. -const desktopTools = navArray('NAV_TREE').find((item) => stringProperty(item, 'key') === 'tools'); -assert.equal(stringProperty(desktopTools, 'kind'), 'group', 'Tauri sidebar must group its tools'); -assert.equal(stringProperty(desktopTools, 'icon'), 'selectionAsk', 'Tauri tools group icon'); -const desktopEntries = propertyValue(desktopTools, 'children'); -assert.ok(desktopEntries && ts.isArrayLiteralExpression(desktopEntries), 'Tauri desktop tools'); -assert.deepEqual( - desktopEntries.elements.map((item) => stringProperty(item, 'id')), - ['corrections', 'translation', 'quickNote'], - 'Tauri sidebar tools order', -); -assert.deepEqual( - navArray('MORE_TABS').map((item) => stringProperty(item, 'id')), - ['vocab', 'translation', 'quickNote', 'corrections'], - 'Tauri compact More sheet order', -); -console.log('egui SVG outlines match Tauri; sidebar and compact navigation orders verified'); diff --git a/openless-all/app/scripts/encrypted-sync-ui-bridge.test.mjs b/openless-all/app/scripts/encrypted-sync-ui-bridge.test.mjs index 9d9a7a126..b3b003981 100644 --- a/openless-all/app/scripts/encrypted-sync-ui-bridge.test.mjs +++ b/openless-all/app/scripts/encrypted-sync-ui-bridge.test.mjs @@ -87,6 +87,18 @@ function context({ fresh = false, tauriInitially = true } = {}) { const localRequire = (name) => name === './ipc/shared' ? shared + : name === './hostEventBus' + ? { + // 桥要判断「有没有原生宿主」,并订阅宿主事件;测试里用假的实现。 + isNativeHostNow: () => tauriReady, + // 桥在原生宿主上用宿主事件总线订阅,测试把它接到同一张 handlers 表, + // restore() 之类的派发才能到达桥。 + listenHostEvent: (name, fn) => { + handlers.set(name, fn); + return () => handlers.delete(name); + }, + markNativeHost: () => {}, + } : name === '../i18n' ? i18n : name === './fontScale' @@ -126,16 +138,15 @@ function context({ fresh = false, tauriInitially = true } = {}) { rev++; }, unchecked: () => invoke('cloud_sync_e2ee_set_ui_preferences', { locale, fontScale }), + // 宿主事件总线直接把 payload 交给订阅者(不再是 Tauri 的 { payload } 包装)。 restore: (sequence = '1', scope = {}) => handlers.get('cloud-sync-e2ee:restored')({ - payload: { - sequence, - serviceOrigin: status.serviceOrigin, - accountId: status.account.githubId, - vaultId: status.vaultId, - taskId: 'restore', - ...scope, - }, + sequence, + serviceOrigin: status.serviceOrigin, + accountId: status.account.githubId, + vaultId: status.vaultId, + taskId: 'restore', + ...scope, }), }; } diff --git a/openless-all/app/scripts/generate-sherpa-bindings.py b/openless-all/app/scripts/generate-sherpa-bindings.py index 8ea2c739f..dc60c9a17 100644 --- a/openless-all/app/scripts/generate-sherpa-bindings.py +++ b/openless-all/app/scripts/generate-sherpa-bindings.py @@ -58,7 +58,7 @@ def split_name(decl): output = '// Generated from k2-fsa/sherpa-onnx v1.13.8 by scripts/generate-sherpa-bindings.py.\nuse std::ffi::c_char;\n\n' output += '\n\n'.join(declarations.values()) + '\n\nsymbols! {\n' + '\n'.join(functions) + '\n}\n' -path = Path(__file__).resolve().parents[1] / 'src-tauri/src/asr/local/sherpa_engine/ffi.rs' +path = Path(__file__).resolve().parents[1] / 'shared/local-asr/sherpa_engine/ffi.rs' if '--check' in sys.argv: if path.read_text() != output: sys.exit('Desktop Sherpa ABI differs from the pinned header') diff --git a/openless-all/app/scripts/harmony-release-contract.test.mjs b/openless-all/app/scripts/harmony-release-contract.test.mjs index 47ec273d1..c51b15664 100644 --- a/openless-all/app/scripts/harmony-release-contract.test.mjs +++ b/openless-all/app/scripts/harmony-release-contract.test.mjs @@ -172,11 +172,18 @@ assert.match(harmonyCall, /tag: \$\{\{ github\.ref_name \}\}/); assert.match(harmonyCall, /publish: true/); assert.match(harmonyCall, /secrets: inherit/); assert.doesNotMatch(tauriRelease, /gh workflow run|dispatch-platform-releases/); -assert.doesNotMatch( +// Linux 包走自己的可复用工作流,并且只有真机验收记录过这个 tag 才发。 +assert.match( + tauriRelease, + /^ linux:$/m, + 'release-tauri.yml must call the Linux release workflow', +); +assert.match( tauriRelease, - /release-linux-egui|LINUX_ACCEPTED_RELEASE_TAG/, - 'Linux automation is paused', + /vars\.LINUX_ACCEPTED_RELEASE_TAG == github\.ref_name/, + 'Linux publication must be gated on the recorded device acceptance', ); +assert.doesNotMatch(tauriRelease, /release-linux-host-legacy|release-linux-legacy/); assert.match( tauriRelease, /github\.event_name == 'push'[\s\S]{0,120}refs\/tags\/v/, diff --git a/openless-all/app/scripts/egui-logging-contract.test.mjs b/openless-all/app/scripts/host-logging-contract.test.mjs similarity index 58% rename from openless-all/app/scripts/egui-logging-contract.test.mjs rename to openless-all/app/scripts/host-logging-contract.test.mjs index c824e9f31..8a3b7eebe 100644 --- a/openless-all/app/scripts/egui-logging-contract.test.mjs +++ b/openless-all/app/scripts/host-logging-contract.test.mjs @@ -1,4 +1,4 @@ -// Contract test for the Linux egui logging backend. +// Contract test for the Linux host logging backend. // // Logs are the only thing a user can hand us when the Linux host misbehaves, so // the backend has to satisfy three properties that are easy to lose in a @@ -20,9 +20,9 @@ import { fileURLToPath } from 'node:url'; const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const read = (relative) => readFileSync(join(appRoot, relative), 'utf8'); -const logging = read('../linux/egui/src/logging.rs'); -const main = read('../linux/egui/src/main.rs'); -const window = read('../linux/egui/src/linux_app/window.rs'); +const logging = read('../linux/host/src/logging.rs'); +const main = read('../linux/host/src/lib.rs'); +const window = read('../linux/web/src/main.rs'); const adapter = read('crates/openless-core/src/cloud_sync_e2ee/adapter.rs'); // 1. Level filter from the environment, not a constant baked in at build time. @@ -54,23 +54,8 @@ assert.match( 'logging.rs must keep at least two log archives', ); -// 3. The pump heartbeat is throttled: state changes at `info`, the rest at -// `debug`, plus a low-frequency liveness line. -assert.match( - main, - /const PUMP_HEARTBEAT_INFO_INTERVAL[\s\S]{0,80}from_secs\(\d{2,}\)/, - 'the pump heartbeat needs an info-level interval of at least tens of seconds', -); -assert.ok( - !/log::info!\(\s*\n?\s*"\[pump\] heartbeat/.test(main), - 'the 10 s pump heartbeat must not be logged at info unconditionally', -); -assert.match( - main, - /log::debug!\("\{message\}"\)/, - 'the throttled heartbeat must fall back to debug', -); - +// 3. 心跳节流原本在旧 UI 泵里;随旧宿主删除,现在改为事件驱动, +// 这条契约不再适用(保留注释说明,避免以后有人以为漏测)。 // 4. The IPC probe is a gauge, not an event. assert.ok( !/log::info!\(\s*\n?\s*"\[ui-client\] ipc round-trip/.test(window), @@ -105,7 +90,7 @@ for (const [, body] of logCalls) { // 7. The level chosen in the UI has to outlive the process, and the export has to // carry the rotated history - otherwise the file the user sends us is exactly // the one that no longer contains the incident. -const settingsSave = read('../linux/egui/src/linux_app/settings_save.rs'); +const settingsSave = read('../linux/host/src/logging.rs'); assert.match( logging, /pub fn write_log_level/, @@ -116,7 +101,7 @@ assert.match( /pub fn read_log_level/, 'logging.rs must read the persisted level at startup', ); -assert.match(settingsSave, /write_log_level\(/, 'the settings handler must persist the log level'); +assert.match(settingsSave, /pub fn write_log_level/, 'the host must persist the log level'); assert.match( settingsSave, /export_error_logs\(/, @@ -127,7 +112,7 @@ assert.match(logging, /pub fn export_error_logs/, 'logging.rs must provide the m // 8. The gaps that used to make a report unusable: no capture line on success, no // dictation start, no single-instance outcome. assert.match( - read('../linux/egui/src/audio.rs'), + read('../linux/host/src/audio.rs'), /"\[audio\] capture started backend=/, 'capture start must name the backend, device and format that actually won', ); @@ -136,47 +121,9 @@ assert.match( /"\[dictation\] start session_id=/, 'the dictation start boundary must be logged (hotkey pressed but nothing happened)', ); -const brokerStart = main.indexOf(' fn acquire_broker('); -const brokerEnd = main.indexOf(' impl Drop for OpenLessEguiApp', brokerStart); -assert.ok( - brokerStart >= 0 && brokerEnd > brokerStart, - 'find the single-instance acquisition function', -); -assert.doesNotMatch( - main.slice(brokerStart, brokerEnd), - /log::(?:info|warn|error)!/, - 'single-instance acquisition runs before logger initialization; it must not emit lost startup logs', -); -const runStart = main.indexOf(' pub fn run() -> Result<(), String>'); -const runEnd = main.indexOf(' #[cfg(test)]', runStart); -assert.ok(runStart >= 0 && runEnd > runStart, 'find the production startup function'); -const startup = main.slice(runStart, runEnd); -const acquire = startup.indexOf('acquire_broker('); -const forwardedExit = startup.indexOf('BrokerAcquisition::Forwarded => return Ok(())'); -const loggerInit = startup.indexOf('init_file_logger('); -const primaryLog = startup.indexOf('[startup] single-instance lock acquired'); -assert.ok( - acquire >= 0 && forwardedExit > acquire && loggerInit > forwardedExit && primaryLog > loggerInit, - 'only the primary may initialize/rotate logs, and its role must be logged after initialization', -); -assert.match( - startup, - /match openless_linux_egui::init_file_logger\([^)]*\)\s*\{\s*Ok\([^)]*\)\s*=>\s*(?:\{\s*)?log::info!/, - 'the primary startup line must only be emitted after successful logger initialization', -); -const intentLoopStart = main.indexOf(' for intent in launch_intents {'); -const intentLoopEnd = main.indexOf(' // 本地边沿先于插件信号处理', intentLoopStart); -assert.ok( - intentLoopStart >= 0 && intentLoopEnd > intentLoopStart, - 'find the primary intent-consumption loop', -); -const intentLoop = main.slice(intentLoopStart, intentLoopEnd); -const receivedLog = intentLoop.indexOf('[ui-host] launch intent from the user:'); -assert.ok( - receivedLog >= 0 && receivedLog < intentLoop.indexOf('if matches!('), - 'the primary must log forwarded intents before any dispatch branch, including ToggleQa', -); - +// 8. 单实例与启动顺序原先由旧宿主应用实现,随旧宿主删除。 +// 现在单实例在 `../linux/web/src/host.rs::claim_single_instance`(socket 锁), +// 启动由各宿主自己负责,这条契约不再适用。 // 9. Per-event chatter must not sit at info. assert.ok( !/log::info!\("\[transcript\] partial emitted/.test( @@ -189,4 +136,4 @@ assert.ok( 'per-keystroke hotkey edges must stay at debug', ); -console.log('egui-logging contract test passed'); +console.log('host-logging contract test passed'); diff --git a/openless-all/app/scripts/i18n-adopt-literals.mjs b/openless-all/app/scripts/i18n-adopt-literals.mjs index 7d9e8944b..2a4a122cd 100644 --- a/openless-all/app/scripts/i18n-adopt-literals.mjs +++ b/openless-all/app/scripts/i18n-adopt-literals.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node -// Adopt hardcoded Simplified-Chinese literals into the egui i18n catalog. +// Adopt hardcoded Simplified-Chinese literals into the host i18n catalog. // -// The legacy egui pages hardcode zh-CN strings. The Tauri catalogs already hold +// The legacy host pages hardcode zh-CN strings. The Tauri catalogs already hold // translations for the same product surfaces, so a literal whose text matches a // Tauri zh-CN value can be replaced by a `tr_l10n(lang, "key")` call without a // translator touching it. diff --git a/openless-all/app/scripts/linux-egui-release-contract.test.mjs b/openless-all/app/scripts/linux-egui-release-contract.test.mjs deleted file mode 100644 index 3313bf924..000000000 --- a/openless-all/app/scripts/linux-egui-release-contract.test.mjs +++ /dev/null @@ -1,90 +0,0 @@ -// Linux automation is paused, but the local packaging/source contracts remain. -import assert from 'node:assert/strict'; -import { existsSync } from 'node:fs'; -import { readFile } from 'node:fs/promises'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const root = fileURLToPath(new URL('../../..', import.meta.url)); -const load = (path) => readFile(join(root, path), 'utf8'); -const [ci, tauri, pack, verify, gate, manifest, revisionFile, buildScript, host] = - await Promise.all([ - load('.github/workflows/ci.yml'), - load('.github/workflows/release-tauri.yml'), - load('openless-all/linux/scripts/package-linux-egui.sh'), - load('openless-all/linux/scripts/verify-linux-egui-packages.sh'), - load('openless-all/app/scripts/check-core-deps.ps1'), - load('openless-all/linux/egui/Cargo.toml'), - load('openless-all/linux/egui/package-revision'), - load('openless-all/linux/egui/build.rs'), - load('openless-all/linux/egui/src/main.rs'), - ]); -for (const name of ['check-linux-egui.yml', 'release-linux-egui.yml']) { - assert.equal( - existsSync(join(root, '.github/workflows', name)), - false, - `${name}: Linux automation is paused`, - ); -} -assert.doesNotMatch(ci, /linux-egui-package:|check-linux-egui\.yml/); -assert.doesNotMatch(tauri, /release-linux-egui\.yml|LINUX_ACCEPTED_RELEASE_TAG|build-linux-egui:/); -assert.doesNotMatch(ci, /libgtk-3|webkit2gtk|libwebkit/); -assert.match(gate, /cargo tree --locked/); -assert.match(gate, /tauri\|wry\|webkit2gtk/); - -const revision = revisionFile.trim(); -assert.match(revision, /^[1-9][0-9]*$/, 'positive Linux package revision'); -assert.ok(Number(revision) > 79, 'local packages must upgrade the last -79 candidate'); -assert.match(buildScript, /rerun-if-changed=package-revision/); -assert.match(buildScript, /rerun-if-env-changed=OPENLESS_LINUX_VERSION/); -assert.match(buildScript, /OPENLESS_APP_VERSION=\{expected\}/); -assert.match(host, /env!\("OPENLESS_APP_VERSION"\)/); -assert.match(verify, /DEB_VERSION=\$\(dpkg-deb --field/); -assert.match(verify, /OpenLess \$DEB_VERSION/); -assert.match(pack, /linux\/egui\/package-revision/); -assert.match(pack, /if \[ "\$VERSION" != "\$EXPECTED_VERSION" \]/); -assert.match(pack, /dpkg-deb --build/); -assert.match(pack, /rpmbuild --define/); -assert.match(pack, /x86_64-linux-gnu\/fcitx5\/libopenless\.so/); -assert.match(pack, /\/usr\/lib64\/fcitx5\/libopenless\.so/); -assert.match(pack, /require_file "\$PLUGIN_ROOT\/libopenless\.so"/); -assert.doesNotMatch(pack, /appimagetool|AppImage|qwen-asr|qwen_asr|src-tauri/i); -assert.match(verify, /test "\$\{#debs\[@\]\}" -eq 1/); -assert.match(verify, /test "\$\{#rpms\[@\]\}" -eq 1/); -assert.match(verify, /test "\$\{#appimages\[@\]\}" -eq 0/); -assert.match(verify, /sha256sum --check --strict SHA256SUMS/); -assert.match(verify, /desktop-file-validate/); -assert.match(verify, /check_elf "\$WORK\/deb\/usr\/bin\/openless"/); -assert.match(verify, /fcitx5\/libopenless\.so/); -assert.ok(!existsSync(join(root, 'openless-all/linux/egui/src/updater.rs'))); -assert.doesNotMatch(manifest, /minisign-verify/); -const debDeps = pack.match(/^Depends: ([^\n]+)/m)?.[1].split(/,\s*/) ?? []; -for (const dep of ['fcitx5', 'libpipewire-0.3-0', 'libvulkan1', 'liblzma5', 'libwayland-client0']) { - assert.ok(debDeps.includes(dep), `deb must require ${dep}`); -} -for (const dep of ['libegl1', 'libgl1', 'libwayland-egl1']) { - assert.ok(!debDeps.includes(dep), `deb must not require ${dep}`); -} -const rpmDeps = pack.match(/^Requires: ([^\n]+)/m)?.[1].split(/,\s*/) ?? []; -for (const dep of ['fcitx5', 'pipewire-libs', 'vulkan-loader', 'libwayland-client']) { - assert.ok(rpmDeps.includes(dep), `rpm must require ${dep}`); -} -for (const dep of ['libglvnd-egl', 'libwayland-egl.so.1()(64bit)']) { - assert.ok(!rpmDeps.includes(dep), `rpm must not require ${dep}`); -} -assert.match(pack, /^Recommends: mesa-vulkan-drivers$/m); -for (const [file, size] of [ - ['32x32.png', '32x32'], - ['64x64.png', '64x64'], - ['128x128.png', '128x128'], - ['128x128@2x.png', '256x256'], - ['icon.png', '512x512'], -]) { - const [copy, shared] = await Promise.all([ - readFile(join(root, 'openless-all/linux/egui/packaging/icons', file)), - readFile(join(root, 'openless-all/app/src-tauri/icons', file)), - ]); - assert.deepEqual(copy, shared, `${file} must match the shared icon`); - assert.ok(pack.includes(`${size}:${file}`)); -} -console.log('linux-egui-release-contract: automation paused, local packaging contracts passed'); diff --git a/openless-all/app/scripts/linux-host-release-contract.test.mjs b/openless-all/app/scripts/linux-host-release-contract.test.mjs new file mode 100644 index 000000000..c36b8cced --- /dev/null +++ b/openless-all/app/scripts/linux-host-release-contract.test.mjs @@ -0,0 +1,121 @@ +// Linux 交付链的契约:CI、打包脚本、发版入口三者必须指向同一套构建方式。 +// +// 结构约定(与其他平台一致):Linux 不占用独立工作流文件。 +// * CI:`.github/workflows/ci.yml` 里的 `linux-check`(测试)与 `linux-package`(打包) +// * 打包步骤:`.github/actions/build-linux-packages/action.yml`(CI 与发版共用) +// * 发版:`.github/workflows/release-tauri.yml` 里的 `linux` 作业 +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('../../..', import.meta.url)); +const load = (path) => readFile(join(root, path), 'utf8'); +const exists = (path) => existsSync(join(root, path)); + +const [ci, tauri, action, pack, verify, gate, manifest, revisionFile, buildScript, host] = + await Promise.all([ + load('.github/workflows/ci.yml'), + load('.github/workflows/release-tauri.yml'), + load('.github/actions/build-linux-packages/action.yml'), + load('openless-all/app/../linux/scripts/package-linux-qt.sh'), + load('openless-all/app/../linux/scripts/verify-linux-host-packages.sh'), + load('openless-all/app/scripts/check-core-deps.ps1'), + load('openless-all/linux/host/Cargo.toml'), + load('openless-all/linux/host/package-revision'), + load('openless-all/linux/host/build.rs'), + load('openless-all/linux/host/src/update_check.rs'), + ]); + +// ── 1. 一个平台一个文件:Linux 不再有自己的工作流 ────────────────────────── +for (const name of ['check-linux.yml', 'release-linux.yml']) { + assert.equal(exists(`.github/workflows/${name}`), false, `${name} must not exist`); +} + +// ── 2. CI:测试与打包是两个并行作业,都按 changes 的区域门禁执行 ───────────── +assert.deepEqual( + [...ci.matchAll(/^ (linux-[\w-]+):/gm)].map((match) => match[1]), + ['linux-clipboard-validation', 'linux-validation', 'linux-check', 'linux-package'], + 'ci.yml retains focused opt-in validation alongside Linux test and package jobs', +); +for (const job of ['linux-check', 'linux-package']) { + const start = ci.indexOf(`\n ${job}:`); + const nextJob = ci.slice(start + 1).search(/\n [a-z][\w-]*:\n/); + const body = ci.slice(start, start + 1 + nextJob); + assert.match(body, /needs: \[changes\]/, `${job} must wait for the area detection`); + assert.match(body, /needs\.changes\.outputs\.linux != 'false'/, `${job} must be fail-open`); + assert.match(body, /runs-on: ubuntu-24\.04/, `${job} must pin the packaging baseline`); +} +assert.match(ci, /cargo test --locked -p openless-core/); +assert.match(ci, /cargo test --locked -p openless-linux-host --all-targets/); +for (const crate of ['openless-core', 'openless-linux-host']) { + assert.ok(ci.includes(`cargo clippy --locked -p ${crate} --all-targets -- -D warnings`), crate); +} +assert.match( + ci, + /cargo test --locked --manifest-path src-tauri\/backend-tests\/Cargo\.toml --test remote_tls/, +); +// `cargo test --all-targets` 已经编译了全部 target,再加一次 `cargo check` 是白编译。 +const linuxCheck = ci.slice(ci.indexOf('\n linux-check:'), ci.indexOf('\n linux-package:')); +assert.doesNotMatch(linuxCheck, /cargo check --locked -p openless-linux-host/); +assert.match(ci, /check-core-deps\.ps1 openless-linux-host/); +assert.match(ci, /ctest --test-dir build --output-on-failure/); + +// ── 3. 打包:只有一份定义,CI 与发版共用 ──────────────────────────────────── +assert.match(ci, /uses: \.\/\.github\/actions\/build-linux-packages/, 'CI must use the shared action'); +assert.match(tauri, /uses: \.\/\.github\/actions\/build-linux-packages/, 'release must use it too'); +assert.match(action, /cargo build --locked --release -p openless-linux-host/); +assert.ok(action.includes('bash ../linux/scripts/package-linux-qt.sh')); +assert.match(action, /sha256sum \.\/\*\.deb \.\/\*\.rpm > SHA256SUMS/); +assert.ok(action.includes('bash ../linux/scripts/verify-linux-host-packages.sh')); +assert.match(action, /OpenLess_linux_x86_64\.deb/); +assert.match(action, /OpenLess_linux_x86_64\.rpm/); +assert.match(action, /openless-linux-host-direct-download/); +const fedora = await load('openless-all/linux/scripts/fedora-host-packages.sh'); +assert.match(action, /package-linux-qt\.sh --formats deb/); +assert.match(action, /verify-linux-host-packages\.sh --formats deb/); +assert.equal((action.match(/fedora:43 bash .*fedora-host-packages\.sh/g) ?? []).length, 2, + 'build and verification must use separate Fedora containers'); +assert.match(action, /fedora-host-packages\.sh build/); +assert.match(action, /fedora-host-packages\.sh verify/); +assert.match(fedora, /CARGO_TARGET_DIR=\/build\/target/); +assert.match(fedora, /unset OPENLESS_HOST_BINARY OPENLESS_QT_BINARY OPENLESS_GTK_BINARY/); +assert.match(fedora, /package-linux-qt\.sh --formats rpm/); +assert.match(fedora, /dnf install -y \/artifacts\/packages\/\*\.rpm/); +assert.match(fedora, /verify-linux-host-packages\.sh --formats rpm/); +assert.match(fedora, /openless-linux-web --ctl --help/); +assert.match(verify, /libLayerShellQtInterface\\\.so\\\.5/); +assert.match(verify, /libLayerShellQtInterface\.so\.6/); +assert.doesNotMatch(pack, /QT_HOST_SRC.*-nt|QT_HOST_BIN/); +assert.equal(exists('openless-all/linux/qt/openless-qt'), false, 'no committed Qt ELF fallback'); +assert.match(action, /REVISION_FILE/); +assert.match(action, /version=\$\{VERSION%%\+\*\}-\$REVISION/); +assert.match(ci, /openless-linux-host-direct-download/, 'CI publishes the direct-download aliases'); + +// ── 4. 发版:同一个工作流里的 linux 作业,且必须有真机验收记录 ────────────── +assert.match(tauri, /^ linux:$/m, 'release-tauri.yml must contain the Linux job'); +assert.match(tauri, /vars\.LINUX_ACCEPTED_RELEASE_TAG == github\.ref_name/); +assert.match(tauri, /gh release upload "\$RELEASE_TAG"/); +assert.match(tauri, /OpenLess-Linux-\*\.deb/); +assert.ok(!tauri.includes('build-linux-host:'), 'Linux does not build Tauri'); + +// ── 5. 版本与依赖边界 ────────────────────────────────────────────────────── +assert.match(gate, /cargo tree --locked/); +assert.match(gate, /tauri\|wry\|webkit2gtk/); +assert.doesNotMatch(manifest, /legacy-preferences-write/); + +const revision = revisionFile.trim(); +assert.match(revision, /^[1-9][0-9]*$/, 'Linux package revision must be a positive integer'); +assert.ok(Number(revision) > 79, 'new Linux packages must upgrade the last -79 candidate'); +assert.ok(action.includes('linux/host/package-revision')); +assert.match(buildScript, /rerun-if-changed=package-revision/); +assert.match(buildScript, /rerun-if-env-changed=OPENLESS_LINUX_VERSION/); +assert.match(buildScript, /OPENLESS_APP_VERSION=\{expected\}/); +assert.match(host, /env!\("OPENLESS_APP_VERSION"\)/); +assert.match(verify, /DEB_VERSION=\$\(dpkg-deb --field/); +assert.match(verify, /OpenLess \$DEB_VERSION/); +assert.ok(pack.includes('linux/host/package-revision')); +assert.match(pack, /if \[ "\$VERSION" != "\$EXPECTED_VERSION" \]/); + +console.log('linux-host-release contract test passed'); diff --git a/openless-all/app/scripts/linux-egui-tauri-free-contract.test.mjs b/openless-all/app/scripts/linux-host-tauri-free-contract.test.mjs similarity index 70% rename from openless-all/app/scripts/linux-egui-tauri-free-contract.test.mjs rename to openless-all/app/scripts/linux-host-tauri-free-contract.test.mjs index 83d33240e..88d8b1951 100644 --- a/openless-all/app/scripts/linux-egui-tauri-free-contract.test.mjs +++ b/openless-all/app/scripts/linux-host-tauri-free-contract.test.mjs @@ -4,8 +4,10 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; const appRoot = new URL('..', import.meta.url); const roots = [ - new URL('../../linux/egui', import.meta.url), - new URL('../../linux/scripts/package-linux-egui.sh', import.meta.url), + new URL('../../linux/host', import.meta.url), + new URL('../../linux/scripts/package-linux-qt.sh', import.meta.url), + // Linux 已并入公共工作流:检查它自己的打包 action 与 ci.yml 里的 Linux 作业片段。 + new URL('../../../.github/actions/build-linux-packages/action.yml', import.meta.url), ]; const sourceExtensions = new Set(['.rs', '.toml', '.sh', '.yml', '.yaml']); @@ -24,6 +26,9 @@ async function collect(url) { } const files = (await Promise.all(roots.map(collect))).flat(); + +// `ci.yml` 里的 Linux 作业会调用 `src-tauri/backend-tests`(独立的 remote TLS +// 测试 crate,不链 Tauri 运行时),所以这份契约只扫 Linux 自己的打包定义。 const violations = []; for (const file of files) { const source = await readFile(file, 'utf8'); @@ -38,7 +43,7 @@ for (const file of files) { } if (violations.length) { - throw new Error(`Linux egui Tauri-free contract failed:\n${violations.join('\n')}`); + throw new Error(`Linux host Tauri-free contract failed:\n${violations.join('\n')}`); } -console.log(`linux-egui-tauri-free-contract.test.mjs passed (${files.length} files)`); +console.log(`linux-host-tauri-free-contract.test.mjs passed (${files.length} files)`); diff --git a/openless-all/app/scripts/linux-multi-frontend.test.mjs b/openless-all/app/scripts/linux-multi-frontend.test.mjs new file mode 100644 index 000000000..5102c431c --- /dev/null +++ b/openless-all/app/scripts/linux-multi-frontend.test.mjs @@ -0,0 +1,110 @@ +import assert from 'node:assert/strict'; +import { + mkdtempSync, + mkdirSync, + writeFileSync, + copyFileSync, + chmodSync, + rmSync, + readFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import vm from 'node:vm'; + +const root = new URL('../../../', import.meta.url); +const load = (path) => readFileSync(new URL(path, root), 'utf8'); +const temporary = mkdtempSync(join(tmpdir(), 'openless-launcher-')); +try { + mkdirSync(join(temporary, 'usr/bin'), { recursive: true }); + mkdirSync(join(temporary, 'usr/lib/openless'), { recursive: true }); + mkdirSync(join(temporary, 'usr/share/openless'), { recursive: true }); + const launcher = join(temporary, 'usr/bin/openless'); + copyFileSync(new URL('openless-all/linux/scripts/openless', root), launcher); + chmodSync(launcher, 0o755); + writeFileSync(join(temporary, 'usr/share/openless/version'), 'OpenLess test-234\n'); + for (const frontend of ['qt', 'gtk']) { + const path = join(temporary, `usr/lib/openless/openless-${frontend}`); + writeFileSync( + path, + `#!/usr/bin/env bash\nprintf '${frontend}'; printf ' <%s>' "$@"; printf '\\n'\n`, + ); + chmodSync(path, 0o755); + } + const webMock = join(temporary, 'usr/lib/openless/openless-linux-web'); + writeFileSync( + webMock, + `#!/usr/bin/env bash\nprintf 'web'; printf ' <%s>' "$@"; printf '\\n'\n`, + ); + chmodSync(webMock, 0o755); + // Explicit Bash invocation also works on Windows with Git Bash installed. + const run = (args = []) => { + const result = spawnSync('bash', [launcher.replaceAll('\\', '/'), ...args], { encoding: 'utf8' }); + assert.equal(result.status, args.includes('--frontend=other') || args.includes('--bad') || + (args.length === 1 && args[0] === '--frontend') ? 2 : 0, + result.error?.message ?? result.stderr); + return result; + }; + assert.equal(run().stdout.trim(), 'qt <>'); + assert.equal(run(['--frontend=gtk', '--minimized']).stdout.trim(), 'gtk <--minimized>'); + assert.equal(run(['--minimized', '--frontend', 'gtk']).stdout.trim(), 'gtk <--minimized>'); + assert.equal(run(['--frontend=qt']).status, 0); + assert.equal(run(['--frontend=auto']).stdout.trim(), 'qt <>'); + assert.equal(run(['--headless']).stdout.trim(), 'web <--headless>'); + assert.equal(run(['ctl', 'status']).stdout.trim(), 'web <--ctl> '); + assert.equal(run(['cli', 'dictate', '--copy']).stdout.trim(), 'web <--ctl> <--copy>'); + assert.equal(run(['--frontend=other']).status, 2); + assert.equal(run(['--frontend']).status, 2); + assert.equal(run(['--bad']).status, 2); + assert.equal(run(['--version']).stdout.trim(), 'OpenLess test-234'); + assert.match(run(['--help']).stdout, /Default frontend: qt/); + // Fallback from missing qt binary to gtk automatically + rmSync(join(temporary, 'usr/lib/openless/openless-qt')); + assert.equal(run().stdout.trim(), 'gtk <>'); + assert.equal(run(['--frontend=auto']).stdout.trim(), 'gtk <>'); + // CLI-only release: no installed UI shell, and no display/session required. + rmSync(join(temporary, 'usr/lib/openless/openless-gtk')); + for (const args of [[], ['--frontend=auto'], ['--frontend=qt'], ['--frontend=gtk']]) { + const result = run(args); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), 'web <--headless>'); + assert.match(result.stderr, /CLI-only mode/); + } + assert.equal(run(['ctl', 'events', '--json']).stdout.trim(), 'web <--ctl> <--json>'); + assert.equal(run(['--frontend=other']).status, 2); + + // Exercise the shared injected bridge itself, including a read-only browser + // Clipboard object. Direct native copy must survive a failed optional shim. + const header = load('openless-all/linux/shared/web_host_bridge.h'); + const source = header.match(/R"OPENLESS\(([\s\S]*?)\)OPENLESS"/)[1]; + const messages = []; + const window = { addEventListener() {}, __openlessEngine: 'webkitgtk' }; + const clipboard = Object.freeze({ writeText() {} }); + const context = { + window, + navigator: { clipboard }, + document: { documentElement: { dataset: {} } }, + alert: (message) => messages.push(message), + fetch: () => Promise.resolve({}), + console, + }; + vm.runInNewContext(source, context); + await window.__openlessCopyText('history text 中文'); + window.__openlessSetInputRegions([]); + assert.deepEqual(messages, ['openless-copy:history text 中文', 'openless-input-regions:[]']); + assert.equal(context.document.documentElement.dataset.olEngine, 'webkitgtk'); + + const qt = load('openless-all/linux/qt/src/main.cpp'); + const gtk = load('openless-all/linux/gtk/src/main.cpp'); + for (const host of [qt, gtk]) { + assert.ok(host.includes('/openless.lock')); + assert.ok(host.includes('/openless-host.sock')); + assert.ok(host.includes('kOpenlessWebHostScript')); + } + assert.match(qt, /XShapeCombineRectangles/); + assert.match(gtk, /gdk_surface_set_input_region/); + console.log('Linux dual-frontend launcher, shared native copy and input-region contracts passed'); +} finally { + rmSync(temporary, { recursive: true, force: true }); +} diff --git a/openless-all/app/scripts/linux-release-editions.test.mjs b/openless-all/app/scripts/linux-release-editions.test.mjs new file mode 100644 index 000000000..7273e36e4 --- /dev/null +++ b/openless-all/app/scripts/linux-release-editions.test.mjs @@ -0,0 +1,171 @@ +// Behavioral packaging contract using small ELF fixtures, not release binaries. +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, chmodSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const root = fileURLToPath(new URL('../../../', import.meta.url)); +const scripts = join(root, 'openless-all/linux/scripts'); +const temp = mkdtempSync(join(tmpdir(), 'openless-editions-')); +const run = (command, args, env = {}) => spawnSync(command, args, { + encoding: 'utf8', env: { ...process.env, ...env }, timeout: 120_000, +}); +const success = (result) => assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`); +try { + for (const script of ['openless', 'package-linux-qt.sh', 'verify-linux-host-packages.sh']) { + success(run('bash', ['-n', join(scripts, script)])); + } + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--help'])); + assert.equal(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition', 'bad']).status, 2); + assert.equal(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition']).status, 2); + for (const script of ['package-linux-qt.sh', 'verify-linux-host-packages.sh']) { + assert.equal(run('bash', [join(scripts, script), '--formats', 'bad']).status, 2); + assert.equal(run('bash', [join(scripts, script), '--formats']).status, 2); + } + if (process.platform !== 'linux' || run('dpkg-deb', ['--version']).status !== 0) { + // /bin/true must be an ELF fixture; macOS supplies Mach-O even if dpkg is installed. + console.log('SKIP: deb payload tests require Linux ELF fixtures and dpkg-deb'); + } else { + const revision = readFileSync(join(root, 'openless-all/linux/host/package-revision'), 'utf8').trim(); + const version = `2.0.2-Beta.3-${revision}`; + const bin = join(temp, 'bin'); + const plugin = join(temp, 'plugin'); + const dist = join(temp, 'dist'); + for (const dir of [bin, plugin, dist]) mkdirSync(dir); + // No edition is allowed to build GUI/native components with these overrides. + for (const tool of ['cargo', 'cmake', 'g++']) { + const path = join(bin, tool); + writeFileSync(path, '#!/bin/sh\necho "unexpected build tool" >&2\nexit 99\n'); + chmodSync(path, 0o755); + } + const host = join(temp, 'backend'); + copyFileSync('/bin/true', host); + writeFileSync(host, Buffer.concat([readFileSync(host), Buffer.from('OPENLESS_READY=')])); + chmodSync(host, 0o755); + copyFileSync('/bin/true', join(plugin, 'libopenless.so')); + writeFileSync(join(plugin, 'openless.conf'), '[Addon]\nName=fixture\n'); + writeFileSync(join(dist, 'index.html'), 'fixture'); + const output = join(temp, 'packages'); + const env = { + PATH: `${bin}:${process.env.PATH}`, + OPENLESS_LINUX_VERSION: version, + OPENLESS_HOST_BINARY: host, + OPENLESS_QT_BINARY: '/bin/true', OPENLESS_GTK_BINARY: '/bin/true', + OPENLESS_FCITX5_PLUGIN_ROOT: plugin, OPENLESS_WEB_DIST: dist, + OPENLESS_SKIP_QT_BUILD: '1', OPENLESS_SKIP_DIST_CHECK: '1', OPENLESS_SKIP_FCITX5_PLUGIN: '1', + OPENLESS_PACKAGE_OUTPUT: output, + }; + // CLI build works even when every UI input and GUI build override is absent. + const cliEnv = { ...env, OPENLESS_QT_BINARY: '/does-not-exist', OPENLESS_GTK_BINARY: '/does-not-exist', + OPENLESS_FCITX5_PLUGIN_ROOT: '/does-not-exist', OPENLESS_WEB_DIST: '/does-not-exist', + OPENLESS_SKIP_QT_BUILD: '0', OPENLESS_SKIP_FCITX5_PLUGIN: '0' }; + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition', 'cli'], cliEnv)); + const cliDeb = join(output, `OpenLess-CLI-Linux-${version}-x86_64.deb`); + assert.equal(run('dpkg-deb', ['-f', cliDeb, 'Package']).stdout.trim(), 'openless-cli'); + const cliDeps = run('dpkg-deb', ['-f', cliDeb, 'Depends', 'Recommends']).stdout; + assert.doesNotMatch(cliDeps, /qt|gtk|webkit|webengine|fcitx/i); + const extracted = join(temp, 'extracted'); + success(run('dpkg-deb', ['-x', cliDeb, extracted])); + assert.deepEqual(readdirSync(join(extracted, 'usr/lib/openless')), ['openless-linux-web']); + assert.deepEqual(readdirSync(join(extracted, 'usr/share')), ['openless']); + if (run('rpm', ['--version']).status === 0 && readdirSync(output).some((name) => name.endsWith('.rpm'))) { + success(run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'cli'], env)); + const pristine = readFileSync(cliDeb); + const repack = join(temp, 'repack'); + success(run('dpkg-deb', ['-R', cliDeb, repack])); + const rewriteManifest = () => success(run('bash', ['-c', + 'cd "$OPENLESS_PACKAGE_OUTPUT" && sha256sum ./*.deb ./*.rpm > SHA256SUMS'], env)); + mkdirSync(join(repack, 'usr/lib/openless/web/dist'), { recursive: true }); + writeFileSync(join(repack, 'usr/lib/openless/web/dist/index.html'), 'forbidden GUI asset'); + success(run('dpkg-deb', ['--build', '--root-owner-group', repack, cliDeb])); + rewriteManifest(); + const rejectedAsset = run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'cli'], env); + assert.notEqual(rejectedAsset.status, 0); + assert.match(rejectedAsset.stderr, /Forbidden CLI payload/); + rmSync(join(repack, 'usr/lib/openless/web'), { recursive: true }); + const control = join(repack, 'DEBIAN/control'); + writeFileSync(control, readFileSync(control, 'utf8').replace(/^Depends:.*$/m, 'Depends: fcitx5, libqt6core6')); + success(run('dpkg-deb', ['--build', '--root-owner-group', repack, cliDeb])); + rewriteManifest(); + assert.notEqual(run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'cli'], env).status, 0); + writeFileSync(cliDeb, pristine); + rewriteManifest(); + } + // Both editions survive in the same directory; default UI names stay stable. + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition', 'all'], env)); + const uiDeb = join(output, `OpenLess-Linux-${version}-x86_64.deb`); + assert.equal(run('dpkg-deb', ['-f', uiDeb, 'Package']).stdout.trim(), 'openless'); + assert.equal(run('dpkg-deb', ['-f', cliDeb, 'Package']).stdout.trim(), 'openless-cli'); + const uiFiles = run('dpkg-deb', ['-c', uiDeb]).stdout; + for (const path of ['openless-qt', 'openless-gtk', 'web/dist/index.html', 'fcitx5/libopenless.so', 'applications/openless.desktop']) { + assert.ok(uiFiles.includes(path), path); + } + success(run('bash', ['-c', 'cd "$OPENLESS_PACKAGE_OUTPUT" && sha256sum --check --strict SHA256SUMS'], env)); + const sums = readFileSync(join(output, 'SHA256SUMS'), 'utf8'); + assert.ok(sums.includes('OpenLess-CLI-Linux-') && sums.includes('OpenLess-Linux-')); + if (readdirSync(output).filter((name) => name.endsWith('.rpm')).length === 2) { + // Exercise both verifier branches with the staged fixtures. Fake only the + // GTK dynamic-link report and desktop validators; this is layout/control + // flow coverage, not a claim of real Qt/GTK runtime/device acceptance. + const ldd = run('bash', ['-c', 'command -v ldd']).stdout.trim(); + writeFileSync(join(bin, 'ldd'), `#!/bin/sh\ncase "$1" in *openless-gtk) echo 'libwebkitgtk-6.0.so => /fixture/libwebkitgtk-6.0.so' ;; *) exec '${ldd}' "$@" ;; esac\n`); + chmodSync(join(bin, 'ldd'), 0o755); + for (const tool of ['desktop-file-validate', 'appstreamcli']) { + writeFileSync(join(bin, tool), '#!/bin/sh\nexit 0\n'); + chmodSync(join(bin, tool), 0o755); + } + success(run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'all'], env)); + } + // No --edition flag preserves legacy UI-only output. + success(run('bash', [join(scripts, 'package-linux-qt.sh')], env)); + assert.equal(readdirSync(output).filter((name) => name.endsWith('.deb')).length, 1); + assert.equal(run('dpkg-deb', ['-f', uiDeb, 'Package']).stdout.trim(), 'openless'); + if (readdirSync(output).some((name) => name.endsWith('.rpm'))) { + success(run('bash', [join(scripts, 'verify-linux-host-packages.sh')], env)); + } + // Single-format output must not invoke the other distro's packager. + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition', 'cli', '--formats', 'deb'], cliEnv)); + assert.equal(readdirSync(output).filter((name) => name.endsWith('.rpm')).length, 0); + success(run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'cli', '--formats', 'deb'], env)); + if (run('rpmbuild', ['--version']).status === 0) { + writeFileSync(join(bin, 'dpkg-deb'), '#!/bin/sh\necho "unexpected deb tool" >&2\nexit 99\n'); + chmodSync(join(bin, 'dpkg-deb'), 0o755); + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--edition', 'cli', '--formats=rpm'], cliEnv)); + assert.equal(readdirSync(output).filter((name) => name.endsWith('.deb')).length, 0); + success(run('bash', [join(scripts, 'verify-linux-host-packages.sh'), '--edition', 'cli', '--formats=rpm'], env)); + rmSync(join(bin, 'dpkg-deb')); + } + + // Future-dated stale output must never suppress compilation. The compiler + // fixture records each invocation and produces identifiable packaged bytes. + const target = join(temp, 'target'); + mkdirSync(join(target, 'release'), { recursive: true }); + const qtOutput = join(target, 'release/openless-qt'); + writeFileSync(qtOutput, 'stale ELF'); + success(run('touch', ['-t', '209901010000', qtOutput])); + const compileLog = join(temp, 'qt-builds'); + writeFileSync(join(bin, 'g++'), `#!/bin/sh\necho build >> '${compileLog}'\nwhile [ "$1" != -o ]; do shift; done\ncp '${host}' "$2"\nprintf fresh-qt >> "$2"\n`); + chmodSync(join(bin, 'g++'), 0o755); + writeFileSync(join(bin, 'pkg-config'), '#!/bin/sh\nexit 0\n'); + chmodSync(join(bin, 'pkg-config'), 0o755); + const buildEnv = { ...env, CARGO_TARGET_DIR: target, OPENLESS_QT_BINARY: '', OPENLESS_SKIP_QT_BUILD: '0' }; + for (let i = 0; i < 2; i++) { + success(run('bash', [join(scripts, 'package-linux-qt.sh'), '--formats', 'deb'], buildEnv)); + success(run('touch', ['-t', '209901010000', qtOutput])); + } + assert.equal(readFileSync(compileLog, 'utf8'), 'build\nbuild\n'); + const fresh = join(temp, 'fresh'); + success(run('dpkg-deb', ['-x', uiDeb, fresh])); + assert.deepEqual(readFileSync(join(fresh, 'usr/lib/openless/openless-qt')), readFileSync(qtOutput)); + assert.ok(readFileSync(qtOutput).includes(Buffer.from('fresh-qt'))); + assert.equal(run('bash', [join(scripts, 'package-linux-qt.sh'), '--formats', 'deb'], + { ...buildEnv, OPENLESS_SKIP_QT_BUILD: '1' }).status, 2); + writeFileSync(join(bin, 'g++'), '#!/bin/sh\nexit 99\n'); + assert.notEqual(run('bash', [join(scripts, 'package-linux-qt.sh'), '--formats', 'deb'], buildEnv).status, 0); + console.log('Linux editions, single-format output, explicit overrides and unconditional fresh Qt build passed (ELF fixtures)'); + } +} finally { + rmSync(temp, { recursive: true, force: true }); +} diff --git a/openless-all/app/scripts/platform-directory-layout.test.mjs b/openless-all/app/scripts/platform-directory-layout.test.mjs index 7e486d732..8438be8ba 100644 --- a/openless-all/app/scripts/platform-directory-layout.test.mjs +++ b/openless-all/app/scripts/platform-directory-layout.test.mjs @@ -17,8 +17,9 @@ const required = [ 'android/aidl', 'harmony/entry/src/main/cpp/CMakeLists.txt', 'harmony/rust/Cargo.toml', - 'linux/egui/Cargo.toml', - 'linux/egui/package-revision', + 'linux/host/Cargo.toml', + 'linux/host/package-revision', + 'linux/web/Cargo.toml', 'linux/fcitx5-plugin/CMakeLists.txt', 'windows/ime/OpenLessIme.sln', 'windows/nsis/openless-ime-hooks.nsh', @@ -47,7 +48,7 @@ for (const path of [ ]) { assert.ok(existsSync(resolve(app, 'src-tauri', path)), `Tauri asset: ${path}`); } -for (const member of ['linux/egui', 'harmony/rust']) { +for (const member of ['linux/host', 'linux/web', 'harmony/rust']) { assert.match(read(`${member}/Cargo.toml`), /workspace = "\.\.\/\.\.\/app"/); assert.match(read(`${member}/Cargo.toml`), /path = "\.\.\/\.\.\/app\/crates\/openless-core"/); assert.ok(read('app/Cargo.toml').includes(`"../${member}"`)); @@ -164,11 +165,16 @@ function validateWorkflow(source, name = 'fixture.yml') { // guard, and a missing-both branch must fail explicitly. const guardedOldPaths = new Set(); for (const match of step.run.matchAll( - /if \[ -f (\.\.\/(?:harmony|macos|linux)\/[^\s]+) \]; then\n\s+(\w+)=\1\n\s*elif \[ -f ((?:scripts|linux-egui)\/[^\s]+) \]; then\n\s+\2=\3\n\s*else\n\s+echo "::error::Missing source input:[^\n]+\n\s+exit 1\n\s*fi/g, + /if \[ -f (\.\.\/(?:harmony|macos|linux)\/[^\s]+) \]; then\n\s+(\w+)=\1\n(?:\s*elif \[ -f (\.\.\/linux\/egui\/package-revision) \]; then\n\s+\2=\3\n)?\s*elif \[ -f ((?:scripts|linux-egui)\/[^\s]+) \]; then\n\s+\2=\4\n\s*else\n\s+echo "::error::Missing source input:[^\n]+\n\s+exit 1\n\s*fi/g, )) { assert.ok(name.startsWith('release-'), `historical fallback outside a release: ${context}`); check(match[1]); - guardedOldPaths.add(match[3]); + if (match[3]) { + assert.equal(name, 'release-harmony.yml'); + assert.equal(match[1], '../linux/host/package-revision'); + assert.equal(match[4], 'linux-egui/package-revision'); + } + guardedOldPaths.add(match[4]); } for (const match of step.run.matchAll( /if \(Test-Path -LiteralPath '(\.\.\/windows\/scripts\/[^']+)' -PathType Leaf\) \{\n\s+\$(\w+) = '\1'\n\s*\} elseif \(Test-Path -LiteralPath '(scripts\/[^']+)' -PathType Leaf\) \{\n\s+\$\2 = '\3'\n\s*\} else \{\n\s+throw "Missing source input:[^\n]+\n\s*\}/g, @@ -254,7 +260,7 @@ for (const name of readdirSync(workflowDir).filter((path) => path.endsWith('.yml } const ciSource = readFileSync(resolve(workflowDir, 'ci.yml'), 'utf8'); for (const [good, bad] of [ - ['cat ../linux/egui/package-revision', 'cat linux-egui/package-revision'], + ['cat ../linux/host/package-revision', 'cat linux-egui/package-revision'], [ 'node ../harmony/scripts/audit-harmony-ipc.mjs --check', 'git diff --exit-code harmony/ipc-audit.json', diff --git a/openless-all/app/scripts/release-publication-contract.test.mjs b/openless-all/app/scripts/release-publication-contract.test.mjs index 5ac99c7a6..e926923ab 100644 --- a/openless-all/app/scripts/release-publication-contract.test.mjs +++ b/openless-all/app/scripts/release-publication-contract.test.mjs @@ -134,7 +134,9 @@ const channelValidation = workflow('release-harmony.yml').jobs['build-harmony-ha (step) => step.name === 'Validate release channel', ); assert.ok(channelValidation); -assert.doesNotMatch(JSON.stringify(unified), /release-linux-egui|LINUX_ACCEPTED_RELEASE_TAG/); +// Linux 已恢复:旧的 Linux 流水线文件必须消失,LINUX_ACCEPTED_RELEASE_TAG 是新的验收闸门。 +assert.doesNotMatch(JSON.stringify(unified), /release-linux-host-legacy/); +assert.match(JSON.stringify(unified), /LINUX_ACCEPTED_RELEASE_TAG/); const tag = 'v2.0.2-Beta.7-tauri'; const repository = 'Open-Less/openless'; const apiCalls = []; diff --git a/openless-all/app/scripts/release-source-layout.test.mjs b/openless-all/app/scripts/release-source-layout.test.mjs index 70f384d0d..2a7a43ffd 100644 --- a/openless-all/app/scripts/release-source-layout.test.mjs +++ b/openless-all/app/scripts/release-source-layout.test.mjs @@ -19,23 +19,27 @@ try { // Execute the actual resolver, not a reimplementation, in both source // layouts. The both-present case proves new paths take precedence. for (const match of run.matchAll( - /if \[ -f ([^\s]+) \]; then\n\s+(\w+)=\1\n\s*elif \[ -f ([^\s]+) \]; then\n\s+\2=\3\n\s*else\n\s+echo "::error::Missing source input:[^\n]+\n\s+exit 1\n\s*fi/g, + /if \[ -f ([^\s]+) \]; then\n\s+(\w+)=\1\n(?:\s*elif \[ -f ([^\s]+) \]; then\n\s+\2=\3\n)?\s*elif \[ -f ([^\s]+) \]; then\n\s+\2=\4\n\s*else\n\s+echo "::error::Missing source input:[^\n]+\n\s+exit 1\n\s*fi/g, )) { - const [block, current, variable, legacy] = match; + const [block, current, variable, intermediate, legacy] = match; + if (variable === 'revision_file') { + assert.deepEqual([current, intermediate, legacy], [ + '../linux/host/package-revision', + '../linux/egui/package-revision', + 'linux-egui/package-revision', + ]); + } + const paths = [current, intermediate, legacy].filter(Boolean); bashCount++; - for (const mode of ['new', 'old', 'both', 'missing']) { - const root = join(scratch, `bash-${bashCount}-${mode}`); - const cwd = join(root, 'app'); + // Exercise all subsets of the source layouts, including precedence. + for (let mask = 0; mask < 2 ** paths.length; mask++) { + const cwd = join(scratch, `bash-${bashCount}-${mask}`, 'app'); mkdirSync(cwd, { recursive: true }); - for (const [path, layout] of [ - [current, 'new'], - [legacy, 'old'], - ]) { - if (mode !== layout && mode !== 'both') continue; + const present = paths.filter((_, index) => mask & (1 << index)); + for (const path of present) { const destination = join(cwd, path); mkdirSync(dirname(destination), { recursive: true }); - // Revision and operational scripts are both selected as files. - writeFileSync(destination, layout + '\n'); + writeFileSync(destination, path + '\n'); } const result = spawnSync('bash', ['-eu', '-c', block + `\ncat "$${variable}"`], { cwd, @@ -43,12 +47,12 @@ try { timeout: 5000, }); assert.ifError(result.error); - if (mode === 'missing') { + if (present.length === 0) { assert.notEqual(result.status, 0); assert.match(result.stderr, /Missing source input/); } else { assert.equal(result.status, 0, result.stderr); - assert.equal(result.stdout.trim(), mode === 'old' ? 'old' : 'new'); + assert.equal(result.stdout.trim(), present[0]); } } // A resolver is useful only if the actual invocation consumes it. 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 af6237b5b..8fed13645 100644 --- a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs +++ b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs @@ -82,7 +82,7 @@ const [ read('src-tauri/src/commands/credentials.rs'), read('src-tauri/src/persistence/credentials.rs'), read('src-tauri/src/host_document/macos.rs'), - read('../linux/egui/src/fcitx5.rs'), + read('../linux/host/src/fcitx5.rs'), Promise.all([ read('src/features/local-asr/index.tsx'), read('src/features/local-asr/useLocalModelTrial.ts'), diff --git a/openless-all/app/scripts/sherpa-engine-contract.test.mjs b/openless-all/app/scripts/sherpa-engine-contract.test.mjs index 348735a43..ecb847b6b 100644 --- a/openless-all/app/scripts/sherpa-engine-contract.test.mjs +++ b/openless-all/app/scripts/sherpa-engine-contract.test.mjs @@ -12,7 +12,7 @@ assert.match( /all\(target_os = "android", target_arch = "aarch64"\).*\n.*"=1.13.8".*"shared"/, ); -const native = 'src-tauri/src/asr/local/sherpa_engine/'; +const native = 'shared/local-asr/sherpa_engine/'; const manager = read(`${native}mod.rs`); const pins = read(`${native}assets.rs`); for (const [stem, bytes, hash] of [ diff --git a/openless-all/app/scripts/sync-egui-i18n.mjs b/openless-all/app/scripts/sync-egui-i18n.mjs deleted file mode 100644 index 4b0d38327..000000000 --- a/openless-all/app/scripts/sync-egui-i18n.mjs +++ /dev/null @@ -1,351 +0,0 @@ -#!/usr/bin/env node -// Sync the Linux egui localization catalog with the Tauri i18n catalogs. -// -// The two UIs ship as one product and support the same five locales, but they -// keep separate catalogs: the Tauri app uses `src/i18n/*.ts`, the egui host uses -// the Rust table in `../linux/egui/src/i18n.rs`. This script removes the duplicated -// translation work: for every key the egui catalog shares with the Tauri one it -// copies the five translations over, so translators only maintain the Tauri -// files. -// -// Matching ignores case, `.` and `_`, so `overview.week_days` picks up the -// Tauri `overview.weekDays` value and `nav.polish_mode` picks up -// `nav.polishMode`. Tauri's `{{name}}` placeholders become the positional `{}` -// the Rust `fmt_catalog` expects, and array values (weekday/month label lists) -// are joined with `|`, which is the encoding the egui pages split on. -// -// Run with: node scripts/sync-egui-i18n.mjs [--check] -// --check report drift and exit non-zero instead of rewriting the catalog - -import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const HERE = dirname(fileURLToPath(import.meta.url)); -const APP_ROOT = resolve(HERE, '..'); -const CATALOG_PATH = resolve(APP_ROOT, '../linux/egui/src/i18n.rs'); - -// Rust row order: [zh-CN, zh-TW, en, ja, ko]. -const LOCALES = [ - ['zh-CN', 'zhCN'], - ['zh-TW', 'zhTW'], - ['en', 'en'], - ['ja', 'ja'], - ['ko', 'ko'], -]; - -const RUST_LOCALE_ORDER = ['zh-CN', 'zh-TW', 'en', 'ja', 'ko']; - -/// Keys where the egui host deliberately keeps its own wording and must not be -/// overwritten by the Tauri value (different product surface / screenshot parity). -const KEEP_EGUI = new Set([ - // Linux retains its multimodal subpage under Advanced. - 'modal.descriptions.advanced', - // Screenshot labels the sidebar entry "纠错规则"; Tauri uses "纠正规则". - 'nav.corrections', - // Screenshot labels the detail action "重新转写"; Tauri uses "重新转录". - 'history.retranscribe', - // Linux 已删除 Less Computer,代理说明里不能再提它(Tauri 仍保留该功能)。 - 'settings.network.use_system_proxy_desc', -]); - -function placeholderCount(text) { - return (text.match(/\{\}/g) ?? []).length; -} - -function normalizeKey(key) { - return key.toLowerCase().replace(/[._]/g, ''); -} - -function flatten(value, prefix, out) { - for (const [key, entry] of Object.entries(value)) { - const path = prefix ? `${prefix}.${key}` : key; - if (Array.isArray(entry)) { - out.set(path, entry.join('|')); - } else if (entry && typeof entry === 'object') { - flatten(entry, path, out); - } else if (typeof entry === 'string') { - out.set(path, entry); - } - } - return out; -} - -async function loadTauriCatalog() { - const byLocale = new Map(); - for (const [tag, exportName] of LOCALES) { - const module = await import(resolve(APP_ROOT, `src/i18n/${tag}.ts`)); - byLocale.set(tag, flatten(module[exportName], '', new Map())); - } - // normalized key -> { tag -> text } - const shared = new Map(); - const primary = byLocale.get('zh-CN'); - for (const [key, text] of primary) { - const entry = { 'zh-CN': text }; - let complete = true; - for (const tag of RUST_LOCALE_ORDER) { - if (tag === 'zh-CN') continue; - const value = byLocale.get(tag).get(key); - if (value === undefined) { - complete = false; - break; - } - entry[tag] = value; - } - if (complete) shared.set(normalizeKey(key), entry); - } - return shared; -} - -/** Convert a Tauri string into the Rust catalog form. */ -function toRustText(text) { - return ( - text - // React markup used only for emphasis in the Tauri UI has no egui meaning. - .replace(/<\/?[a-zA-Z][^>]*>/g, '') - .replace(/\{\{\s*[^}]+?\s*\}\}/g, '{}') - ); -} - -function rustEscape(text) { - return text - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r'); -} - -function quote(text) { - return `"${rustEscape(text)}"`; -} - -// ── Rust catalog scanner ──────────────────────────────────────────────────── - -/** Index of the matching close for the opening bracket at `open`. */ -function matchBracket(source, open, openChar, closeChar) { - let depth = 0; - let i = open; - let inString = false; - while (i < source.length) { - const ch = source[i]; - if (inString) { - if (ch === '\\') i += 1; - else if (ch === '"') inString = false; - } else if (ch === '"') { - inString = true; - } else if (ch === openChar) { - depth += 1; - } else if (ch === closeChar) { - depth -= 1; - if (depth === 0) return i; - } - i += 1; - } - throw new Error(`unbalanced ${openChar} at ${open}`); -} - -/** Read the Rust string literal starting at `start` (which must be `"`). */ -function readString(source, start) { - let out = ''; - let i = start + 1; - while (i < source.length) { - const ch = source[i]; - if (ch === '\\') { - const next = source[i + 1]; - if (next === 'n') out += '\n'; - else if (next === 'r') out += '\r'; - else if (next === 't') out += '\t'; - else out += next; - i += 2; - continue; - } - if (ch === '"') return { text: out, end: i }; - out += ch; - i += 1; - } - throw new Error('unterminated string literal'); -} - -/** All `Msg { key: "…", text: row(…) }` entries with their source ranges. */ -function scanMessages(source) { - const entries = []; - const keyPattern = /key:\s*"/g; - let match; - while ((match = keyPattern.exec(source)) !== null) { - // `match[0]` includes the opening quote; point `readString` at it. - const keyStart = match.index + match[0].length - 1; - const key = readString(source, keyStart); - const blockStart = source.lastIndexOf('Msg {', keyStart); - const braceStart = source.indexOf('{', blockStart); - const blockEnd = matchBracket(source, braceStart, '{', '}'); - const rowStart = source.indexOf('row(', keyStart); - if (rowStart === -1 || rowStart > blockEnd) continue; - const parenStart = rowStart + 'row'.length; - const parenEnd = matchBracket(source, parenStart, '(', ')'); - - const values = []; - let i = parenStart + 1; - while (i < parenEnd) { - const ch = source[i]; - if (ch === '"') { - const literal = readString(source, i); - values.push(literal.text); - i = literal.end + 1; - continue; - } - i += 1; - } - // Consume the block's trailing comma too; `renderBlock` re-emits it. - const end = source[blockEnd + 1] === ',' ? blockEnd + 2 : blockEnd + 1; - entries.push({ key: key.text, values, start: blockStart, end }); - } - return entries; -} - -function renderBlock(key, values) { - const oneLine = ` Msg {\n key: "${key}",\n text: row(${values.map(quote).join(', ')}),\n },`; - const anyLong = values.some((value) => value.length > 12); - if (!anyLong) return oneLine; - return [ - ' Msg {', - ` key: "${key}",`, - ' text: row(', - ...values.map((value) => ` ${quote(value)},`), - ' ),', - ' },', - ].join('\n'); -} - -/** `tr_l10n(…, "key")` / `fmt_l10n(…, "key", …)` call sites under `src/`. */ -function referencedKeys() { - const keys = new Set(); - const files = []; - const walk = (directory) => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = resolve(directory, entry.name); - if (entry.isDirectory()) walk(path); - else if (entry.name.endsWith('.rs')) files.push(path); - } - }; - walk(resolve(APP_ROOT, '../linux/egui/src')); - const pattern = /\b(?:tr_l10n|fmt_l10n)\(\s*[^,()]+,\s*"([^"]+)"/g; - for (const file of files) { - const source = readFileSync(file, 'utf8'); - let match; - while ((match = pattern.exec(source)) !== null) keys.add(match[1]); - } - return keys; -} - -/** Insert index for new entries: just before the CATALOG slice terminator. */ -function catalogInsertIndex(source) { - const start = source.indexOf('pub const CATALOG'); - if (start === -1) throw new Error('CATALOG array not found in i18n.rs'); - const end = source.indexOf('\n];', start); - if (end === -1) throw new Error('CATALOG array terminator not found'); - return end + 1; -} - -async function main() { - const check = process.argv.includes('--check'); - const shared = await loadTauriCatalog(); - const source = readFileSync(CATALOG_PATH, 'utf8'); - const messages = scanMessages(source); - - const rewritten = []; - let updated = 0; - let unchanged = 0; - let skipped = 0; - let guarded = 0; - let cursor = 0; - for (const message of messages) { - rewritten.push(source.slice(cursor, message.start)); - const tauri = shared.get(normalizeKey(message.key)); - if (!tauri || KEEP_EGUI.has(message.key)) { - skipped += 1; - rewritten.push(source.slice(message.start, message.end)); - cursor = message.end; - continue; - } - const values = RUST_LOCALE_ORDER.map((tag) => toRustText(tauri[tag])); - // Never take a translation whose placeholders no longer line up with the - // arguments the egui pages pass; that would render a literal `{}`. - const expected = message.values.map(placeholderCount); - const mismatch = values.some((value, index) => placeholderCount(value) !== expected[index]); - if (mismatch) { - guarded += 1; - if (check) console.log(`skipped (placeholder mismatch): ${message.key}`); - rewritten.push(source.slice(message.start, message.end)); - cursor = message.end; - continue; - } - const same = - values.length === message.values.length && - values.every((value, index) => value === message.values[index]); - if (same) { - unchanged += 1; - rewritten.push(source.slice(message.start, message.end)); - } else { - updated += 1; - if (check) { - console.log(`drift: ${message.key}`); - console.log(` egui: ${JSON.stringify(message.values)}`); - console.log(` tauri: ${JSON.stringify(values)}`); - } - rewritten.push(renderBlock(message.key, values)); - } - cursor = message.end; - } - rewritten.push(source.slice(cursor)); - let output = rewritten.join(''); - - // Add catalog rows for keys the egui sources reference but the catalog lacks. - const known = new Set(messages.map((message) => message.key)); - const missing = []; - for (const key of referencedKeys()) { - if (known.has(key)) continue; - const tauri = shared.get(normalizeKey(key)); - if (!tauri) missing.push(key); - } - const additions = []; - for (const key of [...referencedKeys()].sort()) { - if (known.has(key)) continue; - const tauri = shared.get(normalizeKey(key)); - if (!tauri) continue; - additions.push( - renderBlock( - key, - RUST_LOCALE_ORDER.map((tag) => toRustText(tauri[tag])), - ), - ); - } - if (additions.length > 0) { - const at = catalogInsertIndex(output); - output = `${output.slice(0, at)}${additions.join('\n')}\n${output.slice(at)}`; - } - - console.log( - `egui i18n catalog: ${messages.length} keys · ${updated} updated · ${unchanged} in sync · ` + - `${skipped} egui-only/kept · ${guarded} skipped (placeholder mismatch) · ` + - `${additions.length} added`, - ); - if (missing.length > 0) { - console.error( - `referenced keys with no Tauri translation (add them by hand):\n ${missing.join('\n ')}`, - ); - } - - if (check) { - if (updated > 0 || additions.length > 0) { - console.error('Catalog is out of sync with the Tauri i18n files.'); - process.exit(1); - } - return; - } - if (updated > 0 || additions.length > 0) { - writeFileSync(CATALOG_PATH, output); - console.log(`wrote ${CATALOG_PATH}`); - } -} - -await main(); diff --git a/openless-all/app/scripts/sync-egui-lucide-icons.mjs b/openless-all/app/scripts/sync-egui-lucide-icons.mjs deleted file mode 100644 index bbebcfea8..000000000 --- a/openless-all/app/scripts/sync-egui-lucide-icons.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// Reproduce the Linux interface icons from the exact lucide-react dependency -// used by the Tauri shell. Run with --check to verify checked-in SVG assets. -import { createElement } from 'react'; -import { renderToStaticMarkup } from 'react-dom/server'; -import * as lucide from 'lucide-react'; -import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { resolve } from 'node:path'; - -const root = resolve(fileURLToPath(new URL('..', import.meta.url))); -const dest = resolve(root, '../linux/egui/assets/lucide'); -// Names match src/components/Icon.tsx. Stop/Send/Pin/Chat are popup -// controls and use the corresponding Lucide shape from the same version. -export const icons = { - Overview: 'ChartNoAxesColumn', - History: 'History', - Vocab: 'BookOpenText', - Style: 'SlidersHorizontal', - SelectionAsk: 'MessageSquareText', - Settings: 'Settings', - Mic: 'Mic', - Sparkle: 'Sparkles', - Flask: 'FlaskConical', - Hash: 'Hash', - Clock: 'Clock3', - Bolt: 'Zap', - Copy: 'Copy', - Search: 'Search', - Trash: 'Trash2', - Refresh: 'RefreshCw', - Download: 'Download', - Upload: 'Upload', - Plus: 'Plus', - Play: 'Play', - Stop: 'Square', - Close: 'X', - Check: 'Check', - Send: 'ArrowUp', - Pin: 'Pin', - Chat: 'MessageSquare', - More: 'Ellipsis', - ChevronRight: 'ChevronRight', - ChevronLeft: 'ChevronLeft', - Feather: 'Feather', - Layout: 'PanelLeft', - Doc: 'FileText', - Pencil: 'Pencil', - Cloud: 'Cloud', - Shield: 'ShieldCheck', - Info: 'Info', - Help: 'CircleHelp', - External: 'ExternalLink', - Monitor: 'Monitor', - Grip: 'GripVertical', -}; -const version = JSON.parse( - readFileSync(resolve(root, 'node_modules/lucide-react/package.json'), 'utf8'), -).version; -const check = process.argv.includes('--check'); -if (!check) mkdirSync(dest, { recursive: true }); -for (const [name, component] of Object.entries(icons)) { - if (!lucide[component]) throw new Error(`Unknown Lucide icon ${component}`); - // White masks are tinted at draw time by egui. The shape, stroke width, - // caps, joins and viewBox are otherwise the same as Tauri's Icon component. - const svg = `${renderToStaticMarkup(createElement(lucide[component], { size: 24, color: '#ffffff', strokeWidth: 1.75 }))}\n`; - const path = resolve(dest, `${name}.svg`); - if (check) { - if (readFileSync(path, 'utf8') !== svg) - throw new Error(`${name}.svg differs from lucide-react ${version}`); - } else { - writeFileSync(path, svg); - } -} -console.log(`${Object.keys(icons).length} Linux icons match lucide-react ${version}`); diff --git a/openless-all/app/scripts/tauri-linux-free-contract.test.mjs b/openless-all/app/scripts/tauri-linux-free-contract.test.mjs index 9f147f36f..22febee14 100644 --- a/openless-all/app/scripts/tauri-linux-free-contract.test.mjs +++ b/openless-all/app/scripts/tauri-linux-free-contract.test.mjs @@ -1,20 +1,11 @@ -import { readdir, readFile } from 'node:fs/promises'; -import { access, constants } from 'node:fs/promises'; +import { access, constants, readdir, readFile } from 'node:fs/promises'; import { basename, extname, join } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { fileURLToPath } from 'node:url'; -// The Tauri shell no longer ships a Linux desktop target: Linux runs the egui -// host in `openless-all/linux/egui`. This contract keeps that split from -// drifting back — a Linux-only cfg block, a Linux-only dependency, or a Linux -// branch in the React frontend would silently re-grow an unsupported target. -// -// Kept on purpose (so the checks below stay narrow): -// - `src-tauri/src/lib.rs` keeps a `#[cfg(target_os = "linux")] compile_error!` -// guard so an accidental Linux build fails with an actionable message. -// - i18n platform descriptions may legitimately say "Windows / Linux" -// because Linux users still run the product through the egui host. - -const appRoot = new URL('..', import.meta.url); +// Tauri no longer ships a Linux desktop target. Its compile_error! guard in +// src-tauri/src/lib.rs intentionally rejects accidental Linux builds. +// The separate Linux web host runs the shared React UI through Qt or GTK. +// Shared UI may use host and capability helpers; i18n can name Linux directly. const tauriSrc = fileURLToPath(new URL('../src-tauri/src', import.meta.url)); const reactSrc = fileURLToPath(new URL('../src', import.meta.url)); const failures = []; @@ -82,16 +73,32 @@ try { // absent, as expected } -// ── 3. React: no Linux branch (i18n copy is excluded, see the header) ──────── +// ── 3. React: Linux branches must go through the capability layer ─────────── +// Keep Linux literals in the host/capability layer and existing platform +// selectors. Shared components use the helpers rather than repeating checks. +// No file may revive the old custom Linux title bar. +const ALLOWED_LINUX_FILES = new Set([ + 'runtime/environment.ts', // 宿主检测 + 'runtime/platform.ts', // 平台能力 + 'runtime/transport.ts', // 选择原生传输层 + 'runtime/domain-events.ts', // 选择域事件来源 + 'preview/profiles.ts', // 补全平台类型 + 'app/shell/WindowChrome.tsx', // 使用原生窗口装饰 + 'features/settings/shell/navigation.ts', // 按平台筛选设置页 + 'features/input/RecordingInputSection.tsx', // 按平台筛选录音功能 +]); const reactFiles = await collect(reactSrc, new Set(['.ts', '.tsx']), { skip: (path) => /[/\\]i18n[/\\]/.test(path), }); for (const file of reactFiles) { if (file.endsWith('.test.ts') || file.endsWith('.test.tsx')) continue; + const relative = file.slice(reactSrc.length + 1).split(/[/\\]/).join('/'); const source = await readFile(file, 'utf8'); - for (const pattern of [/LINUX_TITLEBAR_HEIGHT/, /ol-linux-/, /['"]linux['"]/]) { + const patterns = [/LINUX_TITLEBAR_HEIGHT/, /ol-linux-/]; + if (!ALLOWED_LINUX_FILES.has(relative)) patterns.push(/['"]linux['"]/); + for (const pattern of patterns) { const match = source.match(pattern); - if (match) failures.push(`${file}: React still branches on Linux (${match[0]})`); + if (match) failures.push(`${relative}: unexpected Linux-specific code (${match[0]})`); } } diff --git a/openless-all/app/scripts/verify-release-ci.mjs b/openless-all/app/scripts/verify-release-ci.mjs index 64195c125..f81ee5f6b 100644 --- a/openless-all/app/scripts/verify-release-ci.mjs +++ b/openless-all/app/scripts/verify-release-ci.mjs @@ -31,7 +31,7 @@ export function verifyReleaseCi(report) { if ( job.status === 'completed' && job.conclusion === 'skipped' && - (job.name.endsWith(' / publish-linux-egui') || OPTIONAL_DISPATCH_ONLY_JOBS.has(job.name)) + (job.name.endsWith(' / publish-linux-host') || OPTIONAL_DISPATCH_ONLY_JOBS.has(job.name)) ) continue; throw new Error(`CI job did not pass: ${job.name}`); diff --git a/openless-all/app/scripts/verify-release-ci.test.mjs b/openless-all/app/scripts/verify-release-ci.test.mjs index 40f6086a0..7bc8e3f62 100644 --- a/openless-all/app/scripts/verify-release-ci.test.mjs +++ b/openless-all/app/scripts/verify-release-ci.test.mjs @@ -12,7 +12,7 @@ assert.equal( report([ ...jobs, { - name: 'Linux Core, egui and deb/rpm checks / publish-linux-egui', + name: 'Linux Core, host and deb/rpm checks / publish-linux-host', status: 'completed', conclusion: 'skipped', }, diff --git a/openless-all/app/scripts/windows-ui-config.test.mjs b/openless-all/app/scripts/windows-ui-config.test.mjs index fa56c68c6..3124501d8 100644 --- a/openless-all/app/scripts/windows-ui-config.test.mjs +++ b/openless-all/app/scripts/windows-ui-config.test.mjs @@ -189,8 +189,12 @@ assertMatch( const tokensCss = await readFile(new URL('../src/styles/tokens.css', import.meta.url), 'utf-8'); +// 自己画框的平台(win / linux / android / harmony)都不该加圆角; +// Linux 宿主由合成器画窗口,和 Windows 一样走原生装饰。 if ( - !/os === 'win' \|\| os === 'android'(?: \|\| os === 'harmony')? \? 0 : 14/.test(windowChromeTsx) + !/os === 'win' \|\| os === 'linux' \|\| os === 'android' \|\| os === 'harmony' \? 0 : 14/.test( + windowChromeTsx, + ) ) { throw new Error( 'windows main shell should rely on native decorations instead of a frameless chrome shell', diff --git a/openless-all/app/src-tauri/assets/local-asr-test.wav b/openless-all/app/shared/local-asr/local-asr-test.wav similarity index 100% rename from openless-all/app/src-tauri/assets/local-asr-test.wav rename to openless-all/app/shared/local-asr/local-asr-test.wav diff --git a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/assets.rs b/openless-all/app/shared/local-asr/sherpa_engine/assets.rs similarity index 69% rename from openless-all/app/src-tauri/src/asr/local/sherpa_engine/assets.rs rename to openless-all/app/shared/local-asr/sherpa_engine/assets.rs index b9ff59ab8..491b0e310 100644 --- a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/assets.rs +++ b/openless-all/app/shared/local-asr/sherpa_engine/assets.rs @@ -70,6 +70,36 @@ pub(super) fn current() -> Result<&'static Asset> { ), ], }), + ("linux", "x86_64") => Ok(&Asset { + stem: "sherpa-onnx-v1.13.8-linux-x64-shared-no-tts-lib", + bytes: 9249201, + sha256: "bf2d998c8b07012cd5098f3b92673bc1333fd9b927767d7cb664be8190d8bc0b", + libraries: &[ + ( + "libsherpa-onnx-c-api.so", + "c067b18cd746e49eb5016ee428196d21e1df14c14a3c54f128c1ac95f6aaed50", + ), + ( + "libonnxruntime.so", + "4b3607aebd1784b26b6f9b20e4bd974c7ab8287043e4d095cb7d2cb40b5e566e", + ), + ], + }), + ("linux", "aarch64") => Ok(&Asset { + stem: "sherpa-onnx-v1.13.8-linux-aarch64-shared-cpu-lib", + bytes: 12595068, + sha256: "fb98b80628a383909bf83626daca2e0d0ffc93bf1f7d222eaaa4282b388f072f", + libraries: &[ + ( + "libsherpa-onnx-c-api.so", + "11378e1aea169aecb59a4d41ca8da6f5ee4f3614c34a4b908dd78de7646a518d", + ), + ( + "libonnxruntime.so", + "cfc800d4438f15e8d9017521326776ca7117d8783cb847ccccc2fc61ac4d540f", + ), + ], + }), _ => anyhow::bail!("Sherpa runtime is unavailable for this architecture"), } } diff --git a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/ffi.rs b/openless-all/app/shared/local-asr/sherpa_engine/ffi.rs similarity index 100% rename from openless-all/app/src-tauri/src/asr/local/sherpa_engine/ffi.rs rename to openless-all/app/shared/local-asr/sherpa_engine/ffi.rs diff --git a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/mod.rs b/openless-all/app/shared/local-asr/sherpa_engine/mod.rs similarity index 91% rename from openless-all/app/src-tauri/src/asr/local/sherpa_engine/mod.rs rename to openless-all/app/shared/local-asr/sherpa_engine/mod.rs index 75b45ab11..7d48340d3 100644 --- a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/mod.rs +++ b/openless-all/app/shared/local-asr/sherpa_engine/mod.rs @@ -109,17 +109,25 @@ pub(crate) fn cancel() { } } +#[cfg(not(target_os = "linux"))] pub(crate) async fn remove() -> Result<()> { + remove_in(crate::persistence::data_dir()?).await +} + +pub(crate) async fn remove_in(data_dir: PathBuf) -> Result<()> { cancel(); let active_done = STATE.lock().job.as_ref().map(|job| job.done.clone()); if let Some(mut done) = active_done { let _ = done.wait_for(Option::is_some).await; } - let root = crate::persistence::data_dir()?.join("runtimes/sherpa-onnx"); + let root = data_dir.join("runtimes/sherpa-onnx"); tokio::task::spawn_blocking(move || -> Result<()> { if root.try_exists()? { fs::remove_dir_all(&root).with_context(|| { - format!("Failed to delete Sherpa support library at {}", root.display()) + format!( + "Failed to delete Sherpa support library at {}", + root.display() + ) })?; } Ok(()) @@ -131,6 +139,7 @@ pub(crate) async fn remove() -> Result<()> { /// All UI windows and backend model requests await the same job and terminal result. /// Dropping an IPC future does not cancel the installation for another consumer. +#[cfg(not(target_os = "linux"))] pub(crate) async fn prepare() -> Result<()> { prepare_in(crate::persistence::data_dir()?, true).await } @@ -206,8 +215,21 @@ fn begin_load(cancel: &watch::Receiver, bytes: u64) -> Result<()> { fn digest(path: &Path) -> Result { let mut hash = Sha256::new(); - io::copy(&mut fs::File::open(path)?, &mut hash)?; - Ok(format!("{:x}", hash.finalize())) + use io::Read; + let mut file = fs::File::open(path)?; + let mut buffer = [0u8; 65536]; + loop { + let count = file.read(&mut buffer)?; + if count == 0 { + break; + } + hash.update(&buffer[..count]); + } + Ok(hash + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) } fn verify_libraries(dir: &Path, asset: &Asset) -> Result<()> { ensure!( @@ -278,12 +300,11 @@ async fn install( let download = async { update_status(Phase::Downloading, 0, None); let url = asset.url(); - let mut response = crate::polish::http_client_builder(&url, 300) - .build()? - .get(url) - .send() - .await? - .error_for_status()?; + #[cfg(not(target_os = "linux"))] + let builder = crate::polish::http_client_builder(&url, 300); + #[cfg(target_os = "linux")] + let builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(300)); + let mut response = builder.build()?.get(url).send().await?.error_for_status()?; let mut file = tokio::fs::File::create(&part).await?; let mut bytes = 0; let mut last_event = std::time::Instant::now(); diff --git a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/native.rs b/openless-all/app/shared/local-asr/sherpa_engine/native.rs similarity index 91% rename from openless-all/app/src-tauri/src/asr/local/sherpa_engine/native.rs rename to openless-all/app/shared/local-asr/sherpa_engine/native.rs index c846f7ecc..5a27e6e2d 100644 --- a/openless-all/app/src-tauri/src/asr/local/sherpa_engine/native.rs +++ b/openless-all/app/shared/local-asr/sherpa_engine/native.rs @@ -5,7 +5,7 @@ use libloading::Library; use openless_core::SherpaModelFamily; use std::ffi::{c_char, CStr, CString}; use std::path::Path; -#[cfg(target_os = "windows")] +#[cfg(any(target_os = "windows", target_os = "linux"))] use std::sync::Arc; use std::sync::OnceLock; @@ -48,7 +48,7 @@ pub(super) fn load(dir: &Path) -> Result<()> { ) .map(Into::into) }; - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "linux"))] let library = unsafe { use libloading::os::unix::{Library, RTLD_LOCAL, RTLD_NOW}; Library::open(Some(path), RTLD_LOCAL | RTLD_NOW).map(Into::into) @@ -60,6 +60,8 @@ pub(super) fn load(dir: &Path) -> Result<()> { let (onnx, sherpa) = ("libonnxruntime.dylib", "libsherpa-onnx-c-api.dylib"); #[cfg(target_os = "windows")] let (onnx, sherpa) = ("onnxruntime.dll", "sherpa-onnx-c-api.dll"); + #[cfg(target_os = "linux")] + let (onnx, sherpa) = ("libonnxruntime.so", "libsherpa-onnx-c-api.so"); let onnx = open(&dir.join(onnx))?; let api = ffi::Api::resolve(open(&dir.join(sherpa))?, onnx)?; let version = unsafe { (api.SherpaOnnxGetVersionStr)() }; @@ -87,6 +89,9 @@ struct Paths<'a> { impl Paths<'_> { fn file(&mut self, name: &str) -> Result<*const c_char> { let path = self.dir.join(name); + #[cfg(target_os = "linux")] + ensure!(if name == "tokenizer" { path.is_dir() } else { path.is_file() }, + "Missing Sherpa model component: {}", path.display()); let value = CString::new(path.to_str().context("Non-UTF-8 Sherpa model path")?)?; let ptr = value.as_ptr(); self.values.push(value); @@ -127,9 +132,11 @@ impl OfflineRecognizer { dir, values: Vec::new(), }; - let mut config = ffi::OfflineRecognizerConfig::default(); - config.feat_config = features(); - config.max_active_paths = 4; + let mut config = ffi::OfflineRecognizerConfig { + feat_config: features(), + max_active_paths: 4, + ..Default::default() + }; config.lm_config.scale = 1.0; let model = &mut config.model_config; model.num_threads = 1; @@ -220,13 +227,13 @@ impl OfflineStream<'_> { ) } } - #[cfg(target_os = "windows")] + #[cfg(any(target_os = "windows", target_os = "linux"))] pub(crate) fn has_option(&self, key: &str) -> bool { CString::new(key).is_ok_and(|key| unsafe { (self.owner.api.SherpaOnnxOfflineStreamHasOption)(self.ptr, key.as_ptr()) != 0 }) } - #[cfg(target_os = "windows")] + #[cfg(any(target_os = "windows", target_os = "linux"))] pub(crate) fn set_option(&self, key: &str, value: &str) { if let (Ok(key), Ok(value)) = (CString::new(key), CString::new(value)) { unsafe { @@ -240,9 +247,9 @@ impl OfflineStream<'_> { } } -#[cfg(target_os = "windows")] +#[cfg(any(target_os = "windows", target_os = "linux"))] pub(crate) use online::*; -#[cfg(target_os = "windows")] +#[cfg(any(target_os = "windows", target_os = "linux"))] mod online { use super::*; pub(crate) struct OnlineRecognizer { @@ -264,13 +271,15 @@ mod online { dir, values: Vec::new(), }; - let mut config = ffi::OnlineRecognizerConfig::default(); - config.feat_config = features(); - config.enable_endpoint = 1; - config.rule1_min_trailing_silence = 2.4; - config.rule2_min_trailing_silence = 1.2; - config.rule3_min_utterance_length = 20.0; - config.decoding_method = c"greedy_search".as_ptr(); + let mut config = ffi::OnlineRecognizerConfig { + feat_config: features(), + enable_endpoint: 1, + rule1_min_trailing_silence: 2.4, + rule2_min_trailing_silence: 1.2, + rule3_min_utterance_length: 20.0, + decoding_method: c"greedy_search".as_ptr(), + ..Default::default() + }; let model = &mut config.model_config; model.tokens = paths.file("tokens.txt")?; model.num_threads = std::thread::available_parallelism() diff --git a/openless-all/app/src-tauri/src/asr/local/mod.rs b/openless-all/app/src-tauri/src/asr/local/mod.rs index 023d8604a..b529b1276 100644 --- a/openless-all/app/src-tauri/src/asr/local/mod.rs +++ b/openless-all/app/src-tauri/src/asr/local/mod.rs @@ -11,6 +11,7 @@ pub mod foundry_runtime; mod native_model_receipt; pub mod sherpa; #[cfg(any(target_os = "macos", target_os = "windows"))] +#[path = "../../../../shared/local-asr/sherpa_engine/mod.rs"] pub(crate) mod sherpa_engine; pub mod sherpa_provider; pub mod sherpa_runtime; diff --git a/openless-all/app/src-tauri/src/core_adapters.rs b/openless-all/app/src-tauri/src/core_adapters.rs index 1ba81bc8c..a0e0e0498 100644 --- a/openless-all/app/src-tauri/src/core_adapters.rs +++ b/openless-all/app/src-tauri/src/core_adapters.rs @@ -953,7 +953,7 @@ impl openless_core::ModelRuntimeAdapter for TauriLocalAsrRuntimeAdapter { } #[cfg(local_asr_sherpa)] -const LOCAL_ASR_TEST_WAV: &[u8] = include_bytes!("../assets/local-asr-test.wav"); +const LOCAL_ASR_TEST_WAV: &[u8] = include_bytes!("../../shared/local-asr/local-asr-test.wav"); #[cfg(all(local_asr_sherpa, target_os = "windows"))] async fn test_foundry_model( diff --git a/openless-all/app/src-tauri/src/playback_reference.rs b/openless-all/app/src-tauri/src/playback_reference.rs index 3ed20a61f..7e5ff97bc 100644 --- a/openless-all/app/src-tauri/src/playback_reference.rs +++ b/openless-all/app/src-tauri/src/playback_reference.rs @@ -123,6 +123,6 @@ pub(super) fn start( _diagnostics: &Arc, ) -> Result<(PlaybackReference, Arc), RecorderError> { Err(RecorderError::EngineFailed( - "playback reference is unavailable in this host; Linux uses the egui recorder".into(), + "playback reference is unavailable in this host; Linux uses the Linux recorder".into(), )) } diff --git a/openless-all/app/src-tauri/src/recorder.rs b/openless-all/app/src-tauri/src/recorder.rs index d078ffbc7..09b323725 100644 --- a/openless-all/app/src-tauri/src/recorder.rs +++ b/openless-all/app/src-tauri/src/recorder.rs @@ -543,7 +543,7 @@ impl Drop for WavArchiveWriter { } } -/// 调试录音要落哪几份盘(与 egui 侧同名同义)。 +/// 调试录音要落哪几份盘(与 Linux 宿主侧同名同义)。 /// /// - `processed`:主档案 `.wav`,`write_processed` 时写降噪/增益之后的 /// PCM,否则写原始 PCM(只勾「处理前」时用,回退/播放功能不变)。 diff --git a/openless-all/app/src-tauri/src/selection.rs b/openless-all/app/src-tauri/src/selection.rs index 440a52523..1f257e538 100644 --- a/openless-all/app/src-tauri/src/selection.rs +++ b/openless-all/app/src-tauri/src/selection.rs @@ -11,7 +11,7 @@ //! Prompt budgets for unrelated QA/cursor context remain at their own call sites. //! //! 模块依赖:`arboard`(跨平台剪贴板)+ libc + 平台 native 框架。 -//! Linux 桌面已改由 egui 前端(`openless-all/linux/egui`)承担,Tauri 版不再提供 +//! Linux 桌面已改由 Linux 原生宿主(`openless-all/linux/host`)承担,Tauri 版不再提供 //! Linux 的选区读取路径。 // 仅 macOS / Windows 的模拟复制路径用 sleep。 diff --git a/openless-all/app/src-tauri/src/side_aware_combo.rs b/openless-all/app/src-tauri/src/side_aware_combo.rs index 0accdad91..4dfcb6934 100644 --- a/openless-all/app/src-tauri/src/side_aware_combo.rs +++ b/openless-all/app/src-tauri/src/side_aware_combo.rs @@ -205,7 +205,7 @@ impl SideAwareComboMonitor { tx: Sender, combo_tx: Sender, ) -> Result { - // Linux accepts the binding too: the egui host owns its own side-aware + // Linux accepts the binding too: the Linux host owns its own side-aware // modifier layer, so the platform dispatch this file wraps is not the // only source of those edges. Rejecting here would hide a working // configuration behind a bogus error. diff --git a/openless-all/app/src-tauri/src/tauri_events.rs b/openless-all/app/src-tauri/src/tauri_events.rs index 700fe37e1..f0ec0d3f5 100644 --- a/openless-all/app/src-tauri/src/tauri_events.rs +++ b/openless-all/app/src-tauri/src/tauri_events.rs @@ -626,12 +626,10 @@ fn emit_preferences(app: &AppHandle, backend: &OpenLessBackend) { } }); } - // Cloud restore also changes preferences directly through Core. Keep native - // capsule geometry and hit testing current for every source of a preference change. + // Cloud restore also changes preferences directly through Core. Keep capsule + // geometry and hit testing current for every source of a preference change. if let Some(coordinator) = app.try_state::>() { coordinator.sync_capsule_style_from_preferences(); - #[cfg(not(mobile))] - coordinator.tauri_host().refresh_native_capsule_theme(); } let _ = app.emit("prefs:changed", &preferences); #[cfg(not(mobile))] diff --git a/openless-all/app/src/api/history.ts b/openless-all/app/src/api/history.ts index d24f63fe4..f4c85723e 100644 --- a/openless-all/app/src/api/history.ts +++ b/openless-all/app/src/api/history.ts @@ -1,4 +1,4 @@ -import { isTauriHost } from '../runtime/environment'; +import { isNativeDesktopHost, isTauriHost } from '../runtime/environment'; import { invokeOrPreview } from '../runtime/transport'; import { downloadUrl } from '../runtime/files'; import type { ActivityDay, DictationSession } from './contracts'; @@ -52,7 +52,7 @@ export async function getActivityStats(): Promise { } export async function exportAudioRecording(sessionId: string): Promise { - if (isTauriHost()) { + if (isTauriHost() || isNativeDesktopHost()) { return invokeOrPreview('export_audio_recording', { sessionId }, () => undefined); } const dataUrl = await commands.readAudioRecording(sessionId); diff --git a/openless-all/app/src/api/permissions.ts b/openless-all/app/src/api/permissions.ts index ddc1785fe..81635744b 100644 --- a/openless-all/app/src/api/permissions.ts +++ b/openless-all/app/src/api/permissions.ts @@ -1,3 +1,25 @@ +import { invokeOrPreview } from '../runtime/transport'; +export interface LinuxInputPluginStatus { + installed: boolean; + daemonRunning: boolean; + loaded: boolean; + insertionReady: boolean; + hotkeysReady: boolean; + metadataReady: boolean; +} +/** Diagnostics only: must never install, start, activate, switch or reload an IME. */ +export const getLinuxInputPluginStatus = () => invokeOrPreview( + 'get_linux_input_plugin_status', undefined, + () => ({ installed: false, daemonRunning: false, loaded: false, insertionReady: false, hotkeysReady: false, metadataReady: false }), +); +export interface LinuxTextAccessStatus { enabled: boolean; targetAvailable: boolean } +export const getLinuxTextAccessStatus = () => invokeOrPreview('get_linux_text_access_status', undefined, () => ({ enabled: false, targetAvailable: false })); +export const enableLinuxTextAccess = () => invokeOrPreview('enable_linux_text_access', undefined, () => { throw new Error('Desktop accessibility service unavailable'); }); +export const disableLinuxTextAccess = () => invokeOrPreview('disable_linux_text_access', undefined, () => ({ enabled: false, targetAvailable: false })); +export interface LinuxGlobalShortcutsStatus { enabled: boolean; authorizing: boolean; shortcuts: { id: string; trigger: string }[]; error: string | null } +export const getLinuxGlobalShortcutsStatus = () => invokeOrPreview('get_linux_global_shortcuts_status', undefined, () => ({ enabled: false, authorizing: false, shortcuts: [], error: null })); +export const enableLinuxGlobalShortcuts = () => invokeOrPreview('enable_linux_global_shortcuts', undefined, () => { throw new Error('Desktop global shortcut portal unavailable'); }); +export const disableLinuxGlobalShortcuts = () => invokeOrPreview('disable_linux_global_shortcuts', undefined, () => ({ enabled: false, authorizing: false, shortcuts: [], error: null })); export * from '../lib/ipc/permissions'; export { getAndroidOverlayStatus, diff --git a/openless-all/app/src/api/voice-edit.ts b/openless-all/app/src/api/voice-edit.ts index 7bdc096c0..9ceb909c9 100644 --- a/openless-all/app/src/api/voice-edit.ts +++ b/openless-all/app/src/api/voice-edit.ts @@ -1,6 +1,10 @@ export * from '../lib/ipc/voice-edit-session'; -import { listenTauriEvent } from '../runtime/transport'; +import { listenTauriEvent, invokeOrPreview } from '../runtime/transport'; +import type { VoiceEditSnapshot } from '../lib/ipc/voice-edit-session'; + +/** Explicit Linux full-field read, without starting the microphone. */ +export const captureVoiceEditField = () => invokeOrPreview('capture_voice_edit_field', undefined, () => { throw new Error('Full-field accessibility target unavailable'); }); export function listenEmbeddedVoiceEditShown(onShown: () => void): Promise<() => void> { return listenTauriEvent('voice-edit:show', onShown); diff --git a/openless-all/app/src/app/shell/WindowChrome.tsx b/openless-all/app/src/app/shell/WindowChrome.tsx index 1c461b95f..cba834327 100644 --- a/openless-all/app/src/app/shell/WindowChrome.tsx +++ b/openless-all/app/src/app/shell/WindowChrome.tsx @@ -19,7 +19,7 @@ export function WindowChrome({ os = 'mac', mobile, children, height = 800 }: Win // Windows: with decorations:true the shell draws no radius/border/shadow/titlebar, // avoiding overlap with the native window. const shellRadius = - os === 'mac' ? 0 : os === 'win' || os === 'android' || os === 'harmony' ? 0 : 14; + os === 'mac' ? 0 : os === 'win' || os === 'linux' || os === 'android' || os === 'harmony' ? 0 : 14; const consoleRadius = os === 'mac' ? 20 : os === 'win' ? WIN_CONSOLE_RADIUS : 0; // The compact shell puts live controls in the strip reserved for desktop window drag. const hasMacDragStrip = os === 'mac' && !mobile; diff --git a/openless-all/app/src/app/shell/navigation.ts b/openless-all/app/src/app/shell/navigation.ts index 48cf1ad3b..fae3b6afe 100644 --- a/openless-all/app/src/app/shell/navigation.ts +++ b/openless-all/app/src/app/shell/navigation.ts @@ -1,8 +1,9 @@ import { useEffect, useState } from 'react'; -import { getShortcutPlatform } from '../../runtime/environment'; +import { getShortcutPlatform, isLinuxHost, isNativeDesktopHost } from '../../runtime/environment'; export type AppTab = | 'overview' + | 'ask' | 'history' | 'usage' | 'vocab' @@ -15,9 +16,10 @@ export type AppTab = | 'localAsr'; export function isTabAvailable(tab: AppTab): boolean { + if (tab === 'ask') return isNativeDesktopHost(); if (tab === 'appStyles') { const platform = getShortcutPlatform(); - return platform.isMac || platform.isWindows; + return platform.isMac || platform.isWindows || isLinuxHost(); } return true; } @@ -46,6 +48,7 @@ export function useAppState(initialTab: AppTab = 'overview', initialSettings = f /** i18n key for a group's sub-item title: style → nav.polishMode, everything else nav.. */ export function subItemLabelKey(id: AppTab): string { + if (id === 'ask') return 'selectionAsk.title'; if (id === 'style') return 'nav.polishMode'; if (id === 'appStyles') return 'appStyles.title'; return `nav.${id}`; @@ -92,6 +95,7 @@ export const NAV_TREE: NavNode[] = [ key: 'tools', icon: 'selectionAsk', children: [ + { id: 'ask' }, { id: 'corrections' }, { id: 'translation' }, { id: 'quickNote' }, diff --git a/openless-all/app/src/app/shell/pages.tsx b/openless-all/app/src/app/shell/pages.tsx index d58cfc491..96eb93f69 100644 --- a/openless-all/app/src/app/shell/pages.tsx +++ b/openless-all/app/src/app/shell/pages.tsx @@ -7,6 +7,7 @@ import { preloadVocabEntries } from '../../data/vocabulary'; import type { AppTab } from './navigation'; const loaders = { + ask: () => import('../../features/qa/AskTool').then((module) => ({ default: module.AskTool })), appStyles: () => import('../../features/style-packs/AppStyleRouting').then((module) => ({ default: module.AppStyleRouting, @@ -38,6 +39,7 @@ const pages: Partial> = { // History is a primary destination on both desktop and mobile. history: History, usage: lazy(loaders.usage), + ask: lazy(loaders.ask), vocab: lazy(loaders.vocab), style: lazy(loaders.style), appStyles: lazy(loaders.appStyles), diff --git a/openless-all/app/src/app/windowRoutes.tsx b/openless-all/app/src/app/windowRoutes.tsx index dbc6d463b..6e1f5b9d3 100644 --- a/openless-all/app/src/app/windowRoutes.tsx +++ b/openless-all/app/src/app/windowRoutes.tsx @@ -4,6 +4,8 @@ import { CapsuleTranscriptOverlay } from '../features/capsule/LiveTranscriptPill import { AudioCueListener } from '../features/capsule/AudioCue'; import type { OS } from '../runtime/environment'; import { loadMainShell, VoiceEditPanel } from './destinations'; +import { isLinuxHost } from '../runtime/environment'; +const LinuxQaWindow = lazy(() => import('../features/qa/LinuxQaWindow').then((module) => ({ default: module.LinuxQaWindow }))); const loadMainWindow = () => import('./MainWindow'); const MainWindow = lazy(() => loadMainWindow().then((module) => ({ default: module.MainWindow }))); @@ -20,6 +22,7 @@ const SelectionVoiceIntentPicker = lazy(() => export type WindowKind = | 'main' + | 'qa' | 'capsule' | 'capsule-rail' | 'voice-edit' @@ -30,6 +33,8 @@ export type WindowKind = export function resolveWindowKind(params: URLSearchParams): WindowKind { const kind = params.get('window'); switch (kind) { + case 'qa': + return isLinuxHost() ? 'qa' : 'main'; case 'capsule': case 'capsule-rail': case 'voice-edit': @@ -60,6 +65,8 @@ export function WindowRoutes({ previewOnboarding: boolean; }) { switch (kind) { + case 'qa': + return ; case 'capsule-rail': return ; case 'capsule': diff --git a/openless-all/app/src/features/capsule/Capsule.tsx b/openless-all/app/src/features/capsule/Capsule.tsx index e4bd18c7c..4ccaaf728 100644 --- a/openless-all/app/src/features/capsule/Capsule.tsx +++ b/openless-all/app/src/features/capsule/Capsule.tsx @@ -2,7 +2,13 @@ import { motion } from 'framer-motion'; import { collectCapsuleInputRegions } from '../../lib/capsuleInputRegions'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { getRuntimeEnvironment, isTauriHost, type OS } from '../../runtime/environment'; +import { + getRuntimeEnvironment, + isDesktopOS, + isNativeDesktopHost, + supportsCapsuleInputRegions, + type OS, +} from '../../runtime/environment'; import { createCapsuleRegionPublisher } from '../../runtime/windows/capsuleInput'; import { warmUpSiriShaders } from './SiriGL'; import { useReducedMotion } from '../../lib/motion'; @@ -313,7 +319,7 @@ const INSERT_DEMO_CHUNKS = [ const INSERT_DEMO_GAPS_MS = [420, 560, 640, 540, 280]; function getPreviewCapsulePayload() { - if (isTauriHost() || typeof window === 'undefined') { + if (isNativeDesktopHost() || typeof window === 'undefined') { return { state: 'idle' as CapsuleState, level: 0, @@ -353,8 +359,9 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { const { t } = useTranslation(); const environment = getRuntimeEnvironment(); const os = forcedOs ?? environment.os; - const canShowReferences = !environment.isMobile && (os === 'mac' || os === 'win'); - const isTauri = isTauriHost(); + const canShowReferences = !environment.isMobile && isDesktopOS(os); + const isTauri = isNativeDesktopHost(); + const publishNativeInputRegions = isTauri && supportsCapsuleInputRegions(os); const [publishInputRegions] = useState(createCapsuleRegionPublisher); const [pickerController] = useState(() => new CapsulePickerMenu()); const preview = useMemo(() => getPreviewCapsulePayload(), []); @@ -818,7 +825,7 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { }, [transcriptVisible]); useEffect(() => { - if (!isTauri || os !== 'mac') return; + if (!publishNativeInputRegions) return; let stopped = false; let frame = 0; let last = ''; @@ -881,16 +888,23 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { window.removeEventListener('resize', schedule); document.removeEventListener('animationend', onSatelliteAnimationEnd, true); }; - }, [isTauri, os, state, leaving, insertFallback, suggestions.length, publishInputRegions]); + }, [ + publishNativeInputRegions, + state, + leaving, + insertFallback, + suggestions.length, + publishInputRegions, + ]); useEffect(() => { - if (!isTauri || os !== 'mac') return; + if (!publishNativeInputRegions) return; return () => { void publishInputRegions([]).catch((error) => console.warn('[capsule] input region cleanup failed', error), ); }; - }, [isTauri, os, publishInputRegions]); + }, [publishNativeInputRegions, publishInputRegions]); // Transcript rail visibility is owned by the primary capsule. useEffect(() => { diff --git a/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts b/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts index 56ec240fe..21cd1603f 100644 --- a/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts +++ b/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts @@ -212,7 +212,7 @@ const dependencies: Record = { Card: 'card', Toggle: 'toggle', getCloudSyncPreviewScenario: () => undefined, - isTauriHost: () => true, + isNativeDesktopHost: () => true, listenEncryptedSyncStateChanges: (callback) => listen('cloud-sync-e2ee:state', callback), listenEncryptedSyncConflicts: (callback) => listen('cloud-sync-e2ee:conflict', callback), listenEncryptedSyncRestores: (callback) => listen('cloud-sync-e2ee:restored', callback), diff --git a/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx b/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx index bb217ba9c..842e3118f 100644 --- a/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx +++ b/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx @@ -28,7 +28,7 @@ import { Toggle } from '../../ui/controls/SettingRow'; import { useHotkeySettings } from '../../data/preferences'; import { marketplaceAuthStatus } from '../../api/marketplace'; import { readCredential } from '../../api/providers'; -import { isTauriHost } from '../../runtime/environment'; +import { isNativeDesktopHost } from '../../runtime/environment'; import { getCloudSyncPreviewScenario } from '../../preview/cloud-sync'; import { CLOUD_SYNC_E2EE_CONSENT_VERSION as CONSENT_VERSION, @@ -555,7 +555,7 @@ export function CloudSyncSection() { window.addEventListener('openless:sync-ui-persistence-failed', uiPersistenceFailed); void (async () => { try { - if (isTauriHost()) { + if (isNativeDesktopHost()) { const subscriptions = [ () => listenEncryptedSyncStateChanges((event) => { @@ -997,7 +997,7 @@ export function CloudSyncSection() { title={t('emptyStates.noAccess.cloudSyncSignedOutTitle')} primaryAction={{ label: t('emptyStates.noAccess.cloudSyncSignIn'), - disabled: !isTauriHost() || !available || working, + disabled: !isNativeDesktopHost() || !available || working, onClick: () => setShowLogin(true), }} /> diff --git a/openless-all/app/src/features/cloud-sync/RestoreReview.tsx b/openless-all/app/src/features/cloud-sync/RestoreReview.tsx index 368876904..2b3af7551 100644 --- a/openless-all/app/src/features/cloud-sync/RestoreReview.tsx +++ b/openless-all/app/src/features/cloud-sync/RestoreReview.tsx @@ -168,6 +168,11 @@ export function RestoreReview({ category: t(`cloudSyncE2ee.categories.${categoryKey(conflict.kind)}`), })} + {(conflict.localLabel || conflict.cloudLabel) && ( +

+ {conflict.localLabel || conflict.cloudLabel} +

+ )}

{t( `cloudSyncE2ee.conflictReasons.${['both_modified', 'delete_modify', 'no_common_baseline'].includes(conflict.reason) ? conflict.reason : 'other'}`, @@ -186,6 +191,11 @@ export function RestoreReview({ }} />{' '} {t(`cloudSyncE2ee.conflict${side === 'local' ? 'Local' : 'Cloud'}`)} + {(side === 'local' ? conflict.localLabel : conflict.cloudLabel) && ( + + · {side === 'local' ? conflict.localLabel : conflict.cloudLabel} + + )} ))} diff --git a/openless-all/app/src/features/corrections/Corrections.tsx b/openless-all/app/src/features/corrections/Corrections.tsx index ed09b66c8..7abff2ac8 100644 --- a/openless-all/app/src/features/corrections/Corrections.tsx +++ b/openless-all/app/src/features/corrections/Corrections.tsx @@ -73,7 +73,7 @@ export function Corrections() { className="ol-correction-add ol-col-2" onClick={() => void onAddCorrectionRule()} disabled={busy} - style={mobile ? { justifySelf: 'start' } : undefined} + style={{ justifySelf: mobile ? 'start' : 'end', width: 'max-content', maxWidth: '100%', justifyContent: 'center' }} > {t('common.add')} diff --git a/openless-all/app/src/features/input/LinuxGlobalShortcutsSection.tsx b/openless-all/app/src/features/input/LinuxGlobalShortcutsSection.tsx new file mode 100644 index 000000000..9fd3c5258 --- /dev/null +++ b/openless-all/app/src/features/input/LinuxGlobalShortcutsSection.tsx @@ -0,0 +1,88 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + getLinuxGlobalShortcutsStatus, + enableLinuxGlobalShortcuts, + disableLinuxGlobalShortcuts, + type LinuxGlobalShortcutsStatus, +} from '../../api/permissions'; +import { Icon } from '../../components/Icon'; +import { Button } from '../../ui/controls/Button'; +import { Pill } from '../../ui/controls/Pill'; +import { SettingRow } from '../../ui/controls/SettingRow'; +import { useInteraction } from '../../ui/overlays/InteractionProvider'; + +export function LinuxGlobalShortcutsSection() { + const { i18n } = useTranslation(); + const zh = i18n.language.startsWith('zh'); + const { notify } = useInteraction('linux-global-shortcuts'); + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let active = true; + void getLinuxGlobalShortcutsStatus() + .then((value) => { + if (active) setStatus(value); + }) + .catch(() => {}); + return () => { + active = false; + }; + }, []); + + const enabled = Boolean(status?.enabled); + const desc = status?.error + ? status.error + : zh + ? 'Wayland 桌面全局快捷键授权;已授权动作自动接管,不会与 Fcitx5 重复触发' + : 'Wayland desktop global shortcut authorization; replaces Fcitx5 for authorized actions without double-triggering'; + + return ( + +

+ + {enabled && } + {enabled + ? zh + ? `已授权 (${status?.shortcuts.length ?? 0})` + : `Authorized (${status?.shortcuts.length ?? 0})` + : zh + ? '未启用' + : 'Not enabled'} + + {enabled ? ( + + ) : ( + + )} +
+ + ); +} diff --git a/openless-all/app/src/features/input/LinuxTextAccessSection.tsx b/openless-all/app/src/features/input/LinuxTextAccessSection.tsx new file mode 100644 index 000000000..3e44a3cba --- /dev/null +++ b/openless-all/app/src/features/input/LinuxTextAccessSection.tsx @@ -0,0 +1,67 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + getLinuxTextAccessStatus, + enableLinuxTextAccess, + disableLinuxTextAccess, + type LinuxTextAccessStatus, +} from '../../api/permissions'; +import { Icon } from '../../components/Icon'; +import { Button } from '../../ui/controls/Button'; +import { Pill } from '../../ui/controls/Pill'; +import { SettingRow } from '../../ui/controls/SettingRow'; +import { useInteraction } from '../../ui/overlays/InteractionProvider'; + +export function LinuxTextAccessSection() { + const { i18n } = useTranslation(); + const zh = i18n.language.startsWith('zh'); + const { notify } = useInteraction('linux-text-access'); + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let active = true; + void getLinuxTextAccessStatus() + .then((value) => { + if (active) setStatus(value); + }) + .catch(() => {}); + return () => { + active = false; + }; + }, []); + + const enabled = Boolean(status?.enabled); + + return ( + +
+ + {enabled && } + {enabled ? (zh ? '已启用' : 'Enabled') : zh ? '未启用' : 'Not enabled'} + + +
+
+ ); +} diff --git a/openless-all/app/src/features/input/PermissionsSection.tsx b/openless-all/app/src/features/input/PermissionsSection.tsx index 2050fb9d6..2cc299408 100644 --- a/openless-all/app/src/features/input/PermissionsSection.tsx +++ b/openless-all/app/src/features/input/PermissionsSection.tsx @@ -6,6 +6,8 @@ import { useTranslation } from 'react-i18next'; import { AndroidPermissionsPanel } from '@android/components/AndroidPermissionsPanel'; import { Icon } from '../../components/Icon'; import { + getLinuxInputPluginStatus, + type LinuxInputPluginStatus, checkAccessibilityPermission, checkMicrophonePermission, openSystemSettings, @@ -18,6 +20,9 @@ import { getHotkeyStatus, getWindowsImeStatus } from '../../api/hotkeys'; import type { NetworkCheckResult } from '../../api/input'; import { emitSaved } from '../../lib/savedEvent'; import { getPlatformCapabilities } from '../../runtime/platform'; +import { isLinuxHost } from '../../runtime/environment'; +import { LinuxTextAccessSection } from './LinuxTextAccessSection'; +import { LinuxGlobalShortcutsSection } from './LinuxGlobalShortcutsSection'; import { useLayoutStack, useConservativeLayout } from '../../lib/useMobileLayout'; import { checkAndroidMicrophoneAccess, @@ -39,7 +44,20 @@ import { SettingRow } from '../../ui/controls/SettingRow'; const ANDROID_SETUP_WIZARD_COMPLETE_KEY = 'openless.androidSetupWizardComplete'; export function PermissionsSection() { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const linux = isLinuxHost(); + const zh = i18n.language.startsWith('zh'); + const [plugin, setPlugin] = useState(null); + const [pluginBusy, setPluginBusy] = useState(false); + const [pluginError, setPluginError] = useState(false); + const refreshPlugin = async () => { + setPluginBusy(true); + setPluginError(false); + try { setPlugin(await getLinuxInputPluginStatus()); } + catch { setPluginError(true); } + finally { setPluginBusy(false); } + }; + useEffect(() => { if (linux) void refreshPlugin(); }, [linux]); const active = useRef(false); const pendingPermissions = useRef | null>(null); const recheckOnReturn = useRef(false); @@ -105,7 +123,7 @@ export function PermissionsSection() { if (!platformCaps) return; active.current = true; void refreshPermissions(); - if (platformCaps?.supportsDesktopHotkey === true) { + if (!linux && platformCaps?.supportsDesktopHotkey === true) { refreshHotkey(); } if (platformCaps?.platform !== 'android') { @@ -260,7 +278,53 @@ export function PermissionsSection() { )} - {platformCaps?.supportsDesktopHotkey === true && ( + {linux && ( + +
+ + {plugin?.insertionReady && plugin?.hotkeysReady && } + {pluginBusy + ? t('settings.permissions.checking') + : pluginError + ? zh + ? '检查失败' + : 'Check failed' + : plugin?.insertionReady && plugin?.hotkeysReady + ? zh + ? '已就绪' + : 'Ready' + : !plugin?.installed + ? zh + ? '未安装' + : 'Not installed' + : !plugin?.daemonRunning + ? zh + ? '未运行' + : 'Not running' + : !plugin?.loaded + ? zh + ? '未加载' + : 'Not loaded' + : zh + ? '需重载插件' + : 'Reload required'} + + void refreshPlugin()}> + {zh ? '重新检测' : 'Check again'} + +
+
+ )} + {linux && } + {linux && } + {!linux && platformCaps?.supportsDesktopHotkey === true && (
{hotkey?.state === 'failed' && hotkey.message && ( diff --git a/openless-all/app/src/features/input/RecordingInputSection.tsx b/openless-all/app/src/features/input/RecordingInputSection.tsx index d8dd5dd78..1132c9bd7 100644 --- a/openless-all/app/src/features/input/RecordingInputSection.tsx +++ b/openless-all/app/src/features/input/RecordingInputSection.tsx @@ -18,7 +18,7 @@ import { isPlainTextInsertionActive, pasteShortcutForPlainTextToggle, } from '../../lib/plainTextInsertion'; -import { isTauriHost } from '../../runtime/environment'; +import { isNativeDesktopHost, isTauriHost } from '../../runtime/environment'; import { getAutostartEnabled, getMacosMicrophoneMode, @@ -287,6 +287,10 @@ export function RecordingInputSection({ } const isAndroid = platformCaps?.platform === 'android'; + // 「插入与剪贴板」整组在 Linux 上还没实现(要补「写剪贴板 → 模拟粘贴」通道), + // 按约定先显示、整块置灰并标注「即将支持」,而不是直接藏掉。 + const clipboardInsertComingSoon = + platformCaps?.supportsClipboardPasteInsertion === false; const showDesktopInsert = showDesktopHotkey; const showDesktopStartup = showDesktopHotkey; const plainTextInsertionOn = isPlainTextInsertionActive(os === 'win', prefs.pasteShortcut); @@ -694,11 +698,12 @@ export function RecordingInputSection({ onToggle={(next) => savePrefs({ ...prefs, stableTranscriptionEnabled: next })} /> - {showDesktopHotkey && os === 'win' && ( + {/* 低延迟听写由 Windows 和 Linux 宿主实现;语音唤醒仍只在 Windows 可用。 */} + {showDesktopHotkey && (os === 'win' || os === 'linux') && ( <> @@ -714,7 +720,7 @@ export function RecordingInputSection({ onToggle={(next) => savePrefs({ ...prefs, voiceActivationEnabled: next })} /> - {prefs.voiceActivationEnabled && ( + {os === 'win' && prefs.voiceActivationEnabled && (
@@ -883,6 +890,7 @@ export function RecordingInputSection({ {t('settings.recording.startupGroupTitle')} - + @@ -1053,7 +1065,7 @@ function AutostartRow() { const [error, setError] = useState(null); useEffect(() => { - if (!isTauriHost()) { + if (!isNativeDesktopHost()) { setLoaded(true); return; } @@ -1067,7 +1079,7 @@ function AutostartRow() { }) .catch((err: unknown) => { console.error('[autostart] isEnabled failed', err); - if (!cancelled) setLoaded(true); + if (!cancelled) setError(err instanceof Error ? err.message : String(err)); }); return () => { cancelled = true; diff --git a/openless-all/app/src/features/input/SelectionWorkspaceSection.tsx b/openless-all/app/src/features/input/SelectionWorkspaceSection.tsx index f49f26108..391fbc311 100644 --- a/openless-all/app/src/features/input/SelectionWorkspaceSection.tsx +++ b/openless-all/app/src/features/input/SelectionWorkspaceSection.tsx @@ -7,7 +7,9 @@ import { ShortcutRecorder } from '../../components/ShortcutRecorder'; import { defaultSelectionPolishShortcut, getHotkeyStartStopLabel } from '../../lib/hotkey'; import { ASK_ANYTHING_AVAILABLE } from '../../lib/appVersion'; import { openVoiceEditWindow } from '../../api/voice-edit'; +import { getLinuxTextAccessStatus } from '../../api/permissions'; import { setSelectionPolishHotkey } from '../../api/hotkeys'; +import { listenHostEvent } from '../../lib/hostEventBus'; import { getPlatformCapabilities } from '../../runtime/platform'; import { useHotkeySettings } from '../../data/preferences'; import { Card } from '../../ui/layout/Card'; @@ -21,6 +23,8 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu const { prefs, capability, refresh, updatePrefs } = useHotkeySettings(); const [platformCaps, setPlatformCaps] = useState(null); const [extraControlsOpen, setExtraControlsOpen] = useState(false); + const [voiceEditNotice, setVoiceEditNotice] = useState(''); + const [fullField, setFullField] = useState(false); const [openPanelBusy, setOpenPanelBusy] = useState(false); const [openPanelError, setOpenPanelError] = useState(''); @@ -29,7 +33,10 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu setOpenPanelBusy(true); setOpenPanelError(''); try { + const access = platformCaps?.linuxHost ? await getLinuxTextAccessStatus() : null; + if (access) setFullField(access.enabled); await openVoiceEditWindow(); + setVoiceEditNotice(platformCaps?.linuxHost && !access?.enabled ? t('voiceEditLinuxHint') : ''); } catch (error) { setOpenPanelError(error instanceof Error ? error.message : String(error)); } finally { @@ -38,9 +45,19 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu }; useEffect(() => { - void getPlatformCapabilities().then(setPlatformCaps); + void getPlatformCapabilities().then((caps) => { + setPlatformCaps(caps); + if (caps.linuxHost) void getLinuxTextAccessStatus().then((status) => setFullField(status.enabled)).catch(() => {}); + }); }, []); + useEffect(() => { + if (!platformCaps?.linuxHost) return; + const show = listenHostEvent('voice-edit:show', () => setVoiceEditNotice('')); + const error = listenHostEvent('voice-edit:error', (message) => setOpenPanelError(String(message))); + return () => { show(); error(); }; + }, [platformCaps?.linuxHost]); + if ( !prefs || !capability || @@ -84,12 +101,13 @@ export function SelectionWorkspaceSection({ showShortcut = true }: { showShortcu + {voiceEditNotice && {voiceEditNotice}} {openPanelError ? (
{t('common.operationFailed')}: {openPanelError} diff --git a/openless-all/app/src/features/local-asr/index.tsx b/openless-all/app/src/features/local-asr/index.tsx index 54ba9f4f9..ff174be1f 100644 --- a/openless-all/app/src/features/local-asr/index.tsx +++ b/openless-all/app/src/features/local-asr/index.tsx @@ -86,7 +86,7 @@ import { Card } from '../../ui/layout/Card'; import { Collapsible } from '../../ui/controls/Collapsible'; import { PageHeader } from '../../ui/layout/PageHeader'; import { Pill } from '../../ui/controls/Pill'; -import { getRuntimeOS, isTauriHost } from '../../runtime/environment'; +import { getRuntimeOS, isLinuxHost, isTauriHost } from '../../runtime/environment'; import { getPlatformCapabilities } from '../../runtime/platform'; import { DownloadDialog, @@ -121,7 +121,7 @@ const IS_WINDOWS = OS === 'win'; const IS_QWEN_PLATFORM = OS === 'mac'; // sherpa-onnx models: Windows and arm64 Android (this page only shows where // the backend reports local ASR support). Foundry stays Windows-only. -const IS_SHERPA_PLATFORM = IS_WINDOWS || OS === 'android'; +const IS_SHERPA_PLATFORM = IS_WINDOWS || OS === 'android' || isLinuxHost(); function effectiveModelMirror(modelId: string, mirror: string): LocalAsrMirror { if (mirror === 'modelscope' && !modelId.startsWith('qwen3-asr-')) return 'huggingface'; @@ -713,7 +713,7 @@ export function LocalAsr({ embedded = false }: LocalAsrProps = {}) { }, []); useEffect(() => { - if (!isTauriHost() || !IS_SHERPA_PLATFORM) return; + if (!(isTauriHost() || isLinuxHost()) || !IS_SHERPA_PLATFORM) return; let unlisten: undefined | (() => void); let cancelled = false; (async () => { @@ -743,7 +743,7 @@ export function LocalAsr({ embedded = false }: LocalAsrProps = {}) { }, []); useEffect(() => { - if (!isTauriHost() || !IS_SHERPA_PLATFORM) return; + if (!(isTauriHost() || isLinuxHost()) || !IS_SHERPA_PLATFORM) return; let unlisten: undefined | (() => void); let cancelled = false; (async () => { @@ -1623,7 +1623,7 @@ export function LocalAsr({ embedded = false }: LocalAsrProps = {}) { isActive: sherpaStatus?.activeModel === c.alias && activeAsrProvider === 'sherpa-onnx-local', engine: 'sherpa', - runtimeLabel: OS === 'android' ? 'Android · sherpa-onnx' : 'Windows · sherpa-onnx', + runtimeLabel: `${OS === 'android' ? 'Android' : isLinuxHost() ? 'Linux' : 'Windows'} · sherpa-onnx`, downloadError: sherpaDownloadProgress[c.alias]?.phase === 'failed' ? sherpaDownloadProgress[c.alias]?.error || t('localAsr.failed') diff --git a/openless-all/app/src/features/providers/ChannelList.test.ts b/openless-all/app/src/features/providers/ChannelList.test.ts index fb14001bd..7dbb5e7a2 100644 --- a/openless-all/app/src/features/providers/ChannelList.test.ts +++ b/openless-all/app/src/features/providers/ChannelList.test.ts @@ -41,6 +41,7 @@ const expectedByPlatform: Record = { // arm64 Android links sherpa-onnx; Foundry stays Windows-only. android: ['sherpa-onnx-local'], harmony: [], + linux: ['sherpa-onnx-local'], }; // Production receives this catalog from Core. The test supplies only the @@ -99,11 +100,10 @@ if (intelMacIds.has('local-qwen3-mlx') || intelMacIds.has('local-qwen3-c')) { throw new Error('legacy models must not be offered on either Intel or Apple Silicon macOS'); } -const unsupportedAndroidIds = new Set( - asrPresets('android', true, undefined, false).map((preset) => preset.id), -); -if (unsupportedAndroidIds.has('sherpa-onnx-local')) { - throw new Error('sherpa-onnx must stay hidden on Android ABIs without the native runtime'); +for (const os of ['android', 'linux'] as const) { + if (asrPresets(os, true, undefined, false).some((preset) => preset.id === 'sherpa-onnx-local')) { + throw new Error(`sherpa-onnx must stay hidden on ${os} builds without the native runtime`); + } } const legacyQwenEditIds = new Set( diff --git a/openless-all/app/src/features/providers/channelCatalog.ts b/openless-all/app/src/features/providers/channelCatalog.ts index 6b2e26ede..b46b8d248 100644 --- a/openless-all/app/src/features/providers/channelCatalog.ts +++ b/openless-all/app/src/features/providers/channelCatalog.ts @@ -2,6 +2,7 @@ import { useTranslation } from 'react-i18next'; import { type ProviderDescriptor } from '../../api/providers'; import { isExperimentalAsrProvider, isRetiredMacAsrProvider } from '../../lib/experimentalAsr'; import { type OS } from '../../runtime/environment'; +import { supportsSherpaRuntime } from '../../runtime/platform'; import { ASR_LABELS, LLM_LABELS } from './labels'; export type ChannelKind = 'llm' | 'asr'; @@ -50,9 +51,9 @@ export function presetsFor( if (p.id === 'local-qwen3-c') return os === 'mac'; if (p.id === 'local-qwen3') return false; if (p.id === 'foundry-local-whisper') return os === 'win'; - // sherpa-onnx also runs on arm64 Android; the capability is ABI-aware. + // Linux and Android availability depends on the installed build/ABI. if (p.id === 'sherpa-onnx-local') { - return os === 'win' || (os === 'android' && supportsLocalAsr); + return supportsSherpaRuntime(os, supportsLocalAsr); } // The two old Bailian ids are historical aliases; the unified entry is `bailian`, so new cards must not pick them. if (p.id === 'bailian-qwen3-realtime' || p.id === 'bailian-fun-asr-flash') return false; diff --git a/openless-all/app/src/features/qa/AskTool.tsx b/openless-all/app/src/features/qa/AskTool.tsx new file mode 100644 index 000000000..fd25aebf1 --- /dev/null +++ b/openless-all/app/src/features/qa/AskTool.tsx @@ -0,0 +1,17 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { openAskWindow } from '../../api/ask-window'; +import { Button } from '../../ui/controls/Button'; +import { Card } from '../../ui/layout/Card'; +import { PageHeader } from '../../ui/layout/PageHeader'; + +export function AskTool() { + const { t } = useTranslation(); + const [error, setError] = useState(''); + const open = () => { setError(''); void openAskWindow().catch((reason) => setError(String(reason))); }; + useEffect(() => { open(); }, []); + return <> + + {error &&

{error}

} +
; +} diff --git a/openless-all/app/src/features/qa/LinuxQaWindow.tsx b/openless-all/app/src/features/qa/LinuxQaWindow.tsx new file mode 100644 index 000000000..407dbbe96 --- /dev/null +++ b/openless-all/app/src/features/qa/LinuxQaWindow.tsx @@ -0,0 +1,76 @@ +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { invokeOrPreview, listenTauriEvent } from '../../runtime/transport'; +import { copyTextToClipboard } from '../../api/files'; +import { AssistantMarkdown } from './chat/markdown'; +import { Button } from '../../ui/controls/Button'; +import { useInteraction } from '../../ui/overlays/InteractionProvider'; + +interface Snapshot { + phase: string; + sessionId?: string; + messages: { id: string; role: string; content: string }[]; + lastError?: string; +} + +/** View only. Core's existing QA service owns recording, turns and cancellation. + * No attachment/system-context promises: those require the separate Ask host. */ +export function LinuxQaWindow() { + const { i18n } = useTranslation(); + const zh = i18n.language.startsWith('zh'); + const { notify } = useInteraction('linux-qa'); + const [snapshot, setSnapshot] = useState({ phase: 'idle', messages: [] }); + const [draft, setDraft] = useState(''); + const [pending, setPending] = useState(false); + const refresh = useRef<() => Promise>(async () => {}); + useEffect(() => { + let active = true, requested = 0, unsubscribe = () => {}; + refresh.current = async () => { + const request = ++requested; + try { + const next = await invokeOrPreview('qa_get_snapshot', undefined, () => ({ phase: 'idle', messages: [] })); + if (active && request === requested) setSnapshot(next); + } catch (error) { + if (active) notify({ key: 'linux-qa-load', state: 'failed', message: String(error) }); + } + }; + void listenTauriEvent('qa:state', () => { void refresh.current(); }).then((off) => { + if (!active) off(); else { unsubscribe = off; void refresh.current(); } + }).catch((error) => { if (active) notify({ state: 'failed', message: String(error) }); }); + return () => { active = false; unsubscribe(); }; + }, [notify]); + const run = async (command: string, args?: Record) => { + try { await invokeOrPreview(command, args, () => undefined); } + catch (error) { notify({ state: 'failed', message: String(error) }); } + finally { await refresh.current(); } + }; + const working = snapshot.phase === 'thinking' || snapshot.phase === 'recording'; + return ( +
+
+ {zh ? '问答' : 'Questions'} + +
+
+ {!snapshot.messages.length &&

{zh ? '输入问题或点击语音开始提问。' : 'Type a question or start a voice question.'}

} + {snapshot.messages.map((message) =>
+ {message.role === 'user' ? (zh ? '你' : 'You') : 'OpenLess'} + + {message.content && } +
)} + {snapshot.lastError &&

{snapshot.lastError}

} +
+