diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38e54a31d..ce9d67dd7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,7 +91,6 @@ jobs: # 并在判定为发布改动时就地校验 changelog 与版本号;其余 PR 照旧跑全量测试。 classify: name: Classify changes - if: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest outputs: release_only: ${{ steps.check.outputs.release_only }} @@ -105,11 +104,17 @@ jobs: env: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: python3 script/release_pr.py check + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + python3 script/release_pr.py check + else + # 非 PR 事件也必须产生成功输出;否则 needs 此 job 的矩阵会被整体跳过。 + echo "release_only=false" >> "$GITHUB_OUTPUT" + fi - # PR 快车道:Linux 跑完整 `cargo test --all`;macOS / Windows 只编译 - # (`cargo check --workspace --all-targets`,含测试目标)不链接、不跑测试, - # 平台相关的编译问题仍然会在 PR 阶段暴露。完整三平台测试在 push main + # PR 快车道:Linux 跑完整 `cargo test --all`;macOS / Windows 的 workspace + # 只做 `cargo check --workspace --all-targets`(含测试目标),不链接、不跑测试; + # Windows 额外定向运行真实内嵌 X11 lib 测试。完整三平台测试在 push main # 与 workflow_dispatch 时执行。 test: name: Test (${{ matrix.platform }}, ${{ matrix.target }}) @@ -122,6 +127,38 @@ jobs: runs-on: ${{ matrix.run_on }} steps: - uses: actions/checkout@v7 + - name: Set up Python for Windows X11 component + if: ${{ matrix.platform == 'windows' }} + uses: actions/setup-python@v6 + with: + python-version: "3.x" + - name: Prepare embedded Windows X11 component + id: x11-component + if: ${{ matrix.platform == 'windows' }} + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $archive = Join-Path $env:RUNNER_TEMP "navop-x11-windows-x86_64.zip" + # PowerShell 不默认暴露 Git for Windows 的 usr\bin;只在本 step + # 补上其中的 OpenSSL,避免依赖 runner 的偶然 PATH,也不改写全局 PATH。 + $gitOpenSsl = Join-Path $env:ProgramFiles "Git\usr\bin\openssl.exe" + if (Test-Path -LiteralPath $gitOpenSsl -PathType Leaf) { + $env:Path = "$(Split-Path -Parent $gitOpenSsl);$env:Path" + } + Get-Command python -ErrorAction Stop | Out-Null + Get-Command openssl -ErrorAction Stop | Out-Null + python --version + openssl version + python script/prepare-windows-x11-component.py ` + --target windows-x86_64 ` + --output $archive + if ($LASTEXITCODE -ne 0) { + throw "Windows X11 component preparation failed with exit code $LASTEXITCODE" + } + if (-not (Test-Path -LiteralPath $archive -PathType Leaf)) { + throw "Prepared Windows X11 component is missing: '$archive'" + } + "archive=$archive" >> $env:GITHUB_OUTPUT # gpui 单个 crate 的 rustc 命令行在 Windows 上约 35K 字符(大量 # `--extern` / `-L dependency` 长路径),超过 CreateProcess 的 32,767 # 上限;sccache 冷编译时会以 `os error 206` 失败。把 target 目录换到 @@ -225,11 +262,27 @@ jobs: uses: ilammy/msvc-dev-cmd@v1 with: arch: x64 - # PR 快车道:macOS / Windows 只编译(含测试目标),不链接、不跑测试。 - # 完整测试仍在 Linux 以及 push main / 手动触发时跑三平台。 + # PR 快车道:macOS / Windows 的 workspace 只编译(含测试目标),不链接、不跑测试。 + # 完整测试仍在 Linux 以及 push main / 手动触发时跑三平台;X11 定向 lib 测试例外见下。 - name: Check the workspace (PR fast lane) if: ${{ github.event_name == 'pull_request' && matrix.platform != 'linux' }} run: cargo check --workspace --all-targets + # 只给 lib 测试注入真实组件:它同时编译内嵌构建并运行 + # configured_archive_matches_its_pinned_manifest,验证 SHA256 + Ed25519。 + # 后续 workspace check / test-windows.ps1 不继承该 env;普通测试不访问组件网络。 + - name: Test Windows X11 component with real embedded archive + if: ${{ matrix.platform == 'windows' }} + shell: pwsh + env: + NAVOP_X11_BUNDLED_ARCHIVE: ${{ steps.x11-component.outputs.archive }} + run: | + if ([string]::IsNullOrWhiteSpace($env:NAVOP_X11_BUNDLED_ARCHIVE)) { + throw "NAVOP_X11_BUNDLED_ARCHIVE is missing" + } + cargo test --locked -p x11_component --lib --target ${{ matrix.target }} + if ($LASTEXITCODE -ne 0) { + throw "Embedded x11_component lib tests failed with exit code $LASTEXITCODE" + } - name: Test Windows if: ${{ matrix.platform == 'windows' && github.event_name != 'pull_request' }} shell: pwsh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 56d91b218..567e7fecd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -169,23 +169,25 @@ jobs: # 资产名({binary}-{target}.tar.gz|.zip),bundle_name 是 macOS # .app 目录名,portable_marker 是便携版标记文件名。全量与独立 # 产品同 tag 发布,公开产物名统一 {product}-{version}-{label}。 - macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop","binary":"navop","archive":"navop-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false}' - macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop","binary":"navop","archive":"navop-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false}' - linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop","binary":"navop","archive":"navop-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false}' - linux_arm64='{"target":"aarch64-unknown-linux-gnu","os":"ubuntu-24.04-arm","product":"navop","binary":"navop","archive":"navop-aarch64-unknown-linux-gnu.tar.gz","public_label":"linux-arm64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":true,"windows_native_rdp":false}' - windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop","binary":"navop.exe","archive":"navop-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64"}' - windows_x86='{"target":"i686-pc-windows-msvc","os":"windows-latest","product":"navop","binary":"navop.exe","archive":"navop-i686-pc-windows-msvc.zip","public_label":"win32","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x86"}' + macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop","binary":"navop","archive":"navop-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop","binary":"navop","archive":"navop-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop","binary":"navop","archive":"navop-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + linux_arm64='{"target":"aarch64-unknown-linux-gnu","os":"ubuntu-24.04-arm","product":"navop","binary":"navop","archive":"navop-aarch64-unknown-linux-gnu.tar.gz","public_label":"linux-arm64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":true,"windows_native_rdp":false,"x11_target":""}' + windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop","binary":"navop.exe","archive":"navop-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64","x11_target":"windows-x86_64"}' + # i686 明确不内嵌;空 x11_target 同时保证不注入 bundle env。 + windows_x86='{"target":"i686-pc-windows-msvc","os":"windows-latest","product":"navop","binary":"navop.exe","archive":"navop-i686-pc-windows-msvc.zip","public_label":"win32","bundle_name":"Navop","portable_marker":"navop.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x86","x11_target":""}' # 独立产品只覆盖主力平台(无 linux-arm64 / win32),对齐原 # standalone-products.yml 的平台面;win32 的 shell-plugins 依赖 # 仅支持 64 位,等独立产品需要 32 位时再单独评估。 - shell_macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false}' - shell_macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false}' - shell_linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false}' - shell_windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop-shell","binary":"navop-shell.exe","archive":"navop-shell-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64"}' - data_macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop-data","binary":"navop-data","archive":"navop-data-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false}' - data_macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop-data","binary":"navop-data","archive":"navop-data-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false}' - data_linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop-data","binary":"navop-data","archive":"navop-data-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false}' - data_windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop-data","binary":"navop-data.exe","archive":"navop-data-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64"}' + shell_macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + shell_macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + shell_linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop-shell","binary":"navop-shell","archive":"navop-shell-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + shell_windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop-shell","binary":"navop-shell.exe","archive":"navop-shell-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop Shell","portable_marker":"navop-shell.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64","x11_target":"windows-x86_64"}' + data_macos_arm64='{"target":"aarch64-apple-darwin","os":"macos-latest","product":"navop-data","binary":"navop-data","archive":"navop-data-aarch64-apple-darwin.tar.gz","public_label":"macos-arm64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + data_macos_x64='{"target":"x86_64-apple-darwin","os":"macos-15-intel","product":"navop-data","binary":"navop-data","archive":"navop-data-x86_64-apple-darwin.tar.gz","public_label":"macos-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + data_linux_x64='{"target":"x86_64-unknown-linux-gnu","os":"ubuntu-latest","product":"navop-data","binary":"navop-data","archive":"navop-data-x86_64-unknown-linux-gnu.tar.gz","public_label":"linux-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":false,"x11_target":""}' + # standalone-data 与 full i686 不准备、不内嵌;使用内置 X11 时明确失败,无网络回退。 + data_windows_x64='{"target":"x86_64-pc-windows-msvc","os":"windows-latest","product":"navop-data","binary":"navop-data.exe","archive":"navop-data-x86_64-pc-windows-msvc.zip","public_label":"windows-x64","bundle_name":"Navop Data","portable_marker":"navop-data.portable","arm_linux":false,"windows_native_rdp":true,"windows_arch":"x64","x11_target":""}' case "$RELEASE_PLATFORM" in all) @@ -369,6 +371,45 @@ jobs: "$RUNNER_TEMP/ziglang/bin/python" -m ziglang version cargo-zigbuild --version + - name: Set up Python for embedded Windows X11 component + if: runner.os == 'Windows' && matrix.x11_target != '' + uses: actions/setup-python@v6 + with: + python-version: "3.x" + + - name: Prepare embedded Windows X11 component + id: x11-component + if: runner.os == 'Windows' && matrix.x11_target != '' + shell: pwsh + env: + X11_TARGET: ${{ matrix.x11_target }} + run: | + $ErrorActionPreference = "Stop" + if ($env:X11_TARGET -ne "windows-x86_64") { + throw "Unexpected Windows X11 release target: '$env:X11_TARGET'" + } + $archive = Join-Path $env:RUNNER_TEMP "navop-x11-$env:X11_TARGET.zip" + # 只在本 step 暴露 Git for Windows 自带的 OpenSSL;不写 GITHUB_PATH, + # 不改变后续 Cargo / RDP probe 的工具解析顺序。 + $gitOpenSsl = Join-Path $env:ProgramFiles "Git\usr\bin\openssl.exe" + if (Test-Path -LiteralPath $gitOpenSsl -PathType Leaf) { + $env:Path = "$(Split-Path -Parent $gitOpenSsl);$env:Path" + } + Get-Command python -ErrorAction Stop | Out-Null + Get-Command openssl -ErrorAction Stop | Out-Null + python --version + openssl version + python script/prepare-windows-x11-component.py ` + --target $env:X11_TARGET ` + --output $archive + if ($LASTEXITCODE -ne 0) { + throw "Windows X11 component preparation failed with exit code $LASTEXITCODE" + } + if (-not (Test-Path -LiteralPath $archive -PathType Leaf)) { + throw "Prepared Windows X11 component is missing: '$archive'" + } + "archive=$archive" >> $env:GITHUB_OUTPUT + - name: Configure MSVC environment if: runner.os == 'Windows' uses: ilammy/msvc-dev-cmd@v1 @@ -477,7 +518,13 @@ jobs: NAVOP_PUBLIC_BASE_URL: ${{ vars.NAVOP_PUBLIC_BASE_URL }} NAVOP_WEBSITE_BASE_URL: ${{ vars.NAVOP_WEBSITE_BASE_URL }} ONETCLI_TEAM_MANAGEMENT_URL_TEMPLATE: ${{ vars.ONETCLI_TEAM_MANAGEMENT_URL_TEMPLATE }} + # 非内嵌矩阵项的 output 不存在,表达式得到空字符串;下一步立即清除, + # 使 build.rs 看到“变量缺失”而不是会报错的空路径。 + NAVOP_X11_BUNDLED_ARCHIVE: ${{ steps.x11-component.outputs.archive }} run: | + if ([string]::IsNullOrWhiteSpace($env:NAVOP_X11_BUNDLED_ARCHIVE)) { + Remove-Item Env:NAVOP_X11_BUNDLED_ARCHIVE -ErrorAction SilentlyContinue + } if ([string]::IsNullOrWhiteSpace($env:VCToolsInstallDir)) { throw "VCToolsInstallDir is not configured" } @@ -537,6 +584,37 @@ jobs: throw "Release binary was not created: '$binary'" } + - name: Verify embedded X11 archive in release binary + if: runner.os == 'Windows' && matrix.x11_target != '' + shell: pwsh + env: + NAVOP_X11_BUNDLED_ARCHIVE: ${{ steps.x11-component.outputs.archive }} + RELEASE_BINARY: target/${{ matrix.target }}/release/${{ matrix.binary }} + run: | + if ([string]::IsNullOrWhiteSpace($env:NAVOP_X11_BUNDLED_ARCHIVE)) { + throw "NAVOP_X11_BUNDLED_ARCHIVE is missing" + } + # 只读取 Windows 本地产物,不执行其中任何二进制。完整 zip 字节必须 + # 出现在 exe 中,直接排除 build.rs 静默生成空占位或漏嵌的情况。 + @' + from pathlib import Path + import hashlib + import os + + archive = Path(os.environ["NAVOP_X11_BUNDLED_ARCHIVE"]) + binary = Path(os.environ["RELEASE_BINARY"]) + payload = archive.read_bytes() + executable = binary.read_bytes() + if not payload: + raise SystemExit("Prepared X11 archive is empty") + if payload not in executable: + raise SystemExit(f"Embedded X11 archive was not found in {binary}") + print( + f"Verified embedded X11 archive in {binary}: " + f"{len(payload)} bytes, sha256={hashlib.sha256(payload).hexdigest()}" + ) + '@ | python - + - name: Validate Windows executable manifest if: runner.os == 'Windows' shell: pwsh diff --git a/Cargo.lock b/Cargo.lock index 063df3409..a65b1fd9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4452,6 +4452,16 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -8365,6 +8375,7 @@ dependencies = [ "remote_desktop_view", "remote_file_editor", "rust-i18n", + "semver", "serde", "serde_json", "serde_yaml", @@ -8384,6 +8395,7 @@ dependencies = [ "uuid", "windows 0.62.2", "workspace_explorer", + "x11_component", "x11rb", "zed-font-kit 0.14.1-zed (git+https://github.com/zed-industries/font-kit?rev=110523127440aefb11ce0cf280ae7c5071337ec5)", "zeroize", @@ -9003,7 +9015,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -9482,6 +9494,7 @@ dependencies = [ "serde_yaml", "sha2 0.10.9", "smallvec", + "ssh-key", "sys-locale", "tempfile", "thiserror 2.0.21", @@ -9492,6 +9505,7 @@ dependencies = [ "tracing", "uuid", "windows 0.61.3", + "x11_component", "zeroize", ] @@ -11044,7 +11058,7 @@ dependencies = [ "quinn-udp", "rustc-hash 2.1.3", "rustls 0.23.45", - "socket2 0.5.10", + "socket2 0.6.5", "thiserror 2.0.21", "tokio", "tracing", @@ -11082,7 +11096,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.5.10", + "socket2 0.6.5", "tracing", "windows-sys 0.61.2", ] @@ -12837,7 +12851,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" dependencies = [ "annotate-snippets", - "base64 0.21.7", + "base64 0.23.1", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -13081,6 +13095,7 @@ dependencies = [ "one-assets", "one-core", "one-ui", + "otp", "remote_file_editor", "remote_image_preview", "rust-i18n", @@ -13588,6 +13603,7 @@ dependencies = [ "tokio-socks", "tokio-util", "tracing", + "x11_component", "x11_forwarding", ] @@ -13673,6 +13689,7 @@ dependencies = [ "tokio", "tool_runtime", "tracing", + "x11_component", ] [[package]] @@ -17367,6 +17384,31 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11_component" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "dirs 6.0.0", + "ed25519-dalek 2.2.0", + "fs2", + "hex", + "libc", + "libloading", + "process-util", + "rand 0.8.8", + "semver", + "serde", + "serde_json", + "sha2 0.10.9", + "sysinfo", + "thiserror 2.0.21", + "tokio", + "tracing", + "x11_forwarding", + "zip 2.4.2", +] + [[package]] name = "x11_forwarding" version = "0.15.2" diff --git a/Cargo.toml b/Cargo.toml index f569a9fb4..85ca2217c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,7 @@ members = [ "crates/ssh", "crates/otp", "crates/x11_forwarding", + "crates/x11_component", "crates/sftp", "crates/ftp", "crates/sftp_transfer", @@ -183,6 +184,13 @@ one-ui = { path = "crates/one_ui" } one-assets = { path = "crates/one-assets" } ssh = { path = "crates/ssh" } x11_forwarding = { path = "crates/x11_forwarding" } +x11_component = { path = "crates/x11_component" } +http_client = { package = "gpui-pre-http-client", version = "0.3.99" } +ed25519-dalek = "2.2.0" +fs2 = "0.4.3" +libloading = "0.8.9" +libc = "0.2" +zip = { version = "2.4.2", default-features = false, features = ["deflate"] } sftp = { path = "crates/sftp" } ftp = { path = "crates/ftp" } sftp_transfer = { path = "crates/sftp_transfer" } diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index b09ad62bd..c5a537b49 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -39,12 +39,21 @@ rand.workspace = true base64.workspace = true sha2.workspace = true ed25519-dalek = "2.2.0" +# 「生成密钥」里 ECDSA / RSA 的 OpenSSH 编码复用 ssh-key;版本与 russh 的传递依赖保持一致。 +ssh-key = { version = "0.7.0-rc.11", features = [ + "ed25519", + "p256", + "p384", + "rsa", + "getrandom", +] } parking_lot.workspace = true tool_runtime.workspace = true util.workspace = true process-util.workspace = true rust-i18n.workspace = true sys-locale.workspace = true +x11_component.workspace = true [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 04c61b02e..20bf9637e 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -29,6 +29,11 @@ pub use locale::{ pub use remote_file_editor::{ RemoteFileEditorOverride, RemoteFileEditorUserSettings, RemoteFileOpenMode, }; +pub use x11_component::{ + X11ComponentError, X11ForwardingStatus, X11RestartNotification, X11ServerMode, configured_mode, + current_status, installed_version, reinstall, take_restart_notification, + take_restart_notification_for, +}; // ============================================================================ // 全局用户状态 @@ -1422,6 +1427,9 @@ pub struct AppSettings { pub terminal_enable_autocomplete: bool, #[serde(default = "default_true")] pub terminal_show_suggestion_popup: bool, + /// 是否在终端面板右上角显示包含分屏与录制按钮的悬浮工具条。 + #[serde(default = "default_true")] + pub terminal_show_pane_toolbar: bool, /// 命令提示 / cd 补全 / 历史搜索下拉弹层的背景不透明度。 /// /// 弹层背景画在终端内容之上,下层文字以 (1 - α) 的权重透进弹层:0.72 @@ -1503,6 +1511,9 @@ pub struct AppSettings { pub personal_sync: PersonalSyncSettings, #[serde(default)] pub remote_file_editor: RemoteFileEditorUserSettings, + /// 新 SSH 会话使用的 X11 服务;缺省自动选择以保持旧配置兼容。 + #[serde(default)] + pub x11_server_mode: X11ServerMode, #[serde(default = "default_true")] pub direct_server_transfer_enabled: bool, /// 文件传输发生文件夹冲突时,默认把「合并」作为推荐选项(issue #176)。 @@ -1897,6 +1908,7 @@ impl Default for AppSettings { terminal_auto_copy: default_true(), terminal_enable_autocomplete: default_true(), terminal_show_suggestion_popup: default_true(), + terminal_show_pane_toolbar: default_true(), terminal_suggestion_popup_opacity: default_terminal_suggestion_popup_opacity(), terminal_middle_click_paste: default_true(), terminal_right_click_paste: false, @@ -1927,6 +1939,7 @@ impl Default for AppSettings { ai_chat: AiChatSettings::default(), personal_sync: PersonalSyncSettings::default(), remote_file_editor: RemoteFileEditorUserSettings::default(), + x11_server_mode: X11ServerMode::default(), direct_server_transfer_enabled: true, transfer_prefer_merge_for_directories: true, transfer_prefer_overwrite_for_files: true, @@ -2169,6 +2182,7 @@ impl AppSettings { settings.normalize_font_settings(); settings.normalize_appearance_settings(); settings.normalize_terminal_settings(); + Self::apply_runtime_x11_mode(&settings); cx.set_global(settings); } @@ -2179,6 +2193,7 @@ impl AppSettings { settings.normalize_appearance_settings(); settings.normalize_terminal_settings(); settings.save(); + Self::apply_runtime_x11_mode(&settings); cx.set_global(settings); } @@ -2199,15 +2214,16 @@ impl AppSettings { } pub fn load() -> Self { - let Some(path) = Self::config_path() else { - return Self::default(); - }; - - if !path.exists() { - return Self::default(); - } + let settings = Self::config_path() + .filter(|path| path.exists()) + .map_or_else(Self::default, |path| Self::load_from(&path)); + Self::apply_runtime_x11_mode(&settings); + settings + } - Self::load_from(&path) + /// 只同步进程级选择;`load_from` 保持纯读取,避免隔离测试污染全局。 + fn apply_runtime_x11_mode(settings: &Self) { + x11_component::set_configured_mode(settings.x11_server_mode); } /// 只把 settings.json 里的 `log_file_path` 取出来,不做整份反序列化。 @@ -2591,6 +2607,65 @@ mod tests { assert!(legacy.deeplink_scheme_enabled("jms")); } + #[test] + fn x11_server_mode_defaults_to_auto_and_reads_snake_case() { + let legacy: AppSettings = serde_json::from_str("{}").expect("旧配置应保持兼容"); + assert_eq!(x11_component::X11ServerMode::Auto, legacy.x11_server_mode); + assert_eq!( + x11_component::X11ServerMode::Auto, + AppSettings::default().x11_server_mode + ); + + let external: AppSettings = + serde_json::from_str(r#"{"x11_server_mode":"external"}"#).expect("读取外部模式"); + let embedded: AppSettings = + serde_json::from_str(r#"{"x11_server_mode":"embedded"}"#).expect("读取内置模式"); + assert_eq!( + x11_component::X11ServerMode::External, + external.x11_server_mode + ); + assert_eq!( + x11_component::X11ServerMode::Embedded, + embedded.x11_server_mode + ); + } + + #[gpui::test] + fn x11_runtime_mode_tracks_settings_without_load_from_pollution(cx: &mut gpui::TestAppContext) { + let original = x11_component::configured_mode(); + x11_component::set_configured_mode(x11_component::X11ServerMode::External); + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("settings.json"); + std::fs::write(&path, r#"{"x11_server_mode":"embedded"}"#).expect("写入测试配置"); + + let loaded = AppSettings::load_from(&path); + assert_eq!( + x11_component::X11ServerMode::Embedded, + loaded.x11_server_mode + ); + assert_eq!( + x11_component::X11ServerMode::External, + x11_component::configured_mode() + ); + + AppSettings::apply_runtime_x11_mode(&loaded); + assert_eq!( + x11_component::X11ServerMode::Embedded, + x11_component::configured_mode() + ); + cx.update(|cx| { + cx.set_global(loaded); + AppSettings::update(cx, |settings| { + settings.x11_server_mode = x11_component::X11ServerMode::External; + }); + }); + assert_eq!( + x11_component::X11ServerMode::External, + x11_component::configured_mode() + ); + x11_component::set_configured_mode(original); + } + #[test] fn corrupt_settings_file_is_quarantined_instead_of_silently_reset() { // 回归保护:解析失败若直接回落 Default、再被启动期任意一次 save() 全量覆盖, diff --git a/crates/core/src/storage/credential_vault/keygen_openssh.rs b/crates/core/src/storage/credential_vault/keygen_openssh.rs new file mode 100644 index 000000000..504f9f6c6 --- /dev/null +++ b/crates/core/src/storage/credential_vault/keygen_openssh.rs @@ -0,0 +1,179 @@ +//! 「生成密钥」里 Ed25519 之外的算法:ECDSA 与 RSA。 +//! +//! 编码交给 `ssh-key`,输出结构与 `keygen.rs` 里手写的 Ed25519 一致: +//! 未加密的 `openssh-key-v1` 私钥、一行 `authorized_keys` 公钥、SHA256 指纹。 + +use ssh_key::{ + Comment, EcdsaCurve, HashAlg, LineEnding, PrivateKey, + getrandom::SysRng, + private::{EcdsaKeypair, KeypairData, RsaKeypair}, + rand_core::UnwrapErr, +}; + +use super::keygen::{GeneratedSshKey, generate_ed25519_key}; + +/// RSA 密钥位数:3072 位兼顾兼容性与生成耗时,4096 位在低配机器上要等数秒。 +const RSA_KEY_SIZE: usize = 3072; + +/// 「生成密钥」可选的算法。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SshKeyAlgorithm { + /// Ed25519,默认且最通用。 + Ed25519, + /// ECDSA NIST P-256。 + EcdsaP256, + /// ECDSA NIST P-384。 + EcdsaP384, + /// RSA 3072 位。 + Rsa3072, +} + +impl SshKeyAlgorithm { + /// 下拉框里的全部可选项,顺序即展示顺序。 + pub const ALL: [SshKeyAlgorithm; 4] = [ + SshKeyAlgorithm::Ed25519, + SshKeyAlgorithm::EcdsaP256, + SshKeyAlgorithm::EcdsaP384, + SshKeyAlgorithm::Rsa3072, + ]; +} + +/// 按指定算法生成一对 SSH 密钥。 +/// +/// Ed25519 仍走手写编码,保证 `keygen.rs` 里已有的格式约束不变;其余算法交给 +/// `ssh-key` 生成并编码。RSA 生成较慢,调用方应放到后台线程执行。 +pub fn generate_ssh_key( + algorithm: SshKeyAlgorithm, + comment: &str, +) -> Result { + match algorithm { + SshKeyAlgorithm::Ed25519 => Ok(generate_ed25519_key(comment)), + SshKeyAlgorithm::EcdsaP256 => generate_ecdsa_key(EcdsaCurve::NistP256, comment), + SshKeyAlgorithm::EcdsaP384 => generate_ecdsa_key(EcdsaCurve::NistP384, comment), + SshKeyAlgorithm::Rsa3072 => generate_rsa_key(comment), + } +} + +/// 生成 ECDSA 密钥;曲线支持取决于 `ssh-key` 的 p256 / p384 特性。 +fn generate_ecdsa_key(curve: EcdsaCurve, comment: &str) -> Result { + let mut rng = UnwrapErr(SysRng); + let keypair = EcdsaKeypair::random(&mut rng, curve).map_err(|error| error.to_string())?; + encode_keypair(KeypairData::Ecdsa(keypair), comment) +} + +/// 生成 RSA 密钥;3072 位通常需要零点几秒,慢机器上可能更久。 +fn generate_rsa_key(comment: &str) -> Result { + let mut rng = UnwrapErr(SysRng); + let keypair = RsaKeypair::random(&mut rng, RSA_KEY_SIZE).map_err(|error| error.to_string())?; + encode_keypair(KeypairData::Rsa(keypair), comment) +} + +/// 把密钥对编码成私钥文本、公钥文本与指纹三件套。 +fn encode_keypair(keypair: KeypairData, comment: &str) -> Result { + let key = PrivateKey::new(keypair, Comment::from(comment.trim())) + .map_err(|error| error.to_string())?; + let fingerprint = key.fingerprint(HashAlg::Sha256).to_string(); + let public_key_openssh = key + .public_key() + .to_openssh() + .map_err(|error| error.to_string())?; + let private_key_openssh = key + .to_openssh(LineEnding::LF) + .map_err(|error| error.to_string())? + .to_string(); + + Ok(GeneratedSshKey { + private_key_openssh, + public_key_openssh, + fingerprint, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 生成的密钥要能被 `ssh-key` 自己解析回来,算法与注释都对得上。 + #[test] + fn every_algorithm_parses_back_with_the_expected_name_and_comment() { + let cases = [ + (SshKeyAlgorithm::EcdsaP256, "ecdsa-sha2-nistp256"), + (SshKeyAlgorithm::EcdsaP384, "ecdsa-sha2-nistp384"), + (SshKeyAlgorithm::Rsa3072, "ssh-rsa"), + ]; + + for (algorithm, name) in cases { + let key = generate_ssh_key(algorithm, "工作机").expect("generated key"); + assert!( + key.public_key_openssh.starts_with(&format!("{name} ")), + "{algorithm:?} 的公钥算法名不对:{}", + key.public_key_openssh + ); + assert!(key.public_key_openssh.ends_with(" 工作机")); + + let parsed = PrivateKey::from_openssh(&key.private_key_openssh).expect("可解析"); + assert_eq!(parsed.algorithm().as_str(), name); + assert!(!parsed.is_encrypted()); + assert_eq!( + parsed.fingerprint(HashAlg::Sha256).to_string(), + key.fingerprint + ); + + let public = parsed.public_key().to_openssh().expect("公钥编码"); + assert_eq!(public, key.public_key_openssh); + } + } + + #[test] + fn fingerprints_are_sha256_and_differ_between_generated_keys() { + let first = generate_ssh_key(SshKeyAlgorithm::EcdsaP256, "").expect("first"); + let second = generate_ssh_key(SshKeyAlgorithm::EcdsaP256, "").expect("second"); + + assert!(first.fingerprint.starts_with("SHA256:")); + assert_ne!(first.private_key_openssh, second.private_key_openssh); + assert_ne!(first.fingerprint, second.fingerprint); + } + + /// 用系统 `ssh-keygen` 交叉验证私钥真能被 OpenSSH 接受(RSA 生成慢,跳过)。 + #[cfg(unix)] + #[test] + fn openssh_accepts_the_generated_ecdsa_private_key() { + use std::process::Command; + + let key = generate_ssh_key(SshKeyAlgorithm::EcdsaP256, "navop-test").expect("generated"); + let dir = std::env::temp_dir().join(format!("navop-keygen-ecdsa-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + let path = dir.join("id_ecdsa"); + std::fs::write(&path, &key.private_key_openssh).expect("write private key"); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) + .expect("chmod private key"); + } + + let output = match Command::new("ssh-keygen") + .args(["-y", "-f"]) + .arg(&path) + .output() + { + Ok(output) => output, + Err(error) => { + let _ = std::fs::remove_dir_all(&dir); + eprintln!("跳过:无法执行 ssh-keygen({error})"); + return; + } + }; + let _ = std::fs::remove_dir_all(&dir); + + assert!( + output.status.success(), + "ssh-keygen 拒绝了生成的私钥:{}", + String::from_utf8_lossy(&output.stderr) + ); + let derived = String::from_utf8_lossy(&output.stdout); + assert!( + derived.starts_with("ecdsa-sha2-nistp256 "), + "推导出的公钥异常:{derived}" + ); + } +} diff --git a/crates/core/src/storage/credential_vault/mod.rs b/crates/core/src/storage/credential_vault/mod.rs index ddaaf800a..6c3c6b0eb 100644 --- a/crates/core/src/storage/credential_vault/mod.rs +++ b/crates/core/src/storage/credential_vault/mod.rs @@ -1,4 +1,5 @@ mod keygen; +mod keygen_openssh; mod models; mod reference_scanner; mod reference_types; @@ -8,6 +9,7 @@ mod runtime_resolver; mod tunnel_reference_scanner; pub use keygen::{GeneratedSshKey, generate_ed25519_key}; +pub use keygen_openssh::{SshKeyAlgorithm, generate_ssh_key}; pub use models::*; pub use reference_types::*; pub use repository::*; diff --git a/crates/core/src/storage/credential_vault/resolver.rs b/crates/core/src/storage/credential_vault/resolver.rs index 539080d54..8a0a31bbc 100644 --- a/crates/core/src/storage/credential_vault/resolver.rs +++ b/crates/core/src/storage/credential_vault/resolver.rs @@ -55,9 +55,11 @@ impl CredentialRepository { return Ok(params); }; let credential = self.resolve_reference_entry(reference)?; - // 选了钥匙串后表单里的用户名、认证方式、「连接时输入」都被隐藏, - // 保存下来的值不再参与:登录信息完全由钥匙串记录决定。 - let login = ssh_login_from_credential(reference, credential.as_ref())?; + // 认证方式与「连接时输入」完全由钥匙串记录决定;用户名在记录里没有时 + // 回退到连接上保存的值(表单会把这一栏放出来让用户填写)。 + let manual_username = params.username.clone(); + let login = + ssh_login_from_credential(reference, credential.as_ref(), Some(&manual_username))?; params.username = login.username; params.auth_method = login.auth_method; params.prompt_username = None; @@ -289,8 +291,10 @@ impl CredentialRepository { return Ok(()); }; let credential = self.resolve_reference_entry(reference)?; - // 选了钥匙串后表单里的用户名与认证方式都被隐藏,保存值不再参与。 - let login = ssh_login_from_credential(reference, credential.as_ref())?; + // 认证方式由钥匙串记录决定;用户名缺失时回退到跳板机自己保存的值。 + let manual_username = jump.username.clone(); + let login = + ssh_login_from_credential(reference, credential.as_ref(), Some(&manual_username))?; jump.username = login.username; jump.auth_method = login.auth_method; Ok(()) @@ -314,38 +318,26 @@ struct SshCredentialLogin { auth_method: SshAuthMethod, } -/// 完全按钥匙串记录的内容得出 SSH 用户名与认证方式。 +/// 由钥匙串记录得出 SSH 用户名与认证方式。 /// -/// 选中钥匙串后,表单会隐藏用户名与认证方式,用户无法再改它们,所以连接里 -/// 残留的保存值不能参与;`credential_reference` 里的各个布尔标志同样由表单 -/// 根据当时隐藏的状态算出,也不作依据。规则只有两条: +/// 认证方式完全按记录内容:只有密码用密码,只有私钥用私钥,两者都有时交给 +/// `SshAuthMethod::Chain`,由 SSH 层按服务器通告的方法决定试哪个(服务器只 +/// 接受其中一种就只用那一种,两种都接受则先密码)。 /// -/// - 用户名取记录里的用户名,为空就报错,绝不带着空用户名去连接; -/// - 记录里有什么凭据就用什么:只有密码用密码,只有私钥用私钥,两者都有时 -/// 交给 `SshAuthMethod::Chain`,由 SSH 层按服务器通告的方法决定试哪个 -/// (服务器只接受其中一种就只用那一种,两种都接受则按下面的顺序:先密码)。 +/// 用户名优先取记录里的用户名;记录里留空时回退到连接(或跳板机)上保存的 +/// 用户名 —— 表单在「钥匙串条目没有用户名」时会把用户名一栏放出来,让用户 +/// 随连接一起填写。两处都没有才报错,绝不带着空用户名去连接。 fn ssh_login_from_credential( reference: &crate::storage::CredentialReference, credential: Option<&crate::storage::CredentialEntry>, + manual_username: Option<&str>, ) -> Result { let credential_id = reference.credential_id; let credential = credential.ok_or_else(|| { anyhow::anyhow!(CredentialResolutionError::MissingCredential(credential_id)) })?; - let username = credential - .username - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .ok_or_else(|| { - anyhow::anyhow!(CredentialResolutionError::EmptyField { - credential_id, - credential_name: credential.name.clone(), - field: "username", - }) - })? - .to_string(); + let username = login_username(reference, credential, manual_username)?; let non_empty = |value: &Option| value.clone().filter(|value| !value.is_empty()); let passphrase = non_empty(&credential.passphrase); @@ -382,6 +374,28 @@ fn ssh_login_from_credential( }) } +/// 登录用户名:钥匙串记录优先,记录没有时用连接自己保存的用户名。 +fn login_username( + reference: &crate::storage::CredentialReference, + credential: &crate::storage::CredentialEntry, + manual_username: Option<&str>, +) -> Result { + let from_credential = credential.username.as_deref().and_then(trimmed); + let from_connection = manual_username.and_then(trimmed); + from_credential.or(from_connection).ok_or_else(|| { + anyhow::anyhow!(CredentialResolutionError::EmptyField { + credential_id: reference.credential_id, + credential_name: credential.name.clone(), + field: "username", + }) + }) +} + +fn trimmed(value: &str) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_string()) +} + fn telnet_login_script_from_credential( credential: &crate::storage::CredentialEntry, ) -> Vec { @@ -437,7 +451,15 @@ mod ssh_login_tests { reference: &CredentialReference, entry: &CredentialEntry, ) -> anyhow::Result<(String, SshAuthMethod)> { - ssh_login_from_credential(reference, Some(entry)) + resolve_with_connection_username(reference, entry, None) + } + + fn resolve_with_connection_username( + reference: &CredentialReference, + entry: &CredentialEntry, + manual_username: Option<&str>, + ) -> anyhow::Result<(String, SshAuthMethod)> { + ssh_login_from_credential(reference, Some(entry), manual_username) .map(|login| (login.username, login.auth_method)) } @@ -472,6 +494,32 @@ mod ssh_login_tests { } } + #[test] + fn username_falls_back_to_the_connection_when_the_credential_has_none() { + for username in [None, Some(""), Some(" ")] { + let (resolved, _) = resolve_with_connection_username( + &reference(false, false), + &entry(username, Some("pw"), None, None), + Some(" connection-user "), + ) + .expect("resolve"); + assert_eq!("connection-user", resolved); + } + } + + #[test] + fn credential_username_still_wins_over_the_connection_username() { + for flags in [(false, false), (true, true)] { + let (resolved, _) = resolve_with_connection_username( + &reference(flags.0, flags.1), + &entry(Some("vault-user"), Some("pw"), None, None), + Some("connection-user"), + ) + .expect("resolve"); + assert_eq!("vault-user", resolved); + } + } + #[test] fn password_only_uses_password_auth() { let (_, auth) = resolve( @@ -565,7 +613,7 @@ mod ssh_login_tests { #[test] fn a_missing_credential_keeps_the_dedicated_error_for_the_runtime_fallback() { - let error = ssh_login_from_credential(&reference(false, false), None) + let error = ssh_login_from_credential(&reference(false, false), None, None) .err() .expect("missing credential"); assert!(matches!( diff --git a/crates/core/src/storage/credential_vault/tests/resolver_tests.rs b/crates/core/src/storage/credential_vault/tests/resolver_tests.rs index e84c2ba4c..32d12ce02 100644 --- a/crates/core/src/storage/credential_vault/tests/resolver_tests.rs +++ b/crates/core/src/storage/credential_vault/tests/resolver_tests.rs @@ -7,8 +7,7 @@ use crate::storage::{ ProxyConfig, ProxyType, RedisMode, RedisParams, RedisSentinelConfig, RemoteDesktopBackendPreference, RemoteDesktopParams, RemoteDesktopProtocol, RemoteFileParams, RemoteFileProtocol, SshAccountExpect, SshAuthMethod, SshElevationExpect, SshParams, - StoredConnection, - TelnetLoginStep, TelnetParams, TerminalExpectSend, + StoredConnection, TelnetLoginStep, TelnetParams, TerminalExpectSend, }; use super::with_master_key; @@ -578,8 +577,10 @@ fn resolver_prefers_the_credential_for_ssh_username_and_secret_kinds() { }); } +/// 钥匙串记录里没有用户名时(表单在这种情况下会把用户名一栏放出来),用连接 +/// 自己保存的用户名继续,而不是直接拒绝;两边都空才算错。 #[test] -fn resolver_rejects_ssh_keychain_without_username_or_secret() { +fn resolver_falls_back_to_the_saved_username_when_the_keychain_has_none() { with_master_key(|| { let (_temp, _connection, repository) = super::test_repository(); @@ -588,8 +589,21 @@ fn resolver_rejects_ssh_keychain_without_username_or_secret() { let id = repository .insert(&mut no_username) .expect("insert credential"); - let error = repository + + let resolved = repository .resolve_ssh(ssh_params(Some(password_reference(id)))) + .expect("resolve ssh"); + assert_eq!("manual-user", resolved.username); + assert!(matches!( + resolved.auth_method, + SshAuthMethod::Password { ref password } if password == "pw" + )); + + let mut without_username = ssh_params(Some(password_reference(id))); + without_username.username.clear(); + without_username.username.push_str(" "); + let error = repository + .resolve_ssh(without_username) .expect_err("an empty username must never be sent"); assert!(matches!( error.downcast_ref::(), @@ -599,7 +613,13 @@ fn resolver_rejects_ssh_keychain_without_username_or_secret() { .. }) if credential_name == "No username" )); + }); +} +#[test] +fn resolver_rejects_ssh_keychain_without_secret() { + with_master_key(|| { + let (_temp, _connection, repository) = super::test_repository(); let mut no_secret = CredentialEntry::new("No secret"); no_secret.username = Some("user".to_string()); let id = repository diff --git a/crates/navop_app/Cargo.toml b/crates/navop_app/Cargo.toml index a591659be..428448d50 100644 --- a/crates/navop_app/Cargo.toml +++ b/crates/navop_app/Cargo.toml @@ -10,11 +10,13 @@ gpui = { workspace = true } gpui_platform = { workspace = true } gpui-component = { workspace = true, features = ["tree-sitter-bash", "tree-sitter-sql"] } gpui-component-assets = { workspace = true } +x11_component = { workspace = true } anyhow = { workspace = true } async-trait = { workspace = true } chrono = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +semver = { workspace = true } tokio = { workspace = true, features = ["io-util", "net"] } tracing = { workspace = true } tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/crates/navop_app/locales/main.yml b/crates/navop_app/locales/main.yml index 4477f32cd..568a86b70 100644 --- a/crates/navop_app/locales/main.yml +++ b/crates/navop_app/locales/main.yml @@ -204,6 +204,18 @@ Home: en: Disk zh-CN: 磁盘 zh-HK: 磁碟 + host_metrics_network_label: + en: Network + zh-CN: 网速 + zh-HK: 網速 + host_metrics_network_up: + en: "Upload %{value}" + zh-CN: "上行 %{value}" + zh-HK: "上行 %{value}" + host_metrics_network_down: + en: "Download %{value}" + zh-CN: "下行 %{value}" + zh-HK: "下行 %{value}" host_metrics_cores: en: "%{count} cores" zh-CN: "%{count} 核" @@ -2946,9 +2958,9 @@ Settings: zh-CN: 显示远端资源占用 zh-HK: 顯示遠端資源佔用 show_host_metrics_desc: - en: Collect the operating system, CPU cores, memory and disk capacity and usage of SSH servers with a background session, then show them across connection cards, lists and trees without opening a terminal. - zh-CN: 用后台 SSH 会话采集服务器的系统、CPU 核数、内存与磁盘容量及占用,无需打开终端即可在连接卡片、列表和树中看到 - zh-HK: 用後台 SSH 會話採集伺服器的系統、CPU 核心數、記憶體與磁碟容量及佔用,無需開啟終端即可在連線卡片、列表和樹狀檢視中看到 + en: Collect SSH server system, CPU, memory, disk and network usage with a background session and show them in the connection list without opening a terminal. + zh-CN: 用后台 SSH 会话采集服务器的系统、CPU、内存、磁盘与网络占用,无需打开终端即可在连接列表中看到 + zh-HK: 用後台 SSH 會話採集伺服器的系統、CPU、記憶體、磁碟與網路佔用,無需開啟終端即可在連線列表中看到 home_layout: en: Home Connection Layout zh-CN: 主页连接布局 @@ -2982,6 +2994,105 @@ Settings: zh-CN: 手动排序(拖拽调整) zh-HK: 手動排序(拖曳調整) + # X11 转发服务设置 + X11: + group_title: + en: X11 Forwarding + zh-CN: X11 转发 + zh-HK: X11 轉發 + mode: + en: X11 Server Mode + zh-CN: X11 服务模式 + zh-HK: X11 服務模式 + mode_desc: + en: Applies to new SSH sessions. Existing sessions keep their current server and must be reconnected to use the new mode. + zh-CN: 对新 SSH 会话生效;现有会话保持当前服务,必须重新连接后才会使用新模式。 + zh-HK: 對新 SSH 工作階段生效;現有工作階段保持目前服務,必須重新連線後才會使用新模式。 + mode_auto: + en: Auto (select an available server) + zh-CN: 自动(选择可用服务) + zh-HK: 自動(選擇可用服務) + mode_external: + en: External X server + zh-CN: 外部 X server + zh-HK: 外部 X server + mode_embedded: + en: Built-in yserver (Vulkan) + zh-CN: 内置 yserver(Vulkan) + zh-HK: 內置 yserver(Vulkan) + status: + en: Current Status + zh-CN: 当前状态 + zh-HK: 目前狀態 + status_desc: + en: Shows the actual X11 service selected by the component layer, not a log-derived state. + zh-CN: 显示组件层实际选择的 X11 服务,不从日志推断状态。 + zh-HK: 顯示組件層實際選擇的 X11 服務,不從日誌推斷狀態。 + status_external: + en: "X11 forwarding: local %{server}" + zh-CN: "X11 转发:本机 %{server}" + zh-HK: "X11 轉發:本機 %{server}" + status_embedded: + en: "X11 forwarding: built-in yserver %{version} (Vulkan)" + zh-CN: "X11 转发:内置 yserver %{version}(Vulkan)" + zh-HK: "X11 轉發:內置 yserver %{version}(Vulkan)" + status_disabled: + en: "X11 forwarding: disabled (%{reason})" + zh-CN: "X11 转发:已停用(%{reason})" + zh-HK: "X11 轉發:已停用(%{reason})" + installed_version: + en: "Built-in version: %{version}" + zh-CN: "内置版本:%{version}" + zh-HK: "內置版本:%{version}" + not_installed: + en: not installed + zh-CN: 未安装 + zh-HK: 未安裝 + reinstall: + en: Repair / Reinstall + zh-CN: 修复 / 重新安装 + zh-HK: 修復 / 重新安裝 + installing: + en: Installing… + zh-CN: 正在安装… + zh-HK: 正在安裝… + install_success: + en: "Built-in yserver %{version} is ready. Reconnect SSH to use it." + zh-CN: "内置 yserver %{version} 已就绪,请重新连接 SSH 后使用。" + zh-HK: "內置 yserver %{version} 已就緒,請重新連線 SSH 後使用。" + install_failed_retry: + en: "Could not install the built-in component; please retry. %{reason}" + zh-CN: "内置组件安装失败,可重试。%{reason}" + zh-HK: "內置元件安裝失敗,可重試。%{reason}" + signature_failed_support: + en: "Component signature verification failed; stop using this package and contact support. %{reason}" + zh-CN: "组件验签失败,请停止使用此安装包并联系支持。%{reason}" + zh-HK: "元件驗簽失敗,請停止使用此安裝套件並聯絡支援。%{reason}" + vulkan_unavailable_use_external: + en: "Vulkan support is insufficient; switch to an external X server. %{reason}" + zh-CN: "Vulkan 支持不足,请改用外部 X server。%{reason}" + zh-HK: "Vulkan 支援不足,請改用外部 X server。%{reason}" + handshake_failed_fallback: + en: "The built-in server handshake failed; use Auto to fall back to an external server or select External. %{reason}" + zh-CN: "内置服务握手失败;请用 Auto 降级到外部服务,或切换到 External。%{reason}" + zh-HK: "內置服務握手失敗;請用 Auto 降級到外部服務,或切換至 External。%{reason}" + remote_display_restarted: + en: "The display service was restarted; close old X11 windows and reconnect. Reason: %{reason}" + zh-CN: "显示服务已重启;请关闭旧 X11 窗口并重新连接。原因:%{reason}" + zh-HK: "顯示服務已重新啟動;請關閉舊 X11 視窗並重新連線。原因:%{reason}" + remote_forwarding_disabled_checklist: + en: Check remote sshd_config for X11Forwarding yes, install xauth, then reconnect. + zh-CN: 请检查远端 sshd_config 的 X11Forwarding yes、安装 xauth,然后重新连接。 + zh-HK: 請檢查遠端 sshd_config 的 X11Forwarding yes、安裝 xauth,然後重新連線。 + untrusted_ssh_x_security: + en: "Untrusted ssh -X is limited by the X11 SECURITY timeout; use trusted ssh -Y when required." + zh-CN: "untrusted ssh -X 会受 X11 SECURITY 超时限制;需要可信转发时请使用 ssh -Y。" + zh-HK: "untrusted ssh -X 會受 X11 SECURITY 逾時限制;需要可信轉發時請使用 ssh -Y。" + macos_xquartz_guidance: + en: "On macOS, install and start XQuartz for External mode, then log out and back in if DISPLAY is unavailable." + zh-CN: "macOS 使用 External 时需安装并启动 XQuartz;若 DISPLAY 不可用,请注销后重新登录。" + zh-HK: "macOS 使用 External 時需安裝並啟動 XQuartz;若 DISPLAY 不可用,請登出後重新登入。" + # 文件传输设置 FileTransfer: group_title: @@ -6169,6 +6280,10 @@ CredentialVault: en: Private Key Passphrase zh-CN: 私钥密码 zh-HK: 私鑰密碼 + capability_missing_username: + en: No Username + zh-CN: 缺用户名 + zh-HK: 缺使用者名稱 not_found: en: The credential no longer exists. It may have been deleted. zh-CN: 凭据不存在,可能已被删除。 @@ -6255,6 +6370,10 @@ CredentialForm: en: Optional username zh-CN: 可选用户名 zh-HK: 選填使用者名稱 + username_hint: + en: SSH key login needs a username. Leave it empty only when you connect with a password. + zh-CN: 使用 SSH 密钥登录时需要用户名;只用密码连接时可以留空。 + zh-HK: 使用 SSH 金鑰登入時需要使用者名稱;僅用密碼連線時可留空。 password: en: Password zh-CN: 密码 @@ -6276,17 +6395,41 @@ CredentialForm: zh-CN: 生成 SSH 密钥 zh-HK: 產生 SSH 金鑰 generate_key_description: - en: Creates an Ed25519 key pair. The private key fills the form below and the public key goes to your clipboard. - zh-CN: 生成一对 Ed25519 密钥:私钥自动填入下方表单,公钥复制到剪贴板。 - zh-HK: 產生一對 Ed25519 金鑰:私鑰會填入下方表單,公鑰複製到剪貼簿。 + en: Choose an algorithm, then generate a key pair. The private key fills the form below and the public key goes to your clipboard. + zh-CN: 先选择算法,再生成一对密钥:私钥自动填入下方表单,公钥复制到剪贴板。 + zh-HK: 先選擇演算法,再產生一對金鑰:私鑰會填入下方表單,公鑰複製到剪貼簿。 + generate_key_algorithm_ed25519: + en: Ed25519 (recommended) + zh-CN: Ed25519(推荐) + zh-HK: Ed25519(推薦) + generate_key_algorithm_ecdsa_p256: + en: ECDSA P-256 + zh-CN: ECDSA P-256 + zh-HK: ECDSA P-256 + generate_key_algorithm_ecdsa_p384: + en: ECDSA P-384 + zh-CN: ECDSA P-384 + zh-HK: ECDSA P-384 + generate_key_algorithm_rsa3072: + en: RSA 3072 (slower) + zh-CN: RSA 3072(生成较慢) + zh-HK: RSA 3072(產生較慢) generate_key_action: en: Generate zh-CN: 生成 zh-HK: 產生 + generate_key_running: + en: Generating… + zh-CN: 生成中… + zh-HK: 產生中… generate_key_success: en: Key generated and public key copied. Fingerprint %{fingerprint} zh-CN: 已生成密钥并复制公钥,指纹:%{fingerprint} zh-HK: 已產生金鑰並複製公鑰,指紋:%{fingerprint} + generate_key_failed: + en: "Failed to generate the key: %{error}" + zh-CN: 生成密钥失败:%{error} + zh-HK: 產生金鑰失敗:%{error} private_key_path: en: Private Key Path zh-CN: 私钥路径 @@ -6295,6 +6438,26 @@ CredentialForm: en: e.g. ~/.ssh/id_ed25519 (local only) zh-CN: 例如:~/.ssh/id_ed25519(仅本机使用) zh-HK: 例如:~/.ssh/id_ed25519(僅供本機使用) + private_key_path_browse: + en: Choose a local private key file + zh-CN: 选择本地私钥文件 + zh-HK: 選擇本機私鑰檔案 + private_key_path_select: + en: Select a private key file + zh-CN: 选择私钥文件 + zh-HK: 選擇私鑰檔案 + ssh_key_username: + en: Username + zh-CN: 用户名 + zh-HK: 使用者名稱 + private_key_path_hint: + en: A local path such as ~/.ssh/id_ed25519 works, and you can drop the key file on the field. If key content is also filled in, the content wins. + zh-CN: 支持 ~/.ssh/id_ed25519 这类本机路径,也可以把私钥文件直接拖到这一行;若同时填写私钥内容,连接时优先使用内容。 + zh-HK: 支援 ~/.ssh/id_ed25519 這類本機路徑,也可以把私鑰檔案直接拖到這一行;若同時填寫私鑰內容,連線時優先使用內容。 + private_key_username_missing: + en: Key login still needs a username. Leave it empty only if you will type the username on the connection. + zh-CN: 密钥登录还需要一个用户名;留空时,需要在连接里单独填写用户名。 + zh-HK: 金鑰登入還需要一個使用者名稱;留空時,需要在連線裡單獨填寫使用者名稱。 private_key_content: en: Private Key Content zh-CN: 私钥内容 diff --git a/crates/navop_app/src/credential_vault/form.rs b/crates/navop_app/src/credential_vault/form.rs index 4276d58b8..3e6e7bca1 100644 --- a/crates/navop_app/src/credential_vault/form.rs +++ b/crates/navop_app/src/credential_vault/form.rs @@ -1,12 +1,16 @@ use gpui::{ - App, AppContext, ClipboardItem, Context, Entity, FocusHandle, Focusable, SharedString, Window, + App, AppContext, ClipboardItem, Context, Entity, ExternalPaths, FocusHandle, Focusable, + PathPromptOptions, SharedString, Window, }; use gpui_component::{ - WindowExt, - input::{InputState, TextareaState}, + IndexPath, WindowExt, + input::{InputEvent, InputState, TextareaState}, notification::Notification, + select::SelectState, +}; +use one_core::storage::{ + CredentialEntry, GeneratedSshKey, SshAccountExpect, SshKeyAlgorithm, TerminalExpectSend, }; -use one_core::storage::{CredentialEntry, SshAccountExpect, TerminalExpectSend}; use regex::Regex; use rust_i18n::t; @@ -39,32 +43,151 @@ pub(crate) struct CredentialForm { pub(super) password_send_input: Entity, pub(super) sync_enabled: bool, pub(super) forward_to_agent: bool, + /// 「生成密钥」的算法下拉框,选项顺序与 [`SshKeyAlgorithm::ALL`] 一致。 + pub(super) algorithm_select: Entity>>, + /// 后台正在生成密钥:期间禁用按钮,避免重复生成把表单覆盖掉。 + pub(super) generating_key: bool, + /// 文件选择器挑中的私钥路径,等下一次渲染再写进输入框(写输入态需要 Window)。 + pending_private_key_path: Option, } impl CredentialForm { - /// 生成一对 Ed25519 密钥:私钥写进表单,公钥复制到剪贴板并提示指纹。 + /// 按下拉框选中的算法生成密钥:私钥写进表单,公钥复制到剪贴板并提示指纹。 /// - /// 使用凭据名称作为密钥注释,方便在 `authorized_keys` 里辨认来源。 - pub(super) fn generate_ed25519_key(&mut self, window: &mut Window, cx: &mut Context) { + /// 使用凭据名称作为密钥注释,方便在 `authorized_keys` 里辨认来源。RSA 生成 + /// 在慢机器上要几秒钟,所以统一放后台线程,避免卡住对话框。 + pub(super) fn generate_key(&mut self, window: &mut Window, cx: &mut Context) { + if self.generating_key { + return; + } let comment = self.name_input.read(cx).value().trim().to_string(); - let key = one_core::storage::generate_ed25519_key(&comment); + let algorithm = self.selected_key_algorithm(cx); + self.generating_key = true; + + let task = + cx.background_spawn( + async move { one_core::storage::generate_ssh_key(algorithm, &comment) }, + ); + cx.spawn_in(window, async move |this, cx| { + let result = task.await; + let _ = this.update_in(cx, |form, window, cx| { + form.apply_generated_key(result, window, cx); + }); + }) + .detach(); + cx.notify(); + } + + /// 生成结束:把密钥写进表单并恢复按钮;失败时只弹提示,表单保持原样。 + fn apply_generated_key( + &mut self, + result: Result, + window: &mut Window, + cx: &mut Context, + ) { + self.generating_key = false; + match result { + Ok(key) => { + self.private_key_content_input.update(cx, |state, cx| { + state.set_value(key.private_key_openssh.clone(), window, cx); + }); + cx.write_to_clipboard(ClipboardItem::new_string(key.public_key_openssh)); + window.push_notification( + Notification::success( + t!( + "CredentialForm.generate_key_success", + fingerprint = key.fingerprint + ) + .to_string(), + ) + .autohide(true), + cx, + ); + } + Err(error) => { + window.push_notification( + Notification::error( + t!("CredentialForm.generate_key_failed", error = error).to_string(), + ) + .autohide(true), + cx, + ); + } + } + cx.notify(); + } - self.private_key_content_input.update(cx, |state, cx| { - state.set_value(key.private_key_openssh.clone(), window, cx); + /// 下拉框当前选中项对应的算法;越界时回退到默认的 Ed25519。 + fn selected_key_algorithm(&self, cx: &App) -> SshKeyAlgorithm { + let row = self + .algorithm_select + .read(cx) + .selected_index(cx) + .map_or(0, |index| index.row); + SshKeyAlgorithm::ALL + .get(row) + .copied() + .unwrap_or(SshKeyAlgorithm::Ed25519) + } + + /// 打开系统文件选择器挑选本地私钥文件,选中后写回「私钥路径」。 + pub(super) fn browse_private_key_path(&mut self, cx: &mut Context) { + let future = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: Some( + t!("CredentialForm.private_key_path_select") + .to_string() + .into(), + ), + }); + cx.spawn(async move |this, cx| { + let Ok(Ok(Some(paths))) = future.await else { + return; + }; + let Some(path) = paths.first() else { + return; + }; + let path = path.to_string_lossy().to_string(); + let _ = this.update(cx, |form, cx| { + form.pending_private_key_path = Some(path); + cx.notify(); + }); + }) + .detach(); + } + + /// 渲染前应用浏览结果:写输入态必须拿到 `Window`,所以推迟到这里。 + pub(super) fn apply_pending_private_key_path( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { + let Some(path) = self.pending_private_key_path.take() else { + return; + }; + self.private_key_path_input.update(cx, |state, cx| { + state.set_value(path, window, cx); + }); + } + + /// 拖入私钥文件时,把路径写进「私钥路径」输入框。 + /// + /// 与浏览按钮共用同一份输入态;拖放只是省去一次文件选择对话框。 + pub(super) fn accept_dropped_private_key_path( + &mut self, + paths: &ExternalPaths, + window: &mut Window, + cx: &mut Context, + ) { + let Some(path) = paths.paths().first() else { + return; + }; + let path = path.to_string_lossy().to_string(); + self.private_key_path_input.update(cx, |state, cx| { + state.set_value(path, window, cx); }); - cx.write_to_clipboard(ClipboardItem::new_string(key.public_key_openssh)); - - window.push_notification( - Notification::success( - t!( - "CredentialForm.generate_key_success", - fingerprint = key.fingerprint - ) - .to_string(), - ) - .autohide(true), - cx, - ); cx.notify(); } @@ -89,6 +212,13 @@ impl CredentialForm { window, cx, ); + // 用户名同时出现在「基础信息」与「SSH 密钥」两页,这里订阅变化以便密钥页的提示实时刷新。 + cx.subscribe(&username_input, |_, _, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + cx.notify(); + } + }) + .detach(); let password_input = text_input( existing .as_ref() @@ -168,6 +298,12 @@ impl CredentialForm { let forward_to_agent = existing .as_ref() .is_some_and(|entry| entry.forward_to_agent); + let algorithm_items: Vec = SshKeyAlgorithm::ALL + .iter() + .map(|algorithm| generate_key_algorithm_label(*algorithm)) + .collect(); + let algorithm_select = + cx.new(|cx| SelectState::new(algorithm_items, Some(IndexPath::new(0)), window, cx)); Self { focus_handle: cx.focus_handle(), @@ -185,6 +321,9 @@ impl CredentialForm { password_send_input, sync_enabled, forward_to_agent, + algorithm_select, + generating_key: false, + pending_private_key_path: None, } } @@ -253,6 +392,20 @@ fn input_value(input: &Entity, cx: &App) -> String { input.read(cx).value().to_string() } +/// 「生成密钥」下拉框里展示的算法名称。 +fn generate_key_algorithm_label(algorithm: SshKeyAlgorithm) -> String { + match algorithm { + SshKeyAlgorithm::Ed25519 => t!("CredentialForm.generate_key_algorithm_ed25519").to_string(), + SshKeyAlgorithm::EcdsaP256 => { + t!("CredentialForm.generate_key_algorithm_ecdsa_p256").to_string() + } + SshKeyAlgorithm::EcdsaP384 => { + t!("CredentialForm.generate_key_algorithm_ecdsa_p384").to_string() + } + SshKeyAlgorithm::Rsa3072 => t!("CredentialForm.generate_key_algorithm_rsa3072").to_string(), + } +} + pub(super) fn build_entry( existing: Option, values: CredentialFormValues, @@ -364,6 +517,22 @@ mod tests { ); } + #[test] + fn key_algorithm_labels_cover_every_generation_option() { + let labels: Vec = SshKeyAlgorithm::ALL + .iter() + .map(|algorithm| generate_key_algorithm_label(*algorithm)) + .collect(); + + assert_eq!(labels.len(), SshKeyAlgorithm::ALL.len()); + assert!(labels.iter().all(|label| !label.trim().is_empty())); + + let mut unique = labels.clone(); + unique.sort(); + unique.dedup(); + assert_eq!(unique.len(), labels.len()); + } + #[test] fn normalizes_optional_values() { let entry = build_entry(None, values()).unwrap(); diff --git a/crates/navop_app/src/credential_vault/form_render.rs b/crates/navop_app/src/credential_vault/form_render.rs index bc0e17e1f..d741419c8 100644 --- a/crates/navop_app/src/credential_vault/form_render.rs +++ b/crates/navop_app/src/credential_vault/form_render.rs @@ -1,20 +1,26 @@ -use gpui::{InteractiveElement, IntoElement, ParentElement, Render, Styled, Window, div, px}; +use gpui::prelude::FluentBuilder; +use gpui::{ + ExternalPaths, InteractiveElement, IntoElement, ParentElement, Render, Styled, Window, div, px, +}; use gpui_component::{ - ActiveTheme, Sizable, Size, - button::Button, + ActiveTheme, Disableable, Sizable, Size, + button::{Button, ButtonVariants as _}, h_flex, input::{Input, Textarea}, scroll::ScrollableElement, + select::Select, switch::Switch, tab::{Tab, TabBar}, v_flex, }; +use one_assets::IconName; use rust_i18n::t; use super::form::CredentialForm; impl Render for CredentialForm { - fn render(&mut self, _window: &mut Window, cx: &mut gpui::Context) -> impl IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut gpui::Context) -> impl IntoElement { + self.apply_pending_private_key_path(window, cx); let active_tab = self.active_tab; v_flex() @@ -77,6 +83,10 @@ impl CredentialForm { t!("CredentialForm.username").to_string(), Input::new(&self.username_input).w_full(), )) + .child(form_hint( + t!("CredentialForm.username_hint").to_string(), + cx, + )) .child(form_field( t!("CredentialForm.password").to_string(), Input::new(&self.password_input).w_full().mask_toggle(), @@ -85,6 +95,7 @@ impl CredentialForm { } fn render_ssh_key_tab(&self, cx: &mut gpui::Context) -> impl IntoElement { + let username_missing = self.username_input.read(cx).value().trim().is_empty(); v_flex() .w_full() .gap_3() @@ -94,9 +105,43 @@ impl CredentialForm { cx, )) .child(self.render_generate_ssh_key(cx)) + .child( + v_flex() + .gap_1() + .child(form_field( + t!("CredentialForm.ssh_key_username").to_string(), + Input::new(&self.username_input).w_full(), + )) + .when(username_missing, |this| { + this.child(form_hint( + t!("CredentialForm.private_key_username_missing").to_string(), + cx, + )) + }), + ) .child(form_field( t!("CredentialForm.private_key_path").to_string(), - Input::new(&self.private_key_path_input).w_full(), + h_flex() + .id("credential-private-key-drop") + .w_full() + .gap_2() + .on_drop(cx.listener(|form, paths: &ExternalPaths, window, cx| { + form.accept_dropped_private_key_path(paths, window, cx); + })) + .child(Input::new(&self.private_key_path_input).flex_1()) + .child( + Button::new("credential-browse-private-key") + .icon(IconName::FolderOpen) + .ghost() + .tooltip(t!("CredentialForm.private_key_path_browse").to_string()) + .on_click( + cx.listener(|form, _, _, cx| form.browse_private_key_path(cx)), + ), + ), + )) + .child(form_hint( + t!("CredentialForm.private_key_path_hint").to_string(), + cx, )) .child(form_field( t!("CredentialForm.private_key_content").to_string(), @@ -113,7 +158,7 @@ impl CredentialForm { .child(self.render_forward_to_agent_setting(cx)) } - /// 「生成密钥」入口:一键生成 Ed25519 密钥对,私钥填进表单、公钥复制到剪贴板。 + /// 「生成密钥」入口:按所选算法生成密钥对,私钥填进表单、公钥复制到剪贴板。 fn render_generate_ssh_key(&self, cx: &mut gpui::Context) -> impl IntoElement { h_flex() .w_full() @@ -141,13 +186,25 @@ impl CredentialForm { ), ) .child( - Button::new("credential-generate-key") - .small() - .outline() - .label(t!("CredentialForm.generate_key_action").to_string()) - .on_click(cx.listener(|form, _, window, cx| { - form.generate_ed25519_key(window, cx); - })), + h_flex() + .flex_shrink_0() + .items_center() + .gap_2() + .child(Select::new(&self.algorithm_select).small()) + .child( + Button::new("credential-generate-key") + .small() + .outline() + .disabled(self.generating_key) + .label(if self.generating_key { + t!("CredentialForm.generate_key_running").to_string() + } else { + t!("CredentialForm.generate_key_action").to_string() + }) + .on_click(cx.listener(|form, _, window, cx| { + form.generate_key(window, cx); + })), + ), ) } @@ -273,6 +330,14 @@ fn info_panel(title: String, description: String, cx: &gpui::App) -> impl IntoEl ) } +fn form_hint(text: String, cx: &gpui::App) -> impl IntoElement { + div() + .w_full() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(text) +} + fn form_field(label: String, input: impl IntoElement) -> impl IntoElement { v_flex() .gap_1() @@ -385,15 +450,19 @@ mod tests { assert!(ssh_key.contains("self.render_generate_ssh_key(cx)")); assert!(source.contains("credential-generate-key")); assert!(source.contains("CredentialForm.generate_key_action")); - assert!(source.contains("form.generate_ed25519_key(window, cx)")); - assert!(form.contains("pub(super) fn generate_ed25519_key")); - assert!(form.contains("one_core::storage::generate_ed25519_key(&comment)")); + assert!(source.contains("Select::new(&self.algorithm_select)")); + assert!(source.contains("form.generate_key(window, cx)")); + assert!(form.contains("pub(super) fn generate_key")); + assert!(form.contains("one_core::storage::generate_ssh_key(algorithm, &comment)")); + assert!(form.contains("cx.background_spawn(")); + assert!(form.contains("SshKeyAlgorithm::ALL")); assert!( form.contains( "cx.write_to_clipboard(ClipboardItem::new_string(key.public_key_openssh))" ) ); assert!(form.contains("CredentialForm.generate_key_success")); + assert!(form.contains("CredentialForm.generate_key_failed")); } #[test] @@ -409,4 +478,27 @@ mod tests { assert!(production.contains("self.render_sync_settings(cx)")); assert!(!production.contains("CredentialForm.tab_sync")); } + + #[test] + fn credential_form_explains_username_and_key_path_requirements() { + let source = include_str!("form_render.rs"); + let basic = source + .split("fn render_basic_tab") + .nth(1) + .and_then(|source| source.split("fn render_ssh_key_tab").next()) + .expect("basic tab"); + let ssh_key = source + .split("fn render_ssh_key_tab") + .nth(1) + .and_then(|source| source.split("fn render_generate_ssh_key").next()) + .expect("SSH key tab"); + + assert!(source.contains("fn form_hint(")); + assert!(basic.contains("CredentialForm.username_hint")); + assert!(ssh_key.contains("CredentialForm.private_key_path_hint")); + assert!(ssh_key.contains("CredentialForm.private_key_username_missing")); + assert!(ssh_key.contains("CredentialForm.ssh_key_username")); + assert!(ssh_key.contains("Input::new(&self.username_input)")); + assert!(ssh_key.contains("username_missing")); + } } diff --git a/crates/navop_app/src/credential_vault/render.rs b/crates/navop_app/src/credential_vault/render.rs index 6c016e9de..2c993b4e6 100644 --- a/crates/navop_app/src/credential_vault/render.rs +++ b/crates/navop_app/src/credential_vault/render.rs @@ -339,7 +339,7 @@ fn credential_row( .username .clone() .unwrap_or_else(|| t!("CredentialVault.username_not_set").to_string()); - let chips = capability_chips(&summary); + let chips = capability_chips(&summary, cx); v_flex() .w_full() .gap_3() @@ -410,38 +410,57 @@ fn credential_row( }) } -fn capability_chips(summary: &CredentialSummary) -> Vec { - [ - ( - summary.has_password, - t!("CredentialVault.capability_password").to_string(), - ), - ( - summary.has_private_key_path, - t!("CredentialVault.capability_private_key_path").to_string(), - ), - ( - summary.has_private_key_content, - t!("CredentialVault.capability_private_key_content").to_string(), - ), - ( - summary.has_passphrase, - t!("CredentialVault.capability_passphrase").to_string(), - ), - ] - .into_iter() - .filter(|(present, _)| *present) - .map(|(_, label)| { - div() - .rounded_full() - .bg(gpui::hsla(0.0, 0.0, 0.5, 0.08)) - .px_2() - .py_0p5() - .text_xs() - .child(label) - .into_any_element() - }) - .collect() +fn capability_chips(summary: &CredentialSummary, cx: &gpui::App) -> Vec { + let mut chips: Vec = Vec::new(); + // 有私钥却没有用户名是最常见的一次配置错误:连接时还得靠连接里的用户名兜底。 + if summary.username.is_none() + && (summary.has_private_key_path || summary.has_private_key_content) + { + chips.push( + div() + .rounded_full() + .bg(cx.theme().warning.opacity(0.15)) + .px_2() + .py_0p5() + .text_xs() + .text_color(cx.theme().warning) + .child(t!("CredentialVault.capability_missing_username").to_string()) + .into_any_element(), + ); + } + chips.extend( + [ + ( + summary.has_password, + t!("CredentialVault.capability_password").to_string(), + ), + ( + summary.has_private_key_path, + t!("CredentialVault.capability_private_key_path").to_string(), + ), + ( + summary.has_private_key_content, + t!("CredentialVault.capability_private_key_content").to_string(), + ), + ( + summary.has_passphrase, + t!("CredentialVault.capability_passphrase").to_string(), + ), + ] + .into_iter() + .filter(|(present, _)| *present) + .map(|(_, label)| { + div() + .rounded_full() + .bg(gpui::hsla(0.0, 0.0, 0.5, 0.08)) + .px_2() + .py_0p5() + .text_xs() + .child(label) + .into_any_element() + }), + ); + chips } fn chip(label: impl Into, cx: &gpui::App) -> impl IntoElement { @@ -472,6 +491,20 @@ mod tests { assert!(source.contains(".overflow_y_scrollbar()")); } + #[test] + fn credential_rows_warn_about_key_credentials_without_username() { + let source = include_str!("render.rs"); + let chips = source + .split("fn capability_chips(") + .nth(1) + .and_then(|source| source.split("#[cfg(test)]").next()) + .expect("capability chips source"); + + assert!(chips.contains("CredentialVault.capability_missing_username")); + assert!(chips.contains("summary.username.is_none()")); + assert!(chips.contains("summary.has_private_key_path || summary.has_private_key_content")); + } + #[test] fn credential_list_scroll_boundary_uses_outer_overflow_hidden_and_inner_scrollable() { let source = include_str!("render.rs"); diff --git a/crates/navop_app/src/home_tab.rs b/crates/navop_app/src/home_tab.rs index 319420d53..1693a6986 100644 --- a/crates/navop_app/src/home_tab.rs +++ b/crates/navop_app/src/home_tab.rs @@ -342,26 +342,7 @@ impl HomePage { None } - /// 没有 shell 能力时卡片底部不显示资源状态带。 - pub(crate) fn render_host_metrics_card( - &self, - _connection: &StoredConnection, - _id_prefix: &str, - _cx: &App, - ) -> Option { - None - } - - /// 没有 shell 能力时树行也不显示资源进度条。 - pub(crate) fn render_host_metrics_compact( - &self, - _connection: &StoredConnection, - _id_prefix: &str, - _cx: &App, - ) -> Option { - None - } - + #[cfg(test)] pub(crate) fn shows_host_metrics_strip( &self, _connection: &StoredConnection, diff --git a/crates/navop_app/src/home_tab/connection_card.rs b/crates/navop_app/src/home_tab/connection_card.rs index e0e45e5f1..ac78d217a 100644 --- a/crates/navop_app/src/home_tab/connection_card.rs +++ b/crates/navop_app/src/home_tab/connection_card.rs @@ -1,6 +1,9 @@ use super::*; use std::time::Instant; +/// 资源信息只在列表展示,卡片统一使用紧凑基础高度。 +const CONNECTION_CARD_HEIGHT_REMS: f32 = 4.5; + impl HomePage { pub(super) fn render_connection_card( &self, @@ -33,14 +36,6 @@ impl HomePage { } else { connection_team_badge(conn.team_id.as_deref(), self.team_permissions.teams()) }; - let shows_host_metrics = self.shows_host_metrics_strip(&conn, cx); - let card_height = if shows_host_metrics { - 5.5 - } else if recent { - 3.625 - } else { - 4.5 - }; // 同一连接会同时出现在最近区与普通分组,元素 ID 按展示区命名空间区分(redesign §6.2)。 let card_id = if recent { "conn-card-recent" @@ -55,8 +50,7 @@ impl HomePage { .justify_center() .id(card_id.clone()) .w_full() - // 需要资源状态带时预留第二行;其他连接保持原紧凑高度。 - .h(gpui::rems(card_height)) + .h(gpui::rems(CONNECTION_CARD_HEIGHT_REMS)) .rounded(px(12.0)) .bg(cx.theme().background) .px_3() diff --git a/crates/navop_app/src/home_tab/connection_card_content.rs b/crates/navop_app/src/home_tab/connection_card_content.rs index a73e12a3d..bf6536a9e 100644 --- a/crates/navop_app/src/home_tab/connection_card_content.rs +++ b/crates/navop_app/src/home_tab/connection_card_content.rs @@ -11,10 +11,8 @@ impl HomePage { let display_name = connection_display_name(conn); let name_tooltip: SharedString = display_name.clone().into(); let connection_info = card_connection_info(conn); - let host_metrics = - self.render_host_metrics_card(conn, &format!("{card_id}-host-metrics"), cx); - let header = h_flex() + h_flex() .items_center() .gap_2p5() .w_full() @@ -81,13 +79,6 @@ impl HomePage { ) }), ) - .into_any_element(); - - v_flex() - .w_full() - .gap_2() - .child(header) - .when_some(host_metrics, |this, metrics| this.child(metrics)) .into_any_element() } } diff --git a/crates/navop_app/src/home_tab/content.rs b/crates/navop_app/src/home_tab/content.rs index e25ef2876..3f64b643d 100644 --- a/crates/navop_app/src/home_tab/content.rs +++ b/crates/navop_app/src/home_tab/content.rs @@ -12,6 +12,10 @@ impl HomePage { ) { self.connection_layout = layout.into(); self.sync_sidebar_home_embedded(cx); + #[cfg(feature = "shell")] + if self.connection_layout == ConnectionLayout::List { + self.refresh_host_metrics(cx); + } cx.notify(); } diff --git a/crates/navop_app/src/home_tab/host_metrics.rs b/crates/navop_app/src/home_tab/host_metrics.rs index 7a9fd3fc1..a646ecccb 100644 --- a/crates/navop_app/src/home_tab/host_metrics.rs +++ b/crates/navop_app/src/home_tab/host_metrics.rs @@ -1,6 +1,6 @@ //! 首页连接卡片的远端资源占用(#279)。 //! -//! 用一次性的后台 SSH 会话采集 CPU、内存与磁盘占用,不打开终端页签; +//! 用一次性的后台 SSH 会话采集 CPU、内存、磁盘与网络占用,不打开终端页签; //! 结果按连接缓存,过期后再采集。任何失败都只记 debug 日志,不影响首页交互。 use std::collections::{HashMap, HashSet}; @@ -21,7 +21,7 @@ use one_core::storage::{ }; use rust_i18n::t; -use super::HomePage; +use super::{ConnectionLayout, HomePage}; /// 同一连接资源快照的缓存时间。 const HOST_METRICS_TTL: Duration = Duration::from_secs(300); @@ -29,6 +29,8 @@ const HOST_METRICS_TTL: Duration = Duration::from_secs(300); const HOST_METRICS_REFRESH_INTERVAL: Duration = Duration::from_secs(60); /// 同时进行的后台采集上限:首页一次可能渲染几十个连接,不能同时拉起几十个 SSH 会话。 const HOST_METRICS_MAX_IN_FLIGHT: usize = 2; +/// 资源轨道宽度:容纳英文标签、容量、百分比,并让四项在常见窗口宽度内保持同一行。 +const HOST_METRIC_TRACK_WIDTH_REMS: f32 = 9.0; pub(crate) struct HostMetricsEntry { usage: terminal_view::HostResourceUsage, @@ -70,7 +72,10 @@ impl HomePage { /// 为首页的 SSH 连接排队后台采集(设置关闭或主密钥未解锁时直接跳过)。 pub(super) fn refresh_host_metrics(&mut self, cx: &mut Context) { - if !host_metrics_enabled(cx) || self.saved_connections_locked() { + if self.connection_layout != ConnectionLayout::List + || !host_metrics_enabled(cx) + || self.saved_connections_locked() + { return; } @@ -179,7 +184,7 @@ impl HomePage { }) } - /// 卡片、列表共用的资源标签(没有缓存快照或设置关闭时返回 None)。 + /// 列表使用的资源标签(没有缓存快照或设置关闭时返回 None)。 pub(crate) fn render_host_metrics_detail( &self, connection: &StoredConnection, @@ -203,45 +208,10 @@ impl HomePage { } } - /// 卡片宽度有限,只显示一行三项占用;系统和容量信息通过 tooltip 展开。 - pub(crate) fn render_host_metrics_card( - &self, - connection: &StoredConnection, - id_prefix: &str, - cx: &App, - ) -> Option { - match self.host_metrics_state(connection, cx)? { - HostMetricsState::Ready(usage) => Some(render_host_metrics_card(&usage, id_prefix, cx)), - HostMetricsState::Pending => Some(render_host_metrics_card_status( - id_prefix, - t!("Home.host_metrics_collecting").to_string(), - cx, - )), - HostMetricsState::Unavailable => Some(render_host_metrics_card_status( - id_prefix, - t!("Home.host_metrics_unavailable").to_string(), - cx, - )), - } - } - - /// 树行空间有限,用三条迷你进度条表示 CPU / 内存 / 磁盘,完整数值放 tooltip。 - pub(crate) fn render_host_metrics_compact( - &self, - connection: &StoredConnection, - id_prefix: &str, - cx: &App, - ) -> Option { - match self.host_metrics_state(connection, cx)? { - HostMetricsState::Ready(usage) => { - Some(render_host_metrics_compact(&usage, id_prefix, cx)) - } - HostMetricsState::Pending | HostMetricsState::Unavailable => None, - } - } - pub(crate) fn shows_host_metrics_strip(&self, connection: &StoredConnection, cx: &App) -> bool { - host_metrics_enabled(cx) && connection.connection_type == ConnectionType::SshSftp + self.connection_layout == ConnectionLayout::List + && host_metrics_enabled(cx) + && connection.connection_type == ConnectionType::SshSftp } fn host_metrics_state( @@ -270,35 +240,6 @@ fn host_metrics_enabled(cx: &App) -> bool { AppSettings::global(cx).home_show_host_metrics } -fn format_host_metrics_summary(usage: &terminal_view::HostResourceUsage) -> Option { - let mut parts = Vec::new(); - if let Some(cpu) = usage.cpu_percent { - let mut text = t!("Home.host_metrics_cpu", percent = format!("{cpu:.0}")).to_string(); - if let Some(cores) = usage.cpu_cores { - text.push_str(" · "); - text.push_str(&t!("Home.host_metrics_cores", count = cores.to_string()).to_string()); - } - parts.push(text); - } - if let Some(memory) = usage.memory_percent { - let mut text = t!("Home.host_metrics_memory", percent = format!("{memory:.0}")).to_string(); - if let Some(total) = usage.memory_total_kib { - text.push_str(" · "); - text.push_str(&format_kib_compact(total)); - } - parts.push(text); - } - if let Some(disk) = usage.disk_percent { - let mut text = t!("Home.host_metrics_disk", percent = format!("{disk:.0}")).to_string(); - if let Some(total) = usage.disk_total_kib { - text.push_str(" · "); - text.push_str(&format_kib_compact(total)); - } - parts.push(text); - } - (!parts.is_empty()).then(|| parts.join(" · ")) -} - fn render_host_metrics_detail( usage: &terminal_view::HostResourceUsage, id_prefix: &str, @@ -308,16 +249,26 @@ fn render_host_metrics_detail( h_flex() .min_w_0() .flex_wrap() - .gap_1p5() + .items_center() + .gap_3() .when_some(usage.os_name.as_ref(), |row, os_name| { - row.child(render_host_info_chip( - SharedString::from(format!("{id_prefix}-os")), - os_name.clone(), - cx, - )) + let tooltip: SharedString = os_name.clone().into(); + row.child( + div() + .id(SharedString::from(format!("{id_prefix}-os"))) + .flex_shrink_0() + .max_w(gpui::rems(10.0)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_xs() + .text_color(cx.theme().muted_foreground) + .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .child(os_name.clone()), + ) }) .children(metrics.into_iter().map(|(kind, value)| { - render_host_metric_chip( + render_host_metric_track( SharedString::from(format!("{id_prefix}-{}", kind.id_suffix())), kind.label(), value, @@ -325,6 +276,14 @@ fn render_host_metrics_detail( cx, ) })) + .when_some(host_network_rates(usage), |row, (rx, tx)| { + row.child(render_host_network_track( + SharedString::from(format!("{id_prefix}-network")), + rx, + tx, + cx, + )) + }) .into_any_element() } @@ -349,159 +308,143 @@ fn render_host_metrics_status(id_prefix: &str, text: String, cx: &App) -> AnyEle .into_any_element() } -fn render_host_metrics_card_status(id_prefix: &str, text: String, cx: &App) -> AnyElement { - h_flex() - .id(SharedString::from(format!("{id_prefix}-card-status"))) - .w_full() - .items_center() - .gap_2() - .px_2() - .py_1() - .rounded(cx.theme().radius) - .border_1() - .border_color(cx.theme().border) - .bg(cx.theme().muted) - .child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(text), - ) - .into_any_element() -} - -fn render_host_metrics_card( - usage: &terminal_view::HostResourceUsage, - id_prefix: &str, +fn render_host_metric_track( + id: SharedString, + label: String, + value: f64, + detail: Option, cx: &App, ) -> AnyElement { - let metrics = host_metric_values(usage); - let tooltip: SharedString = format_host_metrics_summary(usage) - .unwrap_or_default() - .into(); - h_flex() - .id(SharedString::from(format!("{id_prefix}-card"))) - .w_full() - .min_w_0() - .items_center() - .gap_2() - .px_2() - .py_1() - .rounded(cx.theme().radius) - .border_1() - .border_color(cx.theme().border) - .bg(cx.theme().muted) - .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) - .children(metrics.into_iter().map(|(kind, value)| { + let tone = metric_color(value, cx); + let percent = format!("{value:.1}%"); + let caption = match detail.as_ref() { + Some(detail) => format!("{label} · {detail}"), + None => label.clone(), + }; + let tooltip_text: SharedString = match detail.as_ref() { + Some(detail) => format!("{label} · {detail} · {percent}"), + None => format!("{label} · {percent}"), + } + .into(); + let accessibility_label = tooltip_text.clone(); + let progress_id = SharedString::from(format!("{}-progress", id.as_ref())); + + v_flex() + .id(id) + .w(gpui::rems(HOST_METRIC_TRACK_WIDTH_REMS)) + .flex_shrink_0() + .gap_1() + .child( h_flex() - .flex_1() + .w_full() .min_w_0() .items_center() .gap_1() .child( div() - .size_1p5() - .flex_shrink_0() - .rounded_full() - .bg(metric_color(value, cx)), - ) - .child( - div() + .flex_1() .min_w_0() .overflow_hidden() .text_ellipsis() .whitespace_nowrap() .text_xs() .text_color(cx.theme().muted_foreground) - .child(kind.label()), + .child(caption), ) .child( div() .flex_shrink_0() + .w_10() + .text_right() .text_xs() .font_weight(gpui::FontWeight::SEMIBOLD) .text_color(if value >= 75.0 { - metric_color(value, cx) + tone } else { cx.theme().foreground }) - .child(format!("{value:.0}%")), - ) - })) - .into_any_element() -} - -fn render_host_info_chip(id: SharedString, text: String, cx: &App) -> AnyElement { - let tooltip: SharedString = text.clone().into(); - h_flex() - .id(id) - .flex_shrink_0() - .max_w(gpui::rems(12.0)) - .px_2() - .py_0p5() - .rounded(cx.theme().radius) - .border_1() - .border_color(cx.theme().border) - .bg(cx.theme().muted) - .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .child(percent), + ), + ) .child( - div() - .min_w_0() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(text), + Progress::new(progress_id) + .with_size(Size::XSmall) + .color(tone) + .value(value.clamp(0.0, 100.0) as f32) + .accessibility_label(accessibility_label), ) + .tooltip(move |window, cx| Tooltip::new(tooltip_text.clone()).build(window, cx)) .into_any_element() } -fn render_host_metric_chip( - id: SharedString, - label: String, - value: f64, - detail: Option, - cx: &App, -) -> AnyElement { - let tone = metric_color(value, cx); - h_flex() +fn render_host_network_track(id: SharedString, rx: String, tx: String, cx: &App) -> AnyElement { + let label = t!("Home.host_metrics_network_label").to_string(); + let up = t!("Home.host_metrics_network_up", value = tx.clone()).to_string(); + let down = t!("Home.host_metrics_network_down", value = rx.clone()).to_string(); + let tooltip_text: SharedString = format!("{label} · {up} · {down}").into(); + + v_flex() .id(id) + .w(gpui::rems(HOST_METRIC_TRACK_WIDTH_REMS)) .flex_shrink_0() - .items_center() - .gap_1() - .px_2() - .py_0p5() - .rounded(cx.theme().radius) - .border_1() - .border_color(cx.theme().border) - .bg(cx.theme().muted) - .child(div().size_1p5().flex_shrink_0().rounded_full().bg(tone)) + .gap_0p5() .child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(label), + h_flex() + .w_full() + .min_w_0() + .items_center() + .gap_1() + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(label), + ) + .child( + div() + .flex_shrink_0() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("↑"), + ) + .child( + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .child(tx), + ), ) .child( - div() - .text_xs() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(if value >= 75.0 { - tone - } else { - cx.theme().foreground - }) - .child(format!("{value:.0}%")), + h_flex() + .w_full() + .min_w_0() + .items_center() + .gap_1() + .child(div().flex_1()) + .child( + div() + .flex_shrink_0() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("↓"), + ) + .child( + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .child(rx), + ), ) - .when_some(detail, |chip, detail| { - chip.child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(format!("· {detail}")), - ) - }) + .tooltip(move |window, cx| Tooltip::new(tooltip_text.clone()).build(window, cx)) .into_any_element() } @@ -538,47 +481,30 @@ fn format_kib_compact(kib: u64) -> String { } } -fn nearly_whole(value: f64) -> bool { - (value - value.round()).abs() < 0.05 +fn host_network_rates(usage: &terminal_view::HostResourceUsage) -> Option<(String, String)> { + let rx = usage.network_rx_bytes_per_sec?; + let tx = usage.network_tx_bytes_per_sec?; + Some((format_network_rate(rx), format_network_rate(tx))) } -fn render_host_metrics_compact( - usage: &terminal_view::HostResourceUsage, - id_prefix: &str, - cx: &App, -) -> AnyElement { - let metrics = host_metric_values(usage); - let tooltip: SharedString = format_host_metrics_summary(usage) - .unwrap_or_default() - .into(); - h_flex() - .id(SharedString::from(format!("{id_prefix}-compact"))) - .flex_shrink_0() - .items_center() - .justify_center() - .px_1p5() - .py_1() - .rounded_full() - .border_1() - .border_color(cx.theme().border) - .bg(cx.theme().muted) - .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) - .child( - v_flex() - .w_5() - .gap_0p5() - .children(metrics.into_iter().map(|(kind, value)| { - Progress::new(SharedString::from(format!( - "{id_prefix}-compact-{}", - kind.id_suffix() - ))) - .with_size(Size::XSmall) - .color(metric_color(value, cx)) - .value(value.clamp(0.0, 100.0) as f32) - .accessibility_label(format!("{} {value:.0}%", kind.label())) - })), - ) - .into_any_element() +fn format_network_rate(bytes_per_sec: f64) -> String { + const KB: f64 = 1024.0; + const MB: f64 = KB * 1024.0; + const GB: f64 = MB * 1024.0; + let value = bytes_per_sec.max(0.0); + if value >= GB { + format!("{:.1} GB/s", value / GB) + } else if value >= MB { + format!("{:.1} MB/s", value / MB) + } else if value >= KB { + format!("{:.1} KB/s", value / KB) + } else { + format!("{value:.0} B/s") + } +} + +fn nearly_whole(value: f64) -> bool { + (value - value.round()).abs() < 0.05 } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -644,6 +570,8 @@ mod tests { memory_percent: None, disk_total_kib: None, disk_percent: Some(51.6), + network_rx_bytes_per_sec: None, + network_tx_bytes_per_sec: None, }) .iter() .map(|(kind, value)| (kind.id_suffix(), *value)) @@ -659,11 +587,20 @@ mod tests { memory_percent: None, disk_total_kib: None, disk_percent: None, + network_rx_bytes_per_sec: None, + network_tx_bytes_per_sec: None, }), Vec::new() ); } + #[test] + fn network_rate_formatter_uses_compact_binary_units() { + assert_eq!(format_network_rate(830.0), "830 B/s"); + assert_eq!(format_network_rate(2.9 * 1024.0), "2.9 KB/s"); + assert_eq!(format_network_rate(3.25 * 1024.0 * 1024.0), "3.2 MB/s"); + } + #[test] fn compact_capacity_uses_reference_style_units() { assert_eq!(format_kib_compact(27 * 1024 * 1024), "27G"); diff --git a/crates/navop_app/src/home_tab/tests/rendering.rs b/crates/navop_app/src/home_tab/tests/rendering.rs index 8cf2ecd06..58bc917b9 100644 --- a/crates/navop_app/src/home_tab/tests/rendering.rs +++ b/crates/navop_app/src/home_tab/tests/rendering.rs @@ -634,20 +634,26 @@ fn connection_card_and_row_require_the_first_click_for_double_click_open() { } #[test] -fn host_metrics_are_wired_to_card_list_and_tree_views() { +fn host_metrics_are_wired_only_to_the_list_view() { let host_metrics = include_str!("../host_metrics.rs"); let card = include_str!("../connection_card_content.rs"); let list = include_str!("../connection_list.rs"); let tree_rows = include_str!("../../persistent_connection_sidebar/rows.rs"); assert!( - card.contains("render_host_metrics_card"), - "卡片必须使用适配窄宽度的紧凑资源状态带" + !card.contains("render_host_metrics_card"), + "卡片不应显示远端资源条,避免与无资源卡片产生高度和内容差异" ); let card_layout = include_str!("../connection_card.rs"); assert!( - card_layout.contains("shows_host_metrics") && card_layout.contains("5.5"), - "卡片必须仅在需要资源状态带时预留第二行高度" + card_layout.contains("const CONNECTION_CARD_HEIGHT_REMS: f32 = 4.5") + && card_layout.contains("CONNECTION_CARD_HEIGHT_REMS") + && card_layout.contains(".h(gpui::rems(CONNECTION_CARD_HEIGHT_REMS))"), + "卡片布局必须使用统一紧凑高度" + ); + assert!( + !card_layout.contains("let card_height = if shows_host_metrics"), + "卡片高度不得再依赖资源条是否显示" ); assert!( list.contains("render_host_metrics_detail"), @@ -658,17 +664,39 @@ fn host_metrics_are_wired_to_card_list_and_tree_views() { "列表中的地址与资源标签应共用一行并在窄宽度下自然换行" ); assert!( - tree_rows.contains("render_host_metrics_compact"), - "树形布局和默认导航布局左侧树必须显示紧凑资源仪表" + !tree_rows.contains("render_host_metrics_compact"), + "树形布局应保留类型标签,不再用资源仪表替换它" ); assert!( host_metrics.contains("home_show_host_metrics"), - "所有布局共用的摘要必须尊重显示开关" + "列表资源信息必须尊重显示开关" + ); + assert!( + host_metrics.contains("self.connection_layout != ConnectionLayout::List") + && host_metrics.contains("self.connection_layout == ConnectionLayout::List"), + "资源探测必须只在列表布局启用,卡片和树形不得建立隐藏的后台 SSH 会话" ); assert!( host_metrics.contains("Progress::new"), "资源占用应使用进度条表达,不能退回纯文字摘要" ); + assert!( + host_metrics.contains("render_host_metric_track") + && host_metrics.contains("HOST_METRIC_TRACK_WIDTH_REMS") + && host_metrics.contains(".w_10()") + && host_metrics.contains(".text_right()"), + "列表资源项必须使用固定宽度的标签、右对齐百分比和进度轨道,保证跨行对齐" + ); + assert!( + host_metrics.contains("accessibility_label(accessibility_label)"), + "进度条必须为辅助技术提供带标签与数值的完整描述" + ); + assert!( + host_metrics.contains("render_host_network_track") + && host_metrics.contains("network_rx_bytes_per_sec") + && host_metrics.contains("network_tx_bytes_per_sec"), + "列表与卡片必须显示远端上下行网络速率" + ); assert!( host_metrics.contains("Tooltip::new"), "树形紧凑仪表必须能通过 tooltip 展开具体数值" diff --git a/crates/navop_app/src/lib.rs b/crates/navop_app/src/lib.rs index f101a525e..9b8d5c825 100644 --- a/crates/navop_app/src/lib.rs +++ b/crates/navop_app/src/lib.rs @@ -21,6 +21,8 @@ mod connection_sort; mod connection_type_menu; mod connection_visuals; mod credential_vault; +#[cfg(all(feature = "nsh-db", feature = "database"))] +mod db_extension_panels; #[cfg(feature = "nsh-host")] #[cfg(feature = "shell")] mod dev_extension_registry; @@ -56,8 +58,6 @@ mod settings; mod sync_conflict_dialog; mod system_tray; mod team_tab; -#[cfg(all(feature = "nsh-db", feature = "database"))] -mod db_extension_panels; #[cfg(all(feature = "nsh-terminal", feature = "shell"))] mod terminal_extension_panels; mod toolbox_tab; @@ -65,6 +65,7 @@ mod update; mod window_visibility; #[cfg(any(target_os = "windows", test))] mod windows_single_instance; +mod x11_runtime; use crate::navop_app::NavopApp; @@ -530,6 +531,10 @@ where eprintln!("Failed to initialize application paths: {error:#}"); return; } + // 路径初始化后、任何设置加载或 SSH 解析前注入产品真实版本与隔离数据目录。 + if let Err(error) = x11_runtime::configure_runtime(version) { + eprintln!("Failed to configure X11 component runtime: {error:?}"); + } // Public MCP 发现文件必须跟着运行模式走:正式版落在数据目录里(与历史位置 // 一致),开发/便携版落在各自的数据根下。否则 `cargo run` 起开发版就会把 // 正式版的发现文件覆盖成开发实例的 pid/端口,劫持用户已经注册好的 MCP 客户端。 @@ -610,7 +615,9 @@ where // 页面请求刷新 DB 树时,回主线程刷新所有打开着的树(db_view 拥有 // 这些 Entity,nsh 宿主不依赖 db_view,所以用函数指针注入)。 #[cfg(all(feature = "nsh-db", feature = "database"))] - universal_plugins::set_nsh_db_tree_refresh(db_view::db_tree_registry::refresh_open_db_trees); + universal_plugins::set_nsh_db_tree_refresh( + db_view::db_tree_registry::refresh_open_db_trees, + ); // 终端侧边栏的扩展面板:catalog 提供面板声明,nsh 宿主提供视图。 // 必须在 universal_plugins::init 之后(NshHost global 先就位)。 #[cfg(all(feature = "nsh-terminal", feature = "shell"))] diff --git a/crates/navop_app/src/persistent_connection_sidebar/rows.rs b/crates/navop_app/src/persistent_connection_sidebar/rows.rs index 2ea61404c..91182dbfd 100644 --- a/crates/navop_app/src/persistent_connection_sidebar/rows.rs +++ b/crates/navop_app/src/persistent_connection_sidebar/rows.rs @@ -332,21 +332,9 @@ impl PersistentConnectionSidebar { .and_then(|connection| connection.id) .map(|id| self.ai_access_levels.get(&id).copied().unwrap_or_default()) .and_then(|level| connection_ai_access_badge(level, cx)); - let host_metrics_compact = connection.as_ref().and_then(|connection| { - home.read(cx).render_host_metrics_compact( - connection, - &format!("persistent-connection-metrics-{id}"), - cx, - ) - }); - // 树只有一行可用;有资源快照时让更有决策价值的数据占用类型标签位置。 - let type_tag = (host_metrics_compact.is_none()) - .then(|| { - connection - .as_ref() - .map(|connection| connection_type_tag(connection, cx)) - }) - .flatten(); + let type_tag = connection + .as_ref() + .map(|connection| connection_type_tag(connection, cx)); let icon = connection .as_ref() .map(|connection| { @@ -488,7 +476,6 @@ impl PersistentConnectionSidebar { }) .child(tree_connection_icon_slot(icon, palette)) .child(tree_connection_name_with_type_tag(name, type_tag)) - .when_some(host_metrics_compact, |row, metrics| row.child(metrics)) .when_some(team_indicator, |row, indicator| row.child(indicator)) .when_some(ai_access_badge, |row, badge| row.child(badge)) .into_any_element() diff --git a/crates/navop_app/src/setting_tab.rs b/crates/navop_app/src/setting_tab.rs index 22c25e8b2..605eb4bdf 100644 --- a/crates/navop_app/src/setting_tab.rs +++ b/crates/navop_app/src/setting_tab.rs @@ -22,6 +22,7 @@ use crate::settings::tool_exposure_settings::{ }; use crate::settings::update_channel::{beta_exit_notice_item, update_channel_item}; use crate::settings::update_mirror::update_mirror_item; +use crate::settings::x11_settings::x11_setting_group; use crate::update; use font_kit::{file_type::FileType, font::Font}; use gpui::http_client::{AsyncBody, Method, Request}; @@ -1345,6 +1346,7 @@ impl SettingsPanel { &default_settings.remote_file_editor, cx, )); + groups.push(x11_setting_group(default_settings.x11_server_mode)); } groups.push(connection_display_setting_group()); groups.push( diff --git a/crates/navop_app/src/settings/mod.rs b/crates/navop_app/src/settings/mod.rs index 11cac63f2..3db399c05 100644 --- a/crates/navop_app/src/settings/mod.rs +++ b/crates/navop_app/src/settings/mod.rs @@ -22,3 +22,5 @@ pub mod remote_file_editor_settings; pub mod tool_exposure_settings; pub mod update_channel; pub mod update_mirror; +pub mod x11_settings; +mod x11_state; diff --git a/crates/navop_app/src/settings/x11_settings.rs b/crates/navop_app/src/settings/x11_settings.rs new file mode 100644 index 000000000..1c784f6e8 --- /dev/null +++ b/crates/navop_app/src/settings/x11_settings.rs @@ -0,0 +1,286 @@ +//! 通用设置中的 X11 服务选择、状态与内置组件维护。 + +use gpui::{ + AnyElement, App, AppContext as _, AsyncApp, Context, Entity, Global, IntoElement, + ParentElement as _, Render, SharedString, Styled as _, WeakEntity, Window, div, + prelude::FluentBuilder as _, +}; +use gpui_component::{ + ActiveTheme as _, + button::Button, + h_flex, + setting::{SettingField, SettingGroup, SettingItem}, + v_flex, +}; +use one_assets::IconName; +use one_core::gpui_tokio::Tokio; +use one_core::settings::{ + AppSettings, X11ForwardingStatus, X11ServerMode, current_status, installed_version, reinstall, + take_restart_notification_for, +}; +use rust_i18n::t; +use std::time::Duration; + +use super::x11_state::{ + X11InstallState, x11_disabled_guidance_key, x11_install_error_key, x11_status_label, +}; + +const X11_RESTART_POLL_INTERVAL: Duration = Duration::from_secs(1); + +#[derive(Clone)] +struct GlobalX11SettingsState(Entity); + +impl Global for GlobalX11SettingsState {} + +#[derive(Default)] +pub(crate) struct X11SettingsView { + install: X11InstallState, +} + +pub(crate) fn x11_setting_group(default_mode: X11ServerMode) -> SettingGroup { + SettingGroup::new() + .title(t!("Settings.General.X11.group_title")) + .item(mode_item(default_mode)) + .item(status_item()) +} + +fn mode_item(default_mode: X11ServerMode) -> SettingItem { + SettingItem::new( + t!("Settings.General.X11.mode"), + SettingField::dropdown( + vec![ + ("auto".into(), mode_label(X11ServerMode::Auto)), + ("external".into(), mode_label(X11ServerMode::External)), + ("embedded".into(), mode_label(X11ServerMode::Embedded)), + ], + |cx: &App| SharedString::from(mode_value(AppSettings::global(cx).x11_server_mode)), + |value: SharedString, cx: &mut App| { + let mode = mode_from_value(&value); + AppSettings::update_and_save(cx, |settings| settings.x11_server_mode = mode); + x11_settings_state(cx).update(cx, |_, cx| cx.notify()); + }, + ) + .default_value(SharedString::from(mode_value(default_mode))), + ) + .description(t!("Settings.General.X11.mode_desc").to_string()) +} + +fn status_item() -> SettingItem { + SettingItem::new( + t!("Settings.General.X11.status"), + SettingField::render(|_, _, cx| x11_settings_state(cx).into_any_element()), + ) + .description(t!("Settings.General.X11.status_desc").to_string()) +} + +fn x11_settings_state(cx: &mut App) -> Entity { + if let Some(global) = cx.try_global::() { + return global.0.clone(); + } + let state = cx.new(X11SettingsView::new); + cx.set_global(GlobalX11SettingsState(state.clone())); + state +} + +fn mode_label(mode: X11ServerMode) -> SharedString { + let label = match mode { + X11ServerMode::Auto => t!("Settings.General.X11.mode_auto"), + X11ServerMode::External => t!("Settings.General.X11.mode_external"), + X11ServerMode::Embedded => t!("Settings.General.X11.mode_embedded"), + }; + SharedString::from(label.to_string()) +} + +fn mode_value(mode: X11ServerMode) -> &'static str { + match mode { + X11ServerMode::Auto => "auto", + X11ServerMode::External => "external", + X11ServerMode::Embedded => "embedded", + } +} + +fn mode_from_value(value: &str) -> X11ServerMode { + match value { + "external" => X11ServerMode::External, + "embedded" => X11ServerMode::Embedded, + _ => X11ServerMode::Auto, + } +} + +impl X11SettingsView { + fn new(cx: &mut Context) -> Self { + let view = Self::default(); + view.poll_restart_notifications(cx); + view + } + + fn poll_restart_notifications(&self, cx: &mut Context) { + let consumer = cx.entity().entity_id().as_u64(); + cx.spawn(async move |this: WeakEntity, cx: &mut AsyncApp| { + loop { + let notification = take_restart_notification_for(consumer); + let alive = this + .update(cx, |this, cx| { + this.install.record_restart(notification); + cx.notify(); + }) + .is_ok(); + if !alive { + break; + } + cx.background_executor() + .timer(X11_RESTART_POLL_INTERVAL) + .await; + } + }) + .detach(); + } + + fn start_reinstall(&mut self, cx: &mut Context) { + if !self.install.begin_install() { + return; + } + cx.notify(); + let task = Tokio::spawn(cx, async move { reinstall().await }); + cx.spawn(async move |this: WeakEntity, cx: &mut AsyncApp| { + let result = task + .await + .map_err(|error| { + t!( + "Settings.General.X11.install_failed_retry", + reason = error.to_string() + ) + .to_string() + }) + .and_then(|result| { + result.map_err(|error| { + let key = x11_install_error_key(&error); + t!(key, reason = error.to_string()).to_string() + }) + }); + let _ = this.update(cx, |this, cx| { + this.install.finish_install(result); + cx.notify(); + }); + }) + .detach(); + } + + fn render_summary(&self, status: &X11ForwardingStatus, cx: &App) -> AnyElement { + let version = installed_version() + .unwrap_or_else(|| t!("Settings.General.X11.not_installed").to_string()); + v_flex() + .gap_1() + .child(div().text_sm().child(x11_status_label(status))) + .child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child( + t!("Settings.General.X11.installed_version", version = version).to_string(), + ), + ) + .into_any_element() + } + + fn render_restart(&self, cx: &App) -> Option { + let notification = self.install.restart_notification()?; + Some( + div() + .text_xs() + .text_color(cx.theme().warning) + .child( + t!( + "Settings.General.X11.remote_display_restarted", + reason = notification.reason + ) + .to_string(), + ) + .into_any_element(), + ) + } + + fn render_install(&self, cx: &mut Context) -> AnyElement { + let installing = self.install.is_installing(); + let label = if installing { + t!("Settings.General.X11.installing") + } else { + t!("Settings.General.X11.reinstall") + }; + h_flex() + .w_full() + .items_center() + .justify_between() + .gap_3() + .when_some( + self.install.message().map(str::to_owned), + |this, message| this.child(div().flex_1().min_w_0().text_sm().child(message)), + ) + .child( + Button::new("settings-x11-reinstall") + .icon(IconName::Refresh) + .label(label) + .loading(installing) + .on_click(cx.listener(|this, _, _, cx| this.start_reinstall(cx))), + ) + .into_any_element() + } +} + +impl Render for X11SettingsView { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let status = current_status(); + v_flex() + .w_full() + .gap_3() + .child(self.render_summary(&status, cx)) + .child(self.render_install(cx)) + .when_some(self.render_restart(cx), |this, notification| { + this.child(notification) + }) + .when_some(disabled_guidance(&status, cx), |this, guidance| { + this.child(guidance) + }) + .when(cfg!(target_os = "macos"), |this| { + this.child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(t!("Settings.General.X11.macos_xquartz_guidance").to_string()), + ) + }) + } +} + +fn disabled_guidance(status: &X11ForwardingStatus, cx: &App) -> Option { + let key = x11_disabled_guidance_key(status)?; + let X11ForwardingStatus::Disabled { reason } = status else { + return None; + }; + Some( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(t!(key, reason = reason).to_string()) + .into_any_element(), + ) +} + +#[cfg(test)] +mod tests { + #[test] + fn x11_mode_description_requires_reconnect_for_existing_sessions() { + for language in ["en", "zh-CN", "zh-HK"] { + rust_i18n::set_locale(language); + let description = rust_i18n::t!("Settings.General.X11.mode_desc"); + let expected = match language { + "en" => "must be reconnected", + "zh-CN" => "必须重新连接", + "zh-HK" => "必須重新連線", + _ => unreachable!(), + }; + assert!(description.contains(expected), "{language}: {description}"); + } + rust_i18n::set_locale("en"); + } +} diff --git a/crates/navop_app/src/settings/x11_state.rs b/crates/navop_app/src/settings/x11_state.rs new file mode 100644 index 000000000..292ca942b --- /dev/null +++ b/crates/navop_app/src/settings/x11_state.rs @@ -0,0 +1,265 @@ +//! X11 设置的状态映射与本地安装状态契约。 + +use one_core::settings::{X11ComponentError, X11ForwardingStatus, X11RestartNotification}; +use rust_i18n::t; + +#[derive(Default)] +pub(crate) struct X11InstallState { + installing: bool, + message: Option, + restart_notification: Option, +} + +impl X11InstallState { + pub(crate) fn begin_install(&mut self) -> bool { + if self.installing { + return false; + } + self.installing = true; + self.message = None; + true + } + + pub(crate) fn finish_install(&mut self, result: Result) { + self.installing = false; + self.message = Some(match result { + Ok(version) => { + t!("Settings.General.X11.install_success", version = version).to_string() + } + Err(error) => error, + }); + } + + pub(crate) fn is_installing(&self) -> bool { + self.installing + } + + pub(crate) fn message(&self) -> Option<&str> { + self.message.as_deref() + } + + pub(crate) fn record_restart(&mut self, notification: Option) { + if let Some(notification) = notification { + self.restart_notification = Some(notification); + } + } + + pub(crate) fn restart_notification(&self) -> Option<&X11RestartNotification> { + self.restart_notification.as_ref() + } +} + +pub(crate) fn x11_install_error_key(error: &X11ComponentError) -> &'static str { + match error { + X11ComponentError::Sha256Mismatch { .. } | X11ComponentError::SignatureInvalid(_) => { + "Settings.General.X11.signature_failed_support" + } + X11ComponentError::VulkanUnavailable { .. } => { + "Settings.General.X11.vulkan_unavailable_use_external" + } + X11ComponentError::Handshake(_) | X11ComponentError::EmbeddedDisabled(_) => { + "Settings.General.X11.handshake_failed_fallback" + } + _ => "Settings.General.X11.install_failed_retry", + } +} + +pub(crate) fn x11_disabled_guidance_key(status: &X11ForwardingStatus) -> Option<&'static str> { + let X11ForwardingStatus::Disabled { reason } = status else { + return None; + }; + if reason.contains("Vulkan") { + return Some("Settings.General.X11.vulkan_unavailable_use_external"); + } + if reason.contains("验签") || reason.contains("SHA256") { + return Some("Settings.General.X11.signature_failed_support"); + } + if reason.contains("握手") || reason.contains("内置 X11") || reason.contains("内置服务") + { + return Some("Settings.General.X11.handshake_failed_fallback"); + } + if reason.contains("X11 组件安装失败") { + return Some("Settings.General.X11.install_failed_retry"); + } + None +} + +pub(crate) fn x11_status_label(status: &X11ForwardingStatus) -> String { + match status { + X11ForwardingStatus::External { server } => { + t!("Settings.General.X11.status_external", server = server).to_string() + } + X11ForwardingStatus::Embedded { version } => { + t!("Settings.General.X11.status_embedded", version = version).to_string() + } + X11ForwardingStatus::Disabled { reason } => { + t!("Settings.General.X11.status_disabled", reason = reason).to_string() + } + } +} + +#[cfg(test)] +mod tests { + use one_core::settings::{X11ComponentError, X11ForwardingStatus, X11RestartNotification}; + + use super::{ + X11InstallState, x11_disabled_guidance_key, x11_install_error_key, x11_status_label, + }; + + #[test] + fn restart_notice_requires_a_structured_event() { + let mut state = X11InstallState::default(); + state.record_restart(None); + assert!(state.restart_notification().is_none()); + + let notification = X11RestartNotification { + generation: 1, + reason: "yserver exited".into(), + }; + state.record_restart(Some(notification.clone())); + assert_eq!(Some(¬ification), state.restart_notification()); + } + + #[test] + fn status_poll_refreshes_even_without_a_restart() { + let source = include_str!("x11_settings.rs"); + assert!(source.contains( + "this.install.record_restart(notification);\n cx.notify();" + )); + } + + #[test] + fn install_rejects_duplicate_clicks_and_finishes_visibly() { + let mut state = X11InstallState::default(); + assert!(state.begin_install()); + assert!(!state.begin_install(), "安装中不得重复发起"); + assert!(state.is_installing()); + + state.finish_install(Ok("1.2.3".to_string())); + assert!(!state.is_installing()); + assert!( + state + .message() + .is_some_and(|message| message.contains("1.2.3")) + ); + + assert!(state.begin_install()); + state.finish_install(Err("内嵌包不可用".to_string())); + assert!(!state.is_installing()); + assert_eq!(Some("内嵌包不可用"), state.message()); + } + + #[test] + fn typed_install_errors_map_to_actionable_messages() { + let cases = [ + ( + X11ComponentError::Install("timeout".to_string()), + "Settings.General.X11.install_failed_retry", + ), + ( + X11ComponentError::SignatureInvalid("bad signature".to_string()), + "Settings.General.X11.signature_failed_support", + ), + ( + X11ComponentError::Sha256Mismatch { + expected: "a".to_string(), + actual: "b".to_string(), + }, + "Settings.General.X11.signature_failed_support", + ), + ( + X11ComponentError::VulkanUnavailable { + required: "1.2".to_string(), + actual: None, + }, + "Settings.General.X11.vulkan_unavailable_use_external", + ), + ( + X11ComponentError::Handshake("protocol".to_string()), + "Settings.General.X11.handshake_failed_fallback", + ), + ]; + + for (error, expected) in cases { + assert_eq!(expected, x11_install_error_key(&error)); + } + } + + #[test] + fn status_label_uses_structured_server_version_and_reason() { + let external = x11_status_label(&X11ForwardingStatus::External { + server: ":0".to_string(), + }); + let embedded = x11_status_label(&X11ForwardingStatus::Embedded { + version: "1.2.3".to_string(), + }); + let disabled = x11_status_label(&X11ForwardingStatus::Disabled { + reason: "display unavailable".to_string(), + }); + + assert!(external.contains(":0")); + assert!(embedded.contains("1.2.3")); + assert!(embedded.contains("Vulkan")); + assert!(disabled.contains("display unavailable")); + } + + #[test] + fn disabled_guidance_matches_local_error_without_remote_restart_guesses() { + let cases = [ + ( + "Vulkan 能力不满足要求", + Some("Settings.General.X11.vulkan_unavailable_use_external"), + ), + ( + "X11 组件 Ed25519 验签失败", + Some("Settings.General.X11.signature_failed_support"), + ), + ( + "X11 组件 SHA256 不匹配", + Some("Settings.General.X11.signature_failed_support"), + ), + ( + "X11 握手失败", + Some("Settings.General.X11.handshake_failed_fallback"), + ), + ( + "X11 组件安装失败", + Some("Settings.General.X11.install_failed_retry"), + ), + ("尚未解析 X11 服务", None), + ("远程显示已重启", None), + ("未找到外部 X11 服务", None), + ]; + + for (reason, expected) in cases { + let status = X11ForwardingStatus::Disabled { + reason: reason.to_string(), + }; + assert_eq!( + expected, + x11_disabled_guidance_key(&status), + "原因: {reason}" + ); + } + } + + #[test] + fn x11_failure_copy_exists_in_all_three_languages() { + for language in ["en", "zh-CN", "zh-HK"] { + rust_i18n::set_locale(language); + for key in [ + "Settings.General.X11.install_failed_retry", + "Settings.General.X11.signature_failed_support", + "Settings.General.X11.vulkan_unavailable_use_external", + "Settings.General.X11.handshake_failed_fallback", + "Settings.General.X11.remote_display_restarted", + "Settings.General.X11.remote_forwarding_disabled_checklist", + "Settings.General.X11.untrusted_ssh_x_security", + "Settings.General.X11.macos_xquartz_guidance", + ] { + assert_ne!(key, rust_i18n::t!(key), "{language} 缺少文案: {key}"); + } + } + rust_i18n::set_locale("en"); + } +} diff --git a/crates/navop_app/src/x11_runtime.rs b/crates/navop_app/src/x11_runtime.rs new file mode 100644 index 000000000..b04749fa2 --- /dev/null +++ b/crates/navop_app/src/x11_runtime.rs @@ -0,0 +1,66 @@ +//! X11 组件的应用级启动配置。 + +use semver::Version; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum X11RuntimeConfigError { + InvalidVersion, + MissingDataDir, +} + +pub(crate) struct X11RuntimeConfig { + pub(crate) version: Version, + pub(crate) data_dir: PathBuf, +} + +pub(crate) fn parse_runtime_config( + version: &str, + data_dir: Option, +) -> Result { + let version = Version::parse(version).map_err(|_| X11RuntimeConfigError::InvalidVersion)?; + let data_dir = data_dir.ok_or(X11RuntimeConfigError::MissingDataDir)?; + Ok(X11RuntimeConfig { version, data_dir }) +} + +pub(crate) fn configure_runtime(version: &str) -> Result<(), X11RuntimeConfigError> { + let config = parse_runtime_config(version, one_core::app_dirs::data_dir())?; + x11_component::set_navop_version(config.version); + x11_component::set_data_dir(config.data_dir); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{X11RuntimeConfigError, parse_runtime_config}; + use std::path::PathBuf; + + #[test] + fn parses_product_version_without_panicking() { + let config = parse_runtime_config("0.23.4", Some(PathBuf::from("/tmp/navop-data"))) + .expect("合法版本与数据目录应可注入"); + + assert_eq!("0.23.4", config.version.to_string()); + assert_eq!(PathBuf::from("/tmp/navop-data"), config.data_dir); + } + + #[test] + fn rejects_invalid_version_and_missing_data_dir() { + assert_eq!( + Err(X11RuntimeConfigError::InvalidVersion), + parse_runtime_config("not-semver", Some(PathBuf::from("/tmp/navop-data"))) + .map(|config| (config.version, config.data_dir)) + ); + assert_eq!( + Err(X11RuntimeConfigError::MissingDataDir), + parse_runtime_config("0.23.4", None).map(|config| (config.version, config.data_dir)) + ); + } + + #[test] + fn navop_app_package_version_is_valid() { + assert!( + parse_runtime_config(env!("CARGO_PKG_VERSION"), Some(PathBuf::from("data"))).is_ok() + ); + } +} diff --git a/crates/one-assets/assets/icons/quick-commands.svg b/crates/one-assets/assets/icons/quick-commands.svg new file mode 100644 index 000000000..5e432e815 --- /dev/null +++ b/crates/one-assets/assets/icons/quick-commands.svg @@ -0,0 +1,13 @@ + + + diff --git a/crates/one-assets/assets/icons/record.svg b/crates/one-assets/assets/icons/record.svg new file mode 100644 index 000000000..f9991a8a7 --- /dev/null +++ b/crates/one-assets/assets/icons/record.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/sftp/src/russh_impl.rs b/crates/sftp/src/russh_impl.rs index e93782efc..788de8b05 100644 --- a/crates/sftp/src/russh_impl.rs +++ b/crates/sftp/src/russh_impl.rs @@ -23,7 +23,7 @@ use rust_i18n::t; use ssh::{ AuthFailureMessages, HostKeyAcceptance, HostKeyDetails, HostKeyIdentity, HostKeyVerifier, KeyboardInteractiveTarget, ProxyConnectConfig, ProxyType, RusshClient, SshConnectConfig, - add_jump_channel_rejected_hint, add_legacy_algorithm_hint, authenticate_with_strategy, + add_jump_channel_rejected_hint, add_legacy_algorithm_hint, authenticate_with_strategy_for_target, build_client_preferred_algorithms_with_legacy, defaults, }; use std::collections::{BTreeMap, BTreeSet}; @@ -2690,11 +2690,13 @@ impl SftpClient for RusshSftpClient { .as_ref() .is_some_and(|jump| jump.bastion_login_username().is_some()); if !bastion_direct { - authenticate_with_strategy( + authenticate_with_strategy_for_target( &mut session, &ssh_config.username, &ssh_config.auth, sftp_auth_failure_messages(), + KeyboardInteractiveTarget::TargetServer, + ssh_config.keyboard_interactive_responder.clone(), ) .await?; } diff --git a/crates/sftp/tests/keyboard_interactive_auth.rs b/crates/sftp/tests/keyboard_interactive_auth.rs new file mode 100644 index 000000000..1ba124a6a --- /dev/null +++ b/crates/sftp/tests/keyboard_interactive_auth.rs @@ -0,0 +1,224 @@ +//! SFTP 目标服务器 keyboard-interactive 认证回归。 +//! +//! 这里不实现完整 SFTP 子系统:认证成功后主动拒绝 `sftp` subsystem, +//! 只验证 `RusshSftpClient::connect` 在目标服务器阶段确实把配置里的 +//! responder 交给了认证策略,而不是像普通跳板机分支那样忽略它。 + +use std::borrow::Cow; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use russh::MethodSet; +use russh::keys::{Algorithm, PrivateKey}; +use russh::server::{Auth, Response, Server as _}; +use sftp::{RusshSftpClient, SftpClient}; +use ssh::{ + HostKeyVerifier, KeyboardInteractiveRequest, KeyboardInteractiveResponder, SshAuth, + SshConnectConfig, +}; +use tokio::net::TcpListener; + +const USERNAME: &str = "tester"; +const PASSWORD: &str = "saved-password"; +const VERIFICATION_CODE: &str = "123456"; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AuthEvent { + KeyboardInteractiveStart, + KeyboardInteractiveAnswers(Vec), +} + +#[derive(Clone, Default)] +struct FakeMfaServer { + events: Arc>>, +} + +impl FakeMfaServer { + fn events(&self) -> Vec { + self.events.lock().expect("events lock").clone() + } +} + +#[derive(Clone)] +struct FakeMfaHandler { + events: Arc>>, +} + +impl FakeMfaHandler { + fn record(&self, event: AuthEvent) { + self.events.lock().expect("events lock").push(event); + } +} + +impl russh::server::Server for FakeMfaServer { + type Handler = FakeMfaHandler; + + fn new_client(&mut self, _: Option) -> Self::Handler { + FakeMfaHandler { + events: self.events.clone(), + } + } +} + +impl russh::server::Handler for FakeMfaHandler { + type Error = anyhow::Error; + + async fn auth_none(&mut self, _: &str) -> Result { + Ok(Auth::reject()) + } + + async fn auth_password(&mut self, _: &str, _: &str) -> Result { + Ok(Auth::reject()) + } + + async fn auth_keyboard_interactive<'a>( + &'a mut self, + _: &str, + _: &str, + response: Option>, + ) -> Result { + let Some(response) = response else { + self.record(AuthEvent::KeyboardInteractiveStart); + return Ok(Auth::Partial { + name: "MFA".into(), + instructions: "".into(), + prompts: Cow::Owned(vec![(Cow::Borrowed("Verification code: "), true)]), + }); + }; + + let answers = response + .map(|answer| String::from_utf8_lossy(&answer).to_string()) + .collect::>(); + self.record(AuthEvent::KeyboardInteractiveAnswers(answers.clone())); + if answers == [VERIFICATION_CODE] { + Ok(Auth::Accept) + } else { + Ok(Auth::reject()) + } + } + + async fn channel_open_session( + &mut self, + _channel: russh::Channel, + reply: russh::server::ChannelOpenHandle, + _session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + reply.accept().await; + Ok(()) + } + + async fn subsystem_request( + &mut self, + channel: russh::ChannelId, + _name: &str, + session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + session.channel_failure(channel)?; + session.close(channel)?; + Ok(()) + } +} + +struct RecordingMfaResponder { + requests: Mutex>, +} + +impl RecordingMfaResponder { + fn new() -> Arc { + Arc::new(Self { + requests: Mutex::new(Vec::new()), + }) + } + + fn prompt_lines(&self) -> Vec { + self.requests + .lock() + .expect("requests lock") + .iter() + .flat_map(|request| request.prompts.iter().map(|prompt| prompt.prompt.clone())) + .collect() + } +} + +#[async_trait] +impl KeyboardInteractiveResponder for RecordingMfaResponder { + async fn respond(&self, request: KeyboardInteractiveRequest) -> anyhow::Result> { + self.requests.lock().expect("requests lock").push(request); + Ok(vec![VERIFICATION_CODE.to_string()]) + } +} + +fn connect_config( + address: std::net::SocketAddr, + responder: Arc, +) -> SshConnectConfig { + SshConnectConfig { + host: address.ip().to_string(), + port: address.port(), + username: USERNAME.to_string(), + auth: SshAuth::Password(PASSWORD.to_string()), + timeout: Some(Duration::from_secs(10)), + keepalive_interval: None, + keepalive_max: None, + jump_server: None, + proxy: None, + keyboard_interactive_responder: Some(responder), + host_key_verifier: HostKeyVerifier::insecure(), + x11_forwarding: false, + allow_legacy_algorithms: false, + forward_agent: false, + agent_identities: Vec::new(), + } +} + +#[tokio::test] +async fn sftp_target_uses_configured_keyboard_interactive_responder() { + let socket = TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("fake SFTP server should bind"); + let address = socket.local_addr().expect("server address"); + let server = FakeMfaServer::default(); + let server_config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + methods: MethodSet::from( + &[ + russh::MethodKind::Password, + russh::MethodKind::KeyboardInteractive, + ][..], + ), + keys: vec![ + PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519) + .expect("test host key should be generated"), + ], + ..Default::default() + }); + let mut running_server = server.clone(); + let server_task = tokio::spawn(async move { + let _ = running_server.run_on_socket(server_config, &socket).await; + }); + + let responder = RecordingMfaResponder::new(); + let result = RusshSftpClient::connect(connect_config(address, responder.clone())).await; + server_task.abort(); + + assert_eq!( + responder.prompt_lines(), + vec!["Verification code: ".to_string()], + "目标服务器下发的 keyboard-interactive 提示必须进入 responder;连接错误:{:?}", + result.as_ref().err() + ); + assert_eq!( + server.events(), + vec![ + AuthEvent::KeyboardInteractiveStart, + AuthEvent::KeyboardInteractiveAnswers(vec![VERIFICATION_CODE.to_string()]), + ], + "responder 的应答必须提交给目标服务器" + ); + assert!( + result.is_err(), + "测试服务器故意拒绝 sftp subsystem,认证之后应返回连接错误" + ); +} diff --git a/crates/sftp_view/Cargo.toml b/crates/sftp_view/Cargo.toml index ebdd26428..54d092af9 100644 --- a/crates/sftp_view/Cargo.toml +++ b/crates/sftp_view/Cargo.toml @@ -16,8 +16,10 @@ sftp_transfer = { workspace = true } remote_file_editor = { workspace = true } remote_image_preview = { workspace = true } ssh = { workspace = true } +otp = { workspace = true } tokio = { workspace = true } anyhow = { workspace = true } +async-trait = { workspace = true } tracing = { workspace = true } chrono = { workspace = true } dirs = { workspace = true } @@ -27,7 +29,6 @@ serde_json = { workspace = true } sysinfo = { workspace = true } [dev-dependencies] -async-trait = { workspace = true } gpui = { workspace = true, features = ["test-support"] } tempfile = "3" diff --git a/crates/sftp_view/locales/sftp_view.yml b/crates/sftp_view/locales/sftp_view.yml index e39a71294..43e4dc494 100644 --- a/crates/sftp_view/locales/sftp_view.yml +++ b/crates/sftp_view/locales/sftp_view.yml @@ -570,6 +570,29 @@ Credentials: zh-CN: 请输入密码。 zh-HK: 請輸入密碼。 +# Keyboard-interactive / MFA +Mfa: + title: + en: Keyboard-interactive authentication + zh-CN: 键盘交互认证 + zh-HK: 鍵盤互動認證 + response_placeholder: + en: MFA response + zh-CN: MFA 响应 + zh-HK: MFA 回應 + response_required: + en: Please fill in every field. + zh-CN: 请填写所有字段。 + zh-HK: 請填寫所有欄位。 + auth_keyboard_interactive_cancelled: + en: MFA/keyboard-interactive authentication was cancelled + zh-CN: 已取消 MFA/keyboard-interactive 二次认证 + zh-HK: 已取消 MFA/keyboard-interactive 二次認證 + submit: + en: Continue + zh-CN: 继续 + zh-HK: 繼續 + # 终端 Terminal: open_here: diff --git a/crates/sftp_view/src/left_remote.rs b/crates/sftp_view/src/left_remote.rs index 401685174..0af4471f0 100644 --- a/crates/sftp_view/src/left_remote.rs +++ b/crates/sftp_view/src/left_remote.rs @@ -97,15 +97,38 @@ impl SftpView { return; } let generation = self.next_left_connection_generation(); - let Some(endpoint) = self.left_remote.as_mut() else { + self.clear_sftp_mfa_for_left(); + let Some((connection_id, connection, mut config, ftp_config, initial_directory)) = + self.left_remote.as_ref().map(|endpoint| { + ( + endpoint.connection.id, + endpoint.connection.clone(), + endpoint.config.clone(), + endpoint.remote_file_ftp.clone(), + endpoint.sftp_initial_directory.clone(), + ) + }) + else { return; }; - endpoint.state = LeftRemoteConnectionState::Connecting; - endpoint.loading = false; - let config = endpoint.config.clone(); - let ftp_config = endpoint.remote_file_ftp.clone(); - let initial_directory = endpoint.sftp_initial_directory.clone(); - let connection_id = endpoint.connection.id; + if let Some(connection_id) = connection_id { + config.keyboard_interactive_responder = self + .sftp_mfa_responder_for( + &connection, + &config, + ftp_config.is_some(), + crate::mfa::SftpMfaTarget::Left { + connection_id, + generation, + }, + ) + .map(|responder| Arc::new(responder) as Arc); + } + if let Some(endpoint) = self.left_remote.as_mut() { + endpoint.config = config.clone(); + endpoint.state = LeftRemoteConnectionState::Connecting; + endpoint.loading = false; + } let window_handle = self.window_handle.clone(); let task = Tokio::spawn(cx, async move { let mut client: Box = match ftp_config { @@ -425,6 +448,7 @@ impl SftpView { ) -> Option { self.left_connection_generation.advance(); self.left_credential_inputs = None; + self.clear_sftp_mfa_for_left(); let mut endpoint = self.left_remote.take()?; self.set_left_connection_active_for(endpoint.connection.id, false, cx); endpoint.client.take() diff --git a/crates/sftp_view/src/lib.rs b/crates/sftp_view/src/lib.rs index aebb11ccb..f0dedc2e8 100644 --- a/crates/sftp_view/src/lib.rs +++ b/crates/sftp_view/src/lib.rs @@ -13,6 +13,7 @@ mod left_credential_prompt; mod left_remote; mod left_remote_state; mod local_volume; +mod mfa; mod ssh_config; use context_menu_handler::ContextMenuHandler; @@ -100,6 +101,7 @@ use tokio::sync::Mutex; use host_key_prompt::{HostKeyPromptTarget, host_key_prompt_request}; use left_credential_prompt::LeftCredentialInputs; use left_remote_state::{LeftRemoteConnectionState, LeftRemoteEndpoint}; +use mfa::{SftpMfaEvent, SftpMfaInputs, SftpMfaResponder, SftpMfaTarget}; actions!( sftp_view, @@ -1607,6 +1609,12 @@ pub struct SftpView { credential_inputs: Option, /// 左侧端点切换时用于录入临时凭据的弹窗状态;`None` 表示不需要提示。 left_credential_inputs: Option, + /// 当前展示的 keyboard-interactive/MFA 弹窗。 + sftp_mfa_inputs: Option, + /// 多个传输连接同时要求 MFA 时按到达顺序逐个提示。 + pending_sftp_mfa_events: VecDeque, + sftp_mfa_event_tx: Option>, + _sftp_mfa_event_task: Option>, /// 远程文件协议为 FTP 时的独立 FTP 连接配置;`None` 表示走 SFTP。 remote_file_ftp: Option, sftp_client: Option, @@ -1962,6 +1970,7 @@ impl SftpView { .unwrap_or_else(|| TransferClientSource::Ssh(config.clone())), MAX_CONCURRENT_TRANSFERS, )); + let (sftp_mfa_event_tx, mut sftp_mfa_event_rx) = tokio::sync::mpsc::unbounded_channel(); let mut view = Self { window_handle: window.window_handle(), @@ -1976,6 +1985,10 @@ impl SftpView { remote_file_ftp, credential_inputs, left_credential_inputs: None, + sftp_mfa_inputs: None, + pending_sftp_mfa_events: VecDeque::new(), + sftp_mfa_event_tx: Some(sftp_mfa_event_tx), + _sftp_mfa_event_task: None, sftp_client: None, connection_generation: ConnectionGeneration::default(), left_connection_generation: ConnectionGeneration::default(), @@ -2029,6 +2042,23 @@ impl SftpView { tab_index, }; + let mfa_window_handle = window.window_handle(); + let mfa_view = cx.entity().downgrade(); + view._sftp_mfa_event_task = Some(cx.spawn( + async move |_: WeakEntity, cx: &mut AsyncApp| { + while let Some(event) = sftp_mfa_event_rx.recv().await { + let updated = cx.update_window(mfa_window_handle, |_, window, cx| { + let _ = mfa_view.update(cx, |this, cx| { + this.receive_sftp_mfa_event(event, window, cx); + }); + }); + if updated.is_err() { + break; + } + } + }, + )); + view.refresh_local_dir(cx); if let Some(input) = view .credential_inputs @@ -2052,6 +2082,29 @@ impl SftpView { self.connection_generation.is_current(generation) } + fn sftp_mfa_responder_for( + &self, + connection: &StoredConnection, + config: &SshConnectConfig, + is_ftp: bool, + target: SftpMfaTarget, + ) -> Option { + if is_ftp { + return None; + } + let params = connection.to_ssh_params().ok()?; + if !params.keyboard_interactive_enabled() { + return None; + } + Some(SftpMfaResponder::new( + target, + self.sftp_mfa_event_tx.clone()?, + mfa::jump_password(config), + mfa::password_from_ssh_auth(&config.auth), + params.otp.clone(), + )) + } + fn next_left_connection_generation(&mut self) -> u64 { self.left_connection_generation.advance() } @@ -2065,9 +2118,20 @@ impl SftpView { return; } let generation = self.next_connection_generation(); + self.clear_sftp_mfa_for_main(); self.set_connection_state(ConnectionState::Connecting, cx); - let config = self.sftp_config.clone(); + let mut config = self.sftp_config.clone(); let ftp_config = self.remote_file_ftp.clone(); + config.keyboard_interactive_responder = self + .sftp_mfa_responder_for( + &self.stored_connection, + &config, + ftp_config.is_some(), + SftpMfaTarget::Main { generation }, + ) + .map(|responder| Arc::new(responder) as Arc); + self.sftp_config = config.clone(); + self.replace_transfer_client_pool(cx); let window_handle = self.window_handle.clone(); let initial_directory = self.sftp_initial_directory.clone(); @@ -2252,7 +2316,6 @@ impl SftpView { Tokio::spawn(cx, disconnect_sftp_client(old_client)).detach(); } self.remote_loading = false; - self.replace_transfer_client_pool(cx); self.connect(cx); } @@ -2301,7 +2364,6 @@ impl SftpView { if let Some(inputs) = self.credential_inputs.as_mut() { inputs.error = None; } - self.replace_transfer_client_pool(cx); self.connect(cx); } Err(error) => { @@ -2328,7 +2390,6 @@ impl SftpView { if let Some(inputs) = self.credential_inputs.as_mut() { inputs.error = None; } - self.replace_transfer_client_pool(cx); self.connect(cx); } Err(error) => { diff --git a/crates/sftp_view/src/mfa.rs b/crates/sftp_view/src/mfa.rs new file mode 100644 index 000000000..f071ea295 --- /dev/null +++ b/crates/sftp_view/src/mfa.rs @@ -0,0 +1,633 @@ +//! SFTP 连接中的 keyboard-interactive/MFA 弹窗。 +//! +//! 底层认证 future 运行在 Tokio 上,不能直接操作 GPUI。这里通过有界生命周期 +//! 的 responder + oneshot 把提示送回视图:保存的密码自动应答,验证码等动态 +//! 提示由用户填写;配置了 TOTP 密钥时优先本地生成验证码。 + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use anyhow::{Result, anyhow}; +use async_trait::async_trait; +use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement, Styled, Subscription, WeakEntity, + Window, div, px, +}; +use gpui_component::{ + ActiveTheme, WindowExt as _, + button::{Button, ButtonVariants}, + dialog::DialogFooter, + input::{Input, InputEvent, InputState}, + v_flex, +}; +use otp::OtpSecret; +use rust_i18n::t; +use ssh::{ + KeyboardInteractivePrompt, KeyboardInteractiveRequest, KeyboardInteractiveResponder, + KeyboardInteractiveTarget, SshAuth, SshConnectConfig, +}; +use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::oneshot; + +use crate::SftpView; + +/// 一次 MFA 提示属于哪条 SFTP 建连链路。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SftpMfaTarget { + Main { generation: u64 }, + Left { connection_id: i64, generation: u64 }, +} + +/// 需要用户填写的单个 keyboard-interactive 提示。 +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SftpMfaPrompt { + pub(crate) prompt: String, + pub(crate) echo: bool, +} + +/// 从 Tokio 认证任务送到 GPUI 的提示事件。 +pub(crate) struct SftpMfaEvent { + pub(crate) target: SftpMfaTarget, + pub(crate) name: String, + pub(crate) instructions: String, + pub(crate) prompts: Vec, + pub(crate) response_tx: oneshot::Sender>, +} + +pub(crate) struct SftpMfaInputs { + target: SftpMfaTarget, + name: String, + instructions: String, + prompts: Vec, + inputs: Vec>, + response_tx: Option>>, + error: Option, + _subscriptions: Vec, +} + +/// 提供给底层 SFTP 客户端的 keyboard-interactive 应答器。 +#[derive(Clone)] +pub(crate) struct SftpMfaResponder { + target: SftpMfaTarget, + event_tx: UnboundedSender, + jump_password: Option, + target_password: Option, + otp: Option, + step_offset: Arc, +} + +impl SftpMfaResponder { + pub(crate) fn new( + target: SftpMfaTarget, + event_tx: UnboundedSender, + jump_password: Option, + target_password: Option, + otp: Option, + ) -> Self { + Self { + target, + event_tx, + jump_password, + target_password, + otp, + step_offset: Arc::new(AtomicU32::new(0)), + } + } + + fn password(&self, target: KeyboardInteractiveTarget) -> Option<&str> { + match target { + KeyboardInteractiveTarget::JumpServer => self.jump_password.as_deref(), + KeyboardInteractiveTarget::TargetServer => self.target_password.as_deref(), + } + } +} + +#[async_trait] +impl KeyboardInteractiveResponder for SftpMfaResponder { + async fn respond(&self, request: KeyboardInteractiveRequest) -> Result> { + let password = self.password(request.target); + let step_offset = self.step_offset.fetch_add(1, Ordering::Relaxed); + if let Some(answers) = ssh::auto_answer_keyboard_interactive( + &request, + self.otp.as_ref(), + password, + step_offset, + otp::current_unix_seconds(), + ) { + return Ok(answers); + } + + let prompts = manual_prompts(&request.prompts, password); + if prompts.is_empty() { + return answers_from_manual_responses(&request.prompts, &[], password); + } + + let (response_tx, response_rx) = oneshot::channel(); + self.event_tx + .send(SftpMfaEvent { + target: self.target, + name: request.name.clone(), + instructions: request.instructions.clone(), + prompts, + response_tx, + }) + .map_err(|_| anyhow!(t!("Mfa.auth_keyboard_interactive_cancelled").to_string()))?; + let responses = response_rx + .await + .map_err(|_| anyhow!(t!("Mfa.auth_keyboard_interactive_cancelled").to_string()))?; + answers_from_manual_responses(&request.prompts, &responses, password) + } +} + +/// 只保留不能由保存的密码自动应答的提示。 +fn manual_prompts( + prompts: &[KeyboardInteractivePrompt], + password: Option<&str>, +) -> Vec { + prompts + .iter() + .filter(|prompt| !(ssh::is_password_prompt(&prompt.prompt) && password.is_some())) + .map(|prompt| SftpMfaPrompt { + prompt: prompt.prompt.clone(), + echo: prompt.echo, + }) + .collect() +} + +/// 把用户填写的动态提示与保存的密码按服务器原始顺序合并。 +fn answers_from_manual_responses( + prompts: &[KeyboardInteractivePrompt], + responses: &[String], + password: Option<&str>, +) -> Result> { + let mut response_index = 0; + let mut answers = Vec::with_capacity(prompts.len()); + + for prompt in prompts { + if ssh::is_password_prompt(&prompt.prompt) { + if let Some(password) = password { + answers.push(password.to_string()); + } else { + let response = responses + .get(response_index) + .ok_or_else(|| anyhow!("SSH password response is missing"))?; + if response.trim().is_empty() { + return Err(anyhow!("SSH password response is empty")); + } + answers.push(response.clone()); + response_index += 1; + } + } else { + let response = responses + .get(response_index) + .ok_or_else(|| anyhow!("SSH MFA response is missing"))?; + if response.trim().is_empty() { + return Err(anyhow!("SSH MFA response is empty")); + } + answers.push(response.clone()); + response_index += 1; + } + } + + if response_index == responses.len() { + Ok(answers) + } else { + Err(anyhow!("SSH MFA response count does not match prompts")) + } +} + +impl SftpView { + pub(crate) fn receive_sftp_mfa_event( + &mut self, + event: SftpMfaEvent, + window: &mut Window, + cx: &mut Context, + ) { + if self.close_state.is_closing() || !self.sftp_mfa_target_is_current(event.target) { + return; + } + if self.sftp_mfa_inputs.is_some() { + self.pending_sftp_mfa_events.push_back(event); + return; + } + self.show_sftp_mfa_event(event, window, cx); + } + + fn show_next_sftp_mfa_event(&mut self, window: &mut Window, cx: &mut Context) { + while self.sftp_mfa_inputs.is_none() { + let Some(event) = self.pending_sftp_mfa_events.pop_front() else { + return; + }; + if self.close_state.is_closing() || !self.sftp_mfa_target_is_current(event.target) { + continue; + } + self.show_sftp_mfa_event(event, window, cx); + } + } + + fn show_sftp_mfa_event( + &mut self, + event: SftpMfaEvent, + window: &mut Window, + cx: &mut Context, + ) { + let target = event.target; + let inputs = event + .prompts + .iter() + .map(|prompt| { + cx.new(|cx| { + let placeholder = if prompt.prompt.trim().is_empty() { + t!("Mfa.response_placeholder").to_string() + } else { + prompt.prompt.clone() + }; + let state = InputState::new(window, cx).placeholder(placeholder); + if prompt.echo { + state + } else { + state.masked(true) + } + }) + }) + .collect::>(); + + let mut subscriptions = Vec::new(); + for input in &inputs { + subscriptions.push(cx.subscribe_in( + input, + window, + move |this, _, event: &InputEvent, window, cx| { + if !is_primary_enter(event) { + return; + } + let submitted = this.submit_sftp_mfa(target, cx); + finish_sftp_mfa_submission(submitted, window, cx); + }, + )); + } + + if let Some(input) = inputs.first() { + input.update(cx, |state, cx| state.focus(window, cx)); + } + self.sftp_mfa_inputs = Some(SftpMfaInputs { + target, + name: event.name, + instructions: event.instructions, + prompts: event.prompts, + inputs, + response_tx: Some(event.response_tx), + error: None, + _subscriptions: subscriptions, + }); + self.show_sftp_mfa_prompt(window, cx); + cx.notify(); + } + + fn show_sftp_mfa_prompt(&mut self, window: &mut Window, cx: &mut Context) { + let Some(inputs) = self.sftp_mfa_inputs.as_ref() else { + return; + }; + if self.close_state.is_closing() || !self.sftp_mfa_target_is_current(inputs.target) { + return; + } + + let target = inputs.target; + let name = inputs.name.clone(); + let instructions = inputs.instructions.clone(); + let prompts = inputs.prompts.clone(); + let input_states = inputs.inputs.clone(); + let error = inputs.error.clone(); + let view = cx.entity().downgrade(); + + window.open_dialog(cx, move |dialog, _window, cx| { + let mut content = v_flex().gap_3(); + if !instructions.trim().is_empty() { + content = content.child( + div() + .text_sm() + .text_color(cx.theme().muted_foreground) + .child(instructions.clone()), + ); + } + for (index, prompt) in prompts.iter().enumerate() { + let input = input_states[index].clone(); + content = content.child(v_flex().gap_1().child(if prompt.echo { + Input::new(&input) + } else { + Input::new(&input).mask_toggle() + })); + } + if let Some(error) = error.clone() { + content = content.child(div().text_sm().text_color(cx.theme().danger).child(error)); + } + + dialog + .title(if name.trim().is_empty() { + t!("Mfa.title").to_string() + } else { + name.clone() + }) + .w(px(460.)) + .child(content) + .footer(sftp_mfa_prompt_footer(target, view.clone())) + .overlay_closable(false) + .close_button(false) + .keyboard(false) + }); + } + + pub(crate) fn submit_sftp_mfa( + &mut self, + target: SftpMfaTarget, + cx: &mut Context, + ) -> bool { + if !self.sftp_mfa_target_is_current(target) { + return false; + } + let Some(inputs) = self.sftp_mfa_inputs.as_mut() else { + return false; + }; + if inputs.target != target { + return false; + } + let responses = inputs + .inputs + .iter() + .map(|input| input.read(cx).text().to_string()) + .collect::>(); + if responses.iter().any(|response| response.trim().is_empty()) { + inputs.error = Some(t!("Mfa.response_required").to_string()); + return false; + } + + let Some(response_tx) = inputs.response_tx.take() else { + return false; + }; + let _ = response_tx.send(responses); + self.sftp_mfa_inputs = None; + cx.notify(); + true + } + + pub(crate) fn cancel_sftp_mfa(&mut self, target: SftpMfaTarget, cx: &mut Context) { + let Some(inputs) = self.sftp_mfa_inputs.as_ref() else { + return; + }; + if inputs.target != target { + return; + } + self.sftp_mfa_inputs = None; + cx.notify(); + } + + pub(crate) fn clear_sftp_mfa_for_main(&mut self) { + if self + .sftp_mfa_inputs + .as_ref() + .is_some_and(|inputs| matches!(inputs.target, SftpMfaTarget::Main { .. })) + { + self.sftp_mfa_inputs = None; + } + self.pending_sftp_mfa_events + .retain(|event| !matches!(event.target, SftpMfaTarget::Main { .. })); + } + + pub(crate) fn clear_sftp_mfa_for_left(&mut self) { + if self + .sftp_mfa_inputs + .as_ref() + .is_some_and(|inputs| matches!(inputs.target, SftpMfaTarget::Left { .. })) + { + self.sftp_mfa_inputs = None; + } + self.pending_sftp_mfa_events + .retain(|event| !matches!(event.target, SftpMfaTarget::Left { .. })); + } + + fn sftp_mfa_target_is_current(&self, target: SftpMfaTarget) -> bool { + match target { + SftpMfaTarget::Main { generation } => self.is_current_connection_generation(generation), + SftpMfaTarget::Left { + connection_id, + generation, + } => { + self.left_remote_id() == Some(connection_id) + && self.is_current_left_connection_generation(generation) + } + } + } +} + +fn sftp_mfa_prompt_footer(target: SftpMfaTarget, view: WeakEntity) -> DialogFooter { + let cancel_view = view.clone(); + let submit_view = view; + DialogFooter::new().children(vec![ + Button::new("sftp-mfa-cancel") + .label(t!("Common.cancel").to_string()) + .on_click(move |_, window, cx| { + window.close_dialog(cx); + let _ = cancel_view.update(cx, |this, cx| { + this.cancel_sftp_mfa(target, cx); + cx.defer_in(window, |this, window, cx| { + this.show_next_sftp_mfa_event(window, cx); + }); + }); + }) + .into_any_element(), + Button::new("sftp-mfa-submit") + .label(t!("Mfa.submit").to_string()) + .primary() + .on_click(move |_, window, cx| { + let _ = submit_view.update(cx, |this, cx| { + let submitted = this.submit_sftp_mfa(target, cx); + finish_sftp_mfa_submission(submitted, window, cx); + }); + }) + .into_any_element(), + ]) +} + +fn finish_sftp_mfa_submission(submitted: bool, window: &mut Window, cx: &mut Context) { + window.close_dialog(cx); + cx.defer_in(window, move |this, window, cx| { + if submitted { + this.show_next_sftp_mfa_event(window, cx); + } else { + this.show_sftp_mfa_prompt(window, cx); + } + }); +} + +fn is_primary_enter(event: &InputEvent) -> bool { + matches!( + event, + InputEvent::PressEnter { + secondary: false, + .. + } + ) +} + +pub(crate) fn password_from_ssh_auth(auth: &SshAuth) -> Option { + match auth { + SshAuth::Password(password) => Some(password.clone()), + SshAuth::Chain(steps) => steps.iter().find_map(password_from_ssh_auth), + _ => None, + } +} + +pub(crate) fn jump_password(config: &SshConnectConfig) -> Option { + config + .jump_server + .as_ref() + .and_then(|jump| password_from_ssh_auth(&jump.auth)) +} + +#[cfg(test)] +mod tests { + use super::{ + SftpMfaEvent, SftpMfaPrompt, SftpMfaResponder, SftpMfaTarget, + answers_from_manual_responses, manual_prompts, + }; + use otp::OtpSecret; + use ssh::{ + KeyboardInteractivePrompt, KeyboardInteractiveRequest, KeyboardInteractiveResponder, + KeyboardInteractiveTarget, + }; + use std::sync::Arc; + + fn request(prompts: &[&str]) -> KeyboardInteractiveRequest { + KeyboardInteractiveRequest { + target: KeyboardInteractiveTarget::TargetServer, + name: "MFA".to_string(), + instructions: String::new(), + prompts: prompts + .iter() + .map(|prompt| KeyboardInteractivePrompt { + prompt: (*prompt).to_string(), + echo: false, + }) + .collect(), + } + } + + #[test] + fn saved_password_is_not_prompted_again() { + let request = request(&["Password: ", "Verification code: "]); + let prompts = manual_prompts(&request.prompts, Some("saved-password")); + + assert_eq!( + prompts, + vec![SftpMfaPrompt { + prompt: "Verification code: ".to_string(), + echo: false, + }] + ); + } + + #[test] + fn manual_responses_are_merged_back_in_server_order() { + let request = request(&["Verification code: ", "Password: ", "Answer: "]); + let answers = answers_from_manual_responses( + &request.prompts, + &["123456".to_string(), "blue".to_string()], + Some("saved-password"), + ) + .expect("responses should map"); + + assert_eq!( + answers, + vec![ + "123456".to_string(), + "saved-password".to_string(), + "blue".to_string(), + ] + ); + } + + #[test] + fn missing_password_becomes_a_manual_prompt() { + let request = request(&["Password: "]); + let prompts = manual_prompts(&request.prompts, None); + + assert_eq!( + prompts, + vec![SftpMfaPrompt { + prompt: "Password: ".to_string(), + echo: false, + }] + ); + } + + #[tokio::test] + async fn responder_bridges_manual_challenge_and_saved_password() { + let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel(); + let responder = Arc::new(SftpMfaResponder::new( + SftpMfaTarget::Main { generation: 7 }, + event_tx, + None, + Some("saved-password".to_string()), + None, + )); + let request = request(&["Verification code: ", "Password: "]); + let responding = { + let responder = responder.clone(); + tokio::spawn(async move { responder.respond(request).await }) + }; + + let SftpMfaEvent { + target, + prompts, + response_tx, + .. + } = event_rx.recv().await.expect("prompt event"); + assert_eq!(target, SftpMfaTarget::Main { generation: 7 }); + assert_eq!( + prompts, + vec![SftpMfaPrompt { + prompt: "Verification code: ".to_string(), + echo: false, + }] + ); + response_tx + .send(vec!["123456".to_string()]) + .expect("response receiver should be live"); + + assert_eq!( + responding.await.expect("responder task").expect("answers"), + vec!["123456".to_string(), "saved-password".to_string()] + ); + } + + #[tokio::test] + async fn configured_otp_is_answered_without_opening_a_prompt() { + let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel(); + let otp = OtpSecret::from_base32("JBSWY3DPEHPK3PXP").expect("valid test OTP secret"); + let responder = SftpMfaResponder::new( + SftpMfaTarget::Main { generation: 9 }, + event_tx, + None, + Some("saved-password".to_string()), + Some(otp), + ); + + let answers = responder + .respond(request(&["Verification code: ", "Password: "])) + .await + .expect("configured OTP should be answered automatically"); + + assert_eq!(answers.len(), 2); + assert_eq!(answers[0].len(), 6); + assert!( + answers[0] + .chars() + .all(|character| character.is_ascii_digit()) + ); + assert_eq!(answers[1], "saved-password"); + assert!( + event_rx.try_recv().is_err(), + "自动 TOTP 不应生成手工输入弹窗事件" + ); + } +} diff --git a/crates/ssh/Cargo.toml b/crates/ssh/Cargo.toml index b3ee5756e..6fa73a5f8 100644 --- a/crates/ssh/Cargo.toml +++ b/crates/ssh/Cargo.toml @@ -22,6 +22,7 @@ sha1 = "0.10" # SSH and SFTP russh.workspace = true x11_forwarding.workspace = true +x11_component.workspace = true # Proxy support tokio-socks.workspace = true diff --git a/crates/ssh/src/connection_key.rs b/crates/ssh/src/connection_key.rs index 778da0e05..6b52fffc0 100644 --- a/crates/ssh/src/connection_key.rs +++ b/crates/ssh/src/connection_key.rs @@ -171,6 +171,7 @@ pub struct ConnectionKey { keepalive_max: Option, keyboard_interactive: Option, x11_forwarding: bool, + x11_resolution_generation: u64, allow_legacy_algorithms: bool, forward_agent: bool, } @@ -229,6 +230,11 @@ impl ConnectionKey { keepalive_max: config.keepalive_max, keyboard_interactive, x11_forwarding: config.x11_forwarding, + x11_resolution_generation: if config.x11_forwarding { + x11_component::resolution_generation() + } else { + 0 + }, allow_legacy_algorithms: config.allow_legacy_algorithms, forward_agent: config.forward_agent, }) @@ -283,6 +289,7 @@ impl fmt::Debug for ConnectionKey { &self.keyboard_interactive.is_some(), ) .field("x11_forwarding", &self.x11_forwarding) + .field("x11_resolution_generation", &self.x11_resolution_generation) .field("allow_legacy_algorithms", &self.allow_legacy_algorithms) .finish() } @@ -391,7 +398,7 @@ impl AuthenticationKey { SshAuth::Chain(steps) => Self::Chain( steps .iter() - .map(|step| Self::new(step, credential.clone())) + .map(|step| Self::new(step, credential)) .collect(), ), } @@ -559,6 +566,12 @@ mod tests { let mut changed_x11 = base_config(); changed_x11.x11_forwarding = true; assert_ne!(baseline_key, key(&changed_x11, target_credentials())); + let before_restart = key(&changed_x11, target_credentials()); + x11_component::set_configured_mode(x11_component::X11ServerMode::External); + let after_mode_change = key(&changed_x11, target_credentials()); + assert_ne!(before_restart, after_mode_change); + x11_component::set_configured_mode(x11_component::X11ServerMode::Embedded); + assert_ne!(after_mode_change, key(&changed_x11, target_credentials())); let mut changed_legacy_algorithms = base_config(); changed_legacy_algorithms.allow_legacy_algorithms = true; diff --git a/crates/ssh/src/lib.rs b/crates/ssh/src/lib.rs index 03db2ab6e..e6d974ce6 100644 --- a/crates/ssh/src/lib.rs +++ b/crates/ssh/src/lib.rs @@ -43,9 +43,11 @@ pub use ssh::{ KeyboardInteractiveResponder, KeyboardInteractiveTarget, LocalPortForwardActivity, LocalPortForwardConfig, LocalPortForwardTunnel, ProxyConnectConfig, ProxyType, PtyConfig, RusshChannel, RusshClient, SshAuth, SshChannel, SshClient, SshConnectConfig, - authenticate_session, authenticate_session_with_fallbacks, authenticate_with_strategy, - authenticate_with_strategy_for_target, build_client_preferred_algorithms, - build_client_preferred_algorithms_with_legacy, connect_via_proxy, defaults, - expand_auto_publickey_auth, start_local_port_forward, start_local_port_forward_with_config, + X11RequestRejected, authenticate_session, authenticate_session_with_fallbacks, + authenticate_with_strategy, authenticate_with_strategy_for_target, + build_client_preferred_algorithms, build_client_preferred_algorithms_with_legacy, + connect_via_proxy, defaults, expand_auto_publickey_auth, start_local_port_forward, + start_local_port_forward_with_config, }; -pub use x11_forwarding::{ForwardRequest, X11Proxy}; +pub use x11_component::X11ForwardingStatus; +pub use x11_forwarding::{ForwardRequest, MagicCookie, ServerEndpoint, X11Proxy}; diff --git a/crates/ssh/src/session_manager.rs b/crates/ssh/src/session_manager.rs index 2a0278130..139c4a083 100644 --- a/crates/ssh/src/session_manager.rs +++ b/crates/ssh/src/session_manager.rs @@ -15,6 +15,9 @@ const PING_THROTTLE: Duration = Duration::from_secs(5); #[async_trait] trait SharedSessionClient: Send + Sync { fn is_connected(&self) -> bool; + fn x11_status(&self) -> Option { + None + } async fn ping(&self) -> Result<()>; async fn disconnect(&mut self) -> Result<()>; } @@ -104,6 +107,8 @@ struct SessionPool { config: RwLock, connector: K, state: Mutex>, + /// 最近一次已解析的 transport X11 状态,供锁忙或重连窗口无阻塞读取。 + last_x11_status: RwLock>, shutdown: CancellationToken, /// Serializes successful client checkout/publication with the synchronous /// shutdown gate. Once `request_shutdown()` returns, no connection can @@ -129,6 +134,7 @@ where }), connector, state: Mutex::new(SessionState::default()), + last_x11_status: RwLock::new(None), shutdown: CancellationToken::new(), shutdown_publication: RwLock::new(()), } @@ -138,6 +144,36 @@ where self.config_snapshot().0 } + fn x11_status(&self) -> Option { + let client = match self.state.try_lock() { + Ok(state) => state.client.clone(), + Err(_) => return self.cached_x11_status(), + }; + let Some(client) = client else { + return self.cached_x11_status(); + }; + let status = match client.try_lock() { + Ok(client) => client.x11_status(), + Err(_) => return self.cached_x11_status(), + }; + self.cache_x11_status(status.clone()); + status + } + + fn cached_x11_status(&self) -> Option { + self.last_x11_status + .read() + .unwrap_or_else(|error| error.into_inner()) + .clone() + } + + fn cache_x11_status(&self, status: Option) { + *self + .last_x11_status + .write() + .unwrap_or_else(|error| error.into_inner()) = status; + } + fn replace_config(&self, config: SshConnectConfig) { let mut current = self.config.write().unwrap_or_else(|err| err.into_inner()); current.value = config; @@ -287,6 +323,7 @@ where } return match result { Ok(new_client) => { + self.cache_x11_status(new_client.x11_status()); let arc = Arc::new(Mutex::new(new_client)); state.connecting = None; state.client = Some(arc.clone()); @@ -388,6 +425,7 @@ where state.client.take() }; + self.cache_x11_status(None); if let Some(client) = client { client.lock().await.disconnect().await?; } @@ -405,6 +443,7 @@ where .write() .unwrap_or_else(|error| error.into_inner()); self.shutdown.cancel(); + self.cache_x11_status(None); } /// Permanently close this manager and wait for both its cached client and @@ -462,6 +501,10 @@ impl SharedSessionClient for RusshClient { SshClient::is_connected(self) } + fn x11_status(&self) -> Option { + SshClient::x11_status(self) + } + async fn ping(&self) -> Result<()> { SshClient::ping(self).await } @@ -505,6 +548,11 @@ impl SshSessionManager { self.inner.client().await } + /// 无副作用读取已缓存连接的 X11 状态;未连接或连接正被使用时返回 None。 + pub fn x11_status(&self) -> Option { + self.inner.x11_status() + } + pub async fn open_channel(&self) -> Result { let client = self.client().await?; let mut guard = client.lock().await; @@ -640,6 +688,13 @@ mod tests { self.connected.load(Ordering::SeqCst) } + fn x11_status(&self) -> Option { + self.is_connected() + .then(|| crate::X11ForwardingStatus::External { + server: "fake X server".into(), + }) + } + async fn ping(&self) -> Result<()> { self.ping_count.fetch_add(1, Ordering::SeqCst); if self.ping_fails.load(Ordering::SeqCst) { @@ -911,6 +966,62 @@ mod tests { assert_eq!(connector.connect_count.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn cached_x11_status_never_connects_and_clears_on_disconnect() { + let connector = Arc::new(FakeConnector::default()); + let pool = SessionPool::new(test_config(), connector.clone()); + + assert_eq!(pool.x11_status(), None); + assert_eq!(connector.connect_count.load(Ordering::SeqCst), 0); + let _client = pool.client().await.expect("client should connect"); + assert_eq!( + pool.x11_status(), + Some(crate::X11ForwardingStatus::External { + server: "fake X server".into(), + }) + ); + assert_eq!(connector.connect_count.load(Ordering::SeqCst), 1); + + pool.disconnect().await.expect("disconnect should succeed"); + assert_eq!(pool.x11_status(), None); + assert_eq!(connector.connect_count.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn x11_status_uses_last_snapshot_when_locks_are_busy_or_client_is_missing() { + let connector = Arc::new(FakeConnector::default()); + let pool = SessionPool::new(test_config(), connector.clone()); + let expected = Some(crate::X11ForwardingStatus::External { + server: "fake X server".into(), + }); + let client = pool.client().await.expect("client should connect"); + assert_eq!(pool.x11_status(), expected); + + let state = pool.state.lock().await; + assert_eq!( + pool.x11_status(), + expected, + "state 锁忙时必须返回最后一次成功读取的快照" + ); + drop(state); + + let client_guard = client.lock().await; + assert_eq!( + pool.x11_status(), + expected, + "client 锁忙时不能把已有状态闪成 None" + ); + drop(client_guard); + + assert!(pool.invalidate_client(&client).await); + assert_eq!( + pool.x11_status(), + expected, + "重连前的无 client 窗口应保留最后快照" + ); + assert_eq!(connector.connect_count.load(Ordering::SeqCst), 1); + } + #[tokio::test] async fn disconnect_clears_cached_client() { let connector = Arc::new(FakeConnector::default()); diff --git a/crates/ssh/src/ssh.rs b/crates/ssh/src/ssh.rs index b881fe606..175c7d0c1 100644 --- a/crates/ssh/src/ssh.rs +++ b/crates/ssh/src/ssh.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; +use std::collections::VecDeque; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::{Arc, Mutex as StdMutex, RwLock}; @@ -11,7 +12,8 @@ use russh::*; use rust_i18n::t; use tokio::io::{AsyncRead, AsyncWrite, copy_bidirectional}; use tokio::net::{TcpListener, TcpStream}; -use tokio::sync::{Mutex, oneshot}; +use tokio::sync::{Mutex, Semaphore, oneshot}; +use x11_component::{X11ForwardingStatus, X11Resolution}; use x11_forwarding::{ForwardRequest, X11Proxy, X11ProxyHandle}; use crate::connection_error::{add_jump_channel_rejected_hint, add_private_key_load_hint}; @@ -466,6 +468,21 @@ impl Default for PtyConfig { } } +const X11_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_X11_CHANNELS: usize = 32; + +/// 远端明确以 CHANNEL_FAILURE 拒绝 `x11-req`,区别于本地发送失败和等待超时。 +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct X11RequestRejected; + +impl std::fmt::Display for X11RequestRejected { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("remote server rejected x11-req") + } +} + +impl std::error::Error for X11RequestRejected {} + pub enum ChannelEvent { Data(Vec), ExtendedData { @@ -537,6 +554,11 @@ pub trait SshClient: Send + Sync { None } + /// 当前连接的 X11 来源或停用原因。 + fn x11_status(&self) -> Option { + None + } + /// 连接是否启用了 ForwardAgent(`auth-agent-req@openssh.com`)。 /// 默认 `false`;具体实现应返回连接配置中的实际值。 fn forward_agent(&self) -> bool { @@ -546,6 +568,7 @@ pub trait SshClient: Send + Sync { struct RusshHandler { x11_handle: Option, + x11_channel_permits: Arc, identity: HostKeyIdentity, host_key_verifier: HostKeyVerifier, remote_forward_target: Arc>>, @@ -566,6 +589,7 @@ impl RusshHandler { ) -> Self { Self { x11_handle, + x11_channel_permits: Arc::new(Semaphore::new(MAX_X11_CHANNELS)), identity, host_key_verifier, remote_forward_target, @@ -722,15 +746,28 @@ impl client::Handler for RusshHandler { return Ok(()); }; - // russh 0.62 起,服务端主动打开的通道必须由回调显式确认。 - // 仅在本连接确实启用了 X11 转发时接受,避免先确认再立即关闭。 - reply.accept().await; + // 先非阻塞获取许可,避免回连洪峰无限创建任务或卡住其它通道回调。 + let Ok(permit) = self.x11_channel_permits.clone().try_acquire_owned() else { + tracing::warn!( + target: "ssh.x11", + originator_address, + originator_port, + limit = MAX_X11_CHANNELS, + "X11 回连通道达到并发上限,拒绝新通道" + ); + reply + .reject(ChannelOpenFailure::AdministrativelyProhibited) + .await; + return Ok(()); + }; + reply.accept().await; let originator = Some(( originator_address.to_string(), u16::try_from(originator_port).unwrap_or(0), )); tokio::spawn(async move { + let _permit = permit; x11_handle .run_channel(channel.into_stream(), originator) .await; @@ -938,6 +975,8 @@ pub struct RusshClient { _jump_session: Option>, /// 本机 X11 转发管理器(仅在配置启用且本机 X server 可用时存在)。 x11_proxy: Option, + /// transport 建连时解析出的本机 X server 状态;各终端会话的请求结果不写入此处。 + x11_status: X11ForwardingStatus, remote_forward_target: Arc>>, /// 连接是否启用了 ForwardAgent(`auth-agent-req@openssh.com`)。 /// @@ -2701,11 +2740,19 @@ impl SshClient for RusshClient { .context("add SSH agent identities")?; } - // X11 转发依赖本机 X server(DISPLAY/XAUTHORITY),解析失败仅降级不阻断连接。 - let x11_proxy = if config.x11_forwarding { + // 仅替换本机 X server 的来源,x11-req 与 cookie 委托仍走既有链路。 + let X11Resolution { + proxy: x11_proxy, + status: x11_status, + } = if config.x11_forwarding { detect_x11_proxy().await } else { - None + X11Resolution { + proxy: None, + status: X11ForwardingStatus::Disabled { + reason: "用户未启用 X11 转发".into(), + }, + } }; let x11_handle = x11_proxy.as_ref().map(|proxy| proxy.handle()); let host_key_verifier = config.host_key_verifier.clone(); @@ -2778,6 +2825,7 @@ impl SshClient for RusshClient { session, _jump_session: None, x11_proxy: x11_proxy.clone(), + x11_status, remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, bastion_direct, @@ -2878,6 +2926,7 @@ impl SshClient for RusshClient { session, _jump_session: Some(jump_session), x11_proxy: x11_proxy.clone(), + x11_status, remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, bastion_direct, @@ -2920,6 +2969,7 @@ impl SshClient for RusshClient { session, _jump_session: None, x11_proxy: x11_proxy.clone(), + x11_status, remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, bastion_direct, @@ -2955,6 +3005,7 @@ impl SshClient for RusshClient { session, _jump_session: None, x11_proxy: x11_proxy.clone(), + x11_status, remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, bastion_direct, @@ -2972,7 +3023,10 @@ impl SshClient for RusshClient { async fn open_channel(&mut self) -> Result { let channel = self.session.channel_open_session().await?; - Ok(RusshChannel { channel }) + Ok(RusshChannel { + channel, + pending: VecDeque::new(), + }) } async fn disconnect(&mut self) -> Result<()> { @@ -3002,6 +3056,10 @@ impl SshClient for RusshClient { self.x11_proxy.as_ref() } + fn x11_status(&self) -> Option { + Some(self.x11_status.clone()) + } + fn forward_agent(&self) -> bool { self.forward_agent } @@ -3018,34 +3076,22 @@ impl RusshClient { } } -/// 解析本机 X server 环境,失败仅告警并返回 None(X11 转发静默停用)。 -async fn detect_x11_proxy() -> Option { - match tokio::task::spawn_blocking(x11_forwarding::detect_local_server).await { - Ok(Ok(proxy)) => { - tracing::info!( - target: "ssh.x11", - endpoint = ?proxy.endpoint(), - "本机 X server 可用,X11 转发已启用" - ); - Some(proxy) +/// 按设置解析 X server;失败作为可见状态返回,不阻断 SSH 连接。 +async fn detect_x11_proxy() -> X11Resolution { + let mode = x11_component::configured_mode(); + let resolution = x11_component::resolve_server(mode).await; + match &resolution.status { + X11ForwardingStatus::Embedded { version } => { + tracing::info!(target: "ssh.x11", %version, "内置 yserver 已就绪"); } - Ok(Err(error)) => { - tracing::warn!( - target: "ssh.x11", - error = %error, - "本机 X server 不可用,X11 转发停用" - ); - None + X11ForwardingStatus::External { server } => { + tracing::info!(target: "ssh.x11", %server, "本机 X server 已就绪"); } - Err(error) => { - tracing::warn!( - target: "ssh.x11", - error = %error, - "解析本机 X11 环境失败,X11 转发停用" - ); - None + X11ForwardingStatus::Disabled { reason } => { + tracing::warn!(target: "ssh.x11", %reason, "X11 转发已停用"); } } + resolution } fn normalize_disconnect_result( @@ -4284,8 +4330,361 @@ zsXyAAAAAAE= } } +#[cfg(test)] +mod x11_protocol_tests { + use std::future::Future; + use std::sync::{Arc, RwLock}; + use std::time::Duration; + + use russh::server::{Auth, Server as _}; + use tokio::net::TcpListener; + + use super::{ + Algorithm, ChannelEvent, ForwardRequest, HostKeyVerifier, PrivateKey, RusshChannel, + RusshClient, RusshHandler, SshAuth, SshChannel, SshClient, SshConnectConfig, X11Proxy, + X11RequestRejected, build_russh_client_config, + }; + use crate::{MagicCookie, ServerEndpoint}; + + #[derive(Clone, Copy)] + enum X11Reply { + RejectWithData, + CloseWithData, + Ignore, + } + + #[derive(Clone)] + struct X11TestServer { + reply: X11Reply, + server_handle_tx: Option>, + } + + impl russh::server::Server for X11TestServer { + type Handler = Self; + + fn new_client(&mut self, _: Option) -> Self::Handler { + self.clone() + } + } + + impl russh::server::Handler for X11TestServer { + type Error = anyhow::Error; + + async fn auth_password(&mut self, _: &str, _: &str) -> Result { + Ok(Auth::Accept) + } + + fn channel_open_session( + &mut self, + _channel: russh::Channel, + reply: russh::server::ChannelOpenHandle, + _session: &mut russh::server::Session, + ) -> impl Future> + Send { + let server_handle_tx = self.server_handle_tx.clone(); + async move { + if let Some(sender) = server_handle_tx { + let _ = sender.send(_session.handle()); + } + reply.accept().await; + Ok(()) + } + } + + fn x11_request( + &mut self, + channel: russh::ChannelId, + _single_connection: bool, + _x11_auth_protocol: &str, + _x11_auth_cookie: &str, + _x11_screen_number: u32, + session: &mut russh::server::Session, + ) -> impl Future> + Send { + let reply = self.reply; + async move { + match reply { + X11Reply::RejectWithData => { + session.data(channel, &b"before-reply"[..])?; + session.channel_failure(channel)?; + } + X11Reply::CloseWithData => { + session.data(channel, &b"before-close"[..])?; + session.close(channel)?; + } + X11Reply::Ignore => {} + } + Ok(()) + } + } + } + + async fn connected_channel( + reply: X11Reply, + ) -> ( + RusshClient, + RusshChannel, + tokio::task::JoinHandle>, + ) { + let socket = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let address = socket.local_addr().unwrap(); + let host_key = PrivateKey::random(&mut rand_010::rng(), Algorithm::Ed25519).unwrap(); + let config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + keys: vec![host_key], + ..Default::default() + }); + let server_task = tokio::spawn(async move { + let mut server = X11TestServer { + reply, + server_handle_tx: None, + }; + server.run_on_socket(config, &socket).await + }); + let mut client = RusshClient::connect(client_config(address)).await.unwrap(); + let channel = client.open_channel().await.unwrap(); + (client, channel, server_task) + } + + fn client_config(address: std::net::SocketAddr) -> SshConnectConfig { + SshConnectConfig { + host: address.ip().to_string(), + port: address.port(), + username: "tester".to_owned(), + auth: SshAuth::Password("password".to_owned()), + timeout: Some(Duration::from_secs(5)), + keepalive_interval: None, + keepalive_max: None, + jump_server: None, + proxy: None, + keyboard_interactive_responder: None, + host_key_verifier: HostKeyVerifier::insecure(), + x11_forwarding: false, + allow_legacy_algorithms: false, + forward_agent: false, + agent_identities: Vec::new(), + } + } + + fn forward_request() -> ForwardRequest { + X11Proxy::for_endpoint( + ServerEndpoint::Inet { + host: "127.0.0.1".to_owned(), + port: 6137, + }, + MagicCookie::generate(), + ) + .issue_request(false) + } + + #[tokio::test] + async fn channel_failure_rejects_request_and_preserves_prior_data() { + let (_client, mut channel, server_task) = connected_channel(X11Reply::RejectWithData).await; + + let result = channel.request_x11_forwarding(&forward_request()).await; + let event = channel.recv().await; + server_task.abort(); + + assert!( + result + .as_ref() + .is_err_and(|error| error.downcast_ref::().is_some()), + "CHANNEL_FAILURE 必须映射为可识别的远端拒绝" + ); + assert!(matches!( + event, + Some(ChannelEvent::Data(data)) if data == b"before-reply" + )); + } + + #[tokio::test] + async fn close_before_reply_is_not_swallowed() { + let (_client, mut channel, server_task) = connected_channel(X11Reply::CloseWithData).await; + + let result = channel.request_x11_forwarding(&forward_request()).await; + let data = channel.recv().await; + let close = channel.recv().await; + server_task.abort(); + + assert!(result.is_err(), "响应前关闭通道不能报告为请求成功"); + assert!( + result + .as_ref() + .is_err_and(|error| error.downcast_ref::().is_none()), + "通道关闭属于本地协议错误,不能伪装成远端拒绝" + ); + assert!(matches!( + data, + Some(ChannelEvent::Data(data)) if data == b"before-close" + )); + assert!(matches!(close, Some(ChannelEvent::Close))); + } + + #[tokio::test] + async fn missing_channel_reply_times_out() { + let (_client, mut channel, server_task) = connected_channel(X11Reply::Ignore).await; + + tokio::time::pause(); + let result = channel.request_x11_forwarding(&forward_request()).await; + server_task.abort(); + tokio::time::resume(); + + assert!(result.is_err(), "没有 CHANNEL_SUCCESS/FAILURE 必须有界超时"); + } + + async fn x11_server_with_handle() -> ( + std::net::SocketAddr, + tokio::sync::mpsc::UnboundedReceiver, + tokio::task::JoinHandle>, + ) { + let socket = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let address = socket.local_addr().unwrap(); + let host_key = PrivateKey::random(&mut rand_010::rng(), Algorithm::Ed25519).unwrap(); + let config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + keys: vec![host_key], + ..Default::default() + }); + let (server_handle_tx, server_handle_rx) = tokio::sync::mpsc::unbounded_channel(); + let server_task = tokio::spawn(async move { + let mut server = X11TestServer { + reply: X11Reply::Ignore, + server_handle_tx: Some(server_handle_tx), + }; + server.run_on_socket(config, &socket).await + }); + (address, server_handle_rx, server_task) + } + + async fn client_with_x11(address: std::net::SocketAddr) -> russh::client::Handle { + let config = client_config(address); + let identity = config.target_host_key_identity(); + let proxy = X11Proxy::for_endpoint( + ServerEndpoint::Inet { + host: "127.0.0.1".to_owned(), + port: 1, + }, + MagicCookie::generate(), + ); + let handler = RusshHandler::new( + identity.clone(), + HostKeyVerifier::insecure(), + Some(proxy.handle()), + Arc::new(RwLock::new(None)), + false, + ); + let russh_config = build_russh_client_config(&config, &identity).unwrap(); + let mut session = russh::client::connect(russh_config, address, handler) + .await + .unwrap(); + assert!( + session + .authenticate_password("tester", "password") + .await + .unwrap() + .success() + ); + session + } + + #[tokio::test] + async fn x11_accept_is_bounded_and_permits_are_released() { + const TEST_LIMIT: usize = 32; + + let (address, mut server_handle_rx, server_task) = x11_server_with_handle().await; + let session = client_with_x11(address).await; + let _session_channel = session.channel_open_session().await.unwrap(); + let server_handle = server_handle_rx.recv().await.unwrap(); + let mut channels = Vec::new(); + for _ in 0..TEST_LIMIT { + let channel = server_handle + .channel_open_x11("127.0.0.1", 6000) + .await + .unwrap(); + channels.push(channel); + } + + let overflow = server_handle.channel_open_x11("127.0.0.1", 6000).await; + assert!(overflow.is_err(), "第 33 条回连必须因并发上限被拒绝"); + let normal_channel = + tokio::time::timeout(Duration::from_secs(1), session.channel_open_session()) + .await + .expect("X11 达到上限不能卡住普通 session 通道") + .expect("普通 session 通道不应受 X11 许可上限影响"); + drop(normal_channel); + channels.pop().unwrap().close().await.unwrap(); + let reopened = tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Ok(channel) = server_handle.channel_open_x11("127.0.0.1", 6000).await { + break channel; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + server_task.abort(); + + assert!(reopened.is_ok(), "通道结束后必须释放许可并允许新回连"); + } +} + pub struct RusshChannel { channel: Channel, + /// 等待 x11-req 响应期间收到的普通通道事件,按原顺序留给 recv。 + pending: VecDeque, +} + +impl RusshChannel { + async fn wait_for_x11_reply(&mut self) -> Result<()> { + loop { + let Some(message) = self.channel.wait().await else { + anyhow::bail!("SSH channel ended before the x11-req response"); + }; + match message { + ChannelMsg::Success => return Ok(()), + ChannelMsg::Failure => return Err(anyhow::Error::new(X11RequestRejected)), + ChannelMsg::Close => { + self.pending.push_back(ChannelMsg::Close); + anyhow::bail!("SSH channel closed before the x11-req response"); + } + ChannelMsg::Data { .. } + | ChannelMsg::ExtendedData { .. } + | ChannelMsg::Eof + | ChannelMsg::ExitStatus { .. } + | ChannelMsg::ExitSignal { .. } => self.pending.push_back(message), + _ => {} + } + } + } + + async fn next_message(&mut self) -> Option { + match self.pending.pop_front() { + Some(message) => Some(message), + None => self.channel.wait().await, + } + } +} + +fn channel_event(message: ChannelMsg) -> Option { + match message { + ChannelMsg::Data { data } => Some(ChannelEvent::Data(data.to_vec())), + ChannelMsg::ExtendedData { data, ext } => Some(ChannelEvent::ExtendedData { + ext, + data: data.to_vec(), + }), + ChannelMsg::Eof => Some(ChannelEvent::Eof), + ChannelMsg::ExitStatus { exit_status } => Some(ChannelEvent::ExitStatus(exit_status)), + ChannelMsg::ExitSignal { + signal_name, + error_message, + .. + } => Some(ChannelEvent::ExitSignal { + signal_name: format!("{:?}", signal_name), + error_message, + }), + ChannelMsg::Close => Some(ChannelEvent::Close), + _ => None, + } } #[async_trait] @@ -4325,7 +4724,9 @@ impl SshChannel for RusshChannel { request.screen, ) .await?; - Ok(()) + tokio::time::timeout(X11_REQUEST_TIMEOUT, self.wait_for_x11_reply()) + .await + .map_err(|_| anyhow::anyhow!("timed out waiting for the x11-req response"))? } async fn request_agent_forwarding(&mut self) -> Result<()> { @@ -4349,26 +4750,12 @@ impl SshChannel for RusshChannel { } async fn recv(&mut self) -> Option { - let msg = self.channel.wait().await?; - Some(match msg { - ChannelMsg::Data { data } => ChannelEvent::Data(data.to_vec()), - ChannelMsg::ExtendedData { data, ext } => ChannelEvent::ExtendedData { - ext, - data: data.to_vec(), - }, - ChannelMsg::Eof => ChannelEvent::Eof, - ChannelMsg::ExitStatus { exit_status } => ChannelEvent::ExitStatus(exit_status), - ChannelMsg::ExitSignal { - signal_name, - error_message, - .. - } => ChannelEvent::ExitSignal { - signal_name: format!("{:?}", signal_name), - error_message, - }, - ChannelMsg::Close => ChannelEvent::Close, - _ => return self.recv().await, - }) + loop { + let message = self.next_message().await?; + if let Some(event) = channel_event(message) { + return Some(event); + } + } } async fn eof(&mut self) -> Result<()> { diff --git a/crates/ssh_form/Cargo.toml b/crates/ssh_form/Cargo.toml index c515f7778..dabb36d5c 100644 --- a/crates/ssh_form/Cargo.toml +++ b/crates/ssh_form/Cargo.toml @@ -22,6 +22,7 @@ terminal = { workspace = true } tokio = { workspace = true } tool_runtime = { workspace = true } tracing = { workspace = true } +x11_component = { workspace = true } [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } diff --git a/crates/ssh_form/locales/ssh_form.yml b/crates/ssh_form/locales/ssh_form.yml index b3bfa4c56..972f90b10 100644 --- a/crates/ssh_form/locales/ssh_form.yml +++ b/crates/ssh_form/locales/ssh_form.yml @@ -253,6 +253,14 @@ SSH: en: Key Path zh-CN: 密钥路径 zh-HK: 密鑰路徑 + key_path_select_file: + en: Select a local private key file + zh-CN: 选择本地私钥文件 + zh-HK: 選擇本機私鑰檔案 + username_missing_in_keychain: + en: This keychain entry has no username. Fill it in here. + zh-CN: 该钥匙串条目没有用户名,请在这里填写 + zh-HK: 該鑰匙圈條目沒有使用者名稱,請在這裡填寫 key_path_placeholder: en: Enter private key path zh-CN: 请输入私钥路径 @@ -772,6 +780,62 @@ SSH: en: Forward remote X11 graphical applications to the local X server. macOS requires XQuartz to be installed and running. Applies to new terminal sessions. zh-CN: 将远端 X11 图形应用转发到本机 X server。macOS 需要安装并启动 XQuartz。对新开的终端会话生效。 zh-HK: 將遠端 X11 圖形應用轉發到本機 X server。macOS 需要安裝並啟動 XQuartz。對新開的終端工作階段生效。 + x11_status_external: + en: "X11 forwarding: local %{server}" + zh-CN: "X11 转发:本机 %{server}" + zh-HK: "X11 轉發:本機 %{server}" + x11_status_embedded: + en: "X11 forwarding: built-in yserver %{version} (Vulkan)" + zh-CN: "X11 转发:内置 yserver %{version}(Vulkan)" + zh-HK: "X11 轉發:內置 yserver %{version}(Vulkan)" + x11_status_disabled: + en: "X11 forwarding: disabled (%{reason})" + zh-CN: "X11 转发:已停用(%{reason})" + zh-HK: "X11 轉發:已停用(%{reason})" + x11_remote_channel_unavailable: + en: the SSH server did not open an X11 forwarding channel + zh-CN: SSH 服务端未建立 X11 转发通道 + zh-HK: SSH 伺服器未建立 X11 轉發通道 + x11_remote_forwarding_disabled_checklist: + en: Check remote sshd_config for X11Forwarding yes, install xauth, then reconnect. + zh-CN: 请检查远端 sshd_config 的 X11Forwarding yes、安装 xauth,然后重新连接。 + zh-HK: 請檢查遠端 sshd_config 的 X11Forwarding yes、安裝 xauth,然後重新連線。 + x11_remote_display_restarted: + en: If the remote display service was restarted, close old X11 windows and reconnect. + zh-CN: 若远程显示服务已重启,请关闭旧 X11 窗口并重新连接。 + zh-HK: 若遠端顯示服務已重新啟動,請關閉舊 X11 視窗並重新連線。 + x11_untrusted_ssh_x_security: + en: "Untrusted ssh -X is limited by the X11 SECURITY timeout; use trusted ssh -Y when required." + zh-CN: "untrusted ssh -X 会受 X11 SECURITY 超时限制;需要可信转发时请使用 ssh -Y。" + zh-HK: "untrusted ssh -X 會受 X11 SECURITY 逾時限制;需要可信轉發時請使用 ssh -Y。" + x11_macos_xquartz_guidance: + en: "On macOS, install and start XQuartz for External mode; ensure DISPLAY authorization is ready." + zh-CN: "macOS 使用 External 时需安装并启动 XQuartz,并确保 DISPLAY 授权就绪。" + zh-HK: "macOS 使用 External 時需安裝並啟動 XQuartz,並確保 DISPLAY 授權就緒。" + x11_switch_external: + en: Switch to external X server + zh-CN: 切换到外部 X server + zh-HK: 切換至外部 X server + x11_switching_external: + en: External mode saved. Detecting the local X server… + zh-CN: 已保存 External 模式,正在重新探测本机 X server… + zh-HK: 已儲存 External 模式,正在重新偵測本機 X server… + x11_channel_open_failed: + en: "Could not open a temporary SSH channel for the X11 request: %{error}. SSH itself is connected." + zh-CN: "无法为 X11 请求打开临时 SSH 通道:%{error}。SSH 本身已连接。" + zh-HK: "無法為 X11 請求開啟臨時 SSH 通道:%{error}。SSH 本身已連線。" + x11_remote_request_rejected: + en: "The SSH server rejected x11-req: %{error}. Check sshd_config for X11Forwarding yes, X11DisplayOffset and xauth; this application uses trusted (-Y) forwarding." + zh-CN: "远端拒绝了 x11-req:%{error}。请检查 sshd_config 的 X11Forwarding yes、X11DisplayOffset 与 xauth;本应用使用 trusted (-Y) 转发。" + zh-HK: "遠端拒絕了 x11-req:%{error}。請檢查 sshd_config 的 X11Forwarding yes、X11DisplayOffset 與 xauth;本應用使用 trusted (-Y) 轉發。" + x11_request_failed: + en: "The X11 request was not completed (local send failure, response timeout or early channel close): %{error}. This was not a remote CHANNEL_FAILURE; SSH itself is connected." + zh-CN: "X11 请求未完成(本地发送失败、等待响应超时或通道提前关闭):%{error}。这不是远端 CHANNEL_FAILURE;SSH 本身已连接。" + zh-HK: "X11 請求未完成(本機傳送失敗、等待回應逾時或通道提前關閉):%{error}。這不是遠端 CHANNEL_FAILURE;SSH 本身已連線。" + x11_request_unavailable: + en: the X11 request did not complete; SSH itself is connected + zh-CN: X11 请求未完成;SSH 本身已连接 + zh-HK: X11 請求未完成;SSH 本身已連線 forward_agent: en: SSH Agent Forwarding zh-CN: SSH Agent 转发 diff --git a/crates/ssh_form/src/lib.rs b/crates/ssh_form/src/lib.rs index 1c6f33b90..24f3d72a1 100644 --- a/crates/ssh_form/src/lib.rs +++ b/crates/ssh_form/src/lib.rs @@ -4,5 +4,6 @@ pub mod host_key_dialog; pub mod otp_qr; pub mod ssh_form_mfa; pub mod ssh_form_window; +mod x11_status; pub use ssh_form_window::{SshFormPostSaveAction, SshFormWindow, SshFormWindowConfig}; diff --git a/crates/ssh_form/src/ssh_form_window.rs b/crates/ssh_form/src/ssh_form_window.rs index 32aa325c6..13efe3f91 100644 --- a/crates/ssh_form/src/ssh_form_window.rs +++ b/crates/ssh_form/src/ssh_form_window.rs @@ -10,9 +10,11 @@ use connection_form::team::{ }; use gpui::prelude::FluentBuilder; use gpui::{ - App, AppContext, AsyncApp, ClipboardEntry, Context, Div, Entity, FocusHandle, Focusable, - InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Render, SharedString, - StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, div, img, px, relative, + App, AppContext, AsyncApp, ClickEvent, ClipboardEntry, Context, Div, Entity, ExternalPaths, + FocusHandle, + Focusable, InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Render, + SharedString, StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, div, img, + px, relative, }; use gpui_component::{ ActiveTheme, Disableable, Icon, Sizable, Size, WindowExt, @@ -33,11 +35,11 @@ use one_assets::IconName; use one_core::cloud_sync::TeamOption; use one_core::connection_notifier::{ConnectionDataEvent, get_notifier}; use one_core::gpui_tokio::Tokio; +use one_core::settings::{AppSettings, X11ServerMode, configured_mode}; use one_core::storage::traits::Repository; use one_core::storage::{ - BastionTarget, FtpParams, - JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, ProxyConfig, - ProxyType as StorageProxyType, RemoteFileParams, + BastionTarget, FtpParams, JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, + ProxyConfig, ProxyType as StorageProxyType, RemoteFileParams, RemoteFileProtocol as StoredRemoteFileProtocol, SSH_ICON_IDS, SftpAccount, SshAccountExpect, SshAgentForwardKey, SshAuthMethod, SshElevationExpect, SshParams, StoredConnection, StoredTerminalEncoding, StoredTerminalType, Workspace, ssh_os_icon, @@ -64,6 +66,7 @@ use crate::ssh_form_mfa::{ CapturedMfaRequest, FormMfaPrompt, FormMfaRequest, JumpServerMfaResponder, OtpAutoAnswerResponder, form_mfa_request_from_keyboard_interactive, is_jump_mfa_required_error, }; +use crate::x11_status::{X11ConnectionState, probe_connection_x11}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SshFormPostSaveAction { @@ -397,6 +400,9 @@ pub struct SshFormWindow { is_testing: bool, is_uninstalling_shell_integration: bool, test_result: Option, String>>, + /// 本次测试连接实际协商出的 X11 状态,不依赖日志文本。 + x11_test_status: Option, + x11_switch_message: Option, shell_integration_uninstall_result: Option>, on_saved: Option, save_action: SaveAction, @@ -858,6 +864,37 @@ pub enum ProxyTypeSelection { Http, } +/// 私钥路径输入框的位置:主连接与跳板机各有一个,都需要能选文件。 +#[derive(Clone, Copy)] +enum KeyPathTarget { + Primary, + Jump, +} + +impl KeyPathTarget { + fn button_id(self) -> &'static str { + match self { + Self::Primary => "browse-key-path", + Self::Jump => "browse-jump-key-path", + } + } + + /// 拖放目标 id:同一行既是输入框容器也是私钥文件落点。 + fn drop_id(self) -> &'static str { + match self { + Self::Primary => "key-path-drop", + Self::Jump => "jump-key-path-drop", + } + } + + fn input(self, form: &SshFormWindow) -> &Entity { + match self { + Self::Primary => &form.key_path_input, + Self::Jump => &form.jump_key_path_input, + } + } +} + impl SshFormWindow { pub fn new(config: SshFormWindowConfig, window: &mut Window, cx: &mut Context) -> Self { let is_editing = config.is_editing(); @@ -1535,6 +1572,8 @@ impl SshFormWindow { is_testing: false, is_uninstalling_shell_integration: false, test_result: None, + x11_test_status: None, + x11_switch_message: None, shell_integration_uninstall_result: None, on_saved, save_action: SaveAction::Close, @@ -1609,9 +1648,12 @@ impl SshFormWindow { let jump_host = self.jump_host_input.read(cx).text().to_string(); let jump_username = self.jump_username_input.read(cx).text().to_string(); let jump_picker = self.jump_credential_picker.read(cx); - // 选了钥匙串后用户名与认证方式都被隐藏,登录信息在连接时由钥匙串解析。 - let jump_keychain_selected = jump_picker.selected_reference().is_some(); - if jump_host.is_empty() || (jump_username.is_empty() && !jump_keychain_selected) { + // 钥匙串条目自带用户名时以记录为准;没有用户名时用这里保存的值(表单会把 + // 这一栏放出来)。两边都空说明配置还不完整。 + let jump_username_from_keychain = jump_picker.field_referenced(CredentialField::Username); + // 钥匙串没有用户名时这一栏必须填,两边都空就算配置不完整。 + let jump_needs_username = !jump_username_from_keychain && jump_username.trim().is_empty(); + if jump_host.is_empty() || jump_needs_username { return None; } let jump_port: u16 = self @@ -1706,11 +1748,15 @@ impl SshFormWindow { let username = self.username_input.read(cx).text().to_string(); let credential_picker = self.credential_picker.read(cx); let credential_reference = credential_picker.selected_reference(); - // 选了钥匙串后用户名、认证方式、「连接时输入」选项都被隐藏,不再参与校验与保存; - // 用户名为空之类的问题在连接时由钥匙串解析给出明确提示。 + // 认证方式与「连接时输入」由钥匙串记录决定;用户名在记录里没有时回退到 + // 这里保存的值(表单在这种情况下会把用户名一栏放出来)。 let keychain_selected = credential_reference.is_some(); + let username_from_keychain = credential_picker.field_referenced(CredentialField::Username); + let needs_username = !username_from_keychain + && username.trim().is_empty() + && (keychain_selected || self.save_username); - if host.is_empty() || (username.is_empty() && self.save_username && !keychain_selected) { + if host.is_empty() || needs_username { return None; } // 堡垒机直连没有资产或账号就渲染不出「用户#账号#资产」登录名,拦住半成品配置。 @@ -2157,10 +2203,13 @@ impl SshFormWindow { cx: &mut Context, ) { self.is_testing = true; + self.x11_test_status = None; + self.x11_switch_message = None; let target_host = params.host.clone(); let mut config = self.build_ssh_connect_config(¶ms); config.host_key_verifier = host_key_verifier.clone(); let x11_requested = config.x11_forwarding; + let x11_mode = configured_mode(); let jump_mfa_capture = CapturedMfaRequest::default(); let jump_mfa_responses = self.collect_jump_mfa_responses(cx, &signature); let jump_password = config @@ -2198,12 +2247,16 @@ impl SshFormWindow { let spawn_result = Tokio::spawn_result(cx, async move { let mut client = RusshClient::connect(config).await?; let os_id = detect_remote_os_id(&mut client).await; - let x11_available = client.x11_forwarding().is_some(); + let x11_probe = probe_connection_x11(&mut client).await; client.disconnect().await?; - Ok::<(Option, bool), anyhow::Error>((os_id, x11_available)) + Ok::<_, anyhow::Error>((os_id, x11_probe)) }) .await; + let x11_state = match &spawn_result { + Ok((_, probe)) => X11ConnectionState::from_test(x11_requested, x11_mode, probe), + _ => None, + }; let jump_mfa_request = match &spawn_result { Err(error) if is_jump_mfa_required_error(error.as_ref()) => jump_mfa_capture.take(), _ => None, @@ -2214,12 +2267,12 @@ impl SshFormWindow { }; let (test_result, x11_unavailable): (Result, String>, bool) = match spawn_result { - Ok((os_id, x11_available)) => ( + Ok((os_id, x11_probe)) => ( Ok(os_id), connection_test_needs_xquartz_warning( cfg!(target_os = "macos"), x11_requested, - x11_available, + x11_probe.accepted(), ), ), Err(error) => (Err(format_connection_error(&error, &target_host)), false), @@ -2256,6 +2309,9 @@ impl SshFormWindow { if let Ok(os_id) = &test_result { this.detected_os_id = os_id.clone(); } + if let Some(x11_state) = x11_state { + this.x11_test_status = Some(x11_state); + } this.test_result = Some(test_result); } cx.notify(); @@ -2897,6 +2953,91 @@ impl SshFormWindow { .detach(); } + /// 私钥路径一行:输入框 + 选择本机文件按钮(路径只在本机使用,选文件比手输可靠)。 + fn render_key_path_row( + &self, + label: &str, + input: &Entity, + target: KeyPathTarget, + cx: &mut Context, + ) -> impl IntoElement { + self.render_form_row( + label, + h_flex() + .id(target.drop_id()) + .w_full() + .gap_2() + .on_drop(cx.listener(move |form, paths: &ExternalPaths, window, cx| { + form.drop_key_path(target, paths, window, cx); + })) + .child( + div() + .min_w_0() + .flex_1() + .child(self.render_form_input(input)), + ) + .child( + Button::new(target.button_id()) + .icon(IconName::FolderOpen) + .ghost() + .on_click(cx.listener(move |form, _, window, cx| { + form.browse_key_path(target, window, cx); + })) + .tooltip(t!("SSH.key_path_select_file").to_string()), + ), + ) + } + + /// 打开系统文件选择器挑一个本机私钥文件,选中后写回对应输入框。 + fn browse_key_path( + &mut self, + target: KeyPathTarget, + window: &mut Window, + cx: &mut Context, + ) { + let input = target.input(self).clone(); + let future = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: Some(t!("SSH.key_path_select_file").to_string().into()), + }); + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(paths))) = future.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + let path = path.to_string_lossy().to_string(); + let _ = this.update_in(cx, |_, window, cx| { + input.update(cx, |state, cx| { + state.set_value(path, window, cx); + }); + }); + }) + .detach(); + } + + /// 把拖进窗口的私钥文件路径写进对应输入框。 + fn drop_key_path( + &mut self, + target: KeyPathTarget, + paths: &ExternalPaths, + window: &mut Window, + cx: &mut Context, + ) { + let Some(path) = paths.paths().first() else { + return; + }; + let path = path.to_string_lossy().to_string(); + let input = target.input(self).clone(); + input.update(cx, |state, cx| { + state.set_value(path, window, cx); + }); + cx.notify(); + } + fn render_icon_selection_indicator( &self, id: String, @@ -3059,6 +3200,12 @@ impl SshFormWindow { .read(cx) .selected_reference() .is_none(); + // 钥匙串条目自带用户名时用户名一栏保持隐藏;没有用户名时放出来让用户填, + // 解析时会回退到这个值,否则连接必然因为缺用户名失败。 + let username_from_keychain = self + .credential_picker + .read(cx) + .field_referenced(CredentialField::Username); // 堡垒机直连时,基础信息的地址/端口/用户名/认证就是堡垒机登录信息。 let host_label = match connection_mode { ConnectionMode::BastionDirect => t!("SSH.bastion_host"), @@ -3133,7 +3280,7 @@ impl SshFormWindow { Select::new(&self.auth_method_select).w_full(), )) }) - .when(credential_is_manual, |form| { + .when(!username_from_keychain, |form| { form.child( self.render_form_row( &t!("SSH.username"), @@ -3147,28 +3294,39 @@ impl SshFormWindow { .flex_1() .child(self.render_form_input(&self.username_input)), ) - .child( - h_flex() - .items_center() - .gap_1() - .flex_shrink_0() - .child( - Checkbox::new("save-username") - .label(t!("SSH.save_username_desc").to_string()) - .checked(self.save_username) - .on_click(cx.listener(|this, _, _, cx| { - this.save_username = !this.save_username; - cx.notify(); - })), - ) - .child( - Button::new("save-username-help") - .icon(IconName::Info) - .ghost() - .xsmall() - .tooltip(t!("SSH.save_username_hint").to_string()), - ), - ), + .when(credential_is_manual, |row| { + row.child( + h_flex() + .items_center() + .gap_1() + .flex_shrink_0() + .child( + Checkbox::new("save-username") + .label(t!("SSH.save_username_desc").to_string()) + .checked(self.save_username) + .on_click(cx.listener(|this, _, _, cx| { + this.save_username = !this.save_username; + cx.notify(); + })), + ) + .child( + Button::new("save-username-help") + .icon(IconName::Info) + .ghost() + .xsmall() + .tooltip(t!("SSH.save_username_hint").to_string()), + ), + ) + }) + .when(!credential_is_manual, |row| { + row.child( + div() + .flex_shrink_0() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(t!("SSH.username_missing_in_keychain").to_string()), + ) + }), ), ) }) @@ -3262,9 +3420,11 @@ impl SshFormWindow { ), ), ) - .child(self.render_form_row( + .child(self.render_key_path_row( &t!("SSH.key_path"), - self.render_form_input(&self.key_path_input), + &self.key_path_input, + KeyPathTarget::Primary, + cx, )) .child(self.render_form_row( &t!("SSH.passphrase"), @@ -3283,9 +3443,11 @@ impl SshFormWindow { .when( credential_is_manual && auth_method == AuthMethodSelection::PrivateKey, |this| { - this.child(self.render_form_row( + this.child(self.render_key_path_row( &t!("SSH.key_path"), - self.render_form_input(&self.key_path_input), + &self.key_path_input, + KeyPathTarget::Primary, + cx, )) .child(self.render_form_row( &t!("SSH.passphrase"), @@ -3426,6 +3588,11 @@ impl SshFormWindow { .read(cx) .selected_reference() .is_none(); + // 与主连接一致:钥匙串条目没有用户名时把这一栏放出来。 + let jump_username_from_keychain = self + .jump_credential_picker + .read(cx) + .field_referenced(CredentialField::Username); v_flex() .w_full() @@ -3450,18 +3617,38 @@ impl SshFormWindow { .child( self.render_form_row(&t!("SSH.keychain"), self.jump_credential_picker.clone()), ) - .when(jump_credential_is_manual, |form| { - form.child(self.render_form_row( - &t!("SSH.jump_username"), - self.render_form_input(&self.jump_username_input), - )) + .when(!jump_username_from_keychain, |form| { + form.child( + self.render_form_row( + &t!("SSH.jump_username"), + h_flex() + .w_full() + .items_center() + .gap_2() + .child( + div() + .min_w_0() + .flex_1() + .child(self.render_form_input(&self.jump_username_input)), + ) + .when(!jump_credential_is_manual, |row| { + row.child( + div() + .flex_shrink_0() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child( + t!("SSH.username_missing_in_keychain").to_string(), + ), + ) + }), + ), + ) }) - .child( - self.render_form_row( - &t!("SSH.jump_auth_method"), - Select::new(&self.jump_auth_method_select).w_full(), - ), - ) + .child(self.render_form_row( + &t!("SSH.jump_auth_method"), + Select::new(&self.jump_auth_method_select).w_full(), + )) .when( jump_credential_is_manual && jump_auth_method == AuthMethodSelection::Password, |this| { @@ -3485,9 +3672,11 @@ impl SshFormWindow { .mask_toggle(), ), ) - .child(self.render_form_row( + .child(self.render_key_path_row( &t!("SSH.jump_key_path"), - self.render_form_input(&self.jump_key_path_input), + &self.jump_key_path_input, + KeyPathTarget::Jump, + cx, )) .child( self.render_form_row( @@ -3510,9 +3699,11 @@ impl SshFormWindow { jump_credential_is_manual && jump_auth_method == AuthMethodSelection::PrivateKey, |this| { - this.child(self.render_form_row( + this.child(self.render_key_path_row( &t!("SSH.jump_key_path"), - self.render_form_input(&self.jump_key_path_input), + &self.jump_key_path_input, + KeyPathTarget::Jump, + cx, )) .child( self.render_form_row( @@ -4122,6 +4313,81 @@ fn mfa_prompt_label(prompt: &str) -> String { } } +impl SshFormWindow { + fn switch_x11_to_external( + &mut self, + _: &ClickEvent, + _window: &mut Window, + cx: &mut Context, + ) { + AppSettings::update_and_save(cx, |settings| { + settings.x11_server_mode = X11ServerMode::External; + }); + self.x11_switch_message = Some(t!("SSH.x11_switching_external").to_string()); + cx.notify(); + let task = Tokio::spawn_result(cx, async move { + Ok(x11_component::resolve_server(X11ServerMode::External).await) + }); + cx.spawn(async move |this: WeakEntity, cx: &mut AsyncApp| { + let status = match task.await { + Ok(resolution) => resolution.status, + Err(error) => one_core::settings::X11ForwardingStatus::Disabled { + reason: error.to_string(), + }, + }; + let _ = this.update(cx, |this, cx| { + if let Some(state) = this.x11_test_status.as_mut() { + state.apply_external_resolution(status); + } + this.x11_switch_message = None; + cx.notify(); + }); + }) + .detach(); + } + + fn render_x11_status(&self, cx: &mut Context) -> Option { + let state = self.x11_test_status.as_ref()?; + let disabled = matches!( + state.status, + one_core::settings::X11ForwardingStatus::Disabled { .. } + ); + let color = if disabled { + cx.theme().danger + } else { + cx.theme().success + }; + let switch_button = state.should_offer_external().then(|| { + Button::new("ssh-x11-use-external") + .label(t!("SSH.x11_switch_external").to_string()) + .small() + .on_click(cx.listener(Self::switch_x11_to_external)) + }); + Some( + v_flex() + .mx_6() + .pb_2() + .gap_1() + .child(div().text_sm().text_color(color).child(state.label())) + .children( + state + .guidance_keys() + .iter() + .map(|key| div().child(t!(*key).to_string())), + ) + .when(cfg!(target_os = "macos"), |this| { + this.child(t!("SSH.x11_macos_xquartz_guidance").to_string()) + }) + .when_some(switch_button, |this, button| this.child(button)) + .when_some(self.x11_switch_message.clone(), |this, message| { + this.child(div().text_color(cx.theme().muted_foreground).child(message)) + }) + .text_xs() + .into_any_element(), + ) + } +} + impl Focusable for SshFormWindow { fn focus_handle(&self, _cx: &App) -> FocusHandle { self.focus_handle.clone() @@ -4135,6 +4401,7 @@ impl Render for SshFormWindow { let is_busy = is_testing || is_uninstalling_shell_integration; let active_tab = self.active_tab; + let x11_status_element = self.render_x11_status(cx); let test_result_element = match &self.test_result { Some(Ok(os_id)) => Some( h_flex() @@ -4247,6 +4514,7 @@ impl Render for SshFormWindow { .when_some(test_result_element, |this, elem| { this.child(h_flex().justify_center().pb_2().child(elem)) }) + .when_some(x11_status_element, |this, elem| this.child(elem)) .when_some(uninstall_result_element, |this, elem| { this.child(div().w_full().min_w_0().px_6().pb_2().child(elem)) }) @@ -4365,9 +4633,9 @@ mod tests { use one_core::settings::AppSettings; use one_core::storage::{ BastionTarget, BastionUserFormat, ConnectionType, CredentialReference, FtpParams, - JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, - RemoteFileParams, RemoteFileProtocol as StoredRemoteFileProtocol, SftpAccount, - SshAuthMethod, SshElevationExpect, SshParams, StoredConnection, StoredTerminalEncoding, + JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, RemoteFileParams, + RemoteFileProtocol as StoredRemoteFileProtocol, SftpAccount, SshAuthMethod, + SshElevationExpect, SshParams, StoredConnection, StoredTerminalEncoding, StoredTerminalType, }; use rust_i18n::t; @@ -4552,6 +4820,94 @@ mod tests { ); } + #[gpui::test] + fn ssh_keychain_without_username_requires_the_connection_username(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.set_global(AppSettings::default()); + gpui_component::init(cx); + }); + let mut params = sample_params(); + params.username = String::new(); + params.credential_reference = Some(CredentialReference { + credential_id: 9, + username: false, + password: true, + ..Default::default() + }); + let initial_connection = StoredConnection::new_ssh("no-username".to_string(), params, None); + let (form, cx) = cx.add_window_view(|window, cx| { + super::SshFormWindow::new( + super::SshFormWindowConfig { + initial_workspace_id: None, + editing_connection: None, + initial_connection: Some(initial_connection), + on_saved: None, + workspaces: Vec::new(), + teams: Vec::new(), + }, + window, + cx, + ) + }); + + // 钥匙串条目没有用户名时,表单必须要求在这里补一个,不能带着空用户名保存。 + assert!( + form.read_with(cx, |form, cx| form.build_ssh_params(cx)) + .is_none(), + "empty username with a username-less keychain entry must block saving" + ); + + form.update_in(cx, |form, window, cx| { + form.username_input.update(cx, |state, cx| { + state.set_value("vault-fallback", window, cx) + }); + }); + let built = form + .read_with(cx, |form, cx| form.build_ssh_params(cx)) + .expect("填写用户名后应能构建参数"); + assert_eq!(built.username, "vault-fallback"); + assert!(built.credential_reference.is_some()); + } + + #[gpui::test] + fn ssh_keychain_with_username_keeps_the_username_optional(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.set_global(AppSettings::default()); + gpui_component::init(cx); + }); + let mut params = sample_params(); + params.username = String::new(); + params.credential_reference = Some(CredentialReference { + credential_id: 9, + username: true, + password: true, + ..Default::default() + }); + let initial_connection = + StoredConnection::new_ssh("has-username".to_string(), params, None); + let (form, cx) = cx.add_window_view(|window, cx| { + super::SshFormWindow::new( + super::SshFormWindowConfig { + initial_workspace_id: None, + editing_connection: None, + initial_connection: Some(initial_connection), + on_saved: None, + workspaces: Vec::new(), + teams: Vec::new(), + }, + window, + cx, + ) + }); + + // 钥匙串条目自带用户名时,连接表单里的用户名仍然可以不填。 + let built = form + .read_with(cx, |form, cx| form.build_ssh_params(cx)) + .expect("钥匙串自带用户名时应能构建参数"); + assert_eq!(built.username, ""); + assert!(built.credential_reference.is_some()); + } + #[test] fn ssh_second_factor_controls_live_in_the_advanced_tab() { let source = include_str!("ssh_form_window.rs"); @@ -6030,9 +6386,7 @@ mod tests { /// 堡垒机直连:基础信息就是堡垒机登录信息,保存时由它派生 jump_server。 #[gpui::test] - fn ssh_form_bastion_direct_derives_jump_config_from_basic_info( - cx: &mut TestAppContext, - ) { + fn ssh_form_bastion_direct_derives_jump_config_from_basic_info(cx: &mut TestAppContext) { cx.update(|cx| { cx.set_global(AppSettings::default()); gpui_component::init(cx); diff --git a/crates/ssh_form/src/x11_status.rs b/crates/ssh_form/src/x11_status.rs new file mode 100644 index 000000000..175968085 --- /dev/null +++ b/crates/ssh_form/src/x11_status.rs @@ -0,0 +1,576 @@ +//! SSH 测试连接的结构化 X11 状态。 + +use one_core::settings::{X11ForwardingStatus, X11ServerMode}; +use rust_i18n::t; +use ssh::{SshChannel as _, SshClient, X11RequestRejected}; + +const REMOTE_GUIDANCE_KEYS: [&str; 2] = [ + "SSH.x11_remote_forwarding_disabled_checklist", + "SSH.x11_untrusted_ssh_x_security", +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum X11RequestOutcome { + NotAttempted, + Accepted, + Rejected, + Failed, +} + +#[derive(Clone, Debug)] +pub(crate) struct X11Probe { + pub(crate) outcome: X11RequestOutcome, + pub(crate) status: Option, +} + +impl X11Probe { + pub(crate) fn accepted(&self) -> bool { + self.outcome == X11RequestOutcome::Accepted + } +} + +/// 用临时 session channel 发送真实 x11-req;任何 X11 错误都只降级 X11 状态。 +pub(crate) async fn probe_connection_x11(client: &mut C) -> X11Probe { + let Some(proxy) = client.x11_forwarding().cloned() else { + return X11Probe { + outcome: X11RequestOutcome::NotAttempted, + status: client.x11_status(), + }; + }; + + let ready_status = client.x11_status(); + let mut channel = match client.open_channel().await { + Ok(channel) => channel, + Err(error) => { + return X11Probe { + outcome: X11RequestOutcome::Failed, + status: Some(X11ForwardingStatus::Disabled { + reason: t!("SSH.x11_channel_open_failed", error = format!("{error:#}")) + .to_string(), + }), + }; + } + }; + + let request = proxy.issue_request(false); + let result = channel.request_x11_forwarding(&request).await; + // 测试 cookie 不会被后续终端复用,成功与失败都立即撤销授权。 + proxy.retract_request(&request); + let _ = channel.close().await; + + match result { + Ok(()) => X11Probe { + outcome: X11RequestOutcome::Accepted, + status: ready_status, + }, + Err(error) => { + let rejected = error.downcast_ref::().is_some(); + X11Probe { + outcome: if rejected { + X11RequestOutcome::Rejected + } else { + X11RequestOutcome::Failed + }, + status: Some(x11_request_error_status(&error)), + } + } + } +} + +fn x11_request_error_status(error: &anyhow::Error) -> X11ForwardingStatus { + let key = if error.downcast_ref::().is_some() { + "SSH.x11_remote_request_rejected" + } else { + "SSH.x11_request_failed" + }; + X11ForwardingStatus::Disabled { + reason: t!(key, error = format!("{error:#}")).to_string(), + } +} + +#[derive(Clone, Debug)] +pub(crate) struct X11ConnectionState { + pub(crate) status: X11ForwardingStatus, + pub(crate) remote_unavailable: bool, + mode: X11ServerMode, +} + +impl X11ConnectionState { + pub(crate) fn from_test( + requested: bool, + mode: X11ServerMode, + probe: &X11Probe, + ) -> Option { + if !requested { + return None; + } + let resolved = probe.status.clone()?; + let remote_unavailable = probe.outcome == X11RequestOutcome::Rejected; + if matches!(resolved, X11ForwardingStatus::Disabled { .. }) + || matches!( + probe.outcome, + X11RequestOutcome::Accepted | X11RequestOutcome::NotAttempted + ) + { + return Some(Self { + status: resolved, + remote_unavailable, + mode, + }); + } + let reason = if remote_unavailable { + t!("SSH.x11_remote_channel_unavailable").to_string() + } else { + t!("SSH.x11_request_unavailable").to_string() + }; + Some(Self { + status: X11ForwardingStatus::Disabled { reason }, + remote_unavailable, + mode, + }) + } + + pub(crate) fn guidance_keys(&self) -> &'static [&'static str] { + if self.remote_unavailable { + &REMOTE_GUIDANCE_KEYS + } else { + &[] + } + } + + pub(crate) fn should_offer_external(&self) -> bool { + self.mode != X11ServerMode::External + && matches!(self.status, X11ForwardingStatus::Disabled { .. }) + } + + pub(crate) fn apply_external_resolution(&mut self, status: X11ForwardingStatus) { + self.mode = X11ServerMode::External; + self.status = status; + self.remote_unavailable = false; + } + + pub(crate) fn label(&self) -> String { + match &self.status { + X11ForwardingStatus::External { server } => { + t!("SSH.x11_status_external", server = server).to_string() + } + X11ForwardingStatus::Embedded { version } => { + t!("SSH.x11_status_embedded", version = version).to_string() + } + X11ForwardingStatus::Disabled { reason } => { + t!("SSH.x11_status_disabled", reason = reason).to_string() + } + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use anyhow::{Result, anyhow}; + use async_trait::async_trait; + use one_core::settings::{X11ForwardingStatus, X11ServerMode}; + use ssh::{ + ChannelEvent, ForwardRequest, MagicCookie, PtyConfig, ServerEndpoint, SshChannel, + SshClient, SshConnectConfig, X11Proxy, X11RequestRejected, + }; + + use super::{X11ConnectionState, X11Probe, X11RequestOutcome, probe_connection_x11}; + + fn probe(outcome: X11RequestOutcome, status: X11ForwardingStatus) -> X11Probe { + X11Probe { + outcome, + status: Some(status), + } + } + + #[derive(Default)] + struct MockChannelState { + requests: Vec, + closed: bool, + rejection: bool, + transport_error: Option, + } + + struct MockChannel { + state: Arc>, + } + + #[async_trait] + impl SshChannel for MockChannel { + async fn request_pty(&mut self, _config: &PtyConfig) -> Result<()> { + Ok(()) + } + + async fn exec(&mut self, _command: &str) -> Result<()> { + Ok(()) + } + + async fn request_shell(&mut self) -> Result<()> { + Ok(()) + } + + async fn request_x11_forwarding(&mut self, request: &ForwardRequest) -> Result<()> { + let mut state = self.state.lock().expect("mock channel state"); + state.requests.push(request.cookie_hex().to_string()); + assert!(!request.single_use); + if state.rejection { + return Err(anyhow::Error::new(X11RequestRejected)); + } + match state.transport_error.clone() { + Some(error) => Err(anyhow!(error)), + None => Ok(()), + } + } + + async fn set_env(&mut self, _name: &str, _value: &str) -> Result<()> { + Ok(()) + } + + async fn send_data(&mut self, _data: &[u8]) -> Result<()> { + Ok(()) + } + + async fn resize_pty(&mut self, _width: u32, _height: u32) -> Result<()> { + Ok(()) + } + + async fn recv(&mut self) -> Option { + None + } + + async fn eof(&mut self) -> Result<()> { + Ok(()) + } + + async fn close(&mut self) -> Result<()> { + self.state.lock().expect("mock channel state").closed = true; + Ok(()) + } + } + + struct MockClient { + proxy: Option, + ready_status: Option, + status: Mutex>, + channel_state: Arc>, + open_error: Option, + open_count: usize, + } + + impl MockClient { + fn new(rejection: bool, transport_error: Option<&str>) -> Self { + let ready_status = X11ForwardingStatus::External { + server: ":0".to_string(), + }; + Self { + proxy: Some(X11Proxy::for_endpoint( + ServerEndpoint::Inet { + host: "127.0.0.1".to_string(), + port: 6137, + }, + MagicCookie::generate(), + )), + ready_status: Some(ready_status.clone()), + status: Mutex::new(Some(ready_status)), + channel_state: Arc::new(Mutex::new(MockChannelState { + rejection, + transport_error: transport_error.map(str::to_string), + ..MockChannelState::default() + })), + open_error: None, + open_count: 0, + } + } + } + + #[async_trait] + impl SshClient for MockClient { + type Channel = MockChannel; + + async fn connect(_config: SshConnectConfig) -> Result { + unreachable!("测试直接构造 mock client") + } + + async fn open_channel(&mut self) -> Result { + self.open_count += 1; + if let Some(error) = self.open_error.take() { + return Err(anyhow!(error)); + } + Ok(MockChannel { + state: Arc::clone(&self.channel_state), + }) + } + + async fn disconnect(&mut self) -> Result<()> { + Ok(()) + } + + fn is_connected(&self) -> bool { + true + } + + fn x11_forwarding(&self) -> Option<&X11Proxy> { + self.proxy.as_ref() + } + + fn x11_status(&self) -> Option { + self.status.lock().expect("mock status").clone() + } + } + + #[tokio::test] + async fn connection_test_sends_real_x11_request_on_a_temporary_channel() { + let mut client = MockClient::new(false, None); + let probe = probe_connection_x11(&mut client).await; + + assert_eq!(X11RequestOutcome::Accepted, probe.outcome); + assert!(probe.accepted()); + assert_eq!(1, client.open_count); + assert_eq!(client.ready_status, probe.status); + let state = client.channel_state.lock().expect("mock channel state"); + assert_eq!(1, state.requests.len()); + assert!(state.closed); + } + + #[tokio::test] + async fn remote_x11_rejection_is_visible_but_not_an_ssh_error() { + let mut client = MockClient::new(true, None); + let probe = probe_connection_x11(&mut client).await; + let state = X11ConnectionState::from_test(true, X11ServerMode::External, &probe) + .expect("X11 拒绝状态"); + + assert_eq!(X11RequestOutcome::Rejected, probe.outcome); + assert!(!probe.accepted()); + assert!(state.remote_unavailable); + assert!(matches!( + state.status, + X11ForwardingStatus::Disabled { ref reason } if reason.contains("x11-req") + )); + assert!(client.is_connected()); + assert!( + client + .channel_state + .lock() + .expect("mock channel state") + .closed + ); + } + + #[tokio::test] + async fn x11_transport_failure_does_not_claim_remote_rejection() { + let mut client = MockClient::new(false, Some("local send failed")); + let probe = probe_connection_x11(&mut client).await; + let state = X11ConnectionState::from_test(true, X11ServerMode::External, &probe) + .expect("X11 失败状态"); + + assert_eq!(X11RequestOutcome::Failed, probe.outcome); + assert!(!state.remote_unavailable); + assert!(state.guidance_keys().is_empty()); + assert!(matches!( + state.status, + X11ForwardingStatus::Disabled { ref reason } + if reason.contains("local send failed") && !reason.contains("sshd_config") + )); + assert!(client.is_connected()); + } + + #[test] + fn disabled_x11_checkbox_has_no_connection_status() { + assert!( + X11ConnectionState::from_test( + false, + X11ServerMode::Auto, + &probe( + X11RequestOutcome::NotAttempted, + X11ForwardingStatus::Disabled { + reason: "not requested".to_string(), + }, + ), + ) + .is_none() + ); + } + + #[test] + fn active_status_preserves_external_or_embedded_details() { + let external = X11ConnectionState::from_test( + true, + X11ServerMode::External, + &probe( + X11RequestOutcome::Accepted, + X11ForwardingStatus::External { + server: ":0".to_string(), + }, + ), + ) + .expect("外部状态"); + assert!(matches!( + external.status, + X11ForwardingStatus::External { ref server } if server == ":0" + )); + + let embedded = X11ConnectionState::from_test( + true, + X11ServerMode::Embedded, + &probe( + X11RequestOutcome::Accepted, + X11ForwardingStatus::Embedded { + version: "1.2.3".to_string(), + }, + ), + ) + .expect("内置状态"); + assert!(matches!( + embedded.status, + X11ForwardingStatus::Embedded { ref version } if version == "1.2.3" + )); + } + + #[test] + fn refused_remote_channel_becomes_visible_disabled_state() { + let state = X11ConnectionState::from_test( + true, + X11ServerMode::External, + &probe( + X11RequestOutcome::Rejected, + X11ForwardingStatus::External { + server: ":0".to_string(), + }, + ), + ) + .expect("远端拒绝也应显示状态"); + + assert!(state.remote_unavailable); + assert!(matches!(state.status, X11ForwardingStatus::Disabled { .. })); + } + + #[test] + fn local_embedded_failure_preserves_reason_and_offers_external() { + let state = X11ConnectionState::from_test( + true, + X11ServerMode::Auto, + &probe( + X11RequestOutcome::NotAttempted, + X11ForwardingStatus::Disabled { + reason: "Vulkan unavailable".to_string(), + }, + ), + ) + .expect("失败状态"); + + assert!(!state.remote_unavailable); + assert!(state.guidance_keys().is_empty()); + assert!(matches!( + state.status, + X11ForwardingStatus::Disabled { ref reason } if reason == "Vulkan unavailable" + )); + } + + #[test] + fn remote_guidance_is_limited_to_actual_channel_refusal() { + let remote = X11ConnectionState::from_test( + true, + X11ServerMode::Embedded, + &probe( + X11RequestOutcome::Rejected, + X11ForwardingStatus::Embedded { + version: "1.2.3".to_string(), + }, + ), + ) + .expect("远端拒绝状态"); + assert_eq!( + &[ + "SSH.x11_remote_forwarding_disabled_checklist", + "SSH.x11_untrusted_ssh_x_security", + ], + remote.guidance_keys() + ); + assert!( + !remote + .guidance_keys() + .contains(&"SSH.x11_remote_display_restarted") + ); + } + + #[test] + fn external_selection_hides_the_offer() { + let mut state = X11ConnectionState { + status: X11ForwardingStatus::Disabled { + reason: "Vulkan unavailable".to_string(), + }, + remote_unavailable: false, + mode: X11ServerMode::Auto, + }; + assert!(state.should_offer_external()); + state.apply_external_resolution(X11ForwardingStatus::External { + server: ":0".to_string(), + }); + assert!(!state.should_offer_external()); + assert!(matches!( + state.status, + X11ForwardingStatus::External { ref server } if server == ":0" + )); + } + + #[test] + fn external_probe_failure_replaces_stale_disabled_reason() { + let mut state = X11ConnectionState { + status: X11ForwardingStatus::Disabled { + reason: "old embedded failure".to_string(), + }, + remote_unavailable: true, + mode: X11ServerMode::Auto, + }; + state.apply_external_resolution(X11ForwardingStatus::Disabled { + reason: "DISPLAY is not reachable".to_string(), + }); + assert!(!state.remote_unavailable); + assert!(state.guidance_keys().is_empty()); + assert!(matches!( + state.status, + X11ForwardingStatus::Disabled { ref reason } if reason == "DISPLAY is not reachable" + )); + } + + #[test] + fn ssh_failure_guidance_exists_in_all_three_languages() { + for language in ["en", "zh-CN", "zh-HK"] { + rust_i18n::set_locale(language); + for key in [ + "SSH.x11_status_external", + "SSH.x11_status_embedded", + "SSH.x11_status_disabled", + "SSH.x11_remote_forwarding_disabled_checklist", + "SSH.x11_remote_display_restarted", + "SSH.x11_untrusted_ssh_x_security", + "SSH.x11_macos_xquartz_guidance", + "SSH.x11_switch_external", + "SSH.x11_switching_external", + "SSH.x11_channel_open_failed", + "SSH.x11_remote_request_rejected", + "SSH.x11_request_failed", + "SSH.x11_request_unavailable", + ] { + assert_ne!(key, rust_i18n::t!(key), "{language} 缺少文案: {key}"); + } + } + rust_i18n::set_locale("en"); + } + + #[test] + fn connection_result_renders_persistent_structured_status() { + let window = include_str!("ssh_form_window.rs"); + assert!(window.contains("x11_test_status: Option")); + assert!(window.contains("render_x11_status")); + assert!(window.contains("x11_test_status = Some(x11_state)")); + assert!(window.contains("probe_connection_x11(&mut client).await")); + assert!(!window.contains("client.x11_forwarding().is_some()")); + assert!(!window.contains("current_status()")); + assert!(window.contains("switch_x11_to_external")); + assert!(window.contains("x11_component::resolve_server(X11ServerMode::External).await")); + assert!(window.contains("AppSettings::update_and_save")); + } +} diff --git a/crates/terminal/src/ssh_backend.rs b/crates/terminal/src/ssh_backend.rs index 68214082d..46eaceb24 100644 --- a/crates/terminal/src/ssh_backend.rs +++ b/crates/terminal/src/ssh_backend.rs @@ -547,6 +547,8 @@ pub struct SshBackend { exec_ids: Arc, performance_metrics: Arc, transfer_cancellation: ActiveTransferCancellation, + /// 本终端会话的 X11 请求结果;不写入共享 SSH transport。 + x11_status: Option, } pub struct SshBackendConnect { @@ -793,6 +795,11 @@ impl SshBackend { disable_shell_integration, ) .await + .map( + |(client, channel, shell_integration_requested, _x11_status)| { + (client, channel, shell_integration_requested) + }, + ) } pub async fn connect(request: SshBackendConnect) -> anyhow::Result { @@ -849,14 +856,15 @@ impl SshBackend { ); } let setup_started_at = Instant::now(); - let (client, mut channel, shell_integration_requested) = Self::establish_channel( - &session_manager, - &pty_config, - connection_id, - disable_shell_integration, - ) - .await - .map_err(add_connect_error_context)?; + let (client, mut channel, shell_integration_requested, x11_status) = + Self::establish_channel( + &session_manager, + &pty_config, + connection_id, + disable_shell_integration, + ) + .await + .map_err(add_connect_error_context)?; tracing::debug!( target: "terminal.ssh.setup", connection_id, @@ -1569,6 +1577,7 @@ impl SshBackend { exec_ids, performance_metrics, transfer_cancellation, + x11_status, }) } @@ -1584,6 +1593,7 @@ impl SshBackend { Arc>, ssh::RusshChannel, bool, + Option, )> { Self::establish_channel_with_manager( session_manager.as_ref(), @@ -1603,6 +1613,7 @@ impl SshBackend { Arc>, ::Channel, bool, + Option, )> { let mut attempt = 0usize; let mut plain_channel_only = disable_shell_integration; @@ -1638,7 +1649,9 @@ impl SshBackend { } else { Self::prepare_plain_ssh_channel(&mut *guard, pty_config) .await - .map(|channel| (channel, shell_integration_requested)) + .map(|(channel, x11_status)| { + (channel, shell_integration_requested, x11_status) + }) } }; @@ -1649,8 +1662,8 @@ impl SshBackend { // 报 Disconnected」的竞态来源。此类错误因此与 channel open 被拒同等处理:失效 // 该 transport generation,并用单个裸交互 channel 重连一次(重连时跳过探测)。 match result { - Ok((channel, shell_integration_requested)) => { - return Ok((client, channel, shell_integration_requested)); + Ok((channel, shell_integration_requested, x11_status)) => { + return Ok((client, channel, shell_integration_requested, x11_status)); } Err(err) if attempt < DEGRADED_RECONNECT_BACKOFFS.len() @@ -1684,10 +1697,10 @@ impl SshBackend { async fn prepare_plain_ssh_channel( client: &mut C, pty_config: &PtyConfig, - ) -> anyhow::Result { + ) -> anyhow::Result<(C::Channel, Option)> { let mut channel = client.open_channel().await?; - Self::start_interactive_shell(client, &mut channel, pty_config).await?; - Ok(channel) + let x11_status = Self::start_interactive_shell(client, &mut channel, pty_config).await?; + Ok((channel, x11_status)) } /// 通过独立 exec channel 只读探测登录 shell 是否支持运行时注入。 @@ -1837,28 +1850,45 @@ impl SshBackend { client: &C, channel: &mut C::Channel, pty_config: &PtyConfig, - ) -> anyhow::Result<()> { + ) -> anyhow::Result> { channel.request_pty(pty_config).await?; - Self::maybe_request_x11_forwarding(client, channel).await; + let x11_status = Self::maybe_request_x11_forwarding(client, channel).await; Self::maybe_request_agent_forwarding(client, channel).await; channel.request_shell().await?; - Ok(()) + Ok(x11_status) } /// 连接启用了 X11 转发时在 pty 之后、shell 之前发送 x11-req。 - /// 服务端拒绝(如 sshd 未开 X11Forwarding)只告警降级,不影响终端使用。 - async fn maybe_request_x11_forwarding(client: &C, channel: &mut C::Channel) { + /// 服务端拒绝只降级当前会话,并把检查项暴露给会话信息面板。 + async fn maybe_request_x11_forwarding( + client: &C, + channel: &mut C::Channel, + ) -> Option { let Some(proxy) = client.x11_forwarding() else { - return; + return client.x11_status(); }; let request = proxy.issue_request(false); - if let Err(error) = channel.request_x11_forwarding(&request).await { - proxy.retract_request(&request); - tracing::warn!( - target: "terminal.ssh.x11", - error = %error, - "服务端拒绝 X11 转发请求,本会话停用 X11 转发" - ); + match channel.request_x11_forwarding(&request).await { + Ok(()) => client.x11_status(), + Err(error) => { + let remote_rejected = error.downcast_ref::().is_some(); + proxy.retract_request(&request); + let status = x11_request_error_status(&error); + if remote_rejected { + tracing::warn!( + target: "terminal.ssh.x11", + error = %error, + "服务端拒绝 X11 转发请求,本会话停用 X11 转发" + ); + } else { + tracing::warn!( + target: "terminal.ssh.x11", + error = %error, + "X11 转发请求发送或等待响应失败,本会话停用 X11 转发" + ); + } + Some(status) + } } } @@ -1878,6 +1908,25 @@ impl SshBackend { } } +fn x11_request_error_status(error: &anyhow::Error) -> ssh::X11ForwardingStatus { + if error.downcast_ref::().is_some() { + return x11_rejection_status(error); + } + let reason = format!( + "X11 转发请求未完成(本地发送失败、等待响应超时或通道提前关闭):{error:#}。\ + 这不是远端 CHANNEL_FAILURE;请检查连接后重试。" + ); + ssh::X11ForwardingStatus::Disabled { reason } +} + +fn x11_rejection_status(error: &anyhow::Error) -> ssh::X11ForwardingStatus { + let reason = format!( + "远端拒绝了 x11-req:{error:#}。请检查 sshd_config 的 X11Forwarding yes、\ + X11DisplayOffset 与 xauth;本应用使用 trusted (-Y),不要用不支持 SECURITY 扩展的 ssh -X 代替。" + ); + ssh::X11ForwardingStatus::Disabled { reason } +} + #[cfg(test)] mod tests { use super::*; @@ -1892,6 +1941,155 @@ mod tests { use tokio::time::sleep; use tokio_util::sync::CancellationToken; + fn backend_with_x11_status(x11_status: Option) -> SshBackend { + let (command_tx, _command_rx) = unbounded_channel(); + SshBackend { + command_tx, + exec_ids: Arc::new(AtomicU64::new(1)), + performance_metrics: Arc::new(TerminalPerformanceMetrics::enabled()), + transfer_cancellation: ActiveTransferCancellation::default(), + x11_status, + } + } + + #[test] + fn x11_rejection_status_contains_remote_and_trusted_checks() { + let status = x11_rejection_status(&anyhow!("administratively prohibited")); + let ssh::X11ForwardingStatus::Disabled { reason } = status else { + panic!("x11-req 拒绝必须进入可见停用状态"); + }; + assert!(reason.contains("X11Forwarding yes")); + assert!(reason.contains("trusted")); + assert!(reason.contains("administratively prohibited")); + } + + #[tokio::test] + async fn x11_rejection_is_scoped_to_the_requesting_session() { + let (mut channel, state) = MockChannel::new([], false); + state.lock().unwrap().x11_remote_rejection = true; + let proxy = ssh::X11Proxy::for_endpoint( + ssh::ServerEndpoint::Inet { + host: "127.0.0.1".to_string(), + port: 6137, + }, + ssh::MagicCookie::generate(), + ); + let ready = ssh::X11ForwardingStatus::External { + server: "test X server".to_string(), + }; + let client = MockClient { + x11_proxy: Some(proxy), + x11_status: Some(ready.clone()), + ..MockClient::new([]) + }; + + let status = SshBackend::maybe_request_x11_forwarding(&client, &mut channel) + .await + .expect("拒绝原因必须返回给当前会话"); + let ssh::X11ForwardingStatus::Disabled { reason } = status else { + panic!("x11-req 拒绝必须停用当前会话的 X11 状态"); + }; + assert!(reason.contains("x11-req")); + assert_eq!(client.x11_status(), Some(ready)); + } + + #[tokio::test] + async fn x11_transport_error_is_not_reported_as_remote_rejection() { + let (mut channel, state) = MockChannel::new([], false); + state.lock().unwrap().x11_error = Some("local send failed".to_string()); + let proxy = ssh::X11Proxy::for_endpoint( + ssh::ServerEndpoint::Inet { + host: "127.0.0.1".to_string(), + port: 6137, + }, + ssh::MagicCookie::generate(), + ); + let ready = ssh::X11ForwardingStatus::External { + server: "test X server".to_string(), + }; + let client = MockClient { + x11_proxy: Some(proxy), + x11_status: Some(ready.clone()), + ..MockClient::new([]) + }; + + let status = SshBackend::maybe_request_x11_forwarding(&client, &mut channel) + .await + .expect("本地错误必须返回给当前会话"); + let ssh::X11ForwardingStatus::Disabled { reason } = status else { + panic!("X11 请求失败必须进入可见停用状态"); + }; + assert!(reason.contains("local send failed")); + assert!(!reason.contains("远端拒绝")); + assert!(!reason.contains("sshd_config")); + assert_eq!(client.x11_status(), Some(ready)); + } + + #[tokio::test] + async fn successful_request_uses_transport_resolved_x11_status() { + let (mut channel, _) = MockChannel::new([], false); + let proxy = ssh::X11Proxy::for_endpoint( + ssh::ServerEndpoint::Inet { + host: "127.0.0.1".to_string(), + port: 6137, + }, + ssh::MagicCookie::generate(), + ); + let ready = ssh::X11ForwardingStatus::External { + server: "test X server".to_string(), + }; + let client = MockClient { + x11_proxy: Some(proxy), + x11_status: Some(ready.clone()), + ..MockClient::new([]) + }; + + let status = SshBackend::maybe_request_x11_forwarding(&client, &mut channel).await; + + assert_eq!(status, Some(ready)); + } + + #[tokio::test] + async fn shared_client_x11_results_are_isolated_per_backend() { + let (mut rejected_channel, rejected_state) = MockChannel::new([], false); + rejected_state.lock().unwrap().x11_remote_rejection = true; + let (mut accepted_channel, _) = MockChannel::new([], false); + let ready = ssh::X11ForwardingStatus::External { + server: "shared X server".to_string(), + }; + let client = MockClient { + x11_proxy: Some(ssh::X11Proxy::for_endpoint( + ssh::ServerEndpoint::Inet { + host: "127.0.0.1".to_string(), + port: 6137, + }, + ssh::MagicCookie::generate(), + )), + x11_status: Some(ready.clone()), + ..MockClient::new([]) + }; + + let rejected = SshBackend::maybe_request_x11_forwarding(&client, &mut rejected_channel) + .await + .expect("tab A 必须保留自己的拒绝状态"); + let accepted = SshBackend::maybe_request_x11_forwarding(&client, &mut accepted_channel) + .await + .expect("tab B 必须保留自己的成功状态"); + let backend_a = backend_with_x11_status(Some(rejected)); + let backend_b = backend_with_x11_status(Some(accepted)); + + assert!(matches!( + TerminalBackend::x11_status(&backend_a), + Some(ssh::X11ForwardingStatus::Disabled { .. }) + )); + assert_eq!(TerminalBackend::x11_status(&backend_b), Some(ready.clone())); + assert_eq!( + client.x11_status(), + Some(ready), + "任一页签的请求结果都不能改写共享 transport 的已解析状态" + ); + } + #[tokio::test] async fn zmodem_probe_flush_arms_only_for_plain_asterisk_prefixes() { let mut detector = ZmodemDetector::default(); @@ -2002,6 +2200,7 @@ mod tests { exec_ids: Arc::new(AtomicU64::new(1)), performance_metrics: metrics.clone(), transfer_cancellation: ActiveTransferCancellation::default(), + x11_status: None, }; TerminalBackend::write(&backend, b"direct".to_vec()); @@ -2047,6 +2246,8 @@ mod tests { exec_consumes_session: bool, recv_delay: Option, send_data_error: bool, + x11_error: Option, + x11_remote_rejection: bool, } struct MockChannel { @@ -2072,6 +2273,8 @@ mod tests { exec_consumes_session, recv_delay, send_data_error: false, + x11_error: None, + x11_remote_rejection: false, })); ( Self { @@ -2129,6 +2332,17 @@ mod tests { } } + async fn request_x11_forwarding(&mut self, _request: &ssh::ForwardRequest) -> Result<()> { + let state = self.state.lock().expect("mock channel state should lock"); + if state.x11_remote_rejection { + return Err(anyhow::Error::new(ssh::X11RequestRejected)); + } + match state.x11_error.clone() { + Some(error) => Err(anyhow!(error)), + None => Ok(()), + } + } + async fn resize_pty(&mut self, _width: u32, _height: u32) -> Result<()> { Ok(()) } @@ -2169,6 +2383,8 @@ mod tests { open_error: Option<&'static str>, disconnect_on_open_error: bool, connected: bool, + x11_proxy: Option, + x11_status: Option, } impl MockClient { @@ -2178,6 +2394,8 @@ mod tests { open_error: None, disconnect_on_open_error: false, connected: true, + x11_proxy: None, + x11_status: None, } } @@ -2190,6 +2408,8 @@ mod tests { open_error: Some(open_error), disconnect_on_open_error: false, connected: true, + x11_proxy: None, + x11_status: None, } } @@ -2204,6 +2424,8 @@ mod tests { open_error: Some(open_error), disconnect_on_open_error: true, connected: true, + x11_proxy: None, + x11_status: None, } } } @@ -2239,6 +2461,14 @@ mod tests { fn is_connected(&self) -> bool { self.connected } + + fn x11_forwarding(&self) -> Option<&ssh::X11Proxy> { + self.x11_proxy.as_ref() + } + + fn x11_status(&self) -> Option { + self.x11_status.clone() + } } struct MockSessionManager { @@ -2518,7 +2748,7 @@ mod tests { let second_client = MockClient::new([fallback_channel]); let manager = MockSessionManager::new([first_client, second_client]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2567,7 +2797,7 @@ mod tests { let second_client = MockClient::new([fallback_channel]); let manager = MockSessionManager::new([first_client, second_client]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2608,7 +2838,7 @@ mod tests { let second_client = MockClient::new([fallback_channel]); let manager = MockSessionManager::new([first_client, second_client]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2652,7 +2882,7 @@ mod tests { let second_client = MockClient::new([fallback_channel]); let manager = MockSessionManager::new([first_client, second_client]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2690,7 +2920,7 @@ mod tests { let third_client = MockClient::new([interactive_channel]); let manager = MockSessionManager::new([first_client, second_client, third_client]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2763,7 +2993,7 @@ mod tests { let manager = MockSessionManager::new([MockClient::new([probe_channel, interactive_channel])]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -2799,7 +3029,7 @@ mod tests { let manager = MockSessionManager::new([MockClient::new([probe_channel, interactive_channel])]); - let (_client, _channel, shell_integration_requested) = + let (_client, _channel, shell_integration_requested, _x11_status) = SshBackend::establish_channel_with_manager( &manager, &PtyConfig::default(), @@ -3051,6 +3281,7 @@ mod tests { exec_ids: Arc::new(AtomicU64::new(1)), performance_metrics: Arc::new(TerminalPerformanceMetrics::enabled()), transfer_cancellation: transfer_cancellation.clone(), + x11_status: None, }; let first = transfer_cancellation.begin(); @@ -3256,6 +3487,10 @@ impl TerminalBackend for SshBackend { self.transfer_cancellation.cancel_handle() } + fn x11_status(&self) -> Option { + self.x11_status.clone() + } + fn cancel_transfer(&self) -> bool { self.transfer_cancellation.cancel() } diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rs index c0ea142b8..583984735 100644 --- a/crates/terminal/src/terminal.rs +++ b/crates/terminal/src/terminal.rs @@ -22,8 +22,8 @@ use one_core::app_dirs; use one_core::gpui_tokio::Tokio; use one_core::settings::AppSettings; use one_core::storage::models::{ - ActiveConnections, SerialParams, SshAccountExpect, SshAgentForwardKey, - SshAuthMethod, StoredConnection, TelnetParams, + ActiveConnections, SerialParams, SshAccountExpect, SshAgentForwardKey, SshAuthMethod, + StoredConnection, TelnetParams, }; use one_core::storage::{ GlobalStorageState, TerminalCommandHistoryRepository, TerminalCommandHistorySort, @@ -710,8 +710,14 @@ fn resolve_ssh_connection( timeout: params.connect_timeout.map(Duration::from_secs), keepalive_interval: params.keepalive_interval.map(Duration::from_secs), keepalive_max: params.keepalive_max, - jump_server: params.jump_server.as_ref().map(sftp_transfer::jump_connect_config), - proxy: params.proxy.as_ref().map(sftp_transfer::proxy_connect_config), + jump_server: params + .jump_server + .as_ref() + .map(sftp_transfer::jump_connect_config), + proxy: params + .proxy + .as_ref() + .map(sftp_transfer::proxy_connect_config), keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), x11_forwarding: params.x11_forwarding.unwrap_or(false), @@ -2827,8 +2833,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, - ssh_session_lease: None, - ssh_credential_revision: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -3409,9 +3415,7 @@ impl Terminal { // acquire 内部会 tokio::spawn(reaper/创建飞行),必须在 Tokio runtime // 上下文里调用;GPUI executor 上没有 reactor,直接 await 会 panic。 let acquire_task = Tokio::spawn(cx, async move { - service - .acquire(&key, acquire_connect_config) - .await + service.acquire(&key, acquire_connect_config).await }); let source = match acquire_task.await { Ok(Ok(lease)) => ManagerSource::Shared(lease), @@ -4098,6 +4102,12 @@ impl Terminal { self.ssh_session_manager.as_ref() } + /// 返回当前终端自身已完成 X11 请求的结果。 + /// 后端安装前不得回退共享 transport 状态,否则其他标签页会被误报为成功。 + pub fn x11_status(&self) -> Option { + self.backend.as_ref().and_then(|backend| backend.x11_status()) + } + pub fn apply_ssh_connection_update(&mut self, update: SshConnectionUpdate) -> Result<()> { if self.is_read_only() { return Err(anyhow!( diff --git a/crates/terminal/src/types.rs b/crates/terminal/src/types.rs index 08bb13e50..6dc42f443 100644 --- a/crates/terminal/src/types.rs +++ b/crates/terminal/src/types.rs @@ -247,6 +247,11 @@ pub trait TerminalBackend: Send { None } + /// 当前终端会话的 X11 状态;非 SSH backend 默认没有该状态。 + fn x11_status(&self) -> Option { + None + } + /// Request cancellation of the currently active ZMODEM transfer. /// /// The backend only acknowledges that the request was delivered. The actual diff --git a/crates/terminal_view/locales/terminal_view.yml b/crates/terminal_view/locales/terminal_view.yml index c6053812f..1c40a9117 100644 --- a/crates/terminal_view/locales/terminal_view.yml +++ b/crates/terminal_view/locales/terminal_view.yml @@ -782,6 +782,18 @@ Settings: en: Terminal autocomplete zh-CN: 终端自动补全 zh-HK: 終端自動補全 + pane_toolbar_section: + en: Panel + zh-CN: 面板 + zh-HK: 面板 + pane_toolbar: + en: Pane toolbar + zh-CN: 面板工具条 + zh-HK: 面板工具列 + pane_toolbar_help: + en: Show the floating toolbar with split and recording buttons in the top-right corner of the terminal pane. + zh-CN: 在终端面板右上角显示包含分屏与录制按钮的悬浮工具条。 + zh-HK: 在終端面板右上角顯示包含分屏與錄製按鈕的懸浮工具列。 middle_click_paste: en: Middle click paste zh-CN: 中键粘贴 @@ -1778,6 +1790,14 @@ TerminalCommandBar: en: Close quick commands zh-CN: 关闭快捷指令 zh-HK: 關閉快速指令 + quick_bar_hint: + en: Pinned quick commands appear here + zh-CN: 置顶的快捷指令会显示在这里 + zh-HK: 置頂的快捷指令會顯示在這裡 + quick_bar_hint_tooltip: + en: Pin a command with the star in the quick command list to show it here. + zh-CN: 在快捷指令列表中点击星标置顶,置顶后会常驻显示在这里。 + zh-HK: 在快捷指令列表中點擊星標置頂,置頂後會常駐顯示在這裡。 fill: en: Fill zh-CN: 填入 @@ -2781,6 +2801,16 @@ TerminalRecording: zh-CN: 选择录制目录失败 zh-HK: 選擇錄製目錄失敗 +TerminalX11: + external: + en: "External X server: %{server}" + zh-CN: "外部 X server:%{server}" + zh-HK: "外部 X server:%{server}" + embedded: + en: "Embedded X server: %{version}" + zh-CN: "内置 X server:%{version}" + zh-HK: "內置 X server:%{version}" + TerminalSessionLog: tab_title: en: "Log · %{name}" diff --git a/crates/terminal_view/src/sidebar/mod.rs b/crates/terminal_view/src/sidebar/mod.rs index 467a2e65d..820c8ab1f 100644 --- a/crates/terminal_view/src/sidebar/mod.rs +++ b/crates/terminal_view/src/sidebar/mod.rs @@ -775,6 +775,8 @@ pub enum TerminalSidebarEvent { ShowLineNumbersChanged(bool), /// 路径与终端同步开关 SyncPathChanged(bool), + /// 终端面板右上角悬浮工具条显隐 + PaneToolbarChanged(bool), /// 自定义高亮规则变更 CustomHighlightsChanged(Vec), /// 在独立页签中打开当前 SSH 连接的 SFTP 文件管理器 @@ -1348,6 +1350,9 @@ impl TerminalSidebar { } cx.emit(TerminalSidebarEvent::SyncPathChanged(*enabled)); } + settings_panel::SettingsPanelEvent::PaneToolbarChanged(enabled) => { + cx.emit(TerminalSidebarEvent::PaneToolbarChanged(*enabled)); + } settings_panel::SettingsPanelEvent::CustomHighlightsChanged(rules) => { cx.emit(TerminalSidebarEvent::CustomHighlightsChanged(rules.clone())); } @@ -1551,7 +1556,11 @@ impl TerminalSidebar { /// 关闭扩展面板(不销毁视图,再次打开复用)。 pub fn close_extension_panel(&mut self, id: &str, cx: &mut Context) { - if let Some(entry) = self.extension_panels.iter_mut().find(|p| p.id.as_ref() == id) { + if let Some(entry) = self + .extension_panels + .iter_mut() + .find(|p| p.id.as_ref() == id) + { if entry.open { entry.open = false; cx.emit(TerminalSidebarEvent::PanelChanged(None)); @@ -1576,7 +1585,11 @@ impl TerminalSidebar { placement: SidebarPlacement, cx: &mut Context, ) { - if let Some(entry) = self.extension_panels.iter_mut().find(|p| p.id.as_ref() == id) { + if let Some(entry) = self + .extension_panels + .iter_mut() + .find(|p| p.id.as_ref() == id) + { if entry.placement != placement { entry.placement = placement; cx.emit(TerminalSidebarEvent::PanelChanged(None)); @@ -1598,7 +1611,11 @@ impl TerminalSidebar { let Some(view) = extension_panels::open_terminal_extension_panel(id, &colors, cx) else { return false; }; - match self.extension_panels.iter_mut().find(|p| p.id.as_ref() == id) { + match self + .extension_panels + .iter_mut() + .find(|p| p.id.as_ref() == id) + { Some(entry) => { entry.view = Some(view); true @@ -1772,7 +1789,11 @@ impl TerminalSidebar { let header_bg = self.colors.muted; let text = self.colors.foreground; let title = entry.title.clone(); - let icon = entry.icon.clone().with_size(IconSize::Small).text_color(text); + let icon = entry + .icon + .clone() + .with_size(IconSize::Small) + .text_color(text); let close_id = entry.id.clone(); let header = PanelHeader::new(SharedString::from(format!( @@ -2244,28 +2265,26 @@ impl TerminalSidebar { .border_color(border_color) .justify_between() .child( - v_flex().items_center().py_2().gap_1().children( - self.tool_dock - .panels - .iter() - .copied() - .map(|panel| self.render_toolbar_button(panel, window, cx)), - ) - .when(!self.extension_panels.is_empty(), |this| { - this.child( - div() - .w(px(16.0)) - .h(px(1.0)) - .my_1() - .bg(self.colors.border), + v_flex() + .items_center() + .py_2() + .gap_1() + .children( + self.tool_dock + .panels + .iter() + .copied() + .map(|panel| self.render_toolbar_button(panel, window, cx)), ) - }) - .children( - self.extension_panels - .iter() - .map(|entry| self.render_extension_toolbar_button(entry, window, cx)) - .collect::>(), - ), + .when(!self.extension_panels.is_empty(), |this| { + this.child(div().w(px(16.0)).h(px(1.0)).my_1().bg(self.colors.border)) + }) + .children( + self.extension_panels + .iter() + .map(|entry| self.render_extension_toolbar_button(entry, window, cx)) + .collect::>(), + ), ) .into_any_element() } @@ -2461,7 +2480,13 @@ impl Render for TerminalSidebarToolbar { }), ) .when(!snapshot.extension_buttons.is_empty(), |this| { - this.child(div().w(px(16.0)).h(px(1.0)).my_1().bg(snapshot.colors.border)) + this.child( + div() + .w(px(16.0)) + .h(px(1.0)) + .my_1() + .bg(snapshot.colors.border), + ) }) .children(snapshot.extension_buttons.iter().cloned().map(|button| { self.render_extension_button(button, item_size, &snapshot.colors, cx) @@ -2513,9 +2538,10 @@ impl Render for TerminalSidebar { .h_full() .flex_shrink_0() .bg(bg_color) - .when(active_panel.is_some() || active_extension.is_some(), |this| { - this.w_full() - }) + .when( + active_panel.is_some() || active_extension.is_some(), + |this| this.w_full(), + ) .when( active_panel.is_none() && active_extension.is_none(), |this| this.w(TOOLBAR_WIDTH), @@ -2554,9 +2580,9 @@ impl Render for TerminalSidebar { mod tests { use super::{ SidebarPanel, TerminalToolDockState, agent_theme_from_terminal_theme, - extension_panel_placement_key, - build_live_terminal_ai_context, build_terminal_ai_context, terminal_ai_system_instruction, - terminal_sidebar_available_panels, workspace_theme_from_terminal_colors, + build_live_terminal_ai_context, build_terminal_ai_context, extension_panel_placement_key, + terminal_ai_system_instruction, terminal_sidebar_available_panels, + workspace_theme_from_terminal_colors, }; use crate::theme::{TerminalColors, TerminalTheme}; use agent_runtime::{ResourceCapability, ResourceKind, ResourceRef}; @@ -2990,10 +3016,9 @@ mod tests { assert!(dock.apply_persisted_placements(&persisted).is_empty()); - assert!(dock.update_available_panels([ - SidebarPanel::Settings, - SidebarPanel::ServerMonitor, - ])); + assert!( + dock.update_available_panels([SidebarPanel::Settings, SidebarPanel::ServerMonitor,]) + ); assert_eq!( dock.apply_persisted_placements(&persisted), vec![SidebarPanel::ServerMonitor] diff --git a/crates/terminal_view/src/sidebar/server_monitor_panel.rs b/crates/terminal_view/src/sidebar/server_monitor_panel.rs index 74d75b43b..4f9038846 100644 --- a/crates/terminal_view/src/sidebar/server_monitor_panel.rs +++ b/crates/terminal_view/src/sidebar/server_monitor_panel.rs @@ -160,6 +160,9 @@ if df -kP -x tmpfs -x devtmpfs -x overlay >/dev/null 2>&1; then fi echo "network:" +if [ -r /proc/uptime ]; then + emit_number "uptime" "$(cut -d' ' -f1 /proc/uptime)" +fi echo " interfaces:" if [ -d /sys/class/net ]; then for nic in /sys/class/net/*; do @@ -501,9 +504,10 @@ struct ProcessStats { top_memory: Vec, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct NetworkTotals { interfaces: Vec, + sampled_at_uptime: Option, } #[derive(Clone, Debug, PartialEq)] @@ -525,8 +529,15 @@ impl NetworkTotals { tx_total, }) .collect(), + sampled_at_uptime: None, } } + + #[cfg(test)] + fn with_uptime(mut self, uptime: f64) -> Self { + self.sampled_at_uptime = Some(uptime); + self + } } #[derive(Clone, Debug, PartialEq)] @@ -1860,11 +1871,16 @@ pub fn sample_network_rates( } } + let interval_secs = if interval_secs > 0.0 { + interval_secs + } else { + 1.0 + }; NetworkRateSample { rx_delta, tx_delta, - rx_bytes_per_sec: rx_delta as f64 / interval_secs.max(1.0), - tx_bytes_per_sec: tx_delta as f64 / interval_secs.max(1.0), + rx_bytes_per_sec: rx_delta as f64 / interval_secs, + tx_bytes_per_sec: tx_delta as f64 / interval_secs, } } @@ -2137,6 +2153,7 @@ fn parse_network_totals(section: &BTreeMap) -> NetworkTotals { }) }) .collect(), + sampled_at_uptime: section.get("uptime").and_then(|value| parse_f64(value)), } } @@ -2285,10 +2302,12 @@ pub struct HostResourceUsage { pub memory_percent: Option, pub disk_total_kib: Option, pub disk_percent: Option, + pub network_rx_bytes_per_sec: Option, + pub network_tx_bytes_per_sec: Option, } impl HostResourceUsage { - /// 生成卡片上的一行摘要;三项都拿不到时返回 None。 + /// 生成卡片上的一行摘要;所有指标都拿不到时返回 None。 pub fn summary(&self) -> Option { let mut parts = Vec::new(); if let Some(cpu) = self.cpu_percent { @@ -2300,10 +2319,25 @@ impl HostResourceUsage { if let Some(disk) = self.disk_percent { parts.push(format!("磁盘 {disk:.0}%")); } + if let (Some(rx), Some(tx)) = (self.network_rx_bytes_per_sec, self.network_tx_bytes_per_sec) + { + parts.push(format!( + "网速 ↑{} ↓{}", + format_bytes_per_sec(tx), + format_bytes_per_sec(rx) + )); + } (!parts.is_empty()).then(|| parts.join(" · ")) } } +#[derive(Default)] +struct ProbeSample { + uptime: Option, + cpu_snapshots: Vec, + network_totals: NetworkTotals, +} + /// 用一次性后台 SSH 会话采集远端资源占用(#279)。 /// /// 采集结束后立即断开,不占用终端页签;失败时把错误原样返回, @@ -2317,14 +2351,22 @@ pub async fn probe_host_resource_usage( let parsed = payload.and_then(|payload| parse_server_stats(&payload)); let stats = parsed?; tokio::time::sleep(Duration::from_millis(250)).await; - let next_cpu_snapshot = collect_cpu_snapshot(session_manager.clone()) + let next_sample = collect_probe_sample(session_manager.clone()) .await .ok() .unwrap_or_default(); session_manager.disconnect().await.ok(); let cpu_percent = (stats.cpu_snapshots.iter().any(|item| item.name == "cpu") - && next_cpu_snapshot.iter().any(|item| item.name == "cpu")) - .then(|| sample_cpu_usage(&stats.cpu_snapshots, &next_cpu_snapshot).total_percent); + && next_sample + .cpu_snapshots + .iter() + .any(|item| item.name == "cpu")) + .then(|| sample_cpu_usage(&stats.cpu_snapshots, &next_sample.cpu_snapshots).total_percent); + let network_rate = stats.network_totals.as_ref().and_then(|previous| { + network_sampling_interval(previous, &next_sample.network_totals).map(|interval_secs| { + sample_network_rates(previous, &next_sample.network_totals, interval_secs) + }) + }); let disk_total_kib = stats .disks .iter() @@ -2357,18 +2399,94 @@ pub async fn probe_host_resource_usage( memory_percent: stats.memory.as_ref().map(|memory| memory.used_percent()), disk_total_kib, disk_percent: stats.disks.iter().map(|disk| disk.percent).reduce(f64::max), + network_rx_bytes_per_sec: network_rate.as_ref().map(|sample| sample.rx_bytes_per_sec), + network_tx_bytes_per_sec: network_rate.as_ref().map(|sample| sample.tx_bytes_per_sec), }) } -async fn collect_cpu_snapshot(session_manager: Arc) -> Result> { +async fn collect_probe_sample(session_manager: Arc) -> Result { let output = exec_capture( &session_manager, - "awk '/^cpu[0-9]* / { total = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11; print $1, $2, $4, $5, total }' /proc/stat", + r#" +if [ -r /proc/uptime ]; then + printf 'uptime %s\n' "$(cut -d' ' -f1 /proc/uptime)" +fi +awk '/^cpu[0-9]* / { total = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11; print "cpu", $1, $2, $4, $5, total }' /proc/stat +if [ -d /sys/class/net ]; then + for nic in /sys/class/net/*; do + name="$(basename "$nic")" + case "$name" in + lo|docker0|veth*|br-*) continue ;; + esac + [ -r "$nic/statistics/rx_bytes" ] || continue + printf 'network %s %s %s\n' "$name" "$(cat "$nic/statistics/rx_bytes")" "$(cat "$nic/statistics/tx_bytes")" + done +fi +"#, ) .await?; - Ok(parse_cpu_snapshot_output(&output)) + Ok(parse_probe_sample_output(&output)) } +fn parse_probe_sample_output(output: &str) -> ProbeSample { + let mut sample = ProbeSample::default(); + for line in output.lines() { + let mut fields = line.split_whitespace(); + match fields.next() { + Some("uptime") => { + sample.uptime = fields.next().and_then(|value| value.parse().ok()); + } + Some("cpu") => { + let Some(name) = fields.next() else { + continue; + }; + let Some(load_user) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + let Some(load_system) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + let Some(load_idle) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + let Some(load_total) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + sample.cpu_snapshots.push(CpuSnapshot { + name: name.to_string(), + load_user, + load_system, + load_idle, + load_total, + }); + } + Some("network") => { + let Some(name) = fields.next() else { + continue; + }; + let Some(rx_total) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + let Some(tx_total) = fields.next().and_then(|value| value.parse().ok()) else { + continue; + }; + sample + .network_totals + .interfaces + .push(NetworkInterfaceTotal { + name: name.to_string(), + rx_total, + tx_total, + }); + } + _ => {} + } + } + sample.network_totals.sampled_at_uptime = sample.uptime; + sample +} + +#[cfg(test)] fn parse_cpu_snapshot_output(output: &str) -> Vec { output .lines() @@ -2385,6 +2503,12 @@ fn parse_cpu_snapshot_output(output: &str) -> Vec { .collect() } +fn network_sampling_interval(previous: &NetworkTotals, current: &NetworkTotals) -> Option { + let previous_uptime = previous.sampled_at_uptime?; + let current_uptime = current.sampled_at_uptime?; + (current_uptime > previous_uptime).then_some(current_uptime - previous_uptime) +} + /// 执行简单远端命令(不推送脚本),用于 legacy 清理等 best-effort 场景。 async fn exec_capture(session_manager: &Arc, command: &str) -> Result { let mut channel = session_manager.open_channel().await?; @@ -2510,8 +2634,9 @@ mod tests { AcceleratorVendor, CpuSnapshot, HistoryLimit, HostResourceUsage, MemoryStats, NetworkTotals, ProcessEntry, REMOTE_MONITOR_SCRIPT, build_collect_command, build_legacy_cleanup_command, history_points, history_tick_margin, - parse_cpu_snapshot_output, parse_server_stats, push_history_point, sample_cpu_usage, - sample_network_rates, split_sections, + network_sampling_interval, parse_cpu_snapshot_output, parse_probe_sample_output, + parse_server_stats, push_history_point, sample_cpu_usage, sample_network_rates, + split_sections, }; #[test] @@ -2525,6 +2650,8 @@ mod tests { memory_percent: None, disk_total_kib: None, disk_percent: Some(51.6), + network_rx_bytes_per_sec: None, + network_tx_bytes_per_sec: None, } .summary() .as_deref(), @@ -2539,12 +2666,34 @@ mod tests { memory_percent: None, disk_total_kib: None, disk_percent: None, + network_rx_bytes_per_sec: None, + network_tx_bytes_per_sec: None, } .summary(), None ); } + #[test] + fn host_resource_usage_summary_includes_network_rates() { + assert_eq!( + HostResourceUsage { + os_name: None, + cpu_cores: None, + cpu_percent: None, + memory_total_kib: None, + memory_percent: None, + disk_total_kib: None, + disk_percent: None, + network_rx_bytes_per_sec: Some(3_000.0), + network_tx_bytes_per_sec: Some(1_536.0), + } + .summary() + .as_deref(), + Some("网速 ↑1.5K/s ↓2.9K/s") + ); + } + #[test] fn host_metrics_cpu_snapshot_parser_reads_total_and_cores() { let snapshots = parse_cpu_snapshot_output( @@ -2559,6 +2708,39 @@ mod tests { assert_eq!(snapshots[0].load_total, 1000); } + #[test] + fn probe_sample_parser_reads_cpu_network_and_remote_uptime() { + let sample = parse_probe_sample_output( + "uptime 123.25\ncpu cpu 100 40 860 1000\ncpu cpu0 50 20 430 500\nnetwork eth0 4000 5000\nnetwork ens5 8000 9000\n", + ); + + assert_eq!(sample.uptime, Some(123.25)); + assert_eq!(sample.cpu_snapshots.len(), 2); + assert_eq!(sample.cpu_snapshots[0].name, "cpu"); + assert_eq!(sample.network_totals.interfaces.len(), 2); + assert_eq!(sample.network_totals.interfaces[1].name, "ens5"); + assert_eq!(sample.network_totals.interfaces[1].rx_total, 8000); + assert_eq!(sample.network_totals.interfaces[1].tx_total, 9000); + assert_eq!(sample.network_totals.sampled_at_uptime, Some(123.25)); + } + + #[test] + fn network_sampling_interval_uses_remote_uptime_fraction() { + let previous = NetworkTotals::new(vec![("eth0", 1_000, 2_000)]).with_uptime(10.25); + let current = NetworkTotals::new(vec![("eth0", 1_150, 2_300)]).with_uptime(10.5); + + assert_eq!(network_sampling_interval(&previous, ¤t), Some(0.25)); + } + + #[test] + fn host_probe_samples_rediscover_network_totals_with_uptime() { + let source = include_str!("server_monitor_panel.rs"); + + assert!(REMOTE_MONITOR_SCRIPT.contains(r#"emit_number "uptime""#)); + assert!(source.contains(r#"'network %s %s %s\n'"#)); + assert!(source.contains("network_sampling_interval")); + } + #[test] fn split_sections_parses_nested_monitor_document() { let sections = split_sections( @@ -2800,6 +2982,17 @@ accelerators: assert_eq!(sampled.tx_delta, 1_500); } + #[test] + fn sample_network_rates_preserves_subsecond_probe_interval() { + let previous = NetworkTotals::new(vec![("eth0", 1_000, 2_000)]); + let current = NetworkTotals::new(vec![("eth0", 1_250, 2_500)]); + + let sampled = sample_network_rates(&previous, ¤t, 0.25); + + assert_eq!(sampled.rx_bytes_per_sec, 1_000.0); + assert_eq!(sampled.tx_bytes_per_sec, 2_000.0); + } + #[test] fn push_history_point_keeps_latest_points_only() { let mut history = vec![10.0, 20.0, 30.0]; diff --git a/crates/terminal_view/src/sidebar/settings_panel.rs b/crates/terminal_view/src/sidebar/settings_panel.rs index 836abc253..8b14bffca 100644 --- a/crates/terminal_view/src/sidebar/settings_panel.rs +++ b/crates/terminal_view/src/sidebar/settings_panel.rs @@ -163,6 +163,8 @@ pub enum SettingsPanelEvent { ShowLineNumbersChanged(bool), /// 路径同步开关变更 SyncPathChanged(bool), + /// 终端面板右上角悬浮工具条(分屏 + 录制)显隐 + PaneToolbarChanged(bool), /// 自定义高亮规则变更 CustomHighlightsChanged(Vec), } @@ -221,6 +223,8 @@ pub struct SettingsPanel { show_line_numbers: bool, /// 路径与终端同步开关 sync_path: bool, + /// 终端面板右上角悬浮工具条显隐 + pane_toolbar_visible: bool, /// 全局自定义高亮规则 custom_highlights: Vec, /// 是否有文件管理器面板(仅 SSH 终端有) @@ -257,6 +261,7 @@ impl SettingsPanel { let scrollback_lines = AppSettings::global(cx).terminal_scrollback_lines; let auto_session_logging = AppSettings::global(cx).terminal_auto_session_logging; + let pane_toolbar_visible = AppSettings::global(cx).terminal_show_pane_toolbar; let selection_highlight = AppSettings::global(cx).terminal_selection_highlight; let show_line_timestamps = AppSettings::global(cx).terminal_show_timestamps; let show_line_numbers = AppSettings::global(cx).terminal_show_line_numbers; @@ -431,6 +436,7 @@ impl SettingsPanel { confirm_multiline_paste: true, confirm_high_risk_command: true, auto_session_logging, + pane_toolbar_visible, auto_copy, autocomplete_enabled, suggestion_popup_enabled, @@ -533,9 +539,10 @@ impl SettingsPanel { return; } self.suggestion_popup_opacity = opacity; - self.suggestion_popup_opacity_slider.update(cx, |slider, cx| { - slider.set_value(opacity, window, cx); - }); + self.suggestion_popup_opacity_slider + .update(cx, |slider, cx| { + slider.set_value(opacity, window, cx); + }); cx.notify(); } @@ -1102,8 +1109,13 @@ impl SettingsPanel { let autocomplete_enabled = self.autocomplete_enabled; let suggestion_popup_enabled = self.suggestion_popup_enabled; // 百分比读数直接取滑块 state:拖动中面板要跟手,写入设置则等松手。 - let suggestion_popup_opacity_percent = - (self.suggestion_popup_opacity_slider.read(cx).value().start() * 100.0).round() as i32; + let suggestion_popup_opacity_percent = (self + .suggestion_popup_opacity_slider + .read(cx) + .value() + .start() + * 100.0) + .round() as i32; let middle_click_paste = self.middle_click_paste; let right_click_paste = self.right_click_paste; let paste_image_upload = self.paste_image_upload; @@ -1262,12 +1274,10 @@ impl SettingsPanel { .text_sm() .child(t!("Settings.suggestion_popup_opacity")), ) - .child( - div().text_xs().text_color(muted_fg).child(t!( - "Settings.suggestion_popup_opacity_value", - percent = suggestion_popup_opacity_percent - )), - ), + .child(div().text_xs().text_color(muted_fg).child(t!( + "Settings.suggestion_popup_opacity_value", + percent = suggestion_popup_opacity_percent + ))), ) .child( Slider::new(&self.suggestion_popup_opacity_slider) @@ -1424,6 +1434,51 @@ impl SettingsPanel { ) } + /// 终端面板右上角悬浮工具条(分屏 + 录制按钮)显隐。 + fn render_pane_toolbar_section(&self, cx: &mut Context) -> impl IntoElement { + let colors = self.colors(); + let border = colors.border; + let muted_fg = colors.muted_foreground; + + v_flex() + .gap_3() + .p_3() + .border_t_1() + .border_color(border) + .child( + v_flex() + .gap_2() + .child( + div() + .text_xs() + .font_weight(FontWeight::MEDIUM) + .text_color(muted_fg) + .child(t!("Settings.pane_toolbar_section").to_uppercase()), + ) + .child( + h_flex() + .items_center() + .justify_between() + .child(div().text_sm().child(t!("Settings.pane_toolbar"))) + .child( + Switch::new("pane-toolbar-switch") + .checked(self.pane_toolbar_visible) + .small() + .on_click(cx.listener(|this, checked: &bool, _window, cx| { + this.pane_toolbar_visible = *checked; + cx.emit(SettingsPanelEvent::PaneToolbarChanged(*checked)); + })), + ), + ) + .child( + div() + .text_xs() + .text_color(muted_fg) + .child(t!("Settings.pane_toolbar_help")), + ), + ) + } + /// 渲染文件管理器设置区域(仅 SSH 终端有文件管理器时显示) fn render_file_manager_section(&self, cx: &mut Context) -> impl IntoElement { let colors = self.colors(); @@ -1924,6 +1979,15 @@ mod tests { })); } + #[test] + fn pane_toolbar_visibility_is_configured_in_the_terminal_sidebar() { + let source = include_str!("settings_panel.rs"); + assert!(source.contains("Switch::new(\"pane-toolbar-switch\")")); + assert!(source.contains("SettingsPanelEvent::PaneToolbarChanged")); + let events = include_str!("../view/sidebar_events.rs"); + assert!(events.contains("settings.terminal_show_pane_toolbar = enabled")); + } + #[test] fn terminal_theme_list_uses_single_panel_scroll_container() { let source = include_str!("settings_panel.rs"); @@ -2005,6 +2069,7 @@ impl Render for SettingsPanel { .child(self.render_cursor_section(cx)) .child(self.render_safety_section(cx)) .child(self.render_session_logging_section(cx)) + .child(self.render_pane_toolbar_section(cx)) .when(has_file_manager, |el| { el.child(self.render_file_manager_section(cx)) }) diff --git a/crates/terminal_view/src/view.rs b/crates/terminal_view/src/view.rs index 8294b31c4..5ece7b80a 100644 --- a/crates/terminal_view/src/view.rs +++ b/crates/terminal_view/src/view.rs @@ -163,6 +163,7 @@ mod paste_confirm_dialog; mod paste_confirmation; mod performance_diagnostics; mod preferences; +mod recording_controls; mod recording_footer; mod recording_playback_config; mod recording_playback_controls; @@ -188,6 +189,7 @@ mod terminal_render; mod text_input; mod tool_dock; mod vi_input; +mod x11_status; mod zmodem_picker; use actions::*; @@ -304,14 +306,18 @@ pub struct TerminalView { local_command_running: bool, /// 上一次已向 TabContainer 广播的连接状态,用于在变化时刷新标签页徽标。 last_connection_status: Option, + /// X11 成功只在每次状态跃迁时轻提示一次,不占用终端底部空间。 + x11_ready_notified: bool, /// InlineSuggest 防抖任务(30ms 延迟刷新建议) suggestion_debounce: Option>, /// 当前 pane 是否正在等待用户选择录制文件保存目录。 recording_path_prompt_pending: bool, - /// 当前 pane 最近一次录制控制错误;在 command bar 中直接展示。 + /// 当前 pane 最近一次录制控制错误;在录制弹层中直接展示。 recording_control_error: Option, - /// 仅在录制时间持续增长时存在,用于每秒刷新 command bar。 + /// 仅在录制时间持续增长时存在,用于每秒刷新录制按钮。 recording_ticker: Option>, + /// 录制控制弹层是否打开;按钮位于 pane 右上角悬浮工具条。 + recording_controls_open: bool, /// 当前 pane 独占的 Playback seek 控件状态。 recording_playback_slider: Entity, /// 用户拖动期间只预览位置,Release 后才重建 Playback grid。 diff --git a/crates/terminal_view/src/view/command_bar/interaction.rs b/crates/terminal_view/src/view/command_bar/interaction.rs index 60ab8460d..7d94d4ef2 100644 --- a/crates/terminal_view/src/view/command_bar/interaction.rs +++ b/crates/terminal_view/src/view/command_bar/interaction.rs @@ -50,6 +50,7 @@ impl TerminalCommandBar { quick_command_panel, quick_search_state, quick_group_scroll_handle: ScrollHandle::new(), + quick_bar_scroll: ScrollHandle::new(), quick_scroll_handle: VirtualListScrollHandle::new(), quick_commands: Vec::new(), suggestions: Vec::new(), @@ -60,14 +61,11 @@ impl TerminalCommandBar { quick_group_filter: QuickGroupFilter::default(), selected_quick_command: None, quick_commands_open: false, - recording_controls_open: false, collapsed: true, input_height: COMMAND_BAR_INPUT_DEFAULT_HEIGHT, autocomplete_enabled: true, suggestion_popup_enabled: true, colors: config.colors, - recording_path_prompt_pending: false, - recording_control_error: None, _subscriptions: subscriptions, }; this.load_quick_commands(cx); @@ -138,21 +136,6 @@ impl TerminalCommandBar { cx.notify(); } - pub(in crate::view) fn set_session_controls_state( - &mut self, - recording_path_prompt_pending: bool, - recording_control_error: Option, - cx: &mut Context, - ) { - self.recording_path_prompt_pending = recording_path_prompt_pending; - self.recording_control_error = recording_control_error; - cx.notify(); - } - - pub(in crate::view) fn refresh_session_controls(&mut self, cx: &mut Context) { - cx.notify(); - } - pub(in crate::view) fn load_quick_commands(&mut self, cx: &mut Context) { self.quick_commands = cx .try_global::() @@ -364,21 +347,12 @@ impl TerminalCommandBar { window: &mut Window, cx: &mut Context, ) { - if event.keystroke.key == "escape" && self.recording_controls_open { - self.close_recording_controls(window, cx); - cx.stop_propagation(); - return; - } if !self.input_has_focus(window, cx) { return; } let handled = match event.keystroke.key.as_str() { "tab" if !self.suggestions.is_empty() => self.accept_selection(window, cx), - "escape" - if !self.suggestions.is_empty() - || self.quick_commands_open - || self.recording_controls_open => - { + "escape" if !self.suggestions.is_empty() || self.quick_commands_open => { self.reset_overlays(cx); cx.notify(); true @@ -397,9 +371,8 @@ impl TerminalCommandBar { .is_focused(window) } - pub(super) fn reset_overlays(&mut self, cx: &mut Context) { + pub(in crate::view) fn reset_overlays(&mut self, cx: &mut Context) { self.quick_commands_open = false; - self.recording_controls_open = false; self.selected_quick_command = None; self.suggestions.clear(); self.selected_suggestion = None; @@ -407,35 +380,6 @@ impl TerminalCommandBar { self.clear_inline_completion(cx); } - pub(super) fn toggle_recording_controls( - &mut self, - window: &mut Window, - cx: &mut Context, - ) { - if self.recording_controls_open { - self.close_recording_controls(window, cx); - return; - } - self.recording_controls_open = true; - self.quick_commands_open = false; - self.selected_quick_command = None; - self.suggestions.clear(); - self.selected_suggestion = None; - self.clear_inline_completion(cx); - cx.notify(); - } - - pub(super) fn close_recording_controls(&mut self, window: &mut Window, cx: &mut Context) { - self.recording_controls_open = false; - if self.collapsed { - cx.emit(TerminalCommandBarEvent::FocusTerminal); - cx.notify(); - } else { - self.focus_input(window, cx); - self.refresh_suggestions(cx); - } - } - pub(super) fn clear_inline_completion(&self, cx: &mut Context) { let _ = cx; } diff --git a/crates/terminal_view/src/view/command_bar/mod.rs b/crates/terminal_view/src/view/command_bar/mod.rs index 0ea7644d8..7d934f991 100644 --- a/crates/terminal_view/src/view/command_bar/mod.rs +++ b/crates/terminal_view/src/view/command_bar/mod.rs @@ -12,11 +12,11 @@ use terminal::terminal::Terminal; pub(super) const COMMAND_BAR_INPUT_DEFAULT_HEIGHT: f32 = 80.0; mod interaction; +mod quick_bar; mod quick_interaction; mod quick_render; mod quick_render_list; mod quick_render_sidebar; -mod recording_render; mod render; mod suggestion_render; @@ -25,10 +25,6 @@ pub(super) enum TerminalCommandBarEvent { Submit(String), InputToPty(String), FocusTerminal, - StartRecording, - PauseRecording, - ResumeRecording, - StopRecording, } pub(super) struct TerminalCommandBarConfig { @@ -52,6 +48,7 @@ pub(super) struct TerminalCommandBar { quick_command_panel: Entity, quick_search_state: Entity, quick_group_scroll_handle: ScrollHandle, + quick_bar_scroll: ScrollHandle, quick_scroll_handle: VirtualListScrollHandle, quick_commands: Vec, suggestions: Vec, @@ -62,14 +59,11 @@ pub(super) struct TerminalCommandBar { quick_group_filter: QuickGroupFilter, selected_quick_command: Option, quick_commands_open: bool, - recording_controls_open: bool, collapsed: bool, input_height: f32, autocomplete_enabled: bool, suggestion_popup_enabled: bool, colors: TerminalColors, - recording_path_prompt_pending: bool, - recording_control_error: Option, _subscriptions: Vec, } diff --git a/crates/terminal_view/src/view/command_bar/quick_bar.rs b/crates/terminal_view/src/view/command_bar/quick_bar.rs new file mode 100644 index 000000000..0e98a9c70 --- /dev/null +++ b/crates/terminal_view/src/view/command_bar/quick_bar.rs @@ -0,0 +1,170 @@ +//! 命令栏折叠行里的置顶快捷指令横条。 +//! +//! 这一行本身就是快捷指令栏:有置顶(pinned)指令时直接横向展示 chips。 +//! 点击 chip 复用 +//! [`TerminalCommandBar::choose_command`],因此 {{参数}} 填写、自动执行标记与 +//! 折叠态写入 PTY 的行为和弹层列表完全一致。 + +use super::*; +use crate::view::command_bar::quick_render::group_color; +use gpui::{ + AnyElement, Context, Hsla, InteractiveElement, IntoElement, ParentElement, + StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px, +}; +use gpui_component::{ActiveTheme, Icon, Sizable as _, h_flex, tooltip::Tooltip}; +use one_assets::IconName; +use rust_i18n::t; + +const QUICK_CHIP_HEIGHT: f32 = 24.0; +const QUICK_CHIP_MAX_WIDTH: f32 = 180.0; + +/// 过滤出需要常驻展示的置顶快捷指令,并保留仓储层已排序的顺序。 +pub(super) fn pinned_quick_commands(commands: &[QuickCommand]) -> Vec<&QuickCommand> { + commands.iter().filter(|command| command.pinned).collect() +} + +/// chip 文案优先使用名称;没有名称时退回命令首行,避免多行命令撑破横条。 +pub(super) fn quick_command_chip_label(command: &QuickCommand) -> String { + command + .name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| { + command + .command + .lines() + .next() + .unwrap_or_default() + .trim() + .to_string() + }) +} + +fn quick_command_chip_tooltip(command: &QuickCommand) -> String { + let mut text = if command + .name + .as_deref() + .is_some_and(|name| !name.trim().is_empty()) + { + format!( + "{}\n{}", + quick_command_chip_label(command), + command.command.trim() + ) + } else { + command.command.trim().to_string() + }; + if let Some(description) = command + .description + .as_deref() + .map(str::trim) + .filter(|description| !description.is_empty()) + { + text.push('\n'); + text.push_str(description); + } + text +} + +impl TerminalCommandBar { + /// 还没有置顶指令时的占位提示:告诉用户置顶后会显示在这里。 + fn render_quick_bar_hint(&self) -> AnyElement { + h_flex() + .id("terminal-quick-bar-hint") + .flex_1() + .min_w_0() + .items_center() + .gap_1() + .px_1() + .tooltip(|window, cx| { + Tooltip::new(t!("TerminalCommandBar.quick_bar_hint_tooltip").to_string()) + .build(window, cx) + }) + .child( + Icon::new(IconName::Pin) + .xsmall() + .text_color(self.colors.muted_foreground), + ) + .child( + div() + .min_w_0() + .truncate() + .text_xs() + .text_color(self.colors.muted_foreground) + .child(t!("TerminalCommandBar.quick_bar_hint").to_string()), + ) + .into_any_element() + } + + /// 折叠行左侧的 chip 滚动区。 + pub(super) fn render_pinned_quick_chips(&self, cx: &mut Context) -> AnyElement { + if pinned_quick_commands(&self.quick_commands).is_empty() { + return self.render_quick_bar_hint().into_any_element(); + } + let border = self.colors.border; + let muted = self.colors.muted; + let foreground = self.colors.foreground; + let accent = self.colors.accent; + let radius = cx.theme().radius; + let chips = pinned_quick_commands(&self.quick_commands) + .into_iter() + .enumerate() + .map(|(index, command)| { + let label = quick_command_chip_label(command); + let tooltip = quick_command_chip_tooltip(command); + let has_group = command.group_name.is_some() || command.group_color.is_some(); + let dot: Option = + has_group.then(|| group_color(command.group_color.as_deref(), accent)); + let value = command.command.clone(); + h_flex() + .id(("terminal-quick-bar-item", index)) + .flex_shrink_0() + .h(px(QUICK_CHIP_HEIGHT)) + .max_w(px(QUICK_CHIP_MAX_WIDTH)) + .min_w_0() + .items_center() + .gap_1() + .px_2() + .rounded(radius) + .border_1() + .border_color(border) + .cursor_pointer() + .overflow_hidden() + .hover(move |chip| chip.bg(muted)) + .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .on_click(cx.listener(move |this, _, window, cx| { + this.choose_command(value.clone(), window, cx); + })) + .when_some(dot, |chip, dot| { + chip.child(div().size_1p5().flex_shrink_0().rounded_full().bg(dot)) + }) + .child( + div() + .min_w_0() + .truncate() + .text_xs() + .font_family("monospace") + .text_color(foreground) + .child(label), + ) + }) + .collect::>(); + + h_flex() + .id("terminal-quick-bar-scroll") + .flex_1() + .min_w_0() + .items_center() + .gap_1() + .overflow_x_scroll() + .track_scroll(&self.quick_bar_scroll) + .children(chips) + .into_any_element() + } +} + +#[cfg(test)] +#[path = "quick_bar_tests.rs"] +mod tests; diff --git a/crates/terminal_view/src/view/command_bar/quick_bar_tests.rs b/crates/terminal_view/src/view/command_bar/quick_bar_tests.rs new file mode 100644 index 000000000..69b982524 --- /dev/null +++ b/crates/terminal_view/src/view/command_bar/quick_bar_tests.rs @@ -0,0 +1,92 @@ +use super::*; +use crate::view::command_bar::render::popover_offset_for; + +fn command(raw: &str) -> QuickCommand { + QuickCommand::new(raw.to_string()) +} + +fn named(command: QuickCommand, name: &str) -> QuickCommand { + let mut command = command; + command.name = Some(name.to_string()); + command +} + +#[test] +fn pinned_quick_commands_keeps_only_pinned_in_existing_order() { + let commands = vec![ + command("cd app").pinned(), + command("kubectl get pods"), + command("tail -f app.log").pinned(), + ]; + + let pinned = pinned_quick_commands(&commands) + .into_iter() + .map(|command| command.command.as_str()) + .collect::>(); + + assert_eq!(vec!["cd app", "tail -f app.log"], pinned); +} + +#[test] +fn chip_label_prefers_trimmed_name() { + let command = named( + command("kubectl rollout status deployment/app"), + " Deploy ", + ); + assert_eq!("Deploy", quick_command_chip_label(&command)); +} + +#[test] +fn chip_label_falls_back_to_first_command_line() { + let command = command(" cd app \nls -la"); + assert_eq!("cd app", quick_command_chip_label(&command)); +} + +#[test] +fn chip_label_ignores_blank_name() { + let command = named(command("cd job-client"), " "); + assert_eq!("cd job-client", quick_command_chip_label(&command)); +} + +#[test] +fn popover_offset_only_reserves_command_bar_body() { + // 折叠行本身就是快捷指令栏,不再额外占一行高度。 + assert_eq!(30.0 + 8.0, popover_offset_for(true, 80.0)); + assert_eq!(120.0 + 8.0, popover_offset_for(false, 120.0)); +} + +#[test] +fn quick_bar_reuses_shared_execution_path_and_scrolls_horizontally() { + let source = include_str!("quick_bar.rs"); + assert!( + source.contains(".overflow_x_scroll()"), + "置顶横条必须支持横向滚动" + ); + assert!( + source.contains("this.choose_command(value.clone(), window, cx)"), + "点击 chip 必须复用 choose_command,保证参数与自动执行行为一致" + ); + + let render = include_str!("render.rs"); + assert!( + render.contains("render_pinned_quick_chips"), + "折叠行必须直接挂载置顶 chip 横条" + ); + assert!( + render.contains("render_quick_command_icon_button"), + "快捷指令入口必须固定在折叠行右侧" + ); +} + +#[test] +fn quick_bar_hint_explains_where_pinned_commands_go() { + let source = include_str!("quick_bar.rs"); + assert!( + source.contains("quick_bar_hint"), + "没有置顶指令时需要提示置顶后会显示在这里" + ); + assert!( + source.contains("render_quick_bar_hint"), + "空状态提示要独立成段,便于后续复用与测试" + ); +} diff --git a/crates/terminal_view/src/view/command_bar/quick_interaction.rs b/crates/terminal_view/src/view/command_bar/quick_interaction.rs index 2af769882..a7d24e7c5 100644 --- a/crates/terminal_view/src/view/command_bar/quick_interaction.rs +++ b/crates/terminal_view/src/view/command_bar/quick_interaction.rs @@ -49,7 +49,6 @@ impl TerminalCommandBar { self.load_quick_commands(cx); self.refresh_quick_command_panel(cx); self.quick_commands_open = true; - self.recording_controls_open = false; self.suggestions.clear(); self.selected_suggestion = None; self.clear_inline_completion(cx); diff --git a/crates/terminal_view/src/view/command_bar/render.rs b/crates/terminal_view/src/view/command_bar/render.rs index eddc75026..f5ffc3bb0 100644 --- a/crates/terminal_view/src/view/command_bar/render.rs +++ b/crates/terminal_view/src/view/command_bar/render.rs @@ -24,6 +24,16 @@ const COMMAND_BAR_RESIZE_GRIP_HOVER_WIDTH: f32 = 48.0; const COMMAND_BAR_RESIZE_GRIP_HEIGHT: f32 = 2.0; const COMMAND_BAR_POPOVER_GAP: f32 = 8.0; +/// 弹层底边偏移:命令栏主体高度 + 间距。 +pub(super) fn popover_offset_for(collapsed: bool, input_height: f32) -> f32 { + let body_height = if collapsed { + COMMAND_BAR_COLLAPSED_HEIGHT + } else { + input_height + }; + body_height + COMMAND_BAR_POPOVER_GAP +} + #[derive(Clone)] struct CommandBarResize { entity_id: EntityId, @@ -39,11 +49,7 @@ impl Render for CommandBarResize { impl TerminalCommandBar { pub(super) fn popover_bottom_offset(&self) -> f32 { - if self.collapsed { - COMMAND_BAR_COLLAPSED_HEIGHT + COMMAND_BAR_POPOVER_GAP - } else { - self.input_height + COMMAND_BAR_POPOVER_GAP - } + popover_offset_for(self.collapsed, self.input_height) } fn render_resize_handle(&self, cx: &mut Context) -> AnyElement { @@ -104,63 +110,72 @@ impl TerminalCommandBar { cx.notify(); } + /// 折叠态这一行就是置顶快捷指令横条:左侧滚动展示 chips,右侧固定 + /// 「快捷指令」与「展开命令输入」两个图标按钮。没有置顶指令时左侧留空, + /// 避免把入口挤到左边。 fn render_toolbar(&self, cx: &mut Context) -> AnyElement { h_flex() .w_full() .h(px(COMMAND_BAR_COLLAPSED_HEIGHT)) .items_center() - .justify_between() - .child(self.render_toolbar_context(cx)) - .child(self.render_collapsed_hint(cx)) + .gap_1() + .child(self.render_pinned_quick_chips(cx)) + .child(self.render_quick_command_icon_button(cx)) + .child(self.render_command_input_toggle_button(cx)) .into_any_element() } - /// 折叠态把「命令输入」入口做成可点击的展开控件:用户会直接点这段文字, - /// 所以点击必须真的展开;按键说明由输入框 placeholder 承担,不另起一行。 - fn render_collapsed_hint(&self, cx: &mut Context) -> AnyElement { - Button::new("terminal-command-collapsed-hint") - .label(t!("TerminalCommandBar.collapsed_hint").to_string()) + /// 折叠态右侧的快捷指令入口:只显示图标,完整弹层里再做搜索、分组与编辑。 + fn render_quick_command_icon_button(&self, cx: &mut Context) -> AnyElement { + Button::new("terminal-command-quick") + .child( + h_flex() + .items_center() + .gap_1() + .child(Icon::new(IconName::QuickCommands).xsmall()) + .when(!self.quick_commands.is_empty(), |this| { + this.child( + div() + .text_xs() + .text_color(self.colors.muted_foreground) + .child(self.quick_commands.len().to_string()), + ) + }), + ) .custom( ButtonCustomVariant::new(cx) - .foreground(self.colors.muted_foreground) + .foreground(self.colors.foreground) .hover(self.colors.muted) .active(self.colors.muted), ) + .selected(self.quick_commands_open) .small() - .tooltip(t!("TerminalCommandBar.expand").to_string()) + .tooltip(if self.quick_commands_open { + t!("TerminalCommandBar.close_quick_commands").to_string() + } else { + t!("TerminalCommandBar.open_quick_commands").to_string() + }) .on_click(cx.listener(|this, _, window, cx| { - this.toggle_collapsed(window, cx); + this.toggle_quick_commands(window, cx); })) .into_any_element() } - fn render_toolbar_context(&self, cx: &mut Context) -> AnyElement { - h_flex() - .min_w_0() - .gap_1() - .items_center() - .child(self.render_terminal_toggle_button(cx)) - .child(self.render_quick_command_button(cx)) - .child(self.render_recording_button(cx)) - .into_any_element() - } - - fn render_terminal_toggle_button(&self, cx: &mut Context) -> AnyElement { - Button::new("terminal-command-terminal-toggle") + /// 展开 / 收起命令输入:入口固定在折叠行右侧,展开后同一按钮移到输入框 + /// 右侧,位置保持一致。 + fn render_command_input_toggle_button(&self, cx: &mut Context) -> AnyElement { + let chevron = if self.collapsed { + IconName::ChevronUp + } else { + IconName::ChevronDown + }; + Button::new("terminal-command-input-toggle") .child( h_flex() .items_center() - .gap_1() + .gap_0p5() .child(Icon::new(IconName::SquareTerminal).xsmall()) - .child( - Icon::new(if self.collapsed { - IconName::ChevronUp - } else { - IconName::ChevronDown - }) - .xsmall() - .flex_shrink_0(), - ), + .child(Icon::new(chevron).xsmall()), ) .custom( ButtonCustomVariant::new(cx) @@ -181,38 +196,11 @@ impl TerminalCommandBar { .into_any_element() } - fn render_quick_command_button(&self, cx: &mut Context) -> AnyElement { - Button::new("terminal-command-quick") - .icon(IconName::SquareTerminal) - .label(format!( - "{} · {}", - t!("TerminalCommandBar.quick_commands"), - self.quick_commands.len() - )) - .custom( - ButtonCustomVariant::new(cx) - .foreground(self.colors.foreground) - .hover(self.colors.muted) - .active(self.colors.muted), - ) - .selected(self.quick_commands_open) - .small() - .tooltip(if self.quick_commands_open { - t!("TerminalCommandBar.close_quick_commands").to_string() - } else { - t!("TerminalCommandBar.open_quick_commands").to_string() - }) - .on_click(cx.listener(|this, _, window, cx| { - this.toggle_quick_commands(window, cx); - })) - .into_any_element() - } - fn render_expanded_actions(&self, cx: &mut Context) -> AnyElement { h_flex() .gap_1() - .child(self.render_quick_command_button(cx)) - .child(self.render_recording_button(cx)) + .child(self.render_quick_command_icon_button(cx)) + .child(self.render_command_input_toggle_button(cx)) .into_any_element() } @@ -225,11 +213,6 @@ impl TerminalCommandBar { .items_start() .gap_1() .py_1() - .child( - div() - .flex_shrink_0() - .child(self.render_terminal_toggle_button(cx)), - ) .child( div().flex_1().min_w_0().h(px(self.input_height)).child( Textarea::new(&self.input_state) @@ -278,9 +261,6 @@ impl Render for TerminalCommandBar { .when(self.quick_commands_open, |bar| { bar.child(self.render_quick_commands(cx)) }) - .when(self.recording_controls_open, |bar| { - bar.child(self.render_recording_controls(cx)) - }) .when(self.collapsed, |bar| bar.child(self.render_toolbar(cx))) .when(!self.collapsed, |bar| { bar.child(self.render_resize_handle(cx)) diff --git a/crates/terminal_view/src/view/command_bar_events.rs b/crates/terminal_view/src/view/command_bar_events.rs index b5889841d..f63c4c33f 100644 --- a/crates/terminal_view/src/view/command_bar_events.rs +++ b/crates/terminal_view/src/view/command_bar_events.rs @@ -46,10 +46,6 @@ impl TerminalView { self.paste_text(command, window, cx); } TerminalCommandBarEvent::FocusTerminal => self.focus_terminal(window, cx), - TerminalCommandBarEvent::StartRecording => self.request_recording_start(cx), - TerminalCommandBarEvent::PauseRecording => self.request_recording_pause(cx), - TerminalCommandBarEvent::ResumeRecording => self.request_recording_resume(cx), - TerminalCommandBarEvent::StopRecording => self.request_recording_stop(cx), } } } diff --git a/crates/terminal_view/src/view/initialization.rs b/crates/terminal_view/src/view/initialization.rs index 042e6bf0f..3007c61b6 100644 --- a/crates/terminal_view/src/view/initialization.rs +++ b/crates/terminal_view/src/view/initialization.rs @@ -335,10 +335,12 @@ impl TerminalView { shell_prompt_input_active: false, local_command_running: false, last_connection_status: None, + x11_ready_notified: false, suggestion_debounce: None, recording_path_prompt_pending: false, recording_control_error: None, recording_ticker: None, + recording_controls_open: false, recording_playback_slider, recording_playback_slider_dragging: false, recording_playback_control_error: None, diff --git a/crates/terminal_view/src/view/command_bar/recording_render.rs b/crates/terminal_view/src/view/recording_controls.rs similarity index 64% rename from crates/terminal_view/src/view/command_bar/recording_render.rs rename to crates/terminal_view/src/view/recording_controls.rs index b84759f4c..6c047100e 100644 --- a/crates/terminal_view/src/view/command_bar/recording_render.rs +++ b/crates/terminal_view/src/view/recording_controls.rs @@ -1,20 +1,25 @@ +//! 终端录制按钮与弹层。 +//! +//! 录制入口从命令栏迁到 pane 右上角的悬浮工具条(分屏按钮旁)。状态与操作 +//! 仍由每个 `TerminalView` 独占:按钮只负责开关弹层,具体的开始/暂停/恢复/ +//! 停止直接调用 `request_recording_*`,不再经过命令栏事件。 + use super::*; use crate::view::recording_footer::{ RecordingFooterStatus, format_recording_elapsed, recording_snapshot_failure, }; use gpui::{ - AnyElement, Context, InteractiveElement, IntoElement, ParentElement, Styled, div, - prelude::FluentBuilder as _, px, + AnyElement, Context, Hsla, InteractiveElement, IntoElement, ParentElement, Styled, div, px, }; use gpui_component::{ - ActiveTheme, Disableable, Selectable, Sizable, - button::{Button, ButtonCustomVariant, ButtonVariants}, + ActiveTheme, Disableable, Sizable, + button::{Button, ButtonVariants}, h_flex, v_flex, }; use one_assets::IconName; use rust_i18n::t; -const RECORDING_POPOVER_WIDTH: f32 = 340.0; +pub(crate) const RECORDING_POPOVER_WIDTH: f32 = 340.0; struct RecordingControlsState { status: RecordingFooterStatus, @@ -23,7 +28,7 @@ struct RecordingControlsState { has_error: bool, } -impl TerminalCommandBar { +impl TerminalView { fn recording_controls_state(&self, cx: &mut Context) -> RecordingControlsState { let snapshot = self.terminal.read(cx).recording_snapshot(); let (status, elapsed, capture_input, runtime_error) = match snapshot { @@ -62,36 +67,47 @@ impl TerminalCommandBar { } } - pub(super) fn render_recording_button(&self, cx: &mut Context) -> AnyElement { + /// 悬浮工具条上的录制按钮状态:文案、状态色。 + pub(crate) fn recording_indicator(&self, cx: &mut Context) -> (SharedString, Hsla) { let state = self.recording_controls_state(cx); - let status_color = state.status.color(cx); + (state.status.label(), state.status.color(cx)) + } - Button::new("terminal-command-recording") - .child( - h_flex() - .items_center() - .gap_1() - .child(div().size_2().rounded_full().bg(status_color)) - .child(t!("TerminalRecording.control").to_string()), - ) - .custom( - ButtonCustomVariant::new(cx) - .foreground(self.colors.foreground) - .hover(self.colors.muted) - .active(self.colors.muted), + pub(crate) fn recording_controls_open(&self) -> bool { + self.recording_controls_open + } + + /// 非分屏时 pane 工具条默认悬浮才显示;录制中或弹层打开时必须常驻, + /// 否则用户看不到录制状态。 + pub(crate) fn recording_tool_visible(&self, cx: &mut Context) -> bool { + self.recording_controls_open || self.recording_path_prompt_pending || { + let state = self.recording_controls_state(cx); + matches!( + state.status, + RecordingFooterStatus::Recording + | RecordingFooterStatus::Paused + | RecordingFooterStatus::Stopping ) - .selected(self.recording_controls_open) - .small() - .tooltip(state.status.label()) - .on_click(cx.listener(|this, _, window, cx| { - this.toggle_recording_controls(window, cx); - })) - .into_any_element() + } + } + + pub(crate) fn toggle_recording_controls(&mut self, cx: &mut Context) { + if self.recording_controls_open { + self.recording_controls_open = false; + } else { + self.recording_controls_open = true; + self.command_bar.update(cx, |bar, cx| { + bar.reset_overlays(cx); + }); + } + cx.emit(TerminalPaneEvent::RecordingChanged); + cx.notify(); } - pub(super) fn render_recording_controls(&self, cx: &mut Context) -> AnyElement { + pub(crate) fn render_recording_popover(&self, cx: &mut Context) -> AnyElement { let state = self.recording_controls_state(cx); let status_color = state.status.color(cx); + let border = cx.theme().border; let is_active = matches!( state.status, RecordingFooterStatus::Recording @@ -100,35 +116,26 @@ impl TerminalCommandBar { ); v_flex() - .absolute() - .bottom(px(self.popover_bottom_offset())) - .right_3() .w(px(RECORDING_POPOVER_WIDTH)) .max_w(gpui::relative(0.96)) .overflow_hidden() .occlude() .rounded(cx.theme().radius) .border_1() - .border_color(self.colors.border) - .bg(self.colors.background) + .border_color(border) + .bg(cx.theme().background) .shadow_lg() - .on_mouse_down_out(cx.listener(|this, _, window, cx| { - let command_bar = cx.entity().downgrade(); - window.defer(cx, move |window, cx| { - let _ = command_bar.update(cx, |this, cx| { - if this.recording_controls_open { - this.close_recording_controls(window, cx); - } - }); - }); - let _ = this; + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.recording_controls_open = false; + cx.emit(TerminalPaneEvent::RecordingChanged); + cx.notify(); })) .child( h_flex() .items_center() .justify_between() .border_b_1() - .border_color(self.colors.border) + .border_color(border) .px_3() .py_2() .child( @@ -144,7 +151,7 @@ impl TerminalCommandBar { header.child( div() .text_xs() - .text_color(self.colors.muted_foreground) + .text_color(cx.theme().muted_foreground) .child(format_recording_elapsed(state.elapsed)), ) }), @@ -157,7 +164,7 @@ impl TerminalCommandBar { .text_color(if state.has_error { cx.theme().danger } else { - self.colors.muted_foreground + cx.theme().muted_foreground }) .child(state.detail), ) @@ -166,7 +173,7 @@ impl TerminalCommandBar { .justify_end() .gap_2() .border_t_1() - .border_color(self.colors.border) + .border_color(border) .px_3() .py_2() .children(self.render_recording_control_buttons(state.status, cx)), @@ -181,14 +188,14 @@ impl TerminalCommandBar { ) -> Vec { if status.can_start() { return vec![ - Button::new("terminal-command-recording-start") + Button::new("terminal-pane-recording-start") .icon(IconName::Play) .label(t!("TerminalRecording.start").to_string()) .primary() .small() .disabled(self.recording_path_prompt_pending) - .on_click(cx.listener(|_, _, _, cx| { - cx.emit(TerminalCommandBarEvent::StartRecording); + .on_click(cx.listener(|this, _, _, cx| { + this.request_recording_start(cx); })) .into_any_element(), ]; @@ -196,25 +203,25 @@ impl TerminalCommandBar { match status { RecordingFooterStatus::Recording => vec![ - Button::new("terminal-command-recording-pause") + Button::new("terminal-pane-recording-pause") .icon(IconName::Pause) .label(t!("TerminalRecording.pause").to_string()) .secondary() .small() - .on_click(cx.listener(|_, _, _, cx| { - cx.emit(TerminalCommandBarEvent::PauseRecording); + .on_click(cx.listener(|this, _, _, cx| { + this.request_recording_pause(cx); })) .into_any_element(), self.render_stop_recording_button(false, cx), ], RecordingFooterStatus::Paused => vec![ - Button::new("terminal-command-recording-resume") + Button::new("terminal-pane-recording-resume") .icon(IconName::Play) .label(t!("TerminalRecording.resume").to_string()) .secondary() .small() - .on_click(cx.listener(|_, _, _, cx| { - cx.emit(TerminalCommandBarEvent::ResumeRecording); + .on_click(cx.listener(|this, _, _, cx| { + this.request_recording_resume(cx); })) .into_any_element(), self.render_stop_recording_button(false, cx), @@ -229,14 +236,14 @@ impl TerminalCommandBar { } fn render_stop_recording_button(&self, disabled: bool, cx: &mut Context) -> AnyElement { - Button::new("terminal-command-recording-stop") + Button::new("terminal-pane-recording-stop") .icon(IconName::CircleX) .label(t!("TerminalRecording.stop").to_string()) .danger() .small() .disabled(disabled) - .on_click(cx.listener(|_, _, _, cx| { - cx.emit(TerminalCommandBarEvent::StopRecording); + .on_click(cx.listener(|this, _, _, cx| { + this.request_recording_stop(cx); })) .into_any_element() } diff --git a/crates/terminal_view/src/view/recording_footer.rs b/crates/terminal_view/src/view/recording_footer.rs index 5b90f0eb1..f0518d926 100644 --- a/crates/terminal_view/src/view/recording_footer.rs +++ b/crates/terminal_view/src/view/recording_footer.rs @@ -7,7 +7,7 @@ use terminal::recording::{ use uuid::Uuid; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum RecordingFooterStatus { +pub(crate) enum RecordingFooterStatus { Ready, Recording, Paused, @@ -17,7 +17,7 @@ pub(super) enum RecordingFooterStatus { } impl RecordingFooterStatus { - pub(super) fn from_recording_state(state: &RecordingState) -> Self { + pub(crate) fn from_recording_state(state: &RecordingState) -> Self { match state { RecordingState::Idle => Self::Ready, RecordingState::Recording => Self::Recording, @@ -28,7 +28,7 @@ impl RecordingFooterStatus { } } - pub(super) fn label(self) -> SharedString { + pub(crate) fn label(self) -> SharedString { match self { Self::Ready => t!("TerminalRecording.ready").to_string().into(), Self::Recording => t!("TerminalRecording.recording").to_string().into(), @@ -39,7 +39,7 @@ impl RecordingFooterStatus { } } - pub(super) fn color(self, cx: &App) -> Hsla { + pub(crate) fn color(self, cx: &App) -> Hsla { match self { Self::Ready => cx.theme().muted_foreground, Self::Recording => cx.theme().danger, @@ -49,7 +49,7 @@ impl RecordingFooterStatus { } } - pub(super) fn can_start(self) -> bool { + pub(crate) fn can_start(self) -> bool { matches!(self, Self::Ready | Self::Stopped | Self::Failed) } } @@ -98,8 +98,7 @@ impl TerminalView { self.recording_path_prompt_pending = true; self.recording_control_error = None; - self.sync_command_bar_session_controls(cx); - cx.notify(); + self.emit_recording_changed(cx); let future = cx.prompt_for_paths(PathPromptOptions { files: false, @@ -137,8 +136,7 @@ impl TerminalView { } this.sync_recording_ticker(cx); - this.sync_command_bar_session_controls(cx); - cx.notify(); + this.emit_recording_changed(cx); }); }) .detach(); @@ -169,7 +167,11 @@ impl TerminalView { Err(error) => self.recording_control_error = Some(error.to_string()), } self.sync_recording_ticker(cx); - self.sync_command_bar_session_controls(cx); + self.emit_recording_changed(cx); + } + + fn emit_recording_changed(&self, cx: &mut Context) { + cx.emit(TerminalPaneEvent::RecordingChanged); cx.notify(); } @@ -217,9 +219,7 @@ impl TerminalView { .update(cx, |this, cx| { let should_continue = this.recording_elapsed_is_advancing(cx); if should_continue { - this.command_bar.update(cx, |bar, cx| { - bar.refresh_session_controls(cx); - }); + cx.emit(TerminalPaneEvent::RecordingChanged); cx.notify(); } else { this.recording_ticker = None; @@ -233,18 +233,6 @@ impl TerminalView { } })); } - - pub(super) fn sync_command_bar_session_controls(&self, cx: &mut Context) { - let recording_path_prompt_pending = self.recording_path_prompt_pending; - let recording_control_error = self.recording_control_error.clone(); - self.command_bar.update(cx, |bar, cx| { - bar.set_session_controls_state( - recording_path_prompt_pending, - recording_control_error, - cx, - ); - }); - } } pub(super) fn recording_snapshot_failure(snapshot: &RecordingSnapshot) -> Option { diff --git a/crates/terminal_view/src/view/sidebar_events.rs b/crates/terminal_view/src/view/sidebar_events.rs index bea628bb5..40975edac 100644 --- a/crates/terminal_view/src/view/sidebar_events.rs +++ b/crates/terminal_view/src/view/sidebar_events.rs @@ -318,6 +318,12 @@ impl TerminalView { settings.sync_path_with_terminal = enabled; }); } + TerminalSidebarEvent::PaneToolbarChanged(enabled) => { + let enabled = *enabled; + AppSettings::update_and_save(cx, |settings| { + settings.terminal_show_pane_toolbar = enabled; + }); + } TerminalSidebarEvent::CustomHighlightsChanged(rules) => { let rules = rules.clone(); let _ = update_settings(cx, move |settings| { diff --git a/crates/terminal_view/src/view/terminal_events.rs b/crates/terminal_view/src/view/terminal_events.rs index f46c5e085..a571f0823 100644 --- a/crates/terminal_view/src/view/terminal_events.rs +++ b/crates/terminal_view/src/view/terminal_events.rs @@ -44,6 +44,7 @@ impl TerminalView { self.ensure_ssh_tool_panels(window, cx); self.sync_zmodem_background_task(None, cx); self.focus_terminal_after_connect_if_ready(window, cx); + self.notify_x11_ready_once(window, cx); self.refresh_history_prompt_matches(cx); cx.emit(TabContentEvent::ContentChanged); cx.notify(); diff --git a/crates/terminal_view/src/view/tests/layout.rs b/crates/terminal_view/src/view/tests/layout.rs index 696e4566f..e92da3792 100644 --- a/crates/terminal_view/src/view/tests/layout.rs +++ b/crates/terminal_view/src/view/tests/layout.rs @@ -262,7 +262,10 @@ fn terminal_render_owns_internal_tool_dock_regions() { assert!(render_source.contains("terminal-tool-dock-toolbar")); assert!(render_source.contains(".child(self.sidebar_toolbar.clone())")); // 右栏宽度必须按“合并后的边”算:只被扩展面板占用时也要留出面板宽度。 - assert!(render_source.contains("let has_right = layout.has_right() || extension_layout.has_right();")); + assert!( + render_source + .contains("let has_right = layout.has_right() || extension_layout.has_right();") + ); assert!(render_source.contains("sidebar_size + TOOLBAR_WIDTH")); } @@ -349,18 +352,31 @@ fn terminal_command_bar_is_only_rendered_for_live_terminal_input() { } #[test] -fn terminal_recording_controls_live_in_the_command_bar() { - let command_bar_source = include_str!("../command_bar/recording_render.rs"); +fn terminal_recording_controls_live_in_the_pane_tool() { + let recording_source = include_str!("../recording_controls.rs"); + let pane_tool_source = include_str!("../../workspace/pane_tool.rs"); let command_bar_layout_source = include_str!("../command_bar/render.rs"); let footer_source = include_str!("../recording_playback_render.rs"); - assert!(command_bar_layout_source.contains("render_recording_button")); - assert!(command_bar_layout_source.contains("render_recording_controls")); - assert!(command_bar_source.contains("terminal-command-recording\"")); - assert!(command_bar_source.contains("terminal-command-recording-start")); - assert!(command_bar_source.contains("terminal-command-recording-pause")); - assert!(command_bar_source.contains("terminal-command-recording-resume")); - assert!(command_bar_source.contains("terminal-command-recording-stop")); + assert!(pane_tool_source.contains("render_recording_button")); + assert!(pane_tool_source.contains("recording_tool_visible")); + assert!( + pane_tool_source.contains("terminal_show_pane_toolbar"), + "pane floating toolbar must honor the settings switch" + ); + assert!(!command_bar_layout_source.contains("render_recording_button")); + assert!(!command_bar_layout_source.contains("render_recording_controls")); + for button_id in [ + "terminal-pane-recording-start", + "terminal-pane-recording-pause", + "terminal-pane-recording-resume", + "terminal-pane-recording-stop", + ] { + assert!( + recording_source.contains(button_id), + "录制弹层按钮应挂在 pane 悬浮工具条下:`{button_id}`" + ); + } assert!(!footer_source.contains("self.render_recording_footer(cx)")); } @@ -506,7 +522,7 @@ fn terminal_viewport_bounds_preserves_the_grid_origin_when_clipped() { fn command_bar_recording_controls_are_pane_private_and_use_safe_terminal_apis() { let view_source = include_str!("../../view.rs"); let recording_source = include_str!("../recording_footer.rs"); - let command_bar_source = include_str!("../command_bar/recording_render.rs"); + let recording_controls_source = include_str!("../recording_controls.rs"); let event_source = include_str!("../command_bar_events.rs"); let render_source = include_str!("../render_layout.rs"); @@ -525,14 +541,21 @@ fn command_bar_recording_controls_are_pane_private_and_use_safe_terminal_apis() assert!(recording_source.contains(".pause_recording()")); assert!(recording_source.contains(".resume_recording()")); assert!(recording_source.contains(".stop_recording()")); - assert!(command_bar_source.contains("TerminalCommandBarEvent::StartRecording")); - assert!(command_bar_source.contains("TerminalCommandBarEvent::PauseRecording")); - assert!(command_bar_source.contains("TerminalCommandBarEvent::ResumeRecording")); - assert!(command_bar_source.contains("TerminalCommandBarEvent::StopRecording")); - assert!(event_source.contains("self.request_recording_start(cx)")); - assert!(event_source.contains("self.request_recording_pause(cx)")); - assert!(event_source.contains("self.request_recording_resume(cx)")); - assert!(event_source.contains("self.request_recording_stop(cx)")); + for direct_call in [ + "this.request_recording_start(cx)", + "this.request_recording_pause(cx)", + "this.request_recording_resume(cx)", + "this.request_recording_stop(cx)", + ] { + assert!( + recording_controls_source.contains(direct_call), + "录制按钮应直接调用终端 API,不再绕命令栏事件:`{direct_call}`" + ); + } + assert!(!event_source.contains("TerminalCommandBarEvent::StartRecording")); + assert!(!event_source.contains("TerminalCommandBarEvent::PauseRecording")); + assert!(!event_source.contains("TerminalCommandBarEvent::ResumeRecording")); + assert!(!event_source.contains("TerminalCommandBarEvent::StopRecording")); for action_handler in [ ".on_action(cx.listener(Self::start_recording_action))", @@ -545,14 +568,14 @@ fn command_bar_recording_controls_are_pane_private_and_use_safe_terminal_apis() } #[test] -fn command_bar_discloses_output_only_capture_and_visible_failures() { - let command_bar_source = include_str!("../command_bar/recording_render.rs"); - - assert!(command_bar_source.contains("TerminalRecording.output_only")); - assert!(command_bar_source.contains("TerminalRecording.input_included")); - assert!(command_bar_source.contains("recording_snapshot_failure(&snapshot)")); - assert!(command_bar_source.contains("recording_control_error")); - assert!(command_bar_source.contains("cx.theme().danger")); +fn recording_popover_discloses_output_only_capture_and_visible_failures() { + let recording_source = include_str!("../recording_controls.rs"); + + assert!(recording_source.contains("TerminalRecording.output_only")); + assert!(recording_source.contains("TerminalRecording.input_included")); + assert!(recording_source.contains("recording_snapshot_failure(&snapshot)")); + assert!(recording_source.contains("recording_control_error")); + assert!(recording_source.contains("cx.theme().danger")); } #[test] @@ -753,20 +776,31 @@ fn terminal_command_bar_keeps_oxideterm_keyboard_and_overlay_contracts() { assert!(interaction_source.contains("collapsed: true")); assert!(render_source.contains("COMMAND_BAR_INPUT_MIN_HEIGHT: f32 = 80.0")); assert!(render_source.contains("fn popover_bottom_offset(&self) -> f32")); - assert!(render_source.contains("self.input_height + COMMAND_BAR_POPOVER_GAP")); + assert!( + render_source.contains("popover_offset_for(self.collapsed, self.input_height)"), + "弹层偏移必须按命令栏主体高度计算(折叠行即快捷指令栏,不再额外占高)" + ); + assert!(render_source.contains("body_height + COMMAND_BAR_POPOVER_GAP")); // 折叠态不能展示输入框按键提示(输入框此时不可见,用户会误以为是终端自身的提示); // 展开态的按键说明由输入框 placeholder 承担,不另起一行,避免与 placeholder 重复。 - let collapsed_hint = render_source - .split("fn render_collapsed_hint") + let toolbar = render_source + .split("fn render_toolbar") .nth(1) - .and_then(|source| source.split("fn render_toolbar_context").next()) - .expect("collapsed hint control should exist"); - assert!(collapsed_hint.contains("TerminalCommandBar.collapsed_hint")); - assert!( - collapsed_hint.contains("this.toggle_collapsed(window, cx)"), - "collapsed hint text must expand the command bar when clicked" - ); - assert!(render_source.contains(".child(self.render_collapsed_hint(cx))")); + .and_then(|source| source.split("fn render_quick_command_icon_button").next()) + .expect("collapsed toolbar should exist"); + assert!(toolbar.contains("self.render_pinned_quick_chips(cx)")); + let chips_position = toolbar + .find("self.render_pinned_quick_chips(cx)") + .expect("pinned chips should render in the collapsed row"); + let quick_position = toolbar + .find("self.render_quick_command_icon_button(cx)") + .expect("quick-command entry should sit on the right side"); + let toggle_position = toolbar + .find("self.render_command_input_toggle_button(cx)") + .expect("command-input toggle should sit on the right side"); + assert!(chips_position < quick_position); + assert!(quick_position < toggle_position); + assert!(!render_source.contains("TerminalCommandBar.collapsed_hint")); assert!(!render_source.contains("TerminalCommandBar.keyboard_hint")); assert!(!render_source.contains("render_expanded_hint")); let command_bar_locale = include_str!("../../../locales/terminal_view.yml") @@ -819,20 +853,20 @@ fn terminal_command_bar_keeps_oxideterm_keyboard_and_overlay_contracts() { .nth(1) .and_then(|source| source.split("impl Render for TerminalCommandBar").next()) .expect("expanded command input row should exist"); - let terminal_toggle = render_source - .split("fn render_terminal_toggle_button") + let input_toggle = render_source + .split("fn render_command_input_toggle_button") .nth(1) .and_then(|source| source.split("fn render_quick_command_button").next()) - .expect("terminal toggle button should exist"); - assert!(terminal_toggle.contains("terminal-command-terminal-toggle")); - assert!(terminal_toggle.contains("IconName::SquareTerminal")); - assert!(terminal_toggle.contains("IconName::ChevronUp")); - assert!(terminal_toggle.contains("IconName::ChevronDown")); - assert!(!terminal_toggle.contains("self.target_label(cx)")); - assert!(terminal_toggle.contains(".selected(!self.collapsed)")); + .expect("command input toggle button should exist"); + assert!(input_toggle.contains("terminal-command-input-toggle")); + assert!(input_toggle.contains("IconName::SquareTerminal")); + assert!(input_toggle.contains("IconName::ChevronUp")); + assert!(input_toggle.contains("IconName::ChevronDown")); + assert!(!input_toggle.contains("self.target_label(cx)")); + assert!(input_toggle.contains(".selected(!self.collapsed)")); assert!(render_source.contains("this.toggle_collapsed(window, cx)")); assert!(expanded_row.contains("self.render_expanded_actions(cx)")); - assert!(expanded_row.contains("self.render_terminal_toggle_button(cx)")); + assert!(!expanded_row.contains("self.render_command_input_toggle_button(cx)")); assert!(!expanded_row.contains("IconName::ChevronRight")); assert!(!render_source.contains("terminal-command-collapse-toggle-expanded")); assert!(!render_source.contains("terminal-command-collapse-toggle\"")); @@ -842,18 +876,14 @@ fn terminal_command_bar_keeps_oxideterm_keyboard_and_overlay_contracts() { assert!(expanded_row.contains(".flex_shrink_0()")); assert!(!expanded_row.contains(".absolute()")); assert!(!render_source.contains("COMMAND_BAR_ACTIONS_WIDTH")); - let terminal_toggle_position = expanded_row - .find("self.render_terminal_toggle_button(cx)") - .expect("terminal toggle should render in the expanded row"); let input_position = expanded_row .find("Textarea::new(&self.input_state)") .expect("command input should render in the expanded row"); let actions_position = expanded_row .find("self.render_expanded_actions(cx)") .expect("expanded actions should render in the expanded row"); - assert!(terminal_toggle_position < input_position); assert!(input_position < actions_position); - assert!(render_source.contains("child(self.render_quick_command_button(cx))")); + assert!(render_source.contains("child(self.render_quick_command_icon_button(cx))")); assert!(render_source.contains("when(self.quick_commands_open")); let choose_quick_command = quick_interaction_source .split("pub(super) fn choose_command") @@ -901,19 +931,19 @@ fn terminal_command_bar_keeps_oxideterm_keyboard_and_overlay_contracts() { .contains("vertical_scrollbar(&self.quick_group_scroll_handle)") ); - let recording_source = include_str!("../command_bar/recording_render.rs"); - let command_bar_state_source = include_str!("../command_bar/mod.rs"); - assert!(command_bar_state_source.contains("recording_controls_open: bool")); - assert!(render_source.contains("self.render_recording_button(cx)")); - assert!(render_source.contains("when(self.recording_controls_open")); - assert!(recording_source.contains("terminal-command-recording\"")); - assert!(recording_source.contains("TerminalRecording.control")); + let recording_source = include_str!("../recording_controls.rs"); + let view_source = include_str!("../../view.rs"); + let pane_tool_source = include_str!("../../workspace/pane_tool.rs"); + let pane_render_source = include_str!("../../workspace/render.rs"); + assert!(view_source.contains("recording_controls_open: bool")); + assert!(pane_tool_source.contains("self.render_recording_button(pane_id, pane, cx)")); + assert!(pane_render_source.contains("recording_controls_open()")); + assert!(pane_render_source.contains("render_recording_popover(cx)")); + assert!(recording_source.contains("RECORDING_POPOVER_WIDTH")); + assert!(recording_source.contains("state.status.label()")); assert!(recording_source.contains("toggle_recording_controls")); - assert!(recording_source.contains("render_recording_controls")); - assert!(recording_source.contains("bottom(px(self.popover_bottom_offset()))")); assert!(recording_source.contains("relative(0.96)")); assert!(recording_source.contains("on_mouse_down_out")); - assert!(recording_source.contains("window.defer(cx")); } #[test] @@ -994,5 +1024,7 @@ fn extension_panel_frame_is_shared_by_both_render_modes() { assert!(frame.contains("sidebar.close_extension_panel(&remove_id, cx)")); assert!(include_str!("../tool_dock.rs").contains("render_extension_tool_panel_frame")); - assert!(include_str!("../../workspace/render.rs").contains("render_extension_tool_panel_frame")); + assert!( + include_str!("../../workspace/render.rs").contains("render_extension_tool_panel_frame") + ); } diff --git a/crates/terminal_view/src/view/workspace_support.rs b/crates/terminal_view/src/view/workspace_support.rs index dc3bb22bc..db85de6ca 100644 --- a/crates/terminal_view/src/view/workspace_support.rs +++ b/crates/terminal_view/src/view/workspace_support.rs @@ -8,6 +8,9 @@ pub(crate) enum TerminalPaneEvent { SaveAsConnection(StoredConnection), /// 请求关闭当前 pane:单 pane 标签由标签容器关闭整个标签页,多 pane 时只关这个 pane。 ClosePaneRequested, + /// 录制状态或录制弹层开关变化:pane 悬浮工具条与弹层由 workspace 渲染, + /// 需要跟着 pane 的状态重绘。 + RecordingChanged, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/terminal_view/src/view/x11_status.rs b/crates/terminal_view/src/view/x11_status.rs new file mode 100644 index 000000000..0386bb7d6 --- /dev/null +++ b/crates/terminal_view/src/view/x11_status.rs @@ -0,0 +1,56 @@ +use super::*; +use ssh::X11ForwardingStatus; + +fn session_notice( + x11_enabled: bool, + status: Option<&X11ForwardingStatus>, +) -> Option { + if !x11_enabled { + return None; + } + match status? { + X11ForwardingStatus::External { server } => { + Some(t!("TerminalX11.external", server = server).to_string()) + } + X11ForwardingStatus::Embedded { version, .. } => { + Some(t!("TerminalX11.embedded", version = version).to_string()) + } + X11ForwardingStatus::Disabled { .. } => None, + } +} + +fn take_session_notice( + notified: &mut bool, + x11_enabled: bool, + status: Option<&X11ForwardingStatus>, +) -> Option { + let Some(notice) = session_notice(x11_enabled, status) else { + *notified = false; + return None; + }; + if *notified { + return None; + } + *notified = true; + Some(notice) +} + +impl TerminalView { + pub(super) fn notify_x11_ready_once(&mut self, window: &mut Window, cx: &mut Context) { + let terminal = self.terminal.read(cx); + let x11_enabled = terminal + .ssh_config() + .is_some_and(|config| config.ssh_config.x11_forwarding); + let Some(notice) = take_session_notice( + &mut self.x11_ready_notified, + x11_enabled, + terminal.x11_status().as_ref(), + ) else { + return; + }; + window.push_notification(Notification::info(notice).autohide(true), cx); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/terminal_view/src/view/x11_status/tests.rs b/crates/terminal_view/src/view/x11_status/tests.rs new file mode 100644 index 000000000..ae25c611f --- /dev/null +++ b/crates/terminal_view/src/view/x11_status/tests.rs @@ -0,0 +1,74 @@ +use super::take_session_notice; +use ssh::X11ForwardingStatus; + +#[test] +fn missing_disabled_and_failed_sessions_have_no_notice() { + let mut notified = false; + let ready = X11ForwardingStatus::External { + server: "127.0.0.1:0".into(), + }; + assert!(take_session_notice(&mut notified, false, Some(&ready)).is_none()); + assert!(take_session_notice(&mut notified, true, None).is_none()); + assert!( + take_session_notice( + &mut notified, + true, + Some(&X11ForwardingStatus::Disabled { + reason: "Vulkan 支持不足".into(), + }), + ) + .is_none() + ); +} + +#[test] +fn successful_session_is_notified_once_per_ready_transition() { + let mut notified = false; + let ready = X11ForwardingStatus::External { + server: "127.0.0.1:0".into(), + }; + let notice = take_session_notice(&mut notified, true, Some(&ready)) + .expect("成功连接必须给出一次轻提示"); + assert!(notice.contains("127.0.0.1:0")); + assert!(take_session_notice(&mut notified, true, Some(&ready)).is_none()); + + assert!(take_session_notice(&mut notified, true, None).is_none()); + assert!(take_session_notice(&mut notified, true, Some(&ready)).is_some()); +} + +#[test] +fn session_notice_reads_only_the_terminal_backend_result() { + let source = include_str!("../x11_status.rs"); + assert!(source.contains(".x11_status()")); + assert!(!source.contains("current_status()")); + assert!(source.contains(".autohide(true)")); + + let terminal_source = include_str!("../../../../terminal/src/terminal.rs"); + let getter = terminal_source + .split("pub fn x11_status(&self)") + .nth(1) + .and_then(|tail| tail.split("\n }").next()) + .expect("Terminal::x11_status 应存在"); + assert!(getter.contains("self.backend")); + assert!( + !getter.contains("ssh_session_manager"), + "当前终端的 X11 请求完成前不得复用共享 transport 的旧状态" + ); +} + +#[test] +fn x11_never_renders_a_terminal_session_footer() { + let source = include_str!("../recording_playback_render.rs"); + assert!(!source.contains("render_x11_session_footer")); +} + +#[test] +fn session_notice_copy_exists_in_all_three_languages() { + for language in ["en", "zh-CN", "zh-HK"] { + rust_i18n::set_locale(language); + for key in ["TerminalX11.external", "TerminalX11.embedded"] { + assert_ne!(key, rust_i18n::t!(key), "{language} 缺少文案: {key}"); + } + } + rust_i18n::set_locale("en"); +} diff --git a/crates/terminal_view/src/workspace/actions.rs b/crates/terminal_view/src/workspace/actions.rs index 2a85d1ada..2e7d9ec8f 100644 --- a/crates/terminal_view/src/workspace/actions.rs +++ b/crates/terminal_view/src/workspace/actions.rs @@ -55,6 +55,7 @@ impl TerminalWorkspace { cx.emit(TerminalWorkspaceEvent::SaveAsConnection(connection.clone())); } // Ctrl+D 断开后再按一次:单 pane 标签关整个标签页,多 pane 只关当前 pane。 + TerminalPaneEvent::RecordingChanged => cx.notify(), TerminalPaneEvent::ClosePaneRequested => { if this.panes.len() <= 1 { cx.emit(TabContentEvent::CloseRequested); diff --git a/crates/terminal_view/src/workspace/pane_tool.rs b/crates/terminal_view/src/workspace/pane_tool.rs index 8f858f1d6..a91279919 100644 --- a/crates/terminal_view/src/workspace/pane_tool.rs +++ b/crates/terminal_view/src/workspace/pane_tool.rs @@ -13,6 +13,7 @@ use gpui_component::{ ActiveTheme as _, Disableable as _, Icon, Placement, Sizable as _, Size, h_flex, }; use one_assets::IconName; +use one_core::settings::AppSettings; use one_core::tab_container::DragTab; use rust_i18n::t; @@ -26,12 +27,19 @@ impl TerminalWorkspace { hover_group: SharedString, cx: &mut Context, ) -> AnyElement { + if !AppSettings::global(cx).terminal_show_pane_toolbar { + return gpui::Empty.into_any_element(); + } let active = self.active_pane_id == pane_id; let split = self.panes.len() > 1; let split_supported = self .panes .get(&pane_id) .is_some_and(|pane| pane.read(cx).duplicate_supported(cx)); + let pane = self.panes.get(&pane_id).cloned(); + let recording_visible = pane + .as_ref() + .is_some_and(|pane| pane.update(cx, |view, cx| view.recording_tool_visible(cx))); let workspace = cx.entity().downgrade(); let drag_source = split .then(|| self.external_tab_drag_source(pane_id, workspace.clone())) @@ -60,8 +68,11 @@ impl TerminalWorkspace { .border_color(border) .text_color(cx.theme().foreground) .when(cx.theme().shadow, |this| this.shadow_md()) - .invisible() - .group_hover(hover_group, |this| this.visible()) + .when(!recording_visible, |this| this.invisible()) + .when(!recording_visible, |this| { + this.group_hover(hover_group, |this| this.visible()) + }) + .child(self.render_recording_button(pane_id, pane, cx)) .child(self.render_split_button(pane_id, workspace, split_supported)) .into_any_element(); } @@ -89,6 +100,7 @@ impl TerminalWorkspace { .with_size(Size::XSmall), ) .child(self.render_drag_title(pane_id, title, drag_source, cx)) + .child(self.render_recording_button(pane_id, pane, cx)) .child(self.render_split_button(pane_id, workspace.clone(), split_supported)) .child(self.render_cancel_split_button(pane_id, workspace.clone())) .child(self.render_close_button(pane_id, workspace)) @@ -134,6 +146,27 @@ impl TerminalWorkspace { .into_any_element() } + fn render_recording_button( + &self, + pane_id: TerminalPaneId, + pane: Option>, + cx: &mut Context, + ) -> AnyElement { + let Some(pane) = pane else { + return div().into_any_element(); + }; + let (label, color) = pane.update(cx, |view, cx| view.recording_indicator(cx)); + Button::new(("terminal-pane-recording", pane_id.value())) + .ghost() + .xsmall() + .child(Icon::new(IconName::Record).xsmall().text_color(color)) + .tooltip(label) + .on_click(move |_, _, cx| { + pane.update(cx, |view, cx| view.toggle_recording_controls(cx)); + }) + .into_any_element() + } + fn render_split_button( &self, pane_id: TerminalPaneId, diff --git a/crates/terminal_view/src/workspace/render.rs b/crates/terminal_view/src/workspace/render.rs index a74634bcf..b0e3cfcbc 100644 --- a/crates/terminal_view/src/workspace/render.rs +++ b/crates/terminal_view/src/workspace/render.rs @@ -10,7 +10,9 @@ use one_core::tab_container::TabContent as _; use super::{TerminalPaneId, TerminalSplitNode, TerminalWorkspace}; use crate::sidebar::SidebarPanel; -use crate::sidebar::tool_dock::{render_extension_tool_panel_frame, render_internal_tool_panel_frame}; +use crate::sidebar::tool_dock::{ + render_extension_tool_panel_frame, render_internal_tool_panel_frame, +}; use crate::view::TerminalWorkspaceSidebarSnapshot; const TERMINAL_PANE_MIN_WIDTH: Pixels = px(240.0); @@ -76,6 +78,12 @@ impl TerminalWorkspace { } else { cx.theme().border }; + // 录制按钮在 pane 悬浮工具条里,弹层贴着工具条下方渲染,属于 pane 内部 + // 覆盖层,不占终端布局。 + let recording_popover = pane + .read(cx) + .recording_controls_open() + .then(|| pane.update(cx, |view, cx| view.render_recording_popover(cx))); let content = v_flex() .id(("terminal-workspace-pane", pane_id.value())) @@ -95,6 +103,9 @@ impl TerminalWorkspace { .child(pane), ) .child(self.render_pane_floating_tool(pane_id, title, hover_group, cx)) + .when_some(recording_popover, |this, popover| { + this.child(div().absolute().top(px(40.0)).right_2().child(popover)) + }) .into_any_element(); self.render_tab_drop_target(pane_id, content, cx) } diff --git a/crates/terminal_view/src/workspace/view.rs b/crates/terminal_view/src/workspace/view.rs index 306ac2fde..c054bba8e 100644 --- a/crates/terminal_view/src/workspace/view.rs +++ b/crates/terminal_view/src/workspace/view.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use gpui::{App, AppContext as _, Context, Entity, Subscription, Window}; use gpui_component::Icon; +use one_core::settings::AppSettings; use one_core::storage::models::StoredConnection; use terminal::LocalConfig; use terminal::terminal::TerminalConnectionKind; @@ -174,6 +175,8 @@ impl TerminalWorkspace { }; this.subscribe_to_pane(initial_pane_id, pane, window, cx); this.set_active_pane_metric_state(cx); + cx.observe_global::(|_, cx| cx.notify()) + .detach(); this } diff --git a/crates/windows_rdp_host/tests/contract.rs b/crates/windows_rdp_host/tests/contract.rs index e213cbbc6..72e8cf7b3 100644 --- a/crates/windows_rdp_host/tests/contract.rs +++ b/crates/windows_rdp_host/tests/contract.rs @@ -2847,12 +2847,12 @@ fn release_only_pull_requests_skip_the_platform_matrix() { " classify:", " test:", &[ - "if: ${{ github.event_name == 'pull_request' }}", "release_only: ${{ steps.check.outputs.release_only }}", "- uses: actions/checkout@v7", "fetch-depth: 0", "BASE_SHA: ${{ github.event.pull_request.base.sha }}", "python3 script/release_pr.py check", + "echo \"release_only=false\" >> \"$GITHUB_OUTPUT\"", ], ); assert_contains_all( diff --git a/crates/x11_component/Cargo.toml b/crates/x11_component/Cargo.toml new file mode 100644 index 000000000..bbce8b870 --- /dev/null +++ b/crates/x11_component/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "x11_component" +version = "0.1.0" +publish.workspace = true +edition.workspace = true + +[dependencies] +base64.workspace = true +dirs.workspace = true +ed25519-dalek.workspace = true +fs2.workspace = true +hex.workspace = true +libc.workspace = true +libloading.workspace = true +process-util.workspace = true +rand.workspace = true +semver.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +sysinfo = { workspace = true, features = ["system"] } +thiserror.workspace = true +tokio = { workspace = true, features = ["fs", "io-util", "net", "process"] } +tracing.workspace = true +x11_forwarding.workspace = true +zip.workspace = true + +[dev-dependencies] + +[lints] +workspace = true diff --git a/crates/x11_component/README.md b/crates/x11_component/README.md new file mode 100644 index 000000000..7d4cb90f4 --- /dev/null +++ b/crates/x11_component/README.md @@ -0,0 +1,43 @@ +# x11_component + +内置与本机 X11 服务的解析、签名安装和单实例进程管理。本期内置范围仅为 Windows x86_64/aarch64;macOS 保持 XQuartz 外部服务。 + +## 应用集成 + +- 启动时调用 `set_data_dir`,传入已经限定产品的数据目录;默认值为 `dirs::data_dir()/navop`,组件根目录只追加 `components/x11`。 +- 调用 `set_navop_version(env!("CARGO_PKG_VERSION").parse()?)`,清单的 `pinned_for_navop` 校验应用版本,而不是 yserver 版本。 +- 使用 `resolve_server(mode)` 获取共享代理;设置变化时调用 `set_configured_mode`。 +- `NAVOP_X11_YSERVER_PATH` 仅供开发/验收注入手动二进制,仍执行相同的 Vulkan、xauth、握手和进程生命周期检查。上游原版会监听所有网卡,因此 TCP 手动入口会 fail-closed。 + +## 内嵌构建 + +正式 Windows full 和 standalone-shell 的 x86_64 构建把完整签名 zip 编进 `navop.exe`。MSI、Burn、portable 和应用自更新都随 exe 携带组件,不依赖旁置资源。 + +```bash +python3 script/prepare-windows-x11-component.py \ + --target windows-x86_64 --output "$PWD/target/navop-x11-component.zip" +NAVOP_X11_BUNDLED_ARCHIVE="$PWD/target/navop-x11-component.zip" \ + cargo build --release -p navop +``` + +准备脚本只接受仓库内固定清单的版本和构建脚本中的固定 URL,在构建前执行 SHA-256 与 Ed25519 验签;`build.rs` 不联网。支持的目标为 `windows-x86_64`、`windows-aarch64`,路径必须是绝对路径。当前 Navop 没有 Windows aarch64 产品 target;Win32、standalone-data 以及未显式配置内嵌包的开发构建使用空占位,不能误装 x64 包。 + +运行时安装与“修复/重新安装”只读取内嵌 zip,完整走灰度(显式 Embedded 除外)、摘要、签名、安全解压、staging 和原子提交。crate 不包含 HTTP client、远程清单或下载重试逻辑;没有内嵌包、包损坏或与编译目标不符时直接失败,不存在网络回退。 + +## 发布与信任根 + +独立组件公钥固定在 `resources/windows/x11-component/public-key.txt`,也可用 `NAVOP_X11_PUBLIC_KEY_BASE64` 在编译期覆盖。它不得复用应用更新公钥。私钥只保存在签名仓库的 GitHub Actions secret,不进入 Navop 仓库。 + +构建脚本的固定地址指向 [feigeCode/yserver `navop-v1.9.0-1`](https://github.com/feigeCode/yserver/releases/tag/navop-v1.9.0-1),不发现 tag、不追踪 latest。该 fork 基于 yserver v1.9.0,增加 `--listen 127.0.0.1`,由 GitHub Actions 构建并签名;源码提交为 `3b3c7f66fb9d9c80752af36b4948fad0b8760671`。 + +运行时清单必须显式给出 `format`(`binary` 或 `zip`)和安全的相对 `executable_path`,不接受 URL 等下载元数据。当前 zip 完整保留 `yserver.exe`、`xauth.exe`、`xkb/` 和 licenses;同一组件版本不得替换为不同摘要,更新时必须提升组件版本并同步固定清单、构建期 URL 和签名。 + +## 测试 + +```bash +cargo fmt -p x11_component +cargo test -p x11_component +cargo clippy -p x11_component --tests -- -D warnings +``` + +测试使用独立临时数据目录、临时签名密钥和内存 zip,覆盖 SHA256/签名错误、安全 zip、原子安装、离线安装/修复、重复/强制安装、rollout、重启窗口、永久禁用原因和指标;运行时测试不访问任何发布服务,也不依赖开发者机器已有 yserver。CI 另用真实固定 zip 编译并校验内嵌产物。macOS 内置路径始终返回 `UnsupportedPlatform`,External 探测仍可工作。 diff --git a/crates/x11_component/build.rs b/crates/x11_component/build.rs new file mode 100644 index 000000000..a75cc7914 --- /dev/null +++ b/crates/x11_component/build.rs @@ -0,0 +1,37 @@ +#[path = "build_support.rs"] +mod build_support; + +fn main() { + println!( + "cargo:rerun-if-env-changed={}", + build_support::BUNDLED_ARCHIVE_ENV + ); + println!("cargo:rerun-if-env-changed=NAVOP_X11_PUBLIC_KEY_BASE64"); + println!( + "cargo:rerun-if-changed=../../resources/windows/x11-component/navop-x11-manifest.json" + ); + println!("cargo:rerun-if-changed=../../resources/windows/x11-component/public-key.txt"); + + let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR 缺失")); + let target_os = std::env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS 缺失"); + let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH 缺失"); + match build_support::configure( + std::env::var_os(build_support::BUNDLED_ARCHIVE_ENV), + &target_os, + &target_arch, + &out_dir, + ) { + Ok(Some(build)) => { + println!("cargo:rerun-if-changed={}", build.source.display()); + println!( + "cargo:rustc-env={}={}", + build_support::BUNDLED_TARGET_ENV, + build.target + ); + } + Ok(None) => { + println!("cargo:rustc-env={}=", build_support::BUNDLED_TARGET_ENV); + } + Err(error) => panic!("{error}"), + } +} diff --git a/crates/x11_component/build_support.rs b/crates/x11_component/build_support.rs new file mode 100644 index 000000000..b7651deae --- /dev/null +++ b/crates/x11_component/build_support.rs @@ -0,0 +1,151 @@ +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; + +pub const BUNDLED_ARCHIVE_ENV: &str = "NAVOP_X11_BUNDLED_ARCHIVE"; +pub const BUNDLED_TARGET_ENV: &str = "NAVOP_X11_BUNDLED_TARGET"; +pub const BUNDLED_ARCHIVE_FILE: &str = "navop-x11-bundled.zip"; + +pub struct EmbeddedBuild { + pub target: &'static str, + pub source: PathBuf, +} + +pub fn target_key(target_os: &str, target_arch: &str) -> Result<&'static str, String> { + match (target_os, target_arch) { + ("windows", "x86_64") => Ok("windows-x86_64"), + ("windows", "aarch64") => Ok("windows-aarch64"), + _ => Err(format!( + "{BUNDLED_ARCHIVE_ENV} 仅支持 Windows x86_64/aarch64,实际为 {target_os}-{target_arch}" + )), + } +} + +/// 没有环境变量时写空占位文件,保留原源码构建;指定后所有输入错误都终止构建。 +pub fn configure( + archive: Option, + target_os: &str, + target_arch: &str, + out_dir: &Path, +) -> Result, String> { + let output = out_dir.join(BUNDLED_ARCHIVE_FILE); + let Some(archive) = archive else { + fs::write(&output, []) + .map_err(|error| format!("无法写入空嵌入占位 {}:{error}", output.display()))?; + return Ok(None); + }; + if archive.is_empty() { + return Err(format!("{BUNDLED_ARCHIVE_ENV} 不能为空字符串")); + } + let target = target_key(target_os, target_arch)?; + let source = PathBuf::from(archive); + if !source.is_absolute() { + return Err(format!( + "{BUNDLED_ARCHIVE_ENV} 必须是绝对 zip 路径:{}", + source.display() + )); + } + if source.extension().and_then(|value| value.to_str()) != Some("zip") { + return Err(format!( + "{BUNDLED_ARCHIVE_ENV} 必须指向 .zip 文件:{}", + source.display() + )); + } + let source = fs::canonicalize(&source).map_err(|error| { + format!( + "{BUNDLED_ARCHIVE_ENV} 路径无法解析 {}:{error}", + source.display() + ) + })?; + let metadata = fs::metadata(&source) + .map_err(|error| format!("无法读取嵌入 zip {}:{error}", source.display()))?; + if !metadata.is_file() { + return Err(format!("嵌入路径不是普通文件:{}", source.display())); + } + fs::copy(&source, &output).map_err(|error| { + format!( + "无法复制嵌入 zip {} 到 {}:{error}", + source.display(), + output.display() + ) + })?; + Ok(Some(EmbeddedBuild { target, source })) +} + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use super::*; + + fn test_dir(name: &str) -> PathBuf { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "navop-x11-build-{name}-{}-{unique}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + path + } + + #[test] + fn target_keys_are_explicit_and_fail_closed() { + assert_eq!(target_key("windows", "x86_64").unwrap(), "windows-x86_64"); + assert_eq!(target_key("windows", "aarch64").unwrap(), "windows-aarch64"); + assert!(target_key("windows", "x86").is_err()); + assert!(target_key("macos", "aarch64").is_err()); + } + + #[test] + fn missing_archive_preserves_source_build() { + let out = test_dir("source"); + assert!(configure(None, "macos", "arm64", &out).unwrap().is_none()); + assert_eq!(fs::read(out.join(BUNDLED_ARCHIVE_FILE)).unwrap(), b""); + fs::remove_dir_all(out).unwrap(); + } + + #[test] + fn archive_path_must_be_absolute_existing_zip() { + let out = test_dir("invalid-path"); + let relative = OsString::from("relative.zip"); + assert!(configure(Some(relative), "windows", "x86_64", &out).is_err()); + let missing = out.join("missing.zip"); + assert!(configure(Some(missing.into_os_string()), "windows", "x86_64", &out).is_err()); + let wrong_extension = out.join("archive.tar"); + fs::write(&wrong_extension, b"not zip").unwrap(); + assert!( + configure( + Some(wrong_extension.into_os_string()), + "windows", + "x86_64", + &out + ) + .is_err() + ); + fs::remove_dir_all(out).unwrap(); + } + + #[test] + fn configured_archive_is_copied_with_matching_target() { + let out = test_dir("embedded"); + let source = out.join("source.zip"); + fs::write(&source, b"signed zip bytes").unwrap(); + let embedded = configure( + Some(source.clone().into_os_string()), + "windows", + "aarch64", + &out, + ) + .unwrap() + .unwrap(); + assert_eq!(embedded.target, "windows-aarch64"); + assert_eq!( + fs::read(out.join(BUNDLED_ARCHIVE_FILE)).unwrap(), + b"signed zip bytes" + ); + fs::remove_dir_all(out).unwrap(); + } +} diff --git a/crates/x11_component/src/archive.rs b/crates/x11_component/src/archive.rs new file mode 100644 index 000000000..8491d8353 --- /dev/null +++ b/crates/x11_component/src/archive.rs @@ -0,0 +1,112 @@ +use std::io::{Cursor, Read as _}; +use std::path::{Path, PathBuf}; + +use zip::ZipArchive; + +use crate::X11ComponentError; +use crate::manifest::{Artifact, ArtifactFormat}; + +const MAX_ARCHIVE_ENTRIES: usize = 4096; +const MAX_UNPACKED_BYTES: u64 = 512 * 1024 * 1024; + +pub fn unpack( + payload: &[u8], + artifact: &Artifact, + staging: &Path, +) -> Result { + match artifact.format { + ArtifactFormat::Binary => write_binary(payload, artifact, staging)?, + ArtifactFormat::Zip => unpack_zip(payload, staging)?, + } + let executable = staging.join(artifact.executable_relative_path()); + if !executable.is_file() { + return Err(install("发布物缺少 executable_path 指向的文件")); + } + make_executable(&executable)?; + Ok(executable) +} + +fn write_binary( + payload: &[u8], + artifact: &Artifact, + staging: &Path, +) -> Result<(), X11ComponentError> { + let path = staging.join(artifact.executable_relative_path()); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(io_error)?; + } + std::fs::write(path, payload).map_err(io_error) +} + +fn unpack_zip(payload: &[u8], staging: &Path) -> Result<(), X11ComponentError> { + let mut archive = ZipArchive::new(Cursor::new(payload)).map_err(zip_error)?; + if archive.len() > MAX_ARCHIVE_ENTRIES { + return Err(install("zip 条目数超过安全上限")); + } + let mut total = 0_u64; + for index in 0..archive.len() { + let mut entry = archive.by_index(index).map_err(zip_error)?; + total = total + .checked_add(entry.size()) + .filter(|size| *size <= MAX_UNPACKED_BYTES) + .ok_or_else(|| install("zip 展开大小超过安全上限"))?; + extract_entry(&mut entry, staging)?; + } + Ok(()) +} + +fn extract_entry( + entry: &mut zip::read::ZipFile<'_>, + staging: &Path, +) -> Result<(), X11ComponentError> { + if entry.name().contains('\\') || is_symlink(entry.unix_mode()) { + return Err(install("zip 包含不兼容路径或符号链接")); + } + let relative = entry + .enclosed_name() + .ok_or_else(|| install("zip 包含目录穿越"))?; + let destination = staging.join(relative); + if entry.is_dir() { + return std::fs::create_dir_all(destination).map_err(io_error); + } + if !entry.is_file() { + return Err(install("zip 包含特殊文件")); + } + if let Some(parent) = destination.parent() { + std::fs::create_dir_all(parent).map_err(io_error)?; + } + let mut output = std::fs::File::create(destination).map_err(io_error)?; + let expected = entry.size(); + let copied = std::io::copy(&mut entry.take(expected + 1), &mut output).map_err(io_error)?; + if copied != expected { + return Err(install("zip 条目展开长度异常")); + } + Ok(()) +} + +fn is_symlink(mode: Option) -> bool { + mode.is_some_and(|mode| mode & 0o170000 == 0o120000) +} + +fn make_executable(_path: &Path) -> Result<(), X11ComponentError> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mut permissions = std::fs::metadata(_path).map_err(io_error)?.permissions(); + permissions.set_mode(0o700); + std::fs::set_permissions(_path, permissions).map_err(io_error)?; + } + Ok(()) +} + +fn zip_error(error: zip::result::ZipError) -> X11ComponentError { + install(error.to_string()) +} + +fn io_error(error: std::io::Error) -> X11ComponentError { + install(error.to_string()) +} + +fn install(reason: impl Into) -> X11ComponentError { + X11ComponentError::Install(reason.into()) +} diff --git a/crates/x11_component/src/bundle.rs b/crates/x11_component/src/bundle.rs new file mode 100644 index 000000000..5a1b3fb3a --- /dev/null +++ b/crates/x11_component/src/bundle.rs @@ -0,0 +1,109 @@ +//! 构建期验证后嵌入的固定组件;运行时只接受这份内嵌归档。 + +pub const PINNED_MANIFEST: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../resources/windows/x11-component/navop-x11-manifest.json" +)); + +static ARCHIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/navop-x11-bundled.zip")); + +#[derive(Clone, Copy)] +pub struct EmbeddedArchive { + pub target: &'static str, + pub bytes: &'static [u8], +} + +pub fn archive() -> Option { + (!ARCHIVE.is_empty()).then_some(EmbeddedArchive { + target: env!("NAVOP_X11_BUNDLED_TARGET"), + bytes: ARCHIVE, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use sha2::Digest; + + #[test] + fn pinned_manifest_contains_both_supported_windows_targets() { + let manifest = crate::manifest::ComponentManifest::parse( + PINNED_MANIFEST, + &semver::Version::new(0, 23, 4), + ) + .unwrap(); + for (target, executable) in [ + ("windows-x86_64", "yserver-1.9.0-windows-x86_64/yserver.exe"), + ( + "windows-aarch64", + "yserver-1.9.0-windows-aarch64/yserver.exe", + ), + ] { + let artifact = manifest.artifact(target).unwrap(); + assert_eq!(artifact.version, "1.9.0-navop.1"); + assert_eq!(artifact.executable_path, executable); + } + } + + #[tokio::test] + async fn configured_archive_installs_complete_component_offline() { + let Some(archive) = archive() else { + assert!(option_env!("NAVOP_X11_BUNDLED_ARCHIVE").is_none()); + return; + }; + let root = std::env::temp_dir().join(format!( + "navop-x11-real-bundle-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let config = crate::InstallConfig { + data_dir: root.clone(), + public_key_base64: crate::X11_PUBLIC_KEY_BASE64.into(), + navop_version: semver::Version::new(0, 23, 4), + target: archive.target.into(), + }; + let result = crate::installer::prepare(config, crate::X11ServerMode::Embedded).await; + let component = match result { + Ok(component) => component, + Err(error) => { + let _ = std::fs::remove_dir_all(&root); + panic!("真实内嵌组件必须能离线完整安装:{error}"); + } + }; + assert!(component.executable.is_file()); + let package_root = component.executable.parent().unwrap(); + assert!(package_root.join("xauth.exe").is_file()); + for directory in ["compat", "keycodes", "rules", "symbols", "types"] { + assert!(package_root.join("xkb").join(directory).is_dir()); + } + assert!(package_root.join("licenses/rust-crates.txt").is_file()); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn configured_archive_matches_its_pinned_manifest() { + let Some(archive) = archive() else { + assert!(option_env!("NAVOP_X11_BUNDLED_ARCHIVE").is_none()); + return; + }; + let manifest = crate::manifest::ComponentManifest::parse( + PINNED_MANIFEST, + &semver::Version::new(0, 23, 4), + ) + .unwrap(); + let artifact = manifest.artifact(archive.target).unwrap(); + assert_eq!( + hex::encode(sha2::Sha256::digest(archive.bytes)), + artifact.sha256 + ); + crate::verify_ed25519( + archive.bytes, + &artifact.signature, + crate::X11_PUBLIC_KEY_BASE64, + ) + .unwrap(); + } +} diff --git a/crates/x11_component/src/command.rs b/crates/x11_component/src/command.rs new file mode 100644 index 000000000..4aec4c0c1 --- /dev/null +++ b/crates/x11_component/src/command.rs @@ -0,0 +1,184 @@ +use std::path::{Path, PathBuf}; + +use rand::{RngCore as _, rngs::OsRng}; +use x11_forwarding::ServerEndpoint; + +use crate::X11ComponentError; + +#[derive(Clone, Debug)] +pub struct EndpointPlan(ServerEndpoint); + +impl EndpointPlan { + pub fn random(manual: bool) -> Result { + if manual || cfg!(target_os = "linux") { + #[cfg(unix)] + return Self::random_unix(); + } + Self::random_tcp() + } + + pub fn random_tcp() -> Result { + for _ in 0..128 { + // yserver 的 TCP 端口固定为 6000 + display,只在合法范围内随机。 + let display = 100 + (OsRng.next_u32() % 59_436) as u16; + let port = 6000 + display; + if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() { + return Ok(Self(ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port, + })); + } + } + Err(X11ComponentError::Process( + "无法在 6000 + display 范围内找到空闲回环端口".into(), + )) + } + + #[cfg(unix)] + fn random_unix() -> Result { + for _ in 0..128 { + let display = 100 + (OsRng.next_u32() % 59_436) as u16; + if !PathBuf::from(format!("/tmp/.X11-unix/X{display}")).exists() { + return Ok(Self(ServerEndpoint::Unix(PathBuf::from(format!( + "/tmp/.X11-unix/X{display}" + ))))); + } + } + Err(X11ComponentError::Process( + "无法找到空闲 X11 Unix socket".into(), + )) + } + + #[cfg(test)] + pub fn persisted(endpoint: ServerEndpoint) -> Self { + Self(endpoint) + } + + pub fn endpoint(&self) -> ServerEndpoint { + self.0.clone() + } + + #[cfg(test)] + pub fn display_number(&self) -> Option { + match &self.0 { + ServerEndpoint::Inet { port, .. } => port.checked_sub(6000), + ServerEndpoint::Unix(path) => display_from_socket(path), + } + } +} + +#[derive(Clone, Copy)] +enum TcpListen { + Disabled, + Loopback, + LegacyAllInterfaces, +} + +/// 所有上游启动参数集中在此处;只有固定 Windows fork 可以声明 loopback 监听。 +pub struct CommandSpec { + executable: PathBuf, + endpoint: ServerEndpoint, + xauth: PathBuf, + tcp_listen: TcpListen, +} + +impl CommandSpec { + pub fn installed_tcp(executable: PathBuf, endpoint: &ServerEndpoint, xauth: PathBuf) -> Self { + Self { + executable, + endpoint: endpoint.clone(), + xauth, + tcp_listen: TcpListen::Loopback, + } + } + + pub fn manual_upstream_tcp( + executable: PathBuf, + endpoint: &ServerEndpoint, + xauth: PathBuf, + ) -> Self { + Self { + executable, + endpoint: endpoint.clone(), + xauth, + tcp_listen: TcpListen::LegacyAllInterfaces, + } + } + + pub fn unix(executable: PathBuf, endpoint: &ServerEndpoint, xauth: PathBuf) -> Self { + Self { + executable, + endpoint: endpoint.clone(), + xauth, + tcp_listen: TcpListen::Disabled, + } + } + + pub fn validate_secure_endpoint(&self) -> Result<(), X11ComponentError> { + match (&self.endpoint, self.tcp_listen) { + (ServerEndpoint::Unix(_), TcpListen::Disabled) => Ok(()), + (ServerEndpoint::Inet { host, port }, TcpListen::Loopback) + if host == "127.0.0.1" && *port >= 6000 => + { + Ok(()) + } + (ServerEndpoint::Inet { .. }, TcpListen::LegacyAllInterfaces) => { + Err(X11ComponentError::EmbeddedDisabled( + "Windows 手动 yserver 不支持 TCP:无法验证旧上游监听地址,请使用内置组件或 Unix socket" + .into(), + )) + } + _ => Err(X11ComponentError::Config("内置端点不是本地安全地址".into())), + } + } + + pub fn display_argument(&self) -> String { + let number = match &self.endpoint { + ServerEndpoint::Inet { port, .. } => port.saturating_sub(6000), + ServerEndpoint::Unix(path) => display_from_socket(path).unwrap_or(0), + }; + format!(":{number}") + } + + pub fn arguments(&self) -> Vec { + let mut args = vec![ + self.display_argument(), + "-auth".into(), + self.xauth.display().to_string(), + ]; + match self.tcp_listen { + TcpListen::Loopback => { + args.push("--listen".into()); + args.push("127.0.0.1".into()); + } + TcpListen::LegacyAllInterfaces => { + args.push("-listen".into()); + args.push("tcp".into()); + } + TcpListen::Disabled => { + args.push("-nolisten".into()); + args.push("tcp".into()); + } + } + args + } + + pub fn executable(&self) -> &Path { + &self.executable + } +} + +#[cfg(test)] +pub fn random_loopback_endpoint(endpoint: &ServerEndpoint) -> Option { + match endpoint { + ServerEndpoint::Inet { host, .. } if host == "127.0.0.1" => Some(endpoint.clone()), + _ => None, + } +} + +fn display_from_socket(path: &Path) -> Option { + path.file_name()?.to_str()?.strip_prefix('X')?.parse().ok() +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/command/tests.rs b/crates/x11_component/src/command/tests.rs new file mode 100644 index 000000000..3ec94a2b2 --- /dev/null +++ b/crates/x11_component/src/command/tests.rs @@ -0,0 +1,119 @@ +use std::path::PathBuf; + +use x11_forwarding::ServerEndpoint; + +use super::{CommandSpec, EndpointPlan, random_loopback_endpoint}; + +#[test] +fn random_endpoint_is_loopback_with_matching_display() { + let plan = EndpointPlan::random_tcp().unwrap(); + let endpoint = plan.endpoint(); + let ServerEndpoint::Inet { host, port } = &endpoint else { + panic!("应为 TCP") + }; + assert_eq!(host, "127.0.0.1"); + let display = plan.display_number().unwrap(); + assert!((100..=59_535).contains(&display)); + assert_eq!(*port, 6000 + display); + let same = EndpointPlan::persisted(endpoint.clone()); + assert_eq!( + same.endpoint(), + ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: *port, + } + ); +} + +#[test] +fn installed_tcp_listens_only_on_loopback() { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 6010, + }; + let spec = + CommandSpec::installed_tcp(PathBuf::from("yserver"), &endpoint, PathBuf::from("auth")); + spec.validate_secure_endpoint().unwrap(); + assert_eq!(spec.display_argument(), ":10"); + assert_eq!( + spec.arguments(), + vec![":10", "-auth", "auth", "--listen", "127.0.0.1"] + ); +} + +#[test] +fn installed_tcp_display_covers_full_valid_range() { + for (port, display) in [(6000, ":0"), (6010, ":10"), (u16::MAX, ":59535")] { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port, + }; + let spec = + CommandSpec::installed_tcp(PathBuf::from("yserver"), &endpoint, PathBuf::from("auth")); + spec.validate_secure_endpoint().unwrap(); + assert_eq!(spec.display_argument(), display); + } +} + +#[test] +fn installed_tcp_rejects_non_loopback_endpoint() { + let endpoint = ServerEndpoint::Inet { + host: "0.0.0.0".into(), + port: 6010, + }; + let spec = + CommandSpec::installed_tcp(PathBuf::from("yserver"), &endpoint, PathBuf::from("auth")); + assert!(spec.validate_secure_endpoint().is_err()); +} + +#[test] +fn installed_tcp_rejects_port_without_display() { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 5999, + }; + let spec = + CommandSpec::installed_tcp(PathBuf::from("yserver"), &endpoint, PathBuf::from("auth")); + assert!(spec.validate_secure_endpoint().is_err()); +} + +#[test] +fn manual_upstream_tcp_all_interfaces_is_rejected() { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 6010, + }; + let spec = CommandSpec::manual_upstream_tcp( + PathBuf::from("yserver"), + &endpoint, + PathBuf::from("auth"), + ); + let error = spec.validate_secure_endpoint().unwrap_err().to_string(); + assert!(error.contains("手动")); + assert!(error.contains("不支持 TCP")); + assert_eq!( + spec.arguments(), + vec![":10", "-auth", "auth", "-listen", "tcp"] + ); +} + +#[test] +fn unix_socket_manual_launch_arguments() { + let endpoint = ServerEndpoint::Unix("/tmp/.X11-unix/X17".into()); + let spec = CommandSpec::unix(PathBuf::from("yserver"), &endpoint, PathBuf::from("auth")); + spec.validate_secure_endpoint().unwrap(); + assert_eq!(spec.display_argument(), ":17"); + assert_eq!( + spec.arguments(), + vec![":17", "-auth", "auth", "-nolisten", "tcp"] + ); +} + +#[test] +fn helper_rejects_non_loopback_tcp() { + let endpoint = ServerEndpoint::Inet { + host: "0.0.0.0".into(), + port: 6000, + }; + assert!(random_loopback_endpoint(&endpoint).is_none()); +} diff --git a/crates/x11_component/src/install_work.rs b/crates/x11_component/src/install_work.rs new file mode 100644 index 000000000..32b27e34e --- /dev/null +++ b/crates/x11_component/src/install_work.rs @@ -0,0 +1,139 @@ +//! 内嵌包校验、解压与目录 I/O 集中在 blocking 阶段执行。 +use std::path::{Path, PathBuf}; + +use rand::{RngCore as _, rngs::OsRng}; +use sha2::{Digest as _, Sha256}; + +use crate::X11ComponentError; +use crate::manifest::Artifact; + +pub async fn unpack_blocking( + payload: &'static [u8], + artifact: Artifact, + public_key_base64: String, + staging: PathBuf, +) -> Result<(), X11ComponentError> { + tokio::task::spawn_blocking(move || { + unpack_sync(payload, &artifact, &public_key_base64, &staging) + }) + .await + .map_err(join_error)? +} + +pub async fn commit_blocking( + staging: PathBuf, + root: PathBuf, + version: String, +) -> Result<(), X11ComponentError> { + tokio::task::spawn_blocking(move || crate::installer::commit_sync(&staging, &root, &version)) + .await + .map_err(join_error)? +} + +fn unpack_sync( + payload: &[u8], + artifact: &Artifact, + public_key_base64: &str, + staging: &Path, +) -> Result<(), X11ComponentError> { + let actual = hex::encode(Sha256::digest(payload)); + if actual != artifact.sha256 { + return Err(X11ComponentError::Sha256Mismatch { + expected: artifact.sha256.clone(), + actual, + }); + } + crate::verify_ed25519(payload, &artifact.signature, public_key_base64)?; + crate::archive::unpack(payload, artifact, staging)?; + Ok(()) +} + +pub async fn cleanup_blocking(path: PathBuf) { + let _ = tokio::task::spawn_blocking(move || std::fs::remove_dir_all(path)).await; +} + +pub fn schedule_cleanup(path: PathBuf) { + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + runtime.spawn(cleanup_blocking(path)); + } else { + let _ = std::thread::Builder::new() + .name("x11-staging-cleanup".into()) + .spawn(move || { + let _ = std::fs::remove_dir_all(path); + }); + } +} + +pub fn replace_destination_sync( + staging: &Path, + destination: &Path, +) -> Result<(), X11ComponentError> { + if !destination.exists() { + return std::fs::rename(staging, destination).map_err(install_error); + } + let backup = backup_path(destination); + std::fs::rename(destination, &backup).map_err(install_error)?; + if let Err(error) = std::fs::rename(staging, destination) { + let _ = std::fs::rename(&backup, destination); + return Err(install_error(error)); + } + std::fs::remove_dir_all(backup).map_err(install_error) +} + +fn backup_path(destination: &Path) -> PathBuf { + let mut random = [0; 8]; + OsRng.fill_bytes(&mut random); + destination.with_extension(format!("replaced-{}", hex::encode(random))) +} + +fn join_error(error: tokio::task::JoinError) -> X11ComponentError { + X11ComponentError::Install(format!("安装 blocking 阶段失败:{error}")) +} + +fn install_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Install(error.to_string()) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use crate::X11ComponentError; + use crate::manifest::{Artifact, ArtifactFormat}; + + #[test] + fn unpack_is_offloaded_to_tokio_blocking_pool() { + // 直接锁定生产函数的调度路径,避免用计时器阈值或任务调度顺序推断非阻塞。 + let source = include_str!("install_work.rs"); + let function = source + .split("pub async fn unpack_blocking(") + .nth(1) + .expect("缺少 unpack_blocking") + .split("pub async fn commit_blocking(") + .next() + .expect("缺少函数边界"); + assert!(function.contains("tokio::task::spawn_blocking(move || {")); + assert!(function.contains("unpack_sync(payload, &artifact, &public_key_base64, &staging)")); + } + + #[tokio::test] + async fn invalid_hash_is_reported_without_touching_the_staging_directory() { + let artifact = Artifact { + version: "1.9.0".into(), + sha256: "00".repeat(32), + signature: String::new(), + min_vulkan: "1.3.0".into(), + format: ArtifactFormat::Binary, + executable_path: "yserver".into(), + }; + let staging = std::env::temp_dir().join("x11-blocking-test"); + let work = tokio::time::timeout( + Duration::from_secs(30), + super::unpack_blocking(&[7; 64 * 1024 * 1024], artifact, String::new(), staging.clone()), + ) + .await + .expect("blocking 哈希应在测试时限内完成"); + assert!(matches!(work, Err(X11ComponentError::Sha256Mismatch { .. }))); + assert!(!staging.exists()); + } +} diff --git a/crates/x11_component/src/installer.rs b/crates/x11_component/src/installer.rs new file mode 100644 index 000000000..52130e4a1 --- /dev/null +++ b/crates/x11_component/src/installer.rs @@ -0,0 +1,280 @@ +use std::path::{Path, PathBuf}; + +use rand::{RngCore as _, rngs::OsRng}; + +use crate::bundle::EmbeddedArchive; +use crate::lock::ComponentLock; +use crate::manifest::{Artifact, ComponentManifest}; +use crate::paths::{component_root, prune_versions_preserving, read_installed, write_current}; +use crate::process::active_versions; +use crate::rollout::should_use_embedded; +use crate::state::{active_version, disable_embedded, update_status}; +use crate::{InstallConfig, X11ComponentError, X11ServerMode}; + +static INSTALL_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +#[derive(Clone, Debug)] +pub(crate) struct InstalledComponent { + pub version: String, + pub executable: PathBuf, + pub min_vulkan: String, +} + +/// 显式安装内嵌组件,始终强制 SHA256 与 Ed25519 校验。 +pub async fn install_with_config(config: InstallConfig) -> Result { + install_with_config_for_mode(config, X11ServerMode::Embedded).await +} + +/// 供解析器传递 Auto 灰度语义;显式 Embedded 不受灰度比例限制。 +pub async fn install_with_config_for_mode( + config: InstallConfig, + mode: X11ServerMode, +) -> Result { + prepare(config, mode) + .await + .map(|component| component.version) +} + +/// 使用同一份内嵌归档重新安装;不存在任何运行时网络回退。 +pub async fn reinstall_with_config(config: InstallConfig) -> Result { + let _guard = INSTALL_LOCK.lock().await; + prepare_locked(config, InstallPurpose::Repair) + .await + .map(|component| component.version) +} + +pub(crate) async fn prepare( + config: InstallConfig, + mode: X11ServerMode, +) -> Result { + let _guard = INSTALL_LOCK.lock().await; + prepare_locked(config, InstallPurpose::Resolve(mode)).await +} + +async fn prepare_locked( + config: InstallConfig, + purpose: InstallPurpose, +) -> Result { + let archive = crate::bundle::archive() + .ok_or_else(|| X11ComponentError::Config("当前构建未内嵌 X11 组件,无法离线安装".into()))?; + install_embedded_manifest(&config, purpose, crate::bundle::PINNED_MANIFEST, archive).await +} + +enum InstallPurpose { + Resolve(X11ServerMode), + Repair, +} + +impl InstallPurpose { + fn mode(&self) -> X11ServerMode { + match self { + Self::Resolve(mode) => *mode, + Self::Repair => X11ServerMode::Embedded, + } + } + + fn force(&self) -> bool { + matches!(self, Self::Repair) + } +} + +async fn install_embedded_manifest( + config: &InstallConfig, + purpose: InstallPurpose, + manifest_text: &str, + archive: EmbeddedArchive, +) -> Result { + if archive.target != config.target { + return Err(X11ComponentError::MissingArtifact(format!( + "内嵌组件目标 {} 与当前目标 {} 不一致", + archive.target, config.target + ))); + } + let manifest = ComponentManifest::parse(manifest_text, &config.navop_version)?; + install_selected_artifact(config, purpose, &manifest, archive).await +} + +async fn install_selected_artifact( + config: &InstallConfig, + purpose: InstallPurpose, + manifest: &ComponentManifest, + archive: EmbeddedArchive, +) -> Result { + if config.public_key_base64.is_empty() { + return Err(X11ComponentError::Config( + "X11 组件发布公钥尚未配置,已 fail-closed".into(), + )); + } + let artifact = manifest.artifact(&config.target)?; + let root = component_root(&config.data_dir); + if !should_use_embedded(&root, purpose.mode(), manifest.rollout_percent())? { + return Err(X11ComponentError::EmbeddedDisabled( + "当前持久灰度编号未纳入 Auto 发布范围".into(), + )); + } + if !purpose.force() { + if let Some(component) = already_installed(&root, &artifact)? { + return Ok(component); + } + } + let destination = root.join("versions").join(&artifact.version); + if destination.exists() { + let _lock = ComponentLock::acquire_async(root.clone()) + .await + .map_err(install_error)?; + ensure_replacement_allowed(&root, &artifact.version)?; + } + let staging = StagingDirectory::new(&root)?; + let result = embedded_install(config, &artifact, &staging.path, archive.bytes).await; + preserve_untrusted_disable_reason(&result); + if result.is_ok() { + staging.disarm(); + } else { + staging.cleanup().await; + } + result +} + +fn preserve_untrusted_disable_reason(result: &Result) { + let reason = match result { + Err( + error @ (X11ComponentError::SignatureInvalid(_) + | X11ComponentError::Sha256Mismatch { .. }), + ) => Some(error.to_string()), + _ => None, + }; + if let Some(reason) = reason { + let reason = disable_embedded(reason); + update_status(crate::X11ForwardingStatus::Disabled { + reason: format!("{reason};本次运行禁用内置"), + }); + } +} + +fn already_installed( + root: &Path, + artifact: &Artifact, +) -> Result, X11ComponentError> { + let executable = root + .join("versions") + .join(&artifact.version) + .join(artifact.executable_relative_path()); + if !executable.is_file() { + return Ok(None); + } + write_current(root, &artifact.version)?; + let installed = read_installed(root).filter(|version| version == &artifact.version); + Ok(installed.map(|version| InstalledComponent { + version, + executable, + min_vulkan: artifact.min_vulkan.clone(), + })) +} + +async fn embedded_install( + config: &InstallConfig, + artifact: &Artifact, + staging: &Path, + payload: &'static [u8], +) -> Result { + crate::install_work::unpack_blocking( + payload, + artifact.clone(), + config.public_key_base64.clone(), + staging.to_path_buf(), + ) + .await?; + finish_install(config, artifact, staging).await +} + +async fn finish_install( + config: &InstallConfig, + artifact: &Artifact, + staging: &Path, +) -> Result { + let root = component_root(&config.data_dir); + commit(staging, &root, &artifact.version).await?; + Ok(InstalledComponent { + version: artifact.version.clone(), + executable: root + .join("versions") + .join(&artifact.version) + .join(artifact.executable_relative_path()), + min_vulkan: artifact.min_vulkan.clone(), + }) +} + +async fn commit(staging: &Path, root: &Path, version: &str) -> Result<(), X11ComponentError> { + crate::install_work::commit_blocking( + staging.to_path_buf(), + root.to_path_buf(), + version.to_string(), + ) + .await +} + +pub(crate) fn commit_sync( + staging: &Path, + root: &Path, + version: &str, +) -> Result<(), X11ComponentError> { + let _lock = ComponentLock::acquire(root).map_err(install_error)?; + ensure_replacement_allowed(root, version)?; + let versions = root.join("versions"); + std::fs::create_dir_all(&versions).map_err(install_error)?; + crate::install_work::replace_destination_sync(staging, &versions.join(version))?; + write_current(root, version)?; + let mut protected = active_versions(root)?; + protected.insert(version.to_string()); + prune_versions_preserving(root, &protected) +} + +fn ensure_replacement_allowed(root: &Path, version: &str) -> Result<(), X11ComponentError> { + if active_version().as_deref() == Some(version) || active_versions(root)?.contains(version) { + return Err(X11ComponentError::Install( + "内置组件正在运行,请重启应用后再重新安装".into(), + )); + } + Ok(()) +} + +struct StagingDirectory { + path: PathBuf, + armed: bool, +} + +impl StagingDirectory { + fn new(root: &Path) -> Result { + std::fs::create_dir_all(root).map_err(install_error)?; + let mut random = [0; 8]; + OsRng.fill_bytes(&mut random); + let path = root.join(format!(".tmp-{}", hex::encode(random))); + std::fs::create_dir(&path).map_err(install_error)?; + Ok(Self { path, armed: true }) + } + + fn disarm(mut self) { + self.armed = false; + } + + async fn cleanup(mut self) { + self.armed = false; + crate::install_work::cleanup_blocking(self.path.clone()).await; + } +} + +impl Drop for StagingDirectory { + fn drop(&mut self) { + // 取消或 panic 的兜底清理也不能阻塞 async worker。 + if self.armed { + crate::install_work::schedule_cleanup(self.path.clone()); + } + } +} + +#[cfg(test)] +mod tests; + +fn install_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Install(error.to_string()) +} diff --git a/crates/x11_component/src/installer/tests.rs b/crates/x11_component/src/installer/tests.rs new file mode 100644 index 000000000..95a4e30cb --- /dev/null +++ b/crates/x11_component/src/installer/tests.rs @@ -0,0 +1,400 @@ +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::X11ComponentError; +use crate::process::{PidFile, instance_path}; +use crate::state::set_active_version; + +fn test_root(name: &str) -> PathBuf { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!( + "x11-installer-{name}-{}-{nonce}", + std::process::id() + )); + std::fs::create_dir_all(&root).unwrap(); + root +} + +#[test] +fn active_version_cannot_be_replaced_by_force_reinstall() { + let _guard = crate::test_support::global_state_lock(); + set_active_version(Some("1.9.0".into())); + let root = test_root("local-active"); + let error = super::ensure_replacement_allowed(&root, "1.9.0").unwrap_err(); + assert!(matches!(error, X11ComponentError::Install(_))); + assert!(error.to_string().contains("重启应用")); + set_active_version(None); + assert!(super::ensure_replacement_allowed(&root, "1.9.0").is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn another_process_active_version_cannot_be_replaced() { + let root = test_root("other-active"); + let record = PidFile::capture( + std::process::id(), + &std::env::current_exe().unwrap(), + "1.9.0", + ) + .unwrap(); + record.write(&instance_path(&root, &record)).unwrap(); + let error = super::ensure_replacement_allowed(&root, &record.version).unwrap_err(); + assert!(matches!(error, X11ComponentError::Install(_))); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn commit_rechecks_active_version_before_replacement() { + let root = test_root("commit-active"); + let staging = root.join("staging"); + std::fs::create_dir_all(&staging).unwrap(); + std::fs::create_dir_all(root.join("versions/1.9.0")).unwrap(); + let record = PidFile::capture( + std::process::id(), + &std::env::current_exe().unwrap(), + "1.9.0", + ) + .unwrap(); + record.write(&instance_path(&root, &record)).unwrap(); + let error = super::commit(&staging, &root, &record.version) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::Install(_))); + assert!(root.join("versions/1.9.0").exists()); + assert!(staging.exists(), "拒绝提交时不能移动 staging"); + std::fs::remove_dir_all(root).unwrap(); +} + +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use ed25519_dalek::{Signer as _, SigningKey, VerifyingKey}; +use sha2::{Digest as _, Sha256}; + +use crate::bundle::EmbeddedArchive; +use crate::{InstallConfig, X11ServerMode}; + +fn embedded_config(root: &std::path::Path, target: &str, signing: &SigningKey) -> InstallConfig { + InstallConfig { + data_dir: root.to_path_buf(), + public_key_base64: BASE64.encode(VerifyingKey::from(signing).to_bytes()), + navop_version: semver::Version::new(0, 23, 4), + target: target.into(), + } +} + +fn zip_payload(executable: &[u8]) -> Vec { + use std::io::Write as _; + + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in [ + ("yserver.exe", executable), + ("share/xkb/keymap", b"keymap".as_slice()), + ] { + writer + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + writer.write_all(bytes).unwrap(); + } + writer.finish().unwrap().into_inner() +} + +fn malicious_zip_payload(entry_name: &str, symlink: bool) -> Vec { + use std::io::Write as _; + + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + writer + .start_file("yserver.exe", zip::write::SimpleFileOptions::default()) + .unwrap(); + writer.write_all(b"embedded").unwrap(); + let options = zip::write::SimpleFileOptions::default(); + if symlink { + writer + .add_symlink(entry_name, "../escape", options) + .unwrap(); + } else { + writer.start_file(entry_name, options).unwrap(); + writer.write_all(b"escape").unwrap(); + } + writer.finish().unwrap().into_inner() +} + +fn artifact_json(version: &str, payload: &[u8], signing: &SigningKey) -> serde_json::Value { + serde_json::json!({ + "version": version, + "sha256": hex::encode(Sha256::digest(payload)), + "signature": BASE64.encode(signing.sign(payload).to_bytes()), + "min_vulkan": "1.3.0", + "format": "zip", + "executable_path": "yserver.exe" + }) +} + +fn embedded_manifest(payload: &[u8], signing: &SigningKey) -> String { + serde_json::json!({ + "schema": 1, + "components": { + "x11-server": { + "channel": "stable", + "pinned_for_navop": ">=0.23.4, <0.24.0", + "rollout_percent": 100, + "artifacts": { + "windows-x86_64": artifact_json("1.9.0", payload, signing) + } + } + } + }) + .to_string() +} + +async fn install_test_archive( + config: &InstallConfig, + purpose: super::InstallPurpose, + manifest: &str, + target: &str, + payload: &[u8], +) -> Result { + super::install_embedded_manifest( + config, + purpose, + manifest, + EmbeddedArchive { + // 生产引用编译期静态字节;测试将短小的临时夹具提升为同样的生命周期。 + target: Box::leak(target.to_owned().into_boxed_str()), + bytes: Box::leak(payload.to_vec().into_boxed_slice()), + }, + ) + .await +} + +#[tokio::test] +async fn missing_embedded_archive_fails_closed_without_network() { + if crate::bundle::archive().is_some() { + return; + } + let root = test_root("missing-embedded"); + let config = InstallConfig { + data_dir: root.clone(), + public_key_base64: String::new(), + navop_version: semver::Version::new(0, 23, 4), + target: "windows-x86_64".into(), + }; + let error = super::prepare(config, X11ServerMode::Embedded) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::Config(reason) if reason.contains("未内嵌"))); + assert!(!root.join("components/x11").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn embedded_install_selects_target_offline() { + let root = test_root("embedded-offline"); + let signing = SigningKey::from_bytes(&[41; 32]); + let payload = zip_payload(b"embedded-x64"); + let arm_payload = zip_payload(b"embedded-arm64"); + let mut manifest: serde_json::Value = + serde_json::from_str(&embedded_manifest(&payload, &signing)).unwrap(); + manifest["components"]["x11-server"]["artifacts"]["windows-aarch64"] = + artifact_json("2.0.0", &arm_payload, &signing); + let manifest = manifest.to_string(); + let config = embedded_config(&root, "windows-x86_64", &signing); + + let installed = install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap(); + assert_eq!(installed.version, "1.9.0"); + let version_root = root.join("components/x11/versions/1.9.0"); + assert_eq!( + std::fs::read(version_root.join("yserver.exe")).unwrap(), + b"embedded-x64" + ); + assert_eq!( + std::fs::read(version_root.join("share/xkb/keymap")).unwrap(), + b"keymap" + ); + assert!(!root.join("components/x11/versions/2.0.0").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn embedded_archive_rejects_traversal_backslash_and_symlink() { + for (index, (entry_name, symlink)) in [ + ("../escape", false), + ("..\\escape", false), + ("escape-link", true), + ] + .into_iter() + .enumerate() + { + let root = test_root(&format!("embedded-archive-{index}")); + let signing = SigningKey::from_bytes(&[47 + index as u8; 32]); + let payload = malicious_zip_payload(entry_name, symlink); + let manifest = embedded_manifest(&payload, &signing); + let config = embedded_config(&root, "windows-x86_64", &signing); + let error = install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap_err(); + assert!( + matches!(error, X11ComponentError::Install(_)), + "{entry_name}" + ); + assert!(!root.join("components/x11/current").exists()); + assert!(!root.join("escape").exists()); + std::fs::remove_dir_all(root).unwrap(); + } +} + +#[tokio::test] +async fn embedded_target_mismatch_fails_closed() { + let root = test_root("embedded-target"); + let signing = SigningKey::from_bytes(&[42; 32]); + let payload = zip_payload(b"embedded-x64"); + let manifest = embedded_manifest(&payload, &signing); + let config = embedded_config(&root, "windows-aarch64", &signing); + let error = install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::MissingArtifact(_))); + assert!(!root.join("components/x11/current").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn embedded_bad_digest_does_not_commit() { + let _guard = crate::test_support::global_state_lock_async().await; + crate::state::reset_embedded_disable_reason_for_test(); + let root = test_root("embedded-digest"); + let signing = SigningKey::from_bytes(&[43; 32]); + let payload = zip_payload(b"embedded"); + let mut manifest: serde_json::Value = + serde_json::from_str(&embedded_manifest(&payload, &signing)).unwrap(); + manifest["components"]["x11-server"]["artifacts"]["windows-x86_64"]["sha256"] = + "0".repeat(64).into(); + let config = embedded_config(&root, "windows-x86_64", &signing); + let error = install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest.to_string(), + "windows-x86_64", + &payload, + ) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::Sha256Mismatch { .. })); + assert!(!root.join("components/x11/current").exists()); + std::fs::remove_dir_all(root).unwrap(); + crate::state::reset_embedded_disable_reason_for_test(); +} + +#[tokio::test] +async fn embedded_bad_signature_disables_until_restart_and_does_not_commit() { + let _guard = crate::test_support::global_state_lock_async().await; + crate::state::reset_embedded_disable_reason_for_test(); + let root = test_root("embedded-signature"); + let signing = SigningKey::from_bytes(&[44; 32]); + let wrong = SigningKey::from_bytes(&[45; 32]); + let payload = zip_payload(b"embedded"); + let manifest = embedded_manifest(&payload, &wrong); + let config = embedded_config(&root, "windows-x86_64", &signing); + let error = install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::SignatureInvalid(_))); + assert!(!root.join("components/x11/current").exists()); + let reason = crate::state::embedded_disable_reason().expect("验签失败应永久禁用内置"); + assert!(reason.contains("验签")); + let previous_status = crate::current_status(); + let resolution = crate::resolve_server(X11ServerMode::Embedded).await; + assert!(resolution.proxy.is_none()); + let crate::X11ForwardingStatus::Disabled { + reason: ref status_reason, + } = resolution.status + else { + panic!("验签失败后 resolver 必须返回禁用状态"); + }; + assert!(status_reason.contains("验签")); + assert_eq!(crate::current_status(), resolution.status); + + install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &embedded_manifest(&payload, &signing), + "windows-x86_64", + &payload, + ) + .await + .unwrap(); + assert_eq!( + crate::state::embedded_disable_reason().as_deref(), + Some(reason.as_str()), + "成功重装不得清除本次运行的安全禁用" + ); + let resolution = crate::resolve_server(X11ServerMode::Embedded).await; + assert!(resolution.proxy.is_none()); + assert_eq!(resolution.status, crate::current_status()); + assert!(matches!( + resolution.status, + crate::X11ForwardingStatus::Disabled { reason: current } if current == *status_reason + )); + crate::state::update_status(previous_status); + std::fs::remove_dir_all(root).unwrap(); + crate::state::reset_embedded_disable_reason_for_test(); +} + +#[tokio::test] +async fn embedded_force_reinstall_verifies_and_replaces_existing_files() { + let root = test_root("embedded-force"); + let signing = SigningKey::from_bytes(&[46; 32]); + let payload = zip_payload(b"original"); + let manifest = embedded_manifest(&payload, &signing); + let config = embedded_config(&root, "windows-x86_64", &signing); + install_test_archive( + &config, + super::InstallPurpose::Resolve(X11ServerMode::Embedded), + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap(); + let executable = root.join("components/x11/versions/1.9.0/yserver.exe"); + std::fs::write(&executable, b"tampered").unwrap(); + + install_test_archive( + &config, + super::InstallPurpose::Repair, + &manifest, + "windows-x86_64", + &payload, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(executable).unwrap(), b"original"); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/src/launch.rs b/crates/x11_component/src/launch.rs new file mode 100644 index 000000000..c01e8c4b6 --- /dev/null +++ b/crates/x11_component/src/launch.rs @@ -0,0 +1,217 @@ +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::OnceLock; + +use process_util::configure_tokio_background_child; +use tokio::process::{Child, Command}; +use x11_forwarding::{MagicCookie, ServerEndpoint}; + +use crate::X11ComponentError; +use crate::command::{CommandSpec, EndpointPlan}; +use crate::installer::InstalledComponent; +use crate::lock::ComponentLock; +use crate::paths::component_root; +use crate::process::{ + PidFile, cleanup_orphan, install_exit_handler, instance_path, register_exit_cleanup, +}; +use crate::runtime::{PersistentEndpoint, RuntimeIdentity}; +use crate::xauth::write_xauth; + +#[derive(Clone, Debug)] +pub struct LaunchSpec { + pub root: PathBuf, + pub executable: PathBuf, + pub version: String, + pub min_vulkan: String, + pub identity: RuntimeIdentity, +} + +struct LaunchInput { + data_dir: PathBuf, + executable: PathBuf, + version: String, + min_vulkan: String, + manual: bool, +} + +impl LaunchSpec { + pub fn installed( + data_dir: PathBuf, + component: InstalledComponent, + ) -> Result { + Self::build(LaunchInput { + data_dir, + executable: component.executable, + version: component.version, + min_vulkan: component.min_vulkan, + manual: false, + }) + } + + pub fn manual(data_dir: PathBuf, executable: PathBuf) -> Result { + Self::build(LaunchInput { + data_dir, + executable, + version: "manual".into(), + min_vulkan: "1.3.0".into(), + manual: true, + }) + } + + fn build(input: LaunchInput) -> Result { + let root = component_root(&input.data_dir); + let identity = load_or_generate_identity(&root, input.manual)?; + Ok(Self { + root, + executable: input.executable, + version: input.version, + min_vulkan: input.min_vulkan, + identity, + }) + } + + pub fn endpoint(&self) -> ServerEndpoint { + self.identity.endpoint.to_endpoint() + } + + pub fn cookie(&self) -> Result { + self.identity.cookie() + } + + /// spawn 前必须在组件锁内统一身份;首次生成的身份也在此落盘。 + pub fn reload_identity_for_spawn(&mut self) -> Result<(), X11ComponentError> { + let path = self.root.join("runtime.json"); + if path.exists() { + self.identity = RuntimeIdentity::read(&path)?; + } else { + self.identity.write(&path)?; + } + Ok(()) + } + + /// 测试及不持锁调用方使用的包装;启动重试必须调用 locked 版本。 + #[cfg(test)] + pub fn refresh_endpoint_after_conflict(&mut self) -> Result<(), X11ComponentError> { + let lock = ComponentLock::acquire(&self.root).map_err(process_error)?; + self.refresh_endpoint_after_conflict_locked(&lock) + } + + /// 调用者必须持有当前组件锁,失败记录清理与 identity 更新不得插入其他启动。 + pub fn refresh_endpoint_after_conflict_locked( + &mut self, + _lock: &ComponentLock, + ) -> Result<(), X11ComponentError> { + let plan = match self.endpoint() { + ServerEndpoint::Inet { .. } => EndpointPlan::random_tcp()?, + ServerEndpoint::Unix(_) => EndpointPlan::random(true)?, + }; + self.identity.endpoint = PersistentEndpoint::from_endpoint(&plan.endpoint()); + self.identity.write(&self.root.join("runtime.json")) + } + + fn command_spec(&self) -> CommandSpec { + let xauth = self.root.join("xauth"); + match self.endpoint() { + ServerEndpoint::Unix(_) => { + CommandSpec::unix(self.executable.clone(), &self.endpoint(), xauth) + } + endpoint @ ServerEndpoint::Inet { .. } if self.version == "manual" => { + CommandSpec::manual_upstream_tcp(self.executable.clone(), &endpoint, xauth) + } + endpoint @ ServerEndpoint::Inet { .. } => { + CommandSpec::installed_tcp(self.executable.clone(), &endpoint, xauth) + } + } + } +} + +pub struct LaunchedChild { + pub child: Child, + pub pid: PidFile, + pub spec: LaunchSpec, +} + +pub async fn spawn_once(spec: &LaunchSpec) -> Result { + ensure_exit_handler()?; + cleanup_orphan(&spec.root.join("yserver.pid"))?; + let mut command = tokio_command(spec)?; + let mut child = command.spawn().map_err(process_error)?; + let child_id = child + .id() + .ok_or_else(|| X11ComponentError::Process("yserver 缺少 pid".into()))?; + let pid = match PidFile::capture(child_id, &spec.executable, &spec.version) { + Ok(pid) => pid, + Err(error) => { + let _ = child.kill().await; + return Err(error); + } + }; + if let Err(error) = write_startup_records(spec, &pid) { + let _ = child.kill().await; + return Err(error); + } + register_exit_cleanup(pid.clone()); + Ok(LaunchedChild { + child, + pid, + spec: spec.clone(), + }) +} + +fn write_startup_records(spec: &LaunchSpec, pid: &PidFile) -> Result<(), X11ComponentError> { + pid.write(&instance_path(&spec.root, pid))?; + if let Err(error) = pid.write(&spec.root.join("yserver.pid")) { + let _ = std::fs::remove_file(instance_path(&spec.root, pid)); + return Err(error); + } + Ok(()) +} + +fn tokio_command(spec: &LaunchSpec) -> Result { + let command_spec = spec.command_spec(); + command_spec.validate_secure_endpoint()?; + let cookie = spec.cookie()?; + let xauth = spec.root.join("xauth"); + write_xauth(&xauth, &spec.endpoint(), &cookie)?; + let mut command = Command::new(command_spec.executable()); + command + .args(command_spec.arguments()) + .env("XAUTHORITY", &xauth) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true); + configure_tokio_background_child(&mut command); + Ok(command) +} + +fn load_or_generate_identity( + root: &PathBuf, + manual: bool, +) -> Result { + let path = root.join("runtime.json"); + if path.exists() { + return RuntimeIdentity::read(&path); + } + let plan = EndpointPlan::random(manual)?; + Ok(RuntimeIdentity::new( + &plan.endpoint(), + &MagicCookie::generate(), + )) +} + +fn ensure_exit_handler() -> Result<(), X11ComponentError> { + static INSTALLED: OnceLock<()> = OnceLock::new(); + if INSTALLED.get().is_none() { + install_exit_handler()?; + let _ = INSTALLED.set(()); + } + Ok(()) +} + +#[cfg(test)] +mod tests; + +fn process_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Process(error.to_string()) +} diff --git a/crates/x11_component/src/launch/tests.rs b/crates/x11_component/src/launch/tests.rs new file mode 100644 index 000000000..21dcae6e9 --- /dev/null +++ b/crates/x11_component/src/launch/tests.rs @@ -0,0 +1,91 @@ +use std::time::Duration; + +use x11_forwarding::{MagicCookie, ServerEndpoint}; + +use crate::lock::ComponentLock; +use crate::runtime::RuntimeIdentity; + +use super::LaunchSpec; + +#[test] +fn initial_port_conflict_rotates_endpoint_but_preserves_cookie() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let root = std::env::temp_dir().join(format!("x11-port-retry-{}", std::process::id())); + let cookie = MagicCookie::from_slice(&[6; 16]).unwrap(); + let mut spec = LaunchSpec { + root: root.clone(), + executable: root.join("yserver"), + version: "manual".into(), + min_vulkan: "1.3.0".into(), + identity: RuntimeIdentity::loopback(port, cookie), + }; + spec.refresh_endpoint_after_conflict().unwrap(); + let ServerEndpoint::Inet { port: rotated, .. } = spec.endpoint() else { + panic!("应保留 TCP 端点类型"); + }; + assert_ne!(rotated, port); + assert!(rotated >= 6000); + assert_eq!(spec.cookie().unwrap().bytes(), &[6; 16]); + let persisted = RuntimeIdentity::read(&root.join("runtime.json")).unwrap(); + assert_eq!(persisted.endpoint, spec.identity.endpoint); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test(flavor = "current_thread")] +async fn build_does_not_wait_for_another_instances_startup_probe() { + let root = std::env::temp_dir().join(format!( + "x11-nonblocking-build-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let data_dir = root; + let component_root = data_dir.join("components/x11"); + std::fs::create_dir_all(&component_root).unwrap(); + let lock = ComponentLock::acquire(&component_root).unwrap(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let releaser = std::thread::spawn(move || { + let _ = release_rx.recv_timeout(Duration::from_secs(2)); + drop(lock); + }); + let started = std::time::Instant::now(); + let mut spec = LaunchSpec::manual(data_dir.clone(), component_root.join("yserver")).unwrap(); + let elapsed = started.elapsed(); + release_tx.send(()).unwrap(); + releaser.join().unwrap(); + assert!( + elapsed < Duration::from_millis(200), + "build 在 async worker 等待组件锁 {elapsed:?}" + ); + assert!(!component_root.join("runtime.json").exists()); + spec.reload_identity_for_spawn().unwrap(); + assert!(component_root.join("runtime.json").is_file()); + std::fs::remove_dir_all(data_dir).unwrap(); +} + +#[test] +fn spawn_reloads_identity_written_by_another_instance() { + let root = std::env::temp_dir().join(format!( + "x11-identity-reload-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let original = RuntimeIdentity::loopback(6010, MagicCookie::from_slice(&[1; 16]).unwrap()); + original.write(&root.join("runtime.json")).unwrap(); + let mut spec = LaunchSpec { + root: root.clone(), + executable: root.join("yserver"), + version: "manual".into(), + min_vulkan: "1.3.0".into(), + identity: original, + }; + let latest = RuntimeIdentity::loopback(6020, MagicCookie::from_slice(&[2; 16]).unwrap()); + latest.write(&root.join("runtime.json")).unwrap(); + spec.reload_identity_for_spawn().unwrap(); + assert_eq!(spec.identity.endpoint, latest.endpoint); + assert_eq!(spec.cookie().unwrap(), latest.cookie().unwrap()); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/src/lib.rs b/crates/x11_component/src/lib.rs new file mode 100644 index 000000000..fa570a9e6 --- /dev/null +++ b/crates/x11_component/src/lib.rs @@ -0,0 +1,117 @@ +//! 内置与本机 X11 服务的解析、验签安装及进程生命周期。 + +use serde::{Deserialize, Serialize}; + +mod archive; +mod bundle; +mod command; +mod install_work; +mod installer; +mod launch; +mod lock; +mod manifest; +mod metrics; +mod paths; +mod process; +mod resolver; +mod restart; +mod rollout; +mod runtime; +mod signature; +mod state; +mod supervisor; +#[cfg(test)] +mod test_support; +mod vulkan; +mod xauth; + +pub use installer::{install_with_config, install_with_config_for_mode, reinstall_with_config}; +pub use metrics::{X11ComponentMetrics, metrics}; +pub use resolver::{installed_version, reinstall, resolve_server}; +pub use signature::verify_ed25519; +pub use state::{ + configured_mode, current_status, resolution_generation, set_configured_mode, set_data_dir, + set_navop_version, take_restart_notification, take_restart_notification_for, +}; + +/// 与程序更新公钥独立;可通过构建环境覆盖,仓库内固定公钥用于离线内嵌组件。 +pub const X11_PUBLIC_KEY_BASE64: &str = match option_env!("NAVOP_X11_PUBLIC_KEY_BASE64") { + Some(key) => key, + None => include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../resources/windows/x11-component/public-key.txt" + )), +}; + +/// X11 服务选择策略。 +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum X11ServerMode { + #[default] + Auto, + External, + Embedded, +} + +/// X11 转发当前状态。 +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum X11ForwardingStatus { + External { server: String }, + Embedded { version: String }, + Disabled { reason: String }, +} + +/// 后台崩溃重启通知;generation 单调递增,UI 消费后从队列移除。 +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct X11RestartNotification { + pub generation: u64, + pub reason: String, +} + +/// X11 组件操作错误。 +#[derive(Debug, thiserror::Error)] +pub enum X11ComponentError { + #[error("当前平台不支持内置 X11 服务:{0}")] + UnsupportedPlatform(String), + #[error("组件清单无效:{0}")] + InvalidManifest(String), + #[error("当前平台没有 X11 组件:{0}")] + MissingArtifact(String), + #[error("X11 组件 SHA256 不匹配")] + Sha256Mismatch { expected: String, actual: String }, + #[error("X11 组件 Ed25519 验签失败:{0}")] + SignatureInvalid(String), + #[error("X11 组件安装失败:{0}")] + Install(String), + #[error("Vulkan 能力不满足要求:需要 {required},实际 {actual:?}")] + VulkanUnavailable { + required: String, + actual: Option, + }, + #[error("X11 握手失败:{0}")] + Handshake(String), + #[error("内置 X11 服务已禁用:{0}")] + EmbeddedDisabled(String), + #[error("另一 Navop 实例已启动内置 X11 服务:{0}")] + ActiveOtherInstance(String), + #[error("X11 服务进程失败:{0}")] + Process(String), + #[error("X11 配置失败:{0}")] + Config(String), +} + +/// X11 解析结果。 +#[derive(Debug)] +pub struct X11Resolution { + pub proxy: Option, + pub status: X11ForwardingStatus, +} + +/// 内嵌安装所需配置;测试通过它注入隔离根目录与临时密钥。 +#[derive(Clone, Debug)] +pub struct InstallConfig { + pub data_dir: std::path::PathBuf, + pub public_key_base64: String, + pub navop_version: semver::Version, + pub target: String, +} diff --git a/crates/x11_component/src/lock.rs b/crates/x11_component/src/lock.rs new file mode 100644 index 000000000..825f1682f --- /dev/null +++ b/crates/x11_component/src/lock.rs @@ -0,0 +1,118 @@ +use std::fs::File; +use std::path::{Path, PathBuf}; + +use fs2::FileExt as _; + +/// 组件根目录的跨进程排他锁;文件描述符随守卫释放。 +pub struct ComponentLock { + _file: File, +} + +impl ComponentLock { + pub fn acquire(root: &Path) -> std::io::Result { + let file = lock_file(root)?; + file.lock_exclusive()?; + Ok(Self { _file: file }) + } + + pub async fn acquire_async(root: PathBuf) -> std::io::Result { + tokio::task::spawn_blocking(move || Self::acquire(&root)) + .await + .map_err(std::io::Error::other)? + } + + pub fn try_acquire(root: &Path) -> std::io::Result> { + let file = lock_file(root)?; + match file.try_lock_exclusive() { + Ok(()) => Ok(Some(Self { _file: file })), + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(None), + Err(error) => Err(error), + } + } +} + +fn lock_file(root: &Path) -> std::io::Result { + std::fs::create_dir_all(root)?; + File::options() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(root.join(".component.lock")) +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::process::{Child, Command}; + use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + + use super::ComponentLock; + + const ROOT_ENV: &str = "NAVOP_X11_LOCK_TEST_ROOT"; + const ID_ENV: &str = "NAVOP_X11_LOCK_TEST_ID"; + + #[test] + fn cross_process_worker() { + let Some(root) = std::env::var_os(ROOT_ENV).map(PathBuf::from) else { + return; + }; + let id = std::env::var(ID_ENV).unwrap(); + std::fs::write(root.join(format!("{id}.started")), b"").unwrap(); + let _lock = ComponentLock::acquire(&root).unwrap(); + std::fs::write(root.join(format!("{id}.locked")), b"").unwrap(); + } + + #[test] + fn component_lock_excludes_another_process() { + let root = test_root(); + let first = ComponentLock::acquire(&root).unwrap(); + let second = spawn_worker(&root, "second"); + wait_for(&root.join("second.started"), Duration::from_secs(5)); + std::thread::sleep(Duration::from_millis(150)); + assert!( + !root.join("second.locked").exists(), + "第一个进程持锁时第二个进程不得进入临界区" + ); + drop(first); + wait_child(second); + assert!(root.join("second.locked").exists()); + std::fs::remove_dir_all(root).unwrap(); + } + + fn spawn_worker(root: &Path, id: &str) -> Child { + Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "lock::tests::cross_process_worker", + "--nocapture", + ]) + .env(ROOT_ENV, root) + .env(ID_ENV, id) + .spawn() + .unwrap() + } + + fn wait_for(path: &Path, timeout: Duration) { + let deadline = Instant::now() + timeout; + while !path.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(path.exists(), "等待 {} 超时", path.display()); + } + + fn wait_child(mut child: Child) { + let status = child.wait().unwrap(); + assert!(status.success(), "锁测试子进程失败:{status}"); + } + + fn test_root() -> PathBuf { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!("x11-lock-{}-{nonce}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + root + } +} diff --git a/crates/x11_component/src/manifest.rs b/crates/x11_component/src/manifest.rs new file mode 100644 index 000000000..9f2b21fc7 --- /dev/null +++ b/crates/x11_component/src/manifest.rs @@ -0,0 +1,169 @@ +use std::collections::BTreeMap; +use std::path::{Component, Path}; + +use semver::{Version, VersionReq}; +use serde::Deserialize; + +use crate::X11ComponentError; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ComponentManifest { + pub schema: u32, + pub components: Components, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Components { + #[serde(rename = "x11-server")] + pub x11_server: X11Component, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct X11Component { + pub channel: String, + pub pinned_for_navop: String, + #[serde(default)] + pub rollout_percent: Option, + #[serde(deserialize_with = "deserialize_artifacts")] + pub artifacts: BTreeMap, +} + +fn deserialize_artifacts<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + struct ArtifactsVisitor; + + impl<'de> serde::de::Visitor<'de> for ArtifactsVisitor { + type Value = BTreeMap; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("不重复的 X11 target 映射") + } + + fn visit_map(self, mut map: A) -> Result + where + A: serde::de::MapAccess<'de>, + { + let mut artifacts = BTreeMap::new(); + while let Some((target, artifact)) = map.next_entry::()? { + if artifacts.insert(target.clone(), artifact).is_some() { + return Err(serde::de::Error::custom(format!("重复 target:{target}"))); + } + } + Ok(artifacts) + } + } + + deserializer.deserialize_map(ArtifactsVisitor) +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ArtifactFormat { + Binary, + Zip, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Artifact { + pub version: String, + pub sha256: String, + pub signature: String, + pub min_vulkan: String, + pub format: ArtifactFormat, + pub executable_path: String, +} + +impl Artifact { + pub fn executable_relative_path(&self) -> &Path { + Path::new(&self.executable_path) + } +} + +impl ComponentManifest { + pub fn parse(text: &str, navop: &Version) -> Result { + let manifest: Self = serde_json::from_str(text) + .map_err(|error| X11ComponentError::InvalidManifest(error.to_string()))?; + manifest.validate(navop)?; + Ok(manifest) + } + + pub fn artifact(&self, target: &str) -> Result { + self.components + .x11_server + .artifacts + .get(target) + .cloned() + .ok_or_else(|| X11ComponentError::MissingArtifact(target.into())) + } + + pub fn rollout_percent(&self) -> u8 { + self.components.x11_server.rollout_percent.unwrap_or(0) + } + + fn validate(&self, navop: &Version) -> Result<(), X11ComponentError> { + if self.schema != 1 { + return invalid("schema 必须为 1"); + } + let component = &self.components.x11_server; + if component.channel != "stable" { + return invalid("channel 必须为 stable"); + } + if component + .rollout_percent + .is_some_and(|percent| percent > 100) + { + return invalid("rollout_percent 不能超过 100"); + } + let requirement = VersionReq::parse(&component.pinned_for_navop) + .map_err(|error| X11ComponentError::InvalidManifest(error.to_string()))?; + if !requirement.matches(navop) { + return invalid(format!("Navop {navop} 不满足 pinned_for_navop")); + } + for artifact in component.artifacts.values() { + validate_artifact(artifact)?; + } + Ok(()) + } +} + +fn validate_artifact(artifact: &Artifact) -> Result<(), X11ComponentError> { + Version::parse(&artifact.version) + .map_err(|error| X11ComponentError::InvalidManifest(error.to_string()))?; + Version::parse(&artifact.min_vulkan) + .map_err(|error| X11ComponentError::InvalidManifest(error.to_string()))?; + validate_executable_path(&artifact.executable_path)?; + let valid_sha = artifact.sha256.len() == 64 + && artifact + .sha256 + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()); + if !valid_sha { + return invalid("sha256 必须为 64 位小写十六进制"); + } + Ok(()) +} + +fn validate_executable_path(path: &str) -> Result<(), X11ComponentError> { + let valid = !path.is_empty() + && !path.contains(['\\', '\0']) + && Path::new(path) + .components() + .all(|part| matches!(part, Component::Normal(_))); + if !valid { + return invalid("executable_path 必须是安全的相对路径"); + } + Ok(()) +} + +fn invalid(reason: impl Into) -> Result { + Err(X11ComponentError::InvalidManifest(reason.into())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/manifest/tests.rs b/crates/x11_component/src/manifest/tests.rs new file mode 100644 index 000000000..0197a11d2 --- /dev/null +++ b/crates/x11_component/src/manifest/tests.rs @@ -0,0 +1,154 @@ +use semver::Version; + +use super::ComponentManifest; +use crate::X11ComponentError; + +fn parse(text: &str) -> Result { + ComponentManifest::parse(text, &Version::new(0, 23, 4)) +} + +fn valid_manifest() -> String { + serde_json::json!({ + "schema": 1, + "components": { + "x11-server": { + "channel": "stable", + "pinned_for_navop": ">=0.16.0, <1.0.0", + "rollout_percent": 25, + "artifacts": { + "windows-x86_64": artifact(), + "windows-aarch64": artifact() + } + } + } + }) + .to_string() +} + +fn artifact() -> serde_json::Value { + serde_json::json!({ + "version": "0.15.2", + "sha256": "a".repeat(64), + "signature": "c2ln", + "min_vulkan": "1.3.0", + "format": "zip", + "executable_path": "bin/yserver.exe" + }) +} + +fn change_manifest(update: impl FnOnce(&mut serde_json::Value)) -> String { + let mut value: serde_json::Value = serde_json::from_str(&valid_manifest()).unwrap(); + update(&mut value); + value.to_string() +} + +#[test] +fn parses_stable_channel_and_platform_artifact() { + let manifest = parse(&valid_manifest()).unwrap(); + assert_eq!(manifest.schema, 1); + assert_eq!( + manifest.artifact("windows-aarch64").unwrap().version, + "0.15.2" + ); + assert!(matches!( + manifest.artifact("linux-x86_64"), + Err(X11ComponentError::MissingArtifact(_)) + )); +} + +#[test] +fn pinned_requirement_matches_navop_version() { + parse(&valid_manifest()).expect("yserver 0.15.2 不应被要求满足 Navop >=0.16"); + let error = ComponentManifest::parse(&valid_manifest(), &Version::new(0, 15, 9)) + .expect_err("旧 Navop 必须被拒绝"); + assert!(error.to_string().contains("pinned_for_navop")); + let invalid = change_manifest(|value| { + value["components"]["x11-server"]["artifacts"]["windows-x86_64"]["version"] = + "latest".into(); + }); + assert!(parse(&invalid).is_err()); +} + +#[test] +fn rejects_unknown_schema_and_nonstable_channel() { + for text in [ + change_manifest(|value| value["schema"] = 2.into()), + change_manifest(|value| value["components"]["x11-server"]["channel"] = "beta".into()), + ] { + assert!(matches!( + parse(&text), + Err(X11ComponentError::InvalidManifest(_)) + )); + } +} + +#[test] +fn artifact_format_and_executable_path_are_validated() { + for path in ["", "../yserver.exe", "/tmp/yserver", "bin/../../yserver"] { + let text = change_manifest(|value| { + value["components"]["x11-server"]["artifacts"]["windows-x86_64"]["executable_path"] = + path.into(); + }); + assert!(parse(&text).is_err(), "危险路径:{path}"); + } + let missing = change_manifest(|value| { + let artifact = &mut value["components"]["x11-server"]["artifacts"]["windows-x86_64"]; + artifact.as_object_mut().unwrap().remove("format"); + }); + assert!(parse(&missing).is_err()); +} + +#[test] +fn duplicate_target_is_rejected_instead_of_overwritten() { + let artifact = artifact().to_string(); + let text = format!( + r#"{{ + "schema": 1, + "components": {{ + "x11-server": {{ + "channel": "stable", + "pinned_for_navop": ">=0.16.0, <1.0.0", + "artifacts": {{ + "windows-x86_64": {artifact}, + "windows-x86_64": {artifact} + }} + }} + }} + }}"# + ); + let error = parse(&text).unwrap_err(); + assert!( + error.to_string().contains("重复"), + "重复 target 必须 fail-closed:{error}" + ); +} + +#[test] +fn runtime_manifest_rejects_legacy_url_metadata() { + let text = change_manifest(|value| { + value["components"]["x11-server"]["artifacts"]["windows-x86_64"]["url"] = + "https://example.invalid/yserver.zip".into(); + }); + assert!(matches!( + parse(&text), + Err(X11ComponentError::InvalidManifest(_)) + )); +} + +#[test] +fn artifact_hash_vulkan_and_rollout_are_validated() { + let cases = [ + ("sha256", "not-sha".into()), + ("min_vulkan", "latest".into()), + ]; + for (field, value) in cases { + let text = change_manifest(|root| { + root["components"]["x11-server"]["artifacts"]["windows-x86_64"][field] = value; + }); + assert!(parse(&text).is_err(), "字段:{field}"); + } + let text = change_manifest(|value| { + value["components"]["x11-server"]["rollout_percent"] = 101.into(); + }); + assert!(parse(&text).is_err()); +} diff --git a/crates/x11_component/src/metrics.rs b/crates/x11_component/src/metrics.rs new file mode 100644 index 000000000..cd43e3170 --- /dev/null +++ b/crates/x11_component/src/metrics.rs @@ -0,0 +1,79 @@ +use std::sync::atomic::{AtomicU64, Ordering}; + +/// 进程内 X11 组件计数快照,供 dogfood 日志和 UI 只读查询。 +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct X11ComponentMetrics { + /// 内置服务首次启动成功次数,不含崩溃重启。 + pub embedded_starts: u64, + /// 监测到已运行的内置服务退出或状态读取失败次数。 + pub crashes: u64, + /// 崩溃后成功恢复握手次数。 + pub restarts: u64, + /// Auto 外部探测不可用而转入内置路径的次数。 + pub auto_external_fallbacks: u64, + /// Embedded 或 Auto 的内置路径最终返回错误次数。 + pub embedded_failures: u64, +} + +#[derive(Clone, Copy)] +pub(crate) enum MetricEvent { + EmbeddedStart, + Crash, + Restart, + AutoExternalFallback, + EmbeddedFailure, +} + +impl MetricEvent { + fn name(self) -> &'static str { + match self { + Self::EmbeddedStart => "embedded_start", + Self::Crash => "crash", + Self::Restart => "restart", + Self::AutoExternalFallback => "auto_external_fallback", + Self::EmbeddedFailure => "embedded_failure", + } + } +} + +static EMBEDDED_STARTS: AtomicU64 = AtomicU64::new(0); +static CRASHES: AtomicU64 = AtomicU64::new(0); +static RESTARTS: AtomicU64 = AtomicU64::new(0); +static AUTO_EXTERNAL_FALLBACKS: AtomicU64 = AtomicU64::new(0); +static EMBEDDED_FAILURES: AtomicU64 = AtomicU64::new(0); + +/// 返回当前进程的单调计数;不发送远端遥测。 +pub fn metrics() -> X11ComponentMetrics { + X11ComponentMetrics { + embedded_starts: EMBEDDED_STARTS.load(Ordering::Relaxed), + crashes: CRASHES.load(Ordering::Relaxed), + restarts: RESTARTS.load(Ordering::Relaxed), + auto_external_fallbacks: AUTO_EXTERNAL_FALLBACKS.load(Ordering::Relaxed), + embedded_failures: EMBEDDED_FAILURES.load(Ordering::Relaxed), + } +} + +pub(crate) fn record(event: MetricEvent) { + let counter = match event { + MetricEvent::EmbeddedStart => &EMBEDDED_STARTS, + MetricEvent::Crash => &CRASHES, + MetricEvent::Restart => &RESTARTS, + MetricEvent::AutoExternalFallback => &AUTO_EXTERNAL_FALLBACKS, + MetricEvent::EmbeddedFailure => &EMBEDDED_FAILURES, + }; + counter.fetch_add(1, Ordering::Relaxed); + let snapshot = metrics(); + tracing::info!( + target: "x11_component.metrics", + event = event.name(), + embedded_starts = snapshot.embedded_starts, + crashes = snapshot.crashes, + restarts = snapshot.restarts, + auto_external_fallbacks = snapshot.auto_external_fallbacks, + embedded_failures = snapshot.embedded_failures, + "X11 组件状态转换" + ); +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/metrics/tests.rs b/crates/x11_component/src/metrics/tests.rs new file mode 100644 index 000000000..664b94aa1 --- /dev/null +++ b/crates/x11_component/src/metrics/tests.rs @@ -0,0 +1,21 @@ +use super::{MetricEvent, metrics, record}; + +#[test] +fn metric_events_update_the_public_snapshot() { + let _guard = crate::test_support::global_state_lock(); + let before = metrics(); + record(MetricEvent::EmbeddedStart); + record(MetricEvent::Crash); + record(MetricEvent::Restart); + record(MetricEvent::AutoExternalFallback); + record(MetricEvent::EmbeddedFailure); + let after = crate::metrics(); + assert_eq!(after.embedded_starts, before.embedded_starts + 1); + assert_eq!(after.crashes, before.crashes + 1); + assert_eq!(after.restarts, before.restarts + 1); + assert_eq!( + after.auto_external_fallbacks, + before.auto_external_fallbacks + 1 + ); + assert_eq!(after.embedded_failures, before.embedded_failures + 1); +} diff --git a/crates/x11_component/src/paths.rs b/crates/x11_component/src/paths.rs new file mode 100644 index 000000000..ed4f08f7d --- /dev/null +++ b/crates/x11_component/src/paths.rs @@ -0,0 +1,206 @@ +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +use rand::{RngCore as _, rngs::OsRng}; +use semver::Version; + +use crate::state::{configured_data_dir, configured_navop_version}; +use crate::{InstallConfig, X11ComponentError}; + +pub const COMPONENT_RELATIVE_PATH: &str = "components/x11"; + +pub fn component_root(data_dir: &Path) -> PathBuf { + data_dir.join(COMPONENT_RELATIVE_PATH) +} + +pub fn read_installed(root: &Path) -> Option { + let version = std::fs::read_to_string(root.join("current")).ok()?; + let version = version.trim(); + Version::parse(version).ok()?; + root.join("versions") + .join(version) + .exists() + .then(|| version.to_string()) +} + +pub fn write_current(root: &Path, version: &str) -> Result<(), X11ComponentError> { + atomic_write(&root.join("current"), version.as_bytes()) +} + +/// 同目录临时文件配合系统原子替换,Windows 也允许覆盖旧值。 +pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), X11ComponentError> { + atomic_write_mode(path, bytes, false) +} + +/// cookie 等机密文件从临时文件创建起就只能由所有者读写。 +pub fn atomic_write_private(path: &Path, bytes: &[u8]) -> Result<(), X11ComponentError> { + atomic_write_mode(path, bytes, true) +} + +fn atomic_write_mode(path: &Path, bytes: &[u8], private: bool) -> Result<(), X11ComponentError> { + let parent = path + .parent() + .ok_or_else(|| X11ComponentError::Install("目标路径缺少父目录".into()))?; + std::fs::create_dir_all(parent).map_err(install_error)?; + let mut random = [0; 8]; + OsRng.fill_bytes(&mut random); + let temporary = path.with_extension(format!("tmp-{}", hex::encode(random))); + let request = WriteRequest { + temporary: &temporary, + path, + bytes, + private, + }; + let result = write_and_replace(request); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +struct WriteRequest<'a> { + temporary: &'a Path, + path: &'a Path, + bytes: &'a [u8], + private: bool, +} + +fn write_and_replace(request: WriteRequest<'_>) -> Result<(), X11ComponentError> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if request.private { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options.open(request.temporary).map_err(install_error)?; + std::io::Write::write_all(&mut file, request.bytes).map_err(install_error)?; + file.sync_all().map_err(install_error)?; + replace_file(request.temporary, request.path)?; + restrict_permissions(request.path, request.private) +} + +#[cfg(unix)] +fn restrict_permissions(path: &Path, private: bool) -> Result<(), X11ComponentError> { + if private { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) + .map_err(install_error)?; + } + Ok(()) +} + +#[cfg(not(unix))] +fn restrict_permissions(_path: &Path, _private: bool) -> Result<(), X11ComponentError> { + Ok(()) +} + +#[cfg(not(target_os = "windows"))] +fn replace_file(temporary: &Path, path: &Path) -> Result<(), X11ComponentError> { + std::fs::rename(temporary, path).map_err(install_error) +} + +#[cfg(target_os = "windows")] +fn replace_file(temporary: &Path, path: &Path) -> Result<(), X11ComponentError> { + use std::os::windows::ffi::OsStrExt as _; + let source = temporary + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + let destination = path + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + // SAFETY:两个 UTF-16 缓冲区均以 NUL 结尾且在本调用期间存活。 + let replaced = unsafe { MoveFileExW(source.as_ptr(), destination.as_ptr(), 0x1 | 0x8) }; + if replaced == 0 { + return Err(install_error(std::io::Error::last_os_error())); + } + Ok(()) +} + +#[cfg(target_os = "windows")] +#[link(name = "kernel32")] +unsafe extern "system" { + fn MoveFileExW(existing: *const u16, replacement: *const u16, flags: u32) -> i32; +} + +#[cfg(test)] +pub fn prune_versions(root: &Path) -> Result<(), X11ComponentError> { + prune_versions_preserving(root, &BTreeSet::new()) +} + +pub fn prune_versions_preserving( + root: &Path, + protected: &BTreeSet, +) -> Result<(), X11ComponentError> { + let mut protected = protected.clone(); + if let Ok(current) = std::fs::read_to_string(root.join("current")) { + protected.insert(current.trim().to_string()); + } + prune_directory(&root.join("versions"), &protected) +} + +fn prune_directory( + versions_root: &Path, + protected: &BTreeSet, +) -> Result<(), X11ComponentError> { + let mut versions = std::fs::read_dir(&versions_root) + .map_err(install_error)? + .filter_map(Result::ok) + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + Version::parse(&name) + .ok() + .map(|version| (version, entry.path())) + }) + .collect::>(); + versions.sort_by(|left, right| right.0.cmp(&left.0)); + let retained = versions + .iter() + .take(2) + .map(|(version, _)| version.clone()) + .collect::>(); + for (version, path) in versions { + if !protected.contains(version.to_string().as_str()) && !retained.contains(&version) { + std::fs::remove_dir_all(path).map_err(install_error)?; + } + } + Ok(()) +} + +pub fn default_config() -> Result { + if crate::X11_PUBLIC_KEY_BASE64.is_empty() { + return Err(X11ComponentError::Config( + "X11 组件发布公钥尚未配置,已 fail-closed".into(), + )); + } + Ok(InstallConfig { + data_dir: configured_data_dir()?, + public_key_base64: crate::X11_PUBLIC_KEY_BASE64.into(), + navop_version: configured_navop_version()?, + target: current_target()?.into(), + }) +} + +pub fn current_target() -> Result<&'static str, X11ComponentError> { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("windows", "x86_64") => Ok("windows-x86_64"), + ("windows", "aarch64") => Ok("windows-aarch64"), + ("linux", "x86_64") => Ok("linux-x86_64"), + ("linux", "aarch64") => Ok("linux-aarch64"), + ("macos", _) => Err(X11ComponentError::UnsupportedPlatform("macOS".into())), + (os, arch) => Err(X11ComponentError::UnsupportedPlatform(format!( + "{os}-{arch}" + ))), + } +} + +fn install_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Install(error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/paths/tests.rs b/crates/x11_component/src/paths/tests.rs new file mode 100644 index 000000000..065985636 --- /dev/null +++ b/crates/x11_component/src/paths/tests.rs @@ -0,0 +1,72 @@ +use super::{atomic_write, component_root, prune_versions, prune_versions_preserving}; + +fn test_root(name: &str) -> std::path::PathBuf { + let root = std::env::temp_dir().join(format!("x11-paths-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + root +} + +#[test] +fn atomic_write_replaces_existing_files() { + let root = test_root("replace"); + let path = root.join("runtime.json"); + atomic_write(&path, b"first").unwrap(); + atomic_write(&path, b"second").unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"second"); + assert_eq!(std::fs::read_dir(&root).unwrap().count(), 1); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn keeps_latest_two_versions() { + let root = test_root("prune"); + for version in ["1.0.0", "1.2.0", "1.1.0"] { + std::fs::create_dir_all(root.join("versions").join(version)).unwrap(); + } + prune_versions(&root).unwrap(); + assert!(!root.join("versions/1.0.0").exists()); + assert!(root.join("versions/1.1.0").exists()); + assert!(root.join("versions/1.2.0").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn prune_preserves_active_old_version() { + let root = test_root("prune-active"); + for version in ["0.9.0", "1.0.0", "1.1.0", "1.2.0"] { + std::fs::create_dir_all(root.join("versions").join(version)).unwrap(); + } + prune_versions_preserving(&root, &["0.9.0".into()].into()).unwrap(); + assert!(root.join("versions/0.9.0").exists()); + assert!(!root.join("versions/1.0.0").exists()); + assert!(root.join("versions/1.1.0").exists()); + assert!(root.join("versions/1.2.0").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn installing_older_version_preserves_current_and_installed_version() { + let root = test_root("prune-older-current"); + for version in ["1.8.0", "1.9.0", "1.10.0"] { + std::fs::create_dir_all(root.join("versions").join(version)).unwrap(); + } + super::write_current(&root, "1.8.0").unwrap(); + prune_versions_preserving(&root, &["1.8.0".into()].into()).unwrap(); + assert!( + root.join("versions/1.8.0").exists(), + "刚写入 current 的版本不得删除" + ); + assert!( + root.join("versions/1.9.0").exists(), + "仍保留最新两个非保护版本" + ); + assert!(root.join("versions/1.10.0").exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn injected_product_data_dir_is_not_nested() { + let root = component_root(std::path::Path::new("/tmp/navop")); + assert_eq!(root, std::path::Path::new("/tmp/navop/components/x11")); +} diff --git a/crates/x11_component/src/process.rs b/crates/x11_component/src/process.rs new file mode 100644 index 000000000..35a023626 --- /dev/null +++ b/crates/x11_component/src/process.rs @@ -0,0 +1,237 @@ +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; +use sysinfo::{Pid, ProcessesToUpdate, System}; + +use crate::X11ComponentError; +use crate::lock::ComponentLock; +use crate::paths::atomic_write; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct PidFile { + pub pid: u32, + pub started_at: u64, + pub executable: PathBuf, + #[serde(default = "legacy_record_version")] + pub version: String, + pub owner_pid: u32, + pub owner_started_at: u64, +} + +impl PidFile { + pub fn read(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(process_error)?; + serde_json::from_slice(&bytes).map_err(|error| X11ComponentError::Config(error.to_string())) + } + + pub fn write(&self, path: &Path) -> Result<(), X11ComponentError> { + let bytes = serde_json::to_vec(self) + .map_err(|error| X11ComponentError::Process(error.to_string()))?; + atomic_write(path, &bytes) + } + + pub fn capture( + pid: u32, + _expected_executable: &Path, + version: &str, + ) -> Result { + let identity = process_identity(pid) + .ok_or_else(|| X11ComponentError::Process("无法读取 yserver 进程身份".into()))?; + let owner = process_identity(std::process::id()) + .ok_or_else(|| X11ComponentError::Process("无法读取 Navop 进程身份".into()))?; + Ok(Self { + pid, + started_at: identity.0, + executable: identity.1, + version: version.to_string(), + owner_pid: std::process::id(), + owner_started_at: owner.0, + }) + } +} + +pub fn instance_path(root: &Path, record: &PidFile) -> PathBuf { + root.join("instances").join(format!( + "{}-{}.json", + record.owner_pid, record.owner_started_at + )) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum OrphanState { + Active, + Orphan, + Stale, +} + +pub fn same_process(record: &PidFile, current: Option<(u64, PathBuf)>) -> bool { + current.is_some_and(|(started_at, executable)| { + started_at == record.started_at && executable == record.executable + }) +} + +pub fn orphan_state( + record: &PidFile, + child: Option<(u64, PathBuf)>, + owner: Option<(u64, ())>, +) -> OrphanState { + if !same_process(record, child) { + return OrphanState::Stale; + } + if owner == Some((record.owner_started_at, ())) { + OrphanState::Active + } else { + OrphanState::Orphan + } +} + +/// 启动前同时检查共享记录和各实例记录,覆盖只写完实例记录的崩溃窗口。 +pub fn cleanup_orphan(path: &Path) -> Result<(), X11ComponentError> { + cleanup_record(path)?; + let Some(root) = path.parent() else { + return Ok(()); + }; + let instances = root.join("instances"); + if !instances.exists() { + return Ok(()); + } + for entry in std::fs::read_dir(instances).map_err(process_error)? { + cleanup_record(&entry.map_err(process_error)?.path())?; + } + Ok(()) +} + +/// 活跃记录可能属于另一 Navop 实例;只有确认 stale 后才删除文件,绝不杀它。 +fn cleanup_record(path: &Path) -> Result<(), X11ComponentError> { + if !path.exists() { + return Ok(()); + } + let record = match PidFile::read(path) { + Ok(record) => record, + Err(X11ComponentError::Config(_)) => return Ok(()), + Err(error) => return Err(error), + }; + let owner = process_identity(record.owner_pid).map(|identity| (identity.0, ())); + match orphan_state(&record, process_identity(record.pid), owner) { + OrphanState::Active => Err(X11ComponentError::ActiveOtherInstance( + "pidfile 属于另一活跃 Navop 实例;拒绝清理".into(), + )), + OrphanState::Orphan => { + // 身份已匹配的子进程可能恰好退出;无论 kill 结果都移除该实例记录。 + let _ = kill_owned(&record); + std::fs::remove_file(path).map_err(process_error) + } + OrphanState::Stale => std::fs::remove_file(path).map_err(process_error), + } +} + +/// 只有共享 pidfile 仍记录同一子进程时才允许删除。 +pub fn remove_pidfile_if_owned(root: &Path, owned: &PidFile) -> Result<(), X11ComponentError> { + let Some(_lock) = ComponentLock::try_acquire(root).map_err(process_error)? else { + return Ok(()); + }; + remove_owned_files(root, owned) +} + +pub(crate) fn remove_owned_files(root: &Path, owned: &PidFile) -> Result<(), X11ComponentError> { + let path = root.join("yserver.pid"); + if path.exists() && PidFile::read(&path).is_ok_and(|current| current == *owned) { + std::fs::remove_file(path).map_err(process_error)?; + } + remove_if_matching(&instance_path(root, owned), owned) +} + +fn remove_if_matching(path: &Path, owned: &PidFile) -> Result<(), X11ComponentError> { + if path.exists() && PidFile::read(path).is_ok_and(|current| current == *owned) { + std::fs::remove_file(path).map_err(process_error)?; + } + Ok(()) +} + +/// 扫描每实例记录;owner 已退出但 yserver 尚存时同样保护其版本。 +pub fn active_versions(root: &Path) -> Result, X11ComponentError> { + let mut versions = BTreeSet::new(); + let directory = root.join("instances"); + if !directory.exists() { + return Ok(versions); + } + for entry in std::fs::read_dir(directory).map_err(process_error)? { + let path = entry.map_err(process_error)?.path(); + let Ok(record) = PidFile::read(&path) else { + continue; + }; + if same_process(&record, process_identity(record.pid)) { + versions.insert(record.version); + } else { + let _ = std::fs::remove_file(path); + } + } + Ok(versions) +} + +/// 仅用于本进程子进程或 owner 已确认死亡的孤儿。 +pub fn kill_owned(record: &PidFile) -> bool { + let mut system = System::new(); + system.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(record.pid)])); + let current = system.process(Pid::from_u32(record.pid)).map(|process| { + ( + process.start_time(), + process.exe().map_or_else(PathBuf::new, Path::to_path_buf), + ) + }); + if same_process(record, current) { + if let Some(process) = system.process(Pid::from_u32(record.pid)) { + return process.kill(); + } + } + false +} + +static EXIT_RECORD: Mutex> = Mutex::new(None); + +pub fn register_exit_cleanup(record: PidFile) { + *EXIT_RECORD + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = Some(record); +} + +extern "C" fn cleanup_at_exit() { + if let Some(record) = EXIT_RECORD + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .take() + { + kill_owned(&record); + } +} + +pub fn install_exit_handler() -> Result<(), X11ComponentError> { + // SAFETY:注册只执行一次,回调在进程正常退出时清理自己的 yserver。 + if unsafe { libc::atexit(cleanup_at_exit) } != 0 { + return Err(X11ComponentError::Process("注册退出清理失败".into())); + } + Ok(()) +} + +fn legacy_record_version() -> String { + "legacy".into() +} + +fn process_identity(pid: u32) -> Option<(u64, PathBuf)> { + let mut system = System::new(); + system.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid)])); + let process = system.process(Pid::from_u32(pid))?; + Some(( + process.start_time(), + process.exe().map_or_else(PathBuf::new, Path::to_path_buf), + )) +} + +fn process_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Process(error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/process/tests.rs b/crates/x11_component/src/process/tests.rs new file mode 100644 index 000000000..9a8e8f013 --- /dev/null +++ b/crates/x11_component/src/process/tests.rs @@ -0,0 +1,169 @@ +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn test_root(name: &str) -> PathBuf { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!("x11-{name}-{}-{nonce}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + root +} + +use crate::X11ComponentError; + +use super::{ + OrphanState, PidFile, cleanup_orphan, instance_path, orphan_state, remove_pidfile_if_owned, + same_process, +}; + +fn record() -> PidFile { + PidFile { + pid: 42, + started_at: 100, + executable: PathBuf::from("/opt/navop/yserver"), + version: "1.9.0".into(), + owner_pid: 7, + owner_started_at: 50, + } +} + +#[test] +fn pid_reuse_and_executable_change_prevent_cleanup() { + let record = record(); + assert!(same_process( + &record, + Some((100, record.executable.clone())) + )); + assert!(!same_process( + &record, + Some((101, record.executable.clone())) + )); + assert!(!same_process( + &record, + Some((100, PathBuf::from("/tmp/other"))) + )); + assert!(!same_process(&record, None)); +} + +#[test] +fn pidfile_roundtrip_and_corrupt_input() { + let root = test_root("pid"); + let path = root.join("yserver.pid"); + let record = record(); + record.write(&path).unwrap(); + assert_eq!(PidFile::read(&path).unwrap(), record); + std::fs::write(&path, "{broken").unwrap(); + assert!(PidFile::read(&path).is_err()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn pidfile_is_removed_only_when_still_owned_by_this_server() { + let root = test_root("owned-pid"); + let path = root.join("yserver.pid"); + let owned = record(); + owned.write(&path).unwrap(); + remove_pidfile_if_owned(&root, &owned).unwrap(); + assert!(!path.exists(), "仍属于自己的记录应被清理"); + + let mut replacement = record(); + replacement.pid += 1; + replacement.write(&path).unwrap(); + remove_pidfile_if_owned(&root, &owned).unwrap(); + assert_eq!(PidFile::read(&path).unwrap(), replacement); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn active_server_has_a_distinct_error() { + let root = test_root("active-pid"); + let record = PidFile::capture( + std::process::id(), + &std::env::current_exe().unwrap(), + "1.9.0", + ) + .unwrap(); + record.write(&root.join("yserver.pid")).unwrap(); + let result = cleanup_orphan(&root.join("yserver.pid")); + assert!( + matches!(result, Err(X11ComponentError::ActiveOtherInstance(_))), + "实际结果:{result:?}" + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn instance_record_without_shared_pidfile_still_blocks_another_launch() { + let root = test_root("instance-without-shared-pid"); + let record = PidFile::capture( + std::process::id(), + &std::env::current_exe().unwrap(), + "1.9.0", + ) + .unwrap(); + record.write(&instance_path(&root, &record)).unwrap(); + let result = cleanup_orphan(&root.join("yserver.pid")); + assert!( + matches!(result, Err(X11ComponentError::ActiveOtherInstance(_))), + "实际结果:{result:?}" + ); + assert!(instance_path(&root, &record).is_file()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn orphan_process_worker() { + if std::env::var_os("NAVOP_X11_ORPHAN_TEST_WORKER").is_some() { + std::thread::sleep(std::time::Duration::from_secs(30)); + } +} + +#[test] +fn instance_scan_removes_stale_records_and_cleans_live_orphans() { + let root = test_root("instance-stale"); + let stale = record(); + stale.write(&instance_path(&root, &stale)).unwrap(); + cleanup_orphan(&root.join("yserver.pid")).unwrap(); + assert!(!instance_path(&root, &stale).exists()); + + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "process::tests::orphan_process_worker", + "--nocapture", + ]) + .env("NAVOP_X11_ORPHAN_TEST_WORKER", "1") + .spawn() + .unwrap(); + let mut orphan = + PidFile::capture(child.id(), &std::env::current_exe().unwrap(), "1.9.0").unwrap(); + orphan.owner_pid = u32::MAX; + orphan.owner_started_at = 0; + orphan.write(&instance_path(&root, &orphan)).unwrap(); + cleanup_orphan(&root.join("yserver.pid")).unwrap(); + assert!(!instance_path(&root, &orphan).exists()); + let status = child.wait().unwrap(); + assert!(!status.success(), "活孤儿子进程应被终止"); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn active_other_instance_is_preserved_and_dead_owner_allows_cleanup() { + let record = record(); + let child = Some((100, record.executable.clone())); + assert_eq!( + orphan_state(&record, child.clone(), Some((50, ()))), + OrphanState::Active + ); + assert_eq!( + orphan_state(&record, child.clone(), None), + OrphanState::Orphan + ); + assert_eq!( + orphan_state(&record, child, Some((51, ()))), + OrphanState::Orphan + ); + assert_eq!(orphan_state(&record, None, None), OrphanState::Stale); +} diff --git a/crates/x11_component/src/resolver.rs b/crates/x11_component/src/resolver.rs new file mode 100644 index 000000000..20e03d4c5 --- /dev/null +++ b/crates/x11_component/src/resolver.rs @@ -0,0 +1,103 @@ +use std::path::PathBuf; + +use x11_forwarding::{ServerEndpoint, detect_local_server}; + +use crate::installer::prepare; +use crate::launch::LaunchSpec; +use crate::metrics::{MetricEvent, record}; +use crate::paths::{component_root, default_config, read_installed}; +use crate::state::{configured_data_dir, embedded_disable_reason, update_status}; +use crate::supervisor::start; +use crate::{X11ComponentError, X11ForwardingStatus, X11Resolution, X11ServerMode}; + +static RESOLVE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +pub async fn resolve_server(mode: X11ServerMode) -> X11Resolution { + let _guard = RESOLVE_LOCK.lock().await; + let resolution = match mode { + X11ServerMode::External => external().await, + X11ServerMode::Embedded => embedded(mode).await, + X11ServerMode::Auto => match external().await { + Ok(resolution) => Ok(resolution), + Err(_) => { + record(MetricEvent::AutoExternalFallback); + embedded(mode).await + } + }, + }; + if resolution.is_err() && mode != X11ServerMode::External { + record(MetricEvent::EmbeddedFailure); + } + let resolution = resolution.unwrap_or_else(disabled); + update_status(resolution.status.clone()); + resolution +} + +pub fn installed_version() -> Option { + let data_dir = configured_data_dir().ok()?; + read_installed(&component_root(&data_dir)) +} + +pub async fn reinstall() -> Result { + if !cfg!(target_os = "windows") { + return Err(X11ComponentError::UnsupportedPlatform( + std::env::consts::OS.into(), + )); + } + crate::reinstall_with_config(default_config()?).await +} + +async fn external() -> Result { + let proxy = tokio::task::spawn_blocking(detect_local_server) + .await + .map_err(|error| X11ComponentError::Process(error.to_string()))? + .map_err(|error| X11ComponentError::Config(error.to_string()))?; + let server = endpoint_name(proxy.endpoint()); + Ok(X11Resolution { + proxy: Some(proxy), + status: X11ForwardingStatus::External { server }, + }) +} + +async fn embedded(mode: X11ServerMode) -> Result { + if let Some(reason) = embedded_disable_reason() { + return Err(X11ComponentError::EmbeddedDisabled(reason)); + } + if !cfg!(target_os = "windows") { + return Err(X11ComponentError::UnsupportedPlatform( + std::env::consts::OS.into(), + )); + } + let spec = match manual_binary() { + Some(executable) => LaunchSpec::manual(configured_data_dir()?, executable)?, + None => { + let config = default_config()?; + let data_dir = config.data_dir.clone(); + let component = prepare(config, mode).await?; + LaunchSpec::installed(data_dir, component)? + } + }; + start(spec).await +} + +fn manual_binary() -> Option { + std::env::var_os("NAVOP_X11_YSERVER_PATH") + .filter(|path| !path.is_empty()) + .map(PathBuf::from) +} + +fn endpoint_name(endpoint: &ServerEndpoint) -> String { + match endpoint { + ServerEndpoint::Unix(path) => path.display().to_string(), + ServerEndpoint::Inet { host, port } => format!("{host}:{port}"), + } +} + +fn disabled(error: X11ComponentError) -> X11Resolution { + X11Resolution { + proxy: None, + status: X11ForwardingStatus::Disabled { + reason: error.to_string(), + }, + } +} diff --git a/crates/x11_component/src/restart.rs b/crates/x11_component/src/restart.rs new file mode 100644 index 000000000..bbcac0c54 --- /dev/null +++ b/crates/x11_component/src/restart.rs @@ -0,0 +1,31 @@ +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +const WINDOW: Duration = Duration::from_secs(10 * 60); +const MAX_RESTARTS: usize = 3; + +/// 崩溃重启滑动窗口;第四次崩溃会关闭本次运行的内置路径。 +#[derive(Default)] +pub struct RestartBudget { + crashes: VecDeque, +} + +impl RestartBudget { + pub fn record_crash(&mut self, now: Instant) -> bool { + while self + .crashes + .front() + .is_some_and(|time| now.saturating_duration_since(*time) >= WINDOW) + { + self.crashes.pop_front(); + } + if self.crashes.len() >= MAX_RESTARTS { + return false; + } + self.crashes.push_back(now); + true + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/restart/tests.rs b/crates/x11_component/src/restart/tests.rs new file mode 100644 index 000000000..19ff586b8 --- /dev/null +++ b/crates/x11_component/src/restart/tests.rs @@ -0,0 +1,15 @@ +use std::time::{Duration, Instant}; + +use super::RestartBudget; + +#[test] +fn restart_budget_allows_three_crashes_per_ten_minutes() { + let start = Instant::now(); + let mut budget = RestartBudget::default(); + assert!(budget.record_crash(start)); + assert!(budget.record_crash(start + Duration::from_secs(1))); + assert!(budget.record_crash(start + Duration::from_secs(2))); + assert!(!budget.record_crash(start + Duration::from_secs(3))); + assert!(!budget.record_crash(start + Duration::from_secs(599))); + assert!(budget.record_crash(start + Duration::from_secs(601))); +} diff --git a/crates/x11_component/src/rollout.rs b/crates/x11_component/src/rollout.rs new file mode 100644 index 000000000..049a1d555 --- /dev/null +++ b/crates/x11_component/src/rollout.rs @@ -0,0 +1,66 @@ +use std::io::ErrorKind; +use std::path::Path; + +use rand::{RngCore as _, rngs::OsRng}; + +use crate::{X11ComponentError, X11ServerMode}; + +/// 每台机器使用持久随机编号,避免清单变化时灰度组漂移。 +pub fn persistent_rollout_id(root: &Path) -> Result { + std::fs::create_dir_all(root).map_err(config_error)?; + let path = root.join("rollout-id"); + match std::fs::read_to_string(&path) { + Ok(text) => return parse_rollout_id(&text), + Err(error) if error.kind() != ErrorKind::NotFound => return Err(config_error(error)), + Err(_) => {} + } + let id = OsRng.next_u64(); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(mut file) => { + use std::io::Write as _; + file.write_all(id.to_string().as_bytes()) + .map_err(config_error)?; + Ok(id) + } + Err(error) if error.kind() == ErrorKind::AlreadyExists => persistent_rollout_id(root), + Err(error) => Err(config_error(error)), + } +} + +/// Auto 遵守内置清单灰度;显式 Embedded 是 dogfood 入口,External 不触发内置。 +pub fn should_use_embedded( + root: &Path, + mode: X11ServerMode, + percent: u8, +) -> Result { + match mode { + X11ServerMode::External => Ok(false), + X11ServerMode::Embedded => Ok(true), + X11ServerMode::Auto => { + if percent >= 100 { + return Ok(true); + } + if percent == 0 { + return Ok(false); + } + Ok((persistent_rollout_id(root)? % 100) < u64::from(percent)) + } + } +} + +fn parse_rollout_id(text: &str) -> Result { + text.trim() + .parse() + .map_err(|_| X11ComponentError::Config("rollout-id 已损坏".into())) +} + +fn config_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Config(error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/rollout/tests.rs b/crates/x11_component/src/rollout/tests.rs new file mode 100644 index 000000000..342bd42fe --- /dev/null +++ b/crates/x11_component/src/rollout/tests.rs @@ -0,0 +1,46 @@ +use super::{persistent_rollout_id, should_use_embedded}; +use crate::X11ServerMode; + +fn temp_root(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "x11-rollout-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&path).unwrap(); + path +} + +#[test] +fn rollout_id_is_persistent_and_bounds_are_enforced() { + let root = temp_root("persistent"); + let first = persistent_rollout_id(&root).unwrap(); + let second = persistent_rollout_id(&root).unwrap(); + assert_eq!(first, second); + assert_eq!( + std::fs::read_to_string(root.join("rollout-id")).unwrap(), + first.to_string() + ); + assert!(!should_use_embedded(&root, X11ServerMode::Auto, 0).unwrap()); + assert!(should_use_embedded(&root, X11ServerMode::Auto, 100).unwrap()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn explicit_embedded_allows_dogfood_and_external_skips_rollout() { + let root = temp_root("dogfood"); + assert!(should_use_embedded(&root, X11ServerMode::Embedded, 0).unwrap()); + assert!(!should_use_embedded(&root, X11ServerMode::External, 100).unwrap()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn corrupt_rollout_id_is_rejected() { + let root = temp_root("invalid"); + std::fs::write(root.join("rollout-id"), "not-a-number").unwrap(); + assert!(persistent_rollout_id(&root).is_err()); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/src/runtime.rs b/crates/x11_component/src/runtime.rs new file mode 100644 index 000000000..0413a73ae --- /dev/null +++ b/crates/x11_component/src/runtime.rs @@ -0,0 +1,105 @@ +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use x11_forwarding::{MagicCookie, ServerEndpoint}; + +use crate::X11ComponentError; +use crate::paths::atomic_write_private; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PersistentEndpoint { + Unix { path: PathBuf }, + Inet { host: String, port: u16 }, +} + +impl PersistentEndpoint { + pub fn to_endpoint(&self) -> ServerEndpoint { + match self { + Self::Unix { path } => ServerEndpoint::Unix(path.clone()), + Self::Inet { host, port } => ServerEndpoint::Inet { + host: host.clone(), + port: *port, + }, + } + } + + pub fn from_endpoint(endpoint: &ServerEndpoint) -> Self { + match endpoint { + ServerEndpoint::Unix(path) => Self::Unix { path: path.clone() }, + ServerEndpoint::Inet { host, port } => Self::Inet { + host: host.clone(), + port: *port, + }, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RuntimeIdentity { + pub endpoint: PersistentEndpoint, + cookie: String, +} + +impl RuntimeIdentity { + #[cfg(test)] + pub fn loopback(port: u16, cookie: MagicCookie) -> Self { + Self { + endpoint: PersistentEndpoint::Inet { + host: "127.0.0.1".into(), + port, + }, + cookie: cookie.hex(), + } + } + + pub fn new(endpoint: &ServerEndpoint, cookie: &MagicCookie) -> Self { + Self { + endpoint: PersistentEndpoint::from_endpoint(endpoint), + cookie: cookie.hex(), + } + } + + pub fn read(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(config_error)?; + let identity: Self = serde_json::from_slice(&bytes) + .map_err(|error| X11ComponentError::Config(error.to_string()))?; + identity.validate()?; + // 旧版本可能留下 0644 文件,读取时立即收紧权限。 + identity.write(path)?; + Ok(identity) + } + + pub fn write(&self, path: &Path) -> Result<(), X11ComponentError> { + self.validate()?; + let bytes = serde_json::to_vec(self) + .map_err(|error| X11ComponentError::Config(error.to_string()))?; + atomic_write_private(path, &bytes) + } + + #[cfg(test)] + pub fn cookie_hex(&self) -> &str { + &self.cookie + } + + pub fn cookie(&self) -> Result { + MagicCookie::from_hex(&self.cookie) + .map_err(|error| X11ComponentError::Config(error.to_string())) + } + + fn validate(&self) -> Result<(), X11ComponentError> { + if let PersistentEndpoint::Inet { host, .. } = &self.endpoint { + if host != "127.0.0.1" { + return Err(X11ComponentError::Config("持久端点不是回环地址".into())); + } + } + self.cookie().map(|_| ()) + } +} + +fn config_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Config(error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/runtime/tests.rs b/crates/x11_component/src/runtime/tests.rs new file mode 100644 index 000000000..a1df1b512 --- /dev/null +++ b/crates/x11_component/src/runtime/tests.rs @@ -0,0 +1,54 @@ +use x11_forwarding::MagicCookie; + +use super::RuntimeIdentity; + +#[test] +fn restart_restores_endpoint_and_cookie() { + let root = std::env::temp_dir().join(format!("x11-runtime-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("runtime.json"); + let identity = RuntimeIdentity::loopback(6017, MagicCookie::from_slice(&[4; 16]).unwrap()); + identity.write(&path).unwrap(); + let restored = RuntimeIdentity::read(&path).unwrap(); + assert_eq!(restored.endpoint, identity.endpoint); + assert_eq!(restored.cookie_hex(), identity.cookie_hex()); + assert_eq!(restored.cookie().unwrap().bytes(), &[4; 16]); + std::fs::remove_dir_all(root).unwrap(); +} + +#[cfg(unix)] +#[test] +fn runtime_identity_is_always_owner_read_write_only() { + use std::os::unix::fs::PermissionsExt as _; + let root = std::env::temp_dir().join(format!("x11-runtime-mode-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("runtime.json"); + let identity = RuntimeIdentity::loopback(6018, MagicCookie::from_slice(&[8; 16]).unwrap()); + identity.write(&path).unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + RuntimeIdentity::read(&path).unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn non_loopback_identity_is_rejected() { + let root = std::env::temp_dir().join(format!("x11-runtime-bad-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("runtime.json"); + let mut identity = RuntimeIdentity::loopback(6000, MagicCookie::from_slice(&[4; 16]).unwrap()); + identity.endpoint = super::PersistentEndpoint::Inet { + host: "0.0.0.0".into(), + port: 6000, + }; + std::fs::write(&path, serde_json::to_vec(&identity).unwrap()).unwrap(); + assert!(RuntimeIdentity::read(&path).is_err()); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/src/signature.rs b/crates/x11_component/src/signature.rs new file mode 100644 index 000000000..b87807fa5 --- /dev/null +++ b/crates/x11_component/src/signature.rs @@ -0,0 +1,27 @@ +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use ed25519_dalek::{Signature, VerifyingKey}; + +use crate::X11ComponentError; + +/// 使用独立公钥对原始字节执行 Ed25519 严格验签。 +pub fn verify_ed25519( + payload: &[u8], + signature_base64: &str, + public_key_base64: &str, +) -> Result<(), X11ComponentError> { + let public = decode::<32>(public_key_base64, "公钥")?; + let signature = decode::<64>(signature_base64, "签名")?; + let key = VerifyingKey::from_bytes(&public) + .map_err(|error| X11ComponentError::SignatureInvalid(error.to_string()))?; + key.verify_strict(payload, &Signature::from_bytes(&signature)) + .map_err(|error| X11ComponentError::SignatureInvalid(error.to_string())) +} + +fn decode(text: &str, name: &str) -> Result<[u8; N], X11ComponentError> { + let bytes = BASE64 + .decode(text.trim()) + .map_err(|error| X11ComponentError::SignatureInvalid(format!("{name}编码:{error}")))?; + bytes + .try_into() + .map_err(|_| X11ComponentError::SignatureInvalid(format!("{name}长度必须为 {N} 字节"))) +} diff --git a/crates/x11_component/src/state.rs b/crates/x11_component/src/state.rs new file mode 100644 index 000000000..7bb5fdf06 --- /dev/null +++ b/crates/x11_component/src/state.rs @@ -0,0 +1,181 @@ +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex, OnceLock, RwLock}; + +use semver::Version; + +use crate::{X11ComponentError, X11ForwardingStatus, X11RestartNotification, X11ServerMode}; + +static CONFIGURED_MODE: AtomicU8 = AtomicU8::new(0); +static RESOLUTION_GENERATION: AtomicU64 = AtomicU64::new(0); +static EMBEDDED_DISABLE_REASON: RwLock> = RwLock::new(None); +static STATUS: OnceLock> = OnceLock::new(); +static DATA_DIR: RwLock> = RwLock::new(None); +static NAVOP_VERSION: RwLock> = RwLock::new(None); +static ACTIVE_VERSION: RwLock> = RwLock::new(None); +static RESTART_GENERATION: AtomicU64 = AtomicU64::new(0); +static RESTART_NOTICE: Mutex> = Mutex::new(None); +static RESTART_NOTICE_CONSUMERS: LazyLock>> = + LazyLock::new(|| Mutex::new(HashSet::new())); + +pub fn configured_mode() -> X11ServerMode { + match CONFIGURED_MODE.load(Ordering::Acquire) { + 1 => X11ServerMode::External, + 2 => X11ServerMode::Embedded, + _ => X11ServerMode::Auto, + } +} + +pub fn set_configured_mode(mode: X11ServerMode) { + let value = match mode { + X11ServerMode::Auto => 0, + X11ServerMode::External => 1, + X11ServerMode::Embedded => 2, + }; + if CONFIGURED_MODE.swap(value, Ordering::AcqRel) != value { + RESOLUTION_GENERATION.fetch_add(1, Ordering::AcqRel); + } +} + +/// 模式、组件重启或禁用发生变化时递增,防止新会话复用旧 X11 transport。 +pub fn resolution_generation() -> u64 { + RESOLUTION_GENERATION.load(Ordering::Acquire) +} + +/// 注入已限定产品的数据目录,避免再次拼接 navop。 +pub fn set_data_dir(path: PathBuf) { + *DATA_DIR + .write() + .unwrap_or_else(|poison| poison.into_inner()) = Some(path); +} + +/// 应用初始化时注入 apps/navop 自身的 CARGO_PKG_VERSION。 +pub fn set_navop_version(version: Version) { + *NAVOP_VERSION + .write() + .unwrap_or_else(|poison| poison.into_inner()) = Some(version); +} + +pub fn configured_data_dir() -> Result { + if let Some(path) = DATA_DIR + .read() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + { + return Ok(path); + } + dirs::data_dir() + .map(|path| path.join("navop")) + .ok_or_else(|| X11ComponentError::Config("无法确定用户数据目录".into())) +} + +pub fn configured_navop_version() -> Result { + NAVOP_VERSION + .read() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + .ok_or_else(|| X11ComponentError::Config("尚未注入 Navop 版本".into())) +} + +pub fn current_status() -> X11ForwardingStatus { + status_lock() + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() +} + +pub fn update_status(status: X11ForwardingStatus) { + *status_lock() + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = status; +} + +pub fn active_version() -> Option { + ACTIVE_VERSION + .read() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() +} + +pub fn set_active_version(version: Option) { + *ACTIVE_VERSION + .write() + .unwrap_or_else(|poison| poison.into_inner()) = version; +} + +pub fn note_restart(reason: String) { + RESOLUTION_GENERATION.fetch_add(1, Ordering::AcqRel); + let generation = RESTART_GENERATION.fetch_add(1, Ordering::AcqRel) + 1; + *RESTART_NOTICE_CONSUMERS + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = HashSet::new(); + *RESTART_NOTICE + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = + Some(X11RestartNotification { generation, reason }); +} + +pub fn take_restart_notification() -> Option { + take_restart_notification_for(0) +} + +/// 每个设置窗口使用自己的 consumer id,避免一个窗口抢走其它窗口的通知。 +pub fn take_restart_notification_for(consumer: u64) -> Option { + let notification = RESTART_NOTICE + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone()?; + let mut consumers = RESTART_NOTICE_CONSUMERS + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + consumers.insert(consumer).then_some(notification) +} + +#[cfg(test)] +pub fn reset_restart_notifications_for_test() { + *RESTART_NOTICE + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = None; + RESTART_NOTICE_CONSUMERS + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clear(); +} + +#[cfg(test)] +pub(crate) fn reset_embedded_disable_reason_for_test() { + *EMBEDDED_DISABLE_REASON + .write() + .unwrap_or_else(|poison| poison.into_inner()) = None; +} + +pub fn embedded_disable_reason() -> Option { + EMBEDDED_DISABLE_REASON + .read() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() +} + +/// 本次运行首次永久禁用的原始原因不被后续修复或回退覆盖。 +pub fn disable_embedded(reason: String) -> String { + let mut current = EMBEDDED_DISABLE_REASON + .write() + .unwrap_or_else(|poison| poison.into_inner()); + if current.is_none() { + *current = Some(reason); + RESOLUTION_GENERATION.fetch_add(1, Ordering::AcqRel); + } + current.clone().unwrap_or_else(|| "内置 X11 已禁用".into()) +} + +#[cfg(test)] +mod tests; + +fn status_lock() -> &'static RwLock { + STATUS.get_or_init(|| { + RwLock::new(X11ForwardingStatus::Disabled { + reason: "尚未解析 X11 服务".into(), + }) + }) +} diff --git a/crates/x11_component/src/state/tests.rs b/crates/x11_component/src/state/tests.rs new file mode 100644 index 000000000..ca29029f3 --- /dev/null +++ b/crates/x11_component/src/state/tests.rs @@ -0,0 +1,44 @@ +use super::{ + note_restart, reset_restart_notifications_for_test, resolution_generation, set_configured_mode, + take_restart_notification, take_restart_notification_for, +}; +use crate::X11ServerMode; + +#[test] +fn restart_notification_is_consumed_once() { + let _guard = crate::test_support::global_state_lock(); + reset_restart_notifications_for_test(); + note_restart("yserver 退出码 1".into()); + let notice = take_restart_notification().expect("应产生结构化通知"); + assert!(notice.generation > 0); + assert!(notice.reason.contains("退出码 1")); + assert!(take_restart_notification().is_none()); +} + +#[test] +fn mode_change_and_restart_advance_resolution_generation() { + let _guard = crate::test_support::global_state_lock(); + let initial = resolution_generation(); + set_configured_mode(X11ServerMode::External); + let changed = resolution_generation(); + assert!(changed > initial); + set_configured_mode(X11ServerMode::External); + assert_eq!(changed, resolution_generation()); + note_restart("测试 sidecar 重启".into()); + assert!(resolution_generation() > changed); + let _ = take_restart_notification(); +} + +#[test] +fn restart_notification_reaches_each_settings_consumer_once() { + let _guard = crate::test_support::global_state_lock(); + reset_restart_notifications_for_test(); + note_restart("测试 sidecar 崩溃".into()); + let _ = take_restart_notification(); + let first = take_restart_notification_for(1).expect("第一个窗口应收到"); + let second = take_restart_notification_for(2).expect("第二个窗口也应收到"); + assert_eq!(first, second); + assert!(take_restart_notification_for(1).is_none()); + assert!(take_restart_notification_for(2).is_none()); + reset_restart_notifications_for_test(); +} diff --git a/crates/x11_component/src/supervisor.rs b/crates/x11_component/src/supervisor.rs new file mode 100644 index 000000000..8d7c830a1 --- /dev/null +++ b/crates/x11_component/src/supervisor.rs @@ -0,0 +1,295 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak}; +use std::time::Duration; + +use tokio::sync::Mutex; +use x11_forwarding::{X11Proxy, probe_endpoint}; + +use crate::launch::{LaunchSpec, LaunchedChild, spawn_once}; +use crate::lock::ComponentLock; +use crate::metrics::{MetricEvent, record}; +use crate::process::{kill_owned, remove_owned_files, remove_pidfile_if_owned}; +use crate::restart::RestartBudget; +use crate::state::{disable_embedded, note_restart, set_active_version, update_status}; +use crate::vulkan::preflight; +use crate::{X11ComponentError, X11ForwardingStatus, X11Resolution}; + +struct RunningServer { + launched: LaunchedChild, +} + +struct RecoveryContext<'a> { + budget: &'a StdMutex, + running: &'a mut Option, +} + +impl RunningServer { + fn resolution(&self) -> Result { + let spec = &self.launched.spec; + Ok(X11Resolution { + proxy: Some(X11Proxy::for_endpoint(spec.endpoint(), spec.cookie()?)), + status: X11ForwardingStatus::Embedded { + version: spec.version.clone(), + }, + }) + } +} + +impl Drop for RunningServer { + fn drop(&mut self) { + let _ = self.launched.child.start_kill(); + let _ = kill_owned(&self.launched.pid); + let _ = remove_pidfile_if_owned(&self.launched.spec.root, &self.launched.pid); + } +} + +pub struct EmbeddedSupervisor { + running: Mutex>, + restart_budget: StdMutex, + monitor_started: AtomicBool, +} + +impl EmbeddedSupervisor { + fn new() -> Self { + Self { + running: Mutex::new(None), + restart_budget: StdMutex::new(RestartBudget::default()), + monitor_started: AtomicBool::new(false), + } + } + + async fn ensure(&self, spec: LaunchSpec) -> Result { + let mut running = self.running.lock().await; + let crash = match running.as_mut() { + Some(active) => match active.launched.child.try_wait() { + Ok(None) => return active.resolution(), + Ok(Some(status)) => Some(format!("yserver 已退出:{status}")), + Err(error) => Some(format!("无法读取 yserver 状态:{error}")), + }, + None => None, + }; + if crash.is_some() { + *running = None; + } + let context = RecoveryContext { + budget: &self.restart_budget, + running: &mut running, + }; + let resolution = recover(context, spec, crash.clone()).await?; + if crash.is_some() { + note_restart(format!("{};恢复结果:成功", crash.unwrap_or_default())); + } + Ok(resolution) + } + + fn ensure_monitor(self: &Arc) { + if self.monitor_started.swap(true, Ordering::AcqRel) { + return; + } + let weak = Arc::downgrade(self); + tokio::spawn(async move { monitor_loop(weak).await }); + } + + async fn maintain(&self) { + let mut running = self.running.lock().await; + let Some(active) = running.as_mut() else { + return; + }; + let crash = match active.launched.child.try_wait() { + Ok(None) => return, + Ok(Some(status)) => format!("yserver 已退出:{status}"), + Err(error) => format!("无法读取 yserver 状态:{error}"), + }; + let spec = active.launched.spec.clone(); + *running = None; + let context = RecoveryContext { + budget: &self.restart_budget, + running: &mut running, + }; + let recovered = recover(context, spec, Some(crash.clone())).await; + if recovered.is_ok() { + note_restart(format!("{crash};恢复结果:成功")); + } else { + record(MetricEvent::EmbeddedFailure); + } + } +} + +pub async fn start(spec: LaunchSpec) -> Result { + preflight(&spec.min_vulkan)?; + let supervisor = global_supervisor(); + let resolution = supervisor.ensure(spec).await; + if resolution.is_ok() { + supervisor.ensure_monitor(); + } + resolution +} + +fn global_supervisor() -> &'static Arc { + static GLOBAL: OnceLock> = OnceLock::new(); + GLOBAL.get_or_init(|| Arc::new(EmbeddedSupervisor::new())) +} + +async fn recover( + context: RecoveryContext<'_>, + spec: LaunchSpec, + crash: Option, +) -> Result { + let RecoveryContext { budget, running } = context; + if crash.is_some() { + record(MetricEvent::Crash); + if !restart_allowed(budget) { + let reason = "yserver 在 10 分钟内崩溃超过 3 次,本次运行禁用".to_string(); + let reason = disable_embedded(reason); + set_active_version(None); + let error = X11ComponentError::EmbeddedDisabled(reason.clone()); + update_status(X11ForwardingStatus::Disabled { + reason: error.to_string(), + }); + if let Some(crash) = crash { + note_restart(format!("{crash};恢复结果:永久禁用;{reason}")); + } + return Err(error); + } + } + let mut launch_spec = spec.clone(); + match launch_with_retry(&mut launch_spec, crash.as_deref()).await { + Ok(launched) => { + if crash.is_some() { + record(MetricEvent::Restart); + } else { + record(MetricEvent::EmbeddedStart); + } + set_active_version(Some(spec.version.clone())); + let active = RunningServer { launched }; + let resolution = active.resolution()?; + update_status(resolution.status.clone()); + *running = Some(active); + Ok(resolution) + } + Err(error) => { + set_active_version(None); + update_status(X11ForwardingStatus::Disabled { + reason: error.to_string(), + }); + if let Some(crash) = crash { + note_restart(format!("{crash};恢复结果:失败;{error}")); + } + Err(error) + } + } +} + +fn restart_allowed(budget: &StdMutex) -> bool { + budget + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .record_crash(std::time::Instant::now()) +} + +#[derive(Debug, Eq, PartialEq)] +enum RetryDecision { + Rotate, + Stop, +} + +fn spawn_retry_decision(error: &X11ComponentError, allow_refresh: bool) -> RetryDecision { + if allow_refresh && matches!(error, X11ComponentError::Process(_)) { + RetryDecision::Rotate + } else { + RetryDecision::Stop + } +} + +fn retry_decision( + _spec: &LaunchSpec, + crash: Option<&str>, + last_attempt: bool, + probe_failed: bool, +) -> RetryDecision { + if crash.is_none() && !last_attempt && probe_failed { + RetryDecision::Rotate + } else { + RetryDecision::Stop + } +} + +async fn launch_with_retry( + spec: &mut LaunchSpec, + crash: Option<&str>, +) -> Result { + let mut last_error = None; + for attempt in 0..2 { + let lock = ComponentLock::acquire_async(spec.root.clone()) + .await + .map_err(|error| X11ComponentError::Process(error.to_string()))?; + spec.reload_identity_for_spawn()?; + let launched = match spawn_once(spec).await { + Ok(launched) => launched, + Err(error) => { + let rotate = spawn_retry_decision(&error, crash.is_none() && attempt == 0) + == RetryDecision::Rotate; + if rotate { + rotate_endpoint_locked(spec, &lock)?; + drop(lock); + continue; + } + return Err(error); + } + }; + match probe_launched(spec, launched, crash, attempt == 1).await { + Ok(launched) => return Ok(launched), + Err((error, rotate)) => { + last_error = Some(error); + if rotate { + rotate_endpoint_locked(spec, &lock)?; + } + drop(lock); + } + } + } + Err(X11ComponentError::Handshake(format!( + "启动后握手重试一次仍失败:{}", + last_error.unwrap_or_else(|| "未知错误".into()) + ))) +} + +fn rotate_endpoint_locked( + spec: &mut LaunchSpec, + lock: &ComponentLock, +) -> Result<(), X11ComponentError> { + spec.refresh_endpoint_after_conflict_locked(lock) +} + +async fn probe_launched( + spec: &LaunchSpec, + mut launched: LaunchedChild, + crash: Option<&str>, + last_attempt: bool, +) -> Result { + let cookie = spec.cookie().map_err(|error| (error.to_string(), false))?; + match probe_endpoint(&spec.endpoint(), &cookie, Duration::from_secs(2)).await { + Ok(()) => Ok(launched), + Err(error) => { + let rotate = retry_decision(spec, crash, last_attempt, true) == RetryDecision::Rotate; + let _ = launched.child.kill().await; + let _ = launched.child.wait().await; + let _ = kill_owned(&launched.pid); + let _ = remove_owned_files(&spec.root, &launched.pid); + Err((error.to_string(), rotate)) + } + } +} + +#[cfg(test)] +mod tests; + +async fn monitor_loop(supervisor: Weak) { + loop { + tokio::time::sleep(Duration::from_secs(1)).await; + let Some(supervisor) = supervisor.upgrade() else { + return; + }; + supervisor.maintain().await; + } +} diff --git a/crates/x11_component/src/supervisor/tests.rs b/crates/x11_component/src/supervisor/tests.rs new file mode 100644 index 000000000..57293259a --- /dev/null +++ b/crates/x11_component/src/supervisor/tests.rs @@ -0,0 +1,120 @@ +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use crate::X11ComponentError; +use crate::launch::LaunchSpec; +use crate::lock::ComponentLock; +use crate::restart::RestartBudget; +use crate::runtime::RuntimeIdentity; +use crate::state::{ + embedded_disable_reason, reset_restart_notifications_for_test, take_restart_notification, +}; +use x11_forwarding::MagicCookie; + +#[test] +fn initial_probe_failure_rotates_endpoint_but_crash_restart_does_not() { + let occupied = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = occupied.local_addr().unwrap().port(); + let spec = LaunchSpec { + root: std::env::temp_dir(), + executable: "/unused/yserver".into(), + version: "manual".into(), + min_vulkan: "1.3.0".into(), + identity: RuntimeIdentity::loopback(port, MagicCookie::from_slice(&[7; 16]).unwrap()), + }; + let decision = super::retry_decision(&spec, None, false, true); + assert_eq!(decision, super::RetryDecision::Rotate); + let decision = super::retry_decision(&spec, Some("crash"), false, true); + assert_eq!(decision, super::RetryDecision::Stop); +} + +#[test] +fn active_other_instance_is_never_a_port_conflict() { + let error = X11ComponentError::ActiveOtherInstance("running".into()); + assert!(matches!( + super::spawn_retry_decision(&error, true), + super::RetryDecision::Stop + )); + let error = X11ComponentError::Process("bind failed".into()); + assert_eq!( + super::spawn_retry_decision(&error, true), + super::RetryDecision::Rotate + ); +} + +#[test] +fn endpoint_rotation_keeps_competitors_outside_the_component_lock() { + let root = std::env::temp_dir().join(format!( + "x11-rotation-lock-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let identity = RuntimeIdentity::loopback(6010, MagicCookie::from_slice(&[3; 16]).unwrap()); + identity.write(&root.join("runtime.json")).unwrap(); + let mut spec = LaunchSpec { + root: root.clone(), + executable: root.join("yserver"), + version: "manual".into(), + min_vulkan: "1.3.0".into(), + identity, + }; + let lock = ComponentLock::acquire(&root).unwrap(); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (locked_tx, locked_rx) = std::sync::mpsc::channel(); + let competitor_root = root.clone(); + let competitor = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + let _lock = ComponentLock::acquire(&competitor_root).unwrap(); + locked_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + super::rotate_endpoint_locked(&mut spec, &lock).unwrap(); + assert!( + locked_rx.recv_timeout(Duration::from_millis(100)).is_err(), + "rotation 完成前另一实例不得进入启动临界区" + ); + drop(lock); + locked_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + competitor.join().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn crash_is_notified_once_when_permanently_disabled() { + let _guard = crate::test_support::global_state_lock_async().await; + reset_restart_notifications_for_test(); + let root = std::env::temp_dir().join(format!( + "x11-restart-disable-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&root).unwrap(); + let spec = LaunchSpec::manual(root.clone(), root.join("yserver")).unwrap(); + let mut budget = RestartBudget::default(); + let now = Instant::now(); + for offset in 0..3 { + assert!(budget.record_crash(now + Duration::from_secs(offset))); + } + let budget = Mutex::new(budget); + let mut running = None; + let context = super::RecoveryContext { + budget: &budget, + running: &mut running, + }; + let error = super::recover(context, spec, Some("crash".into())) + .await + .unwrap_err(); + assert!(matches!(error, X11ComponentError::EmbeddedDisabled(_))); + assert!(embedded_disable_reason().is_some()); + let notice = take_restart_notification().expect("永久禁用也必须通知崩溃结果"); + assert!(notice.reason.contains("crash")); + assert!(notice.reason.contains("永久禁用")); + assert!( + take_restart_notification().is_none(), + "同一次崩溃不得重复通知" + ); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/src/test_support.rs b/crates/x11_component/src/test_support.rs new file mode 100644 index 000000000..d952db3da --- /dev/null +++ b/crates/x11_component/src/test_support.rs @@ -0,0 +1,12 @@ +//! 所有读写进程级状态的单元测试共用同一异步互斥锁。 +use tokio::sync::{Mutex, MutexGuard}; + +static GLOBAL_STATE_TEST_LOCK: Mutex<()> = Mutex::const_new(()); + +pub fn global_state_lock() -> MutexGuard<'static, ()> { + GLOBAL_STATE_TEST_LOCK.blocking_lock() +} + +pub async fn global_state_lock_async() -> MutexGuard<'static, ()> { + GLOBAL_STATE_TEST_LOCK.lock().await +} diff --git a/crates/x11_component/src/vulkan.rs b/crates/x11_component/src/vulkan.rs new file mode 100644 index 000000000..c7ded4f43 --- /dev/null +++ b/crates/x11_component/src/vulkan.rs @@ -0,0 +1,69 @@ +use libloading::Library; +use semver::Version; + +use crate::X11ComponentError; + +type EnumerateLoaderVersion = unsafe extern "system" fn(*mut u32) -> i32; + +pub fn decode_vulkan_version(packed: u32) -> (u32, u32, u32) { + (packed >> 22, (packed >> 12) & 0x3ff, packed & 0xfff) +} + +pub fn check_vulkan_version( + required: &str, + actual: Option, +) -> Result<(), X11ComponentError> { + let required_version = Version::parse(required) + .map_err(|error| X11ComponentError::InvalidManifest(error.to_string()))?; + let meets = actual + .as_deref() + .and_then(|version| Version::parse(version).ok()) + .is_some_and(|version| version >= required_version); + if meets { + return Ok(()); + } + Err(X11ComponentError::VulkanUnavailable { + required: required.into(), + actual, + }) +} + +/// 直接从 Vulkan loader 查询能力,不依赖 vulkaninfo 可执行文件。 +pub fn preflight(required: &str) -> Result<(), X11ComponentError> { + #[cfg(target_os = "windows")] + let names = ["vulkan-1.dll"]; + #[cfg(target_os = "linux")] + let names = ["libvulkan.so.1"]; + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + let names: [&str; 0] = []; + for name in names { + match unsafe { query_loader(name) } { + Ok(actual) => return check_vulkan_version(required, Some(actual)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => { + return Err(X11ComponentError::VulkanUnavailable { + required: required.into(), + actual: Some(error.to_string()), + }); + } + } + } + check_vulkan_version(required, None) +} + +unsafe fn query_loader(name: &str) -> std::io::Result { + let library = + unsafe { Library::new(name) }.map_err(|error| std::io::Error::other(error.to_string()))?; + let enumerate: libloading::Symbol<'_, EnumerateLoaderVersion> = + unsafe { library.get(b"vkEnumerateInstanceVersion\0") } + .map_err(|error| std::io::Error::other(error.to_string()))?; + let mut packed = 0; + if unsafe { enumerate(&mut packed) } != 0 { + return Err(std::io::Error::other("vkEnumerateInstanceVersion 调用失败")); + } + let (major, minor, patch) = decode_vulkan_version(packed); + Ok(format!("{major}.{minor}.{patch}")) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/vulkan/tests.rs b/crates/x11_component/src/vulkan/tests.rs new file mode 100644 index 000000000..05bcc1671 --- /dev/null +++ b/crates/x11_component/src/vulkan/tests.rs @@ -0,0 +1,21 @@ +use crate::X11ComponentError; + +use super::{check_vulkan_version, decode_vulkan_version}; + +#[test] +fn decode_packed_driver_version() { + assert_eq!(decode_vulkan_version((1 << 22) | (3 << 12) | 7), (1, 3, 7)); + assert_eq!(decode_vulkan_version(0), (0, 0, 0)); +} + +#[test] +fn minimum_vulkan_version_is_enforced() { + check_vulkan_version("1.3.0", Some("1.3.7".into())).unwrap(); + check_vulkan_version("1.3.0", Some("1.4.0".into())).unwrap(); + for actual in [None, Some("1.2.9".into())] { + assert!(matches!( + check_vulkan_version("1.3.0", actual), + Err(X11ComponentError::VulkanUnavailable { .. }) + )); + } +} diff --git a/crates/x11_component/src/xauth.rs b/crates/x11_component/src/xauth.rs new file mode 100644 index 000000000..3e82f1923 --- /dev/null +++ b/crates/x11_component/src/xauth.rs @@ -0,0 +1,109 @@ +use std::path::Path; + +use x11_forwarding::{MagicCookie, ServerEndpoint}; + +use crate::X11ComponentError; + +const AUTH_NAME: &[u8] = b"MIT-MAGIC-COOKIE-1"; + +pub fn encode_xauth( + endpoint: &ServerEndpoint, + cookie: &MagicCookie, +) -> Result, X11ComponentError> { + let (family, address, display) = authority_address(endpoint)?; + let mut output = Vec::with_capacity(64); + push_u16(&mut output, family); + for field in [ + address.as_slice(), + display.as_bytes(), + AUTH_NAME, + cookie.bytes().as_slice(), + ] { + let length = u16::try_from(field.len()) + .map_err(|_| X11ComponentError::Config("Xauthority 字段过长".into()))?; + push_u16(&mut output, length); + output.extend_from_slice(field); + } + Ok(output) +} + +pub fn write_xauth( + path: &Path, + endpoint: &ServerEndpoint, + cookie: &MagicCookie, +) -> Result<(), X11ComponentError> { + let bytes = encode_xauth(endpoint, cookie)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options.open(path).map_err(config_error)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + file.set_permissions(std::fs::Permissions::from_mode(0o600)) + .map_err(config_error)?; + } + std::io::Write::write_all(&mut file, &bytes).map_err(config_error) +} + +fn authority_address( + endpoint: &ServerEndpoint, +) -> Result<(u16, Vec, String), X11ComponentError> { + match endpoint { + ServerEndpoint::Inet { host, port } => { + if host != "127.0.0.1" || *port < 6000 { + return Err(X11ComponentError::Config( + "Xauthority 仅接受回环 TCP".into(), + )); + } + Ok((0, vec![127, 0, 0, 1], (*port - 6000).to_string())) + } + ServerEndpoint::Unix(path) => { + let display = path + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| name.strip_prefix('X')) + .filter(|number| number.chars().all(|ch| ch.is_ascii_digit())) + .ok_or_else(|| X11ComponentError::Config("Unix socket 缺少显示号".into()))?; + Ok((256, local_hostname()?, display.into())) + } + } +} + +#[cfg(unix)] +fn local_hostname() -> Result, X11ComponentError> { + let mut buffer = [0 as libc::c_char; 256]; + // SAFETY:buffer 提供有效可写内存,长度与实际容量一致。 + let result = unsafe { libc::gethostname(buffer.as_mut_ptr(), buffer.len()) }; + if result != 0 { + return Err(config_error(std::io::Error::last_os_error())); + } + let length = buffer + .iter() + .position(|byte| *byte == 0) + .unwrap_or(buffer.len()); + if length == 0 { + return Err(X11ComponentError::Config("本机 hostname 为空".into())); + } + Ok(buffer[..length].iter().map(|byte| *byte as u8).collect()) +} + +#[cfg(not(unix))] +fn local_hostname() -> Result, X11ComponentError> { + Ok(b"localhost".to_vec()) +} + +fn push_u16(output: &mut Vec, value: u16) { + output.extend_from_slice(&value.to_be_bytes()); +} + +fn config_error(error: std::io::Error) -> X11ComponentError { + X11ComponentError::Config(error.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/x11_component/src/xauth/tests.rs b/crates/x11_component/src/xauth/tests.rs new file mode 100644 index 000000000..a49d756da --- /dev/null +++ b/crates/x11_component/src/xauth/tests.rs @@ -0,0 +1,67 @@ +use x11_forwarding::{MagicCookie, ServerEndpoint}; + +use super::{encode_xauth, write_xauth}; + +#[test] +fn tcp_record_contains_loopback_display_and_cookie() { + let cookie = MagicCookie::from_slice(&[7; 16]).unwrap(); + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 6012, + }; + let bytes = encode_xauth(&endpoint, &cookie).unwrap(); + let mut expected = vec![0, 0, 0, 4, 127, 0, 0, 1, 0, 2, b'1', b'2', 0, 18]; + expected.extend_from_slice(b"MIT-MAGIC-COOKIE-1"); + expected.extend_from_slice(&[0, 16]); + expected.extend_from_slice(&[7; 16]); + assert_eq!(bytes, expected); +} + +#[test] +fn unix_record_uses_local_family() { + let cookie = MagicCookie::from_slice(&[9; 16]).unwrap(); + let endpoint = ServerEndpoint::Unix("/tmp/.X11-unix/X23".into()); + let bytes = encode_xauth(&endpoint, &cookie).unwrap(); + assert_eq!(&bytes[..2], &256u16.to_be_bytes()); + assert!(bytes.windows(2).any(|window| window == b"23")); +} + +#[cfg(unix)] +#[test] +fn unix_record_uses_the_actual_local_hostname() { + let cookie = MagicCookie::from_slice(&[10; 16]).unwrap(); + let endpoint = ServerEndpoint::Unix("/tmp/.X11-unix/X24".into()); + let bytes = encode_xauth(&endpoint, &cookie).unwrap(); + let hostname = super::local_hostname().unwrap(); + assert!( + bytes + .windows(hostname.len()) + .any(|window| window == hostname) + ); +} + +#[test] +fn xauth_file_is_owner_read_write_only() { + let root = std::env::temp_dir().join(format!("x11-xauth-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("xauthority"); + let cookie = MagicCookie::from_slice(&[3; 16]).unwrap(); + write_xauth( + &path, + &ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 6000, + }, + &cookie, + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/x11_component/tests/public_api.rs b/crates/x11_component/tests/public_api.rs new file mode 100644 index 000000000..aa0b809e1 --- /dev/null +++ b/crates/x11_component/tests/public_api.rs @@ -0,0 +1,75 @@ +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use ed25519_dalek::{Signer as _, SigningKey, VerifyingKey}; +use x11_component::{ + X11ForwardingStatus, X11ServerMode, configured_mode, current_status, installed_version, + set_configured_mode, set_data_dir, verify_ed25519, +}; + +#[test] +fn mode_serializes_snake_case_and_defaults_auto() { + assert_eq!(X11ServerMode::default(), X11ServerMode::Auto); + assert_eq!( + serde_json::to_string(&X11ServerMode::External).unwrap(), + "\"external\"" + ); + assert_eq!( + serde_json::from_str::("\"embedded\"").unwrap(), + X11ServerMode::Embedded + ); +} + +#[test] +fn configured_mode_is_thread_safe() { + set_configured_mode(X11ServerMode::Embedded); + let threads = (0..4) + .map(|_| std::thread::spawn(|| configured_mode())) + .collect::>(); + for thread in threads { + assert_eq!(thread.join().unwrap(), X11ServerMode::Embedded); + } + set_configured_mode(X11ServerMode::Auto); + assert_eq!(configured_mode(), X11ServerMode::Auto); +} + +#[test] +fn initial_status_is_disabled() { + assert!(matches!( + current_status(), + X11ForwardingStatus::Disabled { .. } + )); +} + +#[test] +fn injected_data_dir_controls_installed_version() { + let root = std::env::temp_dir().join(format!("x11-installed-{}", std::process::id())); + let component = root.join("components/x11"); + std::fs::create_dir_all(component.join("versions/9.8.7")).unwrap(); + std::fs::write(component.join("current"), "9.8.7").unwrap(); + set_data_dir(root.clone()); + assert_eq!(installed_version().as_deref(), Some("9.8.7")); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn valid_ed25519_signature_is_accepted() { + let signing = SigningKey::from_bytes(&[7; 32]); + let public = BASE64.encode(VerifyingKey::from(&signing).to_bytes()); + let signature = BASE64.encode(signing.sign(b"payload").to_bytes()); + verify_ed25519(b"payload", &signature, &public).unwrap(); +} + +#[test] +fn wrong_key_and_truncated_signature_are_rejected() { + let signing = SigningKey::from_bytes(&[7; 32]); + let wrong = SigningKey::from_bytes(&[8; 32]); + let signature = signing.sign(b"payload").to_bytes(); + let wrong_public = BASE64.encode(VerifyingKey::from(&wrong).to_bytes()); + let signature_base64 = BASE64.encode(signature); + assert!( + verify_ed25519(b"payload", &signature_base64, &wrong_public).is_err(), + "换公钥后必须验签失败" + ); + let truncated = BASE64.encode(&signature[..63]); + let public = BASE64.encode(VerifyingKey::from(&signing).to_bytes()); + assert!(verify_ed25519(b"payload", &truncated, &public).is_err()); +} diff --git a/crates/x11_forwarding/src/bridge.rs b/crates/x11_forwarding/src/bridge.rs index e82123a27..3e3d52015 100644 --- a/crates/x11_forwarding/src/bridge.rs +++ b/crates/x11_forwarding/src/bridge.rs @@ -11,6 +11,14 @@ use crate::proxy::LocalAuth; use crate::setup::{ClientHello, HEADER_LEN}; use crate::{MagicCookie, ServerEndpoint, X11Error}; +const SETUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +struct RelayOptions<'a> { + endpoint: &'a ServerEndpoint, + exchange: &'a dyn CookieExchange, + setup_timeout: std::time::Duration, +} + #[derive(Debug, Error)] pub enum BridgeError { #[error(transparent)] @@ -48,10 +56,45 @@ where } async fn relay_inner( - mut channel: S, + channel: S, endpoint: &ServerEndpoint, exchange: &dyn CookieExchange, ) -> Result<(), BridgeError> +where + S: AsyncRead + AsyncWrite + Unpin + Send, +{ + let options = RelayOptions { + endpoint, + exchange, + setup_timeout: SETUP_TIMEOUT, + }; + relay_inner_with_options(channel, &options).await +} + +async fn relay_inner_with_options( + channel: S, + options: &RelayOptions<'_>, +) -> Result<(), BridgeError> +where + S: AsyncRead + AsyncWrite + Unpin + Send, +{ + let (mut channel, mut server) = + tokio::time::timeout(options.setup_timeout, setup(channel, options)) + .await + .map_err(|_| { + BridgeError::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "X11 setup timed out", + )) + })??; + tokio::io::copy_bidirectional(&mut channel, &mut server).await?; + Ok(()) +} + +async fn setup( + mut channel: S, + options: &RelayOptions<'_>, +) -> Result<(S, Box), BridgeError> where S: AsyncRead + AsyncWrite + Unpin + Send, { @@ -68,7 +111,7 @@ where // 2. 校验 fake cookie;失败则回一个 setup 失败应答再关闭。 let presented = hello.presented_cookie()?; - let Some(local) = exchange.exchange(&presented) else { + let Some(local) = options.exchange.exchange(&presented) else { reject(&mut channel, &hello).await; return Err(X11Error::CookieRejected.into()); }; @@ -79,10 +122,9 @@ where #[cfg(any(target_os = "windows", test))] LocalAuth::None => hello.encode_with_auth("", &[]), }; - let mut server = open(endpoint).await?; + let mut server = open(options.endpoint).await?; server.write_all(&rewritten).await?; - tokio::io::copy_bidirectional(&mut channel, &mut server).await?; - Ok(()) + Ok((channel, server)) } async fn reject(channel: &mut S, hello: &ClientHello) @@ -223,6 +265,33 @@ mod tests { relay_result.unwrap(); } + #[tokio::test] + async fn stalled_setup_times_out_before_relay() { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 1, + }; + let (_client, channel) = duplex(8192); + let exchange = |_: &MagicCookie| None; + let options = RelayOptions { + endpoint: &endpoint, + exchange: &exchange, + setup_timeout: std::time::Duration::from_millis(20), + }; + + let result = tokio::time::timeout( + std::time::Duration::from_secs(1), + relay_inner_with_options(channel, &options), + ) + .await + .expect("不出示 setup 字节的通道也必须在总超时后退出"); + + assert!(matches!( + result, + Err(BridgeError::Io(error)) if error.kind() == std::io::ErrorKind::TimedOut + )); + } + #[tokio::test] async fn unknown_cookie_gets_failure_reply() { let endpoint = ServerEndpoint::Inet { diff --git a/crates/x11_forwarding/src/error.rs b/crates/x11_forwarding/src/error.rs index 3de8a9bda..618e38cee 100644 --- a/crates/x11_forwarding/src/error.rs +++ b/crates/x11_forwarding/src/error.rs @@ -27,4 +27,10 @@ pub enum X11Error { SetupOversized(usize), #[error("远端出示的 cookie 未通过校验")] CookieRejected, + #[error("X11 setup 健康检查超时")] + ProbeTimeout, + #[error("X11 setup 健康检查 I/O 失败:{0}")] + ProbeIo(String), + #[error("X11 setup 健康检查被拒绝:{0}")] + ProbeRejected(String), } diff --git a/crates/x11_forwarding/src/lib.rs b/crates/x11_forwarding/src/lib.rs index bbc8be714..3e536d0a2 100644 --- a/crates/x11_forwarding/src/lib.rs +++ b/crates/x11_forwarding/src/lib.rs @@ -16,6 +16,7 @@ mod cookie; mod detect; mod display; mod error; +mod probe; mod proxy; mod setup; mod xauthority; @@ -24,4 +25,5 @@ pub use cookie::{ForwardRequest, MagicCookie}; pub use detect::detect_local_server; pub use display::{DisplayAddress, ServerEndpoint}; pub use error::{X11Error, X11Result}; +pub use probe::probe_endpoint; pub use proxy::{X11Proxy, X11ProxyHandle}; diff --git a/crates/x11_forwarding/src/probe.rs b/crates/x11_forwarding/src/probe.rs new file mode 100644 index 000000000..09422b268 --- /dev/null +++ b/crates/x11_forwarding/src/probe.rs @@ -0,0 +1,170 @@ +//! 本机 X server 的 X11 setup 健康检查。 + +use std::io; +use std::time::Duration; + +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::TcpStream; + +use crate::setup::ClientHello; +use crate::{MagicCookie, ServerEndpoint, X11Error, X11Result}; + +const REPLY_HEADER_LEN: usize = 8; +const MAX_REPLY_BODY_LEN: usize = 1024 * 1024; + +trait ProbeStream: AsyncRead + AsyncWrite + Unpin + Send {} +impl ProbeStream for T {} + +/// 用真实 cookie 完成一次 setup 往返;成功应答的可变长度正文也必须完整到达。 +pub async fn probe_endpoint( + endpoint: &ServerEndpoint, + cookie: &MagicCookie, + timeout: Duration, +) -> X11Result<()> { + tokio::time::timeout(timeout, probe_inner(endpoint, cookie)) + .await + .map_err(|_| X11Error::ProbeTimeout)? +} + +async fn probe_inner(endpoint: &ServerEndpoint, cookie: &MagicCookie) -> X11Result<()> { + let mut stream = connect(endpoint).await?; + let hello = ClientHello::for_probe(cookie.bytes()); + let packet = hello.encode_with(cookie.bytes()); + stream.write_all(&packet).await.map_err(io_error)?; + let mut header = [0; REPLY_HEADER_LEN]; + stream.read_exact(&mut header).await.map_err(io_error)?; + let body = read_reply_body(&mut stream, &header).await?; + match header[0] { + 1 => Ok(()), + 0 | 2 => Err(X11Error::ProbeRejected(reply_reason(&header, &body))), + status => Err(X11Error::ProbeRejected(format!("未知 setup 状态 {status}"))), + } +} + +async fn connect(endpoint: &ServerEndpoint) -> X11Result> { + match endpoint { + ServerEndpoint::Inet { host, port } => { + let stream = TcpStream::connect((host.as_str(), *port)) + .await + .map_err(io_error)?; + Ok(Box::new(stream)) + } + #[cfg(unix)] + ServerEndpoint::Unix(path) => { + let stream = tokio::net::UnixStream::connect(path) + .await + .map_err(io_error)?; + Ok(Box::new(stream)) + } + #[cfg(not(unix))] + ServerEndpoint::Unix(path) => Err(X11Error::ProbeIo(format!( + "当前平台不支持 Unix socket:{}", + path.display() + ))), + } +} + +async fn read_reply_body( + stream: &mut (impl ProbeStream + ?Sized), + header: &[u8; REPLY_HEADER_LEN], +) -> X11Result> { + let body_len = u16::from_le_bytes([header[6], header[7]]) as usize * 4; + if body_len > MAX_REPLY_BODY_LEN { + return Err(X11Error::ProbeRejected(format!( + "setup 应答超过 {MAX_REPLY_BODY_LEN} 字节" + ))); + } + let mut body = vec![0; body_len]; + stream.read_exact(&mut body).await.map_err(io_error)?; + Ok(body) +} + +fn reply_reason(header: &[u8; REPLY_HEADER_LEN], body: &[u8]) -> String { + let reason_len = usize::from(header[1]).min(body.len()); + String::from_utf8_lossy(&body[..reason_len]).into_owned() +} + +fn io_error(error: io::Error) -> X11Error { + X11Error::ProbeIo(error.to_string()) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + use super::probe_endpoint; + use crate::setup::ClientHello; + use crate::{MagicCookie, ServerEndpoint, X11Error}; + + async fn tcp_server(reply: Vec) -> (ServerEndpoint, MagicCookie) { + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: listener.local_addr().unwrap().port(), + }; + let cookie = MagicCookie::from_slice(&[0x42; 16]).unwrap(); + let expected_cookie = cookie.clone(); + tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut header = [0; 12]; + stream.read_exact(&mut header).await.unwrap(); + let auth_len = ClientHello::auth_section_len(&header).unwrap(); + let mut packet = header.to_vec(); + packet.resize(12 + auth_len, 0); + stream.read_exact(&mut packet[12..]).await.unwrap(); + let hello = ClientHello::decode(&packet).unwrap(); + assert_eq!(hello.presented_cookie().unwrap(), expected_cookie); + stream.write_all(&reply).await.unwrap(); + }); + (endpoint, cookie) + } + + #[tokio::test] + async fn probe_completes_real_setup_handshake() { + let (endpoint, cookie) = tcp_server(vec![1, 0, 11, 0, 0, 0, 0, 0]).await; + probe_endpoint(&endpoint, &cookie, Duration::from_secs(1)) + .await + .unwrap(); + } + + #[tokio::test] + async fn probe_surfaces_protocol_rejection() { + let (endpoint, cookie) = tcp_server(vec![0, 0, 11, 0, 0, 0, 0, 0]).await; + let error = probe_endpoint(&endpoint, &cookie, Duration::from_secs(1)) + .await + .unwrap_err(); + assert!(matches!(error, X11Error::ProbeRejected(_))); + } + + #[tokio::test] + async fn probe_rejects_truncated_success() { + let (endpoint, cookie) = tcp_server(vec![1, 0, 11, 0]).await; + let error = probe_endpoint(&endpoint, &cookie, Duration::from_secs(1)) + .await + .unwrap_err(); + assert!(matches!(error, X11Error::ProbeIo(_))); + } + + #[tokio::test] + async fn probe_times_out_when_server_never_replies() { + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: listener.local_addr().unwrap().port(), + }; + let cookie = MagicCookie::from_slice(&[0x42; 16]).unwrap(); + let server = tokio::spawn(async move { + let (_stream, _) = listener.accept().await.unwrap(); + tokio::time::sleep(Duration::from_secs(1)).await; + }); + + let error = probe_endpoint(&endpoint, &cookie, Duration::from_millis(20)) + .await + .unwrap_err(); + assert!(matches!(error, X11Error::ProbeTimeout)); + server.abort(); + } +} diff --git a/crates/x11_forwarding/src/proxy.rs b/crates/x11_forwarding/src/proxy.rs index 2a7dc0f3b..2e3863233 100644 --- a/crates/x11_forwarding/src/proxy.rs +++ b/crates/x11_forwarding/src/proxy.rs @@ -63,6 +63,11 @@ impl fmt::Debug for X11Proxy { } impl X11Proxy { + /// 为组件管理的本机 X server 创建代理,继续沿用 fake cookie 委托链路。 + pub fn for_endpoint(endpoint: ServerEndpoint, local: MagicCookie) -> Self { + Self::new(endpoint, 0, local) + } + pub(crate) fn new(endpoint: ServerEndpoint, screen: u32, local: MagicCookie) -> Self { Self::with_auth(endpoint, screen, LocalAuth::Cookie(local)) } @@ -153,6 +158,21 @@ mod tests { ) } + #[test] + fn endpoint_constructor_preserves_cookie_delegation() { + let endpoint = ServerEndpoint::Inet { + host: "127.0.0.1".into(), + port: 6137, + }; + let cookie = MagicCookie::from_slice(&[0x37; 16]).unwrap(); + let proxy = X11Proxy::for_endpoint(endpoint.clone(), cookie.clone()); + + assert_eq!(proxy.endpoint(), &endpoint); + let request = proxy.issue_request(false); + let fake = MagicCookie::from_hex(request.cookie_hex()).unwrap(); + assert_eq!(proxy.state.exchange(&fake), Some(LocalAuth::Cookie(cookie))); + } + #[test] fn issued_request_uses_fresh_fake_cookie() { let proxy = proxy(); diff --git a/crates/x11_forwarding/src/setup.rs b/crates/x11_forwarding/src/setup.rs index 94d3f323f..4b5cd8381 100644 --- a/crates/x11_forwarding/src/setup.rs +++ b/crates/x11_forwarding/src/setup.rs @@ -61,6 +61,16 @@ pub struct ClientHello { } impl ClientHello { + pub(crate) fn for_probe(auth_data: &[u8]) -> Self { + Self { + order: ByteOrder::Lsb, + major: 11, + minor: 0, + auth_name: ForwardRequest::AUTH_NAME.to_string(), + auth_data: auth_data.to_vec(), + } + } + #[cfg(test)] pub(crate) fn forge(order: ByteOrder, auth_name: &str, auth_data: &[u8]) -> Self { Self { diff --git a/docs/design/embedded-x11-yserver.md b/docs/design/embedded-x11-yserver.md new file mode 100644 index 000000000..c6bd24f2e --- /dev/null +++ b/docs/design/embedded-x11-yserver.md @@ -0,0 +1,70 @@ +# 内置 yserver X11 转发设计 + +## 目标与边界 + +本期让 Windows 用户在不安装 VcXsrv 的情况下使用 X11 转发;macOS 继续引导 XQuartz。Linux 不纳入本期内置范围,仍使用本机 X server。远端 sshd、远端软件和现有 cookie 委托链路均不改变。 + +本期不实现 X server,不内嵌单窗口 tab,不把裸字节流塞入 universal-plugins。yserver 只作为原生 sidecar 子进程运行。`yserver-core` 不含窗口 shell、Vulkan 渲染和完整生命周期接口,不能靠直接链接 core 替代 sidecar;进程隔离也避免 yserver 崩溃或 GPU 异常带走 Navop。 + +## 解析优先级 + +设置提供 `Auto`、`External`、`Embedded` 三种持久化模式: + +1. `Auto`:先探测本机 X server,失败后尝试内置组件;两者都不可用时返回带原因的停用状态。 +2. `External`:只使用本机 X server。 +3. `Embedded`:只使用内置组件,失败时明确提示可改用外部 server。 + +`crates/x11_component` 负责模式解析、固定清单、内嵌包安装、验签、版本目录、能力预检和进程监督;`crates/ssh` 只读取全局设置并取得解析结果。每个 `RusshClient` 保存自己的状态,避免并发会话相互覆盖。`X11Proxy::for_endpoint` 只替换本机 server 的来源,x11-req、回连通道、fake cookie、真实 cookie 改写和双向中继继续复用。 + +**本机 endpoint 与远端 DISPLAY 是两套语义。** 远端 DISPLAY 由 sshd 在 accepted x11-req 后分配;远端客户端通过 SSH 通道回连,不会把本机 TCP 端口号当作远端 display。本机使用 `127.0.0.1` 上随机 display 对应的 `6000 + display` 端口;发生冲突时在组件锁内轮换,不再宣称 yserver 支持任意 TCP 端口参数。 + +## 组件供应链与内嵌交付 + +组件版本为 `1.9.0-navop.1`,源码固定为 [feigeCode/yserver](https://github.com/feigeCode/yserver) 提交 `3b3c7f66fb9d9c80752af36b4948fad0b8760671`,发布物固定到 [navop-v1.9.0-1](https://github.com/feigeCode/yserver/releases/tag/navop-v1.9.0-1)。fork 基于上游 v1.9.0,只增加安全监听参数及 Windows 构建配置,不自动追踪 latest。 + +运行时清单使用 schema 1,按 `windows-x86_64`、`windows-aarch64` 选择 artifact。artifact 只包含版本、SHA-256、Ed25519 签名、最低 Vulkan 版本、`format` 和 `executable_path`,不包含 URL 等下载元数据;Windows zip 完整保留 `yserver.exe`、`xauth.exe`、`xkb/` 与 licenses。`pinned_for_navop` 匹配当前 Navop 版本,artifact 自身版本独立解析。签名原始字节是完整 zip,不是摘要文本或解压后的单个可执行文件。同一组件版本不得替换不同摘要,更新组件必须提升版本并同步固定清单和构建期地址。 + +正式 Windows full 和 standalone-shell x86_64 构建前,`script/prepare-windows-x11-component.py` 从脚本内固定地址获取 zip、限制大小、按固定清单校验 SHA-256 与 Ed25519 签名,再通过 `NAVOP_X11_BUNDLED_ARCHIVE` 交给 `crates/x11_component/build.rs` 编进 `navop.exe`。网络访问只发生在构建机,build script 和成品运行时均不联网获取组件。这样 MSI、Burn、portable 和只替换 exe 的自更新都携带同一组件,不依赖旁置 zip。Win32 没有对应 yserver 产品,standalone-data 不嵌入;二者均不得误装 x64 包。当前 Navop 没有 Windows aarch64 产品 target,但组件安装器保留正确架构选择供后续产品接入。 + +运行时安装和“修复/重新安装”只读取内嵌 zip,仍完整执行灰度、摘要、签名、安全 zip 解压、staging 与原子提交。crate 不包含 HTTP client、远程清单或下载重试逻辑;没有内嵌包、包损坏或目标不符时 fail-closed,不存在网络回退。 + +安装进入 `/components/x11/.tmp-/`,校验后原子 rename 到 `/`。验签公钥固定在仓库且独立于应用更新公钥,私钥只在 fork 仓库的 GitHub Actions secret。任何校验失败都删除临时目录并 fail closed。版本目录保留最近两个非活跃版本;current、本次安装版本和任何实例仍在使用的版本都受保护。重新安装不会杀掉活跃 server,提交前在组件锁内重新检查活跃版本。 + +内嵌包验签、解压、目录替换与清理在 blocking 线程执行。组件根目录的跨进程文件锁覆盖安装提交和 server 启动临界区;`instances/*` 记录各进程持有的 server,避免多实例并发覆盖 pidfile、误替换版本或误删记录。 + +内置清单同时承载灰度比例,缺省灰度为 0%;显式 Embedded 和手动二进制入口用于开发验收,不被 Auto 灰度拦截。`NAVOP_X11_YSERVER_PATH` 仍经过同一套 Vulkan、endpoint、进程和握手检查,但不能把上游原版的全网卡监听当作安全内置。 + +## 进程与健康检查 + +组件全局只维护一个 server,同一 Navop 进程内的所有 SSH 会话共享 endpoint,但各自保留 x11-req 的 cookie 委托。cookie 由组件生成并写入 server xauth 文件,同时交给 `X11Proxy::for_endpoint`。本期不跨 Navop 进程附加到已有 server:检测到另一实例仍持有它时明确返回停用原因,而不是猜用对方的 cookie。 + +启动后必须完成一次真实 X11 setup 握手:发送 MIT-MAGIC-COOKIE-1 ClientHello,读取完整 setup reply,并限制应答大小和总超时。仅等待进程或端口可连接不算健康。 + +进程退出由 supervisor 记录并重启,窗口为 10 分钟最多 3 次;超限后本次运行禁用内置,成功、失败和永久禁用都会留下供界面消费的崩溃通知。pidfile 必须同时校验 pid、进程启动时间和可执行文件身份,不能仅按 pid 杀进程。启动在组件锁内同时检查共享 pidfile 和 `instances/*`:另一 Navop 实例仍持有的活跃 server 不能当作孤儿清理;owner 已退出且 child 身份一致的进程才按孤儿回收。首次启动遇到 endpoint 冲突会在锁内轮换随机 identity,崩溃重启保持原 endpoint/cookie。Windows 子进程统一经过 `process-util` 的后台进程配置。 + +启动、崩溃、重启、Auto 回退和内置失败使用单调计数,并输出 `x11_component.metrics` structured 日志,供 dogfood 计算崩溃率和回退率;本期不虚构尚未接入的远端遥测后端。 + +## 上游 endpoint 限制与安全改造 + +上游公开 [setup 文档](https://github.com/joske/yserver/blob/master/docs/setup.md) 的 `yserver :7 -auth -listen tcp` 默认监听 `0.0.0.0`,不能限定 loopback。[Windows 发布说明](https://github.com/joske/yserver/blob/master/tools/windows/README.txt)要求 trusted (`-Y`),并声明 Vulkan 能力要求。该默认 TCP 形态不满足本设计的安全要求。 + +Navop fork 增加 `--listen IP`,只绑定明确给出的单个地址;保留默认行为以兼容上游其他用户。正式内置命令固定为 `--listen 127.0.0.1`,并继续使用 cookie。`CommandSpec::installed_tcp` 和 `manual_upstream_tcp` 分离:已验签的 fork 走安全参数,手动上游 TCP 仍 fail-closed,避免旧版静默忽略新参数。不能把全网卡监听伪装成随机回环端口,也不能靠改写远端 DISPLAY 规避问题。 + +## 用户可见状态 + +设置页展示模式、已安装组件版本和“修复/重新安装”。会话信息显示以下结构化状态之一:外部 server 及其名称、内置 yserver 及版本、已停用及具体原因。 + +本地安装失败、验签失败、Vulkan 不足、握手超时、平台/灰度不可用、远端拒绝 x11-req 都必须有对应文案。只有收到真实 CHANNEL_FAILURE 才显示远端拒绝诊断;本地发送失败、连接关闭和响应超时分别归类,成功响应恢复该会话此前的可用状态。远端拒绝时提示检查 `X11Forwarding yes`、`X11DisplayOffset`、xauth,并明确本应用使用 trusted (`-Y`);不能拿不支持 SECURITY 扩展的 `ssh -X` 行为作为诊断依据。 + +X11 回连等待响应期间保留其他通道事件,每个 SSH 连接最多接受 32 条并发 X11 回连;本机连接、认证头读取和 setup 握手合计有 10 秒超时,已建立的正常双向中继不受这个总时长限制。 + +## 验证 + +- 单元:manifest、artifact、版本、路径、签名正/负/截断/换公钥、cookie、命令安全闸门、崩溃窗口与灰度。 +- 集成:使用内存清单和 zip,覆盖篡改、重复安装、握手失败、重启,以及离线安装、目标不匹配、损坏包和强制修复。 +- 构建:准备脚本校验真实固定 zip,CI 编译内嵌产物并运行内嵌字节与固定清单一致性测试;普通运行时测试不访问组件网络。 +- 转发:setup 探针执行真实协议往返,并验证可变长度正文完整读取。 +- E2E:Windows 上真实 yserver + xterm/gtk3-demo 截图比对;该验收不能用 mock 替代。 +- 手动矩阵:有无 Vulkan、RDP、多显示器、HiDPI、与 VcXsrv 共存、Windows arm64。 + +本环境无法完成 Windows 真实窗口和 GPU 矩阵时,交付报告必须明确标记未验收,不能把单元测试描述成端到端通过。 diff --git a/resources/windows/x11-component/navop-x11-manifest.json b/resources/windows/x11-component/navop-x11-manifest.json new file mode 100644 index 000000000..0b015a6da --- /dev/null +++ b/resources/windows/x11-component/navop-x11-manifest.json @@ -0,0 +1,28 @@ +{ + "schema": 1, + "components": { + "x11-server": { + "channel": "stable", + "pinned_for_navop": ">=0.23.4, <0.24.0", + "rollout_percent": 100, + "artifacts": { + "windows-x86_64": { + "version": "1.9.0-navop.1", + "sha256": "631521cd48acd625e2e7310132b38cbb706e816323413e3417f84122b73fd92a", + "signature": "4GInhRO+Dtk815ZoaAGhjqpO2F57/VaLHHOVQv7bsCAKMpISLMXFLrg7gzmCK6lGtUtYIm0laJhvHDw3XPmWDg==", + "min_vulkan": "1.3.0", + "format": "zip", + "executable_path": "yserver-1.9.0-windows-x86_64/yserver.exe" + }, + "windows-aarch64": { + "version": "1.9.0-navop.1", + "sha256": "767a495f6648dc4e10d3d4dce63349d72433383db765f9d0225d378ffff36096", + "signature": "aNOXBfU3rchX+oBcGvIcucEhsYUoU2HfoOanniPKq49i1tQMt7UKGboDoBHeQLFOu6OWQgZG7WKoeLUD/5KuBg==", + "min_vulkan": "1.3.0", + "format": "zip", + "executable_path": "yserver-1.9.0-windows-aarch64/yserver.exe" + } + } + } + } +} diff --git a/resources/windows/x11-component/public-key.txt b/resources/windows/x11-component/public-key.txt new file mode 100644 index 000000000..6a4833801 --- /dev/null +++ b/resources/windows/x11-component/public-key.txt @@ -0,0 +1 @@ +ynaEhu5Dl2msPYkT2biXk1uYrF6CncTKvbKgicJEM+I= diff --git a/script/prepare-windows-x11-component.py b/script/prepare-windows-x11-component.py new file mode 100644 index 000000000..7f063e6b5 --- /dev/null +++ b/script/prepare-windows-x11-component.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""下载并验证固定的 Windows X11 组件,供 Cargo 构建期内嵌;本脚本不接触私钥。""" + +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import subprocess +import tempfile +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parents[1] +RESOURCE_DIR = ROOT / "resources" / "windows" / "x11-component" +EXPECTED_COMPONENT_VERSION = "1.9.0-navop.1" +ARTIFACT_URLS = { + "windows-x86_64": "https://github.com/feigeCode/yserver/releases/download/navop-v1.9.0-1/yserver-1.9.0-navop.1-windows-x86_64.zip", + "windows-aarch64": "https://github.com/feigeCode/yserver/releases/download/navop-v1.9.0-1/yserver-1.9.0-navop.1-windows-arm64.zip", +} +MAX_ARTIFACT_BYTES = 256 * 1024 * 1024 +ED25519_SPKI_DER_PREFIX = bytes.fromhex("302a300506032b6570032100") + + +def prepare(target: str, output: Path) -> dict: + manifest = json.loads((RESOURCE_DIR / "navop-x11-manifest.json").read_text("utf-8")) + component = manifest["components"]["x11-server"] + if manifest.get("schema") != 1 or component.get("channel") != "stable": + raise ValueError("X11 清单 schema/channel 不受支持") + if component.get("rollout_percent") != 100: + raise ValueError("随包组件必须 rollout_percent=100") + artifact = component["artifacts"][target] + if artifact.get("version") != EXPECTED_COMPONENT_VERSION: + raise ValueError("组件版本变化必须同时更新准备脚本的固定版本") + executable_path = PurePosixPath(artifact.get("executable_path", "")) + if ( + artifact.get("format") != "zip" + or executable_path.is_absolute() + or ".." in executable_path.parts + or executable_path.name != "yserver.exe" + ): + raise ValueError("随包组件必须声明安全的 yserver.exe 相对路径") + url = ARTIFACT_URLS[target] + if not url.startswith("https://"): + raise ValueError("组件下载必须使用 HTTPS") + expected_sha256 = artifact["sha256"].lower() + if len(expected_sha256) != 64 or any(c not in "0123456789abcdef" for c in expected_sha256): + raise ValueError("组件 SHA256 格式无效") + signature = base64.b64decode(artifact["signature"], validate=True) + public_key = base64.b64decode( + (RESOURCE_DIR / "public-key.txt").read_text("ascii").strip(), validate=True + ) + if len(signature) != 64 or len(public_key) != 32: + raise ValueError("Ed25519 公钥或签名长度无效") + + output = output.resolve() + output.parent.mkdir(parents=True, exist_ok=True) + # Windows runner 的 TEMP 常在 C:,而 RUNNER_TEMP/输出在 D:; + # 与输出同盘的 staging 才能保证 os.replace 原子提交不会 WinError 17。 + with tempfile.TemporaryDirectory(prefix=".navop-x11-prepare-", dir=output.parent) as temporary: + temporary = Path(temporary) + download = temporary / "component.zip" + digest = hashlib.sha256() + size = 0 + request = urllib.request.Request(url, headers={"User-Agent": "navop-x11-release-builder"}) + with urllib.request.urlopen(request, timeout=120) as response, download.open("wb") as writer: + while chunk := response.read(1024 * 1024): + size += len(chunk) + if size > MAX_ARTIFACT_BYTES: + raise ValueError("组件超过 256 MiB 安全上限") + digest.update(chunk) + writer.write(chunk) + actual_sha256 = digest.hexdigest() + if size == 0 or actual_sha256 != expected_sha256: + raise ValueError(f"组件 SHA256 不匹配:期望 {expected_sha256},实际 {actual_sha256}") + + key_path = temporary / "public-key.der" + signature_path = temporary / "signature.bin" + key_path.write_bytes(ED25519_SPKI_DER_PREFIX + public_key) + signature_path.write_bytes(signature) + subprocess.run( + [ + "openssl", "pkeyutl", "-verify", "-rawin", + "-pubin", "-inkey", str(key_path), "-keyform", "DER", + "-sigfile", str(signature_path), "-in", str(download), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + with zipfile.ZipFile(download) as archive: + names = set(archive.namelist()) + root = executable_path.parent + required_files = ( + str(executable_path), + str(root / "xauth.exe"), + str(root / "licenses" / "rust-crates.txt"), + ) + missing = [name for name in required_files if name not in names] + required_xkb_dirs = ("compat", "keycodes", "rules", "symbols", "types") + if missing or any( + not any( + name.startswith(f"{root}/xkb/{directory}/") and not name.endswith("/") + for name in names + ) + for directory in required_xkb_dirs + ): + raise ValueError(f"组件包结构不完整:{missing} 或缺少 XKB 键盘数据") + os.replace(download, output) + + if hashlib.sha256(output.read_bytes()).hexdigest() != expected_sha256: + raise ValueError("输出组件复核失败") + return { + "target": target, + "version": artifact["version"], + "sha256": expected_sha256, + "bytes": output.stat().st_size, + "output": str(output), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--target", required=True, choices=["windows-x86_64", "windows-aarch64"]) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + print(json.dumps(prepare(args.target, args.output), ensure_ascii=False)) + + +if __name__ == "__main__": + main()