Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
feat: add daemon web console and Windows desktop shell (#138)
澄潭d1cd719540d6
diff --git a/.agents/skills/hiroute-public-pr/references/public-surface.v1.json b/.agents/skills/hiroute-public-pr/references/public-surface.v1.jsonindex 031077b9..6049976e 100644--- a/.agents/skills/hiroute-public-pr/references/public-surface.v1.json+++ b/.agents/skills/hiroute-public-pr/references/public-surface.v1.json@@ -61,7 +61,9 @@"docs/standalone-windows.md","docs/test-selection.md","docs/validation-feedback.md",- "docs/validation-routing.md"+ "docs/validation-routing.md",+ "docs/web-console.md",+ "docs/windows-desktop-installation.md"],"exclude_files": [".claude/skills/hiroute-promo-video"diff --git a/.github/workflows/build-release-platform.yml b/.github/workflows/build-release-platform.ymlindex 7a85596e..4bca73dd 100644--- a/.github/workflows/build-release-platform.yml+++ b/.github/workflows/build-release-platform.yml@@ -1,6 +1,22 @@name: build-release-platformon:+ workflow_dispatch:+ inputs:+ target:+ description: Native installer candidate target+ type: choice+ default: x86_64-pc-windows-msvc+ options: [x86_64-pc-windows-msvc]+ runner:+ description: Native build host+ type: choice+ default: windows-2025+ options: [windows-2025]+ windows_desktop:+ description: Build the NSIS installer for native acceptance+ type: boolean+ default: trueworkflow_call:inputs:target:@@ -9,6 +25,9 @@ on:runner:required: truetype: string+ windows_desktop:+ default: false+ type: booleanpermissions:contents: read@@ -86,16 +105,36 @@ jobs:shell: pwshenv:RELEASE_TARGET: ${{ inputs.target }}+ WINDOWS_DESKTOP: ${{ inputs.windows_desktop }}run: |if ((git rev-parse HEAD) -ne $env:GITHUB_SHA) { throw 'Exact dispatch SHA required' }- python scripts/build-release.py --target $env:RELEASE_TARGET --cpa-source-repo "$env:RUNNER_TEMP/cpa"+ $desktop = @()+ if ($env:WINDOWS_DESKTOP -eq 'true') { $desktop = @('--windows-desktop') }+ $buildOutput = python scripts/build-release.py --target $env:RELEASE_TARGET --cpa-source-repo "$env:RUNNER_TEMP/cpa" @desktopif ($LASTEXITCODE -ne 0) { throw 'Native Windows candidate build failed' }+ $buildOutput+ if ($desktop.Count -gt 0) {+ New-Item artifacts/windows-desktop -ItemType Directory -Force | Out-Null+ $buildOutput | Set-Content artifacts/windows-desktop/build-result.json -Encoding utf8+ $env:HIROUTE_BUILD_SOURCE_SHA = $env:GITHUB_SHA+ $env:CARGO_ENCODED_RUSTFLAGS = '-C' + [char]31 + 'target-feature=+crt-static'+ $env:CMAKE_TOOLCHAIN_FILE = (Join-Path $env:GITHUB_WORKSPACE 'scripts/windows-release-toolchain.cmake').Replace('\', '/')+ cargo test --locked --release --target x86_64-pc-windows-msvc -p hiroute-shell --features shell-runtime --lib -- --nocapture 2>&1 | Tee-Object artifacts/windows-desktop/shell-test.log+ if ($LASTEXITCODE -ne 0) { throw 'Native shell regressions failed' }+ cargo test --locked --release --target x86_64-pc-windows-msvc -p hiroute-cli --lib service::restore_plan::tests -- --nocapture 2>&1 | Tee-Object artifacts/windows-desktop/agent-restore-plan-test.log+ if ($LASTEXITCODE -ne 0) { throw 'Native uninstall restore-plan regressions failed' }+ cargo test --locked --release --target x86_64-pc-windows-msvc -p hiroute-daemon --test windows_desktop --no-run --message-format=json | Tee-Object artifacts/windows-desktop/compiler.jsonl+ if ($LASTEXITCODE -ne 0) { throw 'Native installer acceptance harness compilation failed' }+ python scripts/windows-dev.py bundle-desktop --result artifacts/windows-desktop/build-result.json --log artifacts/windows-desktop/compiler.jsonl --output artifacts/windows-desktop/development-bundle.zip+ if ($LASTEXITCODE -ne 0) { throw 'Native installer development bundle verification failed' }+ }- uses: actions/upload-artifact@v4if: always()with:- name: release-${{ inputs.target }}-${{ github.sha }}-${{ github.run_attempt }}+ name: release-${{ inputs.target }}${{ inputs.windows_desktop && '-desktop' || '' }}-${{ github.sha }}-${{ github.run_attempt }}path: |target/release-candidate/**/assets/*+ target/release-candidate/**/internal-payloads/*target/release-candidate/**/result.jsontarget/release-candidate/**/build.logtarget/release-candidate/**/linux-abi.json@@ -105,5 +144,6 @@ jobs:target/desktop-package/**/result.jsontarget/desktop-package/**/build.logartifacts/ci+ artifacts/windows-desktopif-no-files-found: errorretention-days: 14diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.ymlindex a026293b..e43a54ce 100644--- a/.github/workflows/build-release.yml+++ b/.github/workflows/build-release.yml@@ -28,6 +28,7 @@ jobs:target: ${{ matrix.target }}runner: ${{ matrix.runner }}+ # Headless archives are internal test/installer payloads, never public assets.build-windows:needs: windows-validationstrategy:@@ -42,3 +43,11 @@ jobs:with:target: ${{ matrix.target }}runner: ${{ matrix.runner }}++ build-windows-desktop:+ needs: windows-validation+ uses: ./.github/workflows/build-release-platform.yml+ with:+ target: x86_64-pc-windows-msvc+ runner: windows-2025+ windows_desktop: truediff --git a/.github/workflows/gateway-core.yml b/.github/workflows/gateway-core.ymlindex 93593ae8..f5844198 100644--- a/.github/workflows/gateway-core.yml+++ b/.github/workflows/gateway-core.yml@@ -56,8 +56,8 @@ jobs:if-no-files-found: ignorebackend_shard:name: backend-shard (${{ matrix.shard }})- needs: selection- if: needs.selection.outputs.rust == 'true'+ needs: [selection, frontend]+ if: always() && needs.selection.result == 'success' && needs.selection.outputs.rust == 'true' && (needs.frontend.result == 'success' || needs.frontend.result == 'skipped')strategy:fail-fast: falsematrix: ${{ fromJSON(needs.selection.outputs.backend_matrix) }}@@ -71,6 +71,12 @@ jobs:persist-credentials: falsefetch-depth: 0- uses: ./.github/actions/ci-setup+ - name: Use the candidate console in installed-product tests+ if: matrix.shard == 'integration-daemon'+ uses: actions/download-artifact@v4+ with:+ name: desktop-console-${{ github.run_id }}-${{ github.run_attempt }}+ path: apps/desktop/dist- name: CI adapter testsif: matrix.shard == 'quality' || matrix.shard == 'affected'run: python3 scripts/test-ci-run.py && python3 scripts/test-rust-file-size.py@@ -135,6 +141,12 @@ jobs:working-directory: apps/desktop- run: npm run build && npm testworking-directory: apps/desktop+ - name: Export the exact candidate console+ uses: actions/upload-artifact@v4+ with:+ name: desktop-console-${{ github.run_id }}-${{ github.run_attempt }}+ path: apps/desktop/dist+ if-no-files-found: error- name: Current metadata generationrun: |python3 tools/model-metadata/close_model_metadata.py --checkdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e358b03a..ad3748db 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -70,7 +70,13 @@ jobs:node apps/website/scripts/release-manifest.mjs desktop-artifacts apps/website/data/releases.json --tag "$RELEASE_TAG" > "$RUNNER_TEMP/desktop-assets.txt"while IFS= read -r filename; doidentity="$RUNNER_TEMP/release-assets/$filename.identity.json"- python3 scripts/package-desktop.py verify-dmg "$RUNNER_TEMP/release-assets/$filename" > "$identity"+ case "$filename" in+ *-windows-x86_64-setup.exe)+ gh release download "$RELEASE_TAG" --dir "$RUNNER_TEMP/release-assets" --pattern "$filename.identity.json"+ python3 scripts/package-windows-shell.py verify --installer "$RUNNER_TEMP/release-assets/$filename" --identity "$identity" --revision "$RELEASE_REVISION"+ ;;+ *) python3 scripts/package-desktop.py verify-dmg "$RUNNER_TEMP/release-assets/$filename" > "$identity" ;;+ esacnode apps/website/scripts/release-manifest.mjs verify-desktop-identity apps/website/data/releases.json --tag "$RELEASE_TAG" --revision "$RELEASE_REVISION" --filename "$filename" --identity "$identity"done < "$RUNNER_TEMP/desktop-assets.txt"node apps/website/scripts/release-manifest.mjs standalone-packages apps/website/data/releases.json --tag "$RELEASE_TAG" > "$RUNNER_TEMP/standalone-assets.tsv"diff --git a/.github/workflows/windows-compile.yml b/.github/workflows/windows-compile.ymlindex a2375a79..b1129c7d 100644--- a/.github/workflows/windows-compile.yml+++ b/.github/workflows/windows-compile.yml@@ -1,6 +1,7 @@name: windows-headless-compileon:+ workflow_dispatch:pull_request:paths:- 'crates/**'@@ -11,6 +12,7 @@ on:- 'assets/**'- 'vendor/**'- 'tools/**'+ - 'apps/shell/**'- 'scripts/**'- '.github/workflows/windows-compile.yml'@@ -18,7 +20,7 @@ permissions:contents: readconcurrency:- group: windows-compile-${{ github.event.pull_request.number }}+ group: windows-compile-${{ github.event.pull_request.number || github.run_id }}cancel-in-progress: truejobs:@@ -38,6 +40,9 @@ jobs:shell: pwshrun: rustup show active-toolchain- uses: mozilla-actions/[email protected]+ - uses: actions/setup-node@v4+ with:+ node-version: '22'- uses: actions/cache@v4with:path: |@@ -50,3 +55,24 @@ jobs:run: |cargo check --locked --target x86_64-pc-windows-msvc -p hiroute-cli -p hiroute-daemon -p hiroute-platform -p hiroute-local-storage --all-targetsif ($LASTEXITCODE -ne 0) { throw 'Windows headless compilation failed' }+ - name: Test Windows package and restore policy components+ shell: pwsh+ run: |+ $os = Get-CimInstance Win32_OperatingSystem+ $admin = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ @{ version=$os.Version; build=$os.BuildNumber; architecture=[Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString(); administrator=$admin; evidence='component fixtures, not standard-user installation acceptance' } | ConvertTo-Json -Compress+ cargo test --locked --target x86_64-pc-windows-msvc -p hiroute-host-runtime --lib standalone_install::+ if ($LASTEXITCODE -ne 0) { throw 'Windows installation component regressions failed' }+ - name: Check Windows console shell and its restricted host commands+ shell: pwsh+ env:+ # Compile the host without release payloads; build-release.py stages+ # and validates those before packaging with the production config.+ TAURI_CONFIG: '{"bundle":{"resources":[]}}'+ run: |+ npm ci --prefix apps/shell+ if ($LASTEXITCODE -ne 0) { throw 'Shell frontend dependencies failed' }+ npm run build --prefix apps/shell+ if ($LASTEXITCODE -ne 0) { throw 'Shell frontend build failed' }+ cargo check --locked --target x86_64-pc-windows-msvc -p hiroute-shell --features shell-runtime --all-targets+ if ($LASTEXITCODE -ne 0) { throw 'Windows console shell compilation failed' }diff --git a/.github/workflows/windows-headless.yml b/.github/workflows/windows-headless.ymlindex a4251c17..43c70c7e 100644--- a/.github/workflows/windows-headless.yml+++ b/.github/workflows/windows-headless.yml@@ -36,7 +36,7 @@ jobs:with:python-version: '3.12'- uses: actions/setup-node@v4- if: matrix.scope == 'agents'+ if: matrix.scope == 'agents' || matrix.scope == 'background'with:node-version: '22.19.0'- name: Locked upstream client fixtures@@ -76,10 +76,11 @@ jobs:windows11:name: windows11-x64 (${{ matrix.scope }})needs: native+ if: inputs.scope != 'background'strategy:fail-fast: falsematrix:- scope: ${{ fromJSON(inputs.scope != '' && inputs.scope != 'all' && format('["{0}"]', inputs.scope) || '["components","core","product","background","agents"]') }}+ scope: ${{ fromJSON(inputs.scope != '' && inputs.scope != 'all' && format('["{0}"]', inputs.scope) || '["components","core","product","agents"]') }}runs-on: windows-11-armtimeout-minutes: 75steps:@@ -119,3 +120,64 @@ jobs:path: artifacts/windows11if-no-files-found: errorretention-days: 14++ windows11-arm-install:+ name: Windows 11 ARM64 native Rust installation+ if: inputs.scope == '' || inputs.scope == 'all' || inputs.scope == 'background'+ runs-on: windows-11-arm+ timeout-minutes: 75+ env:+ CARGO_NET_GIT_FETCH_WITH_CLI: 'true'+ CARGO_INCREMENTAL: '0'+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-python@v5+ with:+ python-version: '3.12'+ architecture: arm64+ - name: Native ARM64 Rust toolchain+ shell: pwsh+ run: |+ if ([Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'Arm64') { throw 'Native ARM64 host required' }+ $toolchain = (Get-Content rust-toolchain.toml | Select-String '^channel\s*=\s*"([^" ]+)"').Matches.Groups[1].Value+ if (-not $toolchain) { throw 'Pinned repository toolchain required' }+ rustup toolchain install "$toolchain-aarch64-pc-windows-msvc" --profile minimal+ if ($LASTEXITCODE -ne 0) { throw 'Native ARM64 toolchain unavailable' }+ # The repository toolchain file overrides rustup's default. Bind the+ # complete native toolchain for this step and all subsequent steps.+ $env:RUSTUP_TOOLCHAIN = "$toolchain-aarch64-pc-windows-msvc"+ "RUSTUP_TOOLCHAIN=$env:RUSTUP_TOOLCHAIN" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append+ $hostLine = (rustc -vV | Select-String '^host: (.+)$').Matches.Groups[1].Value+ if ($LASTEXITCODE -ne 0 -or $hostLine -cne 'aarch64-pc-windows-msvc') { throw 'Native ARM64 compiler unavailable' }+ - uses: actions/setup-node@v4+ with:+ node-version: '22'+ architecture: arm64+ - name: Exact CPA source+ shell: pwsh+ run: |+ $pin = Get-Content vendor/cpa/source.json -Raw | ConvertFrom-Json+ git init "$env:RUNNER_TEMP/cpa"+ git -C "$env:RUNNER_TEMP/cpa" fetch --depth=1 $pin.repository $pin.commit+ if ($LASTEXITCODE -ne 0) { throw 'Pinned CPA fetch failed' }+ git -C "$env:RUNNER_TEMP/cpa" checkout --detach FETCH_HEAD+ if ($LASTEXITCODE -ne 0) { throw 'Pinned CPA checkout failed' }+ - uses: actions/setup-go@v5+ with:+ go-version-file: ${{ runner.temp }}/cpa/go.mod+ architecture: arm64+ cache: false+ - name: Native Task install, repeat, lifecycle and uninstall through Rust+ shell: pwsh+ run: |+ & scripts/windows-headless-ci.ps1 -Scope install -ExpectedSha $env:GITHUB_SHA -Evidence artifacts/windows11-arm-install -CpaSource "$env:RUNNER_TEMP/cpa" -Plan web-console-windows-shell -Phase final+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: windows11-arm-install-${{ github.sha }}-${{ github.run_attempt }}+ path: artifacts/windows11-arm-install+ if-no-files-found: error+ retention-days: 14diff --git a/.gitignore b/.gitignoreindex c60e9c8b..28f66819 100644--- a/.gitignore+++ b/.gitignore@@ -30,6 +30,7 @@*.profraw__pycache__/*.pyc+/apps/shell/src-tauri/resources/# Local iteration assessments and stage-review working notes (not product contracts)./docs/acp-mvp-roi-review.md/docs/stage-product-integration-review.mddiff --git a/Cargo.lock b/Cargo.lockindex a6bff237..a46c4544 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -328,6 +328,20 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-executor"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"+dependencies = [+ "async-task",+ "concurrent-queue",+ "fastrand",+ "futures-lite",+ "pin-project-lite",+ "slab",+]+[[package]]name = "async-io"version = "2.6.0"@@ -2298,6 +2312,7 @@ dependencies = ["arc-swap","async-trait","base64 0.22.1",+ "bytes","command-fds","futures","getrandom 0.3.4",@@ -2314,7 +2329,11 @@ dependencies = ["hiroute-observation","hiroute-platform","hiroute-platform-test-support",+ "hiroute-product-session","http",+ "http-body-util",+ "hyper",+ "hyper-util","nix","rusqlite","rustix",@@ -2345,6 +2364,7 @@ dependencies = ["hiroute-diagnostics","hiroute-domain","hiroute-host-runtime",+ "hiroute-product-session","nix","reqwest","serde",@@ -2486,6 +2506,7 @@ dependencies = [name = "hiroute-host-runtime"version = "0.1.0"dependencies = [+ "fs2","getrandom 0.3.4","hiroute-platform","nix",@@ -2578,6 +2599,7 @@ dependencies = ["serde_json","sha2","tempfile",+ "url","windows 0.62.2","windows-sys 0.61.2","zeroize",@@ -2611,6 +2633,22 @@ dependencies = ["tokio",]+[[package]]+name = "hiroute-product-session"+version = "0.1.0"+dependencies = [+ "getrandom 0.3.4",+ "hiroute-application-api",+ "hiroute-client-core",+ "hiroute-diagnostics",+ "hiroute-domain",+ "serde",+ "serde_json",+ "tempfile",+ "tokio",+ "zeroize",+]+[[package]]name = "hiroute-release-facts"version = "0.1.0"@@ -2624,6 +2662,27 @@ dependencies = ["thiserror 2.0.20",]+[[package]]+name = "hiroute-shell"+version = "0.3.1"+dependencies = [+ "fs2",+ "hiroute-application-api",+ "hiroute-client-core",+ "hiroute-host-runtime",+ "hiroute-platform",+ "reqwest",+ "serde",+ "serde_json",+ "sha2",+ "tauri",+ "tauri-build",+ "tauri-plugin-dialog",+ "tauri-plugin-single-instance",+ "tokio",+ "url",+]+[[package]]name = "hmac"version = "0.12.1"@@ -2702,6 +2761,7 @@ dependencies = ["http","http-body","httparse",+ "httpdate","itoa","pin-project-lite","smallvec",@@ -5611,6 +5671,7 @@ dependencies = ["gtk","heck 0.5.0","http",+ "image","jni","libc","log",@@ -5799,6 +5860,21 @@ dependencies = ["windows 0.62.2",]+[[package]]+name = "tauri-plugin-single-instance"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a33a5b7d78f0dec4406b003ea87c40bf928d801b6fd9323a556172c91d8712c1"+dependencies = [+ "serde",+ "serde_json",+ "tauri",+ "thiserror 2.0.20",+ "tracing",+ "windows-sys 0.60.2",+ "zbus",+]+[[package]]name = "tauri-runtime"version = "2.11.3"@@ -7592,8 +7668,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"dependencies = ["async-broadcast",+ "async-executor",+ "async-io",+ "async-lock",+ "async-process","async-recursion",+ "async-task","async-trait",+ "blocking","enumflags2","event-listener","futures-core",diff --git a/Cargo.toml b/Cargo.tomlindex 5ba1d107..79abeb9a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,7 @@[workspace]members = ["apps/desktop/src-tauri",+ "apps/shell/src-tauri","crates/application","crates/application-api","crates/cli",@@ -17,6 +18,7 @@ members = ["crates/local-storage","crates/observation","crates/platform",+ "crates/product-session","crates/platform/test-support","tools/e2e-harness","tools/product-e2e",diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 213de8c8..38ef3460 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -11,6 +11,7 @@ desktop-runtime = ["dep:tauri", "dep:tauri-build", "dep:tauri-plugin-dialog", "ddesktop-pilot = ["desktop-runtime", "dep:tauri-plugin-pilot"][dependencies]+hiroute-product-session = { path = "../../../crates/product-session" }hiroute-client-core = { path = "../../../crates/client-core" }hiroute-diagnostics = { path = "../../../crates/diagnostics" }hiroute-application-api = { path = "../../../crates/application-api" }@@ -40,6 +41,7 @@ hiroute-desktop-host-effects = { path = "../../../crates/desktop-host-effects" }tauri-build = { version = "2.6", optional = true }[dev-dependencies]+hiroute-product-session = { path = "../../../crates/product-session", features = ["test-support"] }tempfile.workspace = true[[bin]]diff --git a/apps/desktop/src-tauri/examples/acl_probe.rs b/apps/desktop/src-tauri/examples/acl_probe.rsindex d3ecd3f0..4183eed7 100644--- a/apps/desktop/src-tauri/examples/acl_probe.rs+++ b/apps/desktop/src-tauri/examples/acl_probe.rs@@ -3,7 +3,6 @@use hiroute_desktop::{bootstrap::Resident,bridge::{self, DesktopState},- session::Session,};use std::{io::{Read, Write},@@ -26,7 +25,7 @@ fn main() {.unwrap().join("hirouted");let resident = Resident::open(&root, &binary).unwrap();- let session = Session::new(resident);+ let session = hiroute_desktop::session_from_resident(resident);let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let url = format!("http://{}/", listener.local_addr().unwrap());std::thread::spawn(move || {diff --git a/apps/desktop/src-tauri/icons/icon.ico b/apps/desktop/src-tauri/icons/icon.iconew file mode 100644index 00000000..80043118Binary files /dev/null and b/apps/desktop/src-tauri/icons/icon.ico differdiff --git a/apps/desktop/src-tauri/src/bootstrap.rs b/apps/desktop/src-tauri/src/bootstrap.rsindex 5ae7a825..b00537b0 100644--- a/apps/desktop/src-tauri/src/bootstrap.rs+++ b/apps/desktop/src-tauri/src/bootstrap.rs@@ -508,39 +508,6 @@ impl Resident {};self.register_operation(digest, revisions, operation)}- pub(crate) fn register_observation(- &mut self,- request: &hiroute_application_api::ObservationReadRequestV2,- revisions: &RevisionSetV1,- ) -> Result<Zeroizing<String>, String> {- let digest = CanonicalDigest::of(request).map_err(|_| "OBSERVATION_REQUEST_INVALID")?;- self.register_operation(&digest, revisions, request.protected_operation())- }- pub(crate) fn register_classifier_diagnostic(- &mut self,- request: &hiroute_application_api::ClassifierDecisionTestRequestV1,- revisions: &RevisionSetV1,- ) -> Result<Zeroizing<String>, String> {- let digest = CanonicalDigest::of(request).map_err(|_| "CLASSIFIER_TEST_INVALID")?;- self.register_operation(&digest, revisions, "TestClassifierDecision")- }- #[cfg(feature = "desktop-runtime")]- pub(crate) fn register_retention(- &mut self,- digest: &CanonicalDigest,- revisions: &RevisionSetV1,- apply: bool,- ) -> Result<Zeroizing<String>, String> {- self.register_operation(- digest,- revisions,- if apply {- "ApplySessionDeletionV2"- } else {- "PreviewSessionDeletionV2"- },- )- }pub fn register_agent_settings(&mut self,restore: bool,@@ -1008,5 +975,6 @@ pub(crate) fn acquire_host_lock(root: &Path) -> Result<File, String> {#[cfg(test)]mod tests;-#[cfg(test)]-pub(crate) use tests::session_resident;++mod authority;+pub use authority::{NativeAuthority, resident};diff --git a/apps/desktop/src-tauri/src/bootstrap/authority.rs b/apps/desktop/src-tauri/src/bootstrap/authority.rsnew file mode 100644index 00000000..398f839e--- /dev/null+++ b/apps/desktop/src-tauri/src/bootstrap/authority.rs@@ -0,0 +1,78 @@+//! The Desktop adapter keeps the inherited descriptor frames and native lifecycle intact.+use super::*;+use hiroute_product_session::{HostAuthority, ProductSession};+use std::sync::{Mutex, MutexGuard};++pub struct NativeAuthority(pub Mutex<Resident>);++impl HostAuthority for NativeAuthority {+ fn as_any(&self) -> &dyn std::any::Any {+ &self.0+ }+ fn has_authority(&self) -> bool {+ self.0+ .lock()+ .is_ok_and(|mut resident| resident.has_authority())+ }+ fn register_operation(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ operation: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ self.0+ .lock()+ .map_err(|_| "TRUSTED_AUTHORITY_UNAVAILABLE")?+ .register_operation(digest, revisions, operation)+ }+ fn register_input(+ &self,+ candidate: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String> {+ candidate+ .validate_shape()+ .map_err(|_| "PROTECTED_INPUT_INVALID")?;+ let mut resident = self.0.lock().map_err(|_| "TRUSTED_AUTHORITY_UNAVAILABLE")?;+ if secret.is_empty() || secret.len() > 32 * 1024 || !resident.has_authority() {+ return Err("PROTECTED_INPUT_INVALID".into());+ }+ if let Err(error) = resident.register_model_input_once(candidate, &secret) {+ if let Some(owned) = &mut resident.owned {+ owned.authority_healthy = false;+ }+ return Err(error);+ }+ resident+ .owned+ .as_mut()+ .ok_or("TRUSTED_AUTHORITY_UNAVAILABLE")?+ .manual_input_candidates+ .insert(candidate.candidate_ref.clone());+ Ok(())+ }+ fn release_model_input(&self, candidate: &ComputeCandidateRefV2) -> Result<(), String> {+ self.0+ .lock()+ .map_err(|_| "TRUSTED_AUTHORITY_UNAVAILABLE")?+ .release_model_input(candidate)+ }+ fn remove_resident_login_item(+ &self,+ ) -> Result<hiroute_application_api::AgentLoginItemDeclarationV2, String> {+ crate::login_item::remove_resident_login_item().map_err(str::to_owned)+ }+ fn compensate_resident_login_item_removal(&self) {+ crate::login_item::compensate_resident_login_item_removal();+ }+}++pub fn resident(session: &ProductSession) -> Result<MutexGuard<'_, Resident>, String> {+ session+ .authority+ .as_any()+ .downcast_ref::<Mutex<Resident>>()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .lock()+ .map_err(|_| "RESIDENT_UNAVAILABLE".to_owned())+}diff --git a/apps/desktop/src-tauri/src/bootstrap/tests.rs b/apps/desktop/src-tauri/src/bootstrap/tests.rsindex f8e5d6fe..db9431be 100644--- a/apps/desktop/src-tauri/src/bootstrap/tests.rs+++ b/apps/desktop/src-tauri/src/bootstrap/tests.rs@@ -1,30 +1,5 @@use super::*;-/// Native channel fixture for Session/transport checks; never a production daemon substitute.-pub(crate) fn session_resident(root: &Path, client: Client) -> Resident {- use std::io::BufRead;- let mut resident = recovery_resident(root, false);- resident.client = client;- let (capability_reader, capability_writer) = pipe().unwrap();- let (ack_reader, mut ack_writer) = pipe().unwrap();- let owned = resident.owned.as_mut().unwrap();- owned.capability = capability_writer;- owned.ack = ack_reader;- std::thread::spawn(move || {- for line in std::io::BufReader::new(capability_reader).lines() {- let registration: serde_json::Value = serde_json::from_str(&line.unwrap()).unwrap();- let mut reply = serde_json::to_vec(&serde_json::json!({- "schema": "hiroute.protected-apply-ack/v2",- "registration_id": registration["registration_id"], "registered": true- }))- .unwrap();- reply.push(b'\n');- ack_writer.write_all(&reply).unwrap();- }- });- resident-}-fn recovery_resident(root: &Path, slow: bool) -> Resident {let (reader, writer) = pipe().unwrap();let (_, capability) = pipe().unwrap();diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rsindex 1a8494f8..d6be7350 100644--- a/apps/desktop/src-tauri/src/bridge.rs+++ b/apps/desktop/src-tauri/src/bridge.rs@@ -1,23 +1,25 @@-//! WebView supplies explicit intent and renders prompts; native preview and typed policy own submission.+use hiroute_application_api::*;+use hiroute_product_session::commands::{+ ClassifierDecisionTestInput, ClassifierHeaderSecretSaveInput, DecisionServiceSaveInput,+ ObservationDeleteInput, ProtectedModelInputRegistration, WebComputeCandidateViewV2,+ WebComputeConnectionApplyRequestV1, WebComputeDiscoveryRefV1, WebComputeManagementChangeV2,+ WebComputeSavePreviewV2, WebComputeSaveResultV2, WebComputeScanResultV2,+ WebComputeSubscriptionCandidatesV2, WebComputeSubscriptionCheckResultV2, WebValidationRefV2,+ WorkerDependencyConfirmationInput, WorkerDependencyConfirmationState,+ WorkerDependencyConfirmationV1,+};+use tauri::Emitter;+// WebView supplies explicit intent and renders prompts; native preview and typed policy own submission.use crate::failure::DesktopFailure;use crate::session::{- AgentCheckCompletion, AgentCheckConfirmation, AgentCheckDispatch, AgentCheckInput,- AgentConfirmation, AgentOutcome, AgentPreparation, AgentSettingsInput, AgentSnapshot,- Confirmation, DesktopSnapshot, EditorInput, ModelSaveAccepted, ModelSaveConfirmation,- MutationOutcome, PriceConfirmation, PriceDisplayResult, PriceEditInput, RenameInput,- RestoreInput, Session, SubscriptionCheckConfirmation,+ AgentCheckCompletion, AgentCheckInput, AgentOutcome, AgentSettingsInput, AgentSnapshot,+ DesktopSnapshot, EditorInput, ModelSaveAccepted, MutationOutcome, PriceDisplayResult,+ PriceEditInput, RenameInput, RestoreInput, Session,};use hiroute_application_api::{ClientOperationViewV1, GetEffectivePricesV2, ModelCatalogQueryV1, ModelCatalogResultV1,};-use hiroute_diagnostics::context::{DiagnosticContext, DiagnosticHandle};-use hiroute_diagnostics::correlation::CorrelationDomain;-use hiroute_diagnostics::error::EventErrorCode;-use hiroute_diagnostics::event::{- ActionEnd, ActionOperation, ActionResult, ApplyEvent, ApplyPhase, ConfirmationEvent,- ConfirmationPhase, DiagnosticEvent, PreviewEvent, PreviewPhase,-};-use hiroute_diagnostics::identity::CorrelationToken;+use hiroute_diagnostics::context::DiagnosticHandle;use serde_json::Value;use std::sync::{Arc,@@ -25,7 +27,6 @@ use std::sync::{};use tauri::{Manager, State, WebviewWindow};use tokio::sync::Mutex;-mod model_connection_web;mod model_connections;use model_connections::*;mod subscription_login;@@ -64,15 +65,6 @@ pub struct DesktopState(pub DiagnosticHandle,);-async fn confirmation_session(- state: &DesktopState,- epoch: u64,-) -> Result<tokio::sync::MutexGuard<'_, Option<Session>>, DesktopFailure> {- crate::confirmation::lock_current_session(&state.0, &state.2, epoch)- .await- .map_err(Into::into)-}-fn desktop_data_root(handle: &tauri::AppHandle) -> Result<std::path::PathBuf, ()> {let root = handle.path().app_local_data_dir().map_err(|_| ())?;#[cfg(debug_assertions)]@@ -90,171 +82,36 @@ fn main_window(window: &WebviewWindow) -> Result<(), String> {}}-/// Diagnostics for one protected native action. Carries the operation family, the real-/// revision and stable results; never confirmation text, payloads, digests or grants.-struct ActionDiagnostics {- context: DiagnosticContext,- operation: ActionOperation,- started: std::time::Instant,-}--impl ActionDiagnostics {- fn begin(handle: &DiagnosticHandle, operation: ActionOperation) -> Self {- Self {- context: handle.context(),- operation,- started: std::time::Instant::now(),- }- }-- fn preview(&self, phase: PreviewPhase, revision: Option<u64>) {- self.context.emit(DiagnosticEvent::Preview(PreviewEvent {- operation: self.operation,- phase,- revision,- }));- }-- fn confirmation(&self, phase: ConfirmationPhase, accepted: Option<bool>) {- self.context- .emit(DiagnosticEvent::Confirmation(ConfirmationEvent {- operation: self.operation,- phase,- accepted,- }));- }-- fn apply(&self, phase: ApplyPhase, revision: Option<u64>, result: Option<ActionResult>) {- self.context.emit(DiagnosticEvent::Apply(ApplyEvent {- operation: self.operation,- phase,- revision,- result,- }));- }-- /// The exact operation this action created, when the product reported one.- fn token(&self, operation_id: Option<&str>) -> Option<CorrelationToken> {- operation_id.and_then(|id| self.context.token(CorrelationDomain::Operation, id))- }-- fn end(&self, result: ActionResult, operation_token: Option<CorrelationToken>) {- self.context.emit(DiagnosticEvent::ActionEnd(ActionEnd {- operation: self.operation,- result,- operation_token,- elapsed_ms: self.started.elapsed().as_millis() as u64,- }));- }-}--impl NativeOutcome {- /// The stable result of this action; a denial is not a failure and vice versa. A- /// non-terminal product state is reported as a failure instead of "applied".- fn action_result(&self, accepted: bool) -> ActionResult {- if !accepted {- return ActionResult::Denied;- }- match self {- Self::Rename(mutation) => mutation_outcome_result(mutation),- Self::Agent(agent) => match &agent.mutation {- Some(mutation) => mutation_outcome_result(mutation),- None => ActionResult::Failed {- code: EventErrorCode::ExternalError,- },- },- Self::Check(completion) => {- if completion.passed() {- ActionResult::Applied- } else {- ActionResult::Failed {- code: EventErrorCode::ExternalError,- }- }- }- Self::ModelSave(accepted) => mutation_result(&accepted.result.state),- Self::SubscriptionCheck(result) => match result.status {- hiroute_application_api::ComputeSubscriptionCheckStatusV2::Verified => {- ActionResult::Applied- }- hiroute_application_api::ComputeSubscriptionCheckStatusV2::SourceChanged => {- ActionResult::Failed {- code: EventErrorCode::Conflict,- }- }- hiroute_application_api::ComputeSubscriptionCheckStatusV2::NeedsAuth => {- ActionResult::Failed {- code: EventErrorCode::Authorization,- }- }- hiroute_application_api::ComputeSubscriptionCheckStatusV2::Unavailable => {- ActionResult::Failed {- code: EventErrorCode::Unavailable,- }- }- _ => ActionResult::Failed {- code: EventErrorCode::ExternalError,- },- },- }- }-- /// The exact product operation this action produced, when it reported one.- fn operation_id(&self) -> Option<&str> {- match self {- Self::Rename(mutation) => mutation- .operation- .as_ref()- .map(|operation| operation.operation_id.as_str()),- Self::Agent(agent) => agent- .mutation- .as_ref()- .and_then(|mutation| mutation.operation.as_ref())- .map(|operation| operation.operation_id.as_str()),- Self::ModelSave(accepted) => Some(accepted.operation.operation_id.as_str()),- Self::SubscriptionCheck(result) => {- Some(result.approval_operation.operation_id.as_str())- }- Self::Check(_) => None,- }- }-}--fn mutation_outcome_result(mutation: &MutationOutcome) -> ActionResult {- mutation.operation.as_ref().map_or_else(- || mutation_result(&mutation.state),- |operation| mutation_result(&operation.state),- )-}--fn mutation_result(state: &str) -> ActionResult {- match state {- "succeeded" => ActionResult::Applied,- "needs_attention" => ActionResult::Failed {- code: EventErrorCode::Recovery,- },- _ => ActionResult::Failed {- code: EventErrorCode::ExternalError,- },- }-}#[tauri::command]pub async fn desktop_snapshot(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<DesktopSnapshot, DesktopFailure> {main_window(&window)?;- let mut guard = state.0.lock().await;- let session = guard.as_mut().ok_or_else(|| {- state- .1- .error- .get()- .cloned()- .unwrap_or("RESIDENT_UNAVAILABLE".into())- })?;- session.resume_observing();- session.snapshot().await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::desktop_snapshot(&context, &product_state).await}#[tauri::command]pub async fn refresh_route_references(@@ -263,25 +120,31 @@ pub async fn refresh_route_references(language: String,) -> Result<MutationOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::PlanEditor);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview_reference_refresh(language)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- confirm(- &window,- &state,- ActionOperation::PlanEditor,- NativeConfirmation::Rename(Box::new(context)),- epoch,- )- .await?- .mutation()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::refresh_route_references(&context, &product_state, language)+ .await}#[tauri::command]pub async fn preview_plan_editor(@@ -290,25 +153,30 @@ pub async fn preview_plan_editor(input: EditorInput,) -> Result<MutationOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::PlanEditor);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview_editor(input)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- confirm(- &window,- &state,- ActionOperation::PlanEditor,- NativeConfirmation::Rename(Box::new(context)),- epoch,- )- .await?- .mutation()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_plan_editor(&context, &product_state, input).await}#[tauri::command]pub async fn plan_editor_options(@@ -317,9 +185,30 @@ pub async fn plan_editor_options(input: hiroute_application_api::PlanEditorOptionsRequestV1,) -> Result<hiroute_application_api::PlanEditorOptionsV1, DesktopFailure> {main_window(&window)?;- let guard = state.0.lock().await;- let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;- crate::session::query(&session.client, "GetPlanEditorOptions", &input).await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::plan_editor_options(&context, &product_state, input).await}#[tauri::command]pub async fn preview_rename(@@ -328,27 +217,30 @@ pub async fn preview_rename(input: RenameInput,) -> Result<MutationOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::Rename);- action.preview(PreviewPhase::Begin, None);- let context = {- let mut guard = confirmation_session(&state, epoch).await?;- guard- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview(input)- .await?+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),};- action.preview(PreviewPhase::End, Some(context.revision()));- confirm(- &window,- &state,- ActionOperation::Rename,- NativeConfirmation::Rename(Box::new(context)),- epoch,- )- .await?- .mutation()+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_rename(&context, &product_state, input).await}#[tauri::command]pub async fn preview_restore_name(@@ -357,93 +249,30 @@ pub async fn preview_restore_name(input: RestoreInput,) -> Result<MutationOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::RestoreName);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview_restore(input)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- confirm(- &window,- &state,- ActionOperation::RestoreName,- NativeConfirmation::Rename(Box::new(context)),- epoch,- )- .await?- .mutation()-}-enum NativeConfirmation {- Rename(Box<Confirmation>),- Price(Box<PriceConfirmation>),- Agent(Box<AgentConfirmation>),- Check(Box<AgentCheckConfirmation>),- ModelSave(Box<ModelSaveConfirmation>),- SubscriptionCheck(Box<SubscriptionCheckConfirmation>),-}-enum NativeOutcome {- Rename(MutationOutcome),- Agent(Box<AgentOutcome>),- Check(AgentCheckCompletion),- ModelSave(ModelSaveAccepted),- SubscriptionCheck(Box<hiroute_application_api::ComputeSubscriptionCheckResultV2>),-}-impl NativeOutcome {- fn mutation(self) -> Result<MutationOutcome, DesktopFailure> {- match self {- Self::Rename(value) => Ok(value),- _ => Err("CONFIRMATION_KIND_MISMATCH".into()),- }- }-}-impl NativeConfirmation {- /// The exact revision this action was previewed against, from the real confirmation- /// context rather than from any WebView-provided value.- fn revision(&self) -> u64 {- match self {- Self::Rename(context) => context.revision(),- Self::Price(context) => context.revision(),- Self::Agent(context) => context.revision(),- Self::Check(context) => context.revision(),- Self::ModelSave(context) => context.revision(),- Self::SubscriptionCheck(context) => context.revision(),- }- }-- fn requires_confirmation(&self) -> bool {- match self {- Self::Rename(c) => c.requires_confirmation(),- Self::Price(_) => false,- Self::Check(c) => c.requires_confirmation(),- Self::Agent(c) => c.requires_confirmation(),- Self::ModelSave(c) => c.requires_confirmation(),- Self::SubscriptionCheck(c) => c.requires_confirmation(),- }- }- fn english(&self) -> bool {- match self {- Self::Rename(c) => c.english(),- Self::Price(c) => c.english(),- Self::Agent(c) => c.english(),- Self::Check(c) => c.english(),- Self::ModelSave(c) => c.english(),- Self::SubscriptionCheck(c) => c.english(),- }- }- fn message(&self) -> String {- match self {- Self::Rename(c) => c.message(),- Self::Price(c) => c.message(),- Self::Agent(c) => c.message(),- Self::Check(c) => c.message(),- Self::ModelSave(c) => c.message(),- Self::SubscriptionCheck(c) => c.message(),- }- }+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_restore_name(&context, &product_state, input).await}#[tauri::command]pub async fn preview_price_change(@@ -452,25 +281,30 @@ pub async fn preview_price_change(input: PriceEditInput,) -> Result<MutationOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::PriceChange);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview_price(input)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- confirm(- &window,- &state,- ActionOperation::PriceChange,- NativeConfirmation::Price(Box::new(context)),- epoch,- )- .await?- .mutation()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_price_change(&context, &product_state, input).await}#[tauri::command]pub async fn model_reference_query(@@ -479,9 +313,30 @@ pub async fn model_reference_query(input: ModelCatalogQueryV1,) -> Result<ModelCatalogResultV1, DesktopFailure> {main_window(&window)?;- let guard = state.0.lock().await;- let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;- crate::session::query(&session.client, "ShowModel", &input).await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::model_reference_query(&context, &product_state, input).await}#[tauri::command]pub async fn effective_price_query(@@ -490,13 +345,31 @@ pub async fn effective_price_query(input: GetEffectivePricesV2,) -> Result<PriceDisplayResult, DesktopFailure> {main_window(&window)?;- let guard = state.0.lock().await;- let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;- Ok(PriceDisplayResult::new(- crate::session::query(&session.client, "GetEffectivePrices", &input).await?,- ))+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::effective_price_query(&context, &product_state, input).await}-#[tauri::command]pub async fn agent_snapshot(window: WebviewWindow,@@ -504,13 +377,30 @@ pub async fn agent_snapshot(native_targets: Option<Vec<hiroute_domain::AgentNativeTargetV1>>,) -> Result<AgentSnapshot, DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .agent_snapshot_for_targets(native_targets.unwrap_or_default())+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::agent_snapshot(&context, &product_state, native_targets).await}#[tauri::command]@@ -520,14 +410,30 @@ pub async fn retry_agent_settings(input: hiroute_application_api::AgentSettingsRetryV1,) -> Result<Value, DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .retry_agent_settings(input)- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::retry_agent_settings(&context, &product_state, input).await}#[tauri::command]pub async fn preview_agent_settings(@@ -536,45 +442,30 @@ pub async fn preview_agent_settings(input: AgentSettingsInput,) -> Result<AgentOutcome, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentSettings);- action.preview(PreviewPhase::Begin, None);- let prepared = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .preview_agent_settings(input)- .await?;- match prepared {- AgentPreparation::Blocked(preview) => {- action.preview(PreviewPhase::End, None);- action.end(- ActionResult::Failed {- code: EventErrorCode::ActionRequired,- },- None,- );- Ok(AgentOutcome {- preview: *preview,- mutation: None,- })- }- AgentPreparation::Ready(context) => {- action.preview(PreviewPhase::End, Some(context.revision()));- match confirm(- &window,- &state,- ActionOperation::AgentSettings,- NativeConfirmation::Agent(context),- epoch,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,)- .await?- {- NativeOutcome::Agent(value) => Ok(*value),- _ => unreachable!(),- }- }- }+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_agent_settings(&context, &product_state, input).await}#[tauri::command]pub async fn check_agent_authentication(@@ -583,30 +474,32 @@ pub async fn check_agent_authentication(input: AgentCheckInput,) -> Result<bool, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentCheck);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .prepare_agent_check(input)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- match confirm(- &window,- &state,- ActionOperation::AgentCheck,- NativeConfirmation::Check(Box::new(context)),- epoch,- )- .await?- {- NativeOutcome::Check(result) => Ok(result.passed()),- _ => unreachable!(),- }+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_agent_authentication(&context, &product_state, input)+ .await}-#[tauri::command]pub async fn check_agent_live(window: WebviewWindow,@@ -614,197 +507,30 @@ pub async fn check_agent_live(input: AgentCheckInput,) -> Result<AgentCheckCompletion, DesktopFailure> {main_window(&window)?;- if input.scope.as_deref() != Some("live") {- return Err("AGENT_INPUT_INVALID".into());- }- let epoch = state.2.load(Ordering::SeqCst);- let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentCheck);- action.preview(PreviewPhase::Begin, None);- let context = confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .prepare_agent_check(input)- .await?;- action.preview(PreviewPhase::End, Some(context.revision()));- match confirm(- &window,- &state,- ActionOperation::AgentCheck,- NativeConfirmation::Check(Box::new(context)),- epoch,- )- .await?- {- NativeOutcome::Check(result) => Ok(result),- _ => unreachable!(),- }-}--async fn confirm(- window: &WebviewWindow,- state: &DesktopState,- operation: ActionOperation,- context: NativeConfirmation,- epoch: u64,-) -> Result<NativeOutcome, DesktopFailure> {- let action = ActionDiagnostics::begin(&state.3, operation);- if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {- let mut guard = state.0.lock().await;- // Recovery may have installed another Session while this callback waited.- if state.2.load(Ordering::SeqCst) == epoch {- guard- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .invalidate_confirmation();- }- action.confirmation(ConfirmationPhase::Expired, None);- action.end(ActionResult::Stale, None);- return Err("CONFIRMATION_STALE".into());- }- let revision = context.revision();- let accepted = if context.requires_confirmation() {- action.confirmation(ConfirmationPhase::Shown, None);- let english = context.english();- let checking = matches!(&context, NativeConfirmation::Check(_));- let live_checking = matches!(&context, NativeConfirmation::Check(c) if c.is_live());- let title = if live_checking {- if english {- "HiRoute · Verify model access"- } else {- "HiRoute · 验证模型接入"- }- } else if checking {- if english {- "HiRoute · Check compatibility"- } else {- "HiRoute · 检查兼容性"- }- } else if english {- "HiRoute · Confirm change"- } else {- "HiRoute · 确认更改"- };- let confirm_label = if live_checking {- if english {- "Run live check"- } else {- "开始真实验证"- }- } else if checking {- if english {- "Start check"- } else {- "开始检查"- }- } else if let NativeConfirmation::Rename(plan) = &context {- plan.action_label()- } else if english {- "Apply change"- } else {- "应用更改"- };- let accepted = request_web_confirmation(- window,- WebConfirmationPrompt {- title: title.into(),- message: context.message(),- confirm_label: confirm_label.into(),- cancel_label: if english { "Cancel" } else { "取消" }.into(),- },- )- .await;- action.confirmation(ConfirmationPhase::Result, Some(accepted));- accepted- } else {- // This context was freshly validated for an explicit action that needs no extra prompt.- true+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())};- if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {- let mut guard = state.0.lock().await;- if state.2.load(Ordering::SeqCst) == epoch {- guard- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .invalidate_confirmation();- }- action.confirmation(ConfirmationPhase::Expired, None);- action.end(ActionResult::Stale, None);- return Err("CONFIRMATION_STALE".into());- }- action.apply(ApplyPhase::Begin, Some(revision), None);- let outcome = if let NativeConfirmation::SubscriptionCheck(context) = context {- let pending = {- let mut guard = confirmation_session(state, epoch).await?;- guard- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .begin_subscription_check_confirmation(*context, accepted)- .await?- };- // Operation A performs connector I/O. Keep native close/recovery commands responsive while- // it runs so close can submit cancellation rather than waiting behind this command.- let completion = pending.execute().await;- // Completion belongs to the Session that submitted it, not the window's prompt epoch.- // Window close must still release an A resource created after the close-time sweep.- crate::session::complete_subscription_check(&state.0, completion)- .await- .map(Box::new)- .map(NativeOutcome::SubscriptionCheck)- } else if let NativeConfirmation::Check(context) = context {- let dispatch = {- let mut guard = confirmation_session(state, epoch).await?;- guard- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .begin_agent_check(*context, accepted)?- };- match dispatch {- AgentCheckDispatch::Cancelled(result) => Ok(NativeOutcome::Check(result)),- AgentCheckDispatch::Pending(pending) => {- pending.execute().await.map(NativeOutcome::Check)- }- }- } else {- let mut guard = confirmation_session(state, epoch).await?;- let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;- match context {- NativeConfirmation::Agent(context) => session- .finish_agent_confirmation(*context, accepted)- .await- .map(|value| NativeOutcome::Agent(Box::new(value))),- NativeConfirmation::Check(_) => unreachable!(),- NativeConfirmation::Rename(context) => session- .finish_native_confirmation(*context, accepted)- .await- .map(NativeOutcome::Rename),- NativeConfirmation::Price(context) => session- .finish_price_confirmation(*context, accepted)- .await- .map(NativeOutcome::Rename),- NativeConfirmation::ModelSave(context) => session- .finish_model_save_confirmation(*context, accepted)- .await- .map(NativeOutcome::ModelSave),- NativeConfirmation::SubscriptionCheck(_) => unreachable!(),- }+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),};- match &outcome {- Ok(value) => {- let result = value.action_result(accepted);- let token = action.token(value.operation_id());- action.apply(ApplyPhase::End, Some(revision), Some(result));- action.end(result, token);- }- Err(failure) => {- let result = ActionResult::Failed {- code: failure.event_code(),- };- action.apply(ApplyPhase::End, Some(revision), Some(result));- action.end(result, None);- }- }- outcome+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_agent_live(&context, &product_state, input).await}#[tauri::command]pub async fn observe_operation(@@ -812,14 +538,30 @@ pub async fn observe_operation(state: State<'_, DesktopState>,) -> Result<Option<ClientOperationViewV1>, DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .observe()- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::observe_operation(&context, &product_state).await}#[tauri::command]pub async fn stop_observing(@@ -827,14 +569,30 @@ pub async fn stop_observing(state: State<'_, DesktopState>,) -> Result<(), String> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .stop_observing();- Ok(())+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::stop_observing(&context, &product_state).await}/// How the main window may be presented at launch. The window is created hidden; only a/// normal foreground launch shows it, and only after the native launch reason is known.@@ -858,6 +616,11 @@ impl LaunchPresentation {&& !window.is_visible().unwrap_or(false){let _ = window.show();+ // Bare Pilot launches need foreground presentation for WebView polling.+ #[cfg(all(feature = "desktop-pilot", debug_assertions))]+ if std::env::var_os("HIROUTE_DESKTOP_TEST_ROOT").is_some() {+ let _ = window.set_focus();+ }}}}@@ -962,13 +725,15 @@ pub fn run() {.with_file_name("hirouted");#[cfg(unix)]{- Ok(Session::new(crate::bootstrap::Resident::open_resident(- &root,- &binary,- cancelled,- diagnostics,- preacquired,- )?))+ Ok(crate::session_from_resident(+ crate::bootstrap::Resident::open_resident(+ &root,+ &binary,+ cancelled,+ diagnostics,+ preacquired,+ )?,+ ))}#[cfg(not(unix))]{@@ -1141,14 +906,30 @@ pub async fn observation_read(request: hiroute_application_api::ObservationReadRequestV2,) -> Result<serde_json::Value, DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .observation_read(request)- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::observation_read(&context, &product_state, request).await}#[cfg(test)]diff --git a/apps/desktop/src-tauri/src/bridge/classifier.rs b/apps/desktop/src-tauri/src/bridge/classifier.rsindex 4be50d8c..0d41a20c 100644--- a/apps/desktop/src-tauri/src/bridge/classifier.rs+++ b/apps/desktop/src-tauri/src/bridge/classifier.rs@@ -1,6 +1,6 @@+use super::*;use super::{DesktopFailure, DesktopState, main_window};use hiroute_application_api::{ApplyResultV1, ClassifierDecisionTestResultV1};-use hiroute_domain::ComplexityClassifierModeV1;use tauri::{State, WebviewWindow};use tauri_plugin_dialog::DialogExt;@@ -8,19 +8,6 @@ const CLASSIFIER_OPENAPI_FILENAME: &str = "hiroute-decision.openapi.json";const CLASSIFIER_OPENAPI: &str =include_str!("../../../../../decision-extensions/api/decision.openapi.json");-#[derive(serde::Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct ClassifierDecisionTestInput {- classifier: ComplexityClassifierModeV1,-}--#[derive(serde::Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct ClassifierHeaderSecretSaveInput {- secret_id: String,- secret: String,-}-#[derive(serde::Serialize)]#[serde(rename_all = "snake_case")]pub(super) enum ClassifierOpenApiSaveOutcome {@@ -32,82 +19,6 @@ fn write_classifier_openapi(path: &std::path::Path) -> std::io::Result<()> {std::fs::write(path, CLASSIFIER_OPENAPI.as_bytes())}-#[derive(serde::Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct DecisionServiceSaveInput {- change: hiroute_domain::DecisionServiceChangeV1,- secret: Option<String>,-}--#[tauri::command]-pub(super) async fn decision_services(- window: WebviewWindow,- state: State<'_, DesktopState>,-) -> Result<crate::session::DecisionServiceList, DesktopFailure> {- main_window(&window)?;- state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .decision_services()- .await-}--#[tauri::command]-pub(super) async fn save_decision_service(- window: WebviewWindow,- state: State<'_, DesktopState>,- input: DecisionServiceSaveInput,-) -> Result<ApplyResultV1, DesktopFailure> {- main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .save_decision_service(input.change, input.secret.map(zeroize::Zeroizing::new))- .await-}--/// Explicitly invokes the production classifier path with the product-owned-/// synthetic first turn. No real conversation or business model call is made.-#[tauri::command]-pub(super) async fn test_classifier_decision(- window: WebviewWindow,- state: State<'_, DesktopState>,- input: ClassifierDecisionTestInput,-) -> Result<ClassifierDecisionTestResultV1, DesktopFailure> {- main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .test_classifier_decision(input.classifier)- .await-}--#[tauri::command]-pub(super) async fn save_classifier_header_secret(- window: WebviewWindow,- state: State<'_, DesktopState>,- input: ClassifierHeaderSecretSaveInput,-) -> Result<ApplyResultV1, DesktopFailure> {- main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .save_classifier_header_secret(input.secret_id, zeroize::Zeroizing::new(input.secret))- .await-}-#[tauri::command]pub(super) async fn save_classifier_openapi(window: WebviewWindow,@@ -145,3 +56,136 @@ mod tests {assert_eq!(document["openapi"], "3.1.0");}}+#[tauri::command]+pub(super) async fn decision_services(+ window: WebviewWindow,+ state: State<'_, DesktopState>,+) -> Result<crate::session::DecisionServiceList, DesktopFailure> {+ main_window(&window)?;+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::decision_services(&context, &product_state).await+}+#[tauri::command]+pub(super) async fn save_decision_service(+ window: WebviewWindow,+ state: State<'_, DesktopState>,+ input: DecisionServiceSaveInput,+) -> Result<ApplyResultV1, DesktopFailure> {+ main_window(&window)?;+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::save_decision_service(&context, &product_state, input).await+}+#[tauri::command]+pub(super) async fn test_classifier_decision(+ window: WebviewWindow,+ state: State<'_, DesktopState>,+ input: ClassifierDecisionTestInput,+) -> Result<ClassifierDecisionTestResultV1, DesktopFailure> {+ main_window(&window)?;+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::test_classifier_decision(&context, &product_state, input)+ .await+}+#[tauri::command]+pub(super) async fn save_classifier_header_secret(+ window: WebviewWindow,+ state: State<'_, DesktopState>,+ input: ClassifierHeaderSecretSaveInput,+) -> Result<ApplyResultV1, DesktopFailure> {+ main_window(&window)?;+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::save_classifier_header_secret(+ &context,+ &product_state,+ input,+ )+ .await+}diff --git a/apps/desktop/src-tauri/src/bridge/model_connections.rs b/apps/desktop/src-tauri/src/bridge/model_connections.rsindex 81782113..2e26b10d 100644--- a/apps/desktop/src-tauri/src/bridge/model_connections.rs+++ b/apps/desktop/src-tauri/src/bridge/model_connections.rs@@ -1,69 +1,35 @@-use super::{DesktopState, NativeConfirmation, NativeOutcome, confirm, main_window};-use crate::failure::DesktopFailure;-use crate::session::ModelSaveAccepted;-use hiroute_application_api::*;-use hiroute_diagnostics::event::ActionOperation;-use serde::Serialize;-use std::sync::atomic::Ordering;-use tauri::{State, WebviewWindow};--use super::model_connection_web::{- WebComputeCandidateViewV2, WebComputeConnectionApplyRequestV1, WebComputeDiscoveryRefV1,- WebComputeManagementChangeV2, WebComputeSavePreviewV2, WebComputeSaveResultV2,- WebComputeScanResultV2, WebComputeSubscriptionCandidatesV2,- WebComputeSubscriptionCheckResultV2, WebValidationRefV2,-};--#[derive(Serialize)]-pub struct ProtectedModelInputRegistration {- input_candidate: ComputeCandidateRefV2,- #[serde(skip_serializing_if = "Option::is_none")]- key_id: Option<String>,-}--fn erase_envelope<T: Serialize>(- envelope: MachineEnvelopeV2<T>,-) -> Result<MachineEnvelopeV2<serde_json::Value>, DesktopFailure> {- Ok(MachineEnvelopeV2 {- schema_version: envelope.schema_version,- request_id: envelope.request_id,- status: envelope.status,- data: envelope- .data- .map(serde_json::to_value)- .transpose()- .map_err(|_| "RESPONSE_DATA_INVALID")?,- operation: envelope.operation,- warnings: envelope.warnings,- next_actions: envelope.next_actions,- error: envelope.error,- })-}--fn envelope_data<T: Serialize>(envelope: MachineEnvelopeV2<T>) -> Result<T, DesktopFailure> {- if envelope.error.is_some() {- return Err(DesktopFailure::backend(erase_envelope(envelope)?));- }- envelope.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())-}-+use super::*;#[tauri::command]pub async fn compute_subscriptions(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<WebComputeSubscriptionCandidatesV2, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(client.compute_subscriptions(&crate::random_id()?).await?).map(Into::into)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::compute_subscriptions(&context, &product_state).await}-#[tauri::command]pub async fn check_subscription(window: WebviewWindow,@@ -72,42 +38,37 @@ pub async fn check_subscription(language: String,) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(Ordering::SeqCst);- let (client, close_requested) = {- let mut guard = super::confirmation_session(&state, epoch).await?;- let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;- let close_requested = session.resume_subscription_interaction();- (session.client.clone(), close_requested)- };- let preview = envelope_data(- client- .preview_subscription_check(&crate::random_id()?, candidate)- .await?,- )?;- let context = super::confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .prepare_subscription_check_confirmation(- preview,- language,- crate::random_id()?,- close_requested,- )?;- match confirm(- &window,- &state,- ActionOperation::SubscriptionCheck,- NativeConfirmation::SubscriptionCheck(Box::new(context)),- epoch,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_subscription(+ &context,+ &product_state,+ candidate,+ language,)- .await?- {- NativeOutcome::SubscriptionCheck(result) => Ok((*result).into()),- _ => unreachable!(),- }+ .await}-#[tauri::command]pub async fn get_subscription_check_result(window: WebviewWindow,@@ -115,55 +76,98 @@ pub async fn get_subscription_check_result(operation: OperationReferenceV1,) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(- client- .subscription_check_result(&crate::random_id()?, operation.operation_id)- .await?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::get_subscription_check_result(+ &context,+ &product_state,+ operation,)- .map(Into::into)+ .await}-#[tauri::command]pub async fn recover_subscription_check(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<Option<WebComputeSubscriptionCheckResultV2>, DesktopFailure> {main_window(&window)?;- let result = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .recover_subscription_check()- .await?;- Ok(result.map(Into::into))+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::recover_subscription_check(&context, &product_state).await}-#[tauri::command]pub async fn close_subscription_check(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<(), DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .close_subscription_check()- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::close_subscription_check(&context, &product_state).await}-#[tauri::command]pub async fn release_subscription_check(window: WebviewWindow,@@ -171,17 +175,36 @@ pub async fn release_subscription_check(validation: WebValidationRefV2,) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {main_window(&window)?;- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .release_subscription_validation(validation.try_into().map_err(DesktopFailure::from)?)- .await- .map(Into::into)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::release_subscription_check(+ &context,+ &product_state,+ validation,+ )+ .await}-#[tauri::command]pub async fn compute_key_masks(window: WebviewWindow,@@ -189,41 +212,62 @@ pub async fn compute_key_masks(query: ComputeKeyMasksQueryV1,) -> Result<ComputeKeyMasksViewV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- crate::session::query(&client, GET_COMPUTE_KEY_MASKS_OPERATION_V1, &query).await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::compute_key_masks(&context, &product_state, query).await}-#[tauri::command]pub async fn compute_management_snapshot(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<ComputeManagementSnapshotV3, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(- client- .compute_management_snapshot_v3(- &crate::random_id()?,- ComputeManagementQueryV2::default(),+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,)- .await?,- )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::compute_management_snapshot(&context, &product_state).await}-#[tauri::command]pub async fn compute_scan(window: WebviewWindow,@@ -231,28 +275,31 @@ pub async fn compute_scan(native_target: Option<hiroute_domain::AgentNativeTargetV1>,) -> Result<WebComputeScanResultV2, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(- client- .scan_compute_points(- &crate::random_id()?,- ComputeScanRequestV2 {- schema: COMPUTE_SCAN_REQUEST_SCHEMA_V2.into(),- native_target,- },+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,)- .await?,- )- .map(Into::into)+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::compute_scan(&context, &product_state, native_target).await}-#[tauri::command]pub async fn prepare_discovered_model_connection(window: WebviewWindow,@@ -260,74 +307,67 @@ pub async fn prepare_discovered_model_connection(discovery: WebComputeDiscoveryRefV1,) -> Result<WebComputeCandidateViewV2, DesktopFailure> {main_window(&window)?;- let discovery: ComputeDiscoveryRefV1 = discovery.try_into().map_err(DesktopFailure::from)?;- let digest_suffix = discovery- .discovery_ref- .strip_prefix("discovery/")- .ok_or("REQUEST_INVALID")?;- let request = PrepareDiscoveredModelConnectionRequestV1 {- prepare_id: format!("desktop/{digest_suffix}"),- discovery,- };- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let status: ClientServiceStatusV1 =- crate::session::query(&client, "GetClientServiceStatus", &ClientEmptyRequestV1 {}).await?;- let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]- let capability = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_discovered_model_prepare(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> = return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());- envelope_data(- client- .prepare_discovered_model_connection(- &crate::random_id()?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",request,- ProtectedClientGrantV2 {- principal_kind: PrincipalKind::Desktop,- capability: capability.to_string(),- },)- .await?,+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::prepare_discovered_model_connection(+ &context,+ &product_state,+ discovery,)- .map(Into::into)+ .await}-#[tauri::command]pub async fn compute_connection_options(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<ComputeConnectionOptionsResultV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- crate::session::query(- &client,- "ListConnectionOptions",- &ComputeConnectionOptionsRequestV1 { candidate: None },- )- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::compute_connection_options(&context, &product_state).await}-#[tauri::command]pub async fn register_protected_model_input(window: WebviewWindow,@@ -336,33 +376,37 @@ pub async fn register_protected_model_input(source_id: Option<String>,) -> Result<ProtectedModelInputRegistration, DesktopFailure> {main_window(&window)?;- #[cfg(unix)]- {- let candidate = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_model_input(zeroize::Zeroizing::new(secret))?;- let key_id = source_id- .as_deref()- .map(|source| hiroute_domain::managed_key_id(source, &candidate.candidate_ref))- .transpose()- .map_err(|_| "CREDENTIAL_INPUT_INVALID")?;- Ok(ProtectedModelInputRegistration {- input_candidate: candidate,- key_id,- })- }- #[cfg(not(unix))]- {- let _ = (state, secret, source_id);- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::register_protected_model_input(+ &context,+ &product_state,+ secret,+ source_id,+ )+ .await}-#[tauri::command]pub async fn release_protected_model_input(window: WebviewWindow,@@ -370,25 +414,36 @@ pub async fn release_protected_model_input(input: ComputeCandidateRefV2,) -> Result<(), DesktopFailure> {main_window(&window)?;- #[cfg(unix)]- {- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .release_model_input(&input)- .map_err(Into::into)- }- #[cfg(not(unix))]- {- let _ = (state, input);- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::release_protected_model_input(+ &context,+ &product_state,+ input,+ )+ .await}-#[tauri::command]pub async fn check_model_connection(window: WebviewWindow,@@ -396,46 +451,32 @@ pub async fn check_model_connection(request: NativeModelConnectionCheckRequestV1,) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let status: ClientServiceStatusV1 = crate::session::query(- &client,- "GetClientServiceStatus",- &hiroute_application_api::ClientEmptyRequestV1 {},- )- .await?;- let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]- let capability = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_model_check(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> = return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());- envelope_data(- client- .check_native_model_connection(- &crate::random_id()?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",request,- ProtectedClientGrantV2 {- principal_kind: PrincipalKind::Desktop,- capability: capability.to_string(),- },)- .await?,- )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_model_connection(&context, &product_state, request)+ .await}-#[tauri::command]pub async fn check_saved_model_connection(window: WebviewWindow,@@ -443,46 +484,36 @@ pub async fn check_saved_model_connection(request: SavedModelConnectionCheckRequestV1,) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let status: ClientServiceStatusV1 = crate::session::query(- &client,- "GetClientServiceStatus",- &hiroute_application_api::ClientEmptyRequestV1 {},- )- .await?;- let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]- let capability = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_saved_model_check(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> = return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());- envelope_data(- client- .check_saved_model_connection(- &crate::random_id()?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",request,- ProtectedClientGrantV2 {- principal_kind: PrincipalKind::Desktop,- capability: capability.to_string(),- },)- .await?,+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_saved_model_connection(+ &context,+ &product_state,+ request,)+ .await}-#[tauri::command]pub async fn check_registered_model_connection(window: WebviewWindow,@@ -490,49 +521,36 @@ pub async fn check_registered_model_connection(request: RegisteredModelConnectionCheckRequestV1,) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {main_window(&window)?;- if request.display_name.is_none() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let status: ClientServiceStatusV1 = crate::session::query(- &client,- "GetClientServiceStatus",- &hiroute_application_api::ClientEmptyRequestV1 {},- )- .await?;- let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]- let capability = state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_registered_model_check(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> = return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());- envelope_data(- client- .check_registered_model_connection(- &crate::random_id()?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",request,- ProtectedClientGrantV2 {- principal_kind: PrincipalKind::Desktop,- capability: capability.to_string(),- },)- .await?,+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::check_registered_model_connection(+ &context,+ &product_state,+ request,)+ .await}-#[tauri::command]pub async fn cancel_model_connection_check(window: WebviewWindow,@@ -540,21 +558,36 @@ pub async fn cancel_model_connection_check(check_id: String,) -> Result<(), DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(- client- .cancel_native_model_connection_check(&crate::random_id()?, check_id)- .await?,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::cancel_model_connection_check(+ &context,+ &product_state,+ check_id,)+ .await}-#[tauri::command]pub async fn preview_compute_save(window: WebviewWindow,@@ -562,23 +595,31 @@ pub async fn preview_compute_save(change: WebComputeManagementChangeV2,) -> Result<WebComputeSavePreviewV2, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let change = change.try_into().map_err(DesktopFailure::from)?;- let preview = envelope_data(- client- .preview_compute_save(&crate::random_id()?, change)- .await?,- )?;- preview.try_into().map_err(DesktopFailure::from)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::preview_compute_save(&context, &product_state, change).await}-#[tauri::command]pub async fn apply_compute_save(window: WebviewWindow,@@ -587,29 +628,37 @@ pub async fn apply_compute_save(language: String,) -> Result<ModelSaveAccepted, DesktopFailure> {main_window(&window)?;- let request: ComputeConnectionApplyRequestV1 =- request.try_into().map_err(DesktopFailure::from)?;- let epoch = state.2.load(Ordering::SeqCst);- let context = super::confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .prepare_model_save_confirmation(request, language)- .await?;- match confirm(- &window,- &state,- ActionOperation::ModelSave,- NativeConfirmation::ModelSave(Box::new(context)),- epoch,+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::apply_compute_save(+ &context,+ &product_state,+ request,+ language,)- .await?- {- NativeOutcome::ModelSave(value) => Ok(value),- _ => unreachable!(),- }+ .await}-#[tauri::command]pub async fn get_compute_save_result(window: WebviewWindow,@@ -617,18 +666,29 @@ pub async fn get_compute_save_result(operation: OperationReferenceV1,) -> Result<WebComputeSaveResultV2, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::get_compute_save_result(&context, &product_state, operation).await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- envelope_data(- client- .get_compute_save_result(&crate::random_id()?, operation)- .await?,- )- .map(Into::into)}diff --git a/apps/desktop/src-tauri/src/bridge/observation.rs b/apps/desktop/src-tauri/src/bridge/observation.rsindex 8a87a454..0b00a78d 100644--- a/apps/desktop/src-tauri/src/bridge/observation.rs+++ b/apps/desktop/src-tauri/src/bridge/observation.rs@@ -1,17 +1,4 @@-use super::web_confirmation::{WebConfirmationPrompt, request_web_confirmation};-use super::{DesktopFailure, DesktopState, main_window};-use std::sync::atomic::Ordering;-use tauri::{State, WebviewWindow};--#[derive(serde::Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct ObservationDeleteInput {- session_id: String,- data_class: hiroute_application_api::DeletionDataClass,- #[serde(default)]- language: Option<String>,-}-+use super::*;#[tauri::command]pub(super) async fn observation_delete(window: WebviewWindow,@@ -19,100 +6,28 @@ pub(super) async fn observation_delete(input: ObservationDeleteInput,) -> Result<serde_json::Value, DesktopFailure> {main_window(&window)?;- #[cfg(unix)]- {- let epoch = state.2.load(Ordering::SeqCst);- let spec = hiroute_application_api::SessionDeletionSpecV1 {- workspace_id: hiroute_domain::WorkspaceId::default(),- session_id: hiroute_domain::SessionId::parse(input.session_id)- .map_err(|_| "SESSION_INVALID")?,- data_class: input.data_class,- delete_rollups: false,- };- let preview = super::confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .deletion_preview(spec)- .await?;- let task_refs: u64 = preview- .managed_scopes- .iter()- .map(|scope| scope.reference_count)- .sum();- let english = input.language.as_deref() == Some("en");- let (title, message, confirm, cancel) = localized_confirmation(- english,- &preview.session.spec.data_class,- preview.session.requests,- preview.session.content_instances,- task_refs,- );- if !request_web_confirmation(- &window,- WebConfirmationPrompt {- title: title.into(),- message,- confirm_label: confirm.into(),- cancel_label: cancel.into(),- },- )- .await- {- return Ok(serde_json::json!({"cancelled":true}));- }- if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {- return Err("CONFIRMATION_STALE".into());- }- let outcome = super::confirmation_session(&state, epoch)- .await?- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .deletion_apply(preview)- .await?;- serde_json::to_value(outcome).map_err(|_| "RESPONSE_DATA_INVALID".into())- }- #[cfg(not(unix))]- {- let _ = (state, input);- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }-}--fn localized_confirmation(- english: bool,- data_class: &hiroute_application_api::DeletionDataClass,- requests: u64,- content_instances: u64,- task_refs: u64,-) -> (&'static str, String, &'static str, &'static str) {- if english {- let scope = if *data_class == hiroute_application_api::DeletionDataClass::ContentOnly {- "This removes prompts, answers and tool content while keeping the run record."- } else {- "This removes the session and its per-request records."- };- (- "HiRoute · Clear this session",- format!(- "{scope}\n\nAffected: {requests} requests, {content_instances} content items and {task_refs} linked task content items.\n\nThis affects only this session and cannot be undone. Your working folders will not be deleted."- ),- "Clear session",- "Cancel",- )- } else {- let scope = if *data_class == hiroute_application_api::DeletionDataClass::ContentOnly {- "将清理问题、回答和工具内容,保留运行记录。"- } else {- "将删除这条会话及其逐请求记录。"- };- (- "HiRoute · 清理此会话",- format!(- "{scope}\n\n影响范围:{requests} 个请求、{content_instances} 段会话正文、{task_refs} 条关联任务正文。\n\n只影响这条会话且不可撤销;不会删除工作目录。"- ),- "确认清理",- "取消",- )- }+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::observation_delete(&context, &product_state, input).await}diff --git a/apps/desktop/src-tauri/src/bridge/subscription_login.rs b/apps/desktop/src-tauri/src/bridge/subscription_login.rsindex 45865740..4687f135 100644--- a/apps/desktop/src-tauri/src/bridge/subscription_login.rs+++ b/apps/desktop/src-tauri/src/bridge/subscription_login.rs@@ -1,21 +1,4 @@-//! Independent sign-in management. Callback material never enters ordinary Local Control JSON.--use super::{DesktopState, main_window};-use crate::failure::DesktopFailure;-use hiroute_application_api::*;-use tauri::{State, WebviewWindow};--fn login_data(- envelope: MachineEnvelopeV2<ComputeSubscriptionLoginResultV1>,-) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {- // The login backend projects only closed reason codes. Do not forward raw OAuth errors or- // serialize an unexpected envelope, which could accidentally expose an authorization URL.- if envelope.error.is_some() {- return Err("SUBSCRIPTION_LOGIN_UNAVAILABLE".into());- }- envelope.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())-}-+use super::*;#[tauri::command]pub async fn manage_subscription_login(window: WebviewWindow,@@ -23,24 +6,32 @@ pub async fn manage_subscription_login(request: ComputeSubscriptionLoginRequestV1,) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {main_window(&window)?;- if !request.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::manage_subscription_login(&context, &product_state, request).await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- login_data(- client- .manage_subscription_login(&crate::random_id()?, request)- .await?,- )}-#[tauri::command]pub async fn submit_subscription_login_callback(window: WebviewWindow,@@ -48,64 +39,35 @@ pub async fn submit_subscription_login_callback(login_ref: String,callback: String,) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {- let callback = zeroize::Zeroizing::new(callback);main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let status = login_data(- client- .manage_subscription_login(- &crate::random_id()?,- ComputeSubscriptionLoginRequestV1::Status {- login_ref: login_ref.clone(),- },+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,)- .await?,- )?;- let session = status- .sessions- .into_iter()- .find(|session| session.login_ref == login_ref)- .ok_or("SUBSCRIPTION_LOGIN_STALE")?;- if session.status != SubscriptionLoginStatusV1::Pending {- return Err("SUBSCRIPTION_LOGIN_STALE".into());- }- let input_candidate = session- .callback_input_candidate- .ok_or("SUBSCRIPTION_LOGIN_STALE")?;- let callback_request_id = crate::random_id()?;- #[cfg(unix)]- state- .0- .lock()- .await- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .resident- .register_subscription_callback_input(&input_candidate, callback)?;- #[cfg(not(unix))]- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());-- let response = client- .manage_subscription_login(- &callback_request_id,- ComputeSubscriptionLoginRequestV1::Callback {- login_ref,- input_candidate: input_candidate.clone(),- },- )- .await;- // Release even after an uncertain response: a consumed input is already gone, and an- // unconsumed callback must not remain available to an unrelated later operation.- #[cfg(unix)]- if let Some(session) = state.0.lock().await.as_mut() {- session.resident.release_model_input(&input_candidate)?;- }- login_data(response?)+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::submit_subscription_login_callback(+ &context,+ &product_state,+ login_ref,+ callback,+ )+ .await}diff --git a/apps/desktop/src-tauri/src/bridge/web_confirmation.rs b/apps/desktop/src-tauri/src/bridge/web_confirmation.rsindex 7769d81d..8db62ad2 100644--- a/apps/desktop/src-tauri/src/bridge/web_confirmation.rs+++ b/apps/desktop/src-tauri/src/bridge/web_confirmation.rs@@ -1,212 +1,20 @@use super::{DesktopFailure, main_window};-use crate::confirmation::CONFIRMATION_TTL;-use serde::{Deserialize, Serialize};-use std::collections::BTreeMap;-use std::sync::Mutex;-use std::sync::atomic::{AtomicU64, Ordering};-use tauri::{Emitter, EventTarget, Manager, State, WebviewWindow};-use tokio::sync::oneshot;--pub(super) const WEB_CONFIRMATION_EVENT: &str = "hiroute-web-confirmation";-const WEB_CONFIRMATION_SCHEMA: &str = "hiroute.web-confirmation/v1";+use std::sync::atomic::Ordering;+use tauri::{Manager, State, WebviewWindow};pub(crate) fn expire_window_confirmations(app: &tauri::AppHandle, window_label: &str) {app.state::<super::DesktopState>().2.fetch_add(1, Ordering::SeqCst);app.state::<WebConfirmationState>()- .cancel_window(window_label);+ .cancel_context(window_label);app.state::<super::WorkerDependencyConfirmationState>().cancel_window(window_label);}-pub(super) struct WebConfirmationPrompt {- pub title: String,- pub message: String,- pub confirm_label: String,- pub cancel_label: String,-}--#[derive(Clone, Debug, Eq, PartialEq, Serialize)]-pub(super) struct WebConfirmationRequest {- schema: &'static str,- confirmation_id: String,- title: String,- message: String,- confirm_label: String,- cancel_label: String,-}--#[derive(Debug, Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct WebConfirmationDecision {- confirmation_id: String,- accepted: bool,-}--struct PendingConfirmation {- window_label: String,- request: WebConfirmationRequest,- sequence: u64,- response: oneshot::Sender<bool>,-}--#[derive(Default)]-pub(super) struct WebConfirmationState {- pending: Mutex<BTreeMap<String, PendingConfirmation>>,- next_sequence: AtomicU64,-}--impl WebConfirmationState {- fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, PendingConfirmation>> {- self.pending- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- }-- fn begin(- &self,- window_label: &str,- prompt: WebConfirmationPrompt,- ) -> Result<(WebConfirmationRequest, oneshot::Receiver<bool>), DesktopFailure> {- let (response, receive) = oneshot::channel();- let mut pending = self.lock();- let sequence = self- .next_sequence- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {- value.checked_add(1)- })- .map_err(|_| DesktopFailure::from("CONFIRMATION_UNAVAILABLE"))?;- let confirmation_id = loop {- let candidate = format!("confirmation/{}", crate::random_id()?);- if !pending.contains_key(&candidate) {- break candidate;- }- };- let request = WebConfirmationRequest {- schema: WEB_CONFIRMATION_SCHEMA,- confirmation_id: confirmation_id.clone(),- title: prompt.title,- message: prompt.message,- confirm_label: prompt.confirm_label,- cancel_label: prompt.cancel_label,- };- pending.insert(- confirmation_id.clone(),- PendingConfirmation {- window_label: window_label.to_owned(),- request: request.clone(),- sequence,- response,- },- );- Ok((request, receive))- }-- fn snapshot(&self, window_label: &str) -> Option<WebConfirmationRequest> {- self.lock()- .values()- .filter(|pending| pending.window_label == window_label)- .min_by_key(|pending| pending.sequence)- .map(|pending| pending.request.clone())- }-- fn resolve(- &self,- window_label: &str,- confirmation_id: &str,- accepted: bool,- ) -> Result<(), DesktopFailure> {- if !valid_confirmation_id(confirmation_id) {- return Err("CONFIRMATION_STALE".into());- }- let pending = {- let mut confirmations = self.lock();- if confirmations- .get(confirmation_id)- .is_none_or(|pending| pending.window_label != window_label)- {- return Err("CONFIRMATION_STALE".into());- }- confirmations- .remove(confirmation_id)- .expect("matching confirmation exists")- };- pending- .response- .send(accepted)- .map_err(|_| DesktopFailure::from("CONFIRMATION_STALE"))- }-- fn cancel(&self, window_label: &str, confirmation_id: &str) {- let pending = {- let mut confirmations = self.lock();- if confirmations- .get(confirmation_id)- .is_some_and(|pending| pending.window_label == window_label)- {- confirmations.remove(confirmation_id)- } else {- None- }- };- if let Some(pending) = pending {- let _ = pending.response.send(false);- }- }-- pub(super) fn cancel_window(&self, window_label: &str) {- let pending = {- let mut confirmations = self.lock();- let ids = confirmations- .iter()- .filter(|(_, pending)| pending.window_label == window_label)- .map(|(id, _)| id.clone())- .collect::<Vec<_>>();- ids.into_iter()- .filter_map(|id| confirmations.remove(&id))- .collect::<Vec<_>>()- };- for pending in pending {- let _ = pending.response.send(false);- }- }-}--fn valid_confirmation_id(value: &str) -> bool {- value.strip_prefix("confirmation/").is_some_and(|id| {- id.len() == 64- && id- .bytes()- .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())- })-}--pub(super) async fn request_web_confirmation(- window: &WebviewWindow,- prompt: WebConfirmationPrompt,-) -> bool {- let state = window.state::<WebConfirmationState>();- let Ok((request, receive)) = state.begin(window.label(), prompt) else {- return false;- };- let confirmation_id = request.confirmation_id.clone();- if window- .emit_to(- EventTarget::webview(window.label()),- WEB_CONFIRMATION_EVENT,- request,- )- .is_err()- {- state.cancel(window.label(), &confirmation_id);- }- let decision = tokio::time::timeout(CONFIRMATION_TTL, receive).await;- if decision.is_err() {- state.cancel(window.label(), &confirmation_id);- }- decision.ok().and_then(Result::ok).unwrap_or(false)-}+pub use hiroute_product_session::web_confirmation::{+ ConfirmationBroker as WebConfirmationState, WebConfirmationDecision, WebConfirmationRequest,+};#[tauri::command]pub(super) async fn web_confirmation_snapshot(@@ -226,82 +34,3 @@ pub(super) async fn resolve_web_confirmation(main_window(&window)?;state.resolve(window.label(), &input.confirmation_id, input.accepted)}--#[cfg(test)]-mod tests {- use super::*;-- fn prompt(title: &str) -> WebConfirmationPrompt {- WebConfirmationPrompt {- title: title.to_owned(),- message: "Apply the verified change.".to_owned(),- confirm_label: "Apply change".to_owned(),- cancel_label: "Cancel".to_owned(),- }- }-- #[tokio::test]- async fn exact_window_and_id_resolve_each_confirmation_once() {- let state = WebConfirmationState::default();- let (request, receive) = state.begin("main", prompt("First")).unwrap();- let id = request.confirmation_id;- assert!(id.starts_with("confirmation/"));- assert_eq!(id.len(), "confirmation/".len() + 64);- assert!(state.resolve("other", &id, true).is_err());- state.resolve("main", &id, true).unwrap();- assert!(receive.await.unwrap());- assert!(state.resolve("main", &id, true).is_err());- }-- #[tokio::test]- async fn closing_one_window_denies_only_its_pending_confirmations() {- let state = WebConfirmationState::default();- let (_, main_one) = state.begin("main", prompt("Main one")).unwrap();- let (_, main_two) = state.begin("main", prompt("Main two")).unwrap();- let (other_request, other) = state.begin("other", prompt("Other")).unwrap();- state.cancel_window("main");- assert!(!main_one.await.unwrap());- assert!(!main_two.await.unwrap());- state- .resolve("other", &other_request.confirmation_id, true)- .unwrap();- assert!(other.await.unwrap());- }-- #[test]- fn snapshot_returns_only_the_oldest_confirmation_for_the_exact_window() {- let state = WebConfirmationState::default();- let (first, _) = state.begin("main", prompt("First")).unwrap();- let (_, _) = state.begin("other", prompt("Other")).unwrap();- let (_, _) = state.begin("main", prompt("Second")).unwrap();- assert_eq!(state.snapshot("main"), Some(first));- assert!(state.snapshot("missing").is_none());- }-- #[test]- fn decision_rejects_unknown_fields() {- let value = serde_json::json!({- "confirmation_id": format!("confirmation/{}", "0".repeat(64)),- "accepted": true,- "injected": "not accepted"- });- assert!(serde_json::from_value::<WebConfirmationDecision>(value).is_err());- }-- #[test]- fn confirmation_ids_are_exact_lowercase_random_tokens() {- assert!(valid_confirmation_id(&format!(- "confirmation/{}",- "0a".repeat(32)- )));- assert!(!valid_confirmation_id("confirmation/1"));- assert!(!valid_confirmation_id(&format!(- "confirmation/{}",- "A0".repeat(32)- )));- assert!(!valid_confirmation_id(&format!(- "other/{}",- "00".repeat(32)- )));- }-}diff --git a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs b/apps/desktop/src-tauri/src/bridge/worker_tasks.rsindex c70d59f2..dc61712f 100644--- a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs+++ b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs@@ -1,268 +1,35 @@-use super::{DesktopState, main_window};-use crate::failure::DesktopFailure;-use hiroute_application_api::{- DelegationAcceptedV1, DelegationCancelV1, DelegationGetV1, DelegationListV1,- DelegationResultV1, DelegationRunViewV1, DelegationWaitV1, MachineEnvelopeV2, WorkPlanListV1,- WorkerCancelRequestV1, WorkerContinueRequestV1, WorkerDependenciesDiscoverRequestV1,- WorkerDependenciesSelectRequestV1, WorkerDependenciesViewV1, WorkerExecutorAvailabilityListV1,- WorkerListRequestV1, WorkerPlansRequestV1, WorkerReadDataV1, WorkerReadRequestV1,- WorkerResidualConfirmRequestV1, WorkerResultRequestV1, WorkerSettingsV1, WorkerStatusRequestV1,- WorkerWaitRequestV1,-};-use serde::{Deserialize, Serialize, de::DeserializeOwned};-use std::collections::BTreeMap;-use std::fs;-use std::path::{Path, PathBuf};-use std::sync::Mutex;-use tauri::{State, WebviewWindow};--const WORKER_DEPENDENCY_CONFIRMATION_SCHEMA_V1: &str =- "hiroute.worker-dependency-selection-confirmation/v1";-const WORKER_DEPENDENCY_CONFIRMATION_TTL_MS: u64 = 60_000;--#[derive(Clone, Debug, Serialize)]-pub(super) struct WorkerDependencyConfirmationV1 {- schema: &'static str,- confirmation_id: String,- selection: WorkerDependenciesSelectRequestV1,- expires_at_ms: u64,-}--#[derive(Debug, Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct WorkerDependencyConfirmationInput {- confirmation_id: String,-}--#[derive(Clone)]-struct PendingWorkerDependencyConfirmation {- window_label: String,- selection: WorkerDependenciesSelectRequestV1,- expires_at_ms: u64,-}--#[derive(Default)]-pub(super) struct WorkerDependencyConfirmationState {- pending: Mutex<BTreeMap<String, PendingWorkerDependencyConfirmation>>,-}--impl WorkerDependencyConfirmationState {- fn lock(- &self,- ) -> std::sync::MutexGuard<'_, BTreeMap<String, PendingWorkerDependencyConfirmation>> {- self.pending- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- }-- fn prepare(- &self,- window_label: &str,- selection: WorkerDependenciesSelectRequestV1,- now_ms: u64,- ) -> Result<WorkerDependencyConfirmationV1, DesktopFailure> {- let expires_at_ms = now_ms- .checked_add(WORKER_DEPENDENCY_CONFIRMATION_TTL_MS)- .ok_or("CLOCK_UNAVAILABLE")?;- let confirmation_id = format!("worker-dependency-confirmation/{}", crate::random_id()?);- let mut pending = self.lock();- pending.retain(|_, entry| entry.window_label != window_label);- pending.insert(- confirmation_id.clone(),- PendingWorkerDependencyConfirmation {- window_label: window_label.to_owned(),- selection: selection.clone(),- expires_at_ms,- },- );- Ok(WorkerDependencyConfirmationV1 {- schema: WORKER_DEPENDENCY_CONFIRMATION_SCHEMA_V1,- confirmation_id,- selection,- expires_at_ms,- })- }-- fn take(- &self,- window_label: &str,- confirmation_id: &str,- now_ms: u64,- ) -> Result<WorkerDependenciesSelectRequestV1, DesktopFailure> {- if !valid_worker_dependency_confirmation_id(confirmation_id) {- return Err("CONFIRMATION_STALE".into());- }- let entry = {- let mut pending = self.lock();- if pending- .get(confirmation_id)- .is_none_or(|entry| entry.window_label != window_label)- {- return Err("CONFIRMATION_STALE".into());- }- pending- .remove(confirmation_id)- .expect("matching Worker dependency confirmation exists")- };- if now_ms > entry.expires_at_ms {- return Err("CONFIRMATION_EXPIRED".into());- }- Ok(entry.selection)- }-- fn cancel(&self, window_label: &str, confirmation_id: &str) -> Result<(), DesktopFailure> {- if !valid_worker_dependency_confirmation_id(confirmation_id) {- return Err("CONFIRMATION_STALE".into());- }- let mut pending = self.lock();- if pending- .get(confirmation_id)- .is_some_and(|entry| entry.window_label != window_label)- {- return Err("CONFIRMATION_STALE".into());- }- pending.remove(confirmation_id);- Ok(())- }-- pub(super) fn cancel_window(&self, window_label: &str) {- self.lock()- .retain(|_, entry| entry.window_label != window_label);- }-}--fn valid_worker_dependency_confirmation_id(value: &str) -> bool {- value- .strip_prefix("worker-dependency-confirmation/")- .is_some_and(|id| {- id.len() == 64- && id- .bytes()- .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())- })-}--fn now_ms() -> Result<u64, DesktopFailure> {- Ok(std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map_err(|_| "CLOCK_UNAVAILABLE")?- .as_millis()- .try_into()- .map_err(|_| "CLOCK_UNAVAILABLE")?)-}--fn normalize_worker_dependency_selection(- request: &WorkerDependenciesSelectRequestV1,-) -> Result<WorkerDependenciesSelectRequestV1, DesktopFailure> {- if !request.valid() {- return Err("REQUEST_INVALID".into());- }- // The shared launch form requires adapters for Codex/Claude and forbids them for- // native ACP clients. Only normalize components that the validated shape contains.- let adapter = request- .adapter_path- .as_deref()- .map(|path| normalize_required_path(Path::new(path), request.node_path.is_none()))- .transpose()?;- let cli = normalize_required_path(Path::new(&request.cli_path), true)?;- let node = request- .node_path- .as_deref()- .map(|path| normalize_required_path(Path::new(path), true))- .transpose()?;- let normalized = WorkerDependenciesSelectRequestV1 {- harness: request.harness,- adapter_path: adapter.map(normalized_path_string).transpose()?,- cli_path: normalized_path_string(cli)?,- node_path: node.map(normalized_path_string).transpose()?,- expected_selection_revision: request.expected_selection_revision,- };- hiroute_application_api::plan_worker_dependency_selection(&normalized)- .ok_or("REQUEST_INVALID")?;- Ok(normalized)-}--fn normalize_required_path(- path: &Path,- require_executable: bool,-) -> Result<PathBuf, DesktopFailure> {- let canonical = match fs::canonicalize(path) {- Ok(path) => path,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- return Err("WORKER_DEPENDENCIES_MISSING".into());- }- Err(_) => return Err("WORKER_DEPENDENCIES_UNAVAILABLE".into()),- };- let metadata = fs::metadata(&canonical).map_err(|_| "WORKER_DEPENDENCIES_UNAVAILABLE")?;- if !metadata.is_file()- || (require_executable && !path_is_executable(&metadata))- || (!require_executable && fs::File::open(&canonical).is_err())- {- return Err("WORKER_DEPENDENCIES_INVALID".into());- }- Ok(canonical)-}--fn normalized_path_string(path: PathBuf) -> Result<String, DesktopFailure> {- path.into_os_string()- .into_string()- .ok()- .filter(|value| {- !value.is_empty()- && value.len() <= 4096- && !value.contains(char::is_control)- && Path::new(value).is_absolute()- })- .ok_or_else(|| "WORKER_DEPENDENCIES_INVALID".into())-}--fn path_is_executable(metadata: &fs::Metadata) -> bool {- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- metadata.permissions().mode() & 0o111 != 0- }- #[cfg(not(unix))]- {- metadata.is_file()- }-}--fn data<R>(envelope: MachineEnvelopeV2<R>) -> Result<R, DesktopFailure>-where- R: DeserializeOwned + Serialize,-{- if envelope.error.is_some() {- let encoded = serde_json::to_value(envelope).map_err(|_| "RESPONSE_DATA_INVALID")?;- let untyped = serde_json::from_value(encoded).map_err(|_| "RESPONSE_DATA_INVALID")?;- return Err(DesktopFailure::backend(untyped));- }- envelope- .data- .ok_or_else(|| DesktopFailure::from("RESPONSE_DATA_MISSING"))-}-+use super::*;#[tauri::command]pub async fn worker_settings_get(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<WorkerSettingsV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let result = data(client.worker_settings(&crate::random_id()?).await?)?;- if !result.valid() {- return Err("RESPONSE_DATA_INVALID".into());- }- Ok(result)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_settings_get(&context, &product_state).await}-#[tauri::command]pub async fn worker_settings_set(window: WebviewWindow,@@ -270,53 +37,62 @@ pub async fn worker_settings_set(input: WorkerSettingsV1,) -> Result<WorkerSettingsV1, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let result = data(- client- .set_worker_settings(&crate::random_id()?, &input)- .await?,- )?;- if !result.valid() {- return Err("RESPONSE_DATA_INVALID".into());- }- Ok(result)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_settings_set(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_executor_availability(window: WebviewWindow,state: State<'_, DesktopState>,) -> Result<WorkerExecutorAvailabilityListV1, DesktopFailure> {main_window(&window)?;- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- let result = data(- client- .worker_executor_availability(&crate::random_id()?)- .await?,- )?;- if !result.valid() {- return Err("RESPONSE_DATA_INVALID".into());- }- Ok(result)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_executor_availability(&context, &product_state).await}-#[tauri::command]pub async fn worker_task_plans(window: WebviewWindow,@@ -324,20 +100,31 @@ pub async fn worker_task_plans(input: WorkerPlansRequestV1,) -> Result<MachineEnvelopeV2<WorkPlanListV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_plans(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_plans(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_dependencies_discover(window: WebviewWindow,@@ -345,22 +132,32 @@ pub async fn worker_dependencies_discover(input: WorkerDependenciesDiscoverRequestV1,) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_dependencies_discover(&context, &product_state, input).await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client- .worker_dependencies_discover(&crate::random_id()?, &input)- .await?)}-#[tauri::command]pub async fn worker_dependencies_select_prepare(window: WebviewWindow,@@ -369,13 +166,37 @@ pub async fn worker_dependencies_select_prepare(input: WorkerDependenciesSelectRequestV1,) -> Result<WorkerDependencyConfirmationV1, DesktopFailure> {main_window(&window)?;- let epoch = desktop.2.load(std::sync::atomic::Ordering::SeqCst);- let session = super::confirmation_session(&desktop, epoch).await?;- session.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;- let selection = normalize_worker_dependency_selection(&input)?;- state.prepare(window.label(), selection, now_ms()?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &desktop.0,+ &desktop.1.error,+ &desktop.2,+ &desktop.3,+ );+ hiroute_product_session::commands::worker_dependencies_select_prepare(+ &context,+ &state,+ &product_state,+ input,+ )+ .await}-#[tauri::command]pub async fn worker_dependencies_select_confirm(window: WebviewWindow,@@ -384,16 +205,37 @@ pub async fn worker_dependencies_select_confirm(input: WorkerDependencyConfirmationInput,) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {main_window(&window)?;- let epoch = state.2.load(std::sync::atomic::Ordering::SeqCst);- let mut session = super::confirmation_session(&state, epoch).await?;- let selection = confirmations.take(window.label(), &input.confirmation_id, now_ms()?)?;- session- .as_mut()- .ok_or("RESIDENT_UNAVAILABLE")?- .select_worker_dependencies(selection)- .await+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_dependencies_select_confirm(+ &context,+ &product_state,+ &confirmations,+ input,+ )+ .await}-#[tauri::command]pub async fn worker_dependencies_select_cancel(window: WebviewWindow,@@ -401,9 +243,26 @@ pub async fn worker_dependencies_select_cancel(input: WorkerDependencyConfirmationInput,) -> Result<(), DesktopFailure> {main_window(&window)?;- state.cancel(window.label(), &input.confirmation_id)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ hiroute_product_session::commands::worker_dependencies_select_cancel(&context, &state, input)+ .await}-#[tauri::command]pub async fn worker_task_list(window: WebviewWindow,@@ -411,20 +270,31 @@ pub async fn worker_task_list(input: WorkerListRequestV1,) -> Result<MachineEnvelopeV2<DelegationListV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_list(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_list(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_status(window: WebviewWindow,@@ -432,20 +302,31 @@ pub async fn worker_task_status(input: WorkerStatusRequestV1,) -> Result<MachineEnvelopeV2<DelegationGetV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_status(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_status(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_result(window: WebviewWindow,@@ -453,20 +334,31 @@ pub async fn worker_task_result(input: WorkerResultRequestV1,) -> Result<MachineEnvelopeV2<DelegationResultV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_result(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_result(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_read(window: WebviewWindow,@@ -474,20 +366,31 @@ pub async fn worker_task_read(input: WorkerReadRequestV1,) -> Result<MachineEnvelopeV2<WorkerReadDataV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_read(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_read(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_wait(window: WebviewWindow,@@ -495,20 +398,31 @@ pub async fn worker_task_wait(input: WorkerWaitRequestV1,) -> Result<MachineEnvelopeV2<DelegationWaitV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_wait(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_wait(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_confirm_residual(window: WebviewWindow,@@ -516,22 +430,32 @@ pub async fn worker_task_confirm_residual(input: WorkerResidualConfirmRequestV1,) -> Result<MachineEnvelopeV2<DelegationRunViewV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_confirm_residual(&context, &product_state, input).await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client- .confirm_worker_residual(&crate::random_id()?, &input)- .await?)}-#[tauri::command]pub async fn worker_task_cancel(window: WebviewWindow,@@ -539,20 +463,31 @@ pub async fn worker_task_cancel(input: WorkerCancelRequestV1,) -> Result<MachineEnvelopeV2<DelegationCancelV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_cancel(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_cancel(&context, &product_state, input).await}-#[tauri::command]pub async fn worker_task_continue(window: WebviewWindow,@@ -560,20 +495,28 @@ pub async fn worker_task_continue(input: WorkerContinueRequestV1,) -> Result<MachineEnvelopeV2<DelegationAcceptedV1>, DesktopFailure> {main_window(&window)?;- if !input.valid() {- return Err("REQUEST_INVALID".into());- }- let client = state- .0- .lock()- .await- .as_ref()- .ok_or("RESIDENT_UNAVAILABLE")?- .client- .clone();- Ok(client.worker_continue(&crate::random_id()?, &input).await?)+ let broker = window.state::<WebConfirmationState>();+ let active = || window.is_visible().unwrap_or(false);+ let notify = |request: &WebConfirmationRequest| {+ window+ .emit_to(+ tauri::EventTarget::webview(window.label()),+ "hiroute-web-confirmation",+ request,+ )+ .map_err(|_| "CONFIRMATION_UNAVAILABLE".to_owned())+ };+ let context = hiroute_product_session::commands::ClientContext {+ id: window.label(),+ confirmations: &broker,+ active: &active,+ notify: Some(¬ify),+ };+ let product_state = hiroute_product_session::commands::CommandState(+ &state.0,+ &state.1.error,+ &state.2,+ &state.3,+ );+ hiroute_product_session::commands::worker_task_continue(&context, &product_state, input).await}--#[cfg(test)]-#[path = "worker_dependencies_tests.rs"]-mod tests;diff --git a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rsindex 7a30958f..add675b1 100644--- a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs+++ b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs@@ -1,6 +1,3 @@-use super::{ActionResult, MutationOutcome, mutation_outcome_result, mutation_result};-use hiroute_application_api::{CanonicalDigest, ClientOperationViewV1};-const MODEL_CONNECTION_COMMANDS: &[&str] = &["compute_management_snapshot","compute_key_masks",@@ -86,62 +83,6 @@ fn native_clipboard_exposes_only_text_writes_in_the_local_main_window() {assert_eq!(clipboard, ["clipboard-manager:allow-write-text"]);}-#[test]-fn action_results_and_failures_classify_without_business_text() {- use crate::failure::DesktopFailure;- use hiroute_client_core::{ClientFailure, FailureCode};- use hiroute_diagnostics::error::EventErrorCode;- assert_eq!(mutation_result("succeeded"), ActionResult::Applied);- assert_eq!(- mutation_result("needs_attention"),- ActionResult::Failed {- code: EventErrorCode::Recovery- }- );- assert_eq!(- mutation_result("rolled_back"),- ActionResult::Failed {- code: EventErrorCode::ExternalError- }- );- let succeeded = MutationOutcome {- state: "submitted".into(),- operation: Some(ClientOperationViewV1 {- model_budget_conflict: None,- operation_id: "op_diagnostics".into(),- state: "succeeded".into(),- sequence: 1,- cancellable: false,- accepted_digest: CanonicalDigest::of_bytes(b"diagnostics"),- safe_error_code: None,- }),- };- assert_eq!(mutation_outcome_result(&succeeded), ActionResult::Applied);- let unknown = MutationOutcome {- state: "response_unknown".into(),- operation: None,- };- assert_eq!(- mutation_outcome_result(&unknown),- ActionResult::Failed {- code: EventErrorCode::ExternalError- }- );- let native = |code: &str| DesktopFailure::Native { code: code.into() };- assert_eq!(- native("window_denied").event_code(),- EventErrorCode::WindowDenied- );- assert_eq!(- native("RESIDENT_UNAVAILABLE").event_code(),- EventErrorCode::ExternalError- );- let transport = DesktopFailure::Transport {- failure: ClientFailure::before_send(FailureCode::TransportUnavailable),- };- assert_eq!(transport.event_code(), EventErrorCode::TransportUnavailable);-}-fn assert_commands(commands: &[&str]) {let handler = include_str!("bridge.rs");let build_manifest = include_str!("../build.rs");diff --git a/apps/desktop/src-tauri/src/fault_tests.rs b/apps/desktop/src-tauri/src/fault_tests.rsindex 91f72cac..400e144b 100644--- a/apps/desktop/src-tauri/src/fault_tests.rs+++ b/apps/desktop/src-tauri/src/fault_tests.rs@@ -5,25 +5,9 @@ use crate::{session::{RenameInput, Session},};use hiroute_application_api::*;-use std::{cell::Cell, path::Path};+use std::path::Path;-#[derive(Clone, Copy, PartialEq, Eq)]-pub(crate) enum Fault {- None,- LoseApplyResponseAndDisconnect,- LoseBeforeApply,-}-thread_local! { static FAULT: Cell<Fault> = const { Cell::new(Fault::None) }; }-pub(crate) fn take(fault: Fault) -> bool {- FAULT.with(|current| {- if current.get() == fault {- current.set(Fault::None);- true- } else {- false- }- })-}+use hiroute_product_session::fault::{FAULT, Fault};fn prepare() -> tempfile::TempDir {let root = tempfile::Builder::new().prefix("hr02-")@@ -50,7 +34,7 @@ fn open(root: &Path) -> Session {.parent().unwrap().join("hirouted");- Session::new(Resident::open(root, &binary).unwrap())+ crate::session_from_resident(Resident::open(root, &binary).unwrap())}async fn plan(session: &mut Session) -> AgentPlanStatusV2 {session.snapshot().await.unwrap().catalog.plans.remove(0)diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 11714cf0..76cdb295 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -5,12 +5,12 @@ pub mod bootstrap;pub mod bridge;#[cfg(unix)]mod cli_entry;-mod confirmation;+pub use hiroute_product_session::{confirmation, failure, operation_observation, session};#[cfg(unix)]mod development_cpa;#[cfg(feature = "desktop-runtime")]mod duplicate_host;-pub mod failure;+#[cfg(all(test, target_os = "macos"))]mod fault_tests;#[cfg(unix)]@@ -18,10 +18,10 @@ mod gateway_address;mod login_item;#[cfg(unix)]mod native_diagnostics;-pub mod operation_observation;+#[cfg(unix)]mod resident_ownership;-pub mod session;+#[cfg(all(target_os = "macos", feature = "desktop-runtime"))]pub mod updates;@@ -30,3 +30,14 @@ pub fn random_id() -> Result<String, String> {getrandom::fill(bytes.as_mut()).map_err(|_| "RANDOM_UNAVAILABLE".to_owned())?;Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())}++#[cfg(unix)]+pub fn session_from_resident(resident: bootstrap::Resident) -> session::Session {+ let client = resident.client.clone();+ session::Session::new(+ client,+ std::sync::Arc::new(bootstrap::NativeAuthority(std::sync::Mutex::new(resident))),+ )+}+#[cfg(all(test, target_os = "macos"))]+mod price_native_tests;diff --git a/apps/desktop/src-tauri/src/price_native_tests.rs b/apps/desktop/src-tauri/src/price_native_tests.rsnew file mode 100644index 00000000..bb6f3faf--- /dev/null+++ b/apps/desktop/src-tauri/src/price_native_tests.rs@@ -0,0 +1,113 @@+use crate::session::*;+use hiroute_application_api::*;+use hiroute_domain::TokenRateV1;+use serde_json::Value;+#[tokio::test]+async fn native_price_confirmation_uses_real_cli_daemon_and_restart() {+ let root = tempfile::Builder::new()+ .prefix("hr10-")+ .tempdir_in(std::fs::canonicalize("/tmp").unwrap())+ .unwrap();+ let home = tempfile::tempdir().unwrap();+ // The registered external settings target requires an existing owned parent.+ std::fs::create_dir(home.path().join(".claude")).unwrap();+ let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/prepare_plan.py");+ let preparation = std::process::Command::new("python3")+ .arg(script)+ .arg(root.path())+ .env("HOME", std::fs::canonicalize(home.path()).unwrap())+ .output()+ .unwrap();+ assert!(+ preparation.status.success(),+ "CLI preparation: {}",+ String::from_utf8_lossy(&preparation.stderr)+ );+ let projection: Value = serde_json::from_slice(+ &std::fs::read(root.path().join("compute-projection.json")).unwrap(),+ )+ .unwrap();+ let binding = &projection["binding"];+ let binary = std::env::current_exe()+ .unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap()+ .join("hirouted");+ let open = || {+ crate::session_from_resident(+ crate::bootstrap::Resident::open(root.path(), &binary).unwrap(),+ )+ };+ let input = |revision| PriceEditInput {+ target_locator: PriceTargetLocatorV1::Binding {+ binding_id: binding["binding_id"].as_str().unwrap().into(),+ },+ currency: "USD".into(),+ valuation_kind: hiroute_domain::PriceValuationKindV1::UsageEstimate,+ expected_source_revision: binding["source_revision"].as_u64().unwrap(),+ expected_binding_revision: Some(binding["revision"].as_u64().unwrap()),+ expected_override_revision: revision,+ language: "en".into(),+ action: DecimalPriceAction::Set {+ input_uncached: "1.200001".into(),+ output: "4.8".into(),+ cache_read: None,+ cache_write: None,+ },+ };+ let mut session = open();+ let context = session.preview_price(input(0)).await.unwrap();+ assert!(context.message().contains("1.200001"));+ let cancelled = session+ .finish_price_confirmation(context, false)+ .await+ .unwrap();+ assert_eq!(cancelled.state, "cancelled_before_apply");+ assert!(session.snapshot().await.unwrap().pending.is_none());+ let context = session.preview_price(input(0)).await.unwrap();+ let outcome = session+ .finish_price_confirmation(context, true)+ .await+ .unwrap();+ assert_eq!(outcome.operation.unwrap().state, "succeeded");+ assert!(session.preview_price(input(0)).await.is_err());+ drop(session);+ let mut session = open();+ let prices: EffectivePricesResultV2 = query(+ &session.client,+ "GetEffectivePrices",+ &GetEffectivePricesV2 {+ targets: vec![EffectivePriceTargetQueryV2 {+ query_id: "selected".into(),+ target_locator: input(1).target_locator,+ currency: "USD".into(),+ valuation_kind: hiroute_domain::PriceValuationKindV1::UsageEstimate,+ }],+ },+ )+ .await+ .unwrap();+ assert_eq!(+ prices.items[0].quote.origin,+ hiroute_domain::PriceOriginV1::Manual+ );+ assert_eq!(+ prices.items[0].quote.rates.input_uncached,+ TokenRateV1::known(1_200_001)+ );+ let mut restore = input(1);+ restore.action = DecimalPriceAction::FollowCatalog;+ let context = session.preview_price(restore).await.unwrap();+ assert_eq!(+ session+ .finish_price_confirmation(context, true)+ .await+ .unwrap()+ .operation+ .unwrap()+ .state,+ "succeeded"+ );+}diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rsindex 6188a1f2..8d98b928 100644--- a/apps/desktop/src-tauri/src/updates.rs+++ b/apps/desktop/src-tauri/src/updates.rs@@ -328,9 +328,11 @@ async fn resident_call<T: Send + 'static>(sessions: &Sessions,call: impl FnOnce(&mut crate::bootstrap::Resident) -> Result<T, String> + Send + 'static,) -> Result<T, String> {- let mut session = sessions.clone().lock_owned().await;+ let session = sessions.clone().lock_owned().await;tokio::task::spawn_blocking(move || {- call(&mut session.as_mut().ok_or("RESIDENT_UNAVAILABLE")?.resident)+ call(&mut *crate::bootstrap::resident(+ session.as_ref().ok_or("RESIDENT_UNAVAILABLE")?,+ )?)}).await.map_err(|_| "UPGRADE_RESIDENT_UNAVAILABLE")?@@ -417,17 +419,19 @@ async fn recover_precommit(let mut session = sessions.clone().lock_owned().await;let result = tokio::task::spawn_blocking(move || {let current = session.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;- if !current.resident.upgrade_stop_requested() {- current.resident.upgrade_status(UpgradeAction::Cancel)?;+ let mut native = crate::bootstrap::resident(current)?;+ if !native.upgrade_stop_requested() {+ native.upgrade_status(UpgradeAction::Cancel)?;} else {crate::bridge::expire_window_confirmations(&handle, "main");- current.invalidate_confirmation();- let resident = current.resident.replacement_after_upgrade_stop(+ let resident = native.replacement_after_upgrade_stop(&root,&executable.with_file_name("hirouted"),&diagnostics,)?;- *session = Some(crate::session::Session::new(resident));+ drop(native);+ current.invalidate_confirmation();+ *session = Some(crate::session_from_resident(resident));}Ok::<_, String>(())})diff --git a/apps/desktop/src-tauri/tests/production_bootstrap.rs b/apps/desktop/src-tauri/tests/production_bootstrap.rsindex 25ff395c..bc976932 100644--- a/apps/desktop/src-tauri/tests/production_bootstrap.rs+++ b/apps/desktop/src-tauri/tests/production_bootstrap.rs@@ -214,7 +214,7 @@ async fn real_role_all_child_ack_and_read_only_lookup_use_shared_core() {.unwrap();assert_eq!(grant.len(), 64);}- let mut session = hiroute_desktop::session::Session::new(resident);+ let mut session = hiroute_desktop::session_from_resident(resident);let agents = session.agent_snapshot().await.unwrap();assert!(agents.trusted_authority);assert!(agents.plans.plans.is_empty());@@ -258,7 +258,7 @@ async fn obsolete_client_receipt_is_ignored_and_native_restart_requeries_backend).unwrap();let resident = Resident::open(root.path(), &binary).unwrap();- let mut session = hiroute_desktop::session::Session::new(resident);+ let mut session = hiroute_desktop::session_from_resident(resident);let snapshot = session.snapshot().await.unwrap();assert!(snapshot.service.recovery_ready);assert!(snapshot.service.mutation_available);diff --git a/apps/desktop/src/agents.tsx b/apps/desktop/src/agents.tsxindex d163e194..00034434 100644--- a/apps/desktop/src/agents.tsx+++ b/apps/desktop/src/agents.tsx@@ -1,3 +1,4 @@+import { SecretTransportWarning } from './host/ConsoleUi';import { AgentDiscoveryFeedback } from './features/agents/AgentDiscoveryFeedback';import { AgentSkillDetails } from './features/agents/AgentSkillDetails';import { loadAgentDiscoveryTargets, saveAgentDiscoveryTargets } from './features/agents/discovery';@@ -6,7 +7,7 @@ import { confirmedCodexLaunchCommand, type PendingCodexLaunchCopy } from './featimport { BrandIcon, Dialog, Disclosure, ProductPage, UiIcon, copyText } from './ui';import { confirmDiscard, useDiscardGuard } from './ui/discard-guard';import React, { useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from './host';import { agentEditorSeed, agentModelFormInvalid, editorFingerprint, EMPTY_EDITOR_VALUES, type AgentEditorValues } from './features/agents/editor-state';import { AgentSettingsFeedback } from './features/agents/AgentSettingsFeedback';import { AgentModelEditor, modelSelectionSummary } from './features/agents/AgentModelEditor';@@ -595,7 +596,7 @@ export function Agents({? text('适配插件已准备;当前 Hermes 进程的加载状态尚未确认。请重新加载插件或开启新会话。', 'Adapter files are prepared; loading in the current Hermes process is unobserved. Reload plugins or start a new session.'): text('适配资源需要修复;请检查自己的文件编辑后重新保存配置。', 'Adapter resources need repair. Review your file edits and save the settings again.')}</p>}{Boolean(selectedModel?.native_adapter?.known_channel_models?.length) && <p className="field-help" data-hermes-known-overrides>{text('已配置的通道模型覆盖', 'Configured channel model overrides')} · {selectedModel?.native_adapter?.known_channel_models?.join(', ')}. {text('需要改用 HiRoute 的通道,请通过 Hermes 的 /model 调整选择。', 'Use Hermes /model in a channel that should switch to HiRoute.')}</p>}- <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selectedModel?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selectedModel?.restore_point_ref && selected.agent_id === 'agent_codex_default' && selected.codex_access?.selected_mode !== 'profile' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selectedModel?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selectedModel?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>+ <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selectedModel?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selectedModel?.restore_point_ref && selected.agent_id === 'agent_codex_default' && selected.codex_access?.selected_mode !== 'profile' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selectedModel?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selectedModel?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><SecretTransportWarning language={language} /><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>{!editor && loadError && <div className="callout warn agent-feedback agent-inline-feedback" role="alert" data-error-code={loadError}><UiIcon name="warning" /><div><strong>{text('状态刷新失败', 'Status refresh failed')}</strong><p>{text('当前仍显示上次读取的结果。', 'The last loaded result is still shown.')}</p><button className="btn" type="button" onClick={() => void refresh()}>{text('重试', 'Retry')}</button></div></div>}{!editor && blockedPreview}{!editor && notice && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{notice}</span></div></div>}diff --git a/apps/desktop/src/features/ClassifierProtocolDialog.tsx b/apps/desktop/src/features/ClassifierProtocolDialog.tsxindex b30d7ae9..e76f02b1 100644--- a/apps/desktop/src/features/ClassifierProtocolDialog.tsx+++ b/apps/desktop/src/features/ClassifierProtocolDialog.tsx@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke, hostCapabilities } from '../host/index.ts';import { copyText, Dialog, UiIcon } from '../ui';import { useState } from 'react';import { protocolExamples, protocolCurl } from './decision-services/protocol-examples';@@ -61,7 +61,7 @@ export function ClassifierProtocolDialog({actionStatus === 'copied' ? text('已复制', 'Copied'): actionStatus === 'copy_failed' ? text('复制失败', 'Copy failed'): actionStatus === 'saving' ? text('请选择保存位置', 'Choose where to save the file')- : actionStatus === 'saved' ? text(`已保存:${CLASSIFIER_OPENAPI_FILENAME}`, `Saved: ${CLASSIFIER_OPENAPI_FILENAME}`)+ : actionStatus === 'saved' ? (hostCapabilities().host === 'console' ? text(`已开始下载:${CLASSIFIER_OPENAPI_FILENAME}`, `Download started: ${CLASSIFIER_OPENAPI_FILENAME}`) : text(`已保存:${CLASSIFIER_OPENAPI_FILENAME}`, `Saved: ${CLASSIFIER_OPENAPI_FILENAME}`)): actionStatus === 'save_cancelled' ? text('已取消保存', 'Save cancelled'): actionStatus === 'save_failed' ? text('保存失败,请重试。', 'Save failed. Try again.'): ''diff --git a/apps/desktop/src/features/PlanQuality.tsx b/apps/desktop/src/features/PlanQuality.tsxindex 59c30665..d359e246 100644--- a/apps/desktop/src/features/PlanQuality.tsx+++ b/apps/desktop/src/features/PlanQuality.tsx@@ -138,7 +138,7 @@ export function PlanQuality({<div className="quality-model-columns" aria-hidden="true"><span>{text('模型 / 思考设置', 'Model / Reasoning')}</span><span>{text('平均阶段胜任度', 'Average stage competence')}</span><span>{text('阶段样本', 'Stage samples')}</span><span /></div>{rows.filter(row => qualityRowSection(row) === branch).map(row => <div className={'quality-model-row' + (selected?.key === row.key ? ' selected' : '')} key={row.key} data-model-configuration={row.configured?.model_configuration_id ?? row.summary?.execution.model_configuration_id ?? ''}><div className="quality-model-name"><strong>{rowName(row)}</strong><span className="badge no-dot">{qualityGroupLabel(row.branch, row.summary?.execution.group ?? row.configured?.group, language)}</span><span>{qualityReasoningLabel(row.summary ? row.summary.reasoning_profile_id : row.configured?.reasoning_profile_id, language)}{version === 'all' && row.summary && ' · r' + row.summary.execution.plan_revision}</span></div>- <div className="quality-model-average">{row.summary?.average_score != null ? <><strong>{row.summary.average_score.toFixed(2)} <small>/ 1</small></strong><div className="quality-score-bar" aria-hidden="true"><span style={{ width: (row.summary.average_score * 100) + '%' }} /></div></> : <span>{row.summary ? text('未评分', 'Unrated') : text('暂无记录', 'No records')}</span>}</div>+ <div className="quality-model-average">{row.summary?.average_score != null ? <><strong>{row.summary.average_score.toFixed(2)} <small>/ 1</small></strong><div className="quality-score-bar" aria-hidden="true"><svg viewBox="0 0 100 4" preserveAspectRatio="none"><rect width={Math.max(0, Math.min(100, row.summary.average_score * 100))} height="4" /></svg></div></> : <span>{row.summary ? text('未评分', 'Unrated') : text('暂无记录', 'No records')}</span>}</div><div className="quality-model-counts"><span>{text((row.summary?.scored_stage_count ?? 0) + ' 已评分', (row.summary?.scored_stage_count ?? 0) + ' scored')}</span><span>{text((row.summary?.unrated_stage_count ?? 0) + ' 未评分', (row.summary?.unrated_stage_count ?? 0) + ' unrated')}</span></div><button type="button" className="btn btn-quiet quality-view-stages" aria-expanded={selected?.key === row.key} onClick={() => { setScore('all'); setSelected(selected?.key === row.key ? null : { key: row.key, execution: row.summary?.execution ?? null }); }}>{selected?.key === row.key ? text('收起阶段', 'Hide stages') : text('查看阶段', 'View stages')}<UiIcon name="chevronRight" /></button></div>)}diff --git a/apps/desktop/src/features/Sessions.tsx b/apps/desktop/src/features/Sessions.tsxindex d3d036e1..9e043d42 100644--- a/apps/desktop/src/features/Sessions.tsx+++ b/apps/desktop/src/features/Sessions.tsx@@ -1,6 +1,6 @@import { RuntimeFacts, type SafeFact } from './RuntimeFacts';import React, { useCallback, useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import { Dialog, Disclosure, formatMoney, ProductPage, Toast, UiIcon, useTransientToast } from '../ui';import type { CorrelationKind } from './session-correlation';import { readableEvent, excerpt, excerptAround, groupToolEvents, contentDisplayRuns, coalesceResponseText, isPrivateContentKind, isTechnicalContentKind, summarizeToolArguments, type ReadableEvent } from './session-content';@@ -471,7 +471,7 @@ function MessageOccurrence({ request, items, anchor, language, modelLabel, technconst responseText = coalesceResponseText(Object.values(events));const visible = potential || responseText.some(part => part.text.length > 0) || Object.values(visibility).some(Boolean);const incomplete = items.some(item => !['available', 'complete'].includes(item.state)) || Object.values(partIncomplete).some(Boolean);- return <article hidden={!visible} aria-hidden={!visible} style={visible ? undefined : { display: 'none' }} className={`message ${!technical && role === 'assistant' ? 'assistant' : !technical && role === 'user' && !contextOnly ? 'user' : 'system'}`}><span className="message-avatar">{technical ? '·' : role === 'assistant' ? 'AI' : role === 'user' && !contextOnly ? 'YOU' : '·'}</span><div><div className="message-role">{roleLabel}{modelLabel && <span className="badge info no-dot">{modelLabel}</span>}{incomplete && <span className="badge warn no-dot">{language === 'zh' ? '内容不完整' : 'Incomplete'}</span>}</div>{items.map(item => <MessagePart key={item.content_id} request={request} item={item} anchor={anchor?.contentId === item.content_id ? anchor.offset : undefined} language={language} onEvent={reportEvent} onVisibility={reportVisibility} onIncomplete={reportIncomplete} onContext={reportContext} />)}{responseText.map(part => <div className="message-content" key={`${part.kind}-${part.index}`}>{part.text}</div>)}</div></article>;+ return <article hidden={!visible} aria-hidden={!visible} className={`message ${!technical && role === 'assistant' ? 'assistant' : !technical && role === 'user' && !contextOnly ? 'user' : 'system'}`}><span className="message-avatar">{technical ? '·' : role === 'assistant' ? 'AI' : role === 'user' && !contextOnly ? 'YOU' : '·'}</span><div><div className="message-role">{roleLabel}{modelLabel && <span className="badge info no-dot">{modelLabel}</span>}{incomplete && <span className="badge warn no-dot">{language === 'zh' ? '内容不完整' : 'Incomplete'}</span>}</div>{items.map(item => <MessagePart key={item.content_id} request={request} item={item} anchor={anchor?.contentId === item.content_id ? anchor.offset : undefined} language={language} onEvent={reportEvent} onVisibility={reportVisibility} onIncomplete={reportIncomplete} onContext={reportContext} />)}{responseText.map(part => <div className="message-content" key={`${part.kind}-${part.index}`}>{part.text}</div>)}</div></article>;}function MessagePart({ request, item, anchor, language, onEvent, onVisibility, onIncomplete, onContext }: { onEvent?: (id: string, event: ReadableEvent) => void; onVisibility(id: string, visible: boolean): void; onIncomplete(id: string, incomplete: boolean): void; onContext(id: string, contextOnly: boolean): void; request: string; item: Content; anchor?: number; language: 'zh' | 'en' }) {diff --git a/apps/desktop/src/features/ShellHostSettings.tsx b/apps/desktop/src/features/ShellHostSettings.tsxnew file mode 100644index 00000000..5de41fe5--- /dev/null+++ b/apps/desktop/src/features/ShellHostSettings.tsx@@ -0,0 +1,35 @@+import { useEffect, useState } from 'react';+import { invoke } from '../host/index.ts';+import { safeDiagnosticCode } from '../error-code';+import type { Language } from '../ui/preferences';+export function ShellHostSettings({ active, language }: { active: boolean; language: Language }) {+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ const [enabled, setEnabled] = useState<boolean | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [confirmRestart, setConfirmRestart] = useState(false);+ useEffect(() => {+ if (!active) return;+ let current = true;+ void invoke<{ enabled: boolean }>('login_start_get').then(value => { if (current) setEnabled(value.enabled); })+ .catch(cause => { if (current) setError(safeDiagnosticCode(cause, 'SHELL_LOGIN_UNAVAILABLE')); });+ return () => { current = false; };+ }, [active]);+ async function action(command: string, args = {}) {+ setBusy(true); setError('');+ try {+ const value = await invoke<{ enabled: boolean } | null>(command, args);+ if (command === 'login_start_set' && value) setEnabled(value.enabled);+ } catch (cause) { setError(safeDiagnosticCode(cause, 'SHELL_HOST_UNAVAILABLE')); }+ finally { setBusy(false); setConfirmRestart(false); }+ }+ return <section className="settings-group"><h2>{text('Windows 桌面应用', 'Windows Desktop')}</h2><div className="settings-list">+ <div className="settings-row"><div className="settings-copy"><strong>{text('登录时启动', 'Start at login')}</strong><span>{text('同时管理桌面窗口和当前用户的后台服务', 'Manage the Desktop window and current-user background service together')}</span></div>+ <button className="btn" type="button" aria-pressed={enabled === true} disabled={busy || enabled === null} onClick={() => void action('login_start_set', { enabled: !enabled })}>{enabled === null ? text('读取中…', 'Loading…') : enabled ? text('已开启', 'On') : text('已关闭', 'Off')}</button>+ </div>+ <div className="settings-row"><div className="settings-copy"><strong>{text('在浏览器中打开', 'Open in browser')}</strong><span>{text('创建一次性本机入口;浏览器会话需要重新进入', 'Create a one-time local entry; the browser session requires re-entry')}</span></div><button className="btn" type="button" disabled={busy} onClick={() => void action('open_in_browser')}>{text('打开', 'Open')}</button></div>+ <div className="settings-row"><div className="settings-copy"><strong>{text('重新启动后台服务', 'Restart background service')}</strong><span>{text('桌面窗口可以保留;现有调用可能暂时中断', 'Keep the Desktop window open; current calls may be interrupted')}</span></div><button className="btn" type="button" disabled={busy} onClick={() => setConfirmRestart(true)}>{text('重启服务…', 'Restart service…')}</button></div>+ {confirmRestart && <div className="gateway-risk"><p>{text('确认重启后台服务?请先等待当前调用和 Worker 任务完成。', 'Restart the background service? Wait for current calls and Worker tasks first.')}</p><button className="btn" type="button" disabled={busy} onClick={() => void action('restart_service')}>{text('确认重启', 'Restart service')}</button><button className="btn" type="button" disabled={busy} onClick={() => setConfirmRestart(false)}>{text('取消', 'Cancel')}</button></div>}+ {error && <div className="settings-inline-error" role="status">{error}</div>}+ </div></section>;+}diff --git a/apps/desktop/src/features/SubscriptionProxySettings.tsx b/apps/desktop/src/features/SubscriptionProxySettings.tsxindex a9993116..6897d6ad 100644--- a/apps/desktop/src/features/SubscriptionProxySettings.tsx+++ b/apps/desktop/src/features/SubscriptionProxySettings.tsx@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import { useEffect, useId, useRef, useState, type ReactNode } from 'react';import { safeDiagnosticCode } from '../error-code';import { clearSubscriptionProxyReturn, requestSubscriptionProxyReturn } from './subscription-proxy-return';@@ -90,7 +90,7 @@ export function SubscriptionProxySettings({ editing, language, writable, onCance</label>{mode === 'manual' && <><label className="field-label">{text('HTTP / HTTPS 代理地址', 'HTTP / HTTPS proxy URL')}<input className="input" type="url" required maxLength={2048} aria-label={text('订阅代理地址', 'Subscription proxy URL')} placeholder={text('http://127.0.0.1:端口', 'http://127.0.0.1:port')} value={url} disabled={busy || !writable} onChange={event => setUrl(event.target.value)} /></label>- <label className="field-label">{text('绕过代理的地址(可选)', 'Proxy bypass list (optional)')}<input className="input" maxLength={4096} aria-label={text('订阅代理绕过列表', 'Subscription proxy bypass list')} placeholder="example.com,192.168.0.0/16" value={bypass} disabled={busy || !writable} onChange={event => setBypass(event.target.value)} /></label>+ <label className="field-label">{text('绕过代理的地址(可选)', 'Proxy bypass list (optional)')}<input className="input" maxLength={4096} aria-label={text('订阅代理绕过列表', 'Subscription proxy bypass list')} placeholder="example.com,198.51.100.0/24" value={bypass} disabled={busy || !writable} onChange={event => setBypass(event.target.value)} /></label><span className="field-help">{text('多个地址用逗号分隔;本机地址自动绕过。代理地址暂不支持用户名或密码。', 'Separate entries with commas; local addresses always bypass the proxy. Proxy URLs do not support usernames or passwords.')}</span></>}{mode === 'inherit' && <span className="field-help">{text('使用 HiRoute 启动时已有的代理设置。', 'Uses the proxy settings available when HiRoute starts.')}</span>}diff --git a/apps/desktop/src/features/UpdatesSettings.tsx b/apps/desktop/src/features/UpdatesSettings.tsxindex edea1d7e..154f93a7 100644--- a/apps/desktop/src/features/UpdatesSettings.tsx+++ b/apps/desktop/src/features/UpdatesSettings.tsx@@ -1,11 +1,11 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke, hostCapabilities } from '../host/index.ts';import { useEffect, useState } from 'react';import { safeDiagnosticCode } from '../error-code';import type { Language } from '../ui/preferences';type UpdateView = {current_version: string;- phase: 'idle' | 'checking' | 'current' | 'available' | 'downloading' | 'verifying' | 'ready' | 'waiting' | 'installing' | 'failed';+ phase: 'idle' | 'checking' | 'check_failed' | 'current' | 'available' | 'downloading' | 'verifying' | 'ready' | 'waiting' | 'installing' | 'failed';available: { version: string; notes: { zh: string; en: string }; size: number } | null;downloaded_bytes: number;active_calls: number;@@ -44,6 +44,7 @@ export function UpdatesSettings({ active, language, onServiceChanged }: { active};const status = !view ? text('正在读取版本信息…', 'Reading version information…'): view.phase === 'checking' ? text('正在检查官网发布版本…', 'Checking official releases…')+ : view.phase === 'check_failed' ? view.error === 'UPGRADE_CATALOG_UNAVAILABLE' ? text('Windows 更新目录暂不可用,可稍后重试检查。', 'The Windows update catalog is unavailable. Try checking again later.') : text('检查更新失败,可稍后重试。', 'Could not check for updates. Try again later.'): view.phase === 'current' ? text('已是最新稳定版本', 'The latest stable version is installed'): view.phase === 'available' ? text(`可升级到 ${view.available?.version}`, `Version ${view.available?.version} is available`): view.phase === 'downloading' ? text(`正在下载 ${view.available?.version} · ${Math.min(100, Math.floor(view.downloaded_bytes / (view.available?.size || 1) * 100))}%`, `Downloading ${view.available?.version} · ${Math.min(100, Math.floor(view.downloaded_bytes / (view.available?.size || 1) * 100))}%`)@@ -66,11 +67,11 @@ export function UpdatesSettings({ active, language, onServiceChanged }: { active</div></div>{view?.available && !busy && <div className="gateway-risk">{view.available.notes[language]}</div>}- {view?.phase === 'ready' && <div className="gateway-risk">{text('安装前会等待现有调用和任务结束。安装与首次启动期间,Agent 路由会暂时不可用;需要时可按备份目录中的说明恢复旧 App 和旧数据。', 'Installation waits for current calls and tasks. Agent routing is temporarily unavailable during installation and first startup. If needed, follow the backup instructions to restore the previous App and data.')}</div>}+ {view?.phase === 'ready' && <div className="gateway-risk">{hostCapabilities().host === 'shell-console' ? text('安装前会等待现有调用和任务结束,可以取消等待。安装期间 Agent 路由会暂时不可用;失败时会尝试恢复旧版本,启动页会显示需要处理的恢复问题。', 'Installation waits for current calls and tasks; you can cancel the wait. Agent routing pauses during installation. A failed update attempts to restore the previous version; the startup page shows any recovery that needs attention.') : text('安装前会等待现有调用和任务结束。安装与首次启动期间,Agent 路由会暂时不可用;需要时可按备份目录中的说明恢复旧 App 和旧数据。', 'Installation waits for current calls and tasks. Agent routing is temporarily unavailable during installation and first startup. If needed, follow the backup instructions to restore the previous App and data.')}</div>}{recovery === 'service_available' && <div className="gateway-risk">{text('升级未完成,旧版本服务已恢复,可继续使用或重试安装。', 'The upgrade did not complete. The previous service is available; continue using HiRoute or retry installation.')}</div>}{recovery === 'stop_pending' && <div className="settings-inline-error" role="status">{text('服务仍在停止,尚未替换应用。请等待服务退出后,完全退出并重新打开 HiRoute。', 'The service is still stopping and the App has not been replaced. Wait for the service to exit, then fully quit and reopen HiRoute.')}</div>}{recovery === 'restart_required' && <div className="settings-inline-error" role="status">{text('尚未替换应用,旧版本服务未能恢复。请完全退出并重新打开 HiRoute,并查看启动页的恢复说明。', 'The App has not been replaced, but the previous service could not be restored. Fully quit and reopen HiRoute and follow the startup recovery instructions.')}</div>}- {code && <div className="settings-inline-error" role="status">{text(`升级不可用(${code})。可重试检查,或从官网下载安装包并完全退出 HiRoute 后覆盖安装。`, `Update unavailable (${code}). Check again, or download from the official website and fully quit HiRoute before replacing the App.`)}</div>}+ {code && <div className="settings-inline-error" role="status">{view?.phase === 'check_failed' ? text(`检查未完成(${code})。当前版本和后台服务仍可继续使用。`, `The check did not complete (${code}). The current version and background service remain available.`) : text(`升级不可用(${code})。可重试检查,或从官网下载安装包并完全退出 HiRoute 后覆盖安装。`, `Update unavailable (${code}). Check again, or download from the official website and fully quit HiRoute before replacing the App.`)}</div>}{view && !view.can_install && <div className="gateway-risk">{text('应用内安装需要使用完整的 HiRoute App。', 'In-app installation requires a complete HiRoute App.')}</div>}</div></section>;}diff --git a/apps/desktop/src/features/WorkerDependencies.tsx b/apps/desktop/src/features/WorkerDependencies.tsxindex c6308756..cd556f43 100644--- a/apps/desktop/src/features/WorkerDependencies.tsx+++ b/apps/desktop/src/features/WorkerDependencies.tsx@@ -1,6 +1,6 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke, isTauriHost } from '../host/index.ts';import { useEffect, useRef, useState } from 'react';-import { BrandIcon, Disclosure, UiIcon } from '../ui';+import { BrandIcon, Disclosure, UiIcon, copyText } from '../ui';import type { PlanOperation } from '../plan-editor-persistence';import {recommendedWorkerDependencies,@@ -174,7 +174,7 @@ export function WorkerDependencies({async function copyCommand(command: string) {setError('');try {- await navigator.clipboard.writeText(command);+ await copyText(command);setNotice(text('安装命令已复制。请在终端执行后返回重新检测。', 'Installation command copied. Run it in a terminal, then return and detect again.'));} catch {setError(text('无法写入剪贴板,请手动复制命令。', 'Could not write to the clipboard. Copy the command manually.'));@@ -182,7 +182,7 @@ export function WorkerDependencies({}async function openInstallationGuide(event: React.MouseEvent<HTMLAnchorElement>) {- if (!("__TAURI_INTERNALS__" in window)) return;+ if (!isTauriHost()) return;event.preventDefault();try {await invoke('open_external_url', { url: event.currentTarget.href });diff --git a/apps/desktop/src/features/decision-services/DecisionConnectionForm.tsx b/apps/desktop/src/features/decision-services/DecisionConnectionForm.tsxindex 60941a8e..19fcc0ec 100644--- a/apps/desktop/src/features/decision-services/DecisionConnectionForm.tsx+++ b/apps/desktop/src/features/decision-services/DecisionConnectionForm.tsx@@ -1,3 +1,4 @@+import { SecretTransportWarning } from '../../host/ConsoleUi';import { useRef, useState } from 'react';import { Disclosure, UiIcon } from '../../ui';import { confirmDiscard, requestEditorReplacement, useDiscardGuard } from '../../ui/discard-guard';@@ -96,7 +97,7 @@ export function DecisionConnectionForm({ initial, saved, language, mutable, onSa{credentialNotice && <p className="field-help" role="status">{credentialNotice}</p>}{connection.auth_header && <div className="field"><label className="field-label" htmlFor="decision-credential">{connection.kind === 'system_one' ? 'API Key' : authMode === 'bearer' ? 'Bearer Token' : t('请求头的完整值', 'Full header value')}</label>{!!connection.auth_header.value_secret_ref && !replacing && <div className="decision-credential-saved"><UiIcon name="lock" /><span>{t('已配置', 'Configured')}</span><button className="btn btn-quiet" type="button" onClick={() => { setReplacing(true); requestAnimationFrame(() => secret.current?.focus()); }}>{t('更换', 'Replace')}</button></div>}- <div className="decision-secret-input" hidden={!!connection.auth_header.value_secret_ref && !replacing}><input ref={secret} id="decision-credential" name="credential" className="input" type={revealed ? 'text' : 'password'} autoComplete="new-password" required={!connection.auth_header.value_secret_ref || replacing} maxLength={32768} aria-invalid={!!issues.credential} placeholder={authMode === 'header' ? t('例如 Bearer your-token', 'For example Bearer your-token') : t('输入 Key 或 Token', 'Enter a key or token')} onChange={event => { setHasSecret(!!event.target.value); setCredentialNotice(''); setIssues({}); }} /><button className="btn btn-quiet" type="button" aria-pressed={revealed} onClick={() => setRevealed(!revealed)}>{revealed ? t('隐藏', 'Hide') : t('显示', 'Show')}</button></div>+ <SecretTransportWarning language={language} /><div className="decision-secret-input" hidden={!!connection.auth_header.value_secret_ref && !replacing}><input ref={secret} id="decision-credential" name="credential" className="input" type={revealed ? 'text' : 'password'} autoComplete="new-password" required={!connection.auth_header.value_secret_ref || replacing} maxLength={32768} aria-invalid={!!issues.credential} placeholder={authMode === 'header' ? t('例如 Bearer your-token', 'For example Bearer your-token') : t('输入 Key 或 Token', 'Enter a key or token')} onChange={event => { setHasSecret(!!event.target.value); setCredentialNotice(''); setIssues({}); }} /><button className="btn btn-quiet" type="button" aria-pressed={revealed} onClick={() => setRevealed(!revealed)}>{revealed ? t('隐藏', 'Hide') : t('显示', 'Show')}</button></div>{replacing && !!connection.auth_header.value_secret_ref && <button className="btn btn-quiet" type="button" onClick={() => { if (secret.current) secret.current.value = ''; setReplacing(false); setHasSecret(false); setRevealed(false); }}>{t('保留已保存的认证', 'Keep saved credential')}</button>}{fieldError('credential')}{authMode === 'bearer' && connection.kind === 'custom' && <span className="field-help">{t('只需填写 Token,HiRoute 自动添加 Bearer 前缀。', 'Enter the token only. HiRoute adds the Bearer prefix.')}</span>}</div>}diff --git a/apps/desktop/src/features/decision-services/DecisionServicesPage.tsx b/apps/desktop/src/features/decision-services/DecisionServicesPage.tsxindex 6cb282ba..6bfefc61 100644--- a/apps/desktop/src/features/decision-services/DecisionServicesPage.tsx+++ b/apps/desktop/src/features/decision-services/DecisionServicesPage.tsx@@ -1,5 +1,5 @@import { useEffect, useState, type ReactNode } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../../host/index.ts';import { Dialog, Disclosure, ProductPage, UiIcon } from '../../ui';import { requestEditorReplacement, useDiscardGuard } from '../../ui/discard-guard';import { ClassifierProtocolDialog } from '../ClassifierProtocolDialog';diff --git a/apps/desktop/src/features/decision-services/types.ts b/apps/desktop/src/features/decision-services/types.tsindex de97237f..dd33797c 100644--- a/apps/desktop/src/features/decision-services/types.ts+++ b/apps/desktop/src/features/decision-services/types.ts@@ -1,3 +1,4 @@+import { randomId } from '../../random-id.ts';import type { Selection } from '../../plan-editor';import decisionPresets from '../../../../../assets/decision-services/providers.v1.json' with { type: 'json' };@@ -33,7 +34,7 @@ export const defaultJudgment: Judgment = { competence: defaultCompetence, degreesimple: defaultConditions[0], complex: defaultConditions[1],} };export function newBranch(name: string, condition = ''): RouteBranch {- return { id: 'branch-' + crypto.randomUUID(), name, condition, candidates: [], primary_candidates: [] };+ return { id: 'branch-' + randomId(), name, condition, candidates: [], primary_candidates: [] };}export function branchRouting(service?: DecisionService): BranchRouting {const branches = [newBranch('分支 1'), newBranch('分支 2')];@@ -42,7 +43,7 @@ export function branchRouting(service?: DecisionService): BranchRouting {}export const providers = decisionPresets.providers;export function emptyService(): DecisionService {- return { id: 'decision-' + crypto.randomUUID(), revision: 1, name: '', connection: {+ return { id: 'decision-' + randomId(), revision: 1, name: '', connection: {kind: 'system_one', provider: providers[0].id, endpoint: providers[0].endpoint, model: providers[0].model,timeout_ms: 10000, auth_header: { name: 'Authorization', value_secret_ref: '' },} };diff --git a/apps/desktop/src/features/diagnostics/DiagnosticsSettings.tsx b/apps/desktop/src/features/diagnostics/DiagnosticsSettings.tsxindex 6e8b9791..eb1ec5be 100644--- a/apps/desktop/src/features/diagnostics/DiagnosticsSettings.tsx+++ b/apps/desktop/src/features/diagnostics/DiagnosticsSettings.tsx@@ -1,3 +1,4 @@+import { hostCapabilities } from '../../host/index.ts';import {canSave,debugEnabled,@@ -102,7 +103,7 @@ export function DiagnosticsSettings(props: DiagnosticsSettingsProps) {<div className="settings-copy"><strong>{text('日志目录', 'Log directory')}</strong><span>- {text(+ {hostCapabilities().directory_reveal === 'path' ? text('日志保存在运行 HiRoute 服务的设备上。可显示目录路径,在该设备上打开目录并查看 daemon/ 下的日志文件;日志不包含对话内容或凭据。', 'Logs are stored on the device running HiRoute. Show the directory path and open it on that device to read the daemon/ logs. Logs contain no conversation content or credentials.') : text('日志保存在本机应用数据目录;点击会在文件管理器中打开该目录。目录里的 .jsonl 文件就是日志:desktop/ 下是客户端日志,daemon/ 下是引擎(本机服务)日志;向社区求助时附上这些文件即可,其余文件不需要发送。日志不含对话内容或凭据。','The logs live in this app\'s local data directory. The button opens that folder in your file manager. The .jsonl files are the logs: desktop/ holds the client logs and daemon/ the engine (local service) logs; attach these when asking the community for help — the other files are not needed. The logs never contain conversation content or credentials.',)}@@ -117,7 +118,7 @@ export function DiagnosticsSettings(props: DiagnosticsSettingsProps) {>{view.logsState.phase === 'busy'? text('打开中…', 'Opening…')- : text('打开日志目录', 'Open log directory')}+ : hostCapabilities().directory_reveal === 'path' ? text('显示目录路径', 'Show directory path') : text('打开日志目录', 'Open log directory')}</button></div></div>diff --git a/apps/desktop/src/features/diagnostics/use-diagnostics.ts b/apps/desktop/src/features/diagnostics/use-diagnostics.tsindex 5f003e61..3bd805be 100644--- a/apps/desktop/src/features/diagnostics/use-diagnostics.ts+++ b/apps/desktop/src/features/diagnostics/use-diagnostics.ts@@ -1,4 +1,5 @@-import { invoke } from '@tauri-apps/api/core';+import { hostCapabilities } from '../../host/index.ts';+import { invoke } from '../../host/index.ts';import { useCallback, useEffect, useRef, useState } from 'react';import {acceptResponse,@@ -115,7 +116,9 @@ export function useDiagnostics(active: boolean, language: 'zh' | 'en'): DiagnostsetLogsState({ phase: 'busy' });try {await invoke<null>('open_diagnostic_directory');- setLogsState(openLogsState(true, undefined, language));+ setLogsState(hostCapabilities().directory_reveal === 'path'+ ? { phase: 'opened', code: language === 'zh' ? '目录路径已显示。' : 'The directory path is displayed.' }+ : openLogsState(true, undefined, language));} catch (error) {setLogsState(openLogsState(false, nativeFailureCode(error, 'diagnostics_unavailable'), language));} finally {diff --git a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsxindex bec8c2ad..b6b8f4b4 100644--- a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx+++ b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx@@ -1,7 +1,8 @@+import { SecretTransportWarning } from '../../host/ConsoleUi';import { connectionName, connectionTemplate } from '../../ui/provider-identity';import { ProviderIcon } from '../../ui/ProviderIcon';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke, isTauriHost } from '../../host/index.ts';import { Dialog } from '../../ui/Dialog';import { Disclosure } from '../../ui/Disclosure';@@ -637,7 +638,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {}async function openDocumentation(event: React.MouseEvent<HTMLAnchorElement>, url?: string) {- if (!("__TAURI_INTERNALS__" in window)) return;+ if (!isTauriHost()) return;event.preventDefault();setExternalLinkError(false);if (!url) {@@ -693,7 +694,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {<fieldset className="connection-fields" disabled={!props.mutable || Boolean(props.appendTo)}><div className="connection-config-heading"><ProviderIcon optionId={custom ? draft.display_template_id : registeredOption?.connection_option_id} language={language} /><div><h3>{custom ? (zh ? '自定义 API' : 'Custom API') : productName}</h3><p>{custom ? (zh ? '填写服务地址,连接兼容的模型服务' : 'Connect a compatible model service') : connectionTemplate(registeredOption?.connection_option_id)?.description[language]}</p></div></div><label className="field"><span className="field-label">{zh ? '连接名称' : 'Connection name'}</span><input className="input" maxLength={60} data-autofocus={screen === 'connection' || undefined} value={draft.display_name} placeholder={zh ? '例如:团队模型服务' : 'e.g. Team models'} onChange={event => invalidate(current => ({ ...current, display_name: event.target.value }), false, 'connection')} /><span className="field-help">{zh ? '用于区分不同账号或用途,保存后可在模型列表中看到。' : 'Distinguish accounts or purposes. This name appears in your model list.'}</span></label>- {draft.authentication.kind !== 'none' && <label className="field"><span className="field-label">API Key</span><input className="input" disabled={!custom && (optionsLoading || !registeredOption)} ref={password} type="password" autoComplete="off" spellCheck={false} placeholder={protectedInputRef.current ? '••••••••••••••••' : draft.existing_source_id ? (zh ? '留空使用已保存的 Key' : 'Leave blank to use the saved key') : (zh ? '粘贴此产品的 API Key' : 'Paste this product’s API key')} onChange={() => invalidate(current => ({ ...current, candidate_ref: null }), true, 'connection')} /></label>}+ {draft.authentication.kind !== 'none' && <label className="field"><SecretTransportWarning language={props.language} /><span className="field-label">API Key</span><input className="input" disabled={!custom && (optionsLoading || !registeredOption)} ref={password} type="password" autoComplete="off" spellCheck={false} placeholder={protectedInputRef.current ? '••••••••••••••••' : draft.existing_source_id ? (zh ? '留空使用已保存的 Key' : 'Leave blank to use the saved key') : (zh ? '粘贴此产品的 API Key' : 'Paste this product’s API key')} onChange={() => invalidate(current => ({ ...current, candidate_ref: null }), true, 'connection')} /></label>}{!custom && registeredOption && <div className="connection-key-help"><span className="field-help">{zh ? '请使用上方产品对应的 Key。' : 'Use the key for the product shown above.'}</span>{connectionTemplate(registeredOption.connection_option_id)?.documentation_url && <a href={connectionTemplate(registeredOption.connection_option_id)?.documentation_url} target="_blank" rel="noreferrer" onClick={event => void openDocumentation(event, connectionTemplate(registeredOption.connection_option_id)?.documentation_url)}>{zh ? '获取 API Key' : 'Get an API key'}<UiIcon name="arrow" /></a>}{externalLinkError && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{zh ? '无法打开默认浏览器;当前表单内容已保留。' : 'The default browser could not be opened. Your form input is retained.'}</span></div>}</div>}{custom ? <>{!optionsLoading && metadataPrefills.length > 0 && <Disclosure className="connection-details" language={language} label={zh ? '使用接入资料预填(可选)' : 'Use connection prefill (optional)'}><div className="connection-fields metadata-prefill-fields">diff --git a/apps/desktop/src/features/model-connections/state.ts b/apps/desktop/src/features/model-connections/state.tsindex 2c3a8256..54f659b8 100644--- a/apps/desktop/src/features/model-connections/state.ts+++ b/apps/desktop/src/features/model-connections/state.ts@@ -1,3 +1,4 @@+import { randomId } from '../../random-id.ts';import type {CandidateModelView,ComputeCandidateRef,@@ -164,7 +165,7 @@ export function buildSaveChange(input: {}export function clientOperationId(prefix: string): string {- return `${prefix}/${globalThis.crypto.randomUUID()}`;+ return `${prefix}/${randomId()}`;}export function clientIdempotencyKey(prefix: string): string {diff --git a/apps/desktop/src/features/model-reference/PriceEditor.tsx b/apps/desktop/src/features/model-reference/PriceEditor.tsxindex 6436d7cb..e8123559 100644--- a/apps/desktop/src/features/model-reference/PriceEditor.tsx+++ b/apps/desktop/src/features/model-reference/PriceEditor.tsx@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../../host/index.ts';import { useEffect, useMemo, useRef, useState } from 'react';import { Dialog, UiIcon } from '../../ui';import { confirmDiscard } from '../../ui/discard-guard';diff --git a/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx b/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsxindex 2f444f4b..a2822c08 100644--- a/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx+++ b/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../../host/index.ts';import { Dialog } from '../../ui';import type { ManagedModel, ManagedSource, ManagementChange, ManagementSnapshot, SavePreview } from './types';diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsxindex 0a1be8ac..6c5c9a33 100644--- a/apps/desktop/src/features/models/Models.tsx+++ b/apps/desktop/src/features/models/Models.tsx@@ -1,7 +1,8 @@+import { SecretTransportWarning } from '../../host/ConsoleUi';import { ProviderIcon } from '../../ui/ProviderIcon';import { connectionName } from '../../ui/provider-identity';import React, { useEffect, useMemo, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../../host/index.ts';import type { Plan } from '../../plan-editor';import { branchSelections } from '../decision-services/types';import { Dialog, UiIcon } from '../../ui';@@ -352,12 +353,12 @@ export function Models(props: Props) {['free', text('免费', 'Free')],] as const).map(([value, label]) => <button className={`source-tab${filter === value ? ' active' : ''}`} key={value} type="button" aria-pressed={filter === value} onClick={() => { setFilter(value); setDetailOpen(false); }}>{label}</button>)}</div>+ <div className="segmented model-view-switch" role="group" aria-label={text('查看方式', 'View')}>+ <button className={`segment${view === 'models' ? ' active' : ''}`} type="button" aria-pressed={view === 'models'} onClick={() => setView('models')}>{text('按模型', 'Models')}</button>+ <button className={`segment${view === 'connections' ? ' active' : ''}`} type="button" aria-pressed={view === 'connections'} onClick={() => setView('connections')}>{text('按接入', 'Connections')}</button>+ </div></div><nav className="master-list native-list" aria-label={text('模型', 'Models')}>- <div className="filter-row" role="group" aria-label={text('查看方式', 'View')}>- <button className="filter-chip" type="button" aria-pressed={view === 'models'} onClick={() => setView('models')}>{text('按模型', 'Models')}</button>- <button className="filter-chip" type="button" aria-pressed={view === 'connections'} onClick={() => setView('connections')}>{text('按接入', 'Connections')}</button>- </div>{entries.map(item => {const active = source?.source_id === item.source.source_id && model?.model_ref === item.model?.model_ref;const itemStatus = modelAvailability(item.source, item.model);@@ -632,7 +633,7 @@ function CredentialEditor({ language, source, model, draft, errorCode, onChange,</div>}{editing ? <div className="field"><label className="field-label" htmlFor="credential-secret">{editing.kind === 'replace' ? text('替换 API Key', 'Replace API key') : 'API Key'}</label>- <input id="credential-secret" data-autofocus className="input" type={showSecret ? 'text' : 'password'} autoComplete="new-password" aria-invalid={Boolean(secretError)} aria-describedby={secretError ? 'credential-secret-error' : undefined} value={editing.kind === 'add' ? draft.addedSecret : draft.keys.find(key => key.draftId === editing.draftId)?.replacement ?? ''} onChange={event => { setSecretError(''); if (editing.kind === 'add') onChange({ ...draft, addedSecret: event.target.value }); else updateKey(editing.draftId, key => ({ ...key, replacement: event.target.value })); }} />+ <SecretTransportWarning language={language} /><input id="credential-secret" data-autofocus className="input" type={showSecret ? 'text' : 'password'} autoComplete="new-password" aria-invalid={Boolean(secretError)} aria-describedby={secretError ? 'credential-secret-error' : undefined} value={editing.kind === 'add' ? draft.addedSecret : draft.keys.find(key => key.draftId === editing.draftId)?.replacement ?? ''} onChange={event => { setSecretError(''); if (editing.kind === 'add') onChange({ ...draft, addedSecret: event.target.value }); else updateKey(editing.draftId, key => ({ ...key, replacement: event.target.value })); }} /><button className="btn btn-quiet" type="button" aria-pressed={showSecret} onClick={() => setShowSecret(value => !value)}>{showSecret ? text('隐藏', 'Hide') : text('显示', 'Show')}</button>{secretError && <p id="credential-secret-error" className="oc-inline-error" role="alert">{secretError}</p>}<div className="task-actions"><button className="btn" type="button" onClick={stopEditing}>{text('取消', 'Cancel')}</button><button className="btn btn-primary" type="button" onClick={acceptSecret}>{text('加入待保存修改', 'Add to changes')}</button></div>diff --git a/apps/desktop/src/features/models/model-draft.ts b/apps/desktop/src/features/models/model-draft.tsindex f5920824..2738e60d 100644--- a/apps/desktop/src/features/models/model-draft.ts+++ b/apps/desktop/src/features/models/model-draft.ts@@ -1,3 +1,4 @@+import { randomId } from '../../random-id.ts';import type { KeyEdit, ManagedSource, PreparedKeyInput, ProtectedKeyInput } from './types';export type DraftKey = {@@ -41,7 +42,7 @@ export function addDraftKey(draft: ModelDraft): ModelDraft {...draft,addedSecret: '',keys: [...draft.keys, {- draftId: crypto.randomUUID(),+ draftId: randomId(),expectedGeneration: 0,fingerprintHint: '待保存',enabled: true,diff --git a/apps/desktop/src/features/observation-client.ts b/apps/desktop/src/features/observation-client.tsindex 07c8a46c..9d46070e 100644--- a/apps/desktop/src/features/observation-client.ts+++ b/apps/desktop/src/features/observation-client.ts@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';let readers = 0;const queue: (() => void)[] = [];diff --git a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsxindex 478d7557..e138bf6f 100644--- a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx+++ b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx@@ -1,5 +1,6 @@+import { SecretTransportWarning } from '../../host/ConsoleUi';import { useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../../host/index.ts';import { BrandIcon, Disclosure, UiIcon } from '../../ui';import { safeDiagnosticCode } from '../../error-code';import type { CandidateRef, SubscriptionLoginProvider, SubscriptionLoginRequest, SubscriptionLoginResult, SubscriptionLoginSession } from './types';@@ -145,7 +146,7 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,{session.status === 'authorized' && session.candidate && <button type="button" className="btn btn-primary" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, () => onConnect(session.candidate!))}>{text('检查并选择模型', 'Check and choose models')}</button>}{session.status !== 'pending' && <button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => setForgetLogin(session.login_ref)}>{text('移除登录', 'Remove sign-in')}</button>}</div>- {callbackLogin === session.login_ref && session.status === 'pending' && <form autoComplete="off" onSubmit={event => { event.preventDefault(); void submitCallback(session); }}><label className="field"><span>{text('粘贴授权完成页面的回调地址或授权码', 'Paste the callback URL or authorization code from the completed sign-in')}</span><input type="password" autoComplete="off" spellCheck={false} value={callback} onChange={event => setCallback(event.currentTarget.value)} /></label><p className="oc-meta">{text('仅用于完成此次登录,不保存在页面中。', 'Used only to complete this sign-in; it is not saved in the page.')}</p><button className="btn" type="submit" disabled={!trustedAuthority || Boolean(busy) || !callback.trim()}>{text('完成授权', 'Finish authorization')}</button></form>}+ {callbackLogin === session.login_ref && session.status === 'pending' && <form autoComplete="off" onSubmit={event => { event.preventDefault(); void submitCallback(session); }}><label className="field"><span>{text('粘贴授权完成页面的回调地址或授权码', 'Paste the callback URL or authorization code from the completed sign-in')}</span><SecretTransportWarning language={language} /><input type="password" autoComplete="off" spellCheck={false} value={callback} onChange={event => setCallback(event.currentTarget.value)} /></label><p className="oc-meta">{text('仅用于完成此次登录,不保存在页面中。', 'Used only to complete this sign-in; it is not saved in the page.')}</p><button className="btn" type="submit" disabled={!trustedAuthority || Boolean(busy) || !callback.trim()}>{text('完成授权', 'Finish authorization')}</button></form>}{forgetLogin === session.login_ref && <div className="callout warn"><p>{text('移除此登录会停止相关订阅连接。保留模型和路由配置,之后可重新登录。', 'Removing this sign-in stops its subscription connection. Model and routing settings remain available for a later sign-in.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, async () => { merge((await manage({ action: 'forget', login_ref: session.login_ref })).sessions); if (alive.current) setForgetLogin(null); })}>{text('确认移除', 'Remove sign-in')}</button><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={() => setForgetLogin(null)}>{text('保留', 'Keep')}</button></div>}</div>)}</div>;diff --git a/apps/desktop/src/features/worker-task-client.ts b/apps/desktop/src/features/worker-task-client.tsindex 55aca6d8..ba5c5294 100644--- a/apps/desktop/src/features/worker-task-client.ts+++ b/apps/desktop/src/features/worker-task-client.ts@@ -1,3 +1,4 @@+import { randomId } from '../random-id.ts';import type { AgentTask } from './AgentTasks';type WorkerRun = {@@ -77,7 +78,7 @@ export type WorkerTaskListRead = {export type WorkerInvoke = <T>(command: string, args: { input: unknown }) => Promise<T>;async function nativeInvoke<T>(command: string, args: { input: unknown }): Promise<T> {- const { invoke } = await import('@tauri-apps/api/core');+ const { invoke } = await import('../host/index.ts');return invoke<T>(command, args);}@@ -273,7 +274,7 @@ export async function cancelWorkerTask(onAccepted?: (status: AgentTask['status']) => void,invokeWorker: WorkerInvoke = nativeInvoke,): Promise<AgentTask['status']> {- const idempotencyKey = `desktop-cancel:${crypto.randomUUID()}`;+ const idempotencyKey = `desktop-cancel:${randomId()}`;const input = { run_id: task.runId, idempotency_key: idempotencyKey, reason: 'user_requested' };let envelope: WorkerEnvelope<WorkerCancel>;try {@@ -304,7 +305,7 @@ export async function confirmWorkerTaskResidual(}const input = {run_id: task.runId, expected_revision: task.stateRevision,- idempotency_key: `desktop-residual:${crypto.randomUUID()}`, user_confirmed: true,+ idempotency_key: `desktop-residual:${randomId()}`, user_confirmed: true,};let envelope: WorkerEnvelope<WorkerRun>;try {diff --git a/apps/desktop/src/host/ConsoleRoot.tsx b/apps/desktop/src/host/ConsoleRoot.tsxnew file mode 100644index 00000000..5b12dde4--- /dev/null+++ b/apps/desktop/src/host/ConsoleRoot.tsx@@ -0,0 +1,95 @@+import { type PropsWithChildren, useEffect, useRef, useState } from 'react';+import { PresentationRoot, UiIcon, usePresentationPreferences } from '../ui';+import { safeDiagnosticCode } from '../error-code';+import { hostKind, initializeShellHost, invoke } from './index.ts';+import { clearConsoleSession, CONSOLE_EXPIRED_EVENT, CONSOLE_UNAVAILABLE_EVENT, exchangeConsoleCredential, readConsoleSession, sessionBearer } from './console.ts';+type Phase = 'loading' | 'login' | 'expired' | 'unavailable' | 'assets' | 'ready';+export function ConsoleRoot({ children }: PropsWithChildren) {+ if (hostKind() === 'tauri') return children;+ return <ConsoleSessionRoot>{children}</ConsoleSessionRoot>;+}+function ConsoleSessionRoot({ children }: PropsWithChildren) {+ const preferences = usePresentationPreferences();+ const zh = preferences.language === 'zh';+ const text = (cn: string, en: string) => zh ? cn : en;+ const [phase, setPhase] = useState<Phase>('loading');+ const [error, setError] = useState('');+ const [token, setToken] = useState('');+ const [busy, setBusy] = useState(false);+ const [hadSession, setHadSession] = useState(false);+ const started = useRef(false);+ const shell = hostKind() === 'shell-console';+ const reconnecting = useRef(false);+ async function reconnectShell() {+ if (reconnecting.current) return;+ reconnecting.current = true; setHadSession(false); setPhase('loading'); setToken('');+ try { await invoke('reconnect'); }+ catch (cause) { setError(safeDiagnosticCode(cause, 'SHELL_RECONNECT_FAILED')); setPhase('unavailable'); }+ finally { reconnecting.current = false; }+ }+ const plaintext = location.protocol === 'http:' && !['127.0.0.1', 'localhost', '[::1]', '::1'].includes(location.hostname);+ const accept = (identity: Awaited<ReturnType<typeof readConsoleSession>>) => { setHadSession(true); setPhase(identity.assets_available ? 'ready' : 'assets'); setError(''); };+ async function retry() {+ if (shell && !sessionBearer()) { await reconnectShell(); return; }+ setBusy(true); setError('');+ try { await initializeShellHost(); if (!sessionBearer()) { setPhase('login'); return; } accept(await readConsoleSession()); }+ catch (cause) { const code = safeDiagnosticCode(cause, 'CONSOLE_UNAVAILABLE'); setError(code); setPhase(code.includes('AUTH') || code.includes('CREDENTIAL') ? 'expired' : 'unavailable'); }+ finally { setBusy(false); }+ }+ useEffect(() => {+ const expired = () => { if (shell) { void reconnectShell(); return; } setHadSession(false); setPhase('expired'); setToken(''); };+ const unavailable = () => setPhase(current => current === 'ready' ? 'unavailable' : current);+ window.addEventListener(CONSOLE_EXPIRED_EVENT, expired);+ window.addEventListener(CONSOLE_UNAVAILABLE_EVENT, unavailable);+ if (!started.current) {+ started.current = true;+ const values = new URLSearchParams(location.search).getAll('code');+ // Clear the launch credential before any await, rendering, or secondary request.+ if (location.pathname === '/launch') history.replaceState(null, '', '/');+ if (values.length) {+ setBusy(true);+ void initializeShellHost().then(() => {+ if (values.length !== 1 || !/^[a-f0-9]{64}$/.test(values[0])) throw { code: 'CONSOLE_CREDENTIAL_INVALID' };+ return exchangeConsoleCredential('launch', values[0]);+ }).then(accept).catch(cause => { clearConsoleSession(); if (shell) { void reconnectShell(); return; } setError(safeDiagnosticCode(cause, 'CONSOLE_CREDENTIAL_INVALID')); setPhase('login'); }).finally(() => setBusy(false));+ } else void retry();+ }+ return () => { window.removeEventListener(CONSOLE_EXPIRED_EVENT, expired); window.removeEventListener(CONSOLE_UNAVAILABLE_EVENT, unavailable); };+ }, []);+ async function login(event: React.FormEvent) {+ event.preventDefault(); if (busy) return;+ const input = token; setToken(''); setBusy(true); setError('');+ try { accept(await exchangeConsoleCredential('token', input)); }+ catch (cause) { setError(safeDiagnosticCode(cause, 'CONSOLE_CREDENTIAL_INVALID')); }+ finally { setBusy(false); }+ }+ const loginPage = !shell && (phase === 'login' || phase === 'expired');+ return <>+ {hadSession && <div className="console-product" hidden={phase !== 'ready'} inert={phase !== 'ready'}>{children}</div>}+ {phase !== 'ready' && <PresentationRoot language={preferences.language} theme={preferences.resolvedTheme} textScale={1}>+ <main className="console-entry"><section className="console-entry-card">+ <div className="console-entry-brand"><span className="brand-mark">H</span><strong>HiRoute</strong></div>+ <h1>{phase === 'loading' ? text('正在连接控制台', 'Connecting to your console')+ : phase === 'expired' ? text('控制台会话已结束', 'Your console session has ended')+ : phase === 'assets' ? text('控制台文件不可用', 'Console files are unavailable')+ : phase === 'unavailable' ? text('暂时无法连接服务', 'The service is unavailable')+ : text('登录控制台', 'Sign in to the console')}</h1>+ {loginPage && <>+ <p>{text('在服务所在设备运行 hiroute console open 获取一次性登录链接,或输入由 hiroute console token create 创建的 access token。', 'On the service host, run hiroute console open for a single-use sign-in link, or enter an access token created with hiroute console token create.')}</p>+ {plaintext && <div className="callout warn" role="note"><UiIcon name="warning" /><span>{text('当前连接未加密,access token 将以明文通过网络发送。仅在信任的网络中继续。', 'This connection is unencrypted. Your access token will travel over the network as plaintext. Continue only on a network you trust.')}</span></div>}+ <form className="console-login" autoComplete="off" onSubmit={event => void login(event)}>+ <label className="field"><span className="field-label">Access token</span><input className="input" type="password" name="access-token" autoComplete="off" spellCheck={false} required maxLength={64} value={token} disabled={busy} onChange={event => setToken(event.currentTarget.value)} autoFocus /></label>+ <button className="btn btn-primary" type="submit" disabled={busy || !token.trim()}>{busy ? text('正在登录…', 'Signing in…') : text('登录', 'Sign in')}</button>+ </form>+ </>}+ {phase === 'unavailable' && <><p>{text('请确认服务正在运行,并检查当前控制台地址。现有数据与操作不会由此页面清除。', 'Check that the service is running and that this console address is current. Your saved data and operations are preserved.')}</p><button className="btn btn-primary" disabled={busy} onClick={() => void retry()}>{busy ? text('正在连接…', 'Connecting…') : text('重试连接', 'Try again')}</button></>}+ {phase === 'assets' && <p>{text('请在服务所在设备重新安装完整的 HiRoute 安装包。', 'Reinstall the complete HiRoute package on the service host.')} <code>CONSOLE_ASSETS_UNAVAILABLE</code></p>}+ {phase === 'loading' && <p role="status">{text('正在读取实际服务状态…', 'Reading the service status…')}</p>}+ {error && <p className="console-entry-error" role="alert">{text('未能完成连接', 'Could not complete the connection')} <code>{error}</code></p>}+ {error === 'CONSOLE_SESSION_LIMIT' && <p>{text('请退出其他设备上的控制台会话,或等待会话过期后重试。', 'Sign out of a console session on another device, or wait for a session to expire and try again.')}</p>}+ {error === 'CONSOLE_RATE_LIMITED' && <p>{text('登录失败次数过多,请等待一分钟后重试。远程登录失败不会阻止本机启动链接。', 'Too many failed sign-in attempts. Wait one minute and try again. Remote sign-in failures do not block local launch links.')}</p>}+ <div className="console-entry-preferences"><button className="btn btn-quiet" onClick={() => preferences.setLanguage(zh ? 'en' : 'zh')}>{zh ? 'English' : '中文'}</button><button className="btn btn-quiet" onClick={() => preferences.setTheme(preferences.resolvedTheme === 'dark' ? 'light' : 'dark')}>{preferences.resolvedTheme === 'dark' ? text('浅色', 'Light') : text('深色', 'Dark')}</button></div>+ </section></main>+ </PresentationRoot>}+ </>;+}diff --git a/apps/desktop/src/host/ConsoleUi.tsx b/apps/desktop/src/host/ConsoleUi.tsxnew file mode 100644index 00000000..53353536--- /dev/null+++ b/apps/desktop/src/host/ConsoleUi.tsx@@ -0,0 +1,31 @@+import { useEffect, useState } from 'react';+import { Dialog, UiIcon } from '../ui';+import { hostKind, plaintextConsole } from './index.ts';+import { logoutConsole } from './console.ts';+export function SecretTransportWarning({ language }: { language: 'zh' | 'en' }) {+ if (!plaintextConsole() || hostKind() === 'tauri') return null;+ return <p className="console-secret-warning" role="note">{language === 'zh'+ ? '此连接未加密。提交的密钥或授权内容会以明文通过网络传输;仅在信任的网络中继续。'+ : 'This connection is unencrypted. Submitted keys or authorization details cross the network as plaintext. Continue only on a network you trust.'}</p>;+}+export function HostNotices({ language }: { language: 'zh' | 'en' }) {+ const [path, setPath] = useState<string | null>(null);+ const zh = language === 'zh';+ useEffect(() => {+ const showPath = (event: Event) => { const value = (event as CustomEvent<unknown>).detail; if (typeof value === 'string' && value.length < 32768) setPath(value); };+ window.addEventListener('hiroute-host-path', showPath);+ return () => window.removeEventListener('hiroute-host-path', showPath);+ }, []);+ if (hostKind() === 'tauri') return null;+ return <>+ {hostKind() === 'console' && <div className={`console-transport-bar ${plaintextConsole() ? 'plaintext' : ''}`} role="status">+ <UiIcon name={plaintextConsole() ? 'warning' : 'info'} />+ <div><strong>{plaintextConsole() ? (zh ? '未加密的远程连接' : 'Unencrypted remote connection') : (zh ? '浏览器控制台会话' : 'Browser console session')}</strong>{plaintextConsole() && <span>{zh ? '会话、密钥和操作内容会以明文传输。' : 'Session credentials, keys and actions travel as plaintext.'}</span>}</div>+ {hostKind() === 'console' && <button className="btn btn-quiet" type="button" onClick={() => void logoutConsole()}>{zh ? '退出控制台' : 'Sign out'}</button>}+ </div>}+ <Dialog open={path !== null} title={zh ? '本机目录路径' : 'Directory on the service host'} closeLabel={zh ? '关闭' : 'Close'} onClose={() => setPath(null)}>+ <p>{zh ? '请在运行 HiRoute 服务的设备上打开此目录。' : 'Open this directory on the device running the HiRoute service.'}</p>+ <input className="input console-path" readOnly value={path ?? ''} onFocus={event => event.currentTarget.select()} aria-label={zh ? '目录路径' : 'Directory path'} />+ </Dialog>+ </>;+}diff --git a/apps/desktop/src/host/console.ts b/apps/desktop/src/host/console.tsnew file mode 100644index 00000000..0a81a53f--- /dev/null+++ b/apps/desktop/src/host/console.ts@@ -0,0 +1,75 @@+import type { ConsoleIdentity, HostCapabilities, HostTransport } from './types.ts';+import { browserCapabilities } from './types.ts';+import { safeDiagnosticCode } from '../error-code.ts';+const SESSION_KEY = 'hiroute.console.session';+const CONTEXT_KEY = 'hiroute.console.context';+const API = '/api/console/v1';+export const CONSOLE_EXPIRED_EVENT = 'hiroute-console-expired';+export const CONSOLE_UNAVAILABLE_EVENT = 'hiroute-console-unavailable';+let context: string | undefined;+let capabilities: HostCapabilities = browserCapabilities;+let transport: ConsoleIdentity['transport'] = 'loopback';+let lastFailure = 'CONSOLE_UNAVAILABLE';+const failure = (code: string) => ({ kind: 'native', code });+function storage(): Storage { try { return window.sessionStorage; } catch { throw failure('CONSOLE_STORAGE_UNAVAILABLE'); } }+export function sessionBearer(): string | null { try { return storage().getItem(SESSION_KEY); } catch { return null; } }+export function clearConsoleSession(): void { try { storage().removeItem(SESSION_KEY); } catch { /* Read-only/denied storage has no usable session. */ } }+function contextId(): string {+ if (context) return context;+ // Reload reuses this tab's context. A new document/tab gets its own random id,+ // even when the browser initially clones the opener's sessionStorage.+ const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;+ const retained = navigation?.type === 'reload' ? storage().getItem(CONTEXT_KEY) : null;+ context = retained && /^[a-f0-9]{32}$/.test(retained) ? retained+ : Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');+ storage().setItem(CONTEXT_KEY, context);+ return context;+}+async function request<T>(path: string, options: RequestInit = {}, authenticated = true): Promise<T> {+ const headers = new Headers(options.headers);+ headers.set('Content-Type', 'application/json');+ if (authenticated) {+ const bearer = sessionBearer();+ if (!bearer) throw failure('CONSOLE_AUTH_REQUIRED');+ headers.set('Authorization', `Bearer ${bearer}`);+ headers.set('X-HiRoute-Context', contextId());+ }+ let response: Response;+ try {+ response = await fetch(`${API}${path}`, { ...options, headers, credentials: 'omit', cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(90_000) });+ } catch {+ window.dispatchEvent(new Event(CONSOLE_UNAVAILABLE_EVENT));+ throw failure('CONSOLE_UNAVAILABLE');+ }+ let value: unknown;+ try { value = await response.json(); } catch { throw failure('RESPONSE_DATA_INVALID'); }+ if (!response.ok) {+ lastFailure = safeDiagnosticCode(value, 'CONSOLE_UNAVAILABLE');+ if (response.status === 401 && authenticated) { clearConsoleSession(); window.dispatchEvent(new Event(CONSOLE_EXPIRED_EVENT)); }+ throw value;+ }+ return value as T;+}+export async function exchangeConsoleCredential(kind: 'launch' | 'token', value: string): Promise<ConsoleIdentity> {+ const exchange = await request<{ bearer: string }>(`/session/${kind}`, { method: 'POST', body: JSON.stringify(kind === 'launch' ? { code: value } : { token: value }) }, false);+ if (!/^[a-f0-9]{64}$/.test(exchange.bearer)) throw failure('RESPONSE_DATA_INVALID');+ storage().setItem(SESSION_KEY, exchange.bearer);+ return readConsoleSession();+}+export async function readConsoleSession(): Promise<ConsoleIdentity> {+ const identity = await request<ConsoleIdentity>('/session');+ if (!identity.session?.id || !['loopback', 'network_plaintext'].includes(identity.transport) || typeof identity.assets_available !== 'boolean') throw failure('RESPONSE_DATA_INVALID');+ transport = identity.transport;+ capabilities = { ...browserCapabilities, platform: typeof identity.capabilities?.platform === 'string' ? identity.capabilities.platform : 'browser', diagnostic_directory: identity.capabilities?.diagnostic_directory, recovery_directory: identity.capabilities?.recovery_directory };+ return identity;+}+export async function logoutConsole(): Promise<void> { try { await request('/session', { method: 'DELETE' }); } finally { clearConsoleSession(); window.dispatchEvent(new Event(CONSOLE_EXPIRED_EVENT)); } }+export const plaintextConsole = () => transport === 'network_plaintext';+export const consoleCapabilities = () => capabilities;+export const consoleTransport: HostTransport = {+ capabilities: consoleCapabilities,+ async call<T>(command: string, args: Record<string, unknown> = {}): Promise<T> {+ if (command === 'startup_status') return { state: 'failed', code: lastFailure, recovery_available: Boolean(capabilities.recovery_directory) } as T;+ return request<T>(`/command/${encodeURIComponent(command)}`, { method: 'POST', body: JSON.stringify(args) });+ },+};diff --git a/apps/desktop/src/host/index.ts b/apps/desktop/src/host/index.tsnew file mode 100644index 00000000..713bfe37--- /dev/null+++ b/apps/desktop/src/host/index.ts@@ -0,0 +1,60 @@+import { browserCapabilities, type HostCapabilities, type HostKind, type HostTransport } from './types.ts';+import { consoleTransport, consoleCapabilities } from './console.ts';+import type { WebConfirmationRequest } from '../features/web-confirmation.ts';+import type { ThemePreference, ResolvedTheme } from '../ui/preferences';+export type { HostCapabilities, HostKind, HostTransport } from './types.ts';+export { plaintextConsole } from './console.ts';+let override: HostTransport | undefined;+let shellCapabilities: HostCapabilities | undefined;+export function hostKind(): HostKind {+ if (override) return override.capabilities().host;+ if (typeof window === 'undefined' || !('__TAURI_INTERNALS__' in window)) return 'console';+ return '__HIROUTE_SHELL__' in window ? 'shell-console' : 'tauri';+}+export const isTauriHost = () => hostKind() !== 'console';+export function hostCapabilities(): HostCapabilities {+ if (override) return override.capabilities();+ if (hostKind() === 'tauri') return { host: 'tauri', platform: 'macos', updates: true, cli_entry: true, quit: true, titlebar: true, login_start: true, directory_reveal: 'native' };+ return hostKind() === 'shell-console' ? shellCapabilities ?? { ...browserCapabilities, host: 'shell-console', platform: 'windows' } : consoleCapabilities();+}+/** Explicit seam for the browser harness. It does not change server authority. */+export function setHostTransport(transport: HostTransport | undefined): void { override = transport; }+export async function initializeShellHost(): Promise<void> {+ if (override) return;+ if (hostKind() === 'shell-console') shellCapabilities = await (await import('@tauri-apps/api/core')).invoke<HostCapabilities>('shell_capabilities');+}+function externalUrl(value: unknown): string {+ if (typeof value !== 'string' || !value || value.length > 2048 || /[\s\u0000-\u001f\u007f]/u.test(value)) throw { kind: 'native', code: 'EXTERNAL_URL_INVALID' };+ const url = new URL(value);+ if (!['http:', 'https:'].includes(url.protocol) || !url.host || url.username || url.password) throw { kind: 'native', code: 'EXTERNAL_URL_SCHEME_DENIED' };+ return value;+}+async function browserCall(command: string, args: Record<string, unknown>): Promise<unknown> {+ if (command === 'open_external_url') {+ const anchor = document.createElement('a'); anchor.href = externalUrl(args.url); anchor.target = '_blank'; anchor.rel = 'noopener noreferrer'; anchor.click(); return;+ }+ if (command === 'save_classifier_openapi') {+ const source = (await import('../../../../decision-extensions/api/decision.openapi.json?raw')).default;+ const url = URL.createObjectURL(new Blob([source], { type: 'application/json' }));+ const anchor = document.createElement('a'); anchor.href = url; anchor.download = 'hiroute-decision.openapi.json'; anchor.rel = 'noopener noreferrer'; anchor.click();+ window.setTimeout(() => URL.revokeObjectURL(url), 0); return 'saved';+ }+ if (command === 'open_diagnostic_directory' || command === 'open_startup_recovery_directory') {+ const caps = hostCapabilities(); const path = command === 'open_diagnostic_directory' ? caps.diagnostic_directory : caps.recovery_directory;+ if (!path) throw { kind: 'native', code: 'APP_DATA_UNAVAILABLE' };+ window.dispatchEvent(new CustomEvent('hiroute-host-path', { detail: path })); return;+ }+ return consoleTransport.call(command, args);+}+export async function invoke<T>(command: string, args: Record<string, unknown> = {}): Promise<T> {+ if (override) {+ if (override.capabilities().host === 'console' && ['open_external_url', 'save_classifier_openapi', 'open_diagnostic_directory', 'open_startup_recovery_directory'].includes(command)) return browserCall(command, args) as Promise<T>;+ return override.call<T>(command, args);+ }+ if (hostKind() === 'tauri') return (await import('./tauri.ts')).tauriTransport.call<T>(command, args);+ if (hostKind() === 'shell-console' && (command.startsWith('update_') || command.startsWith('login_start_') || ['open_external_url', 'save_classifier_openapi', 'open_in_browser', 'restart_service', 'reconnect'].includes(command))) return (await import('@tauri-apps/api/core')).invoke<T>(`shell_${command}`, args);+ return browserCall(command, args) as Promise<T>;+}+export async function listenForHostConfirmations(onRequest: (request: WebConfirmationRequest) => void): Promise<() => void> { return hostKind() === 'tauri' ? (await import('./tauri.ts')).listenNativeConfirmation(onRequest) : () => {}; }+export async function syncHostTheme(preference: ThemePreference, resolved: ResolvedTheme): Promise<'skipped' | 'synced'> { if (hostKind() !== 'tauri') return 'skipped'; await (await import('./tauri.ts')).syncNativeTheme(preference, resolved); return 'synced'; }+export async function nativeClipboard(value: string): Promise<boolean> { if (hostKind() !== 'tauri') return false; return (await import('./tauri.ts')).writeNativeClipboard(value); }diff --git a/apps/desktop/src/host/tauri.ts b/apps/desktop/src/host/tauri.tsnew file mode 100644index 00000000..f41a687e--- /dev/null+++ b/apps/desktop/src/host/tauri.ts@@ -0,0 +1,11 @@+import { invoke, isTauri } from '@tauri-apps/api/core';+import type { HostTransport } from './types.ts';+import type { ThemePreference, ResolvedTheme } from '../ui/preferences';+import { listenForWebConfirmations, type WebConfirmationRequest } from '../features/web-confirmation.ts';+export const tauriTransport: HostTransport = {+ call: (command, args) => invoke(command, args),+ capabilities: () => ({ host: 'tauri', platform: 'macos', updates: true, cli_entry: true, quit: true, titlebar: true, login_start: true, directory_reveal: 'native' }),+};+export async function writeNativeClipboard(text: string): Promise<boolean> { if (!isTauri()) return false; await (await import('@tauri-apps/plugin-clipboard-manager')).writeText(text); return true; }+export async function syncNativeTheme(preference: ThemePreference, resolved: ResolvedTheme): Promise<void> { await (await import('@tauri-apps/api/window')).getCurrentWindow().setTheme(preference === 'system' ? null : resolved); }+export async function listenNativeConfirmation(onRequest: (request: WebConfirmationRequest) => void): Promise<() => void> { return listenForWebConfirmations((await import('@tauri-apps/api/webview')).getCurrentWebview(), onRequest); }diff --git a/apps/desktop/src/host/types.ts b/apps/desktop/src/host/types.tsnew file mode 100644index 00000000..6f9219dc--- /dev/null+++ b/apps/desktop/src/host/types.ts@@ -0,0 +1,27 @@+export type HostKind = 'tauri' | 'console' | 'shell-console';+export type HostCapabilities = {+ host: HostKind;+ platform: string;+ updates: boolean;+ cli_entry: boolean;+ quit: boolean;+ titlebar: boolean;+ login_start: boolean;+ directory_reveal: 'native' | 'path';+ diagnostic_directory?: string;+ recovery_directory?: string;+};+export type HostTransport = {+ call<T>(command: string, args?: Record<string, unknown>): Promise<T>;+ capabilities(): HostCapabilities;+};+export type ConsoleIdentity = {+ session: { id: string; credential_kind: string; token_id: string | null; expires: number };+ transport: 'loopback' | 'network_plaintext';+ assets_available: boolean;+ capabilities: HostCapabilities;+};+export const browserCapabilities: HostCapabilities = {+ host: 'console', platform: 'browser', updates: false, cli_entry: false,+ quit: false, titlebar: false, login_start: false, directory_reveal: 'path',+};diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsxindex 69789690..ec536ca2 100644--- a/apps/desktop/src/main.tsx+++ b/apps/desktop/src/main.tsx@@ -1,4 +1,5 @@import React from 'react';+import { ConsoleRoot } from './host/ConsoleRoot';import { createRoot } from 'react-dom/client';import { DesktopApp } from './product/DesktopApp';import { RenderFailureBoundary } from './ui/RenderFailureBoundary';@@ -6,6 +7,6 @@ import './occami/styles.css';createRoot(document.getElementById('root')!).render(<RenderFailureBoundary>- <DesktopApp />+ <ConsoleRoot><DesktopApp /></ConsoleRoot></RenderFailureBoundary>,);diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.cssindex 5609fb42..83a7de9e 100644--- a/apps/desktop/src/occami/styles.css+++ b/apps/desktop/src/occami/styles.css@@ -1,3 +1,4 @@+@import './styles/console.css';/* Shared product styles. */@import './styles/tokens.css';@import './styles/shell.css';diff --git a/apps/desktop/src/occami/styles/console.css b/apps/desktop/src/occami/styles/console.cssnew file mode 100644index 00000000..01dd67e0--- /dev/null+++ b/apps/desktop/src/occami/styles/console.css@@ -0,0 +1,31 @@+.hr-ui { --hr-text-scale: 1; }+.console-product { width: 100%; height: 100%; min-height: 0; }+.hr-ui[data-text-scale='1.5'] { --hr-text-scale: 1.5; }+.hr-ui[data-text-scale='2'] { --hr-text-scale: 2; }+.message[hidden] { display: none !important; }+.quality-score-bar > svg { display: block; width: 100%; height: 100%; }+.quality-score-bar rect { fill: var(--accent); }+.console-entry { min-height: 100dvh; height: 100dvh; overflow-y: auto; display: grid; place-items: center; padding: 24px; }+.console-entry-card { width: min(100%, 520px); min-width: 0; padding: 28px; border: 1px solid var(--border); border-radius: 16px; background: var(--panel); display: flex; flex-direction: column; gap: 18px; }+.console-entry-brand { display: flex; align-items: center; gap: 12px; }+.console-entry-card h1 { margin: 0; font-size: calc(24px * var(--hr-text-scale)); line-height: 1.3; }+.console-entry-card p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; }+.console-entry-card code { overflow-wrap: anywhere; }+.console-login { display: flex; flex-direction: column; gap: 16px; min-width: 0; }+.console-login .input, .console-path { width: 100%; min-width: 0; }+.console-entry-preferences { display: flex; flex-wrap: wrap; gap: 8px; }+.console-entry-error { color: var(--text-muted); }+.console-transport-bar { position: sticky; top: 0; z-index: 15; display: flex; align-items: center; gap: 12px; padding: 12px 18px; background: var(--panel-high); border-bottom: 1px solid var(--border); }+.console-transport-bar > div { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 4px; }+.console-transport-bar .btn { flex-shrink: 0; }+.console-transport-bar span { color: var(--text-muted); font-size: calc(12px * var(--hr-text-scale)); line-height: 1.5; }+.console-transport-bar.plaintext { border-bottom-width: 2px; }+.host-console .main, .host-shell-console .main { display: flex; flex-direction: column; }+.host-console .main > div:not([hidden]), .host-shell-console .main > div:not([hidden]) { height: auto; flex: 1; min-height: 0; }+.host-console .main > div.console-transport-bar, .host-shell-console .main > div.console-transport-bar,+.host-console .main > div.callout, .host-shell-console .main > div.callout { flex: 0 0 auto; }+.console-secret-warning { margin: 8px 0; padding: 10px 12px; border-left: 3px solid var(--accent); background: var(--panel-high); color: var(--text-muted); font-size: calc(13px * var(--hr-text-scale)); line-height: 1.6; white-space: normal; }+.host-console .window-controls, .host-shell-console .window-controls { display: none; }+.clipboard-probe { position: fixed; opacity: 0; }+.clipboard-manual { width: min(90vw, 640px); max-height: 85dvh; overflow: auto; padding: 24px; border: 1px solid; border-radius: 12px; }+.clipboard-manual textarea { display: block; width: 100%; min-height: 140px; margin: 16px 0; resize: vertical; }diff --git a/apps/desktop/src/occami/styles/pages.css b/apps/desktop/src/occami/styles/pages.cssindex 3e3c09a0..6dbef7b4 100644--- a/apps/desktop/src/occami/styles/pages.css+++ b/apps/desktop/src/occami/styles/pages.css@@ -272,6 +272,7 @@ button.list-row { width: 100%; border-top: 0; border-right: 0; border-left: 0; c.source-tabs { display: flex; gap: 4px; overflow-x: auto; }.source-tab { min-height: calc(30px * var(--hr-text-scale)); padding: 0 10px; border: 0; border-radius: 7px; background: transparent; color: var(--text-muted); font-size:calc(12px * var(--hr-text-scale)); font-weight: 620; white-space: nowrap; }.source-tab.active { background: var(--bg-active); color: var(--text); }+.model-view-switch { justify-self: start; max-width: 100%; }.score-stars { color: var(--yellow); letter-spacing: 1px; }.price-unknown { color: var(--yellow); }diff --git a/apps/desktop/src/occami/styles/v3.css b/apps/desktop/src/occami/styles/v3.cssindex bf30e78c..45016a91 100644--- a/apps/desktop/src/occami/styles/v3.css+++ b/apps/desktop/src/occami/styles/v3.css@@ -8,7 +8,7 @@.review-controls label{display:flex;align-items:center;gap:6px;white-space:nowrap;color:var(--text-muted);}.review-controls .select{height:30px;font-size:calc(12px * var(--hr-text-scale));width:auto;min-width:115px;padding:0 28px 0 10px;}.review-controls .btn{font-size:calc(12px * var(--hr-text-scale));min-height:30px;}-.v3-home{max-width:1080px;margin:0 auto;padding:8px 10px 36px;display:grid;gap:22px;}+.v3-home{max-width:1080px;margin:0 auto;padding:8px 10px 36px;display:grid;grid-template-columns:minmax(0,1fr);gap:22px;}.v3-welcome{padding:24px 0 18px;max-width:750px;}.v3-welcome .eyebrow{color:var(--accent-bright);font-size:calc(12px * var(--hr-text-scale));letter-spacing:.04em;}.v3-welcome h1{font-size:calc(clamp(27px,3vw,39px) * var(--hr-text-scale));line-height:1.45;letter-spacing:-.035em;white-space:pre-line;margin:20px 0 14px;font-weight:660;}@@ -29,6 +29,7 @@.v3-running p,.v3-ready p{color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale));margin:6px 0 0;}.v3-attention>.btn{width:100%;justify-content:flex-start;padding:18px;}.v3-home .surface-header h2{margin:0;font-size:calc(15px * var(--hr-text-scale));font-weight:600;}+.v3-home .native-list{grid-template-columns:minmax(0,1fr);}.v3-recent{min-height:83px;padding:18px 24px;gap:16px;}.v3-recent .row-title{font-size:calc(14px * var(--hr-text-scale));}.v3-recent .row-meta{margin-top:7px;font-size:calc(12px * var(--hr-text-scale));}diff --git a/apps/desktop/src/plan-editor-errors.ts b/apps/desktop/src/plan-editor-errors.tsindex 323c4c9d..c4d6ba4a 100644--- a/apps/desktop/src/plan-editor-errors.ts+++ b/apps/desktop/src/plan-editor-errors.ts@@ -61,6 +61,7 @@ export function planErrorMessage(error: unknown, language: 'zh' | 'en'): stringPLAN_UNCHANGED: ['没有待发布更改。', 'No changes to publish.'],EDITOR_INVALID: ['请检查名称、使用场景及模型设置,当前输入已保留。', 'Check the name, purpose and model settings. Your input is retained.'],INVALID_ARGUMENTS: ['部分路由设置未通过校验,请检查输入后重试。', 'Some routing settings failed validation. Check your input and retry.'],+ REVISION_CONFLICT: ['另一会话更改了此路由。已重新读取当前状态,你的草稿已保留。请核对最新配置后重新编辑并提交。', 'Another session changed this route. The current state was reloaded and your draft is retained. Review the latest configuration before editing and submitting again.'],CONFLICT: ['配置已在其他地方变化,请重新读取后再提交。当前输入已保留。', 'The configuration changed elsewhere. Reload before submitting. Your input is retained.'],QODER_MODEL_BUDGET_CONFLICT: ['新预算低于 Qoder 当前已接入模型声明的容量。请先在 Agent 页面停用 Qoder 的模型路由,再发布此计划并重新配置模型路由;任务协作无需停用。当前输入已保留。', 'The new budget is below the capacity declared by the current Qoder model connection. Disable Qoder model routing on the Agent page, publish this plan, then configure model routing again. Task collaboration can stay enabled. Your input is retained.'],AGENT_MODEL_BUDGET_CONFLICT: ['已接入的 Agent 模型路由容量受保护。请读取连接状态,调整受影响的模型路由后重新发布。任务协作无需停用,当前输入已保留。', 'Installed Agent model routing capacity is protected. Read connection status and adjust the affected model routing before publishing again. Task collaboration can stay enabled. Your input is retained.'],diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsxindex 139e6bb3..6fe3233e 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -1,3 +1,4 @@+import { randomId } from './random-id.ts';import { candidateUnavailableMessage, type UnavailableCandidate } from './plan-candidate-availability';import type { OpenDecisionConnection } from './features/decision-services/presentation';import { BranchRoutingEditor } from './features/decision-services/BranchRoutingEditor';@@ -18,7 +19,7 @@ import { PlanRuntimeSettings } from './features/PlanRuntimeSettings';import { confirmSaveDraftOrDiscard, useDiscardGuard } from './ui/discard-guard';import { resolvePersistedEditor, type PersistedEditor, type PersistenceIdentity, type PlanOperation } from './plan-editor-persistence';import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from './host';export type Selection = { binding_id: string; reasoning?: { kind: 'profile'; profile: string } | { kind: 'toggle'; enabled: boolean } | { kind: 'budget'; tokens: number } };type Mode = 'fixed_model' | 'smart_saving' | 'free_first' | 'custom_branches';type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness'; protocol: 'responses' | 'messages' };@@ -124,7 +125,7 @@ export const PlanEditor = forwardRef<PlanEditorHandle, PlanEditorProps>(functionconst LoadedPlanEditor = forwardRef<PlanEditorHandle, PlanEditorProps & { initialEditor: Editor; initialHead: number | null }>(function LoadedPlanEditor({ initialEditor, initialHead, plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, refreshVersion = 0, usedBy = [], onOpenAgent, onOpenSession, onOpenServices, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {const en = language === 'en', text = (zh: string, eng: string) => en ? eng : zh;const [editor, setEditor] = useState<Editor>(() => structuredClone(initialEditor));- const [draftId] = useState(() => draft?.draft_id ?? 'draft/' + crypto.randomUUID());+ const [draftId] = useState(() => draft?.draft_id ?? 'draft/' + randomId());const [base, setBase] = useState(() => ({ expected_head_revision: initialHead, expected_draft_revision: draft?.revision ?? null }));const [options, setOptions] = useState<Options | null>(null), [busy, setBusy] = useState(false), [error, setError] = useState('');const [baseline, setBaseline] = useState(() => JSON.stringify(editor));@@ -323,7 +324,7 @@ const LoadedPlanEditor = forwardRef<PlanEditorHandle, PlanEditorProps & { initia} else onClose();return true;}- } catch (e) { if (planErrorCode(e) === 'PLAN_UNCHANGED') setNotice(planErrorMessage(e, language)); else reportError(e); }+ } catch (e) { if (['REVISION_CONFLICT', 'PLAN_HEAD_STALE', 'DRAFT_REVISION_STALE'].includes(planErrorCode(e))) await onDone(); if (planErrorCode(e) === 'PLAN_UNCHANGED') setNotice(planErrorMessage(e, language)); else reportError(e); }finally { setBusy(false); }return false;}diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsxindex ba6bfc12..d66e72b0 100644--- a/apps/desktop/src/product/DesktopApp.tsx+++ b/apps/desktop/src/product/DesktopApp.tsx@@ -1,9 +1,12 @@+import { randomId } from '../random-id.ts';+import { hostCapabilities } from '../host/index.ts';+import { HostNotices } from '../host/ConsoleUi';import type { DecisionIntent, OpenDecisionConnection } from '../features/decision-services/presentation';import type { DecisionService } from '../features/decision-services/types';import { DecisionServicesPage } from '../features/decision-services/DecisionServicesPage';import { requestEditorReplacement } from '../ui/discard-guard';import { useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import { Agents } from '../agents';import type { AgentTask, AgentTaskRead } from '../features/AgentTasks';import { Sessions } from '../features/Sessions';@@ -347,7 +350,7 @@ export function DesktopApp() {if (!await requestEditorReplacement('decisions')) return;decisionReturn.current = select;setReturningToRoute(true);- setDecisionIntent({ key: crypto.randomUUID(), kind });+ setDecisionIntent({ key: randomId(), kind });setModelTab('decisions');openPage('models');};@@ -409,14 +412,14 @@ export function DesktopApp() {setNotice('');if (modelTab === 'decisions' && !await requestEditorReplacement('models')) return;setModelTab('general');- setModelIntent({ key: `models/${crypto.randomUUID()}`, ...intent });+ setModelIntent({ key: `models/${randomId()}`, ...intent });openPage('models');}async function showRouting(editor?: RoutingEditorIntent | null, routingNotice?: string) {if (!await allowPageChange('routing', true)) return;setNotice('');- setRoutingIntent({ key: `routing/${crypto.randomUUID()}`, editor, notice: routingNotice });+ setRoutingIntent({ key: `routing/${randomId()}`, editor, notice: routingNotice });openPage('routing');}@@ -483,7 +486,7 @@ export function DesktopApp() {const generation = ++taskReadGeneration.current;taskPager.current = null;setTaskRead({ status: 'loading' });- setAgentIntent({ key: `agents/${crypto.randomUUID()}`, tab: 'tasks', taskId });+ setAgentIntent({ key: `agents/${randomId()}`, tab: 'tasks', taskId });openPage('agents');const locator: WorkerTaskLocator = { taskId, runId };try {@@ -517,19 +520,19 @@ export function DesktopApp() {}if (action.kind === 'view-agents') {if (!await allowPageChange('agents', true)) return;- setAgentIntent({ key: `agents/${crypto.randomUUID()}` });+ setAgentIntent({ key: `agents/${randomId()}` });openPage('agents');return;}if (action.kind === 'create-plan') {- showRouting({ key: crypto.randomUUID() });+ showRouting({ key: randomId() });return;}if (action.kind === 'configure-agent') {if (!await allowPageChange('agents', true)) return;setNotice('');setAgentIntent({- key: `agents/${crypto.randomUUID()}`,+ key: `agents/${randomId()}`,agentId: action.agentId,facet: action.facet ?? 'model',});@@ -558,14 +561,14 @@ export function DesktopApp() {if (action.kind === 'open-session') {if (!await allowPageChange('sessions')) return;setNotice('');- setSessionIntent({ key: `sessions/${crypto.randomUUID()}`, sessionId: action.sessionId });+ setSessionIntent({ key: `sessions/${randomId()}`, sessionId: action.sessionId });openPage('sessions');return;}if (action.kind === 'view-all-sessions') {if (!await allowPageChange('sessions')) return;setNotice('');- setSessionIntent({ key: `sessions/${crypto.randomUUID()}`, sessionId: null });+ setSessionIntent({ key: `sessions/${randomId()}`, sessionId: null });openPage('sessions');return;}@@ -576,7 +579,7 @@ export function DesktopApp() {if (action.kind === 'view-all-tasks') {if (!await allowPageChange('agents', true)) return;setNotice('');- setAgentIntent({ key: `agents/${crypto.randomUUID()}`, tab: 'tasks' });+ setAgentIntent({ key: `agents/${randomId()}`, tab: 'tasks' });openPage('agents');void loadTaskHistory(true);return;@@ -605,9 +608,9 @@ export function DesktopApp() {theme={preferences.resolvedTheme}textScale={preferences.textScale}>- <div className="app-window">+ <div className={`app-window host-${hostCapabilities().host}`}><header className="titlebar" data-tauri-drag-region="deep" onMouseDown={event => {- if (event.button !== 0 || event.detail !== 2) return;+ if (!hostCapabilities().titlebar || event.button !== 0 || event.detail !== 2) return;event.preventDefault();event.stopPropagation();void invoke('perform_titlebar_double_click');@@ -629,6 +632,7 @@ export function DesktopApp() {onOpenSettings={() => void openPageSafely('settings')}/><main className="main">+ <HostNotices language={language} />{notice && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="info" /><span>{notice}</span></div></div>}{upgradePhaseText && <div className="callout" role="status" aria-live="polite"><UiIcon name="info" /><div><strong>{upgradePhaseText}</strong><p>{language === 'zh' ? '请等待升级完成;请保留原数据与完整安装包。' : 'Wait for the upgrade to finish. Keep the original data and complete installation package.'}</p></div></div>}{startupFailure && <div className="callout bad" role="alert" data-error-code={startupFailure.code}>@@ -674,7 +678,7 @@ export function DesktopApp() {const plan = home.desktopSnapshot?.catalog.plans.find(item => item.agent_plan_id === planId);if (plan) void showRouting({ key: plan.agent_plan_id, plan });}}- onCreatePlan={bindingId => void showRouting({ key: `routing/${crypto.randomUUID()}`, initialBindingId: bindingId })}+ onCreatePlan={bindingId => void showRouting({ key: `routing/${randomId()}`, initialBindingId: bindingId })}/></div>}{visited.has('models') && <div hidden={page !== 'models' || modelTab !== 'decisions'}><DecisionServicesPagelanguage={language} active={page === 'models' && modelTab === 'decisions'}@@ -700,8 +704,8 @@ export function DesktopApp() {initialEditor={routingIntent.editor}notice={routingIntent.notice}onRefresh={async () => { setObserving(true); await home.refreshDesktop(); setRefreshVersion(v => v + 1); }}- onOpenAgent={agentId => { void (async () => { if (!await allowPageChange('agents')) return; setAgentIntent({ key: `agents/${crypto.randomUUID()}`, agentId }); openPage('agents'); })(); }}- onOpenSession={(sessionId, requestId) => { void (async () => { if (!await allowPageChange('sessions')) return; setSessionIntent({ key: `sessions/${crypto.randomUUID()}`, sessionId, requestId, returnToQuality: true }); openPage('sessions'); })(); }}+ onOpenAgent={agentId => { void (async () => { if (!await allowPageChange('agents')) return; setAgentIntent({ key: `agents/${randomId()}`, agentId }); openPage('agents'); })(); }}+ onOpenSession={(sessionId, requestId) => { void (async () => { if (!await allowPageChange('sessions')) return; setSessionIntent({ key: `sessions/${randomId()}`, sessionId, requestId, returnToQuality: true }); openPage('sessions'); })(); }}onOperation={value => acceptOperation(value, { kind: 'routing' })}/></div>}{visited.has('agents') && <div hidden={page !== 'agents'}><Agents@@ -728,11 +732,11 @@ export function DesktopApp() {onLoadMoreTasks={() => loadTaskHistory(false)}onReadTask={hydrateTask}onLoadTaskResult={readWorkerTaskResultPage}- onCreatePlan={() => void showRouting({ key: `routing/${crypto.randomUUID()}` })}+ onCreatePlan={() => void showRouting({ key: `routing/${randomId()}` })}onOpenTaskSession={sessionId => {void (async () => {if (!await allowPageChange('sessions')) return;- setSessionIntent({ key: `sessions/${crypto.randomUUID()}`, sessionId });+ setSessionIntent({ key: `sessions/${randomId()}`, sessionId });openPage('sessions');})();}}@@ -760,7 +764,7 @@ export function DesktopApp() {onOpenSessions={() => {void (async () => {if (!await allowPageChange('sessions')) return;- setSessionIntent({ key: `sessions/${crypto.randomUUID()}`, sessionId: null });+ setSessionIntent({ key: `sessions/${randomId()}`, sessionId: null });openPage('sessions');})();}}diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsxindex 6ff6140b..a24de58d 100644--- a/apps/desktop/src/product/ModelManagementPage.tsx+++ b/apps/desktop/src/product/ModelManagementPage.tsx@@ -1,7 +1,8 @@+import { randomId } from '../random-id.ts';import { managementLoadFailureCopy, subscriptionFailureCopy } from '../features/models/subscription-copy';import { requestEditorReplacement } from '../ui/discard-guard';import { useEffect, useMemo, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import { SubscriptionProxySettings } from '../features/SubscriptionProxySettings';import { ModelConnectionForm } from '../features/model-connections/ModelConnectionForm';import { blankModel } from '../features/model-connections/form-support';@@ -123,7 +124,7 @@ export function newModelConnectionDraft(kind: 'known' | 'custom' | 'free' = 'cusreturn {entry_kind: kind === 'free' ? 'free_api_key' : known ? 'preset_api' : 'custom_api',candidate_ref: null,- lineage_ref: `lineage/native/${crypto.randomUUID()}`,+ lineage_ref: `lineage/native/${randomId()}`,display_name: '',existing_source_id: null,expected_source_revision: null,@@ -894,7 +895,7 @@ export function ModelManagementPage({async function loadAppendModels(source: ManagedSource) {const current = await invoke<ManagementSnapshot>('compute_management_snapshot');if (!current.sources.some(item => item.source_id === source.source_id && item.revision === source.revision)) throw { code: 'SOURCE_CHANGED' };- const checkId = `append/${crypto.randomUUID()}`;+ const checkId = `append/${randomId()}`;const checked = await invoke<ModelConnectionCheckView>('check_saved_model_connection', { request: {source_id: source.source_id, expected_source_revision: source.revision, edit_revision: 1, check_id: checkId,} });@@ -912,7 +913,7 @@ export function ModelManagementPage({expected_source_revision: source.revision,...savedSourceConnectionFields(source),models: source.models.map(model => ({- client_id: crypto.randomUUID(), upstream_model_id: model.upstream_model_id,+ client_id: randomId(), upstream_model_id: model.upstream_model_id,display_name: model.display_name, catalog_configuration_id: null,membership: 'user_declared' as const,capabilities: model.capabilities ?? blankModel(model.upstream_model_id, model.display_name).capabilities,diff --git a/apps/desktop/src/product/RoutingPage.tsx b/apps/desktop/src/product/RoutingPage.tsxindex 3e8a0962..c76859b7 100644--- a/apps/desktop/src/product/RoutingPage.tsx+++ b/apps/desktop/src/product/RoutingPage.tsx@@ -1,6 +1,7 @@+import { randomId } from '../random-id.ts';import type { OpenDecisionConnection } from '../features/decision-services/presentation';import { useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import { PlanEditor, type Draft, type Plan, type PlanEditorHandle, type PlanEditorMemory } from '../plan-editor';import { persistenceTargetWasSuperseded, resolvePersistedEditor, type PersistenceIdentity } from '../plan-editor-persistence';import { requestEditorReplacement } from '../ui/discard-guard';@@ -111,7 +112,7 @@ export function RoutingPage({ language, active = true, refreshVersion = 0, snapssetDirty(false);setPendingPersistence(null);setPersistedNotice('');- setEditor({ key: crypto.randomUUID(), editingMemory: {} });+ setEditor({ key: randomId(), editingMemory: {} });setShowList(false);}const usedBy = editor?.plan ? (agentSnapshot?.agents ?? []).flatMap(agent => {diff --git a/apps/desktop/src/product/SettingsPage.tsx b/apps/desktop/src/product/SettingsPage.tsxindex 0b8d5cad..38703dee 100644--- a/apps/desktop/src/product/SettingsPage.tsx+++ b/apps/desktop/src/product/SettingsPage.tsx@@ -1,7 +1,9 @@-import { invoke } from '@tauri-apps/api/core';+import { hostCapabilities } from '../host/index.ts';+import { invoke } from '../host/index.ts';import { useEffect, useState } from 'react';import { DiagnosticsSettings } from '../features/diagnostics/DiagnosticsSettings';import { UpdatesSettings } from '../features/UpdatesSettings';+import { ShellHostSettings } from '../features/ShellHostSettings';import { safeDiagnosticCode } from '../error-code';import { ProductPage } from '../ui';import type { Language, LanguagePreference, ThemePreference } from '../ui/preferences';@@ -89,7 +91,7 @@ export function SettingsPage(props: SettingsPageProps) {let current = true;setCliError('');setListenerError('');- void invoke<CliEntryView>('cli_entry_status').then(value => {+ if (hostCapabilities().cli_entry) void invoke<CliEntryView>('cli_entry_status').then(value => {if (current) setCliEntry(value);}).catch(error => {if (current) setCliError(safeDiagnosticCode(error, 'CLI_ENTRY_UNAVAILABLE'));@@ -169,6 +171,7 @@ export function SettingsPage(props: SettingsPageProps) {return <ProductPage title={text('设置', 'Settings')} subtitle={text('偏好与本机服务', 'Preferences and local service')}><div className="settings-wrap">+ {hostCapabilities().host === 'shell-console' && <ShellHostSettings active={props.active} language={props.language} />}<section className="settings-group"><h2>{text('偏好', 'Preferences')}</h2><div className="settings-list"><div className="settings-row"><div className="settings-copy"><strong>{text('语言', 'Language')}</strong><span>{text('界面与状态文案', 'Interface and status text')}</span></div><div className="segmented">{(['system', 'zh', 'en'] as const).map(language => <button type="button" key={language} className={`segment ${props.languagePreference === language ? 'active' : ''}`} aria-pressed={props.languagePreference === language} onClick={() => props.onLanguageChange(language)}>{language === 'system' ? text('跟随系统', 'System') : language === 'zh' ? '中文' : 'English'}</button>)}</div>@@ -189,8 +192,8 @@ export function SettingsPage(props: SettingsPageProps) {<button className="btn" type="button" onClick={() => props.onOpenSessions()}>{text('查看会话', 'View sessions')}</button></div></div></section><DiagnosticsSettings active={props.active} language={props.language} />- <UpdatesSettings active={props.active} language={props.language} onServiceChanged={props.onServiceChanged} />- <section className="settings-group"><h2>CLI</h2><div className="settings-list"><div className="settings-row">+ {hostCapabilities().updates && <UpdatesSettings active={props.active} language={props.language} onServiceChanged={props.onServiceChanged} />}+ {hostCapabilities().cli_entry && <section className="settings-group"><h2>CLI</h2><div className="settings-list"><div className="settings-row"><div className="settings-copy"><strong>{text('终端入口', 'Terminal entry')}</strong><span>{cliEntry === null? text('正在检查 ~/.local/bin/hiroute', 'Checking ~/.local/bin/hiroute'): text(`状态:${cliEntry.state} · ${cliEntry.entry_path}`, `State: ${cliEntry.state} · ${cliEntry.entry_path}`)}</span>@@ -202,7 +205,7 @@ export function SettingsPage(props: SettingsPageProps) {{cliEntry?.state !== 'valid' && <button className="btn" type="button" disabled={cliBusy || cliEntry?.state === 'conflict'} onClick={() => void updateCliEntry('cli_entry_install')}>{cliEntry?.state === 'broken' ? text('修复', 'Repair') : text('安装', 'Install')}</button>}{cliEntry?.state === 'valid' && <button className="btn" type="button" disabled={cliBusy} onClick={() => void updateCliEntry('cli_entry_remove')}>{text('移除', 'Remove')}</button>}</div>- </div>{cliError && <div className="settings-inline-error" role="status">{text(`CLI 入口不可用(${cliError})`, `CLI entry unavailable (${cliError})`)}</div>}</div></section>+ </div>{cliError && <div className="settings-inline-error" role="status">{text(`CLI 入口不可用(${cliError})`, `CLI entry unavailable (${cliError})`)}</div>}</div></section>}<section className="settings-group"><h2>Gateway</h2><div className="settings-list"><div className="settings-row"><div className="settings-copy"><strong>{text('监听范围', 'Listener access')}</strong><span>{listener?.config.applied? text(`已应用 ${listener.config.applied.address}:${listener.config.applied.port} · ${listener.ready ? 'ready' : 'not ready'}`, `Applied ${listener.config.applied.address}:${listener.config.applied.port} · ${listener.ready ? 'ready' : 'not ready'}`)diff --git a/apps/desktop/src/product/use-desktop-home.ts b/apps/desktop/src/product/use-desktop-home.tsindex cde9f31e..372be730 100644--- a/apps/desktop/src/product/use-desktop-home.ts+++ b/apps/desktop/src/product/use-desktop-home.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';+import { invoke } from '../host/index.ts';import type { AgentSnapshot } from '../agents';import {beginDomainRead,diff --git a/apps/desktop/src/random-id.ts b/apps/desktop/src/random-id.tsnew file mode 100644index 00000000..11e43fec--- /dev/null+++ b/apps/desktop/src/random-id.ts@@ -0,0 +1,8 @@+/** UUID v4 also works on explicitly allowed plaintext console connections. */+export function randomId(): string {+ const bytes = crypto.getRandomValues(new Uint8Array(16));+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+}diff --git a/apps/desktop/src/ui/PresentationRoot.tsx b/apps/desktop/src/ui/PresentationRoot.tsxindex 61eda603..70c40df5 100644--- a/apps/desktop/src/ui/PresentationRoot.tsx+++ b/apps/desktop/src/ui/PresentationRoot.tsx@@ -21,7 +21,6 @@ export function PresentationRoot({data-theme={theme}data-text-scale={String(textScale)}lang={language === 'zh' ? 'zh-CN' : 'en'}- style={{ '--hr-text-scale': textScale } as React.CSSProperties}>{children}</div>diff --git a/apps/desktop/src/ui/WebConfirmationHost.tsx b/apps/desktop/src/ui/WebConfirmationHost.tsxindex ca4defa6..7f55f14b 100644--- a/apps/desktop/src/ui/WebConfirmationHost.tsx+++ b/apps/desktop/src/ui/WebConfirmationHost.tsx@@ -1,10 +1,9 @@-import { invoke } from '@tauri-apps/api/core';-import { getCurrentWebview } from '@tauri-apps/api/webview';+import { invoke } from '../host/index.ts';+import { listenForHostConfirmations } from '../host/index.ts';import { useEffect, useState } from 'react';import {enqueueWebConfirmation,isWebConfirmationRequest,- listenForWebConfirmations,removeWebConfirmation,type WebConfirmationRequest,} from '../features/web-confirmation';@@ -21,7 +20,7 @@ export function WebConfirmationHost() {let disposed = false;let unlisten: (() => void) | undefined;let polling = false;- void listenForWebConfirmations(getCurrentWebview(), request => {+ void listenForHostConfirmations(request => {if (disposed) return;setError('');setQueue(items => enqueueWebConfirmation(items, request));diff --git a/apps/desktop/src/ui/clipboard.ts b/apps/desktop/src/ui/clipboard.tsindex e9801ab5..55af9208 100644--- a/apps/desktop/src/ui/clipboard.ts+++ b/apps/desktop/src/ui/clipboard.ts@@ -1,31 +1,31 @@-import { isTauri } from '@tauri-apps/api/core';-import { writeText } from '@tauri-apps/plugin-clipboard-manager';+import { nativeClipboard } from '../host/index.ts';export async function copyText(value: string): Promise<void> {- if (isTauri()) {- await writeText(value);- return;- }+ if (await nativeClipboard(value)) return;+ const secure = typeof window === 'undefined' || window.isSecureContext !== false;+ if (!secure) return manualCopy(value);try {- if (navigator.clipboard?.writeText) {- await navigator.clipboard.writeText(value);- return;- }- } catch {- // Some native WebViews expose this API but cannot use it after an async save.- }+ if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(value); return; }+ } catch { /* A denied browser API retains the established exact-text copy path. */ }const previousFocus = document.activeElement as HTMLElement | null;const input = document.createElement('textarea');- input.value = value;- input.setAttribute('readonly', '');- input.style.position = 'fixed';- input.style.opacity = '0';+ input.value = value; input.className = 'clipboard-probe'; input.setAttribute('readonly', '');document.body.append(input);- try {- input.select();- if (!document.execCommand('copy')) throw new Error('CLIPBOARD_UNAVAILABLE');- } finally {- input.remove();- previousFocus?.focus();- }+ try { input.select(); if (!document.execCommand('copy')) throw new Error('CLIPBOARD_UNAVAILABLE'); }+ finally { input.remove(); previousFocus?.focus(); }+}+function manualCopy(value: string): Promise<void> {+ return new Promise((resolve, reject) => {+ const previous = document.activeElement as HTMLElement | null;+ const zh = document.querySelector('.occami-root')?.getAttribute('lang')?.startsWith('zh');+ const dialog = document.createElement('dialog'); dialog.className = 'clipboard-manual';+ const instructions = document.createElement('p'); instructions.textContent = zh ? '浏览器不允许自动复制。请选中下面的内容,然后按 Ctrl+C(Mac 为 ⌘C)复制。' : 'Automatic copying is unavailable. Select the text below, then press Ctrl+C (⌘C on Mac).';+ const input = document.createElement('textarea'); input.value = value; input.readOnly = true; input.setAttribute('aria-label', zh ? '待复制内容' : 'Text to copy');+ const close = document.createElement('button'); close.type = 'button'; close.className = 'btn'; close.textContent = zh ? '关闭' : 'Close';+ let copied = false;+ const finish = () => { dialog.close(); dialog.remove(); previous?.focus(); if (copied) resolve(); else reject(new Error('CLIPBOARD_UNAVAILABLE')); };+ input.addEventListener('copy', () => { copied = true; window.setTimeout(finish, 0); }, { once: true });+ close.addEventListener('click', finish); dialog.addEventListener('cancel', event => { event.preventDefault(); finish(); });+ dialog.append(instructions, input, close); document.body.append(dialog); dialog.showModal(); input.focus(); input.select();+ });}diff --git a/apps/desktop/src/ui/native-window-theme.ts b/apps/desktop/src/ui/native-window-theme.tsindex dd58e677..16d287eb 100644--- a/apps/desktop/src/ui/native-window-theme.ts+++ b/apps/desktop/src/ui/native-window-theme.ts@@ -1,16 +1,2 @@-import { getCurrentWindow } from '@tauri-apps/api/window';-import type { ResolvedTheme, ThemePreference } from './preferences';--function isTauriRuntime(): boolean {- return typeof window !== 'undefined'- && '__TAURI_INTERNALS__' in (window as Window & { __TAURI_INTERNALS__?: unknown });-}--export async function syncNativeWindowTheme(- preference: ThemePreference,- resolvedTheme: ResolvedTheme,-): Promise<'skipped' | 'synced'> {- if (!isTauriRuntime()) return 'skipped';- await getCurrentWindow().setTheme(preference === 'system' ? null : resolvedTheme);- return 'synced';-}+import { syncHostTheme } from '../host/index.ts';+export { syncHostTheme as syncNativeWindowTheme };diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex dbe4510a..ff472433 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -1,5 +1,23 @@# Desktop behavior tests+## Console and Windows host coverage++The V3 browser runner accepts `HIROUTE_BROWSER_TRANSPORT=console` to execute the+same required product scenarios through the browser host seam. `--console-only`+checks the production login/session pages with synthetic HTTP, Bearer/context+headers, plaintext warnings and host capabilities, and captures zh/en light/dark+at 1200×813 and 755×600. These component scenarios do not establish real daemon,+native authorization or installation acceptance.++`--shell-host-only` adds the actual Windows startup HTML/styles and production+shell settings/update states, host-only command routing and credential-free+reconnect presentation. It uses synthetic host replies and captures the same+language/theme/size matrix. Native origin ACLs, NSIS, Task/login effects and real+upgrades keep their [installed gates](../../../docs/windows-desktop-installation.md#evidence-and-release-claims).+It also distinguishes an unavailable Windows update catalog from installation+recovery, and checks the bundled local-listener recovery instructions and usable+Recheck action at both supported window sizes.+Start with the user capability, then choose the smallest layer that can observe itscontract. Node state tests explain decision rules; browser scenarios exercise theproduction React components and their wiring through synthetic IPC. Neither layer@@ -35,6 +53,7 @@ proves native authorization, persistence, process cleanup or real model calls.| Inspect models used by branch routes | `desktop.models.branch-route-references` | General-model details include regular and upgrade candidates of enabled branch routes, omit disabled routes, and open the referenced route. || Add a decision connection from an unfinished route | `desktop.decisions.route-detour` | The shell suspends the route draft, saves and returns the exact typed connection, preserves input on cancel, and never publishes automatically. || Inspect a model or open its documentation | `desktop.models.documentation-retains-input`; [model-to-route scenario](v3/browser/model-to-route-scenarios.mjs) | Local readiness does not claim inference success; browser failure retains form input; web anchors retain their default action; route creation uses the selected model. |+| Change model grouping or inspect page controls | `desktop.models.view-switch`, `desktop.presentation.control-layout`; [presentation scenarios](v3/browser/presentation-interactions.mjs) | Production styles preserve model/connection counts, selected model and visible selection. Chinese/English and light/dark checks reject browser-default buttons and horizontal overflow from long recent-session titles at the supported small window. |Task-route save scenarios also cover Pi and Qoder executor reselection: an explicitMessages choice survives clicking the selected executor and reaches the saved draft.@@ -50,6 +69,11 @@ it does not call private component callbacks. In particular, browser checks of`save_classifier_openapi` and `open_external_url` verify UI dispatch/outcomes, notthe native OS action.+For an interactive presentation regression check, open+`product-shell.html?checks=presentation` on the fixture server at 755×600 and+click **Run presentation checks**. It runs the same two required presentation+scenarios with production styles and reports each result; IPC remains mocked.+## Session quality presentationSession quality names come from the exact retained execution request (same session and request ID), then the current configuration display name when available. Opaque configuration/branch IDs belong in diagnostic tooltips, not primary labels. Mixed or unknown attribution must not be presented as one model. History gaps and partial assessment evidence remain separate visible flags; an unrated stage is not assigned a score.diff --git a/apps/desktop/tests/ui-consistency.test.mjs b/apps/desktop/tests/ui-consistency.test.mjsindex 17272daf..dd6ae2b4 100644--- a/apps/desktop/tests/ui-consistency.test.mjs+++ b/apps/desktop/tests/ui-consistency.test.mjs@@ -165,3 +165,34 @@ test('native command authority agrees across handlers, manifest and main-windowassert.ok(permission.includes(`commands.deny = ["${command}"]`), `${command}: wrong denied command`);}});++test('the product catalog covers native handlers and excludes host commands from HTTP', () => {+ const catalog = JSON.parse(read('../../crates/product-session/src/commands.json'));+ const handlers = [...read('src-tauri/src/bridge.rs').matchAll(/tauri::generate_handler!\[([\s\S]*?)\]/g)][0][1]+ .split(',').map(item => item.trim()).filter(Boolean).sort();+ const check = (catalog, handlers) => {+ assert.deepEqual(catalog.map(c => c.name).sort(), handlers);+ assert.equal(new Set(catalog.map(c => c.name)).size, catalog.length);+ assert.ok(catalog.every(c => Array.isArray(c.args) && c.result.startsWith('Result<')));+ assert.ok(catalog.find(c => c.name === 'quit_desktop').host_only);+ assert.equal(catalog.find(c => c.name === 'observation_read').host_only, false);+ };+ check(catalog, handlers);+ assert.throws(() => check(catalog.slice(1), handlers), 'missing catalog commands fail closed');+ assert.throws(() => check(catalog, handlers.slice(1)), 'missing handlers fail closed');+});++test('all product commands have a console route and host commands cannot enter it', () => {+ const catalog = JSON.parse(read('../../crates/product-session/src/commands.json'));+ const shared = read('../../crates/product-session/src/commands/dispatch.rs');+ const hostSettings = read('../../crates/daemon/src/console/host_settings.rs');+ const routes = new Set([...shared.matchAll(/"([a-z][a-z0-9_]*)"\s*=>/g)].map(item => item[1]));+ for (const name of ['gateway_listener_status', 'gateway_listener_apply', 'gateway_listener_recover', 'subscription_proxy_status', 'subscription_proxy_apply', 'diagnostic_status', 'set_diagnostic_level']) {+ assert.ok(hostSettings.includes(`"${name}"`)); routes.add(name);+ }+ const check = routes => assert.deepEqual([...routes].sort(), catalog.filter(c => !c.host_only).map(c => c.name).sort());+ check(routes);+ const broken = new Set(routes); broken.delete('observation_read');+ assert.throws(() => check(broken), 'a missing HTTP route fails the registry check');+ for (const command of catalog.filter(c => c.host_only)) assert.ok(!routes.has(command.name));+});diff --git a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjsindex 8cce13b8..d285b9a4 100644--- a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs@@ -357,7 +357,10 @@ const scenarios = [const previousNative = Object.getOwnPropertyDescriptor(window, 'isTauri');const copied = [];Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { async writeText() { throw new Error('NotAllowedError'); } } });- Object.defineProperty(document, 'execCommand', { configurable: true, value: () => { throw new Error('Browser clipboard is unavailable'); } });+ Object.defineProperty(document, 'execCommand', { configurable: true, value: () => {+ if (window.fixtureTransport !== 'console') throw new Error('Browser clipboard is unavailable');+ copied.push(document.querySelector('textarea').value); return true;+ } });Object.defineProperty(window, 'isTauri', { configurable: true, value: true });try {c().handlers['plugin:clipboard-manager|write_text'] = payload => { copied.push(payload.text); };diff --git a/apps/desktop/tests/v3/browser/agent-trust.tsx b/apps/desktop/tests/v3/browser/agent-trust.tsxindex bd74cbba..84ce6801 100644--- a/apps/desktop/tests/v3/browser/agent-trust.tsx+++ b/apps/desktop/tests/v3/browser/agent-trust.tsx@@ -1,6 +1,6 @@import React, { useState } from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import { Agents, type Agent, type AgentSnapshot, type ModelStatus } from '../../../src/agents';import type { OperationReference } from '../../../src/features/model-connections/types';import { PresentationRoot } from '../../../src/ui';diff --git a/apps/desktop/tests/v3/browser/console-entry.html b/apps/desktop/tests/v3/browser/console-entry.htmlnew file mode 100644index 00000000..67ab7b1c--- /dev/null+++ b/apps/desktop/tests/v3/browser/console-entry.html@@ -0,0 +1,3 @@+<!doctype html>+<html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Console session component scenarios</title></head>+<body><div id="root"></div><script type="module" src="./console-entry.tsx"></script></body></html>diff --git a/apps/desktop/tests/v3/browser/console-entry.tsx b/apps/desktop/tests/v3/browser/console-entry.tsxnew file mode 100644index 00000000..e8bee25c--- /dev/null+++ b/apps/desktop/tests/v3/browser/console-entry.tsx@@ -0,0 +1,69 @@+import React from 'react';+import { createRoot } from 'react-dom/client';+import { ConsoleRoot } from '../../../src/host/ConsoleRoot';+import { consoleTransport } from '../../../src/host/console';+import { hostCapabilities, setHostTransport } from '../../../src/host/index.ts';+import { browserCapabilities } from '../../../src/host/types';+import { DesktopApp } from '../../../src/product/DesktopApp';+import { mockProductInvoke } from './product-fixtures';+import '../../../src/occami/styles.css';++const query = new URLSearchParams(location.search);+const state = query.get('case') ?? 'login';+localStorage.setItem('hiroute.language', query.get('language') ?? 'zh');+localStorage.setItem('hiroute.theme', query.get('theme') ?? 'light');+sessionStorage.clear();+if (!['login', 'launch', 'rate-limited', 'session-limit'].includes(state)) sessionStorage.setItem('hiroute.console.session', 'b'.repeat(64));+if (state === 'launch') history.replaceState(null, '', '/launch?code=' + 'a'.repeat(64));+const control = {+ requests: [] as { path: string; headers: Record<string, string>; credentials?: RequestCredentials; url: string; body: unknown }[],+ expired: state === 'expired', unavailable: state === 'unavailable',+ errors: [] as string[],+ invoke: consoleTransport.call,+ hostRequests: [] as {command:string;args:Record<string,unknown>}[],+ loginEnabled: true,+ capabilities: hostCapabilities,+};+if (query.get('host') === 'shell-console') {+ const unavailable = query.get('update') === 'catalog-unavailable';+ const view = { current_version:'0.3.1',phase:unavailable?'check_failed':query.get('update')??'ready',available:unavailable?null:{version:'0.4.0',notes:{zh:'更新说明',en:'Release notes'},size:1000},downloaded_bytes:unavailable?0:1000,active_calls:1,active_tasks:2,error:unavailable?'UPGRADE_CATALOG_UNAVAILABLE':query.get('update')==='failed'?'UPGRADE_INSTALL_FAILED':null,can_install:true,package_ready:!unavailable,recovery:query.get('update')==='failed'?'service_available':null };+ setHostTransport({ capabilities:()=>({...browserCapabilities,host:'shell-console',platform:'windows',updates:true,login_start:true}),+ call:async <T,>(command:string,args:Record<string,unknown>={})=>{+ if (command.startsWith('update_') || command.startsWith('login_start_') || ['open_in_browser','restart_service','reconnect'].includes(command)) {+ control.hostRequests.push({command,args});+ if (command==='login_start_set') control.loginEnabled=Boolean(args.enabled);+ if (command==='update_cancel') { view.phase='ready';view.active_calls=0;view.active_tasks=0; }+ return (command.startsWith('update_')?view:command.startsWith('login_start_')?{enabled:control.loginEnabled}:null) as T;+ }+ return consoleTransport.call<T>(command,args);+ },+ });+}+const networkFetch = window.fetch.bind(window);+window.fetch = async (input, options) => {+ const url = new URL(String(input), location.href);+ if (!url.pathname.startsWith('/api/console/v1/')) return networkFetch(input, options);+ const headers = new Headers(options?.headers);+ control.requests.push({ path: url.pathname, headers: Object.fromEntries(headers), credentials: options?.credentials, url: location.href, body: options?.body ? JSON.parse(String(options.body)) : null });+ if (control.unavailable) throw new TypeError('Synthetic disconnected service');+ const reply = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });+ if (/\/session\/(launch|token)$/.test(url.pathname)) {+ if (state === 'rate-limited') return reply({ kind: 'native', code: 'CONSOLE_RATE_LIMITED' }, 429);+ if (state === 'session-limit') return reply({ kind: 'native', code: 'CONSOLE_SESSION_LIMIT' }, 503);+ return reply({ bearer: 'b'.repeat(64) });+ }+ if (control.expired) return reply({ kind: 'native', code: 'CONSOLE_AUTH_REQUIRED' }, 401);+ if (url.pathname.endsWith('/session')) return reply({+ session: { id: 'session/component', credential_kind: 'access_token', token_id: 'token/component', expires: 9999999999 },+ transport: query.get('host') === 'shell-console' ? 'loopback' : 'network_plaintext', assets_available: state !== 'assets', capabilities: { platform: 'linux', diagnostic_directory: '/example/diagnostics', recovery_directory: '/example/service' },+ });+ const command = decodeURIComponent(url.pathname.split('/').at(-1)!);+ const args = options?.body ? JSON.parse(String(options.body)) : {};+ if (command === 'observe_operation' || command === 'web_confirmation_snapshot') return reply(null);+ if (command === 'gateway_listener_status') return reply({config:{schema_version:'hiroute.gateway-listener/v1',desired:{address:'127.0.0.1',port_mode:'automatic'},applied:{address:'127.0.0.1',port:5829,applied_at_unix:1}},connect_address:'127.0.0.1:5829',suggested_agent_base_url:'http://127.0.0.1:5829',existing_agent_count:0,ready:true});+ if (command === 'worker_task_list') return reply({ status: 'succeeded', data: { schema: 'hiroute.worker-task-list/v1', tasks: [], next_cursor: null }, next_actions: [], error: null });+ try { return reply(await mockProductInvoke(command, args, 'ready') ?? null); }+ catch (error) { control.errors.push(String(error)); return reply({ kind: 'native', code: 'FIXTURE_COMMAND_UNHANDLED' }, 500); }+};+Object.assign(window, { consoleComponent: control });+createRoot(document.getElementById('root')!).render(<ConsoleRoot><DesktopApp /></ConsoleRoot>);diff --git a/apps/desktop/tests/v3/browser/host-mock.ts b/apps/desktop/tests/v3/browser/host-mock.tsnew file mode 100644index 00000000..8229535c--- /dev/null+++ b/apps/desktop/tests/v3/browser/host-mock.ts@@ -0,0 +1,13 @@+import { mockIPC as nativeMockIPC, mockWindows } from '@tauri-apps/api/mocks';+import { setHostTransport } from '../../../src/host/index.ts';+import { browserCapabilities } from '../../../src/host/types.ts';+export { mockWindows };+export const consoleFixture = () => new URLSearchParams(location.search).get('transport') === 'console';+export function mockIPC(callback: Parameters<typeof nativeMockIPC>[0], options?: Parameters<typeof nativeMockIPC>[1]): void {+ if (!consoleFixture()) { setHostTransport(undefined); nativeMockIPC(callback, options); return; }+ setHostTransport({+ capabilities: () => ({ ...browserCapabilities, diagnostic_directory: '/example/service/diagnostics', recovery_directory: '/example/service' }),+ call: async <T,>(command: string, args: Record<string, unknown> = {}) => await callback(command, args) as T,+ });+ Object.assign(window, { fixtureTransport: 'console' });+}diff --git a/apps/desktop/tests/v3/browser/list-scroll.tsx b/apps/desktop/tests/v3/browser/list-scroll.tsxindex d232a4c4..90924c94 100644--- a/apps/desktop/tests/v3/browser/list-scroll.tsx+++ b/apps/desktop/tests/v3/browser/list-scroll.tsx@@ -1,7 +1,7 @@// Real product pages with synthetic IPC data; no daemon or provider calls.import React from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import { ModelManagementPage } from '../../../src/product/ModelManagementPage';import { RoutingPage } from '../../../src/product/RoutingPage';import { PresentationRoot, parseTextScale } from '../../../src/ui';diff --git a/apps/desktop/tests/v3/browser/main.tsx b/apps/desktop/tests/v3/browser/main.tsxindex 1841474d..b9bf3126 100644--- a/apps/desktop/tests/v3/browser/main.tsx+++ b/apps/desktop/tests/v3/browser/main.tsx@@ -1,6 +1,6 @@import React, { useEffect, useState } from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import { Agents } from '../../../src/agents';import { Sessions } from '../../../src/features/Sessions';import { Home, HomeNavigation, type HomeAction, type HomeNavigationItem } from '../../../src/features/home';diff --git a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx b/apps/desktop/tests/v3/browser/plan-editor-ux.tsxindex e1ca3a5e..52012068 100644--- a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx+++ b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx@@ -2,7 +2,7 @@import { runRoutingWorkerScenarios } from './routing-worker-scenarios.mjs';import { useState } from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import type { Draft, Editor } from '../../../src/plan-editor';import { RoutingPage } from '../../../src/product/RoutingPage';import { PresentationRoot } from '../../../src/ui';diff --git a/apps/desktop/tests/v3/browser/presentation-interactions.mjs b/apps/desktop/tests/v3/browser/presentation-interactions.mjsnew file mode 100644index 00000000..047ca0dd--- /dev/null+++ b/apps/desktop/tests/v3/browser/presentation-interactions.mjs@@ -0,0 +1,89 @@+import { scenario } from './scenario-selection.mjs';++const control = () => window.productShell;+const assert = (value, message) => { if (!value) throw new Error(message); };+const visible = element => element?.getClientRects().length && getComputedStyle(element).visibility === 'visible';+const all = selector => [...document.querySelectorAll(selector)].filter(visible);+const pause = () => new Promise(resolve => setTimeout(resolve, 25));+async function until(check, message) {+ const deadline = Date.now() + 6000;+ while (!check()) { if (Date.now() > deadline) throw new Error(message); await pause(); }+}+async function ready(language, theme) {+ const previousRoot = document.querySelector('.occami-root');+ control().reset();+ localStorage.setItem('hiroute.language', language);+ localStorage.setItem('hiroute.theme', theme);+ control().remount();+ await until(() => document.querySelector('.occami-root') !== previousRoot+ && visible(document.querySelector('.sidebar-health .status-dot.good'))+ && document.querySelector('.occami-root')?.dataset.theme === theme+ && all('button').some(button => button.getAttribute('aria-label') === (language === 'zh' ? '首页' : 'Home')), 'Presentation did not initialize');+}+async function navigate(label) {+ const button = all('button').find(button => button.getAttribute('aria-label') === label);+ assert(button, `Missing navigation: ${label}`); button.click(); await pause();+}+function bounded(element, label) {+ const bounds = element.getBoundingClientRect();+ assert(bounds.width > 0 && bounds.left >= -1 && bounds.right <= innerWidth + 1,+ `${label} is outside the viewport: ${bounds.left}..${bounds.right} of ${innerWidth}`);+}+function styledButtons(label) {+ for (const button of all('button')) {+ assert(getComputedStyle(button).borderTopStyle !== 'outset', `${label}: browser-default button ${button.textContent.trim()}`);+ bounded(button, `${label}: ${button.textContent.trim().slice(0, 50)}`);+ }+}++export const presentationScenarios = [+ scenario('desktop.models.view-switch', ['model-connections', 'presentation'], 'Model/connection grouping has visible selection, usable controls and stable selected models', async () => {+ for (const language of ['zh', 'en']) for (const theme of ['light', 'dark']) {+ await ready(language, theme); await navigate(language === 'zh' ? '模型' : 'Models');+ const groupLabel = language === 'zh' ? '查看方式' : 'View';+ const group = () => all('[role="group"]').find(element => element.getAttribute('aria-label') === groupLabel);+ await until(() => group() && all('.models-feature .master-list > .list-row').length, 'Missing model view');+ const buttons = [...group().querySelectorAll('button')];+ assert(buttons.length === 2, 'Expected the two grouping choices');+ for (const button of buttons) {+ bounded(button, 'Grouping control');+ assert(button.getBoundingClientRect().height >= 28 && parseFloat(getComputedStyle(button).borderRadius) >= 6, 'Grouping control fell back to browser presentation');+ }+ const sources = control().management.sources;+ const modelCount = sources.reduce((count, source) => count + Math.max(1, source.models.length), 0);+ assert(modelCount > sources.length, 'Fixture must distinguish model and connection grouping');+ assert(all('.models-feature .master-list > .list-row').length === modelCount, 'Model grouping omitted saved models');+ const selected = all('.models-feature .master-list > .list-row')[1];+ const selectedName = selected.querySelector('.row-title').textContent;+ selected.click(); await pause();+ // Small windows show one pane at a time; return through the real control.+ const back = all('button').find(button => button.textContent.trim() === (language === 'zh' ? '返回模型列表' : 'Back to models'));+ if (back && !visible(group())) { back.click(); await pause(); }+ buttons[1].click();+ await until(() => all('.models-feature .master-list > .list-row').length === sources.length, 'Connections were not grouped once per source');+ assert(buttons[1].getAttribute('aria-pressed') === 'true' && buttons[0].getAttribute('aria-pressed') === 'false', 'Grouping selection is ambiguous');+ assert(getComputedStyle(buttons[0]).backgroundColor !== getComputedStyle(buttons[1]).backgroundColor, 'Selected grouping has no visible state');+ buttons[0].click(); await pause();+ assert(all('.models-feature .master-list > .list-row').length === modelCount, 'Returning to models lost entries');+ assert(all('.models-feature .list-row[aria-current="page"]')[0]?.textContent.includes(selectedName), 'Grouping discarded the selected model');+ styledButtons('Models');+ }+ }),+ scenario('desktop.presentation.control-layout', ['presentation'], 'Main pages retain styled controls and long recent sessions fit the supported small window', async () => {+ for (const language of ['zh', 'en']) for (const theme of ['light', 'dark']) {+ await ready(language, theme);+ const pages = language === 'zh' ? ['首页', '模型', '智能路由', 'Agent', '会话', '设置']+ : ['Home', 'Models', 'Smart routing', 'Agent', 'Sessions', 'Settings'];+ for (const page of pages) {+ await navigate(page);+ if (page === '首页' || page === 'Home') {+ await until(() => all('.v3-recent').length > 0, 'Missing actual recent-session rows');+ await until(() => all('.v3-recent .row-title').some(title => title.textContent.length >= 40), 'Long recent-session content did not load');+ const content = all('.v3-home')[0].closest('.page-content');+ assert(content.scrollWidth <= content.clientWidth + 1, 'Recent sessions force horizontal scrolling');+ }+ styledButtons(page);+ }+ }+ }),+];diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjsindex c866a9d6..d97fbbde 100644--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs@@ -1,5 +1,6 @@import { scenario, scenarioCatalog, runScenarios } from './scenario-selection.mjs';import { productShellRequired } from './scenario-requirements.mjs';+import { presentationScenarios } from './presentation-interactions.mjs';const c = () => window.productShell;const pause = ms => new Promise(resolve => setTimeout(resolve, ms));const assert = (condition, message) => { if (!condition) throw new Error(message); };@@ -55,6 +56,27 @@ async function routing() {await until(() => document.querySelector('.plan-identity-fields input'), 'route editor');}const scenarios = [+ ...presentationScenarios,+ scenario('desktop.routing.two-context-conflict', ['routing-editor'], 'A rival context revision refuses stale publication and preserves the current draft', async () => {+ await fresh(); await routing();+ const name = document.querySelector('.plan-identity-fields input');+ const draftName = 'Retained after another tab changes the route';+ setInput(name, draftName); await pause(40);+ const rival = structuredClone(c().desktop);+ const plan = rival.catalog.plans[0]; plan.head.head_revision += 1;+ plan.desired.display_name = 'Saved by a second context';+ c().handlers.desktop_snapshot = () => structuredClone(rival);+ c().handlers.preview_plan_editor = ({ input }) => {+ assert(input.expected_head_revision !== undefined, 'Revision was omitted from the draft');+ throw { kind: 'native', code: 'REVISION_CONFLICT' };+ };+ const reads = calls('desktop_snapshot').length;+ await click('保存草稿');+ await until(() => text().includes('保留') && text().includes('另一会话'), 'revision conflict copy');+ assert(calls('desktop_snapshot').length > reads, 'Conflict did not reload current facts');+ assert(document.querySelector('.plan-identity-fields input').value === draftName, 'Rival revision discarded the local draft');+ assert(calls('preview_plan_editor').length === 1, 'Stale publication was retried automatically');+ }),scenario('desktop.models.subscription-scan.append-to-login', ['subscription-proxy', 'subscription-login'], 'Independent sign-in from an append scan creates a new connection instead of retaining the previous append target', async () => {let previous;await fresh(() => {@@ -898,6 +920,12 @@ const scenarios = [setInput(key, 'synthetic-input-preserved'); await pause(40);const link = all('[role="dialog"] a').find(item => item.textContent.includes('获取 API Key'));assert(link?.target === '_blank' && link.rel.includes('noreferrer') && link.href.startsWith('https://'), 'Web documentation link is unavailable');+ if (window.fixtureTransport === 'console') {+ const prevent = event => { assert(!event.defaultPrevented, 'Browser anchor was intercepted'); event.preventDefault(); };+ document.addEventListener('click', prevent, { once: true }); link.click(); await pause(30);+ assert(key.value === 'synthetic-input-preserved' && calls('open_external_url').length === 0, 'Browser documentation navigation lost input or invoked native IPC');+ return;+ }c().handlers.open_external_url = () => { throw new Error('BROWSER_UNAVAILABLE'); };link.click(); await until(() => text().includes('当前表单内容已保留'), 'native browser failure feedback');assert(calls('open_external_url').at(-1)?.payload.url === link.href, 'Native command did not receive the displayed documentation URL');@@ -933,6 +961,15 @@ const scenarios = [await click('自定义分支 · 分类并评分');assert(all('.classifier-protocol pre')[0].textContent.includes('"from": 0'), 'Assessment request has no prior stage');assert(all('.classifier-protocol pre')[1].textContent.includes('review') && text().includes('这里评分属于上一写稿阶段'), 'Assessment targets the new branch');+ if (window.fixtureTransport === 'console') {+ await click('保存 OpenAPI'); await until(() => text().includes('已开始下载') || text().includes('保存失败'), 'browser download outcome');+ if (text().includes('保存失败')) await c().callHost('save_classifier_openapi');+ assert(c().downloads.length === 1, 'Browser did not produce exactly one Blob download');+ const document = JSON.parse(await c().downloads[0].text());+ assert(document.openapi === '3.1.0' && document.paths['/v1/decisions'], 'Browser download differs from the canonical OpenAPI');+ assert(calls('save_classifier_openapi').length === 0, 'Browser requested a native save command');+ return;+ }let finish;c().handlers.save_classifier_openapi = () => new Promise(resolve => { finish = resolve; });await click('保存 OpenAPI');diff --git a/apps/desktop/tests/v3/browser/product-shell.html b/apps/desktop/tests/v3/browser/product-shell.htmlindex 89554172..fac19dcd 100644--- a/apps/desktop/tests/v3/browser/product-shell.html+++ b/apps/desktop/tests/v3/browser/product-shell.html@@ -1,3 +1,23 @@<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>DesktopApp behavior fixture</title></head>-<body><div id="root"></div><script type="module" src="./product-shell.tsx"></script></body></html>+<body><div id="root"></div><script type="module" src="./product-shell.tsx"></script>+<script type="module">+ if (new URLSearchParams(location.search).get('checks') === 'presentation') {+ const run = document.createElement('button');+ run.className = 'btn'; run.textContent = 'Run presentation checks';+ run.style.cssText = 'position:fixed;top:4px;right:8px;z-index:1000';+ document.body.append(run);+ run.onclick = async () => {+ run.remove();+ const output = document.createElement('pre');+ output.dataset.presentationResults = '';+ try {+ const { runProductShellScenarios } = await import('./product-shell-scenarios.mjs');+ const ids = ['desktop.models.view-switch', 'desktop.presentation.control-layout'];+ output.textContent = JSON.stringify(await runProductShellScenarios({ ids, requiredIds: ids }));+ } catch (error) { output.textContent = JSON.stringify({ state: 'red', error: String(error) }); }+ output.style.cssText = 'position:fixed;inset:40px 8px auto;max-height:45vh;overflow:auto;z-index:1000;background:var(--panel-high);padding:12px;white-space:pre-wrap';+ document.body.append(output);+ };+ }+</script></body></html>diff --git a/apps/desktop/tests/v3/browser/product-shell.tsx b/apps/desktop/tests/v3/browser/product-shell.tsxindex 9e88a9cd..c3c58f82 100644--- a/apps/desktop/tests/v3/browser/product-shell.tsx+++ b/apps/desktop/tests/v3/browser/product-shell.tsx@@ -1,6 +1,7 @@import React from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC, mockWindows } from '@tauri-apps/api/mocks';+import { consoleFixture, mockIPC, mockWindows } from './host-mock';+import { invoke } from '../../../src/host/index.ts';import { DesktopApp } from '../../../src/product/DesktopApp';import { fixturePlanAuthoring, mockProductInvoke, readyAgents, readyDesktop, readyManagement } from './product-fixtures';import '../../../src/occami/styles.css';@@ -15,6 +16,8 @@ const control = {management: structuredClone(readyManagement),commands: [] as { command: string; payload: Record<string, unknown> }[],clipboard: [] as string[],+ downloads: [] as Blob[],+ callHost: invoke,handlers: {} as Record<string, (payload: Record<string, unknown>) => unknown>,fixtureResponse: (command: string, payload: Record<string, unknown>) => {const response = mockProductInvoke(command, payload, 'ready');@@ -31,6 +34,7 @@ const control = {control.management = structuredClone(readyManagement);control.commands = [];control.clipboard = [];+ control.downloads = [];control.handlers = {};localStorage.setItem('hiroute.language', 'zh');localStorage.setItem('hiroute.text-scale', '1');@@ -39,6 +43,10 @@ const control = {},};Object.assign(window, { productShell: control });+if (consoleFixture()) {+ const create = URL.createObjectURL.bind(URL);+ URL.createObjectURL = value => { if (value instanceof Blob) control.downloads.push(value); return create(value); };+}Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {writeText: async (value: string) => { control.clipboard.push(value); },} });diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex 9a873e91..747f7d78 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -59,6 +59,9 @@ export const focusedRequirements = {};export const productShellRequired = [+ 'desktop.models.view-switch',+ 'desktop.presentation.control-layout',+ 'desktop.routing.two-context-conflict','desktop.routing.additional-budget-consumers','desktop.models.subscription-scan.recommended-login','desktop.models.subscription-scan.append-to-login',diff --git a/apps/desktop/tests/v3/browser/session-window.tsx b/apps/desktop/tests/v3/browser/session-window.tsxindex 85be9ef2..29883320 100644--- a/apps/desktop/tests/v3/browser/session-window.tsx+++ b/apps/desktop/tests/v3/browser/session-window.tsx@@ -1,6 +1,6 @@import React, { useState } from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import { PlanQuality, type PlanQualityModel } from '../../../src/features/PlanQuality';import { Sessions } from '../../../src/features/Sessions';import { Home, HomeNavigation } from '../../../src/features/home';diff --git a/apps/desktop/tests/v3/browser/subscription-repair.tsx b/apps/desktop/tests/v3/browser/subscription-repair.tsxindex 4df3c547..8a4bf52c 100644--- a/apps/desktop/tests/v3/browser/subscription-repair.tsx+++ b/apps/desktop/tests/v3/browser/subscription-repair.tsx@@ -1,6 +1,6 @@import React, { useState } from 'react';import { createRoot } from 'react-dom/client';-import { mockIPC } from '@tauri-apps/api/mocks';+import { mockIPC } from './host-mock';import { ModelManagementPage } from '../../../src/product/ModelManagementPage';import { PresentationRoot } from '../../../src/ui';import type { ManagementSnapshot } from '../../../src/features/models/types';diff --git a/apps/desktop/tests/v3/browser/vite.config.ts b/apps/desktop/tests/v3/browser/vite.config.tsnew file mode 100644index 00000000..ca23dac1--- /dev/null+++ b/apps/desktop/tests/v3/browser/vite.config.ts@@ -0,0 +1,4 @@+import { defineConfig } from 'vite';++// The production OpenAPI download reads the repository's canonical contract.+export default defineConfig({ server: { allowedHosts: ['console.test'], fs: { allow: [new URL('../../../../../', import.meta.url).pathname] } } });diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex 0d8d6e82..0f8470bd 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -6,6 +6,10 @@ import { connectPage, evaluate, navigate, waitFor } from './cdp-client.mjs';const port = Number(process.argv[2]);const baseUrl = process.argv[3];+const hostTransport = process.env.HIROUTE_BROWSER_TRANSPORT ?? 'tauri';+if (!['tauri', 'console'].includes(hostTransport)) throw new Error('Unknown browser host transport');+const fixtureUrl = relative => { const url = new URL(relative, baseUrl); if (hostTransport === 'console') url.searchParams.set('transport', 'console'); return url.href; };+const outputRoot = path.resolve(process.argv[4]);const subscriptionProxyOnly = process.argv[5] === '--subscription-proxy-only';const shellOnly = process.argv[5] === '--shell-only' || subscriptionProxyOnly;@@ -21,9 +25,15 @@ try {await mkdir(outputRoot, { recursive: true });const client = await connectPage(port);try {+ if (process.argv[5] === '--shell-host-only') {+ await (await import('./shell-host-scenarios.mjs')).runShellHostScenarios(client, baseUrl, outputRoot);+ } else if (process.argv[5] === '--console-only') {+ await (await import('./console-scenarios.mjs')).runConsoleScenarios(client, baseUrl, outputRoot);+ process.exitCode = 0;+ } else {const checks = [];if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !routeOptionsOnly) {- await navigate(client, new URL('agent-trust.html', baseUrl).href, { width: 1280, height: 900 });+ await navigate(client, fixtureUrl('agent-trust.html'), { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.agentTrust)', { timeout: 7000 });const catalog = await evaluate(client, "import('/agent-trust-scenarios.mjs').then(module => module.agentTrustScenarioCatalog)");const selected = selectScenarios(catalog, claudeCollaborationOnly@@ -42,7 +52,7 @@ try {checks.push(...results);}if (!shellOnly && !claudeCollaborationOnly && !routeOptionsOnly) {- await navigate(client, new URL('?page=routing&scenario=ready', baseUrl).href, { width: 1280, height: 900 });+ await navigate(client, fixtureUrl('?page=routing&scenario=ready'), { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });const catalog = await evaluate(client, "import('/routing-worker-scenarios.mjs').then(module => module.routingWorkerScenarioCatalog)");const capability = routeSaveOnly ? 'route-save' : workerReplacementOnly ? 'worker-replacement' : undefined;@@ -56,7 +66,7 @@ try {}}if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly && !routeOptionsOnly) {- await navigate(client, new URL('?page=models&scenario=ready', baseUrl).href, { width: 1280, height: 900 });+ await navigate(client, fixtureUrl('?page=models&scenario=ready'), { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });const fromModel = await evaluate(client, "import('/model-to-route-scenarios.mjs').then(module => module.runModelToRouteScenarios())");if (fromModel.tests !== 1 || fromModel.results?.length !== 1 || !['green', 'red'].includes(fromModel.results[0].state)) {@@ -68,7 +78,7 @@ try {}}if (routeOptionsOnly || (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly)) {- await navigate(client, new URL('plan-editor-ux.html?checks=availability', baseUrl).href, { width: 1280, height: 900 });+ await navigate(client, fixtureUrl('plan-editor-ux.html?checks=availability'), { width: 1280, height: 900 });await waitFor(client, 'Boolean(document.querySelector("button")?.textContent?.includes("运行智能路由交互检查"))', { timeout: 7000 });await evaluate(client, 'document.querySelector("button").click()');await waitFor(client, 'Boolean(document.querySelector("[data-ux-results]")?.textContent)', { timeout: 20000 });@@ -115,15 +125,16 @@ try {}}if (shellOnly || (!routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly && !routeOptionsOnly)) {- await navigate(client, new URL('product-shell.html', baseUrl).href, { width: 1280, height: 900 });+ await navigate(client, fixtureUrl('product-shell.html'), { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.productShell)', { timeout: 7000 });const catalog = await evaluate(client, "import('/product-shell-scenarios.mjs').then(module => module.productShellScenarioCatalog)");const selected = selectScenarios(catalog, subscriptionProxyOnly? { capability: 'subscription-proxy', requiredIds: focusedRequirements['subscription-proxy'] }- : { requiredIds: productShellRequired });+ : { ids: process.env.HIROUTE_BROWSER_SCENARIOS?.split(','), requiredIds: process.env.HIROUTE_BROWSER_SCENARIOS?.split(',') ?? productShellRequired });const results = [];for (const { id } of selected) {const viewport = ['desktop.models.subscription-scan.recommended-login',+ 'desktop.models.view-switch', 'desktop.presentation.control-layout','desktop.routing.additional-budget-consumers'].includes(id)? { width: 755, height: 600 } : { width: 1280, height: 900 };await client.send('Emulation.setDeviceMetricsOverride', { ...viewport, deviceScaleFactor: 1, mobile: false });@@ -143,6 +154,7 @@ try {};await writeFile(path.join(outputRoot, 'agent-trust-report.json'), `${JSON.stringify(report, null, 2)}\n`);if (report.summary.red > 0) process.exitCode = 1;+ }} finally {client.close();}diff --git a/apps/desktop/tests/v3/visual/agent-trust.mjs b/apps/desktop/tests/v3/visual/agent-trust.mjsindex 0b2aeab1..1d96ef8c 100644--- a/apps/desktop/tests/v3/visual/agent-trust.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust.mjs@@ -10,7 +10,7 @@ const desktopRoot = path.resolve(here, '../../..');const outputRoot = path.resolve(process.argv[2] ?? path.join(desktopRoot, 'test-results/v3-agent-trust'));const subscriptionProxyOnly = process.argv[3] === '--subscription-proxy-only';const shellOnly = process.argv[3] === '--shell-only' || subscriptionProxyOnly;-if (process.argv[3] && !['--shell-only', '--subscription-proxy-only', '--route-save-only', '--worker-replacement-only', '--claude-collaboration-only', '--route-options-only'].includes(process.argv[3])) throw new Error(`Unknown scenario selection: ${process.argv[3]}`);+if (process.argv[3] && !['--shell-host-only', '--console-only', '--shell-only', '--subscription-proxy-only', '--route-save-only', '--worker-replacement-only', '--claude-collaboration-only', '--route-options-only'].includes(process.argv[3])) throw new Error(`Unknown scenario selection: ${process.argv[3]}`);const routeSaveOnly = process.argv[3] === '--route-save-only';const workerReplacementOnly = process.argv[3] === '--worker-replacement-only';const claudeCollaborationOnly = process.argv[3] === '--claude-collaboration-only';@@ -40,6 +40,11 @@ const terminate = async child => {new Promise(resolve => child.once('exit', resolve)),new Promise(resolve => setTimeout(resolve, 1500)),]);+ // A detached browser descendant can retain inherited pipes after its parent+ // exits. Close our pipe handles so completed scenarios do not keep Node alive.+ child.stdin?.destroy();+ child.stdout?.destroy();+ child.stderr?.destroy();};const removeProfile = async directory => {for (let attempt = 0; attempt < 5; attempt += 1) {@@ -62,19 +67,20 @@ await mkdir(outputRoot, { recursive: true });let vite;let chrome;try {- vite = spawn(path.join(desktopRoot, 'node_modules/.bin/vite'), ['tests/v3/browser', '--host', '127.0.0.1', '--port', String(httpPort), '--strictPort'], { cwd: desktopRoot, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ vite = spawn(path.join(desktopRoot, 'node_modules/.bin/vite'), ['tests/v3/browser', '--config', 'tests/v3/browser/vite.config.ts', '--host', '127.0.0.1', '--port', String(httpPort), '--strictPort'], { cwd: desktopRoot, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });vite.stdout.resume();vite.stderr.on('data', data => process.stderr.write(data));await waitFor(`http://127.0.0.1:${httpPort}/`);const chromeExecutable = process.env.CHROME_BIN || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : 'google-chrome');- chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', '--no-proxy-server', '--host-resolver-rules=MAP console.test 127.0.0.1', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });chrome.stdout.resume();// Drain the diagnostic pipe: repeated platform warnings can otherwise block Chrome.let chromeErrors = '';chrome.stderr.on('data', data => { chromeErrors = (chromeErrors + data).slice(-8000); });try { await waitFor(`http://127.0.0.1:${cdpPort}/json/version`); }catch (error) { throw new Error(`${error.message}\n${chromeErrors}`); }- const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(subscriptionProxyOnly ? ['--subscription-proxy-only'] : shellOnly ? ['--shell-only'] : routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : routeOptionsOnly ? ['--route-options-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });+ const consoleOnly = process.argv[3] === '--console-only';+ const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://${consoleOnly ? 'console.test' : '127.0.0.1'}:${httpPort}/`, outputRoot, ...(process.argv[3] === '--shell-host-only' ? ['--shell-host-only'] : consoleOnly ? ['--console-only'] : subscriptionProxyOnly ? ['--subscription-proxy-only'] : shellOnly ? ['--shell-only'] : routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : routeOptionsOnly ? ['--route-options-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });const outcome = await waitForExit(runner);if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;} finally {diff --git a/apps/desktop/tests/v3/visual/console-scenarios.mjs b/apps/desktop/tests/v3/visual/console-scenarios.mjsnew file mode 100644index 00000000..27153024--- /dev/null+++ b/apps/desktop/tests/v3/visual/console-scenarios.mjs@@ -0,0 +1,100 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { evaluate, navigate, waitFor } from './cdp-client.mjs';++export async function runConsoleScenarios(client, baseUrl, output) {+ const results = [];+ const assert = (value, message) => { if (!value) throw new Error(message); };+ const settleVisual = () => evaluate(client, `Promise.all(document.getAnimations()+ .filter(animation => animation.effect?.getTiming().iterations !== Infinity)+ .map(animation => animation.finished.catch(() => undefined)))+ .then(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))`);+ const open = async (state, language = 'zh', theme = 'light', width = 1200, height = 813) => {+ const url = new URL('console-entry.html', baseUrl);+ for (const [key, value] of Object.entries({ case: state, language, theme })) url.searchParams.set(key, value);+ await navigate(client, url.href, { width, height });+ await waitFor(client, 'Boolean(window.consoleComponent)');+ await waitFor(client, state === 'ready' || state === 'launch' ? 'Boolean(document.querySelector(".sidebar"))' : 'Boolean(document.querySelector(".console-entry h1")) && !document.querySelector(".console-entry [role=status]")');+ if (state === 'ready' || state === 'launch') {+ await waitFor(client, 'document.querySelector(".console-transport-bar")?.getBoundingClientRect().height > 0');+ assert(await evaluate(client, '!window.consoleComponent.errors.length'), 'Incomplete console component fixture: ' + await evaluate(client, 'JSON.stringify(window.consoleComponent.errors)'));+ }+ if (state === 'login' || state === 'expired') {+ const guidance = language === 'zh' ? '获取一次性登录链接' : 'single-use sign-in link';+ assert(await evaluate(client, `document.body.innerText.includes(${JSON.stringify(guidance)})`), 'Console entry still describes a local-only launch link');+ }+ if (state === 'rate-limited' || state === 'session-limit') {+ await evaluate(client, 'Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value").set.call(document.querySelector("input"), "c".repeat(64)); document.querySelector("input").dispatchEvent(new Event("input",{bubbles:true}))');+ await evaluate(client, 'document.querySelector("form").requestSubmit()');+ await waitFor(client, 'Boolean(document.querySelector("[role=alert]")) && !document.querySelector("input").disabled');+ assert(await evaluate(client, '!document.querySelector("input").value && !sessionStorage.getItem("hiroute.console.session")'), 'Rejected sign-in retained its input or granted a session');+ const hint = state === 'rate-limited' ? (language === 'zh' ? '一分钟' : 'one minute') : (language === 'zh' ? '退出其他设备' : 'Sign out');+ assert(await evaluate(client, `document.body.innerText.includes(${JSON.stringify(hint)})`), 'Sign-in recovery hint is missing');+ }+ };+ const check = async (id, run) => { try { await run(); results.push({ id, state: 'green' }); } catch (error) { results.push({ id, state: 'red', error: String(error) }); } };+ await check('console.session.launch', async () => {+ await open('launch');+ assert(await evaluate(client, 'Boolean(document.querySelector(".console-transport-bar.plaintext"))'), 'Network launch login lost its persistent plaintext warning');+ assert(await evaluate(client, 'location.pathname === "/" && !location.search && window.consoleComponent.requests.filter(r => r.path.endsWith("/launch")).length === 1 && window.consoleComponent.requests.every(r => !r.url.includes("code="))'), 'Launch code was not removed before exchange');+ assert(await evaluate(client, 'sessionStorage.getItem("hiroute.console.session")?.length === 64 && !localStorage.getItem("hiroute.console.session") && !document.cookie'), 'Session escaped sessionStorage');+ assert(await evaluate(client, 'window.consoleComponent.requests.filter(r => !r.path.endsWith("/launch")).every(r => r.headers.authorization?.startsWith("Bearer ") && r.credentials === "omit" && /^[a-f0-9]{32}$/.test(r.headers["x-hiroute-context"]))'), 'Console request authority differs from the Bearer/context contract');+ });+ await check('console.session.token', async () => {+ await open('login');+ assert(await evaluate(client, 'document.querySelector("[role=note]")?.textContent.includes("明文")'), 'Plaintext token warning is missing');+ await evaluate(client, 'Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value").set.call(document.querySelector("input"), "c".repeat(64)); document.querySelector("input").dispatchEvent(new Event("input",{bubbles:true}))');+ await evaluate(client, 'document.querySelector("form").requestSubmit()');+ await waitFor(client, 'Boolean(document.querySelector(".sidebar"))');+ assert(await evaluate(client, 'window.consoleComponent.requests.filter(r => r.path.endsWith("/token")).length === 1 && !document.querySelector("input[name=access-token]")'), 'Token exchange did not clear the form');+ });+ await check('console.session.expired', async () => {+ await open('expired');+ assert(await evaluate(client, '!sessionStorage.getItem("hiroute.console.session") && document.body.innerText.includes("会话已结束")'), '401 did not discard the bearer and render expiry');+ });+ await check('console.host-capabilities', async () => {+ await open('ready');+ await evaluate(client, '[...document.querySelectorAll("button")].find(b => b.textContent.trim() === "设置").click()');+ await waitFor(client, 'Boolean(document.querySelector(".settings-group"))');+ assert(await evaluate(client, '!document.body.innerText.includes("安装命令行") && !document.body.innerText.includes("检查更新")'), 'Browser exposes host-only CLI or update actions');+ assert(await evaluate(client, 'Boolean(document.querySelector(".console-transport-bar.plaintext"))'), 'Persistent plaintext banner is missing');+ });+ for (const language of ['zh', 'en']) for (const theme of ['light', 'dark']) for (const [width, height] of [[1200, 813], [755, 600]]) {+ for (const state of ['login', 'expired', 'unavailable', 'assets', 'ready', 'rate-limited', 'session-limit']) {+ await open(state, language, theme, width, height);+ const geometry = await evaluate(client, `(() => {+ const element = document.querySelector('.console-entry-card') ?? document.querySelector('.console-transport-bar');+ const box = element.getBoundingClientRect();+ const page = document.querySelector('.main .page');+ return { overflow: element.scrollWidth > element.clientWidth + 1, left: box.left, right: box.right, viewport: innerWidth, theme: document.querySelector('.hr-ui').dataset.theme,+ bannerHeight: document.querySelector('.console-transport-bar')?.getBoundingClientRect().height,+ pageTop: page?.getBoundingClientRect().top, pageBottom: page?.getBoundingClientRect().bottom };+ })()`);+ assert(!geometry.overflow && geometry.left >= 0 && geometry.right <= geometry.viewport + 1 && geometry.theme === theme, `Console layout failed: ${state}/${language}/${theme}/${width}: ${JSON.stringify(geometry)}`);+ if (state === 'ready') assert(geometry.bannerHeight < 110 && geometry.pageTop < 200 && geometry.pageBottom <= height + 1, 'Console banner displaced the product page: ' + JSON.stringify(geometry));+ await settleVisual();+ const screenshot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });+ const name = `console-${state}-${language}-${theme}-${width}x${height}.png`;+ await writeFile(path.join(output, name), Buffer.from(screenshot.data, 'base64'));+ results.push({ id: `console.layout.${state}.${language}.${theme}.${width}`, state: 'green', screenshot: name, geometry });+ if (state === 'ready') {+ const click = async (label, selector = 'button') => { await waitFor(client, `[...document.querySelectorAll(${JSON.stringify(selector)})].some(e => e.textContent.includes(${JSON.stringify(label)}))`); await evaluate(client, `[...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.textContent.includes(${JSON.stringify(label)})).click()`); };+ await click(language === 'zh' ? '模型' : 'Models', '.sidebar button');+ await click(language === 'zh' ? '添加模型' : 'Add models');+ await click(language === 'zh' ? '新建 API 接入' : 'New API connection', '.add-choice');+ await click(language === 'zh' ? '百炼' : 'Alibaba Cloud Model Studio', '.connection-provider-card');+ await click('Coding Plan', '.connection-product-card');+ await waitFor(client, 'Boolean(document.querySelector(".console-secret-warning"))');+ assert(await evaluate(client, 'document.querySelector("input[type=password]").getBoundingClientRect().width > 100 && document.querySelector(".console-secret-warning").getBoundingClientRect().width > 100'), 'Plaintext secret form is unreadable');+ await settleVisual();+ const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });+ const secretName = `console-secret-${language}-${theme}-${width}x${height}.png`;+ await writeFile(path.join(output, secretName), Buffer.from(shot.data, 'base64'));+ results.push({ id: `console.secret.${language}.${theme}.${width}`, state: 'green', screenshot: secretName });+ }+ }+ }+ await writeFile(path.join(output, 'console-report.json'), JSON.stringify({ evidence: 'Production React/style components with synthetic HTTP. Native installation and real daemon acceptance are separate.', results }, null, 2) + '\n');+ for (const result of results) process.stdout.write(`${result.state}: ${result.id}${result.error ? ': ' + result.error : ''}\n`);+ if (results.some(result => result.state !== 'green')) throw new Error('Console scenarios failed');+}diff --git a/apps/desktop/tests/v3/visual/shell-host-scenarios.mjs b/apps/desktop/tests/v3/visual/shell-host-scenarios.mjsnew file mode 100644index 00000000..3fdba023--- /dev/null+++ b/apps/desktop/tests/v3/visual/shell-host-scenarios.mjs@@ -0,0 +1,86 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { evaluate,navigate,waitFor } from './cdp-client.mjs';+export async function runShellHostScenarios(client,baseUrl,output) {+ const results=[];+ const assert=(value,message)=>{if(!value)throw new Error(message);};+ const screenshot=async(name)=>{const shot=await client.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});await writeFile(path.join(output,name),Buffer.from(shot.data,'base64'));return name;};+ const open=async(language,theme,width,height,update='ready',state='ready')=>{+ const url=new URL('console-entry.html',baseUrl);+ for(const [key,value]of Object.entries({case:state,host:'shell-console',language,theme,update}))url.searchParams.set(key,value);+ await navigate(client,url.href,{width,height});+ try { await waitFor(client,'Boolean(window.consoleComponent)'); }+ catch(error) {+ await writeFile(path.join(output,'shell-entry-failure.json'),JSON.stringify(await evaluate(client,'({url:location.href,ready:document.readyState,text:document.body.innerText,resources:performance.getEntriesByType("resource").map(r=>({name:r.name,status:r.responseStatus,duration:r.duration}))})'),null,2));+ await screenshot('shell-entry-failure.png');throw error;+ }+ if(state==='expired')return;+ await waitFor(client,'Boolean(document.querySelector(".sidebar"))');+ await evaluate(client,`[...document.querySelectorAll('.sidebar button')].find(b=>b.textContent.trim()===${JSON.stringify(language==='zh'?'设置':'Settings')}).click()`);+ try { await waitFor(client,'document.querySelector(".settings-group")?.textContent.includes("Windows") && Boolean(document.querySelector(".settings-group button[aria-pressed]"))'); }+ catch(error) { await writeFile(path.join(output,'shell-ui-failure.json'),JSON.stringify(await evaluate(client,'({text:document.body.innerText,capabilities:window.consoleComponent.capabilities(),requests:window.consoleComponent.hostRequests,errors:window.consoleComponent.errors})'),null,2));await screenshot('shell-ui-failure.png');throw error; }+ await waitFor(client,'window.consoleComponent.hostRequests.some(r=>r.command==="update_status")');+ const page=await evaluate(client,'(()=>{const b=document.querySelector(".main .page").getBoundingClientRect();return{banner:!!document.querySelector(".console-transport-bar"),top:b.top,bottom:b.bottom};})()');+ assert(!page.banner&&page.top<90&&page.bottom<=height+1,'Windows host notice displaced the product page: '+JSON.stringify(page));+ };+ for(const language of ['zh','en'])for(const theme of ['light','dark'])for(const [width,height]of [[1200,813],[755,600]]) {+ for(const phase of ['ready','waiting','failed','catalog-unavailable']){+ await open(language,theme,width,height,phase);+ const box=await evaluate(client,`(()=>{const wrap=document.querySelector('.settings-wrap');const rows=[...wrap.querySelectorAll('.settings-row')];return {overflow:wrap.scrollWidth>wrap.clientWidth+1,rows:rows.map(e=>{const b=e.getBoundingClientRect();return{width:b.width,overflow:e.scrollWidth>e.clientWidth+1};})};})()`);+ assert(!box.overflow && box.rows.every(r=>r.width>200&&!r.overflow),'Shell settings overflow: '+JSON.stringify(box));+ if(phase==='ready') {+ const hostScreenshot=await screenshot(`shell-host-${language}-${theme}-${width}x${height}.png`);+ results.push({id:`shell.host.${language}.${theme}.${width}`,state:'green',screenshot:hostScreenshot});+ }+ await evaluate(client,`[...document.querySelectorAll('.settings-group')].find(e=>e.querySelector('h2')?.textContent===${JSON.stringify(language==='zh'?'版本升级':'Updates')}).scrollIntoView({block:'start'})`);+ if(phase==='catalog-unavailable') {+ const state=await evaluate(client,`(()=>{const group=[...document.querySelectorAll('.settings-group')].find(e=>e.querySelector('h2')?.textContent===${JSON.stringify(language==='zh'?'版本升级':'Updates')});return{text:group.textContent,buttons:[...group.querySelectorAll('button')].map(b=>({text:b.textContent,disabled:b.disabled}))};})()`);+ assert(state.text.includes('UPGRADE_CATALOG_UNAVAILABLE') && state.text.includes(language==='zh'?'Windows 更新目录暂不可用':'Windows update catalog is unavailable'),'Missing catalog was not identified');+ assert(!state.text.includes(language==='zh'?'升级未完成':'upgrade did not complete') && !state.text.includes(language==='zh'?'最新稳定版本':'latest stable version'),'Failed check implied installation failure or a completed check');+ assert(state.buttons.length===1&&!state.buttons[0].disabled,'Failed check did not retain exactly one usable retry action');+ }+ const name=await screenshot(`shell-settings-${phase}-${language}-${theme}-${width}x${height}.png`);+ results.push({id:`shell.settings.${phase}.${language}.${theme}.${width}`,state:'green',screenshot:name,geometry:box});+ }+ }+ await open('en','light',1200,813,'waiting');+ await evaluate(client,'[...document.querySelectorAll("button")].find(b=>b.textContent==="Cancel update").click()');+ await waitFor(client,'window.consoleComponent.hostRequests.some(r=>r.command==="update_cancel")');+ assert(await evaluate(client,'!window.consoleComponent.requests.some(r=>r.path.includes("update_"))'),'Shell updater escaped onto console HTTP');+ await evaluate(client,'[...document.querySelectorAll(".settings-row")].find(e=>e.textContent.includes("Start at login")).querySelector("button").click()');+ await waitFor(client,'window.consoleComponent.hostRequests.some(r=>r.command==="login_start_set"&&r.args.enabled===false)');+ await evaluate(client,'window.dispatchEvent(new CustomEvent("hiroute-host-path",{detail:"C:\\\\example\\\\diagnostics"}))');+ await waitFor(client,'Boolean(document.querySelector("[role=dialog] input"))');+ assert(await evaluate(client,'document.querySelector("[role=dialog] input").value==="C:\\\\example\\\\diagnostics"'),'Removing the host banner lost the directory-path dialog');+ await evaluate(client,'document.querySelector("button[aria-label=Close]").click()');+ results.push({id:'shell.host-command-routing',state:'green'});+ await open('en','light',1200,813,'ready','expired');+ await waitFor(client,'window.consoleComponent.hostRequests.some(r=>r.command==="reconnect")');+ assert(await evaluate(client,'!document.querySelector("input[name=access-token]")&&!sessionStorage.getItem("hiroute.console.session")'),'Shell expiry exposed a token login or retained its bearer');+ results.push({id:'shell.expiry-remints-through-host',state:'green'});+ const shellIndex=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../../../../shell/index.html');+ for(const language of ['zh','en'])for(const theme of ['light','dark'])for(const [width,height]of [[1200,813],[755,600]])for(const phase of ['waiting','failed','listener-unavailable']){+ const code=phase==='listener-unavailable'?'CONSOLE_LISTENER_UNAVAILABLE':phase==='failed'?'SHELL_INSTALL_RECOVERY_REQUIRED':null;+ const script=await client.send('Page.addScriptToEvaluateOnNewDocument',{source:`Object.defineProperty(navigator,'language',{value:${JSON.stringify(language)}});window.shellHostRequests=[];window.__TAURI_INTERNALS__={invoke:async(command)=>{window.shellHostRequests.push(command);return command==='shell_status'?{phase:${JSON.stringify(phase==='listener-unavailable'?'failed':phase)},code:${JSON.stringify(code)},logs_path:'C:\\\\Users\\\\example\\\\AppData\\\\Local\\\\HiRoute\\\\cli\\\\diagnostics'}:null}};`});+ await client.send('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:theme}]});+ try{+ await navigate(client,new URL('/@fs'+shellIndex,baseUrl).href,{width,height});await waitFor(client,'Boolean(document.querySelector("#explanation")?.textContent)');+ const box=await evaluate(client,`(()=>{const e=document.querySelector('.shell-status section'),b=e.getBoundingClientRect();return{left:b.left,right:b.right,overflow:e.scrollWidth>e.clientWidth+1,theme:document.querySelector('#root').dataset.theme,button:[...document.querySelectorAll('button')].filter(b=>!b.hidden).map(b=>({width:b.getBoundingClientRect().width,height:b.getBoundingClientRect().height}))};})()`);+ assert(box.left>=0&&box.right<=width+1&&!box.overflow&&box.theme===theme&&box.button.every(b=>b.width>35&&b.height>25),'Shell startup layout failed: '+JSON.stringify(box));+ if(phase==='listener-unavailable') {+ const state=await evaluate(client,`(()=>{const recovery=document.querySelector('#console-recovery');const main=document.querySelector('.shell-status');main.scrollTop=0;return{heading:document.querySelector('#phase').textContent,visible:recovery&&!recovery.hidden,steps:recovery?.textContent,top:document.querySelector('h1').getBoundingClientRect().top,commands:recovery?.querySelector('pre')?.textContent};})()`);+ assert(state.visible&&state.heading===(language==='zh'?'本机控制台尚未就绪':'The local console is unavailable')&&state.top>=0,'Healthy service was described as a startup failure or clipped: '+JSON.stringify(state));+ assert(state.commands==='hiroute console init --mode loopback\nhiroute service restart' && state.steps.includes(language==='zh'?'可能中断':'may interrupt'),'Missing explicit configuration/restart steps or restart warning');+ await evaluate(client,'document.querySelector("#retry").scrollIntoView({block:"end"});document.querySelector("#retry").click()');+ await waitFor(client,'window.shellHostRequests.includes("shell_retry_startup")');+ const action=await evaluate(client,'(()=>{const b=document.querySelector("#retry").getBoundingClientRect();return{top:b.top,bottom:b.bottom,commands:window.shellHostRequests.filter(c=>c!=="shell_status")};})()');+ assert(action.top>=0&&action.bottom<=height+1&&action.commands.every(c=>c==='shell_retry_startup'),'Recheck was clipped or bypassed the fixed startup path: '+JSON.stringify({language,theme,width,height,action}));+ }+ const name=await screenshot(`shell-startup-${phase}-${language}-${theme}-${width}x${height}.png`);+ results.push({id:`shell.startup.${phase}.${language}.${theme}.${width}`,state:'green',screenshot:name,geometry:box});+ }finally{await client.send('Page.removeScriptToEvaluateOnNewDocument',{identifier:script.identifier});}+ }+ await writeFile(path.join(output,'shell-host-report.json'),JSON.stringify({evidence:'Production console/settings and actual shell HTML/styles with synthetic host replies. Native origin ACL, installation and update acceptance remain separate.',results},null,2)+'\n');+ for(const result of results)process.stdout.write(`green: ${result.id}\n`);+}diff --git a/apps/shell/.gitignore b/apps/shell/.gitignorenew file mode 100644index 00000000..26f4cb73--- /dev/null+++ b/apps/shell/.gitignore@@ -0,0 +1,3 @@+node_modules/+dist/+src-tauri/gen/diff --git a/apps/shell/README.md b/apps/shell/README.mdnew file mode 100644index 00000000..ddd6ce3d--- /dev/null+++ b/apps/shell/README.md@@ -0,0 +1,47 @@+# Windows console shell++This x64 Tauri host displays the daemon's shared Web console. Product state,+authentication, confirmations and operations stay in `hirouted` and+`crates/product-session`; there is no second Tauri product-command bridge.++`src-tauri/src/runtime` owns these boundaries:++- `service`: fixed installed CLI lookup, bounded native execution, real+ Control/Gateway readiness and one-time console launch minting. A missing local+ listener remains distinct from a service-start failure; the bundled page gives+ explicit owner configuration/restart steps without changing saved scope.+- `mod` / `commands`: private WebView, single instance, navigation lock and+ explicit host commands, each checked against the exact active console origin.+- `tray` / platform `shell_login`: window visibility and current-user login start;+ quitting the shell leaves the Task running.+- `installer`: NSIS's fixed adapter to the native Rust installation transaction.+- `install_transaction`: shell-only digest inventory, prepared/committed backup+ record, removal of obsolete owned payload assets before strict package validation,+ and failure recovery; unchanged cores are retained, successful manual repair+ supersedes stale failure reporting before journal retirement, and standalone+ journals keep their separate owner.+- `updater`: fixed HTTPS V3 selection/download, distinct check-unavailable states,+ verification, cancellable drain+ and a private native finisher that waits for shell exit before passive NSIS.++`src/main.ts` and `index.html` are the bundled startup/failure page. They use the+Desktop production styles and never render caller-supplied HTML. The running+console uses `apps/desktop/src/host`'s `shell-console` transport: product commands+use authenticated HTTP; only the explicitly listed host actions use IPC.++The remote capability matches loopback HTTP; Rust also checks the exact current+origin/port on every host call. It grants no filesystem, shell, product-command,+generic plugin or Local Control access. Tauri's native postMessage fallback keeps+host IPC available under the console's strict HTTP CSP.++Build the installer through `scripts/build-release.py --windows-desktop` on the+native x64 Windows producer. Silent NSIS installation (`/S`) applies default+login/tray choices with no prompts. This is the only offered Windows install+package; headless archives stay internal and SCM installation is not offered. It stages a verified standalone package under the+ignored `src-tauri/resources/standalone` directory. Do not hand-populate or publish+that staging directory. The vendored NSIS template and hooks are explained in+[`installer/README.md`](src-tauri/installer/README.md).++See [installation and recovery](../../docs/windows-desktop-installation.md) and+the [native acceptance boundaries](../../docs/windows-desktop-installation.md#evidence-and-release-claims). Browser+screenshots and compilation do not replace native standard-user acceptance.diff --git a/apps/shell/index.html b/apps/shell/index.htmlnew file mode 100644index 00000000..7c044278--- /dev/null+++ b/apps/shell/index.html@@ -0,0 +1,4 @@+<!doctype html>+<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>HiRoute</title></head>+<body><div id="root" class="hr-ui occami-root"><main class="shell-status"><section class="surface"><h1>HiRoute</h1><h2 id="phase"></h2><p id="explanation" role="status"></p><p id="failure" role="alert"></p><div id="console-recovery" hidden><p id="recovery-explanation"></p><pre>hiroute console init --mode loopback+hiroute service restart</pre><p id="recovery-warning"></p></div><label id="logs-label" for="logs"></label><input id="logs" class="input" readonly><div class="actions"><button id="retry" class="btn btn-primary" hidden></button><button id="language" class="btn"></button><button id="theme" class="btn"></button></div></section></main></div><script type="module" src="./src/main.ts"></script></body></html>diff --git a/apps/shell/package-lock.json b/apps/shell/package-lock.jsonnew file mode 100644index 00000000..4ee8403a--- /dev/null+++ b/apps/shell/package-lock.json@@ -0,0 +1,1016 @@+{+ "name": "hiroute-windows-shell-ui",+ "version": "0.3.1",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "hiroute-windows-shell-ui",+ "version": "0.3.1",+ "devDependencies": {+ "@tauri-apps/cli": "2.11.4",+ "vite": "8.2.2"+ }+ },+ "node_modules/@oxc-project/types": {+ "version": "0.154.0",+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz",+ "integrity": "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/oxc-project"+ }+ },+ "node_modules/@rolldown/binding-android-arm-eabi": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.14.tgz",+ "integrity": "sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-android-arm64": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.14.tgz",+ "integrity": "sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-arm64": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.14.tgz",+ "integrity": "sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-x64": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.14.tgz",+ "integrity": "sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-freebsd-x64": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.14.tgz",+ "integrity": "sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.14.tgz",+ "integrity": "sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-gnu": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.14.tgz",+ "integrity": "sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-musl": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.14.tgz",+ "integrity": "sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.14.tgz",+ "integrity": "sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-s390x-gnu": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.14.tgz",+ "integrity": "sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-gnu": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.14.tgz",+ "integrity": "sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-musl": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.14.tgz",+ "integrity": "sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-openharmony-arm64": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.14.tgz",+ "integrity": "sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-arm64-msvc": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.14.tgz",+ "integrity": "sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-x64-msvc": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.14.tgz",+ "integrity": "sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tauri-apps/cli": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.11.4.tgz",+ "integrity": "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ==",+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "bin": {+ "tauri": "tauri.js"+ },+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/tauri"+ },+ "optionalDependencies": {+ "@tauri-apps/cli-darwin-arm64": "2.11.4",+ "@tauri-apps/cli-darwin-x64": "2.11.4",+ "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4",+ "@tauri-apps/cli-linux-arm64-gnu": "2.11.4",+ "@tauri-apps/cli-linux-arm64-musl": "2.11.4",+ "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4",+ "@tauri-apps/cli-linux-x64-gnu": "2.11.4",+ "@tauri-apps/cli-linux-x64-musl": "2.11.4",+ "@tauri-apps/cli-win32-arm64-msvc": "2.11.4",+ "@tauri-apps/cli-win32-ia32-msvc": "2.11.4",+ "@tauri-apps/cli-win32-x64-msvc": "2.11.4"+ }+ },+ "node_modules/@tauri-apps/cli-darwin-arm64": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz",+ "integrity": "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-darwin-x64": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz",+ "integrity": "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz",+ "integrity": "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm64-gnu": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz",+ "integrity": "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-arm64-musl": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz",+ "integrity": "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-riscv64-gnu": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz",+ "integrity": "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-x64-gnu": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz",+ "integrity": "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-linux-x64-musl": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz",+ "integrity": "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-arm64-msvc": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz",+ "integrity": "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-ia32-msvc": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz",+ "integrity": "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@tauri-apps/cli-win32-x64-msvc": {+ "version": "2.11.4",+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz",+ "integrity": "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 OR MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.33.0",+ "lightningcss-darwin-arm64": "1.33.0",+ "lightningcss-darwin-x64": "1.33.0",+ "lightningcss-freebsd-x64": "1.33.0",+ "lightningcss-linux-arm-gnueabihf": "1.33.0",+ "lightningcss-linux-arm64-gnu": "1.33.0",+ "lightningcss-linux-arm64-musl": "1.33.0",+ "lightningcss-linux-x64-gnu": "1.33.0",+ "lightningcss-linux-x64-musl": "1.33.0",+ "lightningcss-win32-arm64-msvc": "1.33.0",+ "lightningcss-win32-x64-msvc": "1.33.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.20",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.30",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",+ "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.20",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.2"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rolldown": {+ "version": "1.2.14",+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.14.tgz",+ "integrity": "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@oxc-project/types": "=0.154.0",+ "@rolldown/pluginutils": "^1.0.0"+ },+ "bin": {+ "rolldown": "bin/cli.mjs"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "optionalDependencies": {+ "@rolldown/binding-android-arm-eabi": "1.2.14",+ "@rolldown/binding-android-arm64": "1.2.14",+ "@rolldown/binding-darwin-arm64": "1.2.14",+ "@rolldown/binding-darwin-x64": "1.2.14",+ "@rolldown/binding-freebsd-x64": "1.2.14",+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.14",+ "@rolldown/binding-linux-arm64-gnu": "1.2.14",+ "@rolldown/binding-linux-arm64-musl": "1.2.14",+ "@rolldown/binding-linux-ppc64-gnu": "1.2.14",+ "@rolldown/binding-linux-s390x-gnu": "1.2.14",+ "@rolldown/binding-linux-x64-gnu": "1.2.14",+ "@rolldown/binding-linux-x64-musl": "1.2.14",+ "@rolldown/binding-openharmony-arm64": "1.2.14",+ "@rolldown/binding-win32-arm64-msvc": "1.2.14",+ "@rolldown/binding-win32-x64-msvc": "1.2.14"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/vite": {+ "version": "8.2.2",+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",+ "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lightningcss": "^1.33.0",+ "picomatch": "^4.0.5",+ "postcss": "^8.5.26",+ "rolldown": "~1.2.4",+ "tinyglobby": "^0.2.17"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "@vitejs/devtools": "^0.4.0 || ^0.5.0",+ "esbuild": "^0.27.0 || ^0.28.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "@vitejs/devtools": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ }+ }+}diff --git a/apps/shell/package.json b/apps/shell/package.jsonnew file mode 100644index 00000000..2c66bb10--- /dev/null+++ b/apps/shell/package.json@@ -0,0 +1,8 @@+{+ "name": "hiroute-windows-shell-ui",+ "version": "0.3.1",+ "private": true,+ "type": "module",+ "scripts": { "build": "vite build", "tauri": "tauri" },+ "devDependencies": { "@tauri-apps/cli": "2.11.4", "vite": "8.2.2" }+}diff --git a/apps/shell/src-tauri/Cargo.toml b/apps/shell/src-tauri/Cargo.tomlnew file mode 100644index 00000000..2e65ae7e--- /dev/null+++ b/apps/shell/src-tauri/Cargo.toml@@ -0,0 +1,36 @@+[package]+name = "hiroute-shell"+version = "0.3.1"+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[features]+default = []+shell-runtime = ["dep:tauri", "dep:tauri-build", "dep:tauri-plugin-single-instance", "dep:tauri-plugin-dialog"]++[dependencies]+hiroute-host-runtime = { path = "../../../crates/host-runtime" }+serde.workspace = true+serde_json.workspace = true+sha2.workspace = true+fs2.workspace = true+url = "=2.5.8"++[target.'cfg(windows)'.dependencies]+hiroute-application-api = { path = "../../../crates/application-api" }+hiroute-client-core = { path = "../../../crates/client-core" }+hiroute-platform = { path = "../../../crates/platform" }+tokio.workspace = true+reqwest = { version = "=0.13.4" }+tauri = { version = "=2.11.5", features = ["tray-icon", "image-png"], optional = true }+tauri-plugin-single-instance = { version = "=2.4.1", optional = true }+tauri-plugin-dialog = { version = "=2.7.3", default-features = false, optional = true }++[build-dependencies]+tauri-build = { version = "=2.6.3", optional = true }++[[bin]]+name = "hiroute-shell"+path = "src/main.rs"+required-features = ["shell-runtime"]diff --git a/apps/shell/src-tauri/build.rs b/apps/shell/src-tauri/build.rsnew file mode 100644index 00000000..5f710446--- /dev/null+++ b/apps/shell/src-tauri/build.rs@@ -0,0 +1,25 @@+fn main() {+ #[cfg(feature = "shell-runtime")]+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {+ tauri_build::try_build(tauri_build::Attributes::new().app_manifest(+ tauri_build::AppManifest::new().commands(&[+ "shell_status",+ "shell_retry_startup",+ "shell_capabilities",+ "shell_open_in_browser",+ "shell_open_external_url",+ "shell_save_classifier_openapi",+ "shell_login_start_get",+ "shell_login_start_set",+ "shell_restart_service",+ "shell_reconnect",+ "shell_update_status",+ "shell_update_check",+ "shell_update_download",+ "shell_update_install",+ "shell_update_cancel",+ ]),+ ))+ .expect("build the restricted Windows shell manifest");+ }+}diff --git a/apps/shell/src-tauri/capabilities/console.json b/apps/shell/src-tauri/capabilities/console.jsonnew file mode 100644index 00000000..e00de269--- /dev/null+++ b/apps/shell/src-tauri/capabilities/console.json@@ -0,0 +1,8 @@+{+ "identifier": "console",+ "description": "Host-only commands; Rust additionally checks the exact active console origin on every call.",+ "local": false,+ "remote": { "urls": ["http://127.0.0.1:*"] },+ "windows": ["main"],+ "permissions": ["allow-shell-capabilities", "allow-shell-open-in-browser", "allow-shell-open-external-url", "allow-shell-save-classifier-openapi", "allow-shell-login-start-get", "allow-shell-login-start-set", "allow-shell-restart-service", "allow-shell-reconnect", "allow-shell-update-status", "allow-shell-update-check", "allow-shell-update-download", "allow-shell-update-install", "allow-shell-update-cancel"]+}diff --git a/apps/shell/src-tauri/capabilities/status.json b/apps/shell/src-tauri/capabilities/status.jsonnew file mode 100644index 00000000..caa49105--- /dev/null+++ b/apps/shell/src-tauri/capabilities/status.json@@ -0,0 +1,7 @@+{+ "identifier": "status",+ "description": "Bundled startup progress only; never product operations.",+ "local": true,+ "windows": ["main"],+ "permissions": ["allow-shell-status", "allow-shell-retry-startup", "allow-shell-capabilities"]+}diff --git a/apps/shell/src-tauri/installer/LICENSE.tauri-template b/apps/shell/src-tauri/installer/LICENSE.tauri-templatenew file mode 100644index 00000000..b08530d5--- /dev/null+++ b/apps/shell/src-tauri/installer/LICENSE.tauri-template@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2017 - Present Tauri Apps Contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/apps/shell/src-tauri/installer/README.md b/apps/shell/src-tauri/installer/README.mdnew file mode 100644index 00000000..09328667--- /dev/null+++ b/apps/shell/src-tauri/installer/README.md@@ -0,0 +1,16 @@+# Windows installer template++The template is derived from [Tauri CLI 2.11.4](https://github.com/tauri-apps/tauri/blob/tauri-cli-v2.11.4/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi), under the accompanying MIT license. The upstream source SHA-256 is `20f4ecc730defb71f1342eaeaec4021df13be3d843abba0effe88ea5835fa079`. Keep the npm CLI pin and template aligned.++Silent installation applies the default login/tray choices, skips interactive+process prompts and uses explicit default responses for failure messages. Runtime+acceptance must still demonstrate `/S` with the actual NSIS package. Passive+updates skip the options page and reuse saved preferences. Hooks are included+after the template declares the variables used by their page functions.++Local changes enforce native x64 and Task-only admission before product writes, fix the program directory under LocalAppData/Programs, replace directory selection with login/tray choices, preserve the headless service during shell upgrades, and delegate optional data removal to the Rust Agent-restore/journal transaction. The uninstaller deletes its inventoried files and empty directories; it never recursively removes an application/state directory.++Recovery/uninstall use an exact shell copy in the private NSIS plugin directory.+Unavailable Agent state has a separate default-No confirmation; silent/passive+runs refuse it and exceptional removal always keeps business data. Package cleanup+waits for both transaction owners to commit and preserves rollback sources.diff --git a/apps/shell/src-tauri/installer/hooks.nsh b/apps/shell/src-tauri/installer/hooks.nshnew file mode 100644index 00000000..94de54a8--- /dev/null+++ b/apps/shell/src-tauri/installer/hooks.nsh@@ -0,0 +1,125 @@+!include nsDialogs.nsh+!include LogicLib.nsh+Var HiRouteLoginChoice+Var HiRouteTrayChoice+Var HiRouteLoginCheckbox+Var HiRouteTrayCheckbox+Var HiRouteArguments+Var HiRouteRestoreConsent+Var HiRoutePrepared++!macro HiRouteRestoreConfirmation PREFIX+Function ${PREFIX}HiRouteConfirmUnavailableRestore+ StrCpy $HiRouteRestoreConsent 0+ IfSilent hiroute_restore_declined+ ${If} $PassiveMode = 1+ Return+ ${EndIf}+ MessageBox MB_YESNO|MB_ICONEXCLAMATION|MB_DEFBUTTON2 "HiRoute cannot read Agent settings because its background service is unavailable. Continuing stops only this account's HiRoute Task and may interrupt active work. Affected Agents cannot be listed; any HiRoute-configured Agent may need manual restoration. All HiRoute data will be kept. Continue without verified Agent restoration?" /SD IDNO IDNO hiroute_restore_declined+ StrCpy $HiRouteRestoreConsent 1+ hiroute_restore_declined:+FunctionEnd+!macroend+!insertmacro HiRouteRestoreConfirmation ""+!insertmacro HiRouteRestoreConfirmation "un."++Function HiRouteOptions+ ${IfThen} $PassiveMode = 1 ${|} Abort ${|}+ IfSilent 0 +2+ Abort+ nsDialogs::Create 1018+ Pop $0+ ${NSD_CreateLabel} 0 0 100% 32u "HiRoute installs for this account in LocalAppData\Programs\HiRoute. Background service data is kept separately."+ Pop $0+ ${NSD_CreateCheckbox} 0 45u 100% 14u "Start HiRoute and its background service at login"+ Pop $HiRouteLoginCheckbox+ ${If} $HiRouteLoginChoice != 0+ ${NSD_Check} $HiRouteLoginCheckbox+ ${EndIf}+ ${NSD_CreateCheckbox} 0 70u 100% 14u "Show tray icon and keep the window available in the tray"+ Pop $HiRouteTrayCheckbox+ ${If} $HiRouteTrayChoice != 0+ ${NSD_Check} $HiRouteTrayCheckbox+ ${EndIf}+ nsDialogs::Show+FunctionEnd+Function HiRouteOptionsLeave+ ${NSD_GetState} $HiRouteLoginCheckbox $HiRouteLoginChoice+ ${NSD_GetState} $HiRouteTrayCheckbox $HiRouteTrayChoice+FunctionEnd++!macro NSIS_HOOK_PREINSTALL+ StrCmp $INSTDIR "$LOCALAPPDATA\Programs\HiRoute" +3+ MessageBox MB_ICONSTOP "HiRoute install directory is invalid. No product files were written." /SD IDOK+ Abort+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-prepare "$PLUGINSDIR\hiroute-package.json"'+ Pop $0+ Pop $1+ ${If} $0 != 0+ MessageBox MB_ICONSTOP "HiRoute could not prepare a verified backup. Existing data is preserved." /SD IDOK+ Abort+ ${EndIf}+ StrCpy $HiRoutePrepared 1+!macroend++!macro NSIS_HOOK_POSTINSTALL+ StrCpy $HiRouteArguments ""+ ${If} $HiRouteLoginChoice = 0+ StrCpy $HiRouteArguments "$HiRouteArguments --no-login-start"+ ${EndIf}+ ${If} $HiRouteTrayChoice = 0+ StrCpy $HiRouteArguments "$HiRouteArguments --no-tray"+ ${EndIf}+ nsExec::ExecToStack '"$INSTDIR\hiroute-shell.exe" --installer-install $HiRouteArguments'+ Pop $0+ Pop $1+ ${If} $0 = 20+ ${IfThen} $PassiveMode = 1 ${|} Goto hiroute_install_failed ${|}+ IfSilent hiroute_install_failed+ MessageBox MB_YESNO|MB_ICONEXCLAMATION "The older background service cannot drain work. Stopping it may interrupt active requests and Worker tasks. Stop it and continue?" IDNO hiroute_install_failed+ nsExec::ExecToStack '"$INSTDIR\hiroute-shell.exe" --installer-install --allow-legacy-stop $HiRouteArguments'+ Pop $0+ Pop $1+ ${EndIf}+ ${If} $0 != 0+ hiroute_install_failed:+ MessageBox MB_ICONSTOP "HiRoute installation did not complete. Existing data is preserved. $1" /SD IDOK+ Abort+ ${EndIf}+!macroend++!macro NSIS_HOOK_PREUNINSTALL+ ${If} $UpdateMode != 1+ StrCpy $HiRouteArguments ""+ ${If} $DeleteAppDataCheckboxState = 1+ StrCpy $HiRouteArguments "--remove-data"+ ${EndIf}+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-uninstall-helper.exe" --installer-uninstall $HiRouteArguments'+ Pop $0+ Pop $1+ ${If} $0 = 23+ Call un.HiRouteConfirmUnavailableRestore+ ${If} $HiRouteRestoreConsent = 1+ ; Unverified restoration always retains the complete business data.+ StrCpy $DeleteAppDataCheckboxState 0+ StrCpy $HiRouteArguments "--allow-unavailable-agent-restore"+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-uninstall-helper.exe" --installer-uninstall $HiRouteArguments'+ Pop $0+ Pop $1+ ${EndIf}+ ${EndIf}+ ${If} $0 = 20+ ${IfThen} $PassiveMode = 1 ${|} Goto hiroute_uninstall_failed ${|}+ IfSilent hiroute_uninstall_failed+ MessageBox MB_YESNO|MB_ICONEXCLAMATION "The older background service cannot drain work. Stopping it may interrupt active requests and Worker tasks. Stop it and continue uninstalling?" IDNO hiroute_uninstall_failed+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-uninstall-helper.exe" --installer-uninstall --allow-legacy-stop $HiRouteArguments'+ Pop $0+ Pop $1+ ${EndIf}+ ${If} $0 != 0+ hiroute_uninstall_failed:+ MessageBox MB_ICONSTOP "HiRoute was not removed. Resolve any Agent restore decisions or active work, then retry. $1" /SD IDOK+ Abort+ ${EndIf}+ ${EndIf}+!macroenddiff --git a/apps/shell/src-tauri/installer/installer.nsi b/apps/shell/src-tauri/installer/installer.nsinew file mode 100644index 00000000..71cda8d6--- /dev/null+++ b/apps/shell/src-tauri/installer/installer.nsi@@ -0,0 +1,1085 @@+; Derived from tauri-cli-v2.11.4, upstream installer.nsi. See README.md and LICENSE.tauri-template.+Unicode true+ManifestDPIAware true+; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`)+; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see+; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300+; https://github.com/tauri-apps/tauri/pull/10106+ManifestDPIAwareness PerMonitorV2++!if "{{compression}}" == "none"+ SetCompress off+!else+ ; Set the compression algorithm. We default to LZMA.+ SetCompressor /SOLID "{{compression}}"+!endif++; Keep above !include to stay ahead of any plugin command+; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624+{{#if signed_plugins_path}}+!addplugindir "{{signed_plugins_path}}"+{{/if}}++!include MUI2.nsh+!include FileFunc.nsh+!include x64.nsh+!include WordFunc.nsh+!include "utils.nsh"+!include "FileAssociation.nsh"+!include "Win\COM.nsh"+!include "Win\Propkey.nsh"+!include "StrFunc.nsh"+${StrCase}+${StrLoc}+++!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"++!define MANUFACTURER "{{manufacturer}}"+!define PRODUCTNAME "{{product_name}}"+!define VERSION "{{version}}"+!define VERSIONWITHBUILD "{{version_with_build}}"+!define HOMEPAGE "{{homepage}}"+!define INSTALLMODE "{{install_mode}}"+!define LICENSE "{{license}}"+!define INSTALLERICON "{{installer_icon}}"+!define SIDEBARIMAGE "{{sidebar_image}}"+!define HEADERIMAGE "{{header_image}}"+!define UNINSTALLERICON "{{uninstaller_icon}}"+!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}"+!define MAINBINARYNAME "{{main_binary_name}}"+!define MAINBINARYSRCPATH "{{main_binary_path}}"+!define BUNDLEID "{{bundle_id}}"+!define COPYRIGHT "{{copyright}}"+!define OUTFILE "{{out_file}}"+!define ARCH "{{arch}}"+!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}"+!define ALLOWDOWNGRADES "{{allow_downgrades}}"+!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}"+!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}"+!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}"+!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}"+!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}"+!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}"+!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"+!define MANUKEY "Software\${MANUFACTURER}"+!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}"+!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}"+!define ESTIMATEDSIZE "{{estimated_size}}"+!define STARTMENUFOLDER "{{start_menu_folder}}"++Var PassiveMode+Var UpdateMode+Var NoShortcutMode+Var WixMode+Var OldMainBinaryName+Var HiRouteInstallMutex++{{#if installer_hooks}}+!include "{{installer_hooks}}"+{{/if}}++Name "${PRODUCTNAME}"+BrandingText "${COPYRIGHT}"+OutFile "${OUTFILE}"++; We don't actually use this value as default install path,+; it's just for nsis to append the product name folder in the directory selector+; https://nsis.sourceforge.io/Reference/InstallDir+!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}"+InstallDir "${PLACEHOLDER_INSTALL_DIR}"++VIProductVersion "${VERSIONWITHBUILD}"+VIAddVersionKey "ProductName" "${PRODUCTNAME}"+VIAddVersionKey "FileDescription" "${PRODUCTNAME}"+VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"+VIAddVersionKey "FileVersion" "${VERSION}"+VIAddVersionKey "ProductVersion" "${VERSION}"++# additional plugins+!addplugindir "${ADDITIONALPLUGINSPATH}"++; Uninstaller signing command+!if "${UNINSTALLERSIGNCOMMAND}" != ""+ !uninstfinalize '${UNINSTALLERSIGNCOMMAND}'+!endif++; Handle install mode, `perUser`, `perMachine` or `both`+!if "${INSTALLMODE}" == "perMachine"+ RequestExecutionLevel admin+!endif++!if "${INSTALLMODE}" == "currentUser"+ RequestExecutionLevel user+!endif++!if "${INSTALLMODE}" == "both"+ !define MULTIUSER_MUI+ !define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"+ !define MULTIUSER_INSTALLMODE_COMMANDLINE+ !if "${ARCH}" == "x64"+ !define MULTIUSER_USE_PROGRAMFILES64+ !else if "${ARCH}" == "arm64"+ !define MULTIUSER_USE_PROGRAMFILES64+ !endif+ !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"+ !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser"+ !define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME+ !define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation+ !define MULTIUSER_EXECUTIONLEVEL Highest+ !include MultiUser.nsh+!endif++; Installer icon+!if "${INSTALLERICON}" != ""+ !define MUI_ICON "${INSTALLERICON}"+!endif++; Installer sidebar image+!if "${SIDEBARIMAGE}" != ""+ !define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"+!endif++; Enable header images for installer and uninstaller pages when either image is configured.+!if "${HEADERIMAGE}" != ""+ !define MUI_HEADERIMAGE+!else if "${UNINSTALLERHEADERIMAGE}" != ""+ !define MUI_HEADERIMAGE+!endif++; Installer header image+!if "${HEADERIMAGE}" != ""+ !define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"+!endif++; Uninstaller header image+!if "${UNINSTALLERHEADERIMAGE}" != ""+ !define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}"+!endif++; Uninstaller icon+!if "${UNINSTALLERICON}" != ""+ !define MUI_UNICON "${UNINSTALLERICON}"+!endif++; Define registry key to store installer language+!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"+!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"+!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"++; Installer pages, must be ordered as they appear+; 1. Welcome Page+!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive+!insertmacro MUI_PAGE_WELCOME++; 2. License Page (if defined)+!if "${LICENSE}" != ""+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive+ !insertmacro MUI_PAGE_LICENSE "${LICENSE}"+!endif++; 3. Install mode (if it is set to `both`)+!if "${INSTALLMODE}" == "both"+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive+ !insertmacro MULTIUSER_PAGE_INSTALLMODE+!endif++; 4. Custom page to ask user if he wants to reinstall/uninstall+; only if a previous installation was detected+Var ReinstallPageCheck+Page custom PageReinstall PageLeaveReinstall+Function PageReinstall+ ; Replacement is owned by the HiRoute transaction; Control Panel owns uninstall.+ Abort+ ; Uninstall previous WiX installation if exists.+ ;+ ; A WiX installer stores the installation info in registry+ ; using a UUID and so we have to loop through all keys under+ ; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`+ ; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}+ ;+ ; This has a potential issue that there maybe another installation that matches+ ; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,+ ; however, this should be fine since the user will have to confirm the uninstallation+ ; and they can chose to abort it if doesn't make sense.+ StrCpy $0 0+ wix_loop:+ EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0+ StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on+ IntOp $0 $0 + 1+ ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"+ ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"+ StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop+ ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"+ ${StrCase} $R1 $R0 "L"+ ${StrLoc} $R0 $R1 "msiexec" ">"+ StrCmp $R0 0 0 wix_loop_done+ StrCpy $WixMode 1+ StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"+ Goto compare_version+ wix_loop_done:++ ; Check if there is an existing installation, if not, abort the reinstall page+ ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""+ ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"+ ${IfThen} "$R0$R1" == "" ${|} Abort ${|}++ ; Compare this installar version with the existing installation+ ; and modify the messages presented to the user accordingly+ compare_version:+ StrCpy $R4 "$(older)"+ ${If} $WixMode = 1+ ReadRegStr $R0 HKLM "$R6" "DisplayVersion"+ ${Else}+ ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"+ ${EndIf}+ ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}++ nsis_tauri_utils::SemverCompare "${VERSION}" $R0+ Pop $R0+ ; Reinstalling the same version+ ${If} $R0 = 0+ StrCpy $R1 "$(alreadyInstalledLong)"+ StrCpy $R2 "$(addOrReinstall)"+ StrCpy $R3 "$(uninstallApp)"+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"+ ; Upgrading+ ${ElseIf} $R0 = 1+ StrCpy $R1 "$(olderOrUnknownVersionInstalled)"+ StrCpy $R2 "$(uninstallBeforeInstalling)"+ StrCpy $R3 "$(dontUninstall)"+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"+ ; Downgrading+ ${ElseIf} $R0 = -1+ StrCpy $R1 "$(newerVersionInstalled)"+ StrCpy $R2 "$(uninstallBeforeInstalling)"+ !if "${ALLOWDOWNGRADES}" == "true"+ StrCpy $R3 "$(dontUninstall)"+ !else+ StrCpy $R3 "$(dontUninstallDowngrade)"+ !endif+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"+ ${Else}+ Abort+ ${EndIf}++ ; Skip showing the page if passive+ ;+ ; Note that we don't call this earlier at the begining+ ; of this function because we need to populate some variables+ ; related to current installed version if detected and whether+ ; we are downgrading or not.+ ${If} $PassiveMode = 1+ Call PageLeaveReinstall+ ${Else}+ nsDialogs::Create 1018+ Pop $R4+ ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}++ ${NSD_CreateLabel} 0 0 100% 24u $R1+ Pop $R1++ ${NSD_CreateRadioButton} 30u 50u -30u 8u $R2+ Pop $R2+ ${NSD_OnClick} $R2 PageReinstallUpdateSelection++ ${NSD_CreateRadioButton} 30u 70u -30u 8u $R3+ Pop $R3+ ; Disable this radio button if downgrading and downgrades are disabled+ !if "${ALLOWDOWNGRADES}" == "false"+ ${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|}+ !endif+ ${NSD_OnClick} $R3 PageReinstallUpdateSelection++ ; Check the first radio button if this the first time+ ; we enter this page or if the second button wasn't+ ; selected the last time we were on this page+ ${If} $ReinstallPageCheck <> 2+ SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0+ ${Else}+ SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0+ ${EndIf}++ ${NSD_SetFocus} $R2+ nsDialogs::Show+ ${EndIf}+FunctionEnd+Function PageReinstallUpdateSelection+ ${NSD_GetState} $R2 $R1+ ${If} $R1 == ${BST_CHECKED}+ StrCpy $ReinstallPageCheck 1+ ${Else}+ StrCpy $ReinstallPageCheck 2+ ${EndIf}+FunctionEnd+Function PageLeaveReinstall+ ${NSD_GetState} $R2 $R1++ ; If migrating from Wix, always uninstall+ ${If} $WixMode = 1+ Goto reinst_uninstall+ ${EndIf}++ ; In update mode, always proceeds without uninstalling+ ${If} $UpdateMode = 1+ Goto reinst_done+ ${EndIf}++ ; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version+ ; $R1 holds the radio buttons state:+ ; 1 => first choice was selected+ ; 0 => second choice was selected+ ${If} $R0 = 0 ; Same version, proceed+ ${If} $R1 = 1 ; User chose to add/reinstall+ Goto reinst_done+ ${Else} ; User chose to uninstall+ Goto reinst_uninstall+ ${EndIf}+ ${ElseIf} $R0 = 1 ; Upgrading+ ${If} $R1 = 1 ; User chose to uninstall+ Goto reinst_uninstall+ ${Else}+ Goto reinst_done ; User chose NOT to uninstall+ ${EndIf}+ ${ElseIf} $R0 = -1 ; Downgrading+ ${If} $R1 = 1 ; User chose to uninstall+ Goto reinst_uninstall+ ${Else}+ Goto reinst_done ; User chose NOT to uninstall+ ${EndIf}+ ${EndIf}++ reinst_uninstall:+ HideWindow+ ClearErrors++ ${If} $WixMode = 1+ ReadRegStr $R1 HKLM "$R6" "UninstallString"+ ExecWait '$R1' $0+ ${Else}+ ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""+ ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"+ ${IfThen} $R0 != 0 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; an upgrade must preserve the headless service and Agent configuration+ ${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P+ StrCpy $R1 "$R1 _?=$4" ; append uninstall directory+ ExecWait '$R1' $0+ ${EndIf}++ BringToFront++ ${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code++ ${If} $0 <> 0+ ${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"+ ; User cancelled wix uninstaller? return to select un/reinstall page+ ${If} $WixMode = 1+ ${AndIf} $0 = 1602+ Abort+ ${EndIf}++ ; User cancelled NSIS uninstaller? return to select un/reinstall page+ ${If} $0 = 1+ Abort+ ${EndIf}++ ; Other erros? show generic error message and return to select un/reinstall page+ MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)" /SD IDOK+ Abort+ ${EndIf}+ reinst_done:+FunctionEnd++; Fixed per-user program directory; never a standalone state directory.+Page custom HiRouteOptions HiRouteOptionsLeave++; 6. Start menu shortcut page+Var AppStartMenuFolder+!if "${STARTMENUFOLDER}" != ""+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive+ !define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}"+!else+ !define MUI_PAGE_CUSTOMFUNCTION_PRE Skip+!endif+!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder++; 7. Installation page+!insertmacro MUI_PAGE_INSTFILES++; 8. Finish page+;+; Don't auto jump to finish page after installation page,+; because the installation page has useful info that can be used debug any issues with the installer.+!define MUI_FINISHPAGE_NOAUTOCLOSE+; Use show readme button in the finish page as a button create a desktop shortcut+!define MUI_FINISHPAGE_SHOWREADME+!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"+!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut+; Show run app after installation.+!define MUI_FINISHPAGE_RUN+!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary+!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive+!insertmacro MUI_PAGE_FINISH++Function RunMainBinary+ nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""+FunctionEnd++; Uninstaller Pages+; 1. Confirm uninstall page+Var DeleteAppDataCheckbox+Var DeleteAppDataCheckboxState+!define /ifndef WS_EX_LAYOUTRTL 0x00400000+!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow+Function un.ConfirmShow ; Add add a `Delete app data` check box+ ; $1 inner dialog HWND+ ; $2 window DPI+ ; $3 style+ ; $4 x+ ; $5 y+ ; $6 width+ ; $7 height+ FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog+ System::Call "user32::GetDpiForWindow(p r1) i .r2"+ ${If} $(^RTL) = 1+ StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"+ IntOp $4 50 * $2+ ${Else}+ StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"+ IntOp $4 0 * $2+ ${EndIf}+ IntOp $5 100 * $2+ IntOp $6 400 * $2+ IntOp $7 25 * $2+ IntOp $4 $4 / 96+ IntOp $5 $5 / 96+ IntOp $6 $6 / 96+ IntOp $7 $7 / 96+ System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "Remove standalone HiRoute data (Agent files and projects are preserved)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'+ Pop $DeleteAppDataCheckbox+ SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1+ SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1+FunctionEnd+!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave+Function un.ConfirmLeave+ SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState+FunctionEnd+!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive+!insertmacro MUI_UNPAGE_CONFIRM++; 2. Uninstalling Page+!insertmacro MUI_UNPAGE_INSTFILES++;Languages+{{#each languages}}+!insertmacro MUI_LANGUAGE "{{this}}"+{{/each}}+!insertmacro MUI_RESERVEFILE_LANGDLL+{{#each language_files}}+ !include "{{this}}"+{{/each}}++Function .onInit+ StrCpy $HiRoutePrepared 0+ StrCpy $PassiveMode 0+ ${GetOptions} $CMDLINE "/P" $PassiveMode+ ${IfNot} ${Errors}+ StrCpy $PassiveMode 1+ ${EndIf}+ ; Native architecture and SCM admission precede product writes or WebView2 setup.+ System::Call 'kernel32::IsWow64Process2(p -1, *i .r0, *i .r1) i .r2'+ IntOp $1 $1 & 65535+ ${If} $2 = 0+ ${OrIf} $1 != 34404+ MessageBox MB_ICONSTOP "HiRoute Desktop requires a native Windows x64 host." /SD IDOK+ Abort+ ${EndIf}+ InitPluginsDir+ SetOutPath $PLUGINSDIR+ File /oname=hiroute-preflight.exe "${MAINBINARYSRCPATH}"+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-mutex'+ Pop $0+ Pop $1+ ${If} $0 != 0+ Abort+ ${EndIf}+ System::Call 'kernel32::CreateMutexW(p 0, i 0, w r1) p .r2 ?e'+ Pop $0+ StrCpy $HiRouteInstallMutex $2+ ${If} $2 = 0+ ${OrIf} $0 = 183+ MessageBox MB_ICONSTOP "Another HiRoute installation or uninstall is active for this account." /SD IDOK+ Abort+ ${EndIf}+ {{#each resources}}+ !if "{{this.[1]}}" == "standalone\package-manifest.json"+ File "/oname=$PLUGINSDIR\hiroute-package.json" "{{no-escape @key}}"+ !else if "{{this.[1]}}" == "standalone/package-manifest.json"+ File "/oname=$PLUGINSDIR\hiroute-package.json" "{{no-escape @key}}"+ !endif+ {{/each}}+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-preflight'+ Pop $0+ Pop $1+ ${If} $0 != 0+ MessageBox MB_ICONSTOP "HiRoute cannot install over this background service. $1" /SD IDOK+ Abort+ ${EndIf}+ ${IfNot} ${Silent}+ !insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"+ ${EndIf}+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-recover'+ Pop $0+ Pop $1+ ${If} $0 = 23+ Call HiRouteConfirmUnavailableRestore+ ${If} $HiRouteRestoreConsent = 1+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-recover --allow-unavailable-agent-restore'+ Pop $0+ Pop $1+ ${EndIf}+ ${EndIf}+ ${If} $0 != 0+ MessageBox MB_ICONSTOP "HiRoute needs installation recovery. Existing data and changed files are preserved." /SD IDOK+ Abort+ ${EndIf}+ ${If} ${Silent}+ ; Unattended installations always apply the documented default choices.+ StrCpy $HiRouteLoginChoice 1+ StrCpy $HiRouteTrayChoice 2+ ${Else}+ ExecWait '"$PLUGINSDIR\hiroute-preflight.exe" --installer-options' $0+ ${If} $0 > 3+ MessageBox MB_ICONSTOP "HiRoute could not read the existing installation options." /SD IDOK+ Abort+ ${EndIf}+ IntOp $HiRouteLoginChoice $0 & 1+ IntOp $HiRouteTrayChoice $0 & 2+ ${EndIf}+ ${GetOptions} $CMDLINE "/NS" $NoShortcutMode+ ${IfNot} ${Errors}+ StrCpy $NoShortcutMode 1+ ${EndIf}++ ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode+ ${IfNot} ${Errors}+ StrCpy $UpdateMode 1+ ${EndIf}++ !if "${DISPLAYLANGUAGESELECTOR}" == "true"+ !insertmacro MUI_LANGDLL_DISPLAY+ !endif++ !insertmacro SetContext++ ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}"+ ; Set default install location+ !if "${INSTALLMODE}" == "perMachine"+ ${If} ${RunningX64}+ !if "${ARCH}" == "x64"+ StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"+ !else if "${ARCH}" == "arm64"+ StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"+ !else+ StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"+ !endif+ ${Else}+ StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"+ ${EndIf}+ !else if "${INSTALLMODE}" == "currentUser"+ StrCpy $INSTDIR "$LOCALAPPDATA\Programs\HiRoute"+ !endif++ Call RestorePreviousInstallLocation+ ${EndIf}+++ ; Ignore stale registry locations and /D overrides. This directory is intentionally fixed.+ StrCpy $INSTDIR "$LOCALAPPDATA\Programs\HiRoute"++ !if "${INSTALLMODE}" == "both"+ !insertmacro MULTIUSER_INIT+ !endif+FunctionEnd+++Section EarlyChecks+ ; Abort silent installer if downgrades is disabled+ !if "${ALLOWDOWNGRADES}" == "false"+ ${If} ${Silent}+ ; If downgrading+ ${If} $R0 = -1+ System::Call 'kernel32::AttachConsole(i -1)i.r0'+ ${If} $0 <> 0+ System::Call 'kernel32::GetStdHandle(i -11)i.r0'+ System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color+ FileWrite $0 "$(silentDowngrades)"+ ${EndIf}+ Abort+ ${EndIf}+ ${EndIf}+ !endif++SectionEnd++Section WebView2+ ; Check if Webview2 is already installed and skip this section+ ${If} ${RunningX64}+ ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"+ ${Else}+ ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"+ ${EndIf}+ ${If} $4 == ""+ ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"+ ${EndIf}++ ${If} $4 == ""+ ; Webview2 installation+ ;+ ; Skip if updating+ ${If} $UpdateMode <> 1+ !if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"+ Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"+ DetailPrint "$(webview2Downloading)"+ NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"+ Pop $0+ ${If} $0 == "success"+ DetailPrint "$(webview2DownloadSuccess)"+ ${Else}+ DetailPrint "$(webview2DownloadError)"+ Abort "$(webview2AbortError)"+ ${EndIf}+ StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"+ Goto install_webview2+ !endif++ !if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"+ Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"+ File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"+ DetailPrint "$(installingWebview2)"+ StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"+ Goto install_webview2+ !endif++ !if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"+ Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"+ File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"+ DetailPrint "$(installingWebview2)"+ StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"+ Goto install_webview2+ !endif++ Goto webview2_done++ install_webview2:+ DetailPrint "$(installingWebview2)"+ ; $6 holds the path to the webview2 installer+ ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1+ ${If} $1 = 0+ DetailPrint "$(webview2InstallSuccess)"+ ${Else}+ DetailPrint "$(webview2InstallError)"+ Abort "$(webview2AbortError)"+ ${EndIf}+ webview2_done:+ ${EndIf}+ ${Else}+ !if "${MINIMUMWEBVIEW2VERSION}" != ""+ ${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0+ ${If} $R0 = 1+ update_webview:+ DetailPrint "$(installingWebview2)"+ ${If} ${RunningX64}+ ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path"+ ${Else}+ ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path"+ ${EndIf}+ ${If} $R1 == ""+ ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path"+ ${EndIf}+ ${If} $R1 != ""+ ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md+ ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"+ ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1+ ${If} $1 = 0+ DetailPrint "$(webview2InstallSuccess)"+ ${Else}+ MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" /SD IDABORT IDIGNORE ignore IDRETRY update_webview+ Quit+ ignore:+ ${EndIf}+ ${EndIf}+ ${EndIf}+ !endif+ ${EndIf}+SectionEnd++Section Install+ !ifmacrodef NSIS_HOOK_PREINSTALL+ !insertmacro NSIS_HOOK_PREINSTALL+ !endif++ SetOutPath $INSTDIR++ ; Copy main executable+ File "${MAINBINARYSRCPATH}"++ ; Copy resources+ {{#each resources_dirs}}+ CreateDirectory "$INSTDIR\\{{this}}"+ {{/each}}+ {{#each resources}}+ File /a "/oname={{this.[1]}}" "{{no-escape @key}}"+ {{/each}}++ ; Copy external binaries+ {{#each binaries}}+ File /a "/oname={{this}}" "{{no-escape @key}}"+ {{/each}}++ ; Create file associations+ {{#each file_associations as |association| ~}}+ {{#each association.ext as |ext| ~}}+ !insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""+ {{/each}}+ {{/each}}++ ; Register deep links+ {{#each deep_link_protocols as |protocol| ~}}+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" ""+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol"+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0"+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""+ {{/each}}++ ; Create uninstaller+ WriteUninstaller "$INSTDIR\uninstall.exe"++ ; Save $INSTDIR in registry for future installations+ WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR++ !if "${INSTALLMODE}" == "both"+ ; Save install mode to be selected by default for the next installation such as updating+ ; or when uninstalling+ WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1+ !endif++ ; Remove old main binary if it doesn't match new main binary name+ ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"+ ${If} $OldMainBinaryName != ""+ ${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"+ Delete "$INSTDIR\$OldMainBinaryName"+ ${EndIf}++ ; Save current MAINBINARYNAME for future updates+ WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"++ ; Registry information for add/remove programs+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}"+ WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"+ WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""+ WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""+ WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"+ WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"++ ${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2+ IntOp $0 $0 + ${ESTIMATEDSIZE}+ IntFmt $0 "0x%08X" $0+ WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0"++ !if "${HOMEPAGE}" != ""+ WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}"+ WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}"+ WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}"+ !endif++ ; Create start menu shortcut+ !insertmacro MUI_STARTMENU_WRITE_BEGIN Application+ Call CreateOrUpdateStartMenuShortcut+ !insertmacro MUI_STARTMENU_WRITE_END++ ; Create desktop shortcut for silent and passive installers+ ; because finish page will be skipped+ ${If} $PassiveMode = 1+ ${OrIf} ${Silent}+ Call CreateOrUpdateDesktopShortcut+ ${EndIf}++ !ifmacrodef NSIS_HOOK_POSTINSTALL+ !insertmacro NSIS_HOOK_POSTINSTALL+ !endif++ ; Auto close this page for passive mode+ ${If} $PassiveMode = 1+ SetAutoClose true+ ${EndIf}+SectionEnd++Function .onInstSuccess+ SetErrorLevel 0+ ; Check for `/R` flag only in silent and passive installers because+ ; GUI installer has a toggle for the user to (re)start the app+ ${If} $PassiveMode = 1+ ${OrIf} ${Silent}+ ${GetOptions} $CMDLINE "/R" $R0+ ${IfNot} ${Errors}+ ${GetOptions} $CMDLINE "/ARGS" $R0+ nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"+ ${EndIf}+ ${EndIf}+FunctionEnd++Function .onInstFailed+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-rollback'+ Pop $0+ Pop $1+ ${If} $0 = 23+ Call HiRouteConfirmUnavailableRestore+ ${If} $HiRouteRestoreConsent = 1+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-preflight.exe" --installer-rollback --allow-unavailable-agent-restore'+ Pop $0+ Pop $1+ ${EndIf}+ ${EndIf}+ ${If} $0 = 0+ ${AndIf} $HiRoutePrepared = 1+ ; A completed first-install rollback has no surviving Desktop inventory.+ ; Remove only the registration written by this attempt, never an older one.+ IfFileExists "$INSTDIR\shell-package.json" hiroute_rollback_registration_done+ IfFileExists "$INSTDIR\hiroute-shell.exe" hiroute_rollback_registration_done+ ReadRegStr $R0 HKCU "${UNINSTKEY}" "InstallLocation"+ ${If} $R0 == "$\"$INSTDIR$\""+ DeleteRegKey HKCU "${UNINSTKEY}"+ ${EndIf}+ ${EndIf}+ hiroute_rollback_registration_done:+ SetErrorLevel 1+FunctionEnd++Function un.onInit+ StrCmp $INSTDIR "$LOCALAPPDATA\Programs\HiRoute" +3+ MessageBox MB_ICONSTOP "HiRoute uninstall directory is invalid. No files were removed." /SD IDOK+ Abort+ InitPluginsDir+ System::Call 'kernel32::CopyFileW(w "$INSTDIR\hiroute-shell.exe", w "$PLUGINSDIR\hiroute-uninstall-helper.exe", i 1) i .r0'+ ${If} $0 = 0+ MessageBox MB_ICONSTOP "HiRoute could not prepare its uninstall helper. No files were removed. Close HiRoute and try again." /SD IDOK+ Abort+ ${EndIf}+ nsExec::ExecToStack '"$PLUGINSDIR\hiroute-uninstall-helper.exe" --installer-mutex'+ Pop $0+ Pop $1+ ${If} $0 != 0+ Abort+ ${EndIf}+ System::Call 'kernel32::CreateMutexW(p 0, i 0, w r1) p .r2 ?e'+ Pop $0+ StrCpy $HiRouteInstallMutex $2+ ${If} $2 = 0+ ${OrIf} $0 = 183+ MessageBox MB_ICONSTOP "Another HiRoute installation or uninstall is active for this account." /SD IDOK+ Abort+ ${EndIf}+ !insertmacro SetContext++ !if "${INSTALLMODE}" == "both"+ !insertmacro MULTIUSER_UNINIT+ !endif++ !insertmacro MUI_UNGETLANGUAGE++ ${GetOptions} $CMDLINE "/P" $PassiveMode+ ${IfNot} ${Errors}+ StrCpy $PassiveMode 1+ ${EndIf}++ ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode+ ${IfNot} ${Errors}+ StrCpy $UpdateMode 1+ ${EndIf}+FunctionEnd++Section Uninstall++ !ifmacrodef NSIS_HOOK_PREUNINSTALL+ !insertmacro NSIS_HOOK_PREUNINSTALL+ !endif++ ${IfNot} ${Silent}+ !insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"+ ${EndIf}++ ; Delete the app directory and its content from disk+ ; Copy main executable+ Delete "$INSTDIR\${MAINBINARYNAME}.exe"++ ; Delete resources+ {{#each resources}}+ Delete "$INSTDIR\\{{this.[1]}}"+ {{/each}}++ ; Delete external binaries+ {{#each binaries}}+ Delete "$INSTDIR\\{{this}}"+ {{/each}}++ ; Delete app associations+ {{#each file_associations as |association| ~}}+ {{#each association.ext as |ext| ~}}+ !insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}"+ {{/each}}+ {{/each}}++ ; Delete deep links+ {{#each deep_link_protocols as |protocol| ~}}+ ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" ""+ ${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""+ DeleteRegKey SHCTX "Software\Classes\\{{protocol}}"+ ${EndIf}+ {{/each}}+++ ; Delete uninstaller+ Delete "$INSTDIR\shell-install.json"+ Delete "$INSTDIR\shell-package.json"+ Delete "$INSTDIR\uninstall.exe"++ {{#each resources_ancestors}}+ RMDir /REBOOTOK "$INSTDIR\\{{this}}"+ {{/each}}+ RMDir "$INSTDIR"++ ; Remove shortcuts if not updating+ ${If} $UpdateMode <> 1+ !insertmacro DeleteAppUserModelId++ ; Remove start menu shortcut+ !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder+ !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ Pop $0+ ${If} $0 = 1+ !insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"+ Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"+ RMDir "$SMPROGRAMS\$AppStartMenuFolder"+ ${EndIf}+ !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ Pop $0+ ${If} $0 = 1+ !insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk"+ Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk"+ ${EndIf}++ ; Remove desktop shortcuts+ !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ Pop $0+ ${If} $0 = 1+ !insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk"+ Delete "$DESKTOP\${PRODUCTNAME}.lnk"+ ${EndIf}+ ${EndIf}++ ; Remove registry information for add/remove programs+ !if "${INSTALLMODE}" == "both"+ DeleteRegKey SHCTX "${UNINSTKEY}"+ !else if "${INSTALLMODE}" == "perMachine"+ DeleteRegKey HKLM "${UNINSTKEY}"+ !else+ DeleteRegKey HKCU "${UNINSTKEY}"+ !endif++ ; The native hook removes only the exact owned login command and preserves foreign values.++ ; Standalone data removal is exclusively owned by the native restore/journal transaction.+ !ifmacrodef NSIS_HOOK_POSTUNINSTALL+ !insertmacro NSIS_HOOK_POSTUNINSTALL+ !endif++ ; Auto close if passive mode or updating+ ${If} $PassiveMode = 1+ ${OrIf} $UpdateMode = 1+ SetAutoClose true+ ${EndIf}+SectionEnd++Function RestorePreviousInstallLocation+ ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""+ StrCmp $4 "" +2 0+ StrCpy $INSTDIR $4+FunctionEnd++Function Skip+ Abort+FunctionEnd++Function SkipIfPassive+ ${IfThen} $PassiveMode = 1 ${|} Abort ${|}+FunctionEnd+Function un.SkipIfPassive+ ${IfThen} $PassiveMode = 1 ${|} Abort ${|}+FunctionEnd++Function CreateOrUpdateStartMenuShortcut+ ; We used to use product name as MAINBINARYNAME+ ; migrate old shortcuts to target the new MAINBINARYNAME+ StrCpy $R0 0++ !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"+ Pop $0+ ${If} $0 = 1+ !insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ StrCpy $R0 1+ ${EndIf}++ !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"+ Pop $0+ ${If} $0 = 1+ !insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ StrCpy $R0 1+ ${EndIf}++ ${If} $R0 = 1+ Return+ ${EndIf}++ ; Skip creating shortcut if in update mode or no shortcut mode+ ; but always create if migrating from wix+ ${If} $WixMode = 0+ ${If} $UpdateMode = 1+ ${OrIf} $NoShortcutMode = 1+ Return+ ${EndIf}+ ${EndIf}++ !if "${STARTMENUFOLDER}" != ""+ CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"+ CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"+ !else+ CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"+ !endif+FunctionEnd++Function CreateOrUpdateDesktopShortcut+ ; We used to use product name as MAINBINARYNAME+ ; migrate old shortcuts to target the new MAINBINARYNAME+ !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"+ Pop $0+ ${If} $0 = 1+ !insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ Return+ ${EndIf}++ ; Skip creating shortcut if in update mode or no shortcut mode+ ; but always create if migrating from wix+ ${If} $WixMode = 0+ ${If} $UpdateMode = 1+ ${OrIf} $NoShortcutMode = 1+ Return+ ${EndIf}+ ${EndIf}++ CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"+ !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"+FunctionEnddiff --git a/apps/shell/src-tauri/src/handoff.rs b/apps/shell/src-tauri/src/handoff.rsnew file mode 100644index 00000000..7b232680--- /dev/null+++ b/apps/shell/src-tauri/src/handoff.rs@@ -0,0 +1,41 @@+//! A helper's readiness or a parent's disappearance does not authorize replacement.+use serde::{Deserialize, Serialize};+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub(crate) struct WindowsUpdateCommitV1 {+ schema: String,+ generation: String,+ installer_sha256: String,+}+impl WindowsUpdateCommitV1 {+ pub(crate) fn new(generation: String, installer_sha256: String) -> Self {+ Self {+ schema: "hiroute.windows-shell-update-commit/v1".into(),+ generation,+ installer_sha256,+ }+ }+ pub(crate) fn matches(&self, generation: &str, installer_sha256: &str) -> bool {+ self.schema == "hiroute.windows-shell-update-commit/v1"+ && self.generation == generation+ && self.installer_sha256 == installer_sha256+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn readiness_parent_loss_and_another_installer_cannot_authorize_replacement() {+ for record in [b"{}".as_slice(), br#"{"ready":true,"generation":"abc"}"#] {+ assert!(serde_json::from_slice::<WindowsUpdateCommitV1>(record).is_err());+ }+ let commit:WindowsUpdateCommitV1=serde_json::from_value(serde_json::json!({"schema":"hiroute.windows-shell-update-commit/v1","generation":"abc","installer_sha256":"a".repeat(64)})).unwrap();+ assert!(commit.matches("abc", &"a".repeat(64)));+ assert!(!commit.matches("next-attempt", &"a".repeat(64)));+ assert!(!commit.matches("abc", &"b".repeat(64)));+ let mut unknown =+ serde_json::to_value(WindowsUpdateCommitV1::new("abc".into(), "a".repeat(64))).unwrap();+ unknown["executable"] = serde_json::json!("arbitrary.exe");+ assert!(serde_json::from_value::<WindowsUpdateCommitV1>(unknown).is_err());+ }+}diff --git a/apps/shell/src-tauri/src/lib.rs b/apps/shell/src-tauri/src/lib.rsnew file mode 100644index 00000000..e47552ed--- /dev/null+++ b/apps/shell/src-tauri/src/lib.rs@@ -0,0 +1,90 @@+#![forbid(unsafe_code)]+use url::Url;+#[cfg(any(test, all(windows, feature = "shell-runtime")))]+mod handoff;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ConsoleOrigin(String);+impl ConsoleOrigin {+ pub fn launch(value: &str) -> Result<(Self, Url), &'static str> {+ let url = Url::parse(value).map_err(|_| "CONSOLE_LAUNCH_INVALID")?;+ let query: Vec<_> = url.query_pairs().collect();+ if url.scheme() != "http"+ || url.host_str() != Some("127.0.0.1")+ || url.port_or_known_default().is_none_or(|p| p == 0)+ || url.path() != "/launch"+ || !url.username().is_empty()+ || url.password().is_some()+ || url.fragment().is_some()+ || query.len() != 1+ || query[0].0 != "code"+ || query[0].1.len() != 64+ || !query[0]+ .1+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ {+ return Err("CONSOLE_LAUNCH_INVALID");+ }+ Ok((Self(url.origin().ascii_serialization()), url))+ }+ pub fn allows(&self, url: &Url) -> bool {+ url.origin().ascii_serialization() == self.0+ && url.username().is_empty()+ && url.password().is_none()+ }+}+pub fn external_url(value: &str) -> Result<Url, &'static str> {+ let url = Url::parse(value).map_err(|_| "EXTERNAL_URL_INVALID")?;+ if value.len() > 2048+ || value.chars().any(|c| c.is_control() || c.is_whitespace())+ || !matches!(url.scheme(), "http" | "https")+ || url.host_str().is_none()+ || !url.username().is_empty()+ || url.password().is_some()+ {+ return Err("EXTERNAL_URL_SCHEME_DENIED");+ }+ Ok(url)+}+#[cfg(all(windows, feature = "shell-runtime"))]+pub mod runtime;++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn launch_and_ipc_scope_use_exact_console_origin_and_never_accept_remote_credentials() {+ let link = format!("http://127.0.0.1:5838/launch?code={}", "a".repeat(64));+ let (origin, _) = ConsoleOrigin::launch(&link).unwrap();+ assert!(origin.allows(&Url::parse("http://127.0.0.1:5838/").unwrap()));+ for url in [+ "http://localhost:5838/",+ "http://127.0.0.1:5839/",+ "https://127.0.0.1:5838/",+ "http://example.test:5838/",+ ] {+ assert!(!origin.allows(&Url::parse(url).unwrap()));+ }+ for value in [+ link.replace("127.0.0.1", "example.test"),+ link.clone() + "&code=duplicate",+ link.clone() + "#fragment",+ link.replace("/launch", "/other"),+ ] {+ assert!(ConsoleOrigin::launch(&value).is_err());+ }+ }+ #[test]+ fn host_external_open_cannot_execute_schemes_or_embed_account_credentials() {+ for value in [+ "file:///C:/test",+ "javascript:alert(1)",+ "http://user:[email protected]",+ "https://example.test/\nnext",+ ] {+ assert!(external_url(value).is_err());+ }+ assert!(external_url("https://example.test/guide").is_ok());+ }+}diff --git a/apps/shell/src-tauri/src/main.rs b/apps/shell/src-tauri/src/main.rsnew file mode 100644index 00000000..4d6c4013--- /dev/null+++ b/apps/shell/src-tauri/src/main.rs@@ -0,0 +1,16 @@+#![forbid(unsafe_code)]+#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]+fn main() {+ #[cfg(windows)]+ {+ if let Some(exit) = hiroute_shell::runtime::run_helper() {+ std::process::exit(exit);+ }+ hiroute_shell::runtime::run();+ }+ #[cfg(not(windows))]+ {+ eprintln!("UNSUPPORTED_PLATFORM");+ std::process::exit(2);+ }+}diff --git a/apps/shell/src-tauri/src/runtime/commands.rs b/apps/shell/src-tauri/src/runtime/commands.rsnew file mode 100644index 00000000..61648441--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/commands.rs@@ -0,0 +1,216 @@+use super::*;+use serde_json::{Value, json};+use tauri::State;+type StateRef<'a> = State<'a, Arc<ShellState>>;+#[tauri::command]+pub(super) fn shell_status(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<Status, &'static str> {+ authorize_status(&window)?;+ state+ .status+ .lock()+ .map(|s| s.clone())+ .map_err(|_| "SHELL_STATE_UNAVAILABLE")+}+#[tauri::command]+pub(super) fn shell_retry_startup(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<(), &'static str> {+ authorize_status(&window)?;+ recover_and_start(&window, state.inner())+}+fn recover_and_start(window: &WebviewWindow, state: &Arc<ShellState>) -> Result<(), &'static str> {+ match updater::recover_startup(window.app_handle(), state, true) {+ Ok(true) => {}+ Ok(false) => start(window.app_handle().clone(), state.clone()),+ Err(code) => {+ state.phase("failed", Some(code));+ return Err(code);+ }+ }+ Ok(())+}+#[tauri::command]+pub(super) fn shell_capabilities(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<Value, &'static str> {+ if authorize_status(&window).is_err() {+ authorize(&window, &state)?;+ }+ Ok(+ json!({"host":"shell-console","platform":"windows","updates":true,"cli_entry":false,"quit":true,"titlebar":false,"login_start":true,"directory_reveal":"path"}),+ )+}+#[tauri::command]+pub(super) async fn shell_open_in_browser(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<(), &'static str> {+ authorize(&window, &state)?;+ let (_, url) = service::launch().await?;+ hiroute_platform::windows::shell_open::url(url.as_str()).map_err(|_| "BROWSER_UNAVAILABLE")+}+#[tauri::command]+pub(super) fn shell_open_external_url(+ window: WebviewWindow,+ state: StateRef<'_>,+ url: String,+) -> Result<(), &'static str> {+ authorize(&window, &state)?;+ let url = crate::external_url(&url)?;+ hiroute_platform::windows::shell_open::url(url.as_str()).map_err(|_| "BROWSER_UNAVAILABLE")+}+#[tauri::command]+pub(super) async fn shell_save_classifier_openapi(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<&'static str, &'static str> {+ use tauri_plugin_dialog::DialogExt;+ authorize(&window, &state)?;+ tauri::async_runtime::spawn_blocking(move || {+ let Some(path) = window+ .dialog()+ .file()+ .set_file_name("hiroute-decision.openapi.json")+ .add_filter("OpenAPI JSON", &["json"])+ .blocking_save_file()+ else {+ return Ok("cancelled");+ };+ let path = path.into_path().map_err(|_| "FILE_SAVE_UNAVAILABLE")?;+ std::fs::write(+ path,+ include_bytes!("../../../../../decision-extensions/api/decision.openapi.json"),+ )+ .map_err(|_| "FILE_SAVE_UNAVAILABLE")?;+ Ok("saved")+ })+ .await+ .map_err(|_| "FILE_SAVE_UNAVAILABLE")?+}+pub(super) fn login_get() -> Result<Value, &'static str> {+ let native = std::env::current_exe().map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?;+ let run = hiroute_platform::windows::shell_login::enabled(&native)+ .map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?;+ let manager = service::manager(&["service", "autostart", "status", "--output", "json"])?;+ let task = manager["enabled"]+ .as_bool()+ .or_else(|| manager["autostart_enabled"].as_bool())+ .ok_or("SHELL_LOGIN_UNAVAILABLE")?;+ Ok(json!({"enabled":run && task,"shell_enabled":run,"service_enabled":task}))+}+pub(super) fn login_set(enabled: bool) -> Result<Value, &'static str> {+ let before = login_get()?;+ let native = std::env::current_exe().map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?;+ service::manager(&[+ "service",+ "autostart",+ if enabled { "enable" } else { "disable" },+ "--output",+ "json",+ ])?;+ if hiroute_platform::windows::shell_login::set(&native, enabled).is_err() {+ let old = before["service_enabled"] == true;+ let _ = service::manager(&[+ "service",+ "autostart",+ if old { "enable" } else { "disable" },+ "--output",+ "json",+ ]);+ return Err("SHELL_LOGIN_UNAVAILABLE");+ }+ login_get()+}+#[tauri::command]+pub(super) async fn shell_login_start_get(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<Value, &'static str> {+ authorize(&window, &state)?;+ tauri::async_runtime::spawn_blocking(login_get)+ .await+ .map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?+}+#[tauri::command]+pub(super) async fn shell_login_start_set(+ window: WebviewWindow,+ state: StateRef<'_>,+ enabled: bool,+) -> Result<Value, &'static str> {+ authorize(&window, &state)?;+ tauri::async_runtime::spawn_blocking(move || login_set(enabled))+ .await+ .map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?+}+#[tauri::command]+pub(super) async fn shell_restart_service(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<(), &'static str> {+ authorize(&window, &state)?;+ tauri::async_runtime::spawn_blocking(|| {+ service::manager(&["service", "restart", "--output", "json"])+ })+ .await+ .map_err(|_| "SERVICE_RESTART_FAILED")??;+ Ok(())+}+#[tauri::command]+pub(super) fn shell_reconnect(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<(), &'static str> {+ authorize(&window, &state)?;+ window+ .navigate(+ url::Url::parse("http://tauri.localhost/").map_err(|_| "SHELL_NAVIGATION_FAILED")?,+ )+ .map_err(|_| "SHELL_NAVIGATION_FAILED")?;+ *state.origin.lock().map_err(|_| "SHELL_STATE_UNAVAILABLE")? = None;+ recover_and_start(&window, state.inner())+}+#[tauri::command]+pub(super) fn shell_update_status(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<updater::UpdateView, &'static str> {+ authorize(&window, &state)?;+ state.updater.status()+}+#[tauri::command]+pub(super) fn shell_update_check(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<updater::UpdateView, &'static str> {+ authorize(&window, &state)?;+ updater::Updater::check(state.inner().clone())+}+#[tauri::command]+pub(super) fn shell_update_download(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<updater::UpdateView, &'static str> {+ authorize(&window, &state)?;+ updater::Updater::download(state.inner().clone())+}+#[tauri::command]+pub(super) fn shell_update_install(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<updater::UpdateView, &'static str> {+ authorize(&window, &state)?;+ updater::Updater::install(window.app_handle().clone(), state.inner().clone())+}+#[tauri::command]+pub(super) fn shell_update_cancel(+ window: WebviewWindow,+ state: StateRef<'_>,+) -> Result<updater::UpdateView, &'static str> {+ authorize(&window, &state)?;+ state.updater.cancel()+}diff --git a/apps/shell/src-tauri/src/runtime/install_transaction.rs b/apps/shell/src-tauri/src/runtime/install_transaction.rsnew file mode 100644index 00000000..c027e00a--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/install_transaction.rs@@ -0,0 +1,732 @@+//! Shell files and the standalone journal have separate owners. Retain shell bytes until+//! the native standalone transaction, login settings and readiness check all succeed.+use hiroute_host_runtime::standalone_install::{Package, windows};+use hiroute_platform::windows::security;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::{+ collections::BTreeMap,+ fs,+ io::{self, Read},+ path::{Path, PathBuf},+};++const INVENTORY: &str = "shell-package.json";+const PENDING: &str = "install-pending.json";+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Inventory {+ schema: String,+ files: BTreeMap<String, String>,+}+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Pending {+ schema: String,+ phase: Phase,+ old: BTreeMap<String, String>,+ new: BTreeMap<String, String>,+ service_active: bool,+ previous_package: Option<PathBuf>,+ previous_autostart: bool,+ console_desired: hiroute_host_runtime::ConsoleListenerDesiredV1,+ shell_login: bool,+}+#[derive(Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+enum Phase {+ Prepared,+ Committed,+}+fn invalid() -> io::Error {+ io::Error::other("SHELL_INSTALL_RECOVERY_REQUIRED")+}+fn present(path: &Path) -> io::Result<bool> {+ match fs::symlink_metadata(path) {+ Ok(_) => Ok(true),+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error),+ }+}+pub(super) fn data() -> io::Result<PathBuf> {+ Ok(hiroute_platform::windows::background::local_app_data()?.join("HiRoute/shell"))+}+pub(super) fn root() -> io::Result<PathBuf> {+ Ok(hiroute_platform::windows::background::local_app_data()?.join("Programs/HiRoute"))+}+pub(super) fn hash(path: &Path) -> io::Result<String> {+ let mut file = security::open_identity(path, false)?;+ if file.metadata()?.len() > 2 * 1024 * 1024 * 1024 {+ return Err(invalid());+ }+ let mut sha = Sha256::new();+ let mut buf = [0; 64 * 1024];+ loop {+ let n = file.read(&mut buf)?;+ if n == 0 {+ break;+ }+ sha.update(&buf[..n]);+ }+ Ok(format!("{:x}", sha.finalize()))+}+fn safe_name(name: &str) -> bool {+ !name.is_empty()+ && name.len() < 512+ && !name.contains('\\')+ && name.split('/').all(|s| {+ !s.is_empty()+ && s != "."+ && s != ".."+ && s.bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"-_.@".contains(&b))+ })+}+fn validate(files: &BTreeMap<String, String>) -> io::Result<()> {+ if files.len() > 6000+ || files.iter().any(|(n, h)| {+ !safe_name(n) || h.len() != 64 || !h.bytes().all(|b| b.is_ascii_hexdigit())+ })+ {+ return Err(invalid());+ }+ Ok(())+}+fn read<T: serde::de::DeserializeOwned>(path: &Path, private: bool) -> io::Result<T> {+ let mut file = if private {+ security::open_owner_only(path, false)?+ } else {+ security::open_identity(path, false)?+ };+ let mut bytes = vec![];+ file.by_ref()+ .take(1024 * 1024 + 1)+ .read_to_end(&mut bytes)?;+ if bytes.len() > 1024 * 1024 {+ return Err(invalid());+ }+ serde_json::from_slice(&bytes).map_err(|_| invalid())+}+fn write(path: &Path, value: &impl Serialize) -> io::Result<()> {+ hiroute_platform::durable::write_private_atomic(+ path,+ &serde_json::to_vec(value).map_err(|_| invalid())?,+ )+}+fn backup_file(source: &Path, dest: &Path, expected: &str) -> io::Result<()> {+ let parent = security::ensure_private_directory(dest.parent().ok_or_else(invalid)?)?;+ if !present(dest)? {+ let mut source = security::open_identity(source, false)?;+ let mut output =+ security::create_owner_only_file_at(&parent, dest.file_name().ok_or_else(invalid)?)?;+ io::copy(&mut source, &mut output)?;+ output.sync_all()?;+ // The owner-only writer denies all sharing on Windows. Close it before+ // reopening the completed backup for identity and content verification.+ drop(output);+ }+ if hash(dest)? != expected {+ return Err(invalid());+ }+ Ok(())+}+fn pending() -> io::Result<Pending> {+ let value: Pending = read(&data()?.join(PENDING), true)?;+ if value.schema != "hiroute.windows-shell-transaction/v1" {+ return Err(invalid());+ }+ validate(&value.old)?;+ validate(&value.new)?;+ if let Some(package) = &value.previous_package {+ let layout =+ hiroute_host_runtime::StandaloneLayout::from_environment().map_err(|_| invalid())?;+ if package.parent() != Some(layout.home.join(".local/lib/hiroute").as_path())+ || package.components().any(|p| {+ matches!(+ p,+ std::path::Component::ParentDir | std::path::Component::CurDir+ )+ })+ {+ return Err(invalid());+ }+ }+ value.console_desired.validate().map_err(|_| invalid())?;+ Ok(value)+}+pub(super) fn has_pending() -> io::Result<bool> {+ present(&data()?.join(PENDING))+}+pub(super) fn validate_installed() -> io::Result<()> {+ let root = root()?;+ let inventory: Inventory = read(&root.join(INVENTORY), false)?;+ if inventory.schema != "hiroute.windows-shell-package/v1" {+ return Err(invalid());+ }+ validate(&inventory.files)?;+ for (name, expected) in inventory.files {+ let path = root.join(name);+ if present(&path)? && hash(&path)? != expected {+ return Err(invalid());+ }+ }+ Ok(())+}+pub(super) fn prepare(manifest: &Path) -> io::Result<()> {+ windows::preflight()?;+ let package: Package = read(manifest, false)?;+ package.validate()?;+ if package.target != "x86_64-pc-windows-msvc" {+ return Err(invalid());+ }+ if has_pending()? {+ rollback(false)?;+ }+ let root = root()?;+ let mut old = BTreeMap::new();+ let inventory = root.join(INVENTORY);+ let existed = present(&inventory)?;+ if existed {+ let before: Inventory = read(&inventory, false)?;+ if before.schema != "hiroute.windows-shell-package/v1" {+ return Err(invalid());+ }+ validate(&before.files)?;+ for (name, expected) in before.files {+ if !present(&root.join(&name))? {+ continue;+ }+ if hash(&root.join(&name))? != expected {+ return Err(invalid());+ }+ old.insert(name, expected);+ }+ old.insert(INVENTORY.into(), hash(&inventory)?);+ } else if present(&root.join("hiroute-shell.exe"))? {+ return Err(invalid());+ }+ let mut new: BTreeMap<String, String> = package+ .files+ .iter()+ .map(|(name, item)| {+ (+ format!("standalone/{}", Package::relative(name)),+ item.sha256.clone(),+ )+ })+ .collect();+ new.insert("standalone/package-manifest.json".into(), hash(manifest)?);+ new.insert("hiroute-shell.exe".into(), hash(&std::env::current_exe()?)?);+ validate(&new)?;+ for name in new.keys() {+ if present(&root.join(name))? && !old.contains_key(name) {+ return Err(invalid());+ }+ }+ let layout =+ hiroute_host_runtime::StandaloneLayout::from_environment().map_err(|_| invalid())?;+ let previous_package =+ match hiroute_host_runtime::read_standalone_install_record(&layout.marker_path) {+ Ok(record) => Some(record.install_root),+ Err(_) if !present(&layout.marker_path)? => None,+ Err(_) => return Err(invalid()),+ };+ let (service_active, previous_autostart) = if previous_package.is_some() {+ let definition = hiroute_platform::windows::background::read_definition(+ &layout.data_root.join("service/windows-background.json"),+ )?;+ (+ hiroute_platform::windows::task::active(&definition)?,+ hiroute_platform::windows::task::autostart(&definition)?,+ )+ } else {+ (false, false)+ };+ let console_desired =+ hiroute_host_runtime::ConsoleListenerStore::new(layout.gateway_config_root())+ .read()+ .map_err(|_| invalid())?+ .desired;+ let shell_login = if existed {+ hiroute_platform::windows::shell_login::enabled(&root.join("hiroute-shell.exe"))?+ } else {+ false+ };+ let data = data()?;+ security::ensure_private_directory(&data)?;+ let backups = data.join("install-backups");+ security::ensure_private_directory(&backups)?;+ for (name, expected) in &old {+ backup_file(&root.join(name), &backups.join(name), expected)?;+ }+ write(+ &data.join(PENDING),+ &Pending {+ schema: "hiroute.windows-shell-transaction/v1".into(),+ phase: Phase::Prepared,+ old,+ new,+ service_active,+ previous_package,+ previous_autostart,+ console_desired,+ shell_login,+ },+ )+}+/// NSIS overlays files, so old content-hashed assets must leave the package's+/// closed file set before the Rust package reader admits the new payload.+pub(super) fn prune_payload() -> io::Result<()> {+ let value = pending()?;+ if value.phase != Phase::Prepared {+ return Err(invalid());+ }+ prune_old_payload(+ &root()?,+ &data()?.join("install-backups"),+ &value.old,+ &value.new,+ )+}+fn prune_old_payload(+ root: &Path,+ backups: &Path,+ old: &BTreeMap<String, String>,+ new: &BTreeMap<String, String>,+) -> io::Result<()> {+ validate(old)?;+ validate(new)?;+ let obsolete: Vec<_> = old+ .iter()+ .filter(|(name, _)| name.starts_with("standalone/") && !new.contains_key(*name))+ .collect();+ // Check the whole deletion set and every retained rollback copy first.+ for (name, expected) in &obsolete {+ if hash(&backups.join(name))? != **expected+ || (present(&root.join(name))? && hash(&root.join(name))? != **expected)+ {+ return Err(invalid());+ }+ }+ for (name, _) in obsolete {+ let path = root.join(name);+ if present(&path)? {+ fs::remove_file(path)?;+ }+ }+ Ok(())+}+/// Record NSIS-generated files before any service mutation. Unknown replacements stay for repair.+pub(super) fn record_generated() -> io::Result<()> {+ let mut value = pending()?;+ let root = root()?;+ for name in ["uninstall.exe", "shell-install.json"] {+ let path = root.join(name);+ if present(&path)? {+ value.new.insert(name.into(), hash(&path)?);+ }+ }+ write(&data()?.join(PENDING), &value)+}+pub(super) fn write_preferences(bytes: &[u8]) -> io::Result<()> {+ let mut value = pending()?;+ value.new.insert(+ "shell-install.json".into(),+ format!("{:x}", Sha256::digest(bytes)),+ );+ write(&data()?.join(PENDING), &value)?;+ hiroute_platform::durable::write_private_atomic(&root()?.join("shell-install.json"), bytes)+}+fn cleanup_committed() {+ let report = match windows::cleanup_packages() {+ Ok(report) => serde_json::json!({"status":"complete","packages":report}),+ Err(_) => serde_json::json!({"status":"pending","code":"INSTALL_PACKAGE_CLEANUP_REQUIRED"}),+ };+ if let Ok(data) = data() {+ let _ = write(&data.join("package-cleanup.json"), &report);+ }+}+pub(super) fn commit() -> io::Result<()> {+ record_generated()?;+ let mut value = pending()?;+ let root = root()?;+ for (name, expected) in &value.new {+ if hash(&root.join(name))? != *expected {+ return Err(invalid());+ }+ }+ for (name, expected) in &value.old {+ let path = root.join(name);+ if name != INVENTORY && !value.new.contains_key(name) && present(&path)? {+ if hash(&path)? != *expected {+ return Err(invalid());+ }+ fs::remove_file(path)?;+ }+ }+ let inventory = Inventory {+ schema: "hiroute.windows-shell-package/v1".into(),+ files: value.new.clone(),+ };+ let bytes = serde_json::to_vec(&inventory).map_err(|_| invalid())?;+ value+ .new+ .insert(INVENTORY.into(), format!("{:x}", Sha256::digest(&bytes)));+ write(&data()?.join(PENDING), &value)?;+ hiroute_platform::durable::write_private_atomic(&root.join(INVENTORY), &bytes)?;+ value.phase = Phase::Committed;+ write(&data()?.join(PENDING), &value)?;+ complete_commit(&data()?, &value.old)?;+ cleanup_committed();+ Ok(())+}++fn complete_commit(data: &Path, old: &BTreeMap<String, String>) -> io::Result<()> {+ // A manual install has no update finisher to replace an earlier failure. Keep+ // the committed journal until reporting succeeds so recovery can repeat it.+ write(+ &data.join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"succeeded"}),+ )?;+ clear(data, old)+}++fn clear(data: &Path, old: &BTreeMap<String, String>) -> io::Result<()> {+ for (name, expected) in old {+ let path = data.join("install-backups").join(name);+ if present(&path)? {+ if hash(&path)? != *expected {+ return Err(invalid());+ }+ fs::remove_file(path)?;+ }+ }+ fs::remove_file(data.join(PENDING))+}+pub(super) fn rollback(allow_unavailable_agent_restore: bool) -> io::Result<()> {+ if !has_pending()? {+ return Ok(());+ }+ let value = pending()?;+ let root = root()?;+ if value.phase == Phase::Committed {+ validate_installed()?;+ complete_commit(&data()?, &value.old)?;+ cleanup_committed();+ return Ok(());+ }+ windows::recover_pending()?;+ // Validate the complete replacement set before restoring the first file.+ for name in value.old.keys().chain(value.new.keys()) {+ let path = root.join(name);+ if present(&path)? {+ let actual = hash(&path)?;+ if value.old.get(name) != Some(&actual) && value.new.get(name) != Some(&actual) {+ return Err(invalid());+ }+ }+ }+ let remove_added_path = super::installer::path_added(&root).map_err(|_| invalid())?+ && !super::installer::path_added(&data()?.join("install-backups"))+ .map_err(|_| invalid())?;+ // A failed post-install hook can follow a committed standalone transaction. Reinstall+ // the retained package only if that core changed. An early payload rejection must+ // not drain unrelated work in the still-running previous installation.+ if let Some(package) = &value.previous_package {+ let layout =+ hiroute_host_runtime::StandaloneLayout::from_environment().map_err(|_| invalid())?;+ let current = if present(&layout.marker_path)? {+ Some(+ hiroute_host_runtime::read_standalone_install_record(&layout.marker_path)+ .map_err(|_| invalid())?,+ )+ } else {+ None+ };+ if let Some(current) = current.filter(|record| record.install_root == *package) {+ if current.service_definition+ != layout.data_root.join("service/windows-background.json")+ {+ return Err(invalid());+ }+ let definition = hiroute_platform::windows::background::read_definition(+ ¤t.service_definition,+ )?;+ if definition.daemon != package.join("hirouted.exe") {+ return Err(invalid());+ }+ definition.verify_image()?;+ // Task verification preserves foreign registrations; changing the login+ // trigger does not stop the existing process or run it again.+ hiroute_platform::windows::task::set_autostart(&definition, value.previous_autostart)?;+ } else {+ windows::install(serde_json::from_value(serde_json::json!({"schema":"hiroute.windows-install-request/v1","package_directory":package,"autostart":value.previous_autostart,"console_loopback":false,"defer_package_cleanup":true})).map_err(|_|invalid())?)?;+ }+ } else {+ let layout =+ hiroute_host_runtime::StandaloneLayout::from_environment().map_err(|_| invalid())?;+ if present(&layout.marker_path)? {+ // The bundled CLI is outside the version root that uninstall removes.+ let cli = root.join("standalone/hiroute.exe");+ let (success, reply) = super::service::execute_reply(+ &cli,+ &["__windows-uninstall", "--request-stdin"],+ Some(&serde_json::to_vec(&serde_json::json!({"schema":"hiroute.windows-uninstall-request/v1","allow_unavailable_agent_restore":allow_unavailable_agent_restore})).map_err(|_|invalid())?),+ std::time::Duration::from_secs(600),+ )+ .map_err(|_| invalid())?;+ if !success {+ return Err(io::Error::other(+ if reply["error"]["code"] == "AGENT_CONTROL_UNAVAILABLE" {+ "AGENT_CONTROL_UNAVAILABLE"+ } else {+ "SHELL_INSTALL_RECOVERY_REQUIRED"+ },+ ));+ }+ }+ }+ if remove_added_path {+ hiroute_platform::windows::user_path::configure(false)?;+ }+ for (name, expected) in &value.old {+ let backup = data()?.join("install-backups").join(name);+ if hash(&backup)? != *expected {+ return Err(invalid());+ }+ let dest = root.join(name);+ if let Some(parent) = dest.parent() {+ security::open_identity(parent, true)?;+ }+ fs::copy(backup, dest)?;+ }+ let layout =+ hiroute_host_runtime::StandaloneLayout::from_environment().map_err(|_| invalid())?;+ hiroute_host_runtime::ConsoleListenerStore::new(layout.gateway_config_root())+ .configure(value.console_desired.clone())+ .map_err(|_| invalid())?;+ if value.shell_login {+ hiroute_platform::windows::shell_login::set(&root.join("hiroute-shell.exe"), true)?;+ } else {+ hiroute_platform::windows::shell_login::remove()?;+ }+ for (name, expected) in &value.new {+ let path = root.join(name);+ if !value.old.contains_key(name) && present(&path)? {+ if hash(&path)? != *expected {+ return Err(invalid());+ }+ fs::remove_file(path)?;+ }+ }+ if value.service_active {+ super::service::manager(&["service", "start", "--output", "json"])+ .map_err(|_| invalid())?;+ }+ write(+ &data()?.join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"failed","code":"UPGRADE_INSTALL_FAILED","service_available":value.service_active}),+ )?;+ clear(&data()?, &value.old)?;+ cleanup_committed();+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ struct PayloadDirectory(PathBuf);+ impl PayloadDirectory {+ fn new() -> Self {+ let value = Self(std::env::temp_dir().join(format!(+ "hiroute-shell-payload-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ )));+ security::ensure_private_directory(&value.0).unwrap();+ value+ }+ fn file(&self, name: &str, bytes: &[u8]) -> String {+ let path = self.0.join(name);+ security::ensure_private_directory(path.parent().unwrap()).unwrap();+ fs::write(&path, bytes).unwrap();+ hash(&path).unwrap()+ }+ }+ impl Drop for PayloadDirectory {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.0);+ }+ }++ #[test]+ fn committed_manual_repair_replaces_stale_failure_before_retiring_journal() {+ let temporary = PayloadDirectory::new();+ let previous = temporary.file("install-backups/previous.exe", b"previous shell");+ temporary.file(PENDING, b"committed shell transaction");+ write(+ &temporary.0.join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"failed","code":"UPGRADE_INSTALL_FAILED","service_available":true}),+ )+ .unwrap();+ complete_commit(+ &temporary.0,+ &BTreeMap::from([("previous.exe".into(), previous)]),+ )+ .unwrap();+ let outcome: serde_json::Value =+ read(&temporary.0.join("update-outcome.json"), true).unwrap();+ assert_eq!(+ outcome,+ serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"succeeded"})+ );+ assert!(!temporary.0.join(PENDING).exists());+ assert!(!temporary.0.join("install-backups/previous.exe").exists());+ }++ #[test]+ fn failed_committed_reporting_preserves_journal_and_backups_for_retry() {+ let temporary = PayloadDirectory::new();+ let previous = temporary.file("install-backups/previous.exe", b"previous shell");+ temporary.file(PENDING, b"committed shell transaction");+ let old = BTreeMap::from([("previous.exe".into(), previous)]);+ let outcome = temporary.0.join("update-outcome.json");+ security::ensure_private_directory(&outcome).unwrap();+ assert!(complete_commit(&temporary.0, &old).is_err());+ assert!(temporary.0.join(PENDING).exists());+ assert_eq!(+ fs::read(temporary.0.join("install-backups/previous.exe")).unwrap(),+ b"previous shell"+ );+ fs::remove_dir(outcome).unwrap();+ complete_commit(&temporary.0, &old).unwrap();+ assert!(!temporary.0.join(PENDING).exists());+ }++ #[test]+ fn interrupted_committed_cleanup_repeats_reporting_without_losing_journal() {+ let temporary = PayloadDirectory::new();+ let previous = temporary.file("install-backups/previous.exe", b"previous shell");+ temporary.file(PENDING, b"committed shell transaction");+ temporary.file("install-backups/previous.exe", b"foreign change");+ let old = BTreeMap::from([("previous.exe".into(), previous)]);+ assert!(complete_commit(&temporary.0, &old).is_err());+ let first: serde_json::Value =+ read(&temporary.0.join("update-outcome.json"), true).unwrap();+ assert_eq!(first["status"], "succeeded");+ assert!(temporary.0.join(PENDING).exists());+ temporary.file("install-backups/previous.exe", b"previous shell");+ complete_commit(&temporary.0, &old).unwrap();+ let retried: serde_json::Value =+ read(&temporary.0.join("update-outcome.json"), true).unwrap();+ assert_eq!(retried, first);+ assert!(!temporary.0.join(PENDING).exists());+ }++ #[test]+ fn changed_frontend_names_retire_only_verified_old_payload_and_keep_rollback_bytes() {+ let temporary = PayloadDirectory::new();+ let name = "standalone/console/assets/index-old.js";+ let previous = temporary.file(&format!("program/{name}"), b"old frontend");+ temporary.file(&format!("backups/{name}"), b"old frontend");+ let next = temporary.file(+ "program/standalone/console/assets/index-new.js",+ b"new frontend",+ );+ temporary.file("program/standalone/foreign.txt", b"foreign content");+ temporary.file("program/shell-install.json", b"previous preferences");+ let old = BTreeMap::from([(name.into(), previous)]);+ let new = BTreeMap::from([("standalone/console/assets/index-new.js".into(), next)]);+ let root = temporary.0.join("program");+ let backups = temporary.0.join("backups");+ prune_old_payload(&root, &backups, &old, &new).unwrap();+ assert!(!root.join(name).exists());+ assert_eq!(fs::read(backups.join(name)).unwrap(), b"old frontend");+ assert_eq!(+ fs::read(root.join("standalone/console/assets/index-new.js")).unwrap(),+ b"new frontend"+ );+ assert_eq!(+ fs::read(root.join("standalone/foreign.txt")).unwrap(),+ b"foreign content"+ );+ assert_eq!(+ fs::read(root.join("shell-install.json")).unwrap(),+ b"previous preferences"+ );+ prune_old_payload(&root, &backups, &old, &new).unwrap();+ fs::copy(backups.join(name), root.join(name)).unwrap();+ assert_eq!(fs::read(root.join(name)).unwrap(), b"old frontend");+ }++ #[test]+ fn changed_payload_or_backup_blocks_the_whole_prune_before_first_removal() {+ for change_backup in [false, true] {+ let temporary = PayloadDirectory::new();+ let mut old = BTreeMap::new();+ for name in ["standalone/console/a-old.js", "standalone/console/z-old.js"] {+ old.insert(+ name.into(),+ temporary.file(&format!("program/{name}"), b"previous"),+ );+ temporary.file(&format!("backups/{name}"), b"previous");+ }+ temporary.file(+ &format!(+ "{}/standalone/console/z-old.js",+ if change_backup { "backups" } else { "program" }+ ),+ b"changed content",+ );+ let root = temporary.0.join("program");+ assert!(+ prune_old_payload(&root, &temporary.0.join("backups"), &old, &BTreeMap::new())+ .is_err()+ );+ assert_eq!(+ fs::read(root.join("standalone/console/a-old.js")).unwrap(),+ b"previous"+ );+ assert!(root.join("standalone/console/z-old.js").exists());+ }+ }++ #[test]+ fn backup_copy_closes_exclusive_writer_before_verification() {+ struct Temporary(PathBuf);+ impl Drop for Temporary {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.0);+ }+ }+ let temporary = Temporary(std::env::temp_dir().join(format!(+ "hiroute-shell-backup-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ )));+ let parent = security::ensure_private_directory(&temporary.0).unwrap();+ let source = temporary.0.join("previous-shell.exe");+ fs::write(&source, b"retained shell bytes").unwrap();+ let expected = hash(&source).unwrap();+ let dest = temporary.0.join("backup.exe");+ let writer =+ security::create_owner_only_file_at(&parent, dest.file_name().unwrap()).unwrap();+ assert_eq!(hash(&dest).unwrap_err().raw_os_error(), Some(32));+ drop(writer);+ fs::remove_file(&dest).unwrap();++ backup_file(&source, &dest, &expected).unwrap();+ assert_eq!(fs::read(&dest).unwrap(), b"retained shell bytes");+ backup_file(&source, &dest, &expected).unwrap();+ fs::write(&dest, b"changed backup").unwrap();+ assert!(backup_file(&source, &dest, &expected).is_err());+ assert_eq!(fs::read(&dest).unwrap(), b"changed backup");+ }+}diff --git a/apps/shell/src-tauri/src/runtime/installer.rs b/apps/shell/src-tauri/src/runtime/installer.rsnew file mode 100644index 00000000..ac13ac7e--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/installer.rs@@ -0,0 +1,305 @@+//! NSIS invokes this fixed native adapter; verified package installation still uses the CLI stdin verbs.+use super::service;+use hiroute_host_runtime::standalone_install::{Package, windows};+use hiroute_platform::windows::{security, shell_login, user_path};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::{+ io::{Read, Write},+ path::PathBuf,+ time::Duration,+};++#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ShellInstall {+ schema: String,+ cli_path_added: bool,+ tray_enabled: bool,+}+fn read_preferences(root: &std::path::Path) -> Result<Option<ShellInstall>, &'static str> {+ let mut file = match security::open_identity(&root.join("shell-install.json"), false) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ _ => return Err("INSTALL_OWNERSHIP_CONFLICT"),+ };+ let mut bytes = vec![];+ Read::by_ref(&mut file)+ .take(4097)+ .read_to_end(&mut bytes)+ .map_err(|_| "INSTALL_OWNERSHIP_CONFLICT")?;+ if bytes.len() > 4096 {+ return Err("INSTALL_OWNERSHIP_CONFLICT");+ }+ let value: ShellInstall =+ serde_json::from_slice(&bytes).map_err(|_| "INSTALL_OWNERSHIP_CONFLICT")?;+ if value.schema != "hiroute.windows-shell-install/v1" {+ return Err("INSTALL_OWNERSHIP_CONFLICT");+ }+ Ok(Some(value))+}+pub(super) fn path_added(root: &std::path::Path) -> Result<bool, &'static str> {+ Ok(read_preferences(root)?.is_some_and(|record| record.cli_path_added))+}+pub(super) fn tray_enabled() -> bool {+ program_root()+ .ok()+ .and_then(|root| read_preferences(&root).ok().flatten())+ .is_none_or(|record| record.tray_enabled)+}+fn options() -> Result<i32, &'static str> {+ let root = hiroute_platform::windows::background::local_app_data()+ .map_err(|_| "INSTALL_DIRECTORY_INVALID")?+ .join("Programs/HiRoute");+ let Some(preferences) = read_preferences(&root)? else {+ return Ok(3);+ };+ let layout = hiroute_host_runtime::StandaloneLayout::from_environment()+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ let definition = hiroute_platform::windows::background::read_definition(+ &layout.data_root.join("service/windows-background.json"),+ )+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ let login = hiroute_platform::windows::task::autostart(&definition)+ .map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?+ && shell_login::enabled(&root.join("hiroute-shell.exe"))+ .map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?;+ Ok(i32::from(login) | (i32::from(preferences.tray_enabled) << 1))+}+pub(super) fn program_root() -> Result<PathBuf, &'static str> {+ let expected = hiroute_platform::windows::background::local_app_data()+ .map_err(|_| "INSTALL_DIRECTORY_INVALID")?+ .join("Programs/HiRoute");+ let exe = std::env::current_exe().map_err(|_| "INSTALL_DIRECTORY_INVALID")?;+ let actual = exe.parent().ok_or("INSTALL_DIRECTORY_INVALID")?;+ let held = security::open_identity(actual, true).map_err(|_| "INSTALL_DIRECTORY_INVALID")?;+ let expected =+ security::open_identity(&expected, true).map_err(|_| "INSTALL_DIRECTORY_INVALID")?;+ if security::file_identity(&held).map_err(|_| "INSTALL_DIRECTORY_INVALID")?+ != security::file_identity(&expected).map_err(|_| "INSTALL_DIRECTORY_INVALID")?+ {+ return Err("INSTALL_DIRECTORY_INVALID");+ }+ Ok(actual.to_owned())+}+fn preflight() -> Result<(), String> {+ windows::preflight().map_err(|error| error.to_string())?;+ let path = hiroute_platform::windows::background::local_app_data()+ .map_err(|_| "INSTALL_DIRECTORY_INVALID")?+ .join("Programs/HiRoute");+ for ancestor in path.ancestors() {+ match security::open_identity(ancestor, true) {+ Ok(_) => {}+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(_) => return Err("INSTALL_DIRECTORY_INVALID".into()),+ }+ }+ Ok(())+}+fn request(cli: &std::path::Path, verb: &str, value: Value) -> Result<Value, String> {+ let bytes = serde_json::to_vec(&value).map_err(|_| "INSTALL_REQUEST_INVALID")?;+ let (success, value) = service::execute_reply(+ cli,+ &[verb, "--request-stdin"],+ Some(&bytes),+ Duration::from_secs(600),+ )+ .map_err(str::to_owned)?;+ if !success {+ return Err(+ serde_json::to_string(&value["error"]).unwrap_or_else(|_| "INSTALL_FAILED".into())+ );+ }+ Ok(value)+}+fn install(args: &[String]) -> Result<Value, String> {+ windows::preflight().map_err(|error| error.to_string())?;+ let root = program_root()?;+ let package = root.join("standalone");+ super::install_transaction::record_generated().map_err(|error| error.to_string())?;+ super::install_transaction::prune_payload().map_err(|error| error.to_string())?;+ Package::read(&package).map_err(|_| "INSTALL_PACKAGE_INVALID")?;+ let enabled = !args.iter().any(|arg| arg == "--no-login-start");+ request(+ &package.join("hiroute.exe"),+ "__windows-install",+ json!({"schema":"hiroute.windows-install-request/v1", "package_directory":package,"autostart":enabled,"console_loopback":true,"defer_package_cleanup":true,"allow_legacy_stop":args.iter().any(|arg| arg == "--allow-legacy-stop")}),+ )?;+ let previous = read_preferences(&root)?.is_some_and(|value| value.cli_path_added);+ let added = user_path::configure(true).map_err(|_| "USER_PATH_UNAVAILABLE")?;+ let bytes = serde_json::to_vec(&ShellInstall {+ schema: "hiroute.windows-shell-install/v1".into(),+ cli_path_added: previous || added,+ tray_enabled: !args.iter().any(|a| a == "--no-tray"),+ })+ .map_err(|_| "INSTALL_FAILED")?;+ if super::install_transaction::write_preferences(&bytes).is_err() {+ if added {+ let _ = user_path::configure(false);+ }+ return Err("INSTALL_FAILED".into());+ }+ super::commands::login_set(enabled)?;+ service::manager(&["service", "start", "--output", "json"])?;+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|_| "SERVICE_NOT_READY")?+ .block_on(service::wait_ready())?;+ super::install_transaction::commit().map_err(|error| error.to_string())?;+ Ok(json!({"installed":true,"started":true}))+}+fn uninstall(args: &[String]) -> Result<Value, String> {+ windows::preflight().map_err(|error| error.to_string())?;+ // NSIS runs a verified copy outside the installation so interrupted first+ // installs can remove their own shell files during recovery as well.+ let root = super::install_transaction::root().map_err(|error| error.to_string())?;+ if super::install_transaction::hash(+ &std::env::current_exe().map_err(|error| error.to_string())?,+ )+ .map_err(|error| error.to_string())?+ != super::install_transaction::hash(&root.join("hiroute-shell.exe"))+ .map_err(|error| error.to_string())?+ {+ return Err("INSTALL_OWNERSHIP_CONFLICT".into());+ }+ if super::install_transaction::has_pending().map_err(|error| error.to_string())? {+ super::install_transaction::rollback(+ args.iter()+ .any(|arg| arg == "--allow-unavailable-agent-restore"),+ )+ .map_err(|error| error.to_string())?;+ let layout = hiroute_host_runtime::StandaloneLayout::from_environment()+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ if !root+ .join("shell-package.json")+ .try_exists()+ .map_err(|error| error.to_string())?+ && !layout+ .marker_path+ .try_exists()+ .map_err(|error| error.to_string())?+ {+ return Ok(+ json!({"uninstalled":true,"recovered_first_install":true,"state_preserved":true}),+ );+ }+ }+ super::install_transaction::validate_installed().map_err(|error| error.to_string())?;+ let previous = read_preferences(&root)?;+ let package = root.join("standalone");+ Package::read(&package).map_err(|_| "INSTALL_PACKAGE_INVALID")?;+ let cli = package.join("hiroute.exe");+ let result = request(+ &cli,+ "__windows-uninstall",+ json!({"schema":"hiroute.windows-uninstall-request/v1", "remove_data":args.iter().any(|arg| arg == "--remove-data"),"allow_legacy_stop":args.iter().any(|arg| arg == "--allow-legacy-stop"),"allow_unavailable_agent_restore":args.iter().any(|arg| arg == "--allow-unavailable-agent-restore")}),+ )?;+ shell_login::remove().map_err(|_| "SHELL_LOGIN_UNAVAILABLE")?;+ if previous.is_some_and(|v| v.cli_path_added) {+ user_path::configure(false).map_err(|_| "USER_PATH_UNAVAILABLE")?;+ }+ Ok(result)+}+pub fn run_if_requested() -> Option<i32> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let verb = args.first()?;+ if !verb.starts_with("--installer-") {+ return None;+ }+ if verb == "--installer-mutex" {+ if args.len() != 1 || hiroute_platform::windows::install::require_x64().is_err() {+ return Some(1);+ }+ let Ok(name) = hiroute_platform::windows::install::desktop_mutex_name() else {+ return Some(1);+ };+ let mut output = std::io::stdout().lock();+ return Some(+ if write!(output, "{name}")+ .and_then(|()| output.flush())+ .is_ok()+ {+ 0+ } else {+ 1+ },+ );+ }+ if verb == "--installer-options" {+ return Some(+ if args.len() == 1 && hiroute_platform::windows::install::require_x64().is_ok() {+ options().unwrap_or(8)+ } else {+ 8+ },+ );+ }+ if verb == "--installer-prepare" {+ let result = if args.len() == 2 {+ super::install_transaction::prepare(std::path::Path::new(&args[1]))+ } else {+ Err(std::io::ErrorKind::InvalidInput.into())+ };+ return Some(if result.is_ok() { 0 } else { 1 });+ }+ if matches!(+ verb.as_str(),+ "--installer-rollback" | "--installer-recover"+ ) {+ let allow = args+ .get(1)+ .is_some_and(|arg| arg == "--allow-unavailable-agent-restore");+ if args.len() > 2 || (args.len() == 2 && !allow) {+ return Some(1);+ }+ let result =+ windows::recover_pending().and_then(|()| super::install_transaction::rollback(allow));+ let _ = super::updater::resume_admission();+ return Some(match result {+ Ok(()) => 0,+ Err(error) if error.to_string() == "AGENT_CONTROL_UNAVAILABLE" => 23,+ Err(_) => 1,+ });+ }+ let result = if args.iter().skip(1).any(|a| {+ !matches!(+ a.as_str(),+ "--no-login-start"+ | "--no-tray"+ | "--allow-legacy-stop"+ | "--remove-data"+ | "--allow-unavailable-agent-restore"+ )+ }) {+ Err("INSTALL_ARGUMENTS_INVALID".into())+ } else if hiroute_platform::windows::install::require_x64().is_err() {+ Err("INSTALL_ARCHITECTURE_UNSUPPORTED".into())+ } else {+ match verb.as_str() {+ "--installer-preflight" => preflight().map(|_| json!({"ready":true})),+ "--installer-install" => install(&args),+ "--installer-uninstall" => uninstall(&args),+ _ => Err("INSTALL_ARGUMENTS_INVALID".into()),+ }+ };+ let (exit, text) = match result {+ Ok(value) => (0, value.to_string()),+ Err(error) => (+ if error.contains("DRAIN_UNSUPPORTED") {+ 20+ } else if error.contains("AGENT_RESTORE_REQUIRED") {+ 21+ } else if error.contains("UPGRADE_ACTIVE_WORK") {+ 22+ } else if error.contains("AGENT_CONTROL_UNAVAILABLE") {+ 23+ } else {+ 1+ },+ error,+ ),+ };+ let _ = writeln!(std::io::stdout().lock(), "{text}");+ Some(exit)+}diff --git a/apps/shell/src-tauri/src/runtime/mod.rs b/apps/shell/src-tauri/src/runtime/mod.rsnew file mode 100644index 00000000..bd9646df--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/mod.rs@@ -0,0 +1,205 @@+use crate::ConsoleOrigin;+use serde::Serialize;+use std::sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+};+use tauri::{Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent};+mod commands;+mod install_transaction;+pub mod installer;+mod service;+mod tray;+mod updater;+use commands::*;++#[derive(Clone, Serialize)]+pub struct Status {+ phase: &'static str,+ code: Option<&'static str>,+ logs_path: String,+}+pub struct ShellState {+ origin: Mutex<Option<ConsoleOrigin>>,+ status: Mutex<Status>,+ starting: AtomicBool,+ updater: updater::Updater,+}+impl ShellState {+ fn new() -> Self {+ let logs = hiroute_host_runtime::StandaloneLayout::from_environment()+ .ok()+ .map(|l| l.diagnostics_root().display().to_string())+ .unwrap_or_default();+ Self {+ origin: Mutex::new(None),+ status: Mutex::new(Status {+ phase: "starting",+ code: None,+ logs_path: logs,+ }),+ starting: AtomicBool::new(false),+ updater: updater::Updater::new(),+ }+ }+ fn phase(&self, phase: &'static str, code: Option<&'static str>) {+ if let Ok(mut status) = self.status.lock() {+ status.phase = phase;+ status.code = code;+ }+ }+}+fn focus(app: &tauri::AppHandle) {+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.show();+ let _ = window.unminimize();+ let _ = window.set_focus();+ }+}+fn start(app: tauri::AppHandle, state: Arc<ShellState>) {+ if state.starting.swap(true, Ordering::AcqRel) {+ return;+ }+ state.phase("starting", None);+ tauri::async_runtime::spawn(async move {+ let outcome = async {+ let (origin, url) = service::ready_launch(&state).await?;+ *state.origin.lock().map_err(|_| "SHELL_STATE_UNAVAILABLE")? = Some(origin);+ let window = app+ .get_webview_window("main")+ .ok_or("SHELL_WINDOW_UNAVAILABLE")?;+ window+ .navigate(url)+ .map_err(|_| "SHELL_NAVIGATION_FAILED")?;+ state.phase("ready", None);+ Ok::<_, &'static str>(())+ }+ .await;+ if let Err(code) = outcome {+ state.phase("failed", Some(code));+ focus(&app);+ }+ state.starting.store(false, Ordering::Release);+ });+}+fn local_status(url: &url::Url) -> bool {+ ((url.scheme() == "tauri" && url.host_str() == Some("localhost"))+ || (url.scheme() == "http" && url.host_str() == Some("tauri.localhost")))+ && matches!(url.path(), "/" | "/index.html")+}+fn authorize(window: &WebviewWindow, state: &ShellState) -> Result<(), &'static str> {+ let url = window.url().map_err(|_| "SHELL_ORIGIN_DENIED")?;+ if window.label() != "main"+ || !state+ .origin+ .lock()+ .map_err(|_| "SHELL_STATE_UNAVAILABLE")?+ .as_ref()+ .is_some_and(|o| o.allows(&url))+ {+ return Err("SHELL_ORIGIN_DENIED");+ }+ Ok(())+}+fn authorize_status(window: &WebviewWindow) -> Result<(), &'static str> {+ if window.label() != "main" || !local_status(&window.url().map_err(|_| "SHELL_ORIGIN_DENIED")?)+ {+ return Err("SHELL_ORIGIN_DENIED");+ }+ Ok(())+}+pub fn run() {+ if hiroute_platform::windows::install::require_x64().is_err() {+ return;+ }+ let state = Arc::new(ShellState::new());+ let tray_enabled = installer::tray_enabled();+ let background = tray_enabled && std::env::args_os().any(|arg| arg == "--background");+ let outcome = tauri::Builder::default()+ .plugin(tauri_plugin_single_instance::init(|app, _, _| focus(app)))+ .plugin(tauri_plugin_dialog::init())+ .manage(state.clone())+ .invoke_handler(tauri::generate_handler![+ shell_status,+ shell_retry_startup,+ shell_capabilities,+ shell_open_in_browser,+ shell_open_external_url,+ shell_save_classifier_openapi,+ shell_login_start_get,+ shell_login_start_set,+ shell_restart_service,+ shell_reconnect,+ shell_update_status,+ shell_update_check,+ shell_update_download,+ shell_update_install,+ shell_update_cancel+ ])+ .on_window_event(move |window, event| {+ if window.label() == "main"+ && let WindowEvent::CloseRequested { api, .. } = event+ {+ if tray_enabled {+ api.prevent_close();+ let _ = window.hide();+ } else {+ window.app_handle().exit(0);+ }+ }+ })+ .setup(move |app| {+ let navigation = state.clone();+ WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))+ .title("HiRoute")+ .inner_size(1200., 813.)+ .min_inner_size(755., 600.)+ .visible(!background)+ .incognito(true)+ .initialization_script(+ "Object.defineProperty(window,'__HIROUTE_SHELL__',{value:true});",+ )+ .on_navigation(move |url| {+ if local_status(url)+ || navigation+ .origin+ .lock()+ .ok()+ .and_then(|o| o.clone())+ .is_some_and(|o| o.allows(url))+ {+ return true;+ }+ if let Ok(url) = crate::external_url(url.as_str()) {+ let _ = hiroute_platform::windows::shell_open::url(url.as_str());+ }+ false+ })+ .on_new_window(|url, _| {+ if let Ok(url) = crate::external_url(url.as_str()) {+ let _ = hiroute_platform::windows::shell_open::url(url.as_str());+ }+ tauri::webview::NewWindowResponse::Deny+ })+ .build()?;+ if tray_enabled {+ tray::create(app)?;+ }+ match updater::recover_startup(app.handle(), &state, false) {+ Ok(true) => {}+ Ok(false) => start(app.handle().clone(), state.clone()),+ Err(code) => {+ state.phase("failed", Some(code));+ focus(app.handle());+ }+ }+ Ok(())+ })+ .run(tauri::generate_context!());+ if outcome.is_err() {+ hiroute_platform::windows::shell_open::startup_failure();+ }+}+pub fn run_helper() -> Option<i32> {+ updater::run_if_requested().or_else(installer::run_if_requested)+}diff --git a/apps/shell/src-tauri/src/runtime/service.rs b/apps/shell/src-tauri/src/runtime/service.rsnew file mode 100644index 00000000..e57d0908--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/service.rs@@ -0,0 +1,229 @@+use super::ShellState;+use crate::ConsoleOrigin;+use hiroute_application_api::{+ ConsoleLaunchRequestV1, ConsoleLaunchV1, ErrorCode, MachineEnvelopeV2, SystemStatusV1,+};+use hiroute_client_core::{Client, LocalEndpoint};+use hiroute_host_runtime::{+ StandaloneLayout, read_standalone_install_record, standalone_cli_binary,+};+use serde_json::Value;+use std::{+ io::{Read, Write},+ process::{Command, Stdio},+ time::{Duration, Instant},+};++pub(super) fn cli() -> Result<std::path::PathBuf, &'static str> {+ let layout = StandaloneLayout::from_environment().map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ let marker = read_standalone_install_record(&layout.marker_path)+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ if marker.target != "x86_64-pc-windows-msvc"+ || !marker+ .install_root+ .starts_with(layout.home.join(".local/lib/hiroute"))+ {+ return Err("INSTALLATION_UNAVAILABLE");+ }+ let path = standalone_cli_binary(&marker.install_root);+ hiroute_platform::windows::security::open_identity(&path, false)+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ Ok(path)+}+pub(super) fn execute_reply(+ cli: &std::path::Path,+ args: &[&str],+ stdin: Option<&[u8]>,+ timeout: Duration,+) -> Result<(bool, Value), &'static str> {+ use std::os::windows::process::CommandExt;+ let mut child = Command::new(cli)+ .args(args)+ .stdin(if stdin.is_some() {+ Stdio::piped()+ } else {+ Stdio::null()+ })+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .creation_flags(0x08000000)+ .spawn()+ .map_err(|_| "SERVICE_COMMAND_FAILED")?;+ if let Some(bytes) = stdin {+ child+ .stdin+ .take()+ .ok_or("SERVICE_COMMAND_FAILED")?+ .write_all(bytes)+ .map_err(|_| "SERVICE_COMMAND_FAILED")?;+ }+ let output = child.stdout.take().ok_or("SERVICE_COMMAND_FAILED")?;+ let reader = std::thread::spawn(move || {+ let mut bytes = vec![];+ output+ .take(16 * 1024 + 1)+ .read_to_end(&mut bytes)+ .map(|_| bytes)+ });+ let deadline = Instant::now() + timeout;+ let status = loop {+ match child.try_wait().map_err(|_| "SERVICE_COMMAND_FAILED")? {+ Some(status) => break status,+ None if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(30)),+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ return Err("SERVICE_COMMAND_TIMED_OUT");+ }+ }+ };+ let bytes = reader+ .join()+ .map_err(|_| "SERVICE_COMMAND_FAILED")?+ .map_err(|_| "SERVICE_COMMAND_FAILED")?;+ if bytes.len() > 16 * 1024 {+ return Err("SERVICE_RESPONSE_INVALID");+ }+ let value: Value = serde_json::from_slice(&bytes).map_err(|_| "SERVICE_RESPONSE_INVALID")?;+ Ok((status.success(), value))+}+pub(super) fn execute(+ cli: &std::path::Path,+ args: &[&str],+ stdin: Option<&[u8]>,+ timeout: Duration,+) -> Result<Value, &'static str> {+ let (success, value) = execute_reply(cli, args, stdin, timeout)?;+ if !success || value.get("status").is_some_and(|s| s != "succeeded") {+ return Err("SERVICE_COMMAND_FAILED");+ }+ Ok(value.get("data").cloned().unwrap_or(value))+}+pub(super) fn manager(args: &[&str]) -> Result<Value, &'static str> {+ execute(&cli()?, args, None, Duration::from_secs(45))+}+fn client() -> Result<Client, &'static str> {+ let layout = StandaloneLayout::from_environment().map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ Ok(Client::new(+ "hiroute-shell",+ LocalEndpoint::from_runtime_root(layout.runtime_root),+ )+ .with_timeout(Duration::from_secs(2)))+}+pub(super) async fn launch() -> Result<(ConsoleOrigin, url::Url), &'static str> {+ let response = client()?+ .query::<_, ConsoleLaunchV1>(+ "CreateConsoleLaunch",+ "shell-launch",+ &ConsoleLaunchRequestV1 {+ loopback_only: true,+ },+ )+ .await+ .map_err(|_| "CONSOLE_LAUNCH_UNAVAILABLE")?;+ launch_reply(response)+}+fn launch_reply(+ response: MachineEnvelopeV2<ConsoleLaunchV1>,+) -> Result<(ConsoleOrigin, url::Url), &'static str> {+ if let Some(error) = response.error {+ return Err(if error.code == ErrorCode::ActionRequired {+ "CONSOLE_LISTENER_UNAVAILABLE"+ } else {+ "CONSOLE_LAUNCH_UNAVAILABLE"+ });+ }+ let value = response.data.ok_or("CONSOLE_LAUNCH_UNAVAILABLE")?;+ ConsoleOrigin::launch(&value.url)+}+pub(super) async fn ready_launch(+ state: &ShellState,+) -> Result<(ConsoleOrigin, url::Url), &'static str> {+ let status = tauri::async_runtime::spawn_blocking(|| {+ manager(&["service", "status", "--output", "json"])+ })+ .await+ .map_err(|_| "SERVICE_STATUS_UNAVAILABLE")??;+ if status["manager_active"] != true {+ tauri::async_runtime::spawn_blocking(|| manager(&["service", "start", "--output", "json"]))+ .await+ .map_err(|_| "SERVICE_START_FAILED")??;+ }+ state.phase("waiting", None);+ wait_ready().await?;+ launch().await+}+pub(super) async fn wait_ready() -> Result<(), &'static str> {+ let deadline = Instant::now() + Duration::from_secs(45);+ loop {+ if is_ready().await {+ return Ok(());+ }+ if Instant::now() >= deadline {+ return Err("SERVICE_NOT_READY");+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+}+pub(super) async fn is_ready() -> bool {+ let Ok(client) = client() else {+ return false;+ };+ client+ .query::<_, SystemStatusV1>("GetSystemStatus", "shell-ready", &serde_json::json!({}))+ .await+ .is_ok_and(|response| {+ response.error.is_none()+ && response+ .data+ .is_some_and(|s| s.gateway == "ready" && s.daemon == "role_all")+ })+}+pub(super) fn available_blocking() -> bool {+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .is_ok_and(|runtime| runtime.block_on(is_ready()))+}++#[cfg(test)]+mod tests {+ use super::*;+ use hiroute_application_api::ErrorV1;++ #[test]+ fn missing_console_listener_is_not_reported_as_service_start_failure() {+ let failure = |code| -> MachineEnvelopeV2<ConsoleLaunchV1> {+ serde_json::from_value(+ serde_json::to_value(MachineEnvelopeV2::failed(ErrorV1::new(code), None)).unwrap(),+ )+ .unwrap()+ };+ assert_eq!(+ launch_reply(failure(ErrorCode::ActionRequired)).unwrap_err(),+ "CONSOLE_LISTENER_UNAVAILABLE"+ );+ assert_eq!(+ launch_reply(failure(ErrorCode::DaemonUnavailable)).unwrap_err(),+ "CONSOLE_LAUNCH_UNAVAILABLE"+ );+ }++ #[test]+ fn launch_rechecks_and_accepts_only_the_current_bound_loopback_origin() {+ let reply = |host: &str| {+ MachineEnvelopeV2::succeeded(+ ConsoleLaunchV1 {+ url: format!("http://{host}:5839/launch?code={}", "a".repeat(64)),+ expires_in: 120,+ },+ None,+ )+ };+ assert!(launch_reply(reply("127.0.0.1")).is_ok());+ assert_eq!(+ launch_reply(reply("example.test")).unwrap_err(),+ "CONSOLE_LAUNCH_INVALID"+ );+ }+}diff --git a/apps/shell/src-tauri/src/runtime/tray.rs b/apps/shell/src-tauri/src/runtime/tray.rsnew file mode 100644index 00000000..e92f5e4a--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/tray.rs@@ -0,0 +1,45 @@+use super::*;+use tauri::{+ menu::{CheckMenuItem, Menu, MenuItem},+ tray::TrayIconBuilder,+};+pub(super) fn create(app: &tauri::App) -> tauri::Result<()> {+ let open = MenuItem::with_id(app, "open", "Open HiRoute", true, None::<&str>)?;+ let browser = MenuItem::with_id(app, "browser", "Open in browser", true, None::<&str>)?;+ let enabled = commands::login_get().is_ok_and(|v| v["enabled"] == true);+ let login =+ CheckMenuItem::with_id(app, "login", "Start at login", true, enabled, None::<&str>)?;+ let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;+ let menu = Menu::with_items(app, &[&open, &browser, &login, &quit])?;+ TrayIconBuilder::new()+ .icon(tauri::image::Image::from_bytes(include_bytes!(+ "../../../../desktop/src-tauri/icons/icon.png"+ ))?)+ .tooltip("HiRoute")+ .menu(&menu)+ .show_menu_on_left_click(true)+ .on_menu_event(move |app, event| match event.id().as_ref() {+ "open" => focus(app),+ "browser" => {+ tauri::async_runtime::spawn(async {+ if let Ok((_, url)) = service::launch().await {+ let _ = hiroute_platform::windows::shell_open::url(url.as_str());+ }+ });+ }+ "login" => {+ let login = login.clone();+ tauri::async_runtime::spawn_blocking(move || {+ if let Ok(current) = commands::login_get() {+ if let Ok(next) = commands::login_set(current["enabled"] != true) {+ let _ = login.set_checked(next["enabled"] == true);+ }+ }+ });+ }+ "quit" => app.exit(0),+ _ => {}+ })+ .build(app)?;+ Ok(())+}diff --git a/apps/shell/src-tauri/src/runtime/updater.rs b/apps/shell/src-tauri/src/runtime/updater.rsnew file mode 100644index 00000000..85d326a8--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/updater.rs@@ -0,0 +1,391 @@+//! Windows update admission stays in the host; the console cannot choose a URL or executable.+use super::{ShellState, service};+use hiroute_host_runtime::{+ MAX_RELEASE_FEED_BYTES, StandaloneLayout, WINDOWS_RELEASE_FEED, WebsiteReleasesV3,+ WindowsDesktopRelease,+};+use hiroute_platform::windows::{background, lifecycle, security};+use serde::Serialize;+use sha2::{Digest, Sha256};+use std::{+ fs::File,+ io::Write,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::{Duration, Instant},+};++mod finisher;+pub(super) use finisher::{recover_startup, run_if_requested};+#[derive(Clone, Serialize)]+pub(super) struct UpdateView {+ current_version: &'static str,+ phase: &'static str,+ available: Option<WindowsDesktopRelease>,+ downloaded_bytes: u64,+ active_calls: u64,+ active_tasks: u64,+ error: Option<&'static str>,+ can_install: bool,+ package_ready: bool,+ recovery: Option<&'static str>,+}+pub(super) struct Updater {+ view: Mutex<UpdateView>,+ cancel: AtomicBool,+ parent_lock: Mutex<Option<File>>,+}+impl Updater {+ pub(super) fn new() -> Self {+ Self {+ view: Mutex::new(UpdateView {+ current_version: env!("CARGO_PKG_VERSION"),+ phase: "idle",+ available: None,+ downloaded_bytes: 0,+ active_calls: 0,+ active_tasks: 0,+ error: None,+ can_install: super::installer::program_root()+ .is_ok_and(|root| root.join("shell-package.json").is_file()),+ package_ready: false,+ recovery: None,+ }),+ cancel: AtomicBool::new(false),+ parent_lock: Mutex::new(None),+ }+ }+ pub(super) fn status(&self) -> Result<UpdateView, &'static str> {+ self.view+ .lock()+ .map(|v| v.clone())+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")+ }+ fn change(&self, f: impl FnOnce(&mut UpdateView)) {+ if let Ok(mut v) = self.view.lock() {+ f(&mut v);+ }+ }+ fn begin(&self, phase: &'static str) -> Result<(), &'static str> {+ let mut view = self.view.lock().map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;+ if matches!(+ view.phase,+ "checking" | "downloading" | "verifying" | "waiting" | "installing"+ ) {+ return Err("UPGRADE_BUSY");+ }+ self.cancel.store(false, Ordering::Release);+ view.phase = phase;+ view.error = None;+ view.recovery = None;+ Ok(())+ }+ fn cancelled(&self) -> Result<(), &'static str> {+ if self.cancel.load(Ordering::Acquire) {+ Err("UPGRADE_CANCELLED")+ } else {+ Ok(())+ }+ }+ pub(super) fn check(state: Arc<ShellState>) -> Result<UpdateView, &'static str> {+ state.updater.begin("checking")?;+ let initial = state.updater.status()?;+ tauri::async_runtime::spawn(async move {+ let result = async {+ let client = http()?;+ let mut response = client+ .get(WINDOWS_RELEASE_FEED)+ .send()+ .await+ .map_err(|_| "UPGRADE_CHECK_FAILED")?;+ catalog_status(response.status())?;+ if response+ .content_length()+ .is_some_and(|n| n > MAX_RELEASE_FEED_BYTES as u64)+ {+ return Err("UPGRADE_CATALOG_INVALID");+ }+ let mut bytes = vec![];+ while let Some(chunk) =+ response.chunk().await.map_err(|_| "UPGRADE_CHECK_FAILED")?+ {+ if bytes.len() + chunk.len() > MAX_RELEASE_FEED_BYTES {+ return Err("UPGRADE_CATALOG_INVALID");+ }+ bytes.extend_from_slice(&chunk);+ }+ let release =+ WebsiteReleasesV3::parse(&bytes)?.windows_update(env!("CARGO_PKG_VERSION"))?;+ state.updater.change(|v| {+ v.phase = if release.is_some() {+ "available"+ } else {+ "current"+ };+ v.available = release;+ v.package_ready = false;+ v.downloaded_bytes = 0;+ });+ Ok::<_, &'static str>(())+ }+ .await;+ if let Err(code) = result {+ state.updater.change(|v| {+ v.phase = "check_failed";+ v.error = Some(code);+ });+ }+ });+ Ok(initial)+ }+ pub(super) fn download(state: Arc<ShellState>) -> Result<UpdateView, &'static str> {+ if !state.updater.status()?.can_install {+ return Err("UPGRADE_INSTALLATION_UNAVAILABLE");+ }+ let release = state+ .updater+ .status()?+ .available+ .ok_or("UPGRADE_NOT_AVAILABLE")?;+ release.revision_prefix()?;+ state.updater.begin("downloading")?;+ let initial = state.updater.status()?;+ tauri::async_runtime::spawn(async move {+ let result = async {+ let directory = finisher::stage(&release)?;+ let installer = directory.join("installer.exe");+ if installer+ .try_exists()+ .map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?+ {+ std::fs::remove_file(&installer).map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?;+ }+ let held = security::ensure_private_directory(&directory)+ .map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?;+ let mut file = security::create_owner_only_file_at(+ &held,+ std::ffi::OsStr::new("installer.exe"),+ )+ .map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?;+ let mut response = http()?+ .get(release.download_url())+ .send()+ .await+ .map_err(|_| "UPGRADE_DOWNLOAD_FAILED")?+ .error_for_status()+ .map_err(|_| "UPGRADE_DOWNLOAD_FAILED")?;+ if response.content_length().is_some_and(|n| n != release.size) {+ return Err("UPGRADE_PACKAGE_SIZE_MISMATCH");+ }+ let mut sha = Sha256::new();+ let mut count = 0;+ while let Some(chunk) = response+ .chunk()+ .await+ .map_err(|_| "UPGRADE_DOWNLOAD_FAILED")?+ {+ state.updater.cancelled()?;+ count += chunk.len() as u64;+ if count > release.size {+ return Err("UPGRADE_PACKAGE_SIZE_MISMATCH");+ }+ file.write_all(&chunk)+ .map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?;+ sha.update(&chunk);+ state.updater.change(|v| v.downloaded_bytes = count);+ }+ file.sync_all().map_err(|_| "UPGRADE_STAGE_UNAVAILABLE")?;+ drop(file);+ state.updater.change(|v| v.phase = "verifying");+ state.updater.cancelled()?;+ if count != release.size {+ return Err("UPGRADE_PACKAGE_SIZE_MISMATCH");+ }+ if format!("{:x}", sha.finalize()) != release.sha256 {+ return Err("UPGRADE_DIGEST_MISMATCH");+ }+ state.updater.change(|v| {+ v.phase = "ready";+ v.package_ready = true;+ });+ Ok::<_, &'static str>(())+ }+ .await;+ if let Err(code) = result {+ state.updater.change(|v| {+ v.package_ready = false;+ v.phase = if code == "UPGRADE_CANCELLED" {+ "available"+ } else {+ "failed"+ };+ v.error = (code != "UPGRADE_CANCELLED").then_some(code);+ });+ }+ });+ Ok(initial)+ }+ pub(super) fn install(+ app: tauri::AppHandle,+ state: Arc<ShellState>,+ ) -> Result<UpdateView, &'static str> {+ let before = state.updater.status()?;+ if !before.package_ready {+ return Err("UPGRADE_PACKAGE_NOT_READY");+ }+ let release = before.available.ok_or("UPGRADE_NOT_AVAILABLE")?;+ state.updater.begin("waiting")?;+ let initial = state.updater.status()?;+ tauri::async_runtime::spawn_blocking(move || {+ let result = (|| {+ finisher::verify(&release)?; // recheck staged bytes before pausing admission+ let (layout, definition) = daemon()?;+ let endpoint = layout.lifecycle_endpoint();+ let mut status = lifecycle::upgrade(+ &endpoint,+ &definition.daemon,+ "upgrade-prepare",+ Duration::from_secs(2),+ )+ .map_err(drain_error)?;+ loop {+ state.updater.change(|v| {+ v.active_calls = status.active_calls;+ v.active_tasks = status.active_tasks;+ });+ state.updater.cancelled()?;+ if status.drained() {+ break;+ }+ std::thread::sleep(Duration::from_millis(200));+ status = lifecycle::upgrade(+ &endpoint,+ &definition.daemon,+ "upgrade-status",+ Duration::from_secs(2),+ )+ .map_err(drain_error)?;+ }+ state.updater.cancelled()?;+ finisher::launch(&state.updater, &release)?;+ {+ let mut view = state+ .updater+ .view+ .lock()+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;+ state.updater.cancelled()?;+ view.phase = "installing";+ finisher::commit(&release)?;+ }+ app.exit(0);+ Ok::<_, &'static str>(())+ })();+ if let Err(code) = result {+ if let Ok(mut parent) = state.updater.parent_lock.lock() {+ parent.take();+ }+ let resumed = resume_admission().is_ok() && service::available_blocking();+ state.updater.change(|v| {+ v.phase = if code == "UPGRADE_CANCELLED" {+ "ready"+ } else {+ "failed"+ };+ v.error = (code != "UPGRADE_CANCELLED").then_some(code);+ v.recovery = Some(if resumed {+ "service_available"+ } else {+ "restart_required"+ });+ });+ }+ });+ Ok(initial)+ }+ pub(super) fn cancel(&self) -> Result<UpdateView, &'static str> {+ let view = self.view.lock().map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;+ if !matches!(view.phase, "downloading" | "verifying" | "waiting") {+ return Err("UPGRADE_NOT_CANCELLABLE");+ }+ self.cancel.store(true, Ordering::Release);+ Ok(view.clone())+ }+}+fn catalog_status(status: reqwest::StatusCode) -> Result<(), &'static str> {+ match status {+ reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::GONE => {+ Err("UPGRADE_CATALOG_UNAVAILABLE")+ }+ status if status.is_success() => Ok(()),+ _ => Err("UPGRADE_CHECK_FAILED"),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn unavailable_catalog_cannot_be_mistaken_for_a_completed_update_check() {+ for status in [404, 410] {+ assert_eq!(+ catalog_status(reqwest::StatusCode::from_u16(status).unwrap()),+ Err("UPGRADE_CATALOG_UNAVAILABLE"),+ );+ }+ for status in [302, 403, 500] {+ assert_eq!(+ catalog_status(reqwest::StatusCode::from_u16(status).unwrap()),+ Err("UPGRADE_CHECK_FAILED"),+ );+ }+ assert_eq!(catalog_status(reqwest::StatusCode::OK), Ok(()));+ }+}+fn http() -> Result<reqwest::Client, &'static str> {+ reqwest::Client::builder()+ .https_only(true)+ .redirect(reqwest::redirect::Policy::none())+ .connect_timeout(Duration::from_secs(15))+ .timeout(Duration::from_secs(600))+ .build()+ .map_err(|_| "UPGRADE_NETWORK_UNAVAILABLE")+}+fn daemon() -> Result<(StandaloneLayout, background::Definition), &'static str> {+ let layout = StandaloneLayout::from_environment().map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ let definition =+ background::read_definition(&layout.data_root.join("service/windows-background.json"))+ .map_err(|_| "INSTALLATION_UNAVAILABLE")?;+ if definition.manager != background::Manager::Task {+ return Err("INSTALL_SCM_MANAGED");+ }+ Ok((layout, definition))+}+fn drain_error(error: std::io::Error) -> &'static str {+ if error.kind() == std::io::ErrorKind::Unsupported {+ "DRAIN_UNSUPPORTED"+ } else {+ "UPGRADE_DRAIN_FAILED"+ }+}+pub(super) fn resume_admission() -> Result<(), &'static str> {+ let (layout, definition) = daemon()?;+ if !hiroute_platform::windows::task::active(&definition)+ .map_err(|_| "SERVICE_STATUS_UNAVAILABLE")?+ {+ return Ok(());+ }+ match lifecycle::upgrade(+ &layout.lifecycle_endpoint(),+ &definition.daemon,+ "upgrade-cancel",+ Duration::from_secs(2),+ ) {+ Ok(_) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::Unsupported => Ok(()),+ Err(_) => Err("UPGRADE_RESUME_FAILED"),+ }+}diff --git a/apps/shell/src-tauri/src/runtime/updater/finisher.rs b/apps/shell/src-tauri/src/runtime/updater/finisher.rsnew file mode 100644index 00000000..66823b0d--- /dev/null+++ b/apps/shell/src-tauri/src/runtime/updater/finisher.rs@@ -0,0 +1,351 @@+use super::super::install_transaction as transaction;+use super::*;+use fs2::FileExt;+use serde::{Deserialize, Serialize};+use std::{+ fs,+ io::{self, Read},+ path::{Path, PathBuf},+ process::Command,+};+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Job {+ schema: String,+ release: WindowsDesktopRelease,+ helper_sha256: String,+ generation: String,+}+fn err(_: impl std::fmt::Debug) -> &'static str {+ "UPGRADE_STAGE_UNAVAILABLE"+}+fn identifier(value: &str) -> bool {+ value.len() == 64+ && value+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}+fn directory(id: &str) -> Result<PathBuf, &'static str> {+ if !identifier(id) {+ return Err("UPGRADE_ARTIFACT_INVALID");+ }+ Ok(transaction::data().map_err(err)?.join("updates").join(id))+}+pub(super) fn stage(release: &WindowsDesktopRelease) -> Result<PathBuf, &'static str> {+ release.revision_prefix()?;+ let path = directory(&release.sha256)?;+ security::ensure_private_directory(&path).map_err(err)?;+ Ok(path)+}+fn write(path: &Path, value: &impl Serialize) -> Result<(), &'static str> {+ hiroute_platform::durable::write_private_atomic(path, &serde_json::to_vec(value).map_err(err)?)+ .map_err(err)+}+fn read<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, &'static str> {+ let mut file = security::open_owner_only(path, false).map_err(err)?;+ let mut bytes = vec![];+ Read::by_ref(&mut file)+ .take(2 * 1024 * 1024 + 1)+ .read_to_end(&mut bytes)+ .map_err(err)?;+ if bytes.len() > 2 * 1024 * 1024 {+ return Err("UPGRADE_STAGE_INVALID");+ }+ serde_json::from_slice(&bytes).map_err(|_| "UPGRADE_STAGE_INVALID")+}+fn lock(path: &Path) -> Result<File, &'static str> {+ let parent = security::ensure_private_directory(path.parent().ok_or("UPGRADE_STAGE_INVALID")?)+ .map_err(err)?;+ match security::open_read_write(path) {+ Ok(f) => {+ security::verify_owner_only_handle(&f, false).map_err(err)?;+ Ok(f)+ }+ Err(e) if e.kind() == io::ErrorKind::NotFound => security::create_owner_only_file_at(+ &parent,+ path.file_name().ok_or("UPGRADE_STAGE_INVALID")?,+ )+ .map_err(err),+ Err(e) => Err(err(e)),+ }+}+fn helper(directory: &Path) -> Result<PathBuf, &'static str> {+ let path = directory.join("finisher.exe");+ if path.try_exists().map_err(err)? {+ security::open_owner_only(&path, false).map_err(err)?;+ fs::remove_file(&path).map_err(err)?;+ }+ let mut input =+ security::open_identity(&std::env::current_exe().map_err(err)?, false).map_err(err)?;+ let parent = security::ensure_private_directory(directory).map_err(err)?;+ let mut output =+ security::create_owner_only_file_at(&parent, std::ffi::OsStr::new("finisher.exe"))+ .map_err(err)?;+ io::copy(&mut input, &mut output).map_err(err)?;+ output.sync_all().map_err(err)?;+ Ok(path)+}+pub(super) fn verify(release: &WindowsDesktopRelease) -> Result<(), &'static str> {+ release.revision_prefix()?;+ let path = stage(release)?.join("installer.exe");+ let file = security::open_owner_only(&path, false).map_err(err)?;+ if file.metadata().map_err(err)?.len() != release.size {+ return Err("UPGRADE_PACKAGE_SIZE_MISMATCH");+ }+ drop(file);+ if transaction::hash(&path).map_err(err)? != release.sha256 {+ return Err("UPGRADE_DIGEST_MISMATCH");+ }+ Ok(())+}+fn spawn(path: &Path, args: &[&str]) -> Result<(), &'static str> {+ use std::os::windows::process::CommandExt;+ Command::new(path)+ .args(args)+ .creation_flags(0x08000000)+ .spawn()+ .map_err(|_| "UPGRADE_INSTALLER_LAUNCH_FAILED")?;+ Ok(())+}+pub(super) fn launch(+ updater: &Updater,+ release: &WindowsDesktopRelease,+) -> Result<(), &'static str> {+ verify(release)?;+ let directory = stage(release)?;+ let parent = lock(&directory.join("parent.lock"))?;+ parent.try_lock_exclusive().map_err(|_| "UPGRADE_BUSY")?;+ let helper = helper(&directory)?;+ let job = Job {+ schema: "hiroute.windows-shell-update-job/v1".into(),+ release: release.clone(),+ helper_sha256: transaction::hash(&helper).map_err(err)?,+ generation: format!(+ "{:x}-{:x}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(err)?+ .as_nanos(),+ std::process::id()+ ),+ };+ write(&directory.join("job.json"), &job)?;+ let ready = directory.join("ready.json");+ if ready.try_exists().map_err(err)? {+ security::open_owner_only(&ready, false).map_err(err)?;+ fs::remove_file(&ready).map_err(err)?;+ }+ let cancelled = directory.join("cancel.json");+ if cancelled.try_exists().map_err(err)? {+ security::open_owner_only(&cancelled, false).map_err(err)?;+ fs::remove_file(&cancelled).map_err(err)?;+ }+ let committed = directory.join("commit.json");+ if committed.try_exists().map_err(err)? {+ security::open_owner_only(&committed, false).map_err(err)?;+ fs::remove_file(committed).map_err(err)?;+ }+ *updater+ .parent_lock+ .lock()+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")? = Some(parent);+ let result = (|| {+ spawn(&helper, &["--update-finish", &release.sha256])?;+ let deadline = Instant::now() + Duration::from_secs(5);+ while Instant::now() < deadline {+ if ready.try_exists().map_err(err)? {+ let value: serde_json::Value = read(&ready)?;+ if value["ready"] == true && value["generation"] == job.generation {+ return Ok(());+ }+ }+ std::thread::sleep(Duration::from_millis(25));+ }+ Err("UPGRADE_INSTALLER_LAUNCH_FAILED")+ })();+ if result.is_err() {+ let _ = write(&cancelled, &serde_json::json!({"cancelled":true}));+ updater+ .parent_lock+ .lock()+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?+ .take();+ }+ result+}+pub(super) fn commit(release: &WindowsDesktopRelease) -> Result<(), &'static str> {+ let directory = stage(release)?;+ let job: Job = read(&directory.join("job.json"))?;+ if job.schema != "hiroute.windows-shell-update-job/v1" || job.release.sha256 != release.sha256 {+ return Err("UPGRADE_STAGE_INVALID");+ }+ write(+ &directory.join("commit.json"),+ &crate::handoff::WindowsUpdateCommitV1::new(job.generation, release.sha256.clone()),+ )+}+fn wait_parent(directory: &Path) -> Result<File, &'static str> {+ let parent = lock(&directory.join("parent.lock"))?;+ let deadline = Instant::now() + Duration::from_secs(30);+ while parent.try_lock_exclusive().is_err() {+ if Instant::now() >= deadline {+ return Err("UPGRADE_PARENT_EXIT_TIMEOUT");+ }+ std::thread::sleep(Duration::from_millis(30));+ }+ Ok(parent)+}+fn finish(id: &str) -> Result<(), &'static str> {+ let directory = directory(id)?;+ let job: Job = read(&directory.join("job.json"))?;+ if job.schema != "hiroute.windows-shell-update-job/v1"+ || job.release.sha256 != id+ || transaction::hash(&std::env::current_exe().map_err(err)?).map_err(err)?+ != job.helper_sha256+ {+ return Err("UPGRADE_STAGE_INVALID");+ }+ let update = lock(&transaction::data().map_err(err)?.join("update.lock"))?;+ update.try_lock_exclusive().map_err(|_| "UPGRADE_BUSY")?;+ verify(&job.release)?;+ write(+ &directory.join("ready.json"),+ &serde_json::json!({"ready":true,"generation":job.generation}),+ )?;+ let _parent = wait_parent(&directory)?;+ if directory.join("cancel.json").try_exists().map_err(err)? {+ return Err("UPGRADE_CANCELLED");+ }+ let committed: crate::handoff::WindowsUpdateCommitV1 =+ read(&directory.join("commit.json")).map_err(|_| "UPGRADE_COMMIT_MISSING")?;+ if !committed.matches(&job.generation, id) {+ return Err("UPGRADE_COMMIT_MISSING");+ }+ verify(&job.release)?;+ use std::os::windows::process::CommandExt;+ let installed = Command::new(directory.join("installer.exe"))+ .args(["/P", "/UPDATE"])+ .creation_flags(0x08000000)+ .status()+ .is_ok_and(|status| status.success());+ if !installed || transaction::has_pending().map_err(err)? {+ transaction::rollback(false).map_err(|_| "SHELL_INSTALL_RECOVERY_REQUIRED")?;+ let resumed = resume_admission().is_ok() && service::available_blocking();+ write(+ &transaction::data()+ .map_err(err)?+ .join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"failed","code":"UPGRADE_INSTALL_FAILED","service_available":resumed}),+ )?;+ } else {+ write(+ &transaction::data()+ .map_err(err)?+ .join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"succeeded"}),+ )?;+ }+ spawn(+ &transaction::root().map_err(err)?.join("hiroute-shell.exe"),+ &["--recovery-report"],+ )+}+fn recover() -> Result<(), &'static str> {+ let directory = transaction::data().map_err(err)?.join("recovery");+ let _parent = wait_parent(&directory)?;+ let update = lock(&transaction::data().map_err(err)?.join("update.lock"))?;+ update.try_lock_exclusive().map_err(|_| "UPGRADE_BUSY")?;+ let _install =+ hiroute_platform::windows::install::desktop_install_guard().map_err(|_| "UPGRADE_BUSY")?;+ let result = transaction::rollback(false).map_err(|_| "SHELL_INSTALL_RECOVERY_REQUIRED");+ let admission = if daemon().is_ok() {+ resume_admission()+ } else {+ Ok(())+ };+ // The marker prevents a failed recovery from recursively spawning another helper.+ let _ = spawn(+ &transaction::root().map_err(err)?.join("hiroute-shell.exe"),+ &["--recovery-report"],+ );+ result.and(admission)+}+pub(crate) fn run_if_requested() -> Option<i32> {+ let args: Vec<_> = std::env::args().skip(1).collect();+ let result = match args.first().map(String::as_str) {+ Some("--update-finish") if args.len() == 2 => finish(&args[1]),+ Some("--update-recover") if args.len() == 1 => recover(),+ _ => return None,+ };+ if let Err(code) = result {+ let available = resume_admission().is_ok() && service::available_blocking();+ if code != "UPGRADE_CANCELLED" {+ if let Ok(data) = transaction::data() {+ let _ = write(+ &data.join("update-outcome.json"),+ &serde_json::json!({"schema":"hiroute.windows-shell-update-outcome/v1","status":"failed","code":code,"service_available":available}),+ );+ }+ }+ if let Ok(root) = transaction::root() {+ let _ = spawn(&root.join("hiroute-shell.exe"), &["--recovery-report"]);+ }+ Some(1)+ } else {+ Some(0)+ }+}+/// A killed installer may leave admission paused even if it had not reached file replacement.+pub(crate) fn recover_startup(+ app: &tauri::AppHandle,+ state: &Arc<ShellState>,+ manual_retry: bool,+) -> Result<bool, &'static str> {+ let update = lock(&transaction::data().map_err(err)?.join("update.lock"))?;+ update.try_lock_exclusive().map_err(|_| "UPGRADE_BUSY")?;+ if transaction::has_pending().map_err(err)? {+ let _install = hiroute_platform::windows::install::desktop_install_guard()+ .map_err(|_| "UPGRADE_BUSY")?;+ if !manual_retry && std::env::args().any(|a| a == "--recovery-report") {+ return Err("SHELL_INSTALL_RECOVERY_REQUIRED");+ }+ let directory = transaction::data().map_err(err)?.join("recovery");+ security::ensure_private_directory(&directory).map_err(err)?;+ let parent = lock(&directory.join("parent.lock"))?;+ parent.try_lock_exclusive().map_err(|_| "UPGRADE_BUSY")?;+ let helper = helper(&directory)?;+ *state+ .updater+ .parent_lock+ .lock()+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")? = Some(parent);+ spawn(&helper, &["--update-recover"])?;+ drop(update);+ app.exit(0);+ return Ok(true);+ }+ if daemon().is_ok() {+ resume_admission()?;+ }+ let outcome = transaction::data()+ .map_err(err)?+ .join("update-outcome.json");+ if outcome.try_exists().map_err(err)? {+ let value: serde_json::Value = read(&outcome)?;+ if value["schema"] != "hiroute.windows-shell-update-outcome/v1" {+ return Err("UPGRADE_STAGE_INVALID");+ }+ if value["status"] == "failed" {+ state.updater.change(|v| {+ v.phase = "failed";+ v.error = Some("UPGRADE_INSTALL_FAILED");+ v.recovery = Some(if value["service_available"] == true {+ "service_available"+ } else {+ "restart_required"+ });+ });+ }+ }+ Ok(false)+}diff --git a/apps/shell/src-tauri/tauri.conf.json b/apps/shell/src-tauri/tauri.conf.jsonnew file mode 100644index 00000000..966477a0--- /dev/null+++ b/apps/shell/src-tauri/tauri.conf.json@@ -0,0 +1,47 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "productName": "HiRoute",+ "version": "0.3.1",+ "identifier": "ai.hiroute.desktop",+ "build": {+ "frontendDist": "../dist",+ "beforeBuildCommand": "npm run build"+ },+ "app": {+ "windows": [],+ "security": {+ "capabilities": [+ "status",+ "console"+ ],+ "csp": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; frame-src 'none'; form-action 'none'"+ }+ },+ "bundle": {+ "active": true,+ "targets": [+ "nsis"+ ],+ "icon": [+ "../../desktop/src-tauri/icons/icon.ico",+ "../../desktop/src-tauri/icons/icon.png"+ ],+ "resources": {+ "resources/standalone/": "standalone/"+ },+ "windows": {+ "webviewInstallMode": {+ "type": "embedBootstrapper",+ "silent": true+ },+ "nsis": {+ "installMode": "currentUser",+ "template": "installer/installer.nsi",+ "installerHooks": "installer/hooks.nsh",+ "languages": [+ "English"+ ]+ }+ }+ }+}diff --git a/apps/shell/src/main.ts b/apps/shell/src/main.tsnew file mode 100644index 00000000..1999e865--- /dev/null+++ b/apps/shell/src/main.ts@@ -0,0 +1,34 @@+import '../../desktop/src/occami/styles.css';+import './status.css';+declare global { interface Window { __TAURI_INTERNALS__: { invoke<T>(command: string): Promise<T> } } }+type Report = { phase: 'starting' | 'waiting' | 'ready' | 'failed'; code: string | null; logs_path: string };+let language = navigator.language.startsWith('zh') ? 'zh' : 'en';+let dark = matchMedia('(prefers-color-scheme: dark)').matches;+let report: Report = { phase: 'starting', code: null, logs_path: '' };+const element = (id: string) => document.getElementById(id)!;+function render() {+ const zh = language === 'zh'; const text = (cn: string, en: string) => zh ? cn : en;+ const listenerUnavailable = report.phase === 'failed' && report.code === 'CONSOLE_LISTENER_UNAVAILABLE';+ document.documentElement.lang = zh ? 'zh-CN' : 'en';+ element('root').dataset.theme = dark ? 'dark' : 'light';+ element('phase').textContent = listenerUnavailable ? text('本机控制台尚未就绪', 'The local console is unavailable') : report.phase === 'failed' ? text('无法启动本机服务', 'Could not start the local service') : text('正在连接 HiRoute 服务', 'Connecting to HiRoute');+ element('explanation').textContent = listenerUnavailable ? text('后台服务已就绪,但本机控制台未监听。控制台可能已被关闭,或指定端口被占用。', 'The background service is ready, but the local console is not listening. It may be disabled, or its configured port may be in use.') : report.phase === 'failed' ? text('请保留现有数据,在下方日志目录查看详情后重试。', 'Keep your existing data. Check the log directory below, then try again.') : report.phase === 'waiting' ? text('服务正在准备控制台与 Gateway…', 'Preparing the console and Gateway…') : text('正在检查并启动后台服务…', 'Checking and starting the background service…');+ element('console-recovery').hidden = !listenerUnavailable;+ element('recovery-explanation').textContent = text('如需恢复本机界面,请在 PowerShell 中运行以下命令,使用自动选择的本机端口:', 'To restore the local interface, run these commands in PowerShell to use an automatically selected local port:');+ element('recovery-warning').textContent = text('重启服务可能中断正在进行的调用和任务。完成后点击“重新检查”;此按钮只检查状态,不会修改监听设置。', 'Restarting the service may interrupt active calls and tasks. Then select Recheck; the button only checks status and does not change listener settings.');+ element('failure').textContent = report.code ?? '';+ element('logs-label').textContent = text('本机日志目录', 'Local log directory');+ (element('logs') as HTMLInputElement).value = report.logs_path;+ element('retry').hidden = report.phase !== 'failed'; element('retry').textContent = listenerUnavailable ? text('重新检查', 'Recheck') : text('重试', 'Try again');+ element('language').textContent = zh ? 'English' : '中文'; element('theme').textContent = dark ? text('浅色', 'Light') : text('深色', 'Dark');+}+element('language').onclick = () => { language = language === 'zh' ? 'en' : 'zh'; render(); };+element('theme').onclick = () => { dark = !dark; render(); };+element('logs').onfocus = () => (element('logs') as HTMLInputElement).select();+element('retry').onclick = () => { (element('retry') as HTMLButtonElement).disabled = true; void window.__TAURI_INTERNALS__.invoke('shell_retry_startup').finally(() => { (element('retry') as HTMLButtonElement).disabled = false; }); };+async function poll() {+ try { report = await window.__TAURI_INTERNALS__.invoke<Report>('shell_status'); }+ catch { report = { ...report, phase: 'failed', code: 'SHELL_STATUS_UNAVAILABLE' }; }+ render(); window.setTimeout(() => void poll(), 750);+}+render(); void poll();diff --git a/apps/shell/src/status.css b/apps/shell/src/status.cssnew file mode 100644index 00000000..8832b926--- /dev/null+++ b/apps/shell/src/status.css@@ -0,0 +1,8 @@+.shell-status { height: 100%; display: grid; place-items: safe center; overflow: auto; padding: 24px; }+.shell-status > section { width: min(100%, 560px); padding: 28px; display: flex; flex-direction: column; gap: 18px; min-width: 0; }+.shell-status h1, .shell-status h2, .shell-status p { margin: 0; overflow-wrap: anywhere; }+.shell-status h2 { font-size: 24px; line-height: 1.35; }+.shell-status p { line-height: 1.65; }+.shell-status input { min-width: 0; width: 100%; }+.shell-status pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 12px 0; font-size: 13px; line-height: 1.7; }+.shell-status .actions { display: flex; gap: 8px; flex-wrap: wrap; }diff --git a/apps/website/.gitignore b/apps/website/.gitignoreindex 4c2177eb..478d6746 100644--- a/apps/website/.gitignore+++ b/apps/website/.gitignore@@ -8,3 +8,4 @@ public/install.shpublic/releases.jsonpublic/brand/app-icon.pngpublic/news-assets/+public/releases-v3.jsondiff --git a/apps/website/content/guides/install-linux.en.md b/apps/website/content/guides/install-linux.en.mdindex 76b56242..abddb418 100644--- a/apps/website/content/guides/install-linux.en.md+++ b/apps/website/content/guides/install-linux.en.md@@ -28,6 +28,24 @@ export PATH="$HOME/.local/bin:$PATH"The installer downloads the latest stable Linux release and checks its architecture and file integrity before installation. Desktop and standalone must not manage the service in the same `HOME`.+## Configure the optional Web console++Linux keeps the console off unless configured. To choose scope and port during installation:++```sh+curl -fsSL https://hiroute.ai/install.sh | sh -s -- --console-mode loopback --console-port 5838+```++Or initialize it after installation, before starting the service:++```sh+hiroute console init --mode loopback --port 5838+```++For access from another computer, use `--mode network --listen 192.0.2.10 --port 5838 --allow-plaintext-network`, replacing the example IP with the host's reachable address. Wildcard binds such as `0.0.0.0` also require `--advertise-address IP`. The equivalent installer flags use the `--console-` prefix; plaintext consent remains `--allow-plaintext-network`. Upgrades without these options preserve the existing configuration.++After service startup, `hiroute console open` prints a two-minute, single-use login URL for the actual local or remote listener. Open it on your computer; a server needs no desktop. The command never starts listening. Desired changes require a service restart. HTTP remote sessions display an unencrypted-traffic warning. Named CLI-created access tokens remain available for repeated login. See the [console guide](https://github.com/higress-group/HiRoute/blob/main/docs/web-console.md).+## 2. Start the service explicitlyInstallation never starts the service or replays a request automatically. After installation, run:diff --git a/apps/website/content/guides/install-linux.zh.md b/apps/website/content/guides/install-linux.zh.mdindex 4115af5f..1ea378e9 100644--- a/apps/website/content/guides/install-linux.zh.md+++ b/apps/website/content/guides/install-linux.zh.md@@ -28,6 +28,24 @@ export PATH="$HOME/.local/bin:$PATH"安装脚本会下载最新稳定的 Linux 版本,并在安装前检查架构与文件完整性。桌面应用与独立服务版(standalone)不应在同一个 `HOME` 中同时管理服务。+## 配置可选的 Web 控制台++Linux 默认关闭控制台。安装时可选择监听范围和端口:++```sh+curl -fsSL https://hiroute.ai/install.sh | sh -s -- --console-mode loopback --console-port 5838+```++也可以安装后、启动服务前配置:++```sh+hiroute console init --mode loopback --port 5838+```++需要其他电脑访问时,使用 `--mode network --listen 192.0.2.10 --port 5838 --allow-plaintext-network`,把示例 IP 换成主机可达地址。监听 `0.0.0.0` 等通配地址时,还需 `--advertise-address IP` 指定链接中的实际地址。安装器对应参数以 `--console-` 开头,明文风险确认仍为 `--allow-plaintext-network`。升级时不传这些选项会保留已有配置。++服务启动后,`hiroute console open` 为实际已监听的本地或远程地址生成两分钟有效、仅可使用一次的登录 URL。把链接放到自己的电脑上打开即可,服务器不需要桌面;这个命令不会启动监听。修改配置需要重启服务后生效。远程 HTTP 页面持续提示明文传输风险,也可使用 CLI 创建的具名 token 重复登录。详见 [控制台指南](https://github.com/higress-group/HiRoute/blob/main/docs/web-console.md)。+## 2. 启动服务安装不会自动启动服务或重放请求。安装完成后运行:diff --git a/apps/website/content/guides/install-windows.en.md b/apps/website/content/guides/install-windows.en.mdnew file mode 100644index 00000000..57b1164d--- /dev/null+++ b/apps/website/content/guides/install-windows.en.md@@ -0,0 +1,43 @@+# Install HiRoute Desktop on Windows++HiRoute Desktop uses a current-user NSIS installer for native Windows x64. It includes the command line, background service, console files and a WebView2 bootstrapper. Python and administrator privileges are not required. Choose a Windows Desktop installer from the [download page](/en/download/) when a validated release is available.++## Verify the download++The filename is `HiRoute-<version>-<revision>-windows-x86_64-setup.exe`. Download from `hiroute.ai/releases/<version>/` and compare the full SHA-256 shown beside that exact file:++```powershell+Get-FileHash -Algorithm SHA256 -LiteralPath "$env:USERPROFILE\Downloads\YOUR-INSTALLER.exe"+```++[Get-FileHash](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash) calculates the file digest. If it differs, delete the file and download it again.++## Open an unsigned installer++This release is unsigned. Windows may show an unknown publisher or a SmartScreen reputation warning. After verifying the source and digest, select **More info → Run anyway** when that choice is offered. An organization policy or Smart App Control may block this choice; use your organization's approval process. Do not disable Windows security. Microsoft describes these protections in [App & browser control](https://support.microsoft.com/en-us/windows/security/windows-security/app-browser-control-in-the-windows-security-app).++## Install and start++1. Open the installer in your ordinary account. It installs in `%LOCALAPPDATA%\Programs\HiRoute` and keeps service data separately under `%LOCALAPPDATA%\HiRoute\cli`.+2. Login startup and the tray are enabled by default. You can deselect either option. With the tray disabled, closing the window exits the shell; the background service continues.+3. Open HiRoute. It checks the current-user Task, starts the service, waits for the Gateway and opens its local console. There is no password or unlock step. Protected actions retain their page confirmation.++An existing current-user Task installation is upgraded. SCM installation is not offered in this release. An existing SCM-managed installation is refused unchanged before product writes. ARM64 and x86 hosts are unsupported by this Desktop installer.++The installer adds the fixed `.local\bin` directory to your user PATH without replacing other entries. Open a new terminal for the updated PATH. Settings and the tray's **Start at login** action manage the shell and Task together. **Quit** exits the shell and leaves the service running.++For unattended installation, run the verified installer with `/S` and wait for its process exit code. It applies the default login-start and tray choices without prompts, starts the service and returns a nonzero code on failure. CLI-only users install this same package. Windows standalone archives and ARM64 packages are not published.++## Update and recover++Open **Settings → Updates**. The shell downloads a newer stable installer from the official HTTPS catalog and verifies its size and SHA-256 while your service keeps running. Installation waits for active calls and Worker tasks. **Cancel update** resumes normal admission without cancelling or replaying your work. The installer then replaces the application and reopens HiRoute.++A manually downloaded newer installer uses the same drain and transaction path. An older daemon that cannot drain requires an explicit interactive confirmation before it can be stopped; a passive update refuses it. If an update fails, the startup page or Updates shows the failure and recovery status. Keep the logs and retained backups. Starting the shell after an interrupted installer attempts journal recovery and resumes paused admission; changed or foreign files require repair and are preserved.++## Uninstall++Use **Installed apps → HiRoute → Uninstall**. Before removing the service, HiRoute restores its supported Agent configuration. If restoration needs a decision, uninstall stops and reports the Agent IDs; resolve them in HiRoute and retry. It removes only its recorded application files, Task, shell login entry and any CLI PATH entry it added. Data is retained unless you explicitly select its removal. The separate headless state directory is never used as the NSIS install directory.++If the service is unavailable, interactive recovery or uninstall offers a separate confirmation with **No** selected by default. Continuing may interrupt active work and leave configured Agents needing manual restoration; all HiRoute data is kept. Unattended mode refuses this exception, and a known restoration conflict still blocks removal. A failed first install with no Agent data can roll back without starting the service.++After an upgrade commits, obsolete verified package files are removed. Uninstall removes the current verified package too; changed or foreign files are preserved.diff --git a/apps/website/content/guides/install-windows.zh.md b/apps/website/content/guides/install-windows.zh.mdnew file mode 100644index 00000000..dfbd7807--- /dev/null+++ b/apps/website/content/guides/install-windows.zh.md@@ -0,0 +1,43 @@+# Windows 桌面版安装++HiRoute 桌面版提供按当前用户安装的 NSIS 安装包,只支持原生 Windows x64。安装包自带命令行、后台服务、控制台文件和 WebView2 引导安装器,不要求 Python 或管理员权限。经过验证的版本发布后,可从[下载页](/download/)选择 Windows 桌面安装包。++## 校验下载++文件名为 `HiRoute-<版本>-<源码修订>-windows-x86_64-setup.exe`。从 `hiroute.ai/releases/<版本>/` 下载,在 PowerShell 中计算摘要,与下载页该文件旁的完整 SHA-256 比较:++```powershell+Get-FileHash -Algorithm SHA256 -LiteralPath "$env:USERPROFILE\Downloads\YOUR-INSTALLER.exe"+```++[Get-FileHash](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash) 用于计算文件摘要。不一致时请删除文件并重新下载。++## 打开未签名安装包++本期版本没有代码签名,Windows 可能显示“未知发布者”或 SmartScreen 信誉提示。确认下载来源和摘要后,在系统提供该选项时选择“更多信息 → 仍要运行”。组织策略或 Smart App Control 可能禁止继续运行,此时请走组织的应用批准流程,不要关闭 Windows 安全功能。微软的[应用和浏览器控制说明](https://support.microsoft.com/en-us/windows/security/windows-security/app-browser-control-in-the-windows-security-app)介绍了这些保护。++## 安装与启动++1. 在普通用户会话打开安装包。安装目录固定为 `%LOCALAPPDATA%\Programs\HiRoute`;后台服务的数据单独存放在 `%LOCALAPPDATA%\HiRoute\cli`。+2. 登录自启和托盘默认开启,安装时可以分别取消。关闭托盘后,关闭窗口会退出壳,后台服务继续运行。+3. 打开 HiRoute。壳检查当前用户的 Task,启动服务,等待 Gateway 就绪后打开本机控制台。不需要口令或解锁,受保护操作仍在页面内逐次确认。++同一用户已有的 Task 安装会原地升级。本期不提供 SCM 安装;已有 SCM 托管的安装会在产品写入前被拒绝,并保持原样。此桌面安装包不支持 ARM64 或 x86 主机。++安装器把固定的 `.local\bin` 加入当前用户 PATH,保留其它条目;新开终端后生效。设置页与托盘的“Start at login”同时管理壳和后台 Task。托盘“Quit”只退出壳,服务保留运行。++无人值守安装可在校验安装包后,使用 `/S` 运行并等待进程退出码。安装器采用默认的登录自启和托盘选项,全程不弹提示,完成后启动服务,失败时返回非零退出码。仅使用 CLI 和 daemon 的用户也安装同一包。本期不发布 Windows standalone 归档或 ARM64 包。++## 更新与恢复++打开“设置 → 版本升级”。壳从官方 HTTPS 发布目录下载较新的稳定版,并在服务继续运行时检查大小和 SHA-256。安装前等待现有调用与 Worker 任务结束;“取消升级”恢复接收新工作,不取消或重放现有任务。随后安装器替换应用并重新打开 HiRoute。++手动下载的新安装包使用同一套排空与事务流程。旧 daemon 不支持排空时,只有交互式安装经明确确认后才能停止它,静默更新会拒绝。失败后,启动页或升级页显示错误和恢复状态,请保留日志与备份。安装被中断后再次打开壳,会尝试 journal 恢复并恢复被暂停的接收入口;遇到变更或外来文件时保留现场并要求修复。++## 卸载++在“已安装的应用 → HiRoute → 卸载”中开始。移除服务前,HiRoute 会恢复受支持的 Agent 配置;需要人工决策时停止卸载并列出 Agent ID,先在 HiRoute 中处理后再试。卸载只删除已登记的安装文件、Task、壳登录项及它自行加入的 CLI PATH 条目。数据默认保留,只有明确勾选才删除。独立 headless 状态目录不会成为 NSIS 的安装目录。++如果服务不可用,交互式恢复或卸载会另行确认,默认选择“否”。继续操作可能中断正在执行的工作,已配置的 Agent 也可能需要手动恢复;所有 HiRoute 数据都会保留。无人值守模式不会绕过这项确认,已发现的恢复冲突也仍会阻止卸载。首次安装失败且没有 Agent 数据时,可以不启动服务直接回滚。++升级提交后,会清理已验证的旧版本程序文件;卸载也会移除当前版本。被修改或外来的文件会保留。diff --git a/apps/website/data/releases.json b/apps/website/data/releases.jsonindex 69c8666d..5254a12f 100644--- a/apps/website/data/releases.json+++ b/apps/website/data/releases.json@@ -1,5 +1,5 @@{- "schema": "hiroute.website.releases/v2",+ "schema": "hiroute.website.releases/v3","releases": [{"version": "0.3.1",diff --git a/apps/website/scripts/prepare-content.mjs b/apps/website/scripts/prepare-content.mjsindex cfe6b417..9db06662 100644--- a/apps/website/scripts/prepare-content.mjs+++ b/apps/website/scripts/prepare-content.mjs@@ -2,7 +2,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import { generateLinuxInstallScript } from '../src/lib/install-script.mjs';-import { releaseManifest } from '../src/lib/releases.mjs';+import { releaseManifest, projectReleaseManifest, LEGACY_RELEASE_SCHEMA } from '../src/lib/releases.mjs';const website = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const repository = path.resolve(website, '../..');@@ -29,7 +29,8 @@ for (const entry of await fs.readdir(path.join(source, 'assets'), { withFileType}await fs.copyFile(path.join(repository, 'scripts/install-standalone.py'), path.join(installDirectory, 'standalone.py'));await fs.writeFile(path.join(publicDirectory, 'install.sh'), generateLinuxInstallScript(releaseManifest), { mode: 0o755 });-await fs.writeFile(path.join(publicDirectory, 'releases.json'), JSON.stringify(releaseManifest, null, 2) + '\n');+await fs.writeFile(path.join(publicDirectory, 'releases.json'), JSON.stringify(projectReleaseManifest(releaseManifest, LEGACY_RELEASE_SCHEMA), null, 2) + '\n');+await fs.writeFile(path.join(publicDirectory, 'releases-v3.json'), JSON.stringify(projectReleaseManifest(releaseManifest), null, 2) + '\n');console.log('Prepared canonical Decision API, illustrations, and Linux installer entry.');const newsAssets = path.join(publicDirectory, 'news-assets');diff --git a/apps/website/scripts/release-manifest.mjs b/apps/website/scripts/release-manifest.mjsindex 031d976f..8fdd6ad1 100755--- a/apps/website/scripts/release-manifest.mjs+++ b/apps/website/scripts/release-manifest.mjs@@ -19,6 +19,7 @@ if (release && channelIndex >= 0 && release.channel !== args[channelIndex + 1])function expectedFilename(artifact) {if (!release || !revision) throw new Error('--tag and --revision are required');if (artifact.kind === 'desktop') {+ if (artifact.platform === 'Windows') return `HiRoute-${release.version}-${revision.slice(0, 12)}-windows-x86_64-setup.exe`;const suffix = artifact.distribution === 'self-signed' ? 'trial' : 'developer-id';return `HiRoute-${release.version}-${revision.slice(0, 12)}-macos-${artifact.architecture}-${suffix}.dmg`;}diff --git a/apps/website/scripts/validate-build.mjs b/apps/website/scripts/validate-build.mjsindex 8f280a2d..169ff302 100644--- a/apps/website/scripts/validate-build.mjs+++ b/apps/website/scripts/validate-build.mjs@@ -19,7 +19,7 @@ const required = ['docs/decision-api/index.html', 'en/docs/decision-api/index.html','docs/jev-decider/index.html', 'en/docs/jev-decider/index.html','api/decision.openapi.json', 'api/decision-examples.json',- 'install.sh', 'install/standalone.py', 'releases.json', '404.html', 'sitemap-index.xml',+ 'install.sh', 'install/standalone.py', 'releases.json', 'releases-v3.json', '404.html', 'sitemap-index.xml',];for (const relative of required) {if (!fs.existsSync(path.join(dist, relative))) throw new Error(`missing website output: ${relative}`);diff --git a/apps/website/src/components/DocsNav.astro b/apps/website/src/components/DocsNav.astroindex b0ad40cf..60648d32 100644--- a/apps/website/src/components/DocsNav.astro+++ b/apps/website/src/components/DocsNav.astro@@ -8,6 +8,7 @@ const prefix = en ? '/en' : '';<a class:list={{active:active === 'quickstart'}} href={`${prefix}/docs/`}>{en ? 'Quickstart' : '快速开始'}</a><a class:list={{active:active === 'install-macos'}} href={`${prefix}/docs/install-macos/`}>{en ? 'Install on macOS' : 'macOS 安装与首次启动'}</a><a class:list={{active:active === 'install-linux'}} href={`${prefix}/docs/install-linux/`}>{en ? 'Linux headless' : 'Linux 无界面版安装'}</a>+ <a class:list={{active:active === 'install-windows'}} href={`${prefix}/docs/install-windows/`}>{en ? 'Install on Windows' : 'Windows 桌面版安装'}</a><span>{en ? 'USE HIROUTE' : '使用 HIROUTE'}</span><a class:list={{active:active === 'model-routing'}} href={`${prefix}/docs/model-routing/`}>{en ? 'Smart model routing' : '智能模型路由'}</a>diff --git a/apps/website/src/components/DownloadPage.astro b/apps/website/src/components/DownloadPage.astroindex a4869ef8..e2047de9 100644--- a/apps/website/src/components/DownloadPage.astro+++ b/apps/website/src/components/DownloadPage.astro@@ -1,6 +1,7 @@---import SiteLayout from '../layouts/SiteLayout.astro';-import { artifactManifestUrl, artifactUrl, formatBytes, releaseManifest } from '../lib/releases.mjs';+import { releaseManifest } from '../lib/releases.mjs';+import ReleaseArtifact from './ReleaseArtifact.astro';const { language = 'zh' } = Astro.props;const en = language === 'en';const t = (zh, english) => en ? english : zh;@@ -10,13 +11,13 @@ const alternatePath = en ? '/download/' : '/en/download/';const stable = releaseManifest.releases.find(release => release.channel === 'stable');const preview = releaseManifest.releases.find(release => release.channel === 'preview');const shown = [stable, preview].filter((release, index, all) => release && all.indexOf(release) === index);-const stableLinux = stable?.artifacts.filter(artifact => artifact.kind === 'standalone') ?? [];+const stableLinux = stable?.artifacts.filter(artifact => artifact.kind === 'standalone' && artifact.platform === 'Linux') ?? [];const linuxArchitectures = stableLinux.map(artifact => artifact.architecture).join(' / ');---<SiteLayout language={language} title={t('下载 HiRoute', 'Download HiRoute') + ' · HiRoute'}- description={t('在 macOS 使用桌面应用,或在 Linux 用一条命令安装 HiRoute 无界面版。', 'Use HiRoute Desktop on macOS or install HiRoute headless on Linux with one command.')}+ description={t('在 macOS 或 Windows 使用桌面应用,或在 Linux 安装 HiRoute 无界面版。', 'Use HiRoute Desktop on macOS or Windows, or install HiRoute headless on Linux.')}path={path} alternatePath={alternatePath}>- <section class="page-hero wrap"><div class="eyebrow section-label">{t('下载', 'DOWNLOAD')}</div><h1>{t('选择你的运行方式', 'Choose how to run HiRoute')}</h1><p>{t('macOS 提供可视化桌面应用;Linux 提供面向服务器和自动化环境的无界面命令行。选择适合你的安装包,并可通过 SHA256 校验文件完整性。', 'macOS provides the visual Desktop app. Linux provides a headless CLI for servers and automation. Choose the package for your platform and verify its integrity with the provided SHA256 checksum.')}</p></section>+ <section class="page-hero wrap"><div class="eyebrow section-label">{t('下载', 'DOWNLOAD')}</div><h1>{t('选择你的运行方式', 'Choose how to run HiRoute')}</h1><p>{t('macOS 与 Windows 提供可视化桌面应用;Linux 提供面向服务器和自动化环境的无界面命令行。选择适合你的安装包,并可通过 SHA256 校验文件完整性。', 'macOS and Windows provide the visual Desktop app. Linux provides a headless CLI for servers and automation. Choose the package for your platform and verify its integrity with the provided SHA256 checksum.')}</p></section><section class="content-section wrap platform-install"><div class="platform-heading"><div><span class="release-channel">{t('Linux · 无界面版', 'Linux · headless')}</span><h2>{t('一条命令,按当前用户安装', 'One command, installed for the current user')}</h2><p>{t('安装器识别 x86_64 或 aarch64,下载最新稳定版,校验后安装到 ~/.local;不使用 sudo,也不会自动启动服务。', 'The installer detects x86_64 or aarch64, downloads the latest stable release, verifies it, and installs under ~/.local. It uses no sudo and does not start the service automatically.')}</p></div><a class="text-link" href={en ? '/en/docs/install-linux/' : '/docs/install-linux/'}>{t('Linux 无界面版指南', 'Linux headless guide')} →</a></div>@@ -31,9 +32,9 @@ sh install.sh</code></pre></details></section><section class="content-section wrap release-section">- <div class="platform-heading"><div><span class="release-channel">macOS · {t('桌面应用 / 手动包', 'Desktop / manual packages')}</span><h2>{t('版本与发布文件', 'Versions and release files')}</h2><p>{t('桌面应用直接下载 DMG;Linux 一行安装是推荐入口,归档与伴随清单仍保留给离线、镜像和审计场景。', 'Download a DMG for Desktop. The one-line command is the recommended Linux path; archives and companion manifests remain available for offline, mirroring, and audit workflows.')}</p></div></div>- {shown.length === 0 ? <div class="empty-release"><span>{t('准备中', 'IN PREPARATION')}</span><h2>{t('首个公开版本尚未发布', 'The first public release is not published yet')}</h2><p>{t('安装包通过完整性检查、安装走查和发布审核后才会出现在这里。你可以先阅读快速开始。', 'Packages appear here only after integrity checks, installation review, and release approval. Start with the Quickstart in the meantime.')}</p><div class="actions"><a class="button" href={en ? '/en/docs/' : '/docs/'}>{t('快速开始', 'Quickstart')} ↗</a></div></div> : shown.map(release => <article class="release-card"><div class="release-heading"><div><span class="release-channel">{channelLabel(release.channel)}</span><h2>HiRoute {release.version}</h2><p>{release.notes[language]}</p></div><time datetime={release.published_at}>{new Intl.DateTimeFormat(en ? 'en' : 'zh-CN', { dateStyle: 'long' }).format(new Date(release.published_at))}</time></div><div class="artifact-list">{release.artifacts.map(artifact => artifact.kind === 'desktop' ? <div class="artifact-row"><div><strong>{t('macOS 桌面应用', 'macOS Desktop')} · {artifact.architecture}</strong><span>{t(`最低 macOS ${artifact.minimum_os}`, `macOS ${artifact.minimum_os}+`)}</span><span class:list={['distribution-badge', { 'self-signed': artifact.distribution === 'self-signed' }]}>{artifact.distribution === 'self-signed' ? t('自签名 · 首次启动需手动确认', 'Self-signed · manual approval required on first launch') : t('Developer ID 签名与公证', 'Developer ID signed and notarized')}</span><code>SHA256 {artifact.sha256}</code></div><a class="button" href={artifactUrl(release, artifact)}>{t('下载 DMG', 'Download DMG')} · {formatBytes(artifact.size, language)}</a></div> : <div class="artifact-row"><div><strong>{t('Linux 无界面版', 'Linux headless')} · {artifact.architecture}</strong><span>{artifact.target} · {formatBytes(artifact.size, language)}</span><span class="distribution-badge">{t('未签名 · 清单与 SHA256 验证', 'Unsigned · manifest and SHA256 verified')}</span><code>SHA256 {artifact.sha256}</code><a class="companion-link" href={artifactManifestUrl(release, artifact)} download>{t('下载伴随清单', 'Download companion manifest')}</a></div><a class="button outline" href={artifactUrl(release, artifact)}>{t('手动下载归档', 'Manual archive')} ↓</a></div>)}</div></article>)}+ <div class="platform-heading"><div><span class="release-channel">{t('桌面应用 / 手动包', 'Desktop / manual packages')}</span><h2>{t('版本与发布文件', 'Versions and release files')}</h2><p>{t('macOS 下载 DMG,Windows x64 下载 NSIS 安装包;Linux 一行安装是推荐入口,归档与伴随清单仍保留给离线、镜像和审计场景。', 'Download a DMG for macOS or an NSIS installer for Windows x64. The one-line command is the recommended Linux path; archives and companion manifests remain available for offline, mirroring, and audit workflows.')}</p></div></div>+ {shown.length === 0 ? <div class="empty-release"><span>{t('准备中', 'IN PREPARATION')}</span><h2>{t('首个公开版本尚未发布', 'The first public release is not published yet')}</h2><p>{t('安装包通过完整性检查、安装走查和发布审核后才会出现在这里。你可以先阅读快速开始。', 'Packages appear here only after integrity checks, installation review, and release approval. Start with the Quickstart in the meantime.')}</p><div class="actions"><a class="button" href={en ? '/en/docs/' : '/docs/'}>{t('快速开始', 'Quickstart')} ↗</a></div></div> : shown.map(release => <article class="release-card"><div class="release-heading"><div><span class="release-channel">{channelLabel(release.channel)}</span><h2>HiRoute {release.version}</h2><p>{release.notes[language]}</p></div><time datetime={release.published_at}>{new Intl.DateTimeFormat(en ? 'en' : 'zh-CN', { dateStyle: 'long' }).format(new Date(release.published_at))}</time></div><div class="artifact-list">{release.artifacts.map(artifact => <ReleaseArtifact release={release} artifact={artifact} language={language} />)}</div></article>)}</section>- <section class="content-section wrap install-note"><h2>{t('安装边界', 'Installation boundaries')}</h2><ol><li>{t('Linux 无界面版按当前用户安装,不要求 root;桌面应用与独立服务版(standalone)不应在同一 HOME 中同时管理服务。', 'Linux headless is a per-user installation with no root requirement. Desktop and standalone must not manage the service in the same HOME.')}</li><li>{t('Linux 安装不会自动启动服务;安装完成后由你显式启动并检查状态。', 'Linux installation never starts the service automatically; start it explicitly and verify status after installation.')}</li><li>{t('macOS 桌面应用当前要求 macOS 15.0 或更高版本,架构必须与设备匹配。', 'The current Desktop package requires macOS 15.0 or later and must match the device architecture.')}</li></ol><div class="self-signed-note"><strong>{t('关于 macOS 自签名版本', 'About self-signed macOS builds')}</strong><p>{t('短期发布没有 Apple Developer ID 签名和公证。macOS 首次阻止启动时,请在“系统设置 → 隐私与安全性”中确认“仍要打开”;不需要关闭 Gatekeeper 或 SIP。', 'Near-term releases do not have an Apple Developer ID signature or notarization. If macOS blocks the first launch, approve Open Anyway under System Settings → Privacy & Security. Do not disable Gatekeeper or SIP.')}</p><a class="text-link" href={en ? '/en/docs/install-macos/' : '/docs/install-macos/'}>{t('查看完整 macOS 步骤', 'Read the macOS installation steps')} →</a></div><a class="text-link" href={en ? '/en/changelog/' : '/changelog/'}>{t('查看更新日志', 'View changelog')} →</a></section>+ <section class="content-section wrap install-note"><h2>{t('安装边界', 'Installation boundaries')}</h2><ol><li>{t('Linux 无界面版按当前用户安装,不要求 root;桌面应用与独立服务版(standalone)不应在同一 HOME 中同时管理服务。', 'Linux headless is a per-user installation with no root requirement. Desktop and standalone must not manage the service in the same HOME.')}</li><li>{t('Linux 安装不会自动启动服务;安装完成后由你显式启动并检查状态。', 'Linux installation never starts the service automatically; start it explicitly and verify status after installation.')}</li><li>{t('macOS 桌面应用当前要求 macOS 15.0 或更高版本,架构必须与设备匹配。', 'The current Desktop package requires macOS 15.0 or later and must match the device architecture.')}</li></ol><div class="self-signed-note"><strong>{t('关于 macOS 自签名版本', 'About self-signed macOS builds')}</strong><p>{t('短期发布没有 Apple Developer ID 签名和公证。macOS 首次阻止启动时,请在“系统设置 → 隐私与安全性”中确认“仍要打开”;不需要关闭 Gatekeeper 或 SIP。', 'Near-term releases do not have an Apple Developer ID signature or notarization. If macOS blocks the first launch, approve Open Anyway under System Settings → Privacy & Security. Do not disable Gatekeeper or SIP.')}</p><a class="text-link" href={en ? '/en/docs/install-macos/' : '/docs/install-macos/'}>{t('查看完整 macOS 步骤', 'Read the macOS installation steps')} →</a></div><div class="self-signed-note"><strong>{t('关于 Windows 未签名版本', 'About unsigned Windows builds')}</strong><p>{t('Windows 桌面版按当前用户安装,只支持 x64。下载后先核对 SHA-256;遇到 SmartScreen 未知发布者提示时,按安装指南确认来源后继续。', 'Windows Desktop installs for the current user and supports x64. Verify SHA-256 before opening it; follow the installation guide for a SmartScreen unknown-publisher prompt.')}</p><a class="text-link" href={en ? '/en/docs/install-windows/' : '/docs/install-windows/'}>{t('查看 Windows 安装与恢复步骤', 'Read Windows installation and recovery steps')} →</a></div><a class="text-link" href={en ? '/en/changelog/' : '/changelog/'}>{t('查看更新日志', 'View changelog')} →</a></section></SiteLayout>diff --git a/apps/website/src/components/HomePage.astro b/apps/website/src/components/HomePage.astroindex 2f483c35..ff1a9766 100644--- a/apps/website/src/components/HomePage.astro+++ b/apps/website/src/components/HomePage.astro@@ -9,10 +9,11 @@ const path = en ? '/en/' : '/';const alternatePath = en ? '/' : '/en/';const featuredPost = posts[0];const release = latestRelease('stable');-const preferredArtifact = release?.artifacts.find(item => item.kind === 'desktop' && item.architecture === 'arm64')- ?? release?.artifacts.find(item => item.kind === 'desktop');-const linuxArtifact = release?.artifacts.find(item => item.kind === 'standalone');-const releaseKinds = [preferredArtifact && t('macOS 桌面应用', 'macOS Desktop'), linuxArtifact && t('Linux 无界面版', 'Linux headless')].filter(Boolean).join(' / ');+const preferredArtifact = release?.artifacts.find(item => item.kind === 'desktop' && item.platform === 'macOS' && item.architecture === 'arm64')+ ?? release?.artifacts.find(item => item.kind === 'desktop' && item.platform === 'macOS');+const windowsArtifact = release?.artifacts.find(item => item.kind === 'desktop' && item.platform === 'Windows');+const linuxArtifact = release?.artifacts.find(item => item.kind === 'standalone' && item.platform === 'Linux');+const releaseKinds = [preferredArtifact && t('macOS 桌面应用', 'macOS Desktop'), windowsArtifact && t('Windows 桌面应用', 'Windows Desktop'), linuxArtifact && t('Linux 无界面版', 'Linux headless')].filter(Boolean).join(' / ');---<SiteLayout language={language}title={t('HiRoute · 长程 Agent 智能路由引擎', 'HiRoute · Intelligent routing for long-horizon agents')}diff --git a/apps/website/src/components/ReleaseArtifact.astro b/apps/website/src/components/ReleaseArtifact.astronew file mode 100644index 00000000..f4bdf3ea--- /dev/null+++ b/apps/website/src/components/ReleaseArtifact.astro@@ -0,0 +1,17 @@+---+import { artifactManifestUrl, artifactUrl, formatBytes } from '../lib/releases.mjs';+const { release, artifact, language } = Astro.props;+const en = language === 'en';+const t = (zh, english) => en ? english : zh;+const windows = artifact.platform === 'Windows';+const desktop = artifact.kind === 'desktop';+const name = desktop ? windows ? t('Windows 桌面应用', 'Windows Desktop') : t('macOS 桌面应用', 'macOS Desktop')+ : windows ? t('Windows 无界面版', 'Windows headless') : t('Linux 无界面版', 'Linux headless');+---+<div class="artifact-row"><div><strong>{name} · {artifact.architecture}</strong>+ {desktop && !windows ? <span>{t(`最低 macOS ${artifact.minimum_os}`, `macOS ${artifact.minimum_os}+`)}</span> : <span>{desktop ? 'NSIS · x64 · current user' : artifact.target} · {formatBytes(artifact.size, language)}</span>}+ <span class:list={['distribution-badge', { 'self-signed': artifact.distribution === 'self-signed' }]}>{artifact.distribution === 'unsigned' ? t('未签名 · 请核对 SHA-256', 'Unsigned · verify SHA-256') : artifact.distribution === 'self-signed' ? t('自签名 · 首次启动需手动确认', 'Self-signed · manual approval on first launch') : t('Developer ID 签名与公证', 'Developer ID signed and notarized')}</span>+ <code>SHA256 {artifact.sha256}</code>+ {desktop && windows && <a class="companion-link" href={en ? '/en/docs/install-windows/' : '/docs/install-windows/'}>{t('SmartScreen 提示与安装步骤', 'SmartScreen prompt and installation steps')}</a>}+ {!desktop && <a class="companion-link" href={artifactManifestUrl(release, artifact)} download>{t('下载伴随清单', 'Download companion manifest')}</a>}+</div><a class:list={['button', { outline: !desktop }]} href={artifactUrl(release, artifact)}>{desktop ? windows ? t('下载 Windows 安装包', 'Download Windows installer') : t('下载 DMG', 'Download DMG') : t('手动下载归档', 'Manual archive')} · {formatBytes(artifact.size, language)}</a></div>diff --git a/apps/website/src/lib/install-script.mjs b/apps/website/src/lib/install-script.mjsindex 613cefa2..a2b9f471 100644--- a/apps/website/src/lib/install-script.mjs+++ b/apps/website/src/lib/install-script.mjs@@ -42,12 +42,13 @@ command -v python3 >/dev/null 2>&1 || { echo "Python 3 is required." >&2; exit 1temporary=$(mktemp -d "\${TMPDIR:-/tmp}/hiroute-install.XXXXXX")trap 'rm -rf "$temporary"' EXIT HUP INT TERMcurl -fsSL https://hiroute.ai/install/standalone.py -o "$temporary/standalone.py"-python3 "$temporary/standalone.py" install --manifest-url "$manifest_url"+python3 "$temporary/standalone.py" install --manifest-url "$manifest_url" "$@"printf '%s\n' \"HiRoute is installed for the current user. No service was started automatically." \"Ensure $HOME/.local/bin is on PATH, then run:" \" hiroute service start --output json" \- " hiroute system status --output json"+ " hiroute system status --output json" \+ "Configure the console during installation with --console-mode/--console-listen/--console-port, or run hiroute console init before starting the service."`;}diff --git a/apps/website/src/lib/releases.mjs b/apps/website/src/lib/releases.mjsindex 308ab585..586f4218 100644--- a/apps/website/src/lib/releases.mjs+++ b/apps/website/src/lib/releases.mjs@@ -1,6 +1,8 @@import manifest from '../../data/releases.json' with { type: 'json' };+import windowsDesktopCases from '../../../../scripts/windows-desktop-cases.json' with { type: 'json' };-export const RELEASE_SCHEMA = 'hiroute.website.releases/v2';+export const RELEASE_SCHEMA = 'hiroute.website.releases/v3';+export const LEGACY_RELEASE_SCHEMA = 'hiroute.website.releases/v2';export const DOWNLOAD_ORIGIN = 'https://hiroute.ai';const SHA256 = /^[0-9a-f]{64}$/;const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/;@@ -8,7 +10,6 @@ const REVISION = /^[0-9a-f]{40}$/;const FILENAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,239}$/;const STANDALONE_TARGETS = {Linux: { x86_64: 'x86_64-unknown-linux-gnu', aarch64: 'aarch64-unknown-linux-gnu' },- Windows: { x86_64: 'x86_64-pc-windows-msvc', aarch64: 'aarch64-pc-windows-msvc' },};function requiredText(value, field) {@@ -17,7 +18,7 @@ function requiredText(value, field) {export function validateReleaseManifest(value) {if (!value || typeof value !== 'object' || Array.isArray(value)- || value.schema !== RELEASE_SCHEMA || !Array.isArray(value.releases)+ || ![RELEASE_SCHEMA, LEGACY_RELEASE_SCHEMA].includes(value.schema) || !Array.isArray(value.releases) || value.releases.length > 64|| Object.keys(value).some(key => !['schema', 'releases'].includes(key))) {throw new Error('release manifest shape is invalid');}@@ -41,7 +42,7 @@ export function validateReleaseManifest(value) {for (const artifact of release.artifacts) {const commonValid = artifact && typeof artifact === 'object' && !Array.isArray(artifact)&& FILENAME.test(artifact.filename ?? '') && SHA256.test(artifact.sha256 ?? '')- && Number.isSafeInteger(artifact.size) && artifact.size > 0;+ && Number.isSafeInteger(artifact.size) && artifact.size > 0 && artifact.size <= 2 * 1024 ** 3;const desktopValid = commonValid && artifact.kind === 'desktop'&& !Object.keys(artifact).some(key => !['kind', 'platform', 'architecture', 'format', 'minimum_os', 'distribution', 'filename', 'sha256', 'size'].includes(key))&& artifact.platform === 'macOS' && ['arm64', 'x86_64'].includes(artifact.architecture)@@ -56,7 +57,10 @@ export function validateReleaseManifest(value) {&& artifact.manifest_filename === `${artifact.filename}.json`&& FILENAME.test(artifact.manifest_filename ?? '') && SHA256.test(artifact.manifest_sha256 ?? '')&& Number.isSafeInteger(artifact.manifest_size) && artifact.manifest_size > 0;- if (!desktopValid && !standaloneValid) {+ const windowsDesktopValid = commonValid && value.schema === RELEASE_SCHEMA && artifact.kind === 'desktop'+ && !Object.keys(artifact).some(key => !['kind', 'platform', 'architecture', 'format', 'distribution', 'filename', 'sha256', 'size'].includes(key))+ && artifact.platform === 'Windows' && artifact.architecture === 'x86_64' && artifact.format === 'nsis' && artifact.distribution === 'unsigned';+ if (!desktopValid && !windowsDesktopValid && !standaloneValid) {throw new Error(`invalid public artifact in ${release.version}`);}if (desktopValid) {@@ -64,6 +68,12 @@ export function validateReleaseManifest(value) {const expected = new RegExp(`^HiRoute-${release.version.replaceAll('.', '\\.')}-[0-9a-f]{12}-macos-${artifact.architecture}-${suffix}\\.dmg$`);if (!expected.test(artifact.filename)) throw new Error(`artifact filename does not match release: ${artifact.filename}`);}+ if (windowsDesktopValid) {+ const prefix = `HiRoute-${release.version}-`, suffix = '-windows-x86_64-setup.exe';+ const revision = artifact.filename.startsWith(prefix) && artifact.filename.endsWith(suffix)+ ? artifact.filename.slice(prefix.length, -suffix.length) : '';+ if (!/^[0-9a-f]{12}$/.test(revision)) throw new Error(`artifact filename does not match release: ${artifact.filename}`);+ }if (standaloneValid) {const expected = new RegExp(`^hiroute-${release.version.replaceAll('.', '\\.')}-[0-9a-f]{12}-${artifact.target}\\.tar\\.gz$`);if (!expected.test(artifact.filename)) throw new Error(`artifact filename does not match release: ${artifact.filename}`);@@ -79,6 +89,19 @@ export function validateReleaseManifest(value) {return value;}+export function projectReleaseManifest(value, schema = RELEASE_SCHEMA) {+ validateReleaseManifest(value);+ if (![RELEASE_SCHEMA, LEGACY_RELEASE_SCHEMA].includes(schema)) throw new Error('unsupported catalog projection');+ const projected = structuredClone(value); projected.schema = schema;+ if (schema === LEGACY_RELEASE_SCHEMA) {+ projected.releases = projected.releases.flatMap(release => {+ release.artifacts = release.artifacts.filter(artifact => artifact.platform !== 'Windows');+ return release.artifacts.length ? [release] : [];+ });+ }+ return validateReleaseManifest(projected);+}+export function artifactKey(release, artifact) {return `releases/${release.version}/${artifact.filename}`;}@@ -116,6 +139,20 @@ export function verifyDesktopIdentity(release, artifact, identity, expectedRevisif (artifact.kind !== 'desktop' || !REVISION.test(expectedRevision ?? '')) {throw new Error('desktop identity verification inputs are invalid');}+ if (artifact.platform === 'Windows') {+ const expected = { schema: 'hiroute.windows-desktop-package/v1', version: release.version, revision: expectedRevision,+ architecture: 'x86_64', distribution: 'unsigned', installer_sha256: artifact.sha256, integrity: 'green', embedded_components: 'green', native_runtime: 'green' };+ if (!identity || typeof identity !== 'object' || Object.entries(expected).some(([key, value]) => identity[key] !== value)+ || artifact.filename !== `HiRoute-${release.version}-${expectedRevision.slice(0, 12)}-windows-x86_64-setup.exe`) throw new Error('Windows Desktop identity or native acceptance differs from the release');+ const runs = identity.native_evidence?.runs;+ if (!Array.isArray(runs) || runs.length !== Object.keys(windowsDesktopCases).length+ || new Set(runs.map(run => run?.platform)).size !== runs.length+ || runs.some(run => !windowsDesktopCases[run?.platform] || run.revision !== expectedRevision+ || run.installer_sha256 !== artifact.sha256 || run.standard_user !== true || run.architecture !== 'AMD64' || !run.os_version+ || windowsDesktopCases[run.platform].some(id => run.scenarios?.[id] !== 'green')+ || Object.values(run.scenarios ?? {}).some(value => value !== 'green'))) throw new Error('Windows Desktop native acceptance is incomplete or belongs to another artifact');+ return identity;+ }const expectedDistribution = artifact.distribution === 'self-signed' ? 'controlled-trial' : 'developer-id';const expected = {version: release.version,diff --git a/apps/website/src/lib/user-guides.mjs b/apps/website/src/lib/user-guides.mjsindex 629224d2..a2c6d6fe 100644--- a/apps/website/src/lib/user-guides.mjs+++ b/apps/website/src/lib/user-guides.mjs@@ -10,6 +10,7 @@ export const guidePages = {quickstart: { zh: '快速开始', en: 'Quickstart' },'install-macos': { zh: 'macOS 安装与首次启动', en: 'Install and open HiRoute on macOS' },'install-linux': { zh: 'Linux 无界面版安装', en: 'Install HiRoute headless on Linux' },+ 'install-windows': { zh: 'Windows 桌面版安装', en: 'Install HiRoute Desktop on Windows' },'model-routing': { zh: '使用智能模型路由', en: 'Use smart model routing' },'task-routing': { zh: '使用智能任务路由', en: 'Use smart task routing' },cli: { zh: 'HiRoute CLI', en: 'HiRoute CLI' },diff --git a/apps/website/tests/install-script.test.mjs b/apps/website/tests/install-script.test.mjsindex 2742802a..bd3d8ed7 100644--- a/apps/website/tests/install-script.test.mjs+++ b/apps/website/tests/install-script.test.mjs@@ -38,7 +38,7 @@ test(`generated installer selects the ${machine} stable manifest without startinfs.writeFileSync(path.join(bin, 'uname'), `#!/bin/sh\n[ "\${1:-}" = "-s" ] && echo Linux || echo ${machine}\n`, { mode: 0o755 });fs.writeFileSync(path.join(bin, 'curl'), '#!/bin/sh\nprintf "curl %s\\n" "$*" >> "$INSTALL_TEST_LOG"\nwhile [ "$#" -gt 0 ]; do [ "$1" = "-o" ] && { shift; printf "# fixture\\n" > "$1"; exit 0; }; shift; done\nexit 1\n', { mode: 0o755 });fs.writeFileSync(path.join(bin, 'python3'), '#!/bin/sh\nprintf "python3 %s\\n" "$*" >> "$INSTALL_TEST_LOG"\n', { mode: 0o755 });- const result = spawnSync('/bin/sh', [], {+ const result = spawnSync('/bin/sh', ['-s', '--', '--console-mode', 'network', '--console-listen', '192.0.2.1', '--console-port', '8123', '--allow-plaintext-network'], {input: script, encoding: 'utf8', env: {...process.env, PATH: `${bin}:/usr/bin:/bin`, INSTALL_TEST_LOG: log, TMPDIR: root,},@@ -48,6 +48,7 @@ test(`generated installer selects the ${machine} stable manifest without startinassert.match(calls, /curl .*https:\/\/hiroute\.ai\/install\/standalone\.py/);assert.ok(calls.includes(`install --manifest-url https://hiroute.ai/releases/1.2.3/${expected.manifest_filename}`));assert.ok(script.includes(`https://hiroute.ai/releases/1.2.3/${armStandalone.manifest_filename}`));+ assert.match(calls, /--console-mode network --console-listen 192\.0\.2\.1 --console-port 8123 --allow-plaintext-network/);assert.doesNotMatch(calls, /service start/);assert.match(result.stdout, /No service was started automatically/);});diff --git a/apps/website/tests/releases.test.mjs b/apps/website/tests/releases.test.mjsindex 8baa15dd..a0890871 100644--- a/apps/website/tests/releases.test.mjs+++ b/apps/website/tests/releases.test.mjs@@ -8,6 +8,7 @@ import test from 'node:test';import {artifactAssets, artifactKey, artifactManifestUrl, artifactUrl, latestRelease, validateReleaseManifest,verifyDesktopIdentity,+ projectReleaseManifest, LEGACY_RELEASE_SCHEMA,} from '../src/lib/releases.mjs';const revision = 'a'.repeat(40);@@ -25,7 +26,24 @@ const manifest = { schema: 'hiroute.website.releases/v2', releases: [release] };test('Desktop update endpoint publishes the same validated website catalog', () => {const generated = JSON.parse(fs.readFileSync(new URL('../public/releases.json', import.meta.url), 'utf8'));const source = JSON.parse(fs.readFileSync(new URL('../data/releases.json', import.meta.url), 'utf8'));- assert.deepEqual(generated, validateReleaseManifest(source));+ assert.deepEqual(generated, projectReleaseManifest(source, LEGACY_RELEASE_SCHEMA));+ const current = JSON.parse(fs.readFileSync(new URL('../public/releases-v3.json', import.meta.url), 'utf8'));+ assert.deepEqual(current, projectReleaseManifest(source));+});++test('Windows Desktop uses V3 and can never enter the released macOS V2 projection', () => {+ const value = structuredClone(manifest); value.schema = 'hiroute.website.releases/v3';+ const windows = { kind: 'desktop', platform: 'Windows', architecture: 'x86_64', format: 'nsis', distribution: 'unsigned',+ filename: 'HiRoute-1.2.3-aaaaaaaaaaaa-windows-x86_64-setup.exe', sha256: 'c'.repeat(64), size: 512 };+ value.releases[0].artifacts.push(windows);+ assert.equal(validateReleaseManifest(value), value);+ assert.deepEqual(projectReleaseManifest(value, LEGACY_RELEASE_SCHEMA), manifest);+ for (const [field, entry] of [['architecture', 'aarch64'], ['format', 'exe'], ['distribution', 'self-signed'], ['minimum_os', 'any'], ['filename', '../setup.exe']]) {+ const invalid = structuredClone(value); invalid.releases[0].artifacts[1][field] = entry;+ assert.throws(() => validateReleaseManifest(invalid), field);+ }+ const onlyWindows = structuredClone(value); onlyWindows.releases[0].artifacts = [windows];+ assert.equal(projectReleaseManifest(onlyWindows, LEGACY_RELEASE_SCHEMA).releases.length, 0);});const standalone = {kind: 'standalone', platform: 'Linux', architecture: 'x86_64', target: 'x86_64-unknown-linux-gnu',@@ -105,14 +123,14 @@ test('standalone artifacts reject target, filename, and companion-manifest drift}});-test('Windows standalone targets retain architecture and immutable companion identity', () => {+test('Windows standalone packages are rejected for both architectures', () => {for (const architecture of ['x86_64', 'aarch64']) {const target = `${architecture}-pc-windows-msvc`;const candidate = { ...standalone, platform: 'Windows', architecture, target,filename: `hiroute-1.2.3-aaaaaaaaaaaa-${target}.tar.gz`,manifest_filename: `hiroute-1.2.3-aaaaaaaaaaaa-${target}.tar.gz.json` };const value = { ...structuredClone(manifest), releases: [{ ...structuredClone(release), artifacts: [candidate] }] };- assert.equal(validateReleaseManifest(value), value);+ assert.throws(() => validateReleaseManifest(value), /invalid public artifact/);for (const drift of [{ platform: 'Linux' }, { architecture: architecture === 'aarch64' ? 'x86_64' : 'aarch64' },{ target: `${architecture}-unknown-linux-gnu` }, { target: `${architecture}-pc-windows-gnu` },diff --git a/contracts/cli/console-launch-request.v1.schema.json b/contracts/cli/console-launch-request.v1.schema.jsonnew file mode 100644index 00000000..550e3f48--- /dev/null+++ b/contracts/cli/console-launch-request.v1.schema.json@@ -0,0 +1,12 @@+{+ "$id": "hiroute://contracts/cli/console-launch-request.v1.schema.json",+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "loopback_only": {+ "default": false,+ "type": "boolean"+ }+ },+ "type": "object"+}diff --git a/contracts/cli/console-token-create.v1.schema.json b/contracts/cli/console-token-create.v1.schema.jsonnew file mode 100644index 00000000..69337b78--- /dev/null+++ b/contracts/cli/console-token-create.v1.schema.json@@ -0,0 +1,24 @@+{+ "$id": "hiroute://contracts/cli/console-token-create.v1.schema.json",+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "expires_days": {+ "maximum": 3650,+ "minimum": 1,+ "type": [+ "integer",+ "null"+ ]+ },+ "name": {+ "maxLength": 80,+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "name"+ ],+ "type": "object"+}diff --git a/contracts/cli/console-token-revoke.v1.schema.json b/contracts/cli/console-token-revoke.v1.schema.jsonnew file mode 100644index 00000000..c45681b6--- /dev/null+++ b/contracts/cli/console-token-revoke.v1.schema.json@@ -0,0 +1,15 @@+{+ "$id": "hiroute://contracts/cli/console-token-revoke.v1.schema.json",+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "id": {+ "pattern": "^[a-f0-9]{64}$",+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "type": "object"+}diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex 8bf491b0..21bb7170 100644--- a/contracts/cli/contract-set.v1.json+++ b/contracts/cli/contract-set.v1.json@@ -1,5 +1,5 @@{- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","files": {"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb","agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",@@ -7,7 +7,10 @@"agent-scan-request.v1.schema.json": "sha256:2112519120417189cfea67dbc23bcbbeabd573073df6a167fa774a5a766c6653","compute-connection-options-request.v1.schema.json": "sha256:4bc609ffeac30f22dbccb34b907b778722fb45c44d7d8d501afb0b74bf8b58ba","compute-scan-request.union.schema.json": "sha256:0b3fa6c790441aab8dc5a2f8002490ffbd19530fc6e7fd251dead24565d31159",- "coverage-manifest.v1.json": "sha256:d0d6c484d6b5bac06b17e0ea12819a505cd57b130ac90f636dd8514d434126dd",+ "console-launch-request.v1.schema.json": "sha256:bb201709ef64e99036a97d5879a32a8e4e3a9517010e1041def223e723e7f385",+ "console-token-create.v1.schema.json": "sha256:10cc9b80ed0bec4a5ca80e098cf0ee94710eedd7dfce292cf4a8770a11be78ec",+ "console-token-revoke.v1.schema.json": "sha256:fbec29753f6effd3c854bff57984b3c3932ac5b6f2345e52151e353c15933b36",+ "coverage-manifest.v1.json": "sha256:6d204a160f66b2906b485e29ce2ba45f4bef1d3731c1de75a71d1fdf5ca50078","delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878","delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93","delegation-get-request.v1.schema.json": "sha256:85b29839c1c508018ebe40e4b2bb5c1dce7c3a87c27efa30b196b2d1b6658471",@@ -19,14 +22,14 @@"local-control-hello.v2.schema.json": "sha256:32fbce882152a886b79bd139d3b4e459b48d94e0634e56ccb189b2c9971ad772","local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c","machine-envelope.v2.schema.json": "sha256:23e019a3d024ae302a44105caff4ec95d3fb409a29f936dea1360e543ae6abd6",- "manifest.v1.json": "sha256:3695d96499e34d7cc484357caccd219d3e895d90c34c019652f9680a2fe5e8eb",+ "manifest.v1.json": "sha256:c30c072a03a479564565f4a997636d388bb773d2ea15aa209fe011fa68fd82db","operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f","operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850","plan-content-change.v2.schema.json": "sha256:3c5ba659a8705e5355653d7fdd9584080f551396f65bc355349c53e38d1352bd","plan-draft-change.v1.schema.json": "sha256:b59d054c4e4d9f23803e269b5e97ce09cc44f46deeccaf6189fa182a8903b478","plan-editor.v2.schema.json": "sha256:bb1cd2184286958753b1d115c03396e5cdadaa0d31253a5a8eb0d6996bfeb654","plan-lifecycle-change.v1.schema.json": "sha256:4b82ce14414cd1d8f8765cfabd535bf5de24ef559b4ae8728ad365fe37a186a9",- "planned-manifest.v1.json": "sha256:27166c3ec3c7a8434b01b704ccb297831da5d027f001029e8d8ce922789ecd2c",+ "planned-manifest.v1.json": "sha256:ef83b8166de3c9c9c5d2c178de28cd39aa313ae1dff4303b0c470d81da431b03","prepare-discovered-model-connection-request.v1.schema.json": "sha256:4451d8d7d06160f399d683bc3987ac2bd458af09994e4e0d989687667f6af1bd","publication-checkpoint-change.v1.schema.json": "sha256:6b4c58af4a4610abe76a79b23b2febe06bea2a8fa2aeb008653d22e1cff485d9","session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44",diff --git a/contracts/cli/coverage-manifest.v1.json b/contracts/cli/coverage-manifest.v1.jsonindex 28f360a8..818b8abf 100644--- a/contracts/cli/coverage-manifest.v1.json+++ b/contracts/cli/coverage-manifest.v1.json@@ -1,5 +1,61 @@{"commands": [+ {+ "command_id": "console.open",+ "lifecycle": "released",+ "negative": {+ "polarity": "negative",+ "scenario_id": "p0.console.open.negative",+ "state": "executable"+ },+ "positive": {+ "polarity": "positive",+ "scenario_id": "p0.console.open.positive",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.create",+ "lifecycle": "released",+ "negative": {+ "polarity": "negative",+ "scenario_id": "p0.console.token.create.negative",+ "state": "executable"+ },+ "positive": {+ "polarity": "positive",+ "scenario_id": "p0.console.token.create.positive",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.list",+ "lifecycle": "released",+ "negative": {+ "polarity": "negative",+ "scenario_id": "p0.console.token.list.negative",+ "state": "executable"+ },+ "positive": {+ "polarity": "positive",+ "scenario_id": "p0.console.token.list.positive",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.revoke",+ "lifecycle": "released",+ "negative": {+ "polarity": "negative",+ "scenario_id": "p0.console.token.revoke.negative",+ "state": "executable"+ },+ "positive": {+ "polarity": "positive",+ "scenario_id": "p0.console.token.revoke.positive",+ "state": "executable"+ }+ },{"command_id": "schema.list","lifecycle": "released",@@ -1233,7 +1289,7 @@}}],- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","schema_version": {"major": 1,"minor": 0diff --git a/contracts/cli/manifest.v1.json b/contracts/cli/manifest.v1.jsonindex 0a7ab78e..2cd198b0 100644--- a/contracts/cli/manifest.v1.json+++ b/contracts/cli/manifest.v1.json@@ -5,9 +5,192 @@},"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009","proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","visibility": "release","commands": [+ {+ "command_id": "console.open",+ "path": [+ "console",+ "open"+ ],+ "operation_id": "CreateConsoleLaunch",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-launch-request/v1",+ "response_schema": "hiroute.console-launch/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Create a single-use owner console launch link.",+ "usage": "hiroute console open [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console open --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.open"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.open.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.open.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.create",+ "path": [+ "console",+ "token",+ "create"+ ],+ "operation_id": "CreateConsoleToken",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-token-create/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Create a named owner console access token, shown once.",+ "usage": "hiroute console token create [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token create --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.create"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.create.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.create.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.list",+ "path": [+ "console",+ "token",+ "list"+ ],+ "operation_id": "ListConsoleTokens",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "query",+ "request_schema": "hiroute.empty-request/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "none",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "List console token metadata without credential secrets.",+ "usage": "hiroute console token list [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Read-only; no product side effect.",+ "network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token list --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.list"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.list.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.list.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.revoke",+ "path": [+ "console",+ "token",+ "revoke"+ ],+ "operation_id": "RevokeConsoleToken",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-token-revoke/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Revoke a console access token and its sessions.",+ "usage": "hiroute console token revoke [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token revoke --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.revoke"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.revoke.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.revoke.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },{"command_id": "schema.list","path": [diff --git a/contracts/cli/planned-manifest.v1.json b/contracts/cli/planned-manifest.v1.jsonindex 89cdddd5..115402a1 100644--- a/contracts/cli/planned-manifest.v1.json+++ b/contracts/cli/planned-manifest.v1.json@@ -5,9 +5,192 @@},"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009","proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","visibility": "planned","commands": [+ {+ "command_id": "console.open",+ "path": [+ "console",+ "open"+ ],+ "operation_id": "CreateConsoleLaunch",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-launch-request/v1",+ "response_schema": "hiroute.console-launch/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Create a single-use owner console launch link.",+ "usage": "hiroute console open [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console open --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.open"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.open.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.open.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.create",+ "path": [+ "console",+ "token",+ "create"+ ],+ "operation_id": "CreateConsoleToken",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-token-create/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Create a named owner console access token, shown once.",+ "usage": "hiroute console token create [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token create --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.create"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.create.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.create.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.list",+ "path": [+ "console",+ "token",+ "list"+ ],+ "operation_id": "ListConsoleTokens",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "query",+ "request_schema": "hiroute.empty-request/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "none",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "List console token metadata without credential secrets.",+ "usage": "hiroute console token list [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Read-only; no product side effect.",+ "network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token list --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.list"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.list.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.list.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },+ {+ "command_id": "console.token.revoke",+ "path": [+ "console",+ "token",+ "revoke"+ ],+ "operation_id": "RevokeConsoleToken",+ "trace_ids": [],+ "scope": "p0",+ "lifecycle": "released",+ "kind": "action",+ "request_schema": "hiroute.console-token-revoke/v1",+ "response_schema": "hiroute.console-token-result/v1",+ "effect": "typed_action",+ "network": "local_control_only",+ "model_call": "never",+ "stdin_channels": [],+ "idempotency": "not_applicable",+ "help": {+ "purpose": "Revoke a console access token and its sessions.",+ "usage": "hiroute console token revoke [typed options] --non-interactive --output json",+ "arguments_and_options": "Only the typed options declared by the generated request schema are accepted; arbitrary patches, URLs, shell, or plaintext Secret argv are forbidden.",+ "effects": "Application-owned typed operation; side effects are recorded by the Operation and external ledgers.",+ "network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",+ "automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",+ "output": "One hiroute.machine-envelope/v2 JSON object on stdout; diagnostics belong on stderr.",+ "exit_status": "0 success/accepted; 2 usage; 3 conflict/blocker; 4 capability denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention.",+ "examples": [+ "hiroute console token revoke --non-interactive --output json"+ ],+ "see_also": [+ "hiroute schema show --command-id console.token.revoke"+ ]+ },+ "positive": {+ "scenario_id": "p0.console.token.revoke.positive",+ "polarity": "positive",+ "state": "executable"+ },+ "negative": {+ "scenario_id": "p0.console.token.revoke.negative",+ "polarity": "negative",+ "state": "executable"+ }+ },{"command_id": "schema.list","path": [diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex 228d70c0..69d32f2b 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -140,6 +140,13 @@"hiroute.connector-profile/v1","hiroute.connector-registry/v1","hiroute.connector-runtime-fallback/v1",+ "hiroute.console-launch-request/v1",+ "hiroute.console-launch/v1",+ "hiroute.console-listener/v1",+ "hiroute.console-token-create/v1",+ "hiroute.console-token-result/v1",+ "hiroute.console-token-revoke/v1",+ "hiroute.console-tokens/v1","hiroute.control-compensation/v1","hiroute.control-desired/v1","hiroute.cpa-account-attestation/v1",@@ -379,6 +386,7 @@"hiroute.sqlite-logical-state/v1","hiroute.stable-route/v1","hiroute.standalone-install/v1",+ "hiroute.standalone-package/v1","hiroute.standalone-protected-input-request/v1","hiroute.standalone-protected-input-response/v1","hiroute.standalone-proxy-environment/v1",@@ -400,17 +408,29 @@"hiroute.value-view/v1","hiroute.web-confirmation/v1","hiroute.website.releases/v2",+ "hiroute.website.releases/v3","hiroute.windows-artifact-fingerprint/v1","hiroute.windows-background-install/v1","hiroute.windows-background/v1","hiroute.windows-install-journal/v1","hiroute.windows-install-layout/v1",+ "hiroute.windows-install-request/v1",+ "hiroute.windows-install-result/v1","hiroute.windows-lifecycle/v1",+ "hiroute.windows-maintenance-error/v1","hiroute.windows-managed-artifact-marker/v5","hiroute.windows-owner-finalize-request/v1","hiroute.windows-owner-finalize-result/v1","hiroute.windows-scm-owner-request/v1","hiroute.windows-scm-owner-result/v1",+ "hiroute.windows-shell-install/v1",+ "hiroute.windows-shell-package/v1",+ "hiroute.windows-shell-transaction/v1",+ "hiroute.windows-shell-update-commit/v1",+ "hiroute.windows-shell-update-job/v1",+ "hiroute.windows-shell-update-outcome/v1",+ "hiroute.windows-uninstall-request/v1",+ "hiroute.windows-uninstall-result/v1","hiroute.work-plan-list-request/v1","hiroute.work-plan-list/v1","hiroute.worker-cancel-request/v1",@@ -946,6 +966,7 @@{"subject": "desktop_update","audited_prefixes": [+ "hiroute.windows-desktop-package","hiroute.website.releases","hiroute.desktop-upgrade-handoff","hiroute.upgrade-recovery-package",@@ -955,13 +976,39 @@"hiroute.upgrade-installer-decision"],"current_contracts": [- "hiroute.website.releases/v2",+ "hiroute.windows-desktop-package/v1",+ "hiroute.website.releases/v3","hiroute.desktop-upgrade-handoff/v1","hiroute.upgrade-installer-started/v1","hiroute.daemon-upgrade-progress/v1","hiroute.upgrade-installer-decision/v1"],- "legacy_support": []+ "legacy_support": [+ {+ "contract": "hiroute.website.releases/v2",+ "mode": "projection",+ "owner": "website-release-catalog",+ "reason": "Both the current macOS Desktop and supported released macOS Desktop versions read releases.json and strictly reject non-macOS desktop and non-Linux standalone artifacts. The single current V3 catalog emits their restricted V2 projection; this remains the current macOS update feed as well as a compatibility projection. Windows consumers use V3 and accept only x64 NSIS Desktop artifacts. No Windows release predates this change; internal standalone/ARM64 payloads and Python journal production have no legacy-support entry.",+ "removal_condition": "Remove only after the current macOS Desktop reads V3 and no supported released Desktop still reads the V2 feed; retire the frozen v0.3.1 reader regression together with that projection.",+ "allowed_paths": [+ "apps/website/src/lib/releases.mjs",+ "apps/website/scripts/prepare-content.mjs",+ "apps/website/tests/releases.test.mjs",+ "crates/host-runtime/src/releases.rs",+ "crates/host-runtime/src/releases_v3.rs",+ "crates/host-runtime/tests/release_catalog_compatibility.rs",+ "crates/host-runtime/tests/fixtures/website_releases_v2_031.rs",+ "crates/host-runtime/tests/fixtures/website-releases-v2-reader.md",+ "apps/website/README.md",+ "apps/website/tests/install-script.test.mjs",+ "apps/website/tests/oss-publication.test.mjs",+ "scripts/test-build-release.py",+ "scripts/test-release-contract-pr.py",+ "scripts/test-release-contracts.py",+ "scripts/release-contracts.py"+ ]+ }+ ]},{"subject": "pi_native_provider_restore",diff --git a/crates/application-api/src/commands.rs b/crates/application-api/src/commands.rsindex cb153739..f16aeda1 100644--- a/crates/application-api/src/commands.rs+++ b/crates/application-api/src/commands.rs@@ -219,6 +219,42 @@ macro_rules! command {// Only commands with executable positive and negative scenarios may be marked Released and// projected into manifest.v1.json.const COMMANDS: &[StaticCommandDescriptor] = &[+ command!(+ "console.open",+ ["console", "open"],+ "CreateConsoleLaunch",+ [],+ Released,+ Action,+ "Create a single-use owner console launch link."+ ),+ command!(+ "console.token.create",+ ["console", "token", "create"],+ "CreateConsoleToken",+ [],+ Released,+ Action,+ "Create a named owner console access token, shown once."+ ),+ command!(+ "console.token.list",+ ["console", "token", "list"],+ "ListConsoleTokens",+ [],+ Released,+ Query,+ "List console token metadata without credential secrets."+ ),+ command!(+ "console.token.revoke",+ ["console", "token", "revoke"],+ "RevokeConsoleToken",+ [],+ Released,+ Action,+ "Revoke a console access token and its sessions."+ ),command!("schema.list",["schema", "list"],diff --git a/crates/application-api/src/console.rs b/crates/application-api/src/console.rsnew file mode 100644index 00000000..6f5f3132--- /dev/null+++ b/crates/application-api/src/console.rs@@ -0,0 +1,29 @@+//! Owner credential operations. Credential exchanges never traverse Local Control.+use serde::{Deserialize, Serialize};+#[derive(Default, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleLaunchRequestV1 {+ #[serde(default)]+ pub loopback_only: bool,+}+#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleListTokensRequestV1 {}+#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleCreateTokenRequestV1 {+ pub name: String,+ #[serde(default)]+ pub expires_days: Option<u32>,+}+#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleRevokeTokenRequestV1 {+ pub id: String,+}+#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleLaunchV1 {+ pub url: String,+ pub expires_in: u32,+}diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rsindex cdbae8fa..20f55b6e 100644--- a/crates/application-api/src/generated.rs+++ b/crates/application-api/src/generated.rs@@ -376,6 +376,24 @@ fn value_query_schema() -> Value {pub fn generated_contract_files() -> Vec<GeneratedContractFile> {let mut files = BTreeMap::from([+ (+ "console-launch-request.v1.schema.json",+ pretty_json(+ &json!({"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"hiroute://contracts/cli/console-launch-request.v1.schema.json","type":"object","additionalProperties":false,"properties":{"loopback_only":{"type":"boolean","default":false}}}),+ ),+ ),+ (+ "console-token-create.v1.schema.json",+ pretty_json(+ &json!({"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"hiroute://contracts/cli/console-token-create.v1.schema.json","type":"object","additionalProperties":false,"required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":80},"expires_days":{"type":["integer","null"],"minimum":1,"maximum":3650}}}),+ ),+ ),+ (+ "console-token-revoke.v1.schema.json",+ pretty_json(+ &json!({"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"hiroute://contracts/cli/console-token-revoke.v1.schema.json","type":"object","additionalProperties":false,"required":["id"],"properties":{"id":{"type":"string","pattern":"^[a-f0-9]{64}$"}}}),+ ),+ ),("subscription-login-request.v1.schema.json",pretty_json(&subscription_login::request()),@@ -590,6 +608,9 @@ mod tests {"agent-scan-request.v1.schema.json","compute-connection-options-request.v1.schema.json","compute-scan-request.union.schema.json",+ "console-launch-request.v1.schema.json",+ "console-token-create.v1.schema.json",+ "console-token-revoke.v1.schema.json","contract-set.v1.json","coverage-manifest.v1.json","delegation-cancel-request.v1.schema.json",diff --git a/crates/application-api/src/lib.rs b/crates/application-api/src/lib.rsindex 8de75c19..eb22be6b 100644--- a/crates/application-api/src/lib.rs+++ b/crates/application-api/src/lib.rs@@ -264,14 +264,14 @@ mod protocol_tests {#[test]fn p0_registry_and_staging_invariants_remain_closed() {let commands = planned_commands();- assert_eq!(commands.len(), 88);+ assert_eq!(commands.len(), 92);assert_eq!(commands.iter().map(|command| &command.command_id).collect::<BTreeSet<_>>().len(),- 88+ commands.len());assert_eq!(commands@@ -279,7 +279,7 @@ mod protocol_tests {.map(|command| &command.path).collect::<BTreeSet<_>>().len(),- 88+ commands.len());assert_eq!(commands@@ -287,7 +287,7 @@ mod protocol_tests {.map(|command| &command.operation_id).collect::<BTreeSet<_>>().len(),- 88+ commands.len());for operation in ["GetClientServiceStatus", "ListWorkPlans"] {let command = command_by_operation(operation).unwrap();@@ -312,7 +312,7 @@ mod protocol_tests {CommandLifecycle::Released);let release = release_manifest();- assert_eq!(release.commands.len(), 55);+ assert_eq!(release.commands.len(), 59);assert!(release.commands.iter().all(|command| {command.lifecycle == CommandLifecycle::Released&& command.positive.state == CoverageState::Executable@@ -350,3 +350,6 @@ mod protocol_tests {mod plan_authoring;pub use plan_authoring::*;++mod console;+pub use console::*;diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rsindex f8370f36..e7d859f6 100644--- a/crates/application-api/src/protocol.rs+++ b/crates/application-api/src/protocol.rs@@ -826,6 +826,9 @@ pub struct MachineNextActionV1 {pub(crate) fn command_request_schema(command_id: &str) -> &'static str {match command_id {+ "console.open" => "hiroute.console-launch-request/v1",+ "console.token.create" => "hiroute.console-token-create/v1",+ "console.token.revoke" => "hiroute.console-token-revoke/v1","worker.plans" => "hiroute.worker-plans-request/v1","worker.dependencies.discover" => "hiroute.worker-dependencies-discover-request/v1","worker.dependencies.select" => "hiroute.worker-dependencies-select-request/v1",@@ -889,6 +892,10 @@ pub(crate) fn command_request_schema(command_id: &str) -> &'static str {pub(crate) fn command_response_schema(command_id: &str) -> &'static str {match command_id {+ "console.open" => "hiroute.console-launch/v1",+ "console.token.create" | "console.token.list" | "console.token.revoke" => {+ "hiroute.console-token-result/v1"+ }"worker.executors" => "hiroute.worker-executor-availability-list/v1","worker.plans" => "hiroute.work-plan-list/v1","worker.dependencies.discover" | "worker.dependencies.select" => {diff --git a/crates/cli/src/host_commands.rs b/crates/cli/src/host_commands.rsindex 2791fe07..636d2511 100644--- a/crates/cli/src/host_commands.rs+++ b/crates/cli/src/host_commands.rs@@ -15,8 +15,13 @@ use serde_json::json;use crate::args::{Globals, OutputMode};use crate::{CliExecution, LocalControlClient, failure, service, success};+mod console;+pub(crate) fn execute(arguments: &[String], globals: &Globals) -> Option<CliExecution> {let family = arguments.first()?.as_str();+ if family == "console" {+ return Some(console::execute(&arguments[1..], globals));+ }if !matches!(family,"service" | "gateway" | "protected-input" | "subscription-proxy"@@ -50,7 +55,7 @@ pub(crate) fn execute(arguments: &[String], globals: &Globals) -> Option<CliExecfn host_help(family: &str) -> &'static str {match family {"service" => {- "Usage\n hiroute service start|stop|restart|status|logs|doctor --output json\n hiroute service autostart enable|disable|status --output json\n hiroute service run\n Windows package maintenance:\n hiroute service install --manager task --output json\n hiroute service install --manager scm --password-stdin --output json\n hiroute service uninstall --output json\n hiroute service layout --output json\n hiroute service publish-install --request-stdin --output json\n hiroute service write-record --path <PATH> --request-stdin --output json\n"+ "Usage\n hiroute service start|stop|restart|status|logs|doctor --output json\n hiroute service autostart enable|disable|status --output json\n hiroute service run\n hiroute service layout --output json\n"}"gateway" => {"Usage\n hiroute gateway show --output json\n hiroute gateway set --address <IPV4> --port auto|<PORT> [--accept-remote-risk] --output json\n hiroute gateway recover --output json\n"@@ -74,6 +79,16 @@ fn service_command(arguments: &[String],globals: &Globals,) -> Result<serde_json::Value, ErrorCode> {+ // Only the private Rust transaction is an installation entry. The dormant+ // manager adapters remain in the service module for low-level SCM tests.+ if arguments.first().is_some_and(|verb| {+ matches!(+ verb.as_str(),+ "install" | "uninstall" | "prepare-install" | "publish-install" | "write-record"+ )+ }) {+ return Err(ErrorCode::InvalidArguments);+ }let timeout = globals.timeout.unwrap_or(Duration::from_secs(30));let status = match arguments {[verb] if verb == "start" => json_value(service::start(timeout).map_err(map)?)?,@@ -83,7 +98,6 @@ fn service_command([verb] if verb == "logs" => service::logs().map_err(map)?,[verb] if verb == "doctor" => service::doctor(),[verb] if verb == "layout" => service::windows_layout().map_err(map)?,- [verb] if verb == "prepare-install" => service::prepare_windows_install().map_err(map)?,[verb, manager_flag, manager, daemon_flag, daemon]if verb == "describe-install"&& manager_flag == "--manager"@@ -91,26 +105,6 @@ fn service_command({service::describe_windows_manager(manager, std::path::Path::new(daemon)).map_err(map)?}- [verb, source] if verb == "publish-install" && source == "--request-stdin" => {- service::publish_install_record().map_err(map)?- }- [verb, path_flag, path, source]- if verb == "write-record" && path_flag == "--path" && source == "--request-stdin" =>- {- service::write_private_record(std::path::Path::new(path)).map_err(map)?- }- [verb, flag, manager] if verb == "install" && flag == "--manager" && manager == "task" => {- service::install_manager(manager, false).map_err(map)?- }- [verb, flag, manager, password]- if verb == "install"- && flag == "--manager"- && manager == "scm"- && password == "--password-stdin" =>- {- service::install_manager(manager, true).map_err(map)?- }- [verb] if verb == "uninstall" => service::uninstall_manager(timeout).map_err(map)?,[autostart, verb] if autostart == "autostart" && verb == "enable" => {json_value(service::set_autostart(true).map_err(map)?)?}@@ -552,6 +546,25 @@ mod tests {);}+ #[test]+ fn windows_installation_has_no_public_manager_or_record_write_entry() {+ assert!(!host_help("service").contains("--manager"));+ for words in [+ vec!["install", "--manager", "scm", "--password-stdin"],+ vec!["install", "--manager", "task"],+ vec!["uninstall"],+ vec!["publish-install", "--request-stdin"],+ vec!["prepare-install"],+ vec!["write-record", "--path", "foreign", "--request-stdin"],+ ] {+ let args = words.into_iter().map(String::from).collect::<Vec<_>>();+ assert!(matches!(+ service_command(&args, &Globals::default()),+ Err(ErrorCode::InvalidArguments)+ ));+ }+ }+#[test]fn host_command_help_is_available_without_starting_a_service() {for family in [diff --git a/crates/cli/src/host_commands/console.rs b/crates/cli/src/host_commands/console.rsnew file mode 100644index 00000000..fd59302c--- /dev/null+++ b/crates/cli/src/host_commands/console.rs@@ -0,0 +1,189 @@+use super::*;+use hiroute_host_runtime::{ConsoleListenerDesiredV1, ConsoleListenerStore};+mod configuration;++pub(super) fn execute(arguments: &[String], globals: &Globals) -> CliExecution {+ if globals.help {+ return CliExecution{exit_code:0,stdout:"Usage\n hiroute console open [--browser] [--loopback-only]\n hiroute console init [--mode off|loopback|network] [--listen IP] [--port N] [--advertise-address IP] [--allow-plaintext-network]\n hiroute console status\n hiroute console enable [--listen IP] [--port N] [--advertise-address IP] [--allow-plaintext-network]\n hiroute console disable\n hiroute console token create --name NAME [--expires DAYS]\n hiroute console token list\n hiroute console token revoke ID\nAccess tokens are owner credentials. Network HTTP is unencrypted. Configuration takes effect on the next service start; open only mints a one-use URL for the actual listener and never starts listening.\n".into(),stderr:String::new()};+ }+ if globals.agent.is_some() || globals.has_capability() {+ return failure(ErrorCode::CapabilityDenied, globals.request_id.clone());+ }+ let result = command(arguments, globals);+ match result {+ Ok(value) if globals.output == OutputMode::Text => CliExecution {+ exit_code: 0,+ stdout: value+ .get("url")+ .and_then(|v| v.as_str())+ .map(|v| format!("{v}\n"))+ .unwrap_or_else(|| {+ format!(+ "{}\n",+ serde_json::to_string_pretty(&value).unwrap_or_default()+ )+ }),+ stderr: String::new(),+ },+ Ok(value) => success(value, globals.request_id.clone()),+ Err(code) => {+ let mut result = failure(code, globals.request_id.clone());+ if code == ErrorCode::ActionRequired {+ result.stderr = "The console must be configured and listening. Run `hiroute console status`, configure it with `hiroute console init`, then start/restart the service. Network configuration requires `--allow-plaintext-network`; wildcard binds also require `--advertise-address IP`. `console open` never starts a listener.\n".into();+ }+ result+ }+ }+}+fn call(+ operation: &str,+ payload: serde_json::Value,+ globals: &Globals,+) -> Result<serde_json::Value, ErrorCode> {+ let envelope = LocalControlClient::cli_from_environment()+ .map_err(|_| ErrorCode::DaemonUnavailable)?+ .with_timeout(globals.timeout.unwrap_or(Duration::from_secs(30)))+ .call(LocalControlWireRequestV2 {+ schema_version: LOCAL_CONTROL_SCHEMA_V2,+ request_id: globals+ .request_id+ .clone()+ .unwrap_or_else(|| "console-owner".into()),+ operation_id: operation.into(),+ payload,+ protected_grant: None,+ })+ .map_err(|_| ErrorCode::DaemonUnavailable)?;+ if let Some(error) = envelope.error {+ return Err(error.code);+ }+ envelope.data.ok_or(ErrorCode::DaemonUnavailable)+}+fn command(args: &[String], globals: &Globals) -> Result<serde_json::Value, ErrorCode> {+ match args {+ [open, rest @ ..] if open == "open" => {+ let (open_browser, loopback_only) = configuration::open_options(rest)?;+ let value = call(+ "CreateConsoleLaunch",+ json!({"loopback_only":loopback_only}),+ globals,+ )?;+ if open_browser {+ browser(+ value+ .get("url")+ .and_then(|v| v.as_str())+ .ok_or(ErrorCode::DaemonUnavailable)?,+ )?;+ }+ Ok(value)+ }+ [token, list] if token == "token" && list == "list" => {+ call("ListConsoleTokens", json!({}), globals)+ }+ [token, revoke, id] if token == "token" && revoke == "revoke" => {+ call("RevokeConsoleToken", json!({"id":id}), globals)+ }+ [token, create, options @ ..] if token == "token" && create == "create" => {+ let mut name = None;+ let mut days = None;+ let mut it = options.iter();+ while let Some(flag) = it.next() {+ match flag.as_str() {+ "--name" if name.is_none() => name = it.next().cloned(),+ "--expires" if days.is_none() => {+ days = Some(+ it.next()+ .ok_or(ErrorCode::InvalidArguments)?+ .parse::<u32>()+ .map_err(|_| ErrorCode::InvalidArguments)?,+ )+ }+ _ => return Err(ErrorCode::InvalidArguments),+ }+ }+ call(+ "CreateConsoleToken",+ json!({"name":name.ok_or(ErrorCode::InvalidArguments)?,"expires_days":days}),+ globals,+ )+ }+ [status] if status == "status" => {+ serde_json::to_value(store()?.read().map_err(|_| ErrorCode::DaemonUnavailable)?)+ .map_err(|_| ErrorCode::Internal)+ }+ [disable] if disable == "disable" => serde_json::to_value(+ store()?+ .configure(ConsoleListenerDesiredV1::default())+ .map_err(|_| ErrorCode::DaemonUnavailable)?,+ )+ .map_err(|_| ErrorCode::Internal),+ [setup, options @ ..] if setup == "enable" || setup == "init" => {+ let desired = configuration::parse(options, setup == "init")?;+ serde_json::to_value(+ store()?+ .configure(desired)+ .map_err(|_| ErrorCode::DaemonUnavailable)?,+ )+ .map_err(|_| ErrorCode::Internal)+ }+ _ => Err(ErrorCode::InvalidArguments),+ }+}+fn store() -> Result<ConsoleListenerStore, ErrorCode> {+ let layout = StandaloneLayout::from_environment().map_err(|_| ErrorCode::DaemonUnavailable)?;+ Ok(ConsoleListenerStore::new(layout.gateway_config_root()))+}+fn browser(url: &str) -> Result<(), ErrorCode> {+ let mut command = {+ #[cfg(target_os = "macos")]+ {+ std::process::Command::new("open")+ }+ #[cfg(windows)]+ {+ std::process::Command::new("explorer.exe")+ }+ #[cfg(not(any(target_os = "macos", windows)))]+ {+ std::process::Command::new("xdg-open")+ }+ };+ command+ .arg(url)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .map(|_| ())+ .map_err(|_| ErrorCode::ActionRequired)+}+#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn collaboration_never_mints_or_changes_console_credentials() {+ for capability in [false, true] {+ let globals = Globals {+ agent: Some("test".into()),+ capability_fd: capability.then_some(4),+ ..Default::default()+ };+ for args in [+ vec!["open"],+ vec!["token", "create", "--name", "test"],+ vec!["enable"],+ ] {+ let result = execute(+ &args.into_iter().map(str::to_owned).collect::<Vec<_>>(),+ &globals,+ );+ assert!(+ result.stdout.contains("CAPABILITY_DENIED"),+ "{}",+ result.stdout+ );+ }+ }+ }+}diff --git a/crates/cli/src/host_commands/console/configuration.rs b/crates/cli/src/host_commands/console/configuration.rsnew file mode 100644index 00000000..4eaff9ec--- /dev/null+++ b/crates/cli/src/host_commands/console/configuration.rs@@ -0,0 +1,140 @@+use hiroute_application_api::ErrorCode;+use hiroute_host_runtime::{ConsoleListenerDesiredV1, ConsoleListenerMode, ConsolePortMode};+use std::net::IpAddr;++pub(super) fn open_options(options: &[String]) -> Result<(bool, bool), ErrorCode> {+ let (mut browser, mut local) = (false, false);+ for flag in options {+ match flag.as_str() {+ "--browser" if !browser => browser = true,+ "--loopback-only" if !local => local = true,+ _ => return Err(ErrorCode::InvalidArguments),+ }+ }+ Ok((browser, local))+}++pub(super) fn parse(+ options: &[String],+ initialization: bool,+) -> Result<ConsoleListenerDesiredV1, ErrorCode> {+ let mut desired = ConsoleListenerDesiredV1::loopback();+ let mut mode = None;+ let mut address = None;+ let mut it = options.iter();+ while let Some(flag) = it.next() {+ match flag.as_str() {+ "--mode" if initialization && mode.is_none() => {+ mode = Some(match it.next().map(String::as_str) {+ Some("off") => ConsoleListenerMode::Off,+ Some("loopback") => ConsoleListenerMode::Loopback,+ Some("network") => ConsoleListenerMode::Network,+ _ => return Err(ErrorCode::InvalidArguments),+ });+ }+ "--listen" if address.is_none() => address = Some(ip(it.next())?),+ "--advertise-address" if desired.advertise_address.is_none() => {+ desired.advertise_address = Some(ip(it.next())?);+ }+ "--port" if desired.port.is_none() => {+ desired.port_mode = ConsolePortMode::Explicit;+ desired.port = Some(+ it.next()+ .ok_or(ErrorCode::InvalidArguments)?+ .parse()+ .map_err(|_| ErrorCode::InvalidArguments)?,+ );+ }+ "--allow-plaintext-network" if !desired.allow_plaintext_network => {+ desired.allow_plaintext_network = true+ }+ _ => return Err(ErrorCode::InvalidArguments),+ }+ }+ desired.mode = mode.unwrap_or_else(|| {+ if address.is_some_and(|a: IpAddr| !a.is_loopback()) {+ ConsoleListenerMode::Network+ } else {+ ConsoleListenerMode::Loopback+ }+ });+ desired.address = address;+ if desired.mode == ConsoleListenerMode::Network && !desired.allow_plaintext_network {+ return Err(ErrorCode::ActionRequired);+ }+ desired+ .validate_configuration()+ .map_err(|_| ErrorCode::InvalidArguments)?;+ Ok(desired)+}+fn ip(value: Option<&String>) -> Result<IpAddr, ErrorCode> {+ value+ .ok_or(ErrorCode::InvalidArguments)?+ .parse()+ .map_err(|_| ErrorCode::InvalidArguments)+}++#[cfg(test)]+mod tests {+ use super::*;+ fn args(value: &str) -> Vec<String> {+ value.split_whitespace().map(str::to_owned).collect()+ }+ #[test]+ fn launch_selection_is_explicit_and_never_treated_as_browser_open() {+ assert_eq!(open_options(&[]).unwrap(), (false, false));+ assert_eq!(+ open_options(&args("--loopback-only")).unwrap(),+ (false, true)+ );+ assert_eq!(+ open_options(&args("--browser --loopback-only")).unwrap(),+ (true, true)+ );+ assert_eq!(+ open_options(&args("--loopback-only --browser")).unwrap(),+ (true, true)+ );+ for invalid in [+ "--loopback-only --loopback-only",+ "--browser --browser",+ "--remote",+ "--listen 127.0.0.1",+ ] {+ assert_eq!(+ open_options(&args(invalid)).unwrap_err(),+ ErrorCode::InvalidArguments+ );+ }+ }+ #[test]+ fn initialization_validates_scope_port_and_plaintext_before_writing() {+ assert_eq!(+ parse(&[], true).unwrap().mode,+ ConsoleListenerMode::Loopback+ );+ assert_eq!(+ parse(&args("--mode off"), true).unwrap().mode,+ ConsoleListenerMode::Off+ );+ assert_eq!(+ parse(&args("--mode network --listen 192.0.2.1"), true).unwrap_err(),+ ErrorCode::ActionRequired+ );+ for bad in [+ "--port 0",+ "--port 65536",+ "--port 7000 --port 8000",+ "--mode loopback --listen 192.0.2.1",+ "--listen ::1",+ "--listen 0.0.0.0 --allow-plaintext-network",+ "--listen 0.0.0.0 --advertise-address ::1 --allow-plaintext-network",+ ] {+ assert!(parse(&args(bad), true).is_err(), "{bad}");+ }+ let configured = parse(&args("--mode network --listen 0.0.0.0 --port 7000 --advertise-address 192.0.2.1 --allow-plaintext-network"), true).unwrap();+ assert_eq!(configured.port, Some(7000));+ assert_eq!(configured.mode, ConsoleListenerMode::Network);+ assert!(parse(&args("--mode loopback"), false).is_err());+ }+}diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rsindex 1c317026..7f832e9c 100644--- a/crates/cli/src/lib.rs+++ b/crates/cli/src/lib.rs@@ -754,7 +754,7 @@ pub fn root_help() -> String {.collect::<Vec<_>>().join("\n");format!(- "HiRoute headless product CLI\n\nUsage\n hiroute <command> [options]\n\nPublic command families\n{commands}\n\nStart or resume: run 'hiroute quickstart --help'.\nDecision connections: run 'hiroute decision services options --help' for installed presets and reusable saved connections.\nHost management: run 'hiroute service --help', 'hiroute gateway --help', 'hiroute protected-input --help', or 'hiroute subscription-proxy --help'.\nAgent collaboration workflow: run 'hiroute agents collaboration --help' to enable, edit, disable or inspect collaboration independently of model settings.\nApplication/Local Control: run 'hiroute schema list --output json' and 'hiroute schema show --command-id <ID> --output json', then append '--help' to a complete command path, for example 'hiroute worker dependencies discover --help'.\n"+ "HiRoute headless product CLI\n\nUsage\n hiroute <command> [options]\n\nPublic command families\n{commands}\n\nStart or resume: run 'hiroute quickstart --help'.\nDecision connections: run 'hiroute decision services options --help' for installed presets and reusable saved connections.\nHost management: run 'hiroute service --help', 'hiroute gateway --help', 'hiroute protected-input --help', 'hiroute subscription-proxy --help', or 'hiroute console --help'.\nAgent collaboration workflow: run 'hiroute agents collaboration --help' to enable, edit, disable or inspect collaboration independently of model settings.\nApplication/Local Control: run 'hiroute schema list --output json' and 'hiroute schema show --command-id <ID> --output json', then append '--help' to a complete command path, for example 'hiroute worker dependencies discover --help'.\n")}@@ -778,6 +778,14 @@ fn native_help_document(descriptor: &CommandDescriptorV1) -> String {pub fn main_entry() -> u8 {let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();#[cfg(windows)]+ if let Some(verb) = arguments+ .first()+ .and_then(|v| v.to_str())+ .filter(|v| matches!(*v, "__windows-install" | "__windows-uninstall"))+ {+ return service::windows_install_hidden(verb, &arguments[1..]);+ }+ #[cfg(windows)]if arguments.first().is_some_and(|argument| argument == service::windows_background_finalize_verb())@@ -878,7 +886,7 @@ mod tests {assert_eq!(execution.exit_code, 0);assert_eq!(execution.stdout.lines().count(), 1);let value: Value = serde_json::from_str(&execution.stdout).unwrap();- assert_eq!(value["data"]["commands"].as_array().unwrap().len(), 55);+ assert_eq!(value["data"]["commands"].as_array().unwrap().len(), 59);assert!(!execution.stdout.contains(HIDDEN_AGENT_GRANT_HELPER_VERB_V1));}diff --git a/crates/cli/src/service.rs b/crates/cli/src/service.rsindex 4a48e5e9..ecebfbcd 100644--- a/crates/cli/src/service.rs+++ b/crates/cli/src/service.rs@@ -15,8 +15,16 @@ use crate::LocalControlClient;const SERVICE_LABEL: &str = "ai.hiroute.cli";const MAX_LOG_BYTES: usize = 256 * 1024;+#[cfg(windows)]+mod restore_agents;+#[cfg(any(windows, test))]+mod restore_plan;#[cfg(windows)]mod windows;+#[cfg(windows)]+pub(crate) fn windows_install_hidden(verb: &str, args: &[std::ffi::OsString]) -> u8 {+ windows::install_hidden(verb, args)+}#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(crate) enum ServiceFailure {@@ -606,6 +614,10 @@ fn bounded_file(path: &Path) -> String {read().unwrap_or_default()}+#[allow(+ dead_code,+ reason = "Retained unpublished manager adapter; no public installation entry"+)]pub(crate) fn install_manager(manager: &str,password_stdin: bool,@@ -639,6 +651,10 @@ pub(crate) fn windows_background_finalize(args: &[std::ffi::OsString]) -> u8 {windows::finalize_hidden(args)}+#[allow(+ dead_code,+ reason = "Retained unpublished manager adapter; no public installation entry"+)]pub(crate) fn uninstall_manager(timeout: Duration) -> Result<serde_json::Value, ServiceFailure> {#[cfg(windows)]{@@ -667,6 +683,10 @@ pub(crate) fn windows_layout() -> Result<serde_json::Value, ServiceFailure> {Err(ServiceFailure::Unavailable)}+#[allow(+ dead_code,+ reason = "Retained unpublished manager adapter; no public installation entry"+)]pub(crate) fn prepare_windows_install() -> Result<serde_json::Value, ServiceFailure> {#[cfg(windows)]{@@ -718,6 +738,10 @@ pub(crate) fn describe_windows_manager(}}+#[allow(+ dead_code,+ reason = "Retained unpublished manager adapter; no public installation entry"+)]pub(crate) fn publish_install_record() -> Result<serde_json::Value, ServiceFailure> {#[cfg(windows)]{@@ -728,6 +752,10 @@ pub(crate) fn publish_install_record() -> Result<serde_json::Value, ServiceFailuErr(ServiceFailure::Unavailable)}+#[allow(+ dead_code,+ reason = "Retained unpublished manager adapter; no public installation entry"+)]pub(crate) fn write_private_record(path: &Path) -> Result<serde_json::Value, ServiceFailure> {#[cfg(windows)]{diff --git a/crates/cli/src/service/restore_agents.rs b/crates/cli/src/service/restore_agents.rsnew file mode 100644index 00000000..56c5326f--- /dev/null+++ b/crates/cli/src/service/restore_agents.rs@@ -0,0 +1,145 @@+//! Uninstall reuses each context's ordinary restore Preview/Apply; no bulk authority.+use super::restore_plan;+use crate::LocalControlClient;+use hiroute_application_api::*;+use serde_json::{Value, json};+use std::{+ io,+ time::{Duration, Instant},+};++fn call(client: &LocalControlClient, operation: &str, payload: Value) -> io::Result<Value> {+ let envelope = client+ .call(LocalControlWireRequestV2 {+ schema_version: LOCAL_CONTROL_SCHEMA_V2,+ request_id: "windows-uninstall-restore".into(),+ operation_id: operation.into(),+ payload,+ protected_grant: None,+ })+ .map_err(|_| io::Error::other("AGENT_CONTROL_UNAVAILABLE"))?;+ if envelope.error.is_some()+ || !matches!(+ envelope.status,+ MachineStatus::Succeeded | MachineStatus::Accepted+ )+ {+ return Err(io::Error::other("AGENT_RESTORE_UNAVAILABLE"));+ }+ envelope+ .data+ .ok_or_else(|| io::Error::other("AGENT_RESTORE_UNAVAILABLE"))+}+fn preview(client: &LocalControlClient, spec: &AgentSettingsSpecV2) -> io::Result<Value> {+ let value = call(+ client,+ "PreviewAgentConnectionRestore",+ json!({"spec":spec}),+ )?;+ let returned: AgentSettingsSpecV2 =+ serde_json::from_value(value["spec"].clone()).map_err(io::Error::other)?;+ if value["schema"] != "hiroute.agent-settings-preview/v2"+ || value["applicable"] != true+ || value["blockers"].as_array().is_none_or(|b| !b.is_empty())+ || returned.context_id != spec.context_id+ || returned.native_target != spec.native_target+ || returned.management_skill != spec.management_skill+ || returned.model != spec.model+ || returned.collaboration != spec.collaboration+ || returned.restore_native_model != spec.restore_native_model+ || !returned.is_restore_only()+ {+ return Err(io::Error::other("AGENT_RESTORE_DECISION_REQUIRED"));+ }+ Ok(value)+}+pub(super) fn restore(layout: &hiroute_host_runtime::StandaloneLayout) -> io::Result<()> {+ // The caller has admitted the Task registration and starts it for these production queries.+ let client = LocalControlClient::cli_from_environment()+ .map_err(|_| io::Error::other("AGENT_CONTROL_UNAVAILABLE"))?+ .with_timeout(Duration::from_secs(30));+ let until = Instant::now() + Duration::from_secs(30);+ let list = loop {+ match call(&client, "ListAgents", json!({})) {+ Ok(value) => break value,+ Err(error) if Instant::now() < until => {+ let _ = error;+ std::thread::sleep(Duration::from_millis(100));+ }+ Err(_) => return Err(io::Error::other("AGENT_CONTROL_UNAVAILABLE")),+ }+ };+ let _ = layout;+ let contexts = restore_plan::contexts(&list)?;+ let mut blocked = vec![];+ let mut specs = vec![];+ for context in &contexts {+ let name = &context.agent;+ let status = call(+ &client,+ "GetAgentConnectionStatus",+ json!(AgentSettingsStatusRequestV2 {+ schema_version: AGENT_SETTINGS_SCHEMA_V2,+ context_id: context.id.clone(),+ native_target: context.native_target.clone(),+ include_skills: true,+ effective: None,+ }),+ )+ .and_then(|v| serde_json::from_value::<AgentSettingsStatusV2>(v).map_err(io::Error::other));+ let Some(spec) = status+ .ok()+ .filter(|s| s.valid() && s.context_id() == context.id)+ .and_then(|s| restore_plan::spec(context, &s))+ else {+ blocked.push(name.clone());+ continue;+ };+ if !spec.is_restore_only() {+ continue;+ }+ if preview(&client, &spec).is_err() {+ blocked.push(name.clone());+ } else {+ specs.push((name.clone(), spec));+ }+ }+ if !blocked.is_empty() {+ return Err(restore_plan::decision(blocked));+ }+ // Refresh Preview before every Apply because prior restores may advance shared revisions.+ for (name, spec) in specs {+ let result = (|| -> io::Result<()> {+ let preview = preview(&client, &spec)?;+ let mut bytes = [0; 16];+ getrandom::fill(&mut bytes).map_err(|e| io::Error::other(e.to_string()))?;+ let key: String = bytes.iter().map(|b| format!("{b:02x}")).collect();+ let applied = call(+ &client,+ "ApplyAgentConnectionRestore",+ json!({"expected_revisions":preview["expected_revisions"], "spec":preview["spec"], "accept_digest":preview["accept_digest"], "dependency_digest":preview["dependency_digest"], "idempotency_key":key}),+ )?;+ let operation = applied["operation_id"]+ .as_str()+ .ok_or_else(|| io::Error::other("AGENT_RESTORE_UNAVAILABLE"))?;+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ let view = call(&client, "GetOperation", json!({"operation_id":operation}))?;+ match view["state"].as_str() {+ Some("succeeded") => break Ok(()),+ Some("rolled_back" | "needs_attention") | None => {+ break Err(io::Error::other("AGENT_RESTORE_UNAVAILABLE"));+ }+ _ if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(100))+ }+ _ => break Err(io::Error::other("AGENT_RESTORE_UNAVAILABLE")),+ }+ }+ })();+ if result.is_err() {+ return Err(restore_plan::decision(vec![name]));+ }+ }+ Ok(())+}diff --git a/crates/cli/src/service/restore_plan.rs b/crates/cli/src/service/restore_plan.rsnew file mode 100644index 00000000..8a7e5e95--- /dev/null+++ b/crates/cli/src/service/restore_plan.rs@@ -0,0 +1,318 @@+//! Restore the actual owning contexts, rather than a UI status projection.+use hiroute_application_api::{+ AGENT_SETTINGS_SCHEMA_V2, AgentAccessTokenIntentV1, AgentFacetIntent,+ AgentModelSettingsStateV2, AgentNativeTargetV1, AgentSettingsSpecV2, AgentSettingsStatusV2,+};+use serde_json::Value;+use std::{collections::BTreeMap, io};++#[derive(Debug, Eq, PartialEq)]+pub(super) struct Context {+ pub id: String,+ pub agent: String,+ pub model: bool,+ pub collaboration: bool,+ pub management_skill: bool,+ pub native_target: Option<AgentNativeTargetV1>,+}++pub(super) fn decision(mut agents: Vec<String>) -> io::Error {+ agents.sort_unstable();+ agents.dedup();+ io::Error::other(format!(+ "AGENT_RESTORE_REQUIRED:{}",+ serde_json::to_string(&agents).unwrap_or_default()+ ))+}++pub(super) fn contexts(list: &Value) -> io::Result<Vec<Context>> {+ let unavailable = || io::Error::other("AGENT_RESTORE_UNAVAILABLE");+ let agents = list["agents"].as_array().ok_or_else(unavailable)?;+ let mut contexts = BTreeMap::new();+ for agent in agents {+ let Some(context) = agent["context_id"].as_str().filter(|c| !c.is_empty()) else {+ continue;+ };+ let name = agent["agent_id"].as_str().unwrap_or(context);+ let target: Option<AgentNativeTargetV1> =+ serde_json::from_value(agent["native_target"].clone())+ .map_err(|_| decision(vec![name.into()]))?;+ if target+ .as_ref()+ .is_some_and(|target| target.validate().is_err())+ || (name == "agent_hermes_default" && target.is_none())+ {+ return Err(decision(vec![name.into()]));+ }+ let mut insert = |id: &str, model, collaboration| {+ let value = Context {+ id: id.into(),+ agent: name.into(),+ model,+ collaboration,+ management_skill: collaboration,+ native_target: target.clone(),+ };+ if contexts.insert(id.to_owned(), value).is_some() {+ return Err(unavailable());+ }+ Ok(())+ };+ if name == "agent_codex_default" {+ let access = &agent["codex_access"];+ let root = access["root_context_id"]+ .as_str()+ .filter(|c| !c.is_empty())+ .ok_or_else(unavailable)?;+ let profile = access["profile_context_id"]+ .as_str()+ .filter(|c| !c.is_empty())+ .ok_or_else(unavailable)?;+ if root == profile || ![root, profile].contains(&context) {+ return Err(unavailable());+ }+ // Profile status deliberately displays both root-owned Skill facets.+ // Their restore points belong to the root, never to the profile.+ insert(context, true, context == root)?;+ if context != root {+ insert(root, false, true)?;+ }+ } else {+ insert(context, true, true)?;+ }+ }+ Ok(contexts.into_values().collect())+}++pub(super) fn spec(+ context: &Context,+ status: &AgentSettingsStatusV2,+) -> Option<AgentSettingsSpecV2> {+ use AgentModelSettingsStateV2::{Configured, NotConfigured, Restored};+ let restore = |state: &AgentModelSettingsStateV2, point: &Option<String>| match state {+ NotConfigured | Restored => Some(None),+ Configured => point.clone().map(Some),+ _ => None,+ };+ let model = match (context.model, status.model()) {+ (true, Some(m)) => restore(&m.state, &m.restore_point_ref)?,+ _ => None,+ };+ let collaboration = match (context.collaboration, status.collaboration()) {+ (true, Some(c)) => restore(&c.state, &c.restore_point_ref)?,+ _ => None,+ };+ let management = if context.management_skill {+ let management = match status {+ AgentSettingsStatusV2::Model(model) => model.management_skill.as_ref(),+ AgentSettingsStatusV2::CollaborationOnly(status) => status.management_skill.as_ref(),+ }?;+ if management.schema != "hiroute.agent-management-skill-status/v1" {+ return None;+ }+ restore(&management.state, &management.restore_point_ref)?+ } else {+ None+ };+ Some(AgentSettingsSpecV2 {+ schema_version: AGENT_SETTINGS_SCHEMA_V2,+ context_id: context.id.clone(),+ native_target: context.native_target.clone(),+ management_skill: management+ .map(|restore_point_ref| AgentFacetIntent::Restore { restore_point_ref }),+ model: model+ .map(|restore_point_ref| AgentFacetIntent::Restore { restore_point_ref })+ .unwrap_or_default(),+ collaboration: collaboration+ .map(|restore_point_ref| AgentFacetIntent::Restore { restore_point_ref })+ .unwrap_or_default(),+ restore_native_model: None,+ protected_native_model_ids: vec![],+ access_token: AgentAccessTokenIntentV1::Keep,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn codex(selected: &str) -> Value {+ json!({"agents":[{"agent_id":"agent_codex_default","context_id":selected,+ "codex_access":{"root_context_id":"root","profile_context_id":"profile"}}]})+ }++ fn status(context: &str, model: &str, collaboration: &str) -> AgentSettingsStatusV2 {+ serde_json::from_value(json!({"schema":"hiroute.agent-model-settings-status/v2",+ "context_id":context,"state":model,"operation_id":null,"operation_state":null,+ "restore_point_ref":if model == "configured" { Some("model-point") } else { None },+ "applied_revision":null,"surface_results":[],"model_verified":false,+ "management_skill":{"schema":"hiroute.agent-management-skill-status/v1",+ "state":"not_configured","operation_id":null,"operation_state":null,"restore_point_ref":null},+ "collaboration":{"schema":"hiroute.agent-collaboration-settings-status/v2",+ "state":collaboration,"operation_id":null,"operation_state":null,+ "restore_point_ref":if collaboration == "configured" { Some("root-skill-point") } else { None }}})).unwrap()+ }++ fn management_status(context: &str, state: &str) -> AgentSettingsStatusV2 {+ let mut value =+ serde_json::to_value(status(context, "not_configured", "not_configured")).unwrap();+ value["management_skill"]["state"] = json!(state);+ if state == "configured" {+ value["management_skill"]["restore_point_ref"] = json!("management-point");+ }+ serde_json::from_value(value).unwrap()+ }++ #[test]+ fn management_only_restore_keeps_the_explicit_native_target_and_all_other_facets() {+ let root = tempfile::tempdir().unwrap();+ let target = AgentNativeTargetV1::Hermes {+ config_root: root.path().to_str().unwrap().into(),+ };+ let rows = contexts(&json!({"agents":[{"agent_id":"agent_hermes_default","context_id":"hermes","native_target":target}]})).unwrap();+ let restore = spec(&rows[0], &management_status("hermes", "configured")).unwrap();+ assert!(restore.is_restore_only());+ assert_eq!(restore.native_target, Some(target));+ assert_eq!(+ restore.management_skill,+ Some(AgentFacetIntent::Restore {+ restore_point_ref: "management-point".into()+ })+ );+ assert!(matches!(restore.model, AgentFacetIntent::Keep));+ assert!(matches!(restore.collaboration, AgentFacetIntent::Keep));+ for state in ["drift", "pending", "needs_attention"] {+ assert!(spec(&rows[0], &management_status("hermes", state)).is_none());+ }+ let mut missing = serde_json::to_value(management_status("hermes", "configured")).unwrap();+ missing["management_skill"]["restore_point_ref"] = Value::Null;+ assert!(spec(&rows[0], &serde_json::from_value(missing).unwrap()).is_none());+ let missing_target =+ json!({"agents":[{"agent_id":"agent_hermes_default","context_id":"hermes"}]});+ assert!(+ super::contexts(&missing_target)+ .unwrap_err()+ .to_string()+ .starts_with("AGENT_RESTORE_REQUIRED:")+ );+ }++ #[test]+ fn codex_management_projection_is_restored_only_through_the_original_root() {+ let rows = contexts(&codex("profile")).unwrap();+ let profile = rows.iter().find(|row| row.id == "profile").unwrap();+ let root = rows.iter().find(|row| row.id == "root").unwrap();+ assert!(+ spec(profile, &management_status("profile", "configured"))+ .unwrap()+ .management_skill+ .is_none()+ );+ assert!(matches!(+ spec(root, &management_status("root", "configured"))+ .unwrap()+ .management_skill,+ Some(AgentFacetIntent::Restore { .. })+ ));+ let mut missing = serde_json::to_value(management_status("root", "configured")).unwrap();+ missing.as_object_mut().unwrap().remove("management_skill");+ assert!(spec(root, &serde_json::from_value(missing).unwrap()).is_none());+ }++ #[test]+ fn codex_profile_projection_restores_the_skill_only_through_its_root() {+ for selected in ["profile", "root"] {+ let contexts = contexts(&codex(selected)).unwrap();+ assert_eq!(contexts.len(), if selected == "profile" { 2 } else { 1 });+ assert!(contexts.iter().all(|c| c.agent == "agent_codex_default"));+ let root = contexts.iter().find(|c| c.id == "root").unwrap();+ if selected == "profile" {+ let profile = contexts.iter().find(|c| c.id == "profile").unwrap();+ let profile =+ spec(profile, &status("profile", "configured", "configured")).unwrap();+ assert!(matches!(profile.model, AgentFacetIntent::Restore { .. }));+ assert!(matches!(profile.collaboration, AgentFacetIntent::Keep));+ }+ let root = spec(root, &status("root", "not_configured", "configured")).unwrap();+ assert!(matches!(root.model, AgentFacetIntent::Keep));+ assert_eq!(+ root.collaboration,+ AgentFacetIntent::Restore {+ restore_point_ref: "root-skill-point".into()+ }+ );+ }+ }++ #[test]+ fn collaboration_only_codex_does_not_submit_a_restore_to_an_empty_profile() {+ let contexts = contexts(&codex("profile")).unwrap();+ let profile = contexts.iter().find(|c| c.id == "profile").unwrap();+ assert!(+ !spec(profile, &status("profile", "not_configured", "configured"))+ .unwrap()+ .is_restore_only()+ );+ let root = contexts.iter().find(|c| c.id == "root").unwrap();+ assert!(+ spec(root, &status("root", "not_configured", "configured"))+ .unwrap()+ .is_restore_only()+ );+ }++ #[test]+ fn blocked_codex_contexts_report_one_agent_without_hiding_other_agents() {+ let mut blocked: Vec<_> = contexts(&codex("profile"))+ .unwrap()+ .into_iter()+ .map(|context| context.agent)+ .collect();+ blocked.insert(1, "agent_claude_default".into());+ let error = decision(blocked);+ assert_eq!(error.kind(), io::ErrorKind::Other);+ let message = error.to_string();+ let agents: Vec<String> =+ serde_json::from_str(message.strip_prefix("AGENT_RESTORE_REQUIRED:").unwrap()).unwrap();+ assert_eq!(agents, ["agent_claude_default", "agent_codex_default"]);+ assert_eq!(+ decision(vec!["agent_codex_default".into()]).to_string(),+ "AGENT_RESTORE_REQUIRED:[\"agent_codex_default\"]"+ );+ }++ #[test]+ fn root_conflicts_and_missing_restore_points_still_require_a_user_decision() {+ let contexts = contexts(&codex("profile")).unwrap();+ let root = contexts.iter().find(|c| c.id == "root").unwrap();+ for state in ["drift", "pending", "needs_attention"] {+ assert!(spec(root, &status("root", "not_configured", state)).is_none());+ }+ let mut missing = status("root", "not_configured", "configured");+ if let AgentSettingsStatusV2::Model(model) = &mut missing {+ model.collaboration.as_mut().unwrap().restore_point_ref = None;+ }+ assert!(spec(root, &missing).is_none());+ }++ #[test]+ fn ordinary_contexts_keep_both_facets_and_ambiguous_codex_ownership_is_refused() {+ let ordinary =+ json!({"agents":[{"agent_id":"agent_claude_default","context_id":"claude"}]});+ let contexts = contexts(&ordinary).unwrap();+ let plan = spec(&contexts[0], &status("claude", "configured", "configured")).unwrap();+ assert!(matches!(plan.model, AgentFacetIntent::Restore { .. }));+ assert!(matches!(+ plan.collaboration,+ AgentFacetIntent::Restore { .. }+ ));+ for invalid in [+ codex("other"),+ json!({"agents":[{"agent_id":"agent_codex_default","context_id":"profile"}]}),+ json!({"agents":[{"agent_id":"agent_codex_default","context_id":"root","codex_access":{"root_context_id":"root","profile_context_id":"root"}}]}),+ ] {+ assert!(super::contexts(&invalid).is_err());+ }+ }+}diff --git a/crates/cli/src/service/windows.rs b/crates/cli/src/service/windows.rsindex 9b797fec..50a1b2b4 100644--- a/crates/cli/src/service/windows.rs+++ b/crates/cli/src/service/windows.rs@@ -12,8 +12,12 @@ use zeroize::Zeroizing;use super::ServiceFailure;+mod install;mod logs;mod scm_owner;+pub(crate) fn install_hidden(verb: &str, args: &[std::ffi::OsString]) -> u8 {+ install::run(verb, args)+}pub(crate) fn scm_owner_helper_verb() -> &'static str {scm_owner::VERB}diff --git a/crates/cli/src/service/windows/install.rs b/crates/cli/src/service/windows/install.rsnew file mode 100644index 00000000..8b3e5429--- /dev/null+++ b/crates/cli/src/service/windows/install.rs@@ -0,0 +1,66 @@+use hiroute_host_runtime::standalone_install::windows::{self, InstallRequest, UninstallRequest};+use std::{+ ffi::OsString,+ io::{self, Read, Write},+};++pub(crate) fn run(verb: &str, arguments: &[OsString]) -> u8 {+ let execute = || -> io::Result<serde_json::Value> {+ if arguments != [OsString::from("--request-stdin")] {+ return Err(io::ErrorKind::InvalidInput.into());+ }+ let mut bytes = Vec::new();+ io::stdin()+ .lock()+ .take(16 * 1024 + 1)+ .read_to_end(&mut bytes)?;+ if bytes.is_empty() || bytes.len() > 16 * 1024 {+ return Err(io::ErrorKind::InvalidInput.into());+ }+ match verb {+ "__windows-install" => windows::install(+ serde_json::from_slice::<InstallRequest>(&bytes).map_err(io::Error::other)?,+ ),+ "__windows-uninstall" => windows::uninstall(+ serde_json::from_slice::<UninstallRequest>(&bytes).map_err(io::Error::other)?,+ super::super::restore_agents::restore,+ ),+ _ => Err(io::ErrorKind::InvalidInput.into()),+ }+ };+ let (exit, value) = match execute() {+ Ok(value) => (0, value),+ Err(error) => {+ let text = error.to_string();+ let agents = text+ .strip_prefix("AGENT_RESTORE_REQUIRED:")+ .and_then(|v| serde_json::from_str::<Vec<String>>(v).ok());+ let code = if agents.is_some() {+ "AGENT_RESTORE_REQUIRED"+ } else {+ [+ "DRAIN_UNSUPPORTED",+ "UPGRADE_ACTIVE_WORK",+ "INSTALL_SCM_MANAGED",+ "INSTALL_ARCHITECTURE_UNSUPPORTED",+ "INSTALL_MAINTENANCE_BUSY",+ "INSTALL_OWNERSHIP_CONFLICT",+ "AGENT_CONTROL_UNAVAILABLE",+ "AGENT_RESTORE_DATA_REQUIRED",+ "INSTALL_PACKAGE_IN_USE",+ ]+ .into_iter()+ .find(|code| text == *code)+ .unwrap_or("INSTALL_FAILED")+ };+ (+ 1,+ serde_json::json!({"schema":"hiroute.windows-maintenance-error/v1","error":{"code":code,"agents":agents,"message": if code == "INSTALL_SCM_MANAGED" { Some("SCM service installation is not offered in this release. The existing installation was left unchanged.") } else { None }}}),+ )+ }+ };+ if writeln!(io::stdout().lock(), "{}", value).is_err() {+ return 1;+ }+ exit+}diff --git a/crates/cli/tests/contracts.rs b/crates/cli/tests/contracts.rsindex 88c4f792..4aca24c9 100644--- a/crates/cli/tests/contracts.rs+++ b/crates/cli/tests/contracts.rs@@ -16,7 +16,7 @@ fn checked_in_contracts_are_exact_generator_output() {#[test]fn each_p0_leaf_has_stable_positive_and_negative_plans() {let commands = planned_commands();- assert_eq!(commands.len(), 88); // Full staged surface including decision services.+ assert_eq!(commands.len(), 92); // Full staged surface including decision services.for command in commands {assert!(command.positive.scenario_id.ends_with(".positive"));assert!(command.negative.scenario_id.ends_with(".negative"));@@ -35,6 +35,10 @@ fn release_manifest_is_a_strict_subset_of_planned_registry() {.map(|command| command.command_id.as_str()).collect::<Vec<_>>(),[+ "console.open",+ "console.token.create",+ "console.token.list",+ "console.token.revoke","schema.list","schema.show","operations.find",diff --git a/crates/client-core/src/lib.rs b/crates/client-core/src/lib.rsindex ee647e62..53644d69 100644--- a/crates/client-core/src/lib.rs+++ b/crates/client-core/src/lib.rs@@ -25,17 +25,33 @@ use hiroute_diagnostics::context::DiagnosticContext;use hiroute_diagnostics::correlation::CorrelationDomain;use hiroute_diagnostics::error::EventErrorCode;use hiroute_diagnostics::event::{- ControlCallEnd, ControlOperation, ControlStage, ControlStageKind, DiagnosticEvent,- SubmissionState as DiagnosticSubmissionState,+ ControlCallEnd, ControlClientName, ControlOperation, ControlStage, ControlStageKind,+ DiagnosticEvent, SubmissionState as DiagnosticSubmissionState,};use serde::{Serialize, de::DeserializeOwned};use serde_json::Value;use std::time::Duration;use zeroize::Zeroize;+pub trait ControlDispatch: Send + Sync {+ fn dispatch(&self, request: LocalControlWireRequestV2) -> MachineEnvelopeV2<Value>;+}+#[derive(Clone)]+enum Transport {+ LocalEndpoint(LocalEndpoint),+ InProcess(std::sync::Arc<dyn ControlDispatch>),+}+impl std::fmt::Debug for Transport {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::LocalEndpoint(endpoint) => endpoint.fmt(f),+ Self::InProcess(_) => f.write_str("InProcess"),+ }+ }+}#[derive(Clone, Debug)]pub struct Client {- endpoint: LocalEndpoint,+ transport: Transport,name: String,timeout: Duration,diagnostics: Option<DiagnosticContext>,@@ -54,12 +70,29 @@ impl Drop for PrivateRequest {impl Client {pub fn new(name: impl Into<String>, endpoint: LocalEndpoint) -> Self {Self {- endpoint,+ transport: Transport::LocalEndpoint(endpoint),+ name: name.into(),+ timeout: Duration::from_secs(30),+ diagnostics: None,+ }+ }+ pub fn in_process(+ name: impl Into<String>,+ dispatcher: std::sync::Arc<dyn ControlDispatch>,+ ) -> Self {+ Self {+ transport: Transport::InProcess(dispatcher),name: name.into(),timeout: Duration::from_secs(30),diagnostics: None,}}+ pub fn local_endpoint(&self) -> Option<&LocalEndpoint> {+ match &self.transport {+ Transport::LocalEndpoint(endpoint) => Some(endpoint),+ Transport::InProcess(_) => None,+ }+ }pub fn with_timeout(mut self, timeout: Duration) -> Self {self.timeout = timeout;self@@ -71,7 +104,8 @@ impl Client {self}pub fn endpoint(&self) -> &LocalEndpoint {- &self.endpoint+ self.local_endpoint()+ .expect("endpoint is available only for LocalEndpoint clients")}pub async fn query<P: Serialize, R: DeserializeOwned>(@@ -142,8 +176,21 @@ impl Client {.checked_add(self.timeout).ok_or_else(|| ClientFailure::before_send(FailureCode::Deadline))?;let operation = async {+ let endpoint = match &self.transport {+ Transport::LocalEndpoint(endpoint) => endpoint,+ Transport::InProcess(dispatcher) => {+ let dispatcher = dispatcher.clone();+ let request = PrivateRequest(request.0.clone());+ sent = true;+ return tokio::task::spawn_blocking(move || {+ dispatcher.dispatch(request.0.clone())+ })+ .await+ .map_err(|_| FailureCode::TransportUnavailable);+ }+ };let step = std::time::Instant::now();- let validated = self.endpoint.validate_path();+ let validated = endpoint.validate_path();stage(ControlStageKind::EndpointValidate,validated.is_ok(),@@ -158,12 +205,12 @@ impl Client {.protected_grant.as_ref().is_some_and(|g| g.principal_kind == PrincipalKind::Desktop)- && self.endpoint.expected_pid.is_none()+ && endpoint.expected_pid.is_none(){return Err(FailureCode::PeerRejected);}- let stream = self.endpoint.connect().await?;- self.endpoint.validate_peer(&stream)?;+ let stream = endpoint.connect().await?;+ endpoint.validate_peer(&stream)?;Ok::<_, FailureCode>(stream)};let stream = peer.await;@@ -317,6 +364,8 @@ impl Client {Ok(Ok(result)) => {emit_call_end(&context,+ matches!(&self.transport, Transport::InProcess(_))+ .then_some(ControlClientName::Console),operation_kind,request_token,DiagnosticSubmissionState::Sent,@@ -332,6 +381,8 @@ impl Client {let failure = ClientFailure::at(code, sent);emit_call_end(&context,+ matches!(&self.transport, Transport::InProcess(_))+ .then_some(ControlClientName::Console),operation_kind,request_token,submission_state(failure),@@ -344,6 +395,8 @@ impl Client {let failure = ClientFailure::at(FailureCode::Deadline, sent);emit_call_end(&context,+ matches!(&self.transport, Transport::InProcess(_))+ .then_some(ControlClientName::Console),operation_kind,request_token,submission_state(failure),@@ -415,6 +468,7 @@ fn submission_state(failure: ClientFailure) -> DiagnosticSubmissionState {fn emit_call_end(context: &Option<DiagnosticContext>,+ client_name: Option<ControlClientName>,operation: ControlOperation,request_token: Option<hiroute_diagnostics::identity::CorrelationToken>,submission: DiagnosticSubmissionState,@@ -425,6 +479,7 @@ fn emit_call_end(return;};context.emit(DiagnosticEvent::ControlCallEnd(ControlCallEnd {+ client_name,operation,request_token,submission,diff --git a/crates/daemon/Cargo.toml b/crates/daemon/Cargo.tomlindex 20433acf..caaa3dac 100644--- a/crates/daemon/Cargo.toml+++ b/crates/daemon/Cargo.toml@@ -9,6 +9,12 @@ rust-version.workspace = trueintegration-test-hooks = [][dependencies]+bytes.workspace = true+hyper = { version = "=1.11.1", features = ["server", "http1"] }+hyper-util = { version = "=0.1.20", features = ["tokio"] }+http-body-util = "=0.1.5"+hiroute-product-session = { path = "../product-session" }+hiroute-client-core = { path = "../client-core" }hiroute-platform = { path = "../platform" }agent-client-protocol = "=2.1.0"arc-swap.workspace = true@@ -48,7 +54,7 @@ path = "src/control/bin.rs"[dev-dependencies]hiroute-client-core = { path = "../client-core" }-tokio.workspace = true+tokio = { workspace = true, features = ["test-util"] }tokio-util.workspace = true[target.'cfg(unix)'.dev-dependencies]diff --git a/crates/daemon/src/console/assets.rs b/crates/daemon/src/console/assets.rsnew file mode 100644index 00000000..8b400e5a--- /dev/null+++ b/crates/daemon/src/console/assets.rs@@ -0,0 +1,86 @@+use std::{collections::BTreeMap, io::Read, path::Path, sync::Arc};+pub(super) struct Assets {+ files: BTreeMap<String, (&'static str, Arc<[u8]>)>,+}+impl Assets {+ pub fn load(root: &Path) -> Result<Self, ()> {+ let mut files = BTreeMap::new();+ let mut total = 0;+ Self::visit(root, root, &mut files, &mut total)?;+ if !files.contains_key("/index.html") {+ return Err(());+ }+ Ok(Self { files })+ }+ fn visit(+ root: &Path,+ dir: &Path,+ files: &mut BTreeMap<String, (&'static str, Arc<[u8]>)>,+ total: &mut usize,+ ) -> Result<(), ()> {+ let metadata = std::fs::symlink_metadata(dir).map_err(|_| ())?;+ if !metadata.is_dir() || metadata.file_type().is_symlink() {+ return Err(());+ }+ for entry in std::fs::read_dir(dir).map_err(|_| ())? {+ let entry = entry.map_err(|_| ())?;+ let metadata = entry.metadata().map_err(|_| ())?;+ if entry.file_type().map_err(|_| ())?.is_symlink() {+ return Err(());+ }+ if metadata.is_dir() {+ Self::visit(root, &entry.path(), files, total)?;+ continue;+ }+ if !metadata.is_file() || metadata.len() > 16 * 1024 * 1024 || files.len() >= 2048 {+ return Err(());+ }+ let path = entry.path();+ let relative = path+ .strip_prefix(root)+ .map_err(|_| ())?+ .to_str()+ .ok_or(())?+ .replace('\\', "/");+ if !relative+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"/-_.".contains(&b))+ || relative.split('/').any(|c| c == ".." || c.starts_with('.'))+ {+ return Err(());+ }+ let mime = match path.extension().and_then(|s| s.to_str()) {+ Some("html") => "text/html; charset=utf-8",+ Some("js") => "text/javascript; charset=utf-8",+ Some("css") => "text/css; charset=utf-8",+ Some("svg") => "image/svg+xml",+ Some("png") => "image/png",+ Some("ico") => "image/x-icon",+ Some("woff2") => "font/woff2",+ Some("json") => "application/json",+ _ => return Err(()),+ };+ let mut bytes = Vec::new();+ hiroute_platform::private_fs::open_regular_file(&path)+ .map_err(|_| ())?+ .take(16 * 1024 * 1024 + 1)+ .read_to_end(&mut bytes)+ .map_err(|_| ())?;+ *total += bytes.len();+ if bytes.len() > 16 * 1024 * 1024 || *total > 64 * 1024 * 1024 {+ return Err(());+ }+ files.insert(format!("/{relative}"), (mime, Arc::from(bytes)));+ }+ Ok(())+ }+ pub fn get(&self, path: &str) -> Option<(&'static str, Arc<[u8]>)> {+ self.files+ .get(if matches!(path, "/" | "/launch") {+ "/index.html"+ } else {+ path+ })+ .cloned()+ }+}diff --git a/crates/daemon/src/console/auth/launch.rs b/crates/daemon/src/console/auth/launch.rsnew file mode 100644index 00000000..6b598574--- /dev/null+++ b/crates/daemon/src/console/auth/launch.rs@@ -0,0 +1,32 @@+//! An owner-issued code is scoped to one established HTTP origin and transport.+use std::net::SocketAddr;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct LaunchTarget {+ pub origin: String,+ pub loopback_only: bool,+}+impl LaunchTarget {+ pub fn new(address: SocketAddr, loopback_only: bool) -> Self {+ Self {+ origin: format!("http://{}", authority(address)),+ loopback_only,+ }+ }+}++pub(crate) fn authority(address: SocketAddr) -> String {+ if address.port() == 80 {+ match address.ip() {+ std::net::IpAddr::V4(ip) => ip.to_string(),+ std::net::IpAddr::V6(ip) => format!("[{ip}]"),+ }+ } else {+ address.to_string()+ }+}++pub(super) struct Launch {+ pub expires: u64,+ pub target: LaunchTarget,+}diff --git a/crates/daemon/src/console/auth/mod.rs b/crates/daemon/src/console/auth/mod.rsnew file mode 100644index 00000000..3d1de653--- /dev/null+++ b/crates/daemon/src/console/auth/mod.rs@@ -0,0 +1,463 @@+//! Hash-only credentials and bounded in-memory sessions. Never log request bodies.+use http::HeaderMap;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::{+ collections::{BTreeMap, VecDeque},+ net::IpAddr,+ path::{Path, PathBuf},+ time::Instant,+};+use zeroize::Zeroizing;+mod launch;+mod store;+pub use launch::LaunchTarget;+pub(crate) use launch::authority;+#[cfg(test)]+mod tests;++const LAUNCH_TTL: u64 = 120;+const IDLE_TTL: u64 = 12 * 60 * 60;+const ABSOLUTE_TTL: u64 = 7 * 24 * 60 * 60;+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum AuthError {+ Required,+ RateLimited,+ Invalid,+ Capacity,+ Unavailable,+ ListenerUnavailable,+}+impl AuthError {+ pub fn code(self) -> &'static str {+ match self {+ Self::Required => "CONSOLE_AUTH_REQUIRED",+ Self::RateLimited => "CONSOLE_RATE_LIMITED",+ Self::Invalid => "CONSOLE_CREDENTIAL_INVALID",+ Self::Capacity => "CONSOLE_SESSION_LIMIT",+ Self::Unavailable => "CONSOLE_AUTH_UNAVAILABLE",+ Self::ListenerUnavailable => "CONSOLE_LISTENER_UNAVAILABLE",+ }+ }+}+#[derive(Clone, Serialize, Deserialize)]+pub struct TokenMetadata {+ pub id: String,+ pub name: String,+ pub created: u64,+ pub expires: Option<u64>,+ pub revoked: bool,+}+#[derive(Serialize)]+pub struct CreatedToken {+ #[serde(flatten)]+ pub metadata: TokenMetadata,+ pub token: String,+}+#[derive(Clone, Serialize)]+pub struct SessionIdentity {+ pub id: String,+ pub credential_kind: &'static str,+ pub token_id: Option<String>,+ pub expires: u64,+}+#[derive(Serialize)]+pub struct SessionExchange {+ pub bearer: String,+ pub session: SessionIdentity,+}+struct Session {+ identity: SessionIdentity,+ created: u64,+ last_used: u64,+ last_access: Instant,+}+#[derive(Serialize)]+pub(super) struct AuditEvent<'a> {+ at: u64,+ event: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ session_id: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ credential_kind: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ token_id: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ context: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ command: Option<&'a str>,+ #[serde(skip_serializing_if = "Option::is_none")]+ operation_id: Option<&'a str>,+}+pub struct ConsoleAuth {+ root: PathBuf,+ tokens: Vec<store::StoredToken>,+ launches: BTreeMap<String, launch::Launch>,+ sessions: BTreeMap<String, Session>,+ failures: VecDeque<(u64, IpAddr)>,+}+impl ConsoleAuth {+ pub fn open(data_root: &Path) -> Result<Self, AuthError> {+ let root = data_root.join("console");+ store::prepare(&root)?;+ let tokens = store::load(&root)?;+ Ok(Self {+ root,+ tokens,+ launches: BTreeMap::new(),+ sessions: BTreeMap::new(),+ failures: VecDeque::new(),+ })+ }+ pub fn create_launch(&mut self, target: LaunchTarget) -> Result<Zeroizing<String>, AuthError> {+ let now = now()?;+ self.launches.retain(|_, entry| entry.expires > now);+ if self.launches.len() >= 32 {+ return Err(AuthError::Capacity);+ }+ let secret = random()?;+ self.credential_event("launch_created", "launch", None)?;+ self.launches.insert(+ hash(&secret),+ launch::Launch {+ expires: now + LAUNCH_TTL,+ target,+ },+ );+ Ok(secret)+ }+ pub fn create_token(+ &mut self,+ name: String,+ days: Option<u32>,+ ) -> Result<CreatedToken, AuthError> {+ if !valid_name(&name) || days.is_some_and(|d| d == 0 || d > 3650) {+ return Err(AuthError::Invalid);+ }+ if self.tokens.len() >= store::MAX_TOKENS {+ return Err(AuthError::Capacity);+ }+ let created = now()?;+ let metadata = TokenMetadata {+ id: random()?.to_string(),+ name,+ created,+ expires: Some(created + days.unwrap_or(90) as u64 * 86400),+ revoked: false,+ };+ let secret = random()?;+ let mut tokens = self.tokens.clone();+ tokens.push(store::StoredToken {+ metadata: metadata.clone(),+ sha256: hash(&secret),+ });+ store::save(&self.root, &tokens)?;+ self.tokens = tokens;+ self.credential_event("token_created", "token", Some(&metadata.id))?;+ Ok(CreatedToken {+ metadata,+ token: secret.to_string(),+ })+ }+ pub fn list_tokens(&self) -> Vec<TokenMetadata> {+ self.tokens.iter().map(|t| t.metadata.clone()).collect()+ }+ pub fn revoke_token(&mut self, id: &str) -> Result<(), AuthError> {+ let mut tokens = self.tokens.clone();+ tokens+ .iter_mut()+ .find(|t| t.metadata.id == id)+ .ok_or(AuthError::Invalid)?+ .metadata+ .revoked = true;+ store::save(&self.root, &tokens)?;+ self.tokens = tokens;+ self.credential_event("token_revoked", "token", Some(id))?;+ let keys: Vec<_> = self+ .sessions+ .iter()+ .filter(|(_, s)| s.identity.token_id.as_deref() == Some(id))+ .map(|(k, _)| k.clone())+ .collect();+ for key in keys {+ self.remove_session(&key, "session_revoked")?;+ }+ Ok(())+ }+ pub fn exchange_launch(+ &mut self,+ code: &str,+ peer: IpAddr,+ origin: &str,+ ) -> Result<SessionExchange, AuthError> {+ self.rate(peer)?;+ let now = now()?;+ if !valid_secret(code) {+ return self.failed(peer);+ }+ let digest = hash(code);+ if !self.launches.get(&digest).is_some_and(|entry| {+ entry.expires > now+ && entry.target.origin == origin+ && (!entry.target.loopback_only || peer.is_loopback())+ }) {+ return self.failed(peer);+ }+ // Consume before session creation: a failed/cancelled exchange cannot replay.+ self.launches.remove(&digest);+ self.new_session("launch", None, now)+ }+ pub fn exchange_token(+ &mut self,+ token: &str,+ peer: IpAddr,+ ) -> Result<SessionExchange, AuthError> {+ self.rate(peer)?;+ let now = now()?;+ if !valid_secret(token) {+ return self.failed(peer);+ }+ let digest = hash(token);+ let Some(id) = self+ .tokens+ .iter()+ .find(|t| {+ t.sha256 == digest+ && !t.metadata.revoked+ && t.metadata.expires.is_none_or(|e| e > now)+ })+ .map(|t| t.metadata.id.clone())+ else {+ return self.failed(peer);+ };+ self.new_session("token", Some(id), now)+ }+ fn new_session(+ &mut self,+ kind: &'static str,+ token_id: Option<String>,+ now: u64,+ ) -> Result<SessionExchange, AuthError> {+ self.expire(now)?;+ let secret = random()?;+ let identity = SessionIdentity {+ id: random()?.to_string(),+ credential_kind: kind,+ token_id,+ expires: now + IDLE_TTL,+ };+ if self.sessions.len() >= 16 {+ let oldest = self+ .sessions+ .iter()+ .min_by_key(|(_, session)| session.last_access)+ .map(|(key, _)| key.clone())+ .ok_or(AuthError::Unavailable)?;+ self.remove_session(&oldest, "session_evicted")?;+ }+ self.session_event("session_created", &identity, now)?;+ self.sessions.insert(+ hash(&secret),+ Session {+ identity: identity.clone(),+ created: now,+ last_used: now,+ last_access: Instant::now(),+ },+ );+ Ok(SessionExchange {+ bearer: secret.to_string(),+ session: identity,+ })+ }+ pub fn authenticate(+ &mut self,+ headers: &HeaderMap,+ _peer: IpAddr,+ ) -> Result<SessionIdentity, AuthError> {+ let mut values = headers.get_all(http::header::AUTHORIZATION).iter();+ let value = values+ .next()+ .ok_or(AuthError::Required)?+ .to_str()+ .map_err(|_| AuthError::Required)?;+ if values.next().is_some() {+ return Err(AuthError::Required);+ }+ let bearer = value+ .strip_prefix("Bearer ")+ .filter(|v| valid_secret(v))+ .ok_or(AuthError::Required)?;+ self.authenticate_bearer(bearer)+ }+ fn authenticate_bearer(&mut self, bearer: &str) -> Result<SessionIdentity, AuthError> {+ let now = now()?;+ self.expire(now)?;+ let session = self+ .sessions+ .get_mut(&hash(bearer))+ .ok_or(AuthError::Required)?;+ session.last_used = now;+ session.last_access = Instant::now();+ session.identity.expires = (now + IDLE_TTL).min(session.created + ABSOLUTE_TTL);+ Ok(session.identity.clone())+ }+ pub fn logout(&mut self, headers: &HeaderMap, peer: IpAddr) -> Result<(), AuthError> {+ let identity = self.authenticate(headers, peer)?;+ let key = self+ .sessions+ .iter()+ .find(|(_, s)| s.identity.id == identity.id)+ .map(|(k, _)| k.clone())+ .ok_or(AuthError::Required)?;+ self.remove_session(&key, "session_revoked")+ }+ pub fn session_active(&mut self, id: &str) -> bool {+ now().and_then(|n| self.expire(n)).is_ok()+ && self.sessions.values().any(|s| s.identity.id == id)+ }+ fn expire(&mut self, now: u64) -> Result<(), AuthError> {+ let keys: Vec<_> = self+ .sessions+ .iter()+ .filter(|(_, s)| {+ now >= s.last_used + IDLE_TTL+ || now >= s.created + ABSOLUTE_TTL+ || s.identity.token_id.as_ref().is_some_and(|id| {+ self.tokens.iter().all(|t| {+ t.metadata.id != *id+ || t.metadata.revoked+ || t.metadata.expires.is_some_and(|e| e <= now)+ })+ })+ })+ .map(|(k, _)| k.clone())+ .collect();+ for key in keys {+ self.remove_session(&key, "session_expired")?;+ }+ Ok(())+ }+ fn remove_session(&mut self, key: &str, event: &str) -> Result<(), AuthError> {+ if let Some(session) = self.sessions.remove(key) {+ self.session_event(event, &session.identity, now()?)?;+ }+ Ok(())+ }+ fn credential_event(+ &self,+ event: &str,+ kind: &str,+ token_id: Option<&str>,+ ) -> Result<(), AuthError> {+ store::audit(+ &self.root,+ &AuditEvent {+ at: now()?,+ event,+ session_id: None,+ credential_kind: Some(kind),+ token_id,+ context: None,+ command: None,+ operation_id: None,+ },+ )+ }+ fn session_event(&self, event: &str, s: &SessionIdentity, at: u64) -> Result<(), AuthError> {+ store::audit(+ &self.root,+ &AuditEvent {+ at,+ event,+ session_id: Some(&s.id),+ credential_kind: Some(s.credential_kind),+ token_id: s.token_id.as_deref(),+ context: None,+ command: None,+ operation_id: None,+ },+ )+ }+ /// Fields are supplied from the admitted catalog and validated context, never a body.+ pub fn audit_command(+ &self,+ session: &SessionIdentity,+ context: &str,+ command: &str,+ operation_id: Option<&str>,+ ) -> Result<(), AuthError> {+ if !valid_context(context)+ || command.len() > 80+ || !command.bytes().all(|c| c.is_ascii_lowercase() || c == b'_')+ || operation_id.is_some_and(|v| v.len() > 256 || v.chars().any(char::is_control))+ {+ return Err(AuthError::Invalid);+ }+ store::audit(+ &self.root,+ &AuditEvent {+ at: now()?,+ event: "command",+ session_id: Some(&session.id),+ credential_kind: None,+ token_id: None,+ context: Some(context),+ command: Some(command),+ operation_id,+ },+ )+ }+ fn rate(&mut self, peer: IpAddr) -> Result<(), AuthError> {+ let cutoff = now()?.saturating_sub(60);+ while self.failures.front().is_some_and(|(at, _)| *at <= cutoff) {+ self.failures.pop_front();+ }+ // Remote failures must not consume the owner's local recovery budget.+ let realm_failures = self+ .failures+ .iter()+ .filter(|(_, address)| address.is_loopback() == peer.is_loopback())+ .count();+ if realm_failures >= 64 || self.failures.iter().filter(|(_, p)| *p == peer).count() >= 8 {+ Err(AuthError::RateLimited)+ } else {+ Ok(())+ }+ }+ fn failed<T>(&mut self, peer: IpAddr) -> Result<T, AuthError> {+ self.failures.push_back((now()?, peer));+ Err(AuthError::Invalid)+ }+}+pub fn valid_context(value: &str) -> bool {+ (16..=128).contains(&value.len())+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')+}+fn valid_name(value: &str) -> bool {+ !value.trim().is_empty() && value.len() <= 80 && !value.chars().any(char::is_control)+}+fn valid_secret(value: &str) -> bool {+ value.len() == 64+ && value+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}+fn hash(value: &str) -> String {+ format!("{:x}", Sha256::digest(value.as_bytes()))+}+fn random() -> Result<Zeroizing<String>, AuthError> {+ let mut bytes = Zeroizing::new([0u8; 32]);+ getrandom::fill(bytes.as_mut()).map_err(|_| AuthError::Unavailable)?;+ Ok(Zeroizing::new(+ bytes.iter().map(|b| format!("{b:02x}")).collect(),+ ))+}+fn now() -> Result<u64, AuthError> {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .map_err(|_| AuthError::Unavailable)+}diff --git a/crates/daemon/src/console/auth/store.rs b/crates/daemon/src/console/auth/store.rsnew file mode 100644index 00000000..b35023c7--- /dev/null+++ b/crates/daemon/src/console/auth/store.rs@@ -0,0 +1,107 @@+use super::*;+use hiroute_platform::{durable, private_fs};+use std::io::Read;++pub(super) const MAX_TOKENS: usize = 128;+const MAX_STORE: u64 = 128 * 1024;+const MAX_AUDIT: usize = 1024 * 1024;+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub(super) struct StoredToken {+ #[serde(flatten)]+ pub metadata: TokenMetadata,+ pub sha256: String,+}+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Store {+ schema: String,+ tokens: Vec<StoredToken>,+}++pub(super) fn prepare(root: &std::path::Path) -> Result<(), AuthError> {+ private_fs::prepare_storage_directory(root).map_err(|_| AuthError::Unavailable)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ let metadata = std::fs::symlink_metadata(root).map_err(|_| AuthError::Unavailable)?;+ if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {+ return Err(AuthError::Unavailable);+ }+ }+ Ok(())+}+fn read(root: &std::path::Path, name: &str, limit: u64) -> Result<Option<Vec<u8>>, AuthError> {+ let mut file = match private_fs::open_private_file(&root.join(name)) {+ Ok(file) => file,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(_) => return Err(AuthError::Unavailable),+ };+ private_fs::verify_single_link(&file).map_err(|_| AuthError::Unavailable)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ let metadata = file.metadata().map_err(|_| AuthError::Unavailable)?;+ if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {+ return Err(AuthError::Unavailable);+ }+ }+ let mut bytes = Vec::new();+ file.by_ref()+ .take(limit + 1)+ .read_to_end(&mut bytes)+ .map_err(|_| AuthError::Unavailable)?;+ if bytes.len() as u64 > limit {+ return Err(AuthError::Unavailable);+ }+ Ok(Some(bytes))+}+pub(super) fn load(root: &std::path::Path) -> Result<Vec<StoredToken>, AuthError> {+ let Some(bytes) = read(root, "tokens.json", MAX_STORE)? else {+ return Ok(vec![]);+ };+ let store: Store = serde_json::from_slice(&bytes).map_err(|_| AuthError::Unavailable)?;+ let mut ids = std::collections::BTreeSet::new();+ if store.schema != "hiroute.console-tokens/v1"+ || store.tokens.len() > MAX_TOKENS+ || store.tokens.iter().any(|t| {+ !super::valid_secret(&t.sha256)+ || !super::valid_secret(&t.metadata.id)+ || !super::valid_name(&t.metadata.name)+ || t.metadata.created == 0+ || t.metadata.expires.is_some_and(|e| e <= t.metadata.created)+ || !ids.insert(&t.metadata.id)+ })+ {+ return Err(AuthError::Unavailable);+ }+ Ok(store.tokens)+}+pub(super) fn save(root: &std::path::Path, tokens: &[StoredToken]) -> Result<(), AuthError> {+ let bytes = serde_json::to_vec(&Store {+ schema: "hiroute.console-tokens/v1".into(),+ tokens: tokens.to_vec(),+ })+ .map_err(|_| AuthError::Unavailable)?;+ durable::write_private_atomic(&root.join("tokens.json"), &bytes)+ .map_err(|_| AuthError::Unavailable)+}+/// Append bytes without rewriting or interpreting earlier records. Rotation retains two+/// bounded generations, all published through the platform's private-file boundary.+pub(super) fn audit(root: &std::path::Path, event: &AuditEvent<'_>) -> Result<(), AuthError> {+ let mut bytes = read(root, "audit.jsonl", MAX_AUDIT as u64)?.unwrap_or_default();+ let mut row = serde_json::to_vec(event).map_err(|_| AuthError::Unavailable)?;+ row.push(b'\n');+ if bytes.len() + row.len() > MAX_AUDIT {+ if let Some(previous) = read(root, "audit.1.jsonl", MAX_AUDIT as u64)? {+ durable::write_private_atomic(&root.join("audit.2.jsonl"), &previous)+ .map_err(|_| AuthError::Unavailable)?;+ }+ durable::write_private_atomic(&root.join("audit.1.jsonl"), &bytes)+ .map_err(|_| AuthError::Unavailable)?;+ bytes.clear();+ }+ bytes.extend_from_slice(&row);+ durable::write_private_atomic(&root.join("audit.jsonl"), &bytes)+ .map_err(|_| AuthError::Unavailable)+}diff --git a/crates/daemon/src/console/auth/tests.rs b/crates/daemon/src/console/auth/tests.rsnew file mode 100644index 00000000..9694ab00--- /dev/null+++ b/crates/daemon/src/console/auth/tests.rs@@ -0,0 +1,247 @@+use super::*;+fn auth() -> (tempfile::TempDir, ConsoleAuth) {+ let root = tempfile::tempdir().unwrap();+ let auth = ConsoleAuth::open(root.path()).unwrap();+ (root, auth)+}+fn local_target() -> LaunchTarget {+ LaunchTarget::new("127.0.0.1:5838".parse().unwrap(), true)+}+fn peer() -> IpAddr {+ "127.0.0.1".parse().unwrap()+}+fn headers(bearer: &str) -> HeaderMap {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::AUTHORIZATION,+ format!("Bearer {bearer}").parse().unwrap(),+ );+ h+}+#[test]+fn launch_is_loopback_only_short_lived_and_single_use() {+ let (_root, mut a) = auth();+ let code = a.create_launch(local_target()).unwrap();+ assert!(matches!(+ a.exchange_launch(&code, "192.0.2.1".parse().unwrap(), &local_target().origin),+ Err(AuthError::Invalid)+ ));+ let session = a+ .exchange_launch(&code, peer(), &local_target().origin)+ .unwrap();+ assert!(a.authenticate(&headers(&session.bearer), peer()).is_ok());+ assert!(+ a.exchange_launch(&code, peer(), &local_target().origin)+ .is_err()+ );+ let code = a.create_launch(local_target()).unwrap();+ a.launches.get_mut(&hash(&code)).unwrap().expires = now().unwrap() - 1;+ assert!(+ a.exchange_launch(&code, peer(), &local_target().origin)+ .is_err()+ );+}+#[test]+fn token_revocation_ends_sessions_and_disk_never_contains_credentials() {+ let (root, mut a) = auth();+ let token = a.create_token("Test".into(), None).unwrap();+ let session = a.exchange_token(&token.token, peer()).unwrap();+ a.audit_command(+ &session.session,+ "1234567890abcdef",+ "observation_read",+ Some("operation-one"),+ )+ .unwrap();+ a.revoke_token(&token.metadata.id).unwrap();+ assert!(a.authenticate(&headers(&session.bearer), peer()).is_err());+ for entry in std::fs::read_dir(root.path().join("console")).unwrap() {+ let bytes = std::fs::read_to_string(entry.unwrap().path()).unwrap();+ assert!(!bytes.contains(&token.token));+ assert!(!bytes.contains(&session.bearer));+ }+ let mut reopened = ConsoleAuth::open(root.path()).unwrap();+ assert!(reopened.exchange_token(&token.token, peer()).is_err());+}+#[test]+fn idle_absolute_and_credential_expiry_end_authority() {+ let (_root, mut a) = auth();+ for absolute in [false, true] {+ let code = a.create_launch(local_target()).unwrap();+ let session = a+ .exchange_launch(&code, peer(), &local_target().origin)+ .unwrap();+ let entry = a.sessions.get_mut(&hash(&session.bearer)).unwrap();+ if absolute {+ entry.created = now().unwrap() - ABSOLUTE_TTL;+ } else {+ entry.last_used = now().unwrap() - IDLE_TTL;+ }+ assert!(a.authenticate(&headers(&session.bearer), peer()).is_err());+ }+ let token = a.create_token("Expired".into(), Some(1)).unwrap();+ a.tokens[0].metadata.expires = Some(now().unwrap() - 1);+ assert!(a.exchange_token(&token.token, peer()).is_err());+}+#[test]+fn failed_exchanges_have_per_peer_and_global_bounded_limits() {+ let (_root, mut a) = auth();+ for _ in 0..8 {+ assert_eq!(+ a.exchange_token("invalid", peer()).err(),+ Some(AuthError::Invalid)+ );+ }+ assert_eq!(+ a.exchange_token("invalid", peer()).err(),+ Some(AuthError::RateLimited)+ );+ for i in 0..64 {+ let ip = IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, i + 1));+ assert_eq!(+ a.exchange_token("invalid", ip).err(),+ Some(AuthError::Invalid)+ );+ }+ assert_eq!(+ a.exchange_token("invalid", "198.51.100.1".parse().unwrap())+ .err(),+ Some(AuthError::RateLimited)+ );+ assert_eq!(a.failures.len(), 72);+ let code = a.create_launch(local_target()).unwrap();+ let local = "127.0.0.2".parse().unwrap();+ let session = a+ .exchange_launch(&code, local, &local_target().origin)+ .unwrap();+ assert!(a.authenticate(&headers(&session.bearer), local).is_ok());+ // A separate local peer limit still applies; isolation is not an exemption.+ assert_eq!(+ a.exchange_launch(&code, peer(), &local_target().origin)+ .err(),+ Some(AuthError::RateLimited)+ );+}+#[test]+fn bearer_is_explicit_and_capacity_evicts_the_least_recently_used_session() {+ let (root, mut a) = auth();+ assert!(a.authenticate(&HeaderMap::new(), peer()).is_err());+ let mut sessions = vec![];+ for _ in 0..16 {+ let code = a.create_launch(local_target()).unwrap();+ sessions.push(+ a.exchange_launch(&code, peer(), &local_target().origin)+ .unwrap(),+ );+ }+ // Refresh the oldest session: the second session must now be evicted.+ assert!(+ a.authenticate(&headers(&sessions[0].bearer), peer())+ .is_ok()+ );+ let code = a.create_launch(local_target()).unwrap();+ let newest = a+ .exchange_launch(&code, peer(), &local_target().origin)+ .unwrap();+ assert_eq!(a.sessions.len(), 16);+ assert!(+ a.authenticate(&headers(&sessions[0].bearer), peer())+ .is_ok()+ );+ assert!(+ a.authenticate(&headers(&sessions[1].bearer), peer())+ .is_err()+ );+ assert!(a.authenticate(&headers(&newest.bearer), peer()).is_ok());+ assert!(!a.session_active(&sessions[1].session.id));+ assert!(+ std::fs::read_to_string(root.path().join("console/audit.jsonl"))+ .unwrap()+ .contains("session_evicted")+ );+ let b = ConsoleAuth::open(root.path()).unwrap();+ assert!(b.sessions.is_empty());+}+#[test]+fn invalid_credentials_cannot_evict_sessions_and_local_failures_do_not_block_remote_login() {+ let (_root, mut a) = auth();+ let token = a.create_token("Remote".into(), None).unwrap();+ for _ in 0..16 {+ a.exchange_token(&token.token, peer()).unwrap();+ }+ let before: Vec<_> = a.sessions.keys().cloned().collect();+ assert_eq!(+ a.exchange_token("invalid", peer()).err(),+ Some(AuthError::Invalid)+ );+ assert_eq!(a.sessions.keys().cloned().collect::<Vec<_>>(), before);+ for i in 1..=63 {+ let ip = IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, i + 1));+ assert_eq!(+ a.exchange_token("invalid", ip).err(),+ Some(AuthError::Invalid)+ );+ }+ assert_eq!(+ a.exchange_token("invalid", "127.0.1.1".parse().unwrap())+ .err(),+ Some(AuthError::RateLimited)+ );+ assert!(+ a.exchange_token(&token.token, "192.0.2.1".parse().unwrap())+ .is_ok()+ );+ // The failure window expires without restarting the service.+ let old = now().unwrap() - 61;+ for (at, _) in &mut a.failures {+ *at = old;+ }+ assert!(a.exchange_token(&token.token, peer()).is_ok());+}+#[cfg(unix)]+#[test]+fn foreign_modes_links_and_corrupt_store_are_preserved_and_refused() {+ use std::os::unix::fs::{PermissionsExt, symlink};+ let (root, mut a) = auth();+ a.create_token("One".into(), None).unwrap();+ let path = root.path().join("console/tokens.json");+ let bytes = std::fs::read(&path).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();+ assert!(ConsoleAuth::open(root.path()).is_err());+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ std::fs::remove_file(&path).unwrap();+ let foreign = root.path().join("foreign");+ std::fs::write(&foreign, &bytes).unwrap();+ symlink(&foreign, &path).unwrap();+ assert!(ConsoleAuth::open(root.path()).is_err());+ assert_eq!(std::fs::read(&foreign).unwrap(), bytes);+}++#[test]+fn network_launch_is_origin_port_bound_and_mismatches_do_not_consume_it() {+ let (root, mut auth) = auth();+ let remote: IpAddr = "198.51.100.20".parse().unwrap();+ for address in ["192.0.2.1:5838", "[2001:db8::1]:80"] {+ let target = LaunchTarget::new(address.parse().unwrap(), false);+ let code = auth.create_launch(target.clone()).unwrap();+ for wrong in [+ "http://192.0.2.1:5839",+ "http://127.0.0.1:5838",+ "http://evil.example:5838",+ ] {+ assert_eq!(+ auth.exchange_launch(&code, remote, wrong).err(),+ Some(AuthError::Invalid)+ );+ }+ let session = auth.exchange_launch(&code, remote, &target.origin).unwrap();+ assert!(auth.authenticate(&headers(&session.bearer), remote).is_ok());+ assert_eq!(+ auth.exchange_launch(&code, remote, &target.origin).err(),+ Some(AuthError::Invalid)+ );+ let audit = std::fs::read_to_string(root.path().join("console/audit.jsonl")).unwrap();+ assert!(!audit.contains(code.as_str()));+ assert!(!audit.contains(&session.bearer));+ }+}diff --git a/crates/daemon/src/console/authority.rs b/crates/daemon/src/console/authority.rsnew file mode 100644index 00000000..b61debd3--- /dev/null+++ b/crates/daemon/src/console/authority.rs@@ -0,0 +1,54 @@+use hiroute_application_api::*;+use hiroute_product_session::HostAuthority;+use zeroize::Zeroizing;+pub(crate) struct ConsoleAuthority(pub(crate) crate::control::runtime::RuntimeAuthority);+impl HostAuthority for ConsoleAuthority {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }+ fn has_authority(&self) -> bool {+ true+ }+ fn register_operation(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ operation: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ let secret = Zeroizing::new(hiroute_product_session::random_id()?);+ let expires = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|_| "CLOCK_UNAVAILABLE")?+ .as_secs()+ .checked_add(60)+ .ok_or("CLOCK_UNAVAILABLE")?;+ let registration =+ hiroute_local_storage::ApplyCapabilityRegistrationV1::from_protected_launcher(+ secret.to_string(),+ "desktop",+ hiroute_domain::WorkspaceId::default(),+ operation,+ digest.clone(),+ revisions.clone(),+ i64::try_from(expires).map_err(|_| "CLOCK_UNAVAILABLE")?,+ )+ .map_err(|_| "CAPABILITY_INVALID")?;+ self.0.register_apply_capability(registration)?;+ Ok(secret)+ }+ fn register_input(+ &self,+ candidate: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String> {+ self.0.register_manual_protected_input(+ candidate.clone(),+ hiroute_domain::ProtectedSecret::new(secret.as_bytes().to_vec())+ .map_err(|_| "PROTECTED_INPUT_INVALID")?,+ )+ }+ fn release_model_input(&self, candidate: &ComputeCandidateRefV2) -> Result<(), String> {+ self.0+ .release_manual_protected_input(&candidate.candidate_ref)+ }+}diff --git a/crates/daemon/src/console/contexts.rs b/crates/daemon/src/console/contexts.rsnew file mode 100644index 00000000..c3b62305--- /dev/null+++ b/crates/daemon/src/console/contexts.rs@@ -0,0 +1,275 @@+use super::auth::{AuthError, ConsoleAuth};+use hiroute_client_core::Client;+use hiroute_diagnostics::context::DiagnosticHandle;+use hiroute_product_session::{+ HostAuthority, ProductSession,+ commands::{ClientContext, CommandState, WorkerDependencyConfirmationState},+ web_confirmation::ConfirmationBroker,+};+use std::{+ collections::BTreeMap,+ sync::{+ Arc, Mutex, OnceLock,+ atomic::{AtomicBool, AtomicU64, Ordering},+ },+ time::{Duration, Instant},+};+pub(super) struct Context {+ pub session_id: String,+ id: String,+ session: Arc<tokio::sync::Mutex<Option<ProductSession>>>,+ epoch: AtomicU64,+ active: AtomicBool,+ error: OnceLock<String>,+ pub confirmations: ConfirmationBroker,+ dependencies: WorkerDependencyConfirmationState,+ diagnostics: DiagnosticHandle,+}+impl Context {+ fn new(+ session_id: String,+ id: String,+ client: Client,+ authority: Arc<dyn HostAuthority>,+ diagnostics: DiagnosticHandle,+ ) -> Self {+ Self {+ session_id,+ id,+ session: Arc::new(tokio::sync::Mutex::new(Some(ProductSession::new(+ client, authority,+ )))),+ epoch: AtomicU64::new(0),+ active: AtomicBool::new(true),+ error: OnceLock::new(),+ confirmations: ConfirmationBroker::default(),+ dependencies: WorkerDependencyConfirmationState::default(),+ diagnostics,+ }+ }+ pub async fn command(+ &self,+ name: &str,+ args: serde_json::Value,+ auth: &Mutex<ConsoleAuth>,+ ) -> Result<serde_json::Value, hiroute_product_session::failure::DesktopFailure> {+ let active = || {+ self.active.load(Ordering::Acquire)+ && auth+ .lock()+ .is_ok_and(|mut a| a.session_active(&self.session_id))+ };+ if !active() {+ return Err("CONSOLE_AUTH_REQUIRED".into());+ }+ let window = ClientContext {+ id: &self.id,+ confirmations: &self.confirmations,+ active: &active,+ notify: None,+ };+ let state = CommandState(&self.session, &self.error, &self.epoch, &self.diagnostics);+ hiroute_product_session::commands::dispatch(name, args, &window, &state, &self.dependencies)+ .await+ }+ fn invalidate(&self) {+ self.active.store(false, Ordering::Release);+ self.epoch.fetch_add(1, Ordering::SeqCst);+ self.confirmations.cancel_context(&self.id);+ self.dependencies.cancel_window(&self.id);+ }+ pub async fn close(&self) {+ self.invalidate();+ let mut session = self.session.lock().await;+ if let Some(s) = session.as_mut() {+ s.invalidate_confirmation();+ s.stop_observing();+ let _ = s.close_subscription_check().await;+ }+ *session = None;+ }+}+struct Entry {+ context: Arc<Context>,+ last: Instant,+}+#[derive(Default)]+pub(super) struct Contexts {+ entries: Mutex<BTreeMap<(String, String), Entry>>,+}+impl Contexts {+ pub fn acquire(+ &self,+ session: &str,+ context: &str,+ client: Client,+ authority: Arc<dyn HostAuthority>,+ diagnostics: DiagnosticHandle,+ ) -> Result<Arc<Context>, AuthError> {+ let mut entries = self.entries.lock().map_err(|_| AuthError::Unavailable)?;+ let key = (session.to_owned(), context.to_owned());+ if let Some(entry) = entries.get_mut(&key) {+ entry.last = Instant::now();+ return Ok(entry.context.clone());+ }+ if entries.len() >= 32 || entries.keys().filter(|(s, _)| s == session).count() >= 8 {+ return Err(AuthError::Capacity);+ }+ let value = Arc::new(Context::new(+ session.into(),+ context.into(),+ client,+ authority,+ diagnostics,+ ));+ entries.insert(+ key,+ Entry {+ context: value.clone(),+ last: Instant::now(),+ },+ );+ Ok(value)+ }+ pub fn retire(&self, auth: &Mutex<ConsoleAuth>, all: bool) -> Vec<Arc<Context>> {+ let Ok(mut entries) = self.entries.lock() else {+ return vec![];+ };+ let keys: Vec<_> = entries+ .iter()+ .filter(|(_, e)| {+ all || e.last.elapsed() >= Duration::from_secs(30 * 60)+ || !auth+ .lock()+ .is_ok_and(|mut a| a.session_active(&e.context.session_id))+ })+ .map(|(k, _)| k.clone())+ .collect();+ keys.into_iter()+ .filter_map(|key| entries.remove(&key))+ .map(|entry| {+ entry.context.invalidate();+ entry.context+ })+ .collect()+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ use hiroute_application_api::*;+ use zeroize::Zeroizing;+ #[derive(Default)]+ struct Authority(Mutex<std::collections::BTreeSet<String>>);+ impl HostAuthority for Authority {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }+ fn has_authority(&self) -> bool {+ true+ }+ fn register_operation(+ &self,+ _: &CanonicalDigest,+ _: &RevisionSetV1,+ _: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ Err("unused".into())+ }+ fn register_input(+ &self,+ c: &ComputeCandidateRefV2,+ _: Zeroizing<String>,+ ) -> Result<(), String> {+ self.0.lock().unwrap().insert(c.candidate_ref.clone());+ Ok(())+ }+ fn release_model_input(&self, c: &ComputeCandidateRefV2) -> Result<(), String> {+ self.0.lock().unwrap().remove(&c.candidate_ref);+ Ok(())+ }+ }+ #[tokio::test]+ async fn idle_eviction_expires_confirmations_and_releases_only_owned_inputs() {+ let root = tempfile::tempdir().unwrap();+ let mut auth = ConsoleAuth::open(root.path()).unwrap();+ let target = super::super::auth::LaunchTarget::new("127.0.0.1:5838".parse().unwrap(), true);+ let code = auth.create_launch(target.clone()).unwrap();+ let identity = auth+ .exchange_launch(&code, "127.0.0.1".parse().unwrap(), &target.origin)+ .unwrap()+ .session;+ let auth = Mutex::new(auth);+ let authority = Arc::new(Authority::default());+ let contexts = Contexts::default();+ let client = || {+ Client::new(+ "test",+ hiroute_client_core::LocalEndpoint::from_runtime_root("unused"),+ )+ };+ let old = contexts+ .acquire(+ &identity.id,+ "1234567890abcdef",+ client(),+ authority.clone(),+ DiagnosticHandle::noop(),+ )+ .unwrap();+ let other = contexts+ .acquire(+ &identity.id,+ "abcdef1234567890",+ client(),+ authority.clone(),+ DiagnosticHandle::noop(),+ )+ .unwrap();+ old.session+ .lock()+ .await+ .as_ref()+ .unwrap()+ .authority+ .register_model_input(Zeroizing::new("old".into()))+ .unwrap();+ other+ .session+ .lock()+ .await+ .as_ref()+ .unwrap()+ .authority+ .register_model_input(Zeroizing::new("other".into()))+ .unwrap();+ let (_, answer) = old+ .confirmations+ .begin(+ &old.id,+ hiroute_product_session::web_confirmation::WebConfirmationPrompt {+ title: "Confirm".into(),+ message: "One exact action".into(),+ confirm_label: "Apply".into(),+ cancel_label: "Cancel".into(),+ },+ )+ .unwrap();+ contexts+ .entries+ .lock()+ .unwrap()+ .get_mut(&(identity.id.clone(), old.id.clone()))+ .unwrap()+ .last = Instant::now() - Duration::from_secs(1801);+ let expired = contexts.retire(&auth, false);+ assert_eq!(expired.len(), 1);+ assert!(!answer.await.unwrap());+ expired[0].close().await;+ assert_eq!(authority.0.lock().unwrap().len(), 1);+ for context in contexts.retire(&auth, true) {+ context.close().await;+ }+ assert!(authority.0.lock().unwrap().is_empty());+ }+}diff --git a/crates/daemon/src/console/control.rs b/crates/daemon/src/console/control.rsnew file mode 100644index 00000000..5bbef47d--- /dev/null+++ b/crates/daemon/src/console/control.rs@@ -0,0 +1,107 @@+//! OS-trusted credential minting. A collaboration grant can never enter this path.+use super::auth::{AuthError, ConsoleAuth, LaunchTarget};+use hiroute_application_api::*;+use serde_json::{Value, json};+use std::{+ path::Path,+ sync::{Arc, Mutex, OnceLock},+};++pub trait ConsoleEndpoint: Send + Sync {+ fn launch_target(&self, loopback_only: bool) -> Result<LaunchTarget, AuthError>;+}+pub struct ConsoleControl {+ pub(super) auth: Arc<Mutex<ConsoleAuth>>,+ endpoint: OnceLock<Arc<dyn ConsoleEndpoint>>,+}+impl ConsoleControl {+ pub fn open(data_root: &Path) -> Result<Self, AuthError> {+ Ok(Self {+ auth: Arc::new(Mutex::new(ConsoleAuth::open(data_root)?)),+ endpoint: OnceLock::new(),+ })+ }+ pub fn set_endpoint(&self, endpoint: Arc<dyn ConsoleEndpoint>) -> Result<(), AuthError> {+ self.endpoint+ .set(endpoint)+ .map_err(|_| AuthError::Unavailable)+ }+ pub(crate) fn dispatch(+ &self,+ request: &LocalControlWireRequestV2,+ ) -> Option<MachineEnvelopeV2<Value>> {+ if !matches!(+ request.operation_id.as_str(),+ "CreateConsoleLaunch"+ | "CreateConsoleToken"+ | "ListConsoleTokens"+ | "RevokeConsoleToken"+ ) {+ return None;+ }+ let result = if request.protected_grant.is_some() {+ Err(ErrorCode::CapabilityDenied)+ } else {+ self.execute(request).map_err(|e| match e {+ AuthError::Invalid => ErrorCode::InvalidArguments,+ AuthError::ListenerUnavailable => ErrorCode::ActionRequired,+ _ => ErrorCode::DaemonUnavailable,+ })+ };+ Some(match result {+ Ok(data) => MachineEnvelopeV2::succeeded(data, Some(request.request_id.clone())),+ Err(code) => {+ MachineEnvelopeV2::failed(ErrorV1::new(code), Some(request.request_id.clone()))+ }+ })+ }+ fn execute(&self, request: &LocalControlWireRequestV2) -> Result<Value, AuthError> {+ match request.operation_id.as_str() {+ "CreateConsoleLaunch" => {+ let input: ConsoleLaunchRequestV1 = serde_json::from_value(request.payload.clone())+ .map_err(|_| AuthError::Invalid)?;+ let target = self+ .endpoint+ .get()+ .ok_or(AuthError::Unavailable)?+ .launch_target(input.loopback_only)?;+ let url = target.origin.clone();+ let code = self+ .auth+ .lock()+ .map_err(|_| AuthError::Unavailable)?+ .create_launch(target)?;+ Ok(json!({"url":format!("{url}/launch?code={}", code.as_str()),"expires_in":120}))+ }+ "CreateConsoleToken" => {+ let input: ConsoleCreateTokenRequestV1 =+ serde_json::from_value(request.payload.clone())+ .map_err(|_| AuthError::Invalid)?;+ let created = self+ .auth+ .lock()+ .map_err(|_| AuthError::Unavailable)?+ .create_token(input.name, input.expires_days)?;+ serde_json::to_value(created).map_err(|_| AuthError::Unavailable)+ }+ "ListConsoleTokens" => {+ let _: ConsoleListTokensRequestV1 = serde_json::from_value(request.payload.clone())+ .map_err(|_| AuthError::Invalid)?;+ Ok(+ json!({"tokens":self.auth.lock().map_err(|_|AuthError::Unavailable)?.list_tokens()}),+ )+ }+ "RevokeConsoleToken" => {+ let input: ConsoleRevokeTokenRequestV1 =+ serde_json::from_value(request.payload.clone())+ .map_err(|_| AuthError::Invalid)?;+ self.auth+ .lock()+ .map_err(|_| AuthError::Unavailable)?+ .revoke_token(&input.id)?;+ Ok(json!({"revoked":true}))+ }+ _ => Err(AuthError::Invalid),+ }+ }+}diff --git a/crates/daemon/src/console/host_settings.rs b/crates/daemon/src/console/host_settings.rsnew file mode 100644index 00000000..dcdcf6eb--- /dev/null+++ b/crates/daemon/src/console/host_settings.rs@@ -0,0 +1,208 @@+//! Host effects for the seven product settings commands. No caller-controlled path or process.+use super::server::Server;+use hiroute_host_runtime::*;+use hiroute_product_session::{failure::DesktopFailure, session::query};+use serde::Deserialize;+use serde_json::{Value, json};+use std::sync::Arc;+pub(super) fn is_host_product(name: &str) -> bool {+ matches!(+ name,+ "gateway_listener_status"+ | "gateway_listener_apply"+ | "gateway_listener_recover"+ | "subscription_proxy_status"+ | "subscription_proxy_apply"+ | "diagnostic_status"+ | "set_diagnostic_level"+ )+}+fn empty(args: Value) -> Result<(), DesktopFailure> {+ let _: hiroute_application_api::ClientEmptyRequestV1 =+ serde_json::from_value(args).map_err(|_| "REQUEST_INVALID")?;+ Ok(())+}+pub(super) async fn command(+ server: &Arc<Server>,+ name: &str,+ args: Value,+) -> Result<Value, DesktopFailure> {+ match name {+ "gateway_listener_status" => {+ empty(args)?;+ let config = GatewayListenerStore::new(server.layout.gateway_config_root())+ .load_or_default()+ .map_err(|e| e.to_string())?;+ let address = config+ .applied_address()+ .map_err(|e| e.to_string())?+ .and_then(|a| connect_address(a).ok())+ .map(|a| a.to_string());+ let agents: Value = query(+ &server.client,+ "ListAgents",+ &hiroute_application_api::ClientEmptyRequestV1 {},+ )+ .await?;+ let count = agents.get("agents").and_then(Value::as_array).map(|a| {+ a.iter()+ .filter(|a| a.get("context_id").is_some_and(|id| !id.is_null()))+ .count()+ });+ Ok(+ json!({"config":config,"connect_address":address,"suggested_agent_base_url":address.as_ref().map(|a|format!("http://{a}/v1")),"existing_agent_count":count,"ready":address.is_some()}),+ )+ }+ "gateway_listener_apply" => {+ #[derive(Deserialize)]+ #[serde(rename_all = "snake_case")]+ enum Scope {+ Local,+ External,+ }+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Input {+ scope: Scope,+ #[serde(default)]+ accept_remote_risk: bool,+ }+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Arguments {+ input: Input,+ }+ let input: Arguments = serde_json::from_value(args).map_err(|_| "REQUEST_INVALID")?;+ if matches!(input.input.scope, Scope::External) && !input.input.accept_remote_risk {+ return Err("REMOTE_LISTENER_CONFIRMATION_REQUIRED".into());+ }+ let store = GatewayListenerStore::new(server.layout.gateway_config_root());+ let mut desired = store.load_or_default().map_err(|e| e.to_string())?.desired;+ desired.address = if matches!(input.input.scope, Scope::External) {+ "0.0.0.0"+ } else {+ "127.0.0.1"+ }+ .into();+ store.configure(desired).map_err(|e| e.to_string())?;+ restart(server)?;+ Ok(Value::Null)+ }+ "gateway_listener_recover" => {+ empty(args)?;+ GatewayListenerStore::new(server.layout.gateway_config_root())+ .recover()+ .map_err(|e| e.to_string())?;+ restart(server)?;+ Ok(Value::Null)+ }+ "subscription_proxy_status" => {+ empty(args)?;+ serde_json::to_value(+ SubscriptionProxyStore::new(+ server+ .layout+ .storage_root()+ .parent()+ .ok_or("APP_DATA_UNAVAILABLE")?,+ )+ .view()+ .map_err(|e| e.to_string())?,+ )+ .map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "subscription_proxy_apply" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Arguments {+ policy: SubscriptionProxyPolicy,+ }+ let input: Arguments = serde_json::from_value(args).map_err(|_| "REQUEST_INVALID")?;+ SubscriptionProxyStore::new(+ server+ .layout+ .storage_root()+ .parent()+ .ok_or("APP_DATA_UNAVAILABLE")?,+ )+ .configure(input.policy)+ .map_err(|e| e.to_string())?;+ restart(server)?;+ Ok(Value::Null)+ }+ "diagnostic_status" => {+ empty(args)?;+ diagnostics(server)+ }+ "set_diagnostic_level" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Input {+ expected_revision: u64,+ level: hiroute_diagnostics::level::DiagnosticLevel,+ }+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Arguments {+ input: Input,+ }+ let input: Arguments = serde_json::from_value(args).map_err(|_| "REQUEST_INVALID")?;+ let runtime = server+ .diagnostic_runtime+ .clone()+ .ok_or("DIAGNOSTICS_UNAVAILABLE")?;+ tokio::task::spawn_blocking(move || {+ if runtime.override_active() {+ return Err(DesktopFailure::from("DIAGNOSTIC_OVERRIDE_ACTIVE"));+ }+ if !runtime.wait_armed(std::time::Duration::from_secs(2)) || !runtime.owns_role() {+ return Err("DIAGNOSTICS_UNAVAILABLE".into());+ }+ let settings = runtime.settings().ok_or("DIAGNOSTICS_UNAVAILABLE")?;+ let saved = settings+ .save(input.input.expected_revision, input.input.level)+ .map_err(|e| {+ DesktopFailure::from(+ hiroute_diagnostics::settings::stable_code(&e)+ .as_str()+ .to_owned(),+ )+ })?;+ runtime.apply_saved_level(saved.level, saved.revision);+ Ok(())+ })+ .await+ .map_err(|_| "DIAGNOSTICS_UNAVAILABLE")??;+ diagnostics(server)+ }+ _ => Err("COMMAND_UNKNOWN".into()),+ }+}+fn diagnostics(server: &Server) -> Result<Value, DesktopFailure> {+ let runtime = server+ .diagnostic_runtime+ .as_ref()+ .ok_or("DIAGNOSTICS_UNAVAILABLE")?;+ let status = runtime.status();+ Ok(+ json!({"schema":"hiroute.diagnostic-status/v1","settings":{"revision":status.revision,"level":status.level,"error":status.settings_error.or(status.unavailable).map(hiroute_diagnostics::error::StableErrorCode::from_subsystem_reason)},"logs_directory_available":true}),+ )+}+fn restart(server: &Server) -> Result<(), DesktopFailure> {+ let marker = read_standalone_install_record(&server.layout.marker_path)+ .map_err(|_| "SERVICE_UNAVAILABLE")?;+ let cli = standalone_cli_binary(&marker.install_root);+ std::thread::Builder::new()+ .name("hiroute-console-restart".into())+ .spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(500));+ let _ = std::process::Command::new(cli)+ .args(["service", "restart", "--output", "json"])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status();+ })+ .map_err(|_| "SERVICE_UNAVAILABLE")?;+ Ok(())+}diff --git a/crates/daemon/src/console/http.rs b/crates/daemon/src/console/http.rsnew file mode 100644index 00000000..b85e6e0d--- /dev/null+++ b/crates/daemon/src/console/http.rs@@ -0,0 +1,462 @@+use super::{+ auth::{AuthError, valid_context},+ server::Server,+};+use bytes::Bytes;+use http::{Method, Request, Response, StatusCode, header};+use http_body_util::{BodyExt, Full};+use hyper::body::Incoming;+use serde::Deserialize;+use serde_json::{Value, json};+use std::{convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};+use zeroize::Zeroizing;+const PREFIX: &str = "/api/console/v1";+const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'";+type Reply = Response<Full<Bytes>>;+fn normalize_authority(host: &str, port: u16) -> &str {+ if port == 80 {+ host.strip_suffix(":80").unwrap_or(host)+ } else {+ host+ }+}+pub(super) async fn handle(+ server: Arc<Server>,+ request: Request<Incoming>,+ peer: SocketAddr,+ local: SocketAddr,+) -> Result<Reply, Infallible> {+ // Each request gets the full confirmation window, even on an old keep-alive connection.+ let reply = match tokio::time::timeout(+ Duration::from_secs(100),+ checked(&server, request, peer, local),+ )+ .await+ {+ Ok(Ok(reply)) => reply,+ Ok(Err((status, code))) => failure(status, code),+ Err(_) => failure(StatusCode::REQUEST_TIMEOUT, "CONSOLE_UNAVAILABLE"),+ };+ Ok(headers(reply))+}+/// Every request, including data-free assets, is checked before body collection or dispatch.+pub(super) fn valid_origin(+ headers: &http::HeaderMap,+ local: SocketAddr,+ advertised: Option<SocketAddr>,+) -> bool {+ let mut hosts = headers.get_all(header::HOST).iter();+ let Some(host) = hosts.next().and_then(|h| h.to_str().ok()) else {+ return false;+ };+ if hosts.next().is_some() {+ return false;+ }+ let mut allowed = vec![super::auth::authority(local), local.to_string()];+ if let Some(address) = advertised {+ allowed.extend([super::auth::authority(address), address.to_string()]);+ }+ if local.ip().is_loopback() {+ allowed.extend([+ format!("127.0.0.1:{}", local.port()),+ format!("localhost:{}", local.port()),+ format!("[::1]:{}", local.port()),+ ]);+ if local.port() == 80 {+ allowed.extend(["127.0.0.1".into(), "localhost".into(), "[::1]".into()]);+ }+ }+ if !allowed.iter().any(|a| a == host) {+ return false;+ }+ let mut origins = headers.get_all(header::ORIGIN).iter();+ if let Some(origin) = origins.next()+ && (origin+ .to_str()+ .ok()+ .and_then(|value| value.strip_prefix("http://"))+ .map(|host| normalize_authority(host, local.port()))+ != Some(normalize_authority(host, local.port()))+ || origins.next().is_some())+ {+ return false;+ }+ let mut sites = headers.get_all("sec-fetch-site").iter();+ if let Some(site) = sites.next()+ && (!matches!(site.to_str().ok(), Some("same-origin" | "none")) || sites.next().is_some())+ {+ return false;+ }+ true+}+async fn checked(+ server: &Arc<Server>,+ request: Request<Incoming>,+ peer: SocketAddr,+ local: SocketAddr,+) -> Result<Reply, (StatusCode, &'static str)> {+ if !valid_origin(request.headers(), local, server.advertised_on(local)) {+ return Err((StatusCode::FORBIDDEN, "CONSOLE_ORIGIN_DENIED"));+ }+ // Host was checked above, including duplicates, port and configured advertisement.+ let host = request+ .headers()+ .get(header::HOST)+ .and_then(|v| v.to_str().ok())+ .unwrap_or_default();+ let host = normalize_authority(host, local.port());+ let origin = format!("http://{host}");+ let path = request.uri().path().to_owned();+ let method = request.method().clone();+ if !path.starts_with(PREFIX) {+ if method != Method::GET {+ return Err((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"));+ }+ if let Some(assets) = &server.assets {+ if let Some((mime, bytes)) = assets.get(&path) {+ return Ok(Response::builder()+ .status(StatusCode::OK)+ .header(header::CONTENT_TYPE, mime)+ .body(Full::new(Bytes::copy_from_slice(&bytes)))+ .expect("static response"));+ }+ return Err((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"));+ }+ return Ok(Response::builder().status(StatusCode::SERVICE_UNAVAILABLE).header(header::CONTENT_TYPE,"text/html; charset=utf-8").body(Full::new(Bytes::from_static(b"<!doctype html><html><head><meta charset=\"utf-8\"><title>HiRoute</title></head><body><h1>HiRoute</h1><p>CONSOLE_ASSETS_UNAVAILABLE</p><p>Install the complete HiRoute package to open the console.</p></body></html>"))).expect("static response"));+ }+ let endpoint = path+ .strip_prefix(PREFIX)+ .ok_or((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"))?;+ let public = method == Method::POST && matches!(endpoint, "/session/launch" | "/session/token");+ let identity = if public {+ None+ } else {+ Some(+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .authenticate(request.headers(), peer.ip())+ .map_err(auth_failure)?,+ )+ };+ if endpoint == "/session" {+ let identity = identity.ok_or(auth_failure(AuthError::Required))?;+ if method == Method::GET {+ return Ok(json_reply(+ StatusCode::OK,+ json!({"session":identity,"transport":if peer.ip().is_loopback(){"loopback"}else{"network_plaintext"},"assets_available":server.assets.is_some(),"capabilities":{"host":"console","platform":std::env::consts::OS,"updates":false,"cli_entry":false,"quit":false,"titlebar":false,"directory_reveal":"path","diagnostic_directory":server.layout.diagnostics_root(),"recovery_directory":server.layout.state_root,"clipboard":"browser","save_file":true,"open_external_url":true}}),+ ));+ }+ if method == Method::DELETE {+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .logout(request.headers(), peer.ip())+ .map_err(auth_failure)?;+ for context in server.contexts.retire(&server.control.auth, false) {+ tokio::spawn(async move {+ context.close().await;+ });+ }+ return Ok(json_reply(StatusCode::OK, Value::Null));+ }+ return Err((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"));+ }+ if method != Method::POST {+ return Err((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"));+ }+ if request+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.split(';').next())+ != Some("application/json")+ {+ return Err((StatusCode::UNSUPPORTED_MEDIA_TYPE, "REQUEST_INVALID"));+ }+ let context_id = if public {+ None+ } else {+ let mut contexts = request.headers().get_all("x-hiroute-context").iter();+ let value = contexts+ .next()+ .and_then(|v| v.to_str().ok())+ .filter(|v| valid_context(v))+ .ok_or((StatusCode::BAD_REQUEST, "CLIENT_CONTEXT_INVALID"))?;+ if contexts.next().is_some() {+ return Err((StatusCode::BAD_REQUEST, "CLIENT_CONTEXT_INVALID"));+ }+ Some(value.to_owned())+ };+ let limit = hiroute_application_api::LOCAL_CONTROL_MAX_FRAME_BYTES;+ if request+ .headers()+ .get(header::CONTENT_LENGTH)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.parse::<u64>().ok())+ .is_some_and(|n| n > limit as u64)+ {+ return Err((StatusCode::PAYLOAD_TOO_LARGE, "REQUEST_TOO_LARGE"));+ }+ let mut body = request.into_body();+ let bytes = tokio::time::timeout(Duration::from_secs(10), async {+ let mut bytes = Zeroizing::new(Vec::new());+ while let Some(frame) = body.frame().await {+ let frame = frame.map_err(|_| (StatusCode::BAD_REQUEST, "REQUEST_INVALID"))?;+ if let Ok(data) = frame.into_data() {+ if bytes.len() + data.len() > limit {+ return Err((StatusCode::PAYLOAD_TOO_LARGE, "REQUEST_TOO_LARGE"));+ }+ bytes.extend_from_slice(&data);+ }+ }+ Ok(bytes)+ })+ .await+ .map_err(|_| (StatusCode::REQUEST_TIMEOUT, "REQUEST_INVALID"))??;+ if public {+ let result = if endpoint == "/session/launch" {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Input {+ code: String,+ }+ let input: Input = serde_json::from_slice(&bytes)+ .map_err(|_| (StatusCode::BAD_REQUEST, "REQUEST_INVALID"))?;+ let code = Zeroizing::new(input.code);+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .exchange_launch(&code, peer.ip(), &origin)+ } else {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Input {+ token: String,+ }+ let input: Input = serde_json::from_slice(&bytes)+ .map_err(|_| (StatusCode::BAD_REQUEST, "REQUEST_INVALID"))?;+ let token = Zeroizing::new(input.token);+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .exchange_token(&token, peer.ip())+ }+ .map_err(auth_failure)?;+ return Ok(json_reply(+ StatusCode::OK,+ serde_json::to_value(result).map_err(|_| auth_failure(AuthError::Unavailable))?,+ ));+ }+ let name = endpoint+ .strip_prefix("/command/")+ .filter(|n| !n.contains('/'))+ .ok_or((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"))?;+ let command = hiroute_product_session::catalog::product_command(name)+ .ok_or((StatusCode::NOT_FOUND, "COMMAND_UNKNOWN"))?;+ let args: Value =+ serde_json::from_slice(&bytes).map_err(|_| (StatusCode::BAD_REQUEST, "REQUEST_INVALID"))?;+ let identity = identity.ok_or(auth_failure(AuthError::Required))?;+ let context_id = context_id.ok_or((StatusCode::BAD_REQUEST, "CLIENT_CONTEXT_INVALID"))?;+ for context in server.contexts.retire(&server.control.auth, false) {+ tokio::spawn(async move {+ context.close().await;+ });+ }+ let context = server+ .contexts+ .acquire(+ &identity.id,+ &context_id,+ server.client.clone(),+ server.authority.clone(),+ server.diagnostics.clone(),+ )+ .map_err(auth_failure)?;+ let audited = audited(&command.name);+ if audited {+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .audit_command(&identity, &context_id, name, None)+ .map_err(auth_failure)?;+ }+ let result = if super::host_settings::is_host_product(name) {+ super::host_settings::command(server, name, args).await+ } else {+ context.command(name, args, &server.control.auth).await+ };+ match result {+ Ok(value) => {+ if audited && let Some(operation) = operation_id(&value) {+ server+ .control+ .auth+ .lock()+ .map_err(|_| auth_failure(AuthError::Unavailable))?+ .audit_command(&identity, &context_id, name, Some(operation))+ .map_err(auth_failure)?;+ }+ Ok(json_reply(StatusCode::OK, value))+ }+ Err(error) => Ok(json_reply(+ StatusCode::BAD_REQUEST,+ serde_json::to_value(error)+ .unwrap_or_else(|_| json!({"kind":"native","code":"RESPONSE_DATA_INVALID"})),+ )),+ }+}+fn operation_id(value: &Value) -> Option<&str> {+ value+ .get("operation_id")+ .or_else(|| value.get("operation").and_then(|v| v.get("operation_id")))+ .or_else(|| {+ value+ .get("approval_operation")+ .and_then(|v| v.get("operation_id"))+ })+ .or_else(|| {+ value+ .get("mutation")+ .and_then(|v| v.get("operation"))+ .and_then(|v| v.get("operation_id"))+ })+ .and_then(|v| v.as_str())+}+fn audited(name: &str) -> bool {+ !matches!(+ name,+ "desktop_snapshot"+ | "agent_snapshot"+ | "decision_services"+ | "compute_snapshot"+ | "compute_key_masks"+ | "compute_scan"+ | "compute_subscriptions"+ | "compute_connection_options"+ | "get_subscription_check_result"+ | "get_model_connection_check"+ | "get_compute_save_result"+ | "model_reference_query"+ | "effective_price_query"+ | "plan_editor_options"+ | "worker_settings_get"+ | "worker_executor_availability"+ | "worker_plans"+ | "worker_dependencies_discover"+ | "worker_list"+ | "worker_status"+ | "worker_result"+ | "worker_read"+ | "worker_wait"+ | "observe_operation"+ | "web_confirmation_snapshot"+ | "gateway_listener_status"+ | "subscription_proxy_status"+ | "diagnostic_status"+ )+}+fn auth_failure(error: AuthError) -> (StatusCode, &'static str) {+ (+ match error {+ AuthError::Required | AuthError::Invalid => StatusCode::UNAUTHORIZED,+ AuthError::RateLimited => StatusCode::TOO_MANY_REQUESTS,+ AuthError::Capacity => StatusCode::CONFLICT,+ AuthError::Unavailable | AuthError::ListenerUnavailable => {+ StatusCode::SERVICE_UNAVAILABLE+ }+ },+ error.code(),+ )+}+fn failure(status: StatusCode, code: &str) -> Reply {+ json_reply(+ status,+ serde_json::to_value(hiroute_product_session::failure::DesktopFailure::from(+ code.to_owned(),+ ))+ .unwrap_or(Value::Null),+ )+}+fn json_reply(status: StatusCode, value: Value) -> Reply {+ Response::builder()+ .status(status)+ .header(header::CONTENT_TYPE, "application/json")+ .body(Full::new(Bytes::from(+ serde_json::to_vec(&value).unwrap_or_default(),+ )))+ .expect("fixed response")+}+fn headers(mut response: Reply) -> Reply {+ for (name, value) in [+ ("content-security-policy", CSP),+ ("referrer-policy", "no-referrer"),+ ("x-content-type-options", "nosniff"),+ ("cache-control", "no-store"),+ ] {+ response.headers_mut().insert(+ http::header::HeaderName::from_static(name),+ http::HeaderValue::from_static(value),+ );+ }+ response+}+#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn host_origin_and_fetch_site_are_port_exact() {+ let local = "127.0.0.1:5838".parse().unwrap();+ let mut h = http::HeaderMap::new();+ h.insert(header::HOST, "127.0.0.1:5838".parse().unwrap());+ assert!(valid_origin(&h, local, None));+ h.insert(header::ORIGIN, "http://127.0.0.1:5839".parse().unwrap());+ assert!(!valid_origin(&h, local, None));+ h.insert(header::ORIGIN, "http://127.0.0.1:5838".parse().unwrap());+ assert!(valid_origin(&h, local, None));+ h.insert("sec-fetch-site", "same-site".parse().unwrap());+ assert!(!valid_origin(&h, local, None));+ h.remove("sec-fetch-site");+ h.insert(header::HOST, "evil.example:5838".parse().unwrap());+ assert!(!valid_origin(&h, local, None));+ }+}++#[cfg(test)]+mod advertised_tests {+ use super::*;+ #[test]+ fn advertisement_is_explicit_port_exact_and_default_http_port_works() {+ let mut headers = http::HeaderMap::new();+ let local = "198.51.100.1:5838".parse().unwrap();+ let advertised = "192.0.2.1:5838".parse().unwrap();+ headers.insert(header::HOST, "192.0.2.1:5838".parse().unwrap());+ assert!(!valid_origin(&headers, local, None));+ assert!(valid_origin(&headers, local, Some(advertised)));+ headers.insert(header::HOST, "192.0.2.1:5839".parse().unwrap());+ assert!(!valid_origin(&headers, local, Some(advertised)));+ for (host, origin) in [+ ("192.0.2.1", "http://192.0.2.1"),+ ("192.0.2.1:80", "http://192.0.2.1"),+ ("192.0.2.1", "http://192.0.2.1:80"),+ ] {+ headers.insert(header::HOST, host.parse().unwrap());+ headers.insert(header::ORIGIN, origin.parse().unwrap());+ assert!(valid_origin(+ &headers,+ "198.51.100.1:80".parse().unwrap(),+ Some("192.0.2.1:80".parse().unwrap())+ ));+ }+ }+}diff --git a/crates/daemon/src/console/listener_tests.rs b/crates/daemon/src/console/listener_tests.rsnew file mode 100644index 00000000..f564d266--- /dev/null+++ b/crates/daemon/src/console/listener_tests.rs@@ -0,0 +1,154 @@+//! Live role-all composition, including the absence of side effects from launch minting.+use super::{+ ConsoleService,+ tests::{http, request},+};+use hiroute_application_api::ErrorCode;+use hiroute_host_runtime::{+ ConsoleListenerDesiredV1, ConsoleListenerMode, ConsoleListenerStore, ConsolePortMode,+ StandaloneLayout,+};+use serde_json::json;+use std::net::TcpListener;++#[test]+fn launch_uses_only_startup_listeners_and_preserves_pending_configuration() {+ if crate::test_support::isolated_agent_home(+ "console::listener_tests::launch_uses_only_startup_listeners_and_preserves_pending_configuration",+ ) {+ return;+ }+ if super::tests::installed_test_layout(+ "console::listener_tests::launch_uses_only_startup_listeners_and_preserves_pending_configuration",+ ) {+ return;+ }+ for mode in ["off", "occupied", "loopback", "network"] {+ let directory = crate::test_support::private_tempdir();+ let layout = StandaloneLayout::from_values(+ false,+ Some(directory.path().to_path_buf()),+ None,+ None,+ None,+ )+ .unwrap();+ let held = TcpListener::bind("127.0.0.1:0").unwrap();+ let occupied = held.local_addr().unwrap();+ let store = ConsoleListenerStore::new(layout.gateway_config_root());+ let desired = match mode {+ "off" => ConsoleListenerDesiredV1::default(),+ "occupied" => ConsoleListenerDesiredV1 {+ port_mode: ConsolePortMode::Explicit,+ port: Some(occupied.port()),+ ..ConsoleListenerDesiredV1::loopback()+ },+ "network" => ConsoleListenerDesiredV1 {+ mode: ConsoleListenerMode::Network,+ address: Some("0.0.0.0".parse().unwrap()),+ advertise_address: Some("192.0.2.10".parse().unwrap()),+ allow_plaintext_network: true,+ ..Default::default()+ },+ _ => ConsoleListenerDesiredV1::loopback(),+ };+ store.configure(desired).unwrap();+ let gateway = TcpListener::bind("127.0.0.1:0").unwrap();+ let gateway_address = gateway.local_addr().unwrap();+ drop(gateway);+ let role = crate::start_role_all(+ crate::RoleAllConfig::new(+ layout.storage_root(),+ layout.runtime_root.clone(),+ gateway_address,+ layout.gateway_lkg(),+ )+ .with_released_commands_only(),+ )+ .unwrap();+ let mut console = ConsoleService::start(+ &role,+ layout.clone(),+ directory.path().join("missing-assets"),+ None,+ )+ .unwrap();+ let runtime = tokio::runtime::Runtime::new().unwrap();+ let client = hiroute_client_core::Client::new(+ "cli",+ hiroute_client_core::LocalEndpoint::from_runtime_root(&layout.runtime_root),+ );+ let mint = |payload| {+ runtime+ .block_on(client.call_wire(request("CreateConsoleLaunch", payload)))+ .unwrap()+ };+ if matches!(mode, "off" | "occupied") {+ let before = std::fs::read(store.path()).unwrap();+ for payload in [json!({}), json!({"loopback_only":true}), json!({})] {+ assert_eq!(+ mint(payload).error.unwrap().code,+ ErrorCode::ActionRequired,+ "{mode}"+ );+ }+ assert_eq!(std::fs::read(store.path()).unwrap(), before);+ assert!(store.read().unwrap().applied_address.is_none());+ store+ .configure(ConsoleListenerDesiredV1::loopback())+ .unwrap();+ assert_eq!(+ mint(json!({})).error.unwrap().code,+ ErrorCode::ActionRequired,+ "pending configuration cannot start a listener"+ );+ } else {+ let url = mint(json!({})).data.unwrap()["url"]+ .as_str()+ .unwrap()+ .to_owned();+ let applied = store.read().unwrap().applied_address.unwrap();+ let expected = if mode == "network" {+ format!("http://192.0.2.10:{}", applied.port())+ } else {+ format!("http://{applied}")+ };+ assert!(+ url.starts_with(&format!("{expected}/launch?code=")),+ "{url}"+ );+ let local = mint(json!({"loopback_only":true})).data.unwrap()["url"]+ .as_str()+ .unwrap()+ .to_owned();+ let (address, code) = local+ .strip_prefix("http://")+ .unwrap()+ .split_once("/launch?code=")+ .unwrap();+ let address = address.parse().unwrap();+ assert_eq!(+ http(+ address,+ "/api/console/v1/session/launch",+ Some(json!({"code":code})),+ None,+ ""+ )+ .0,+ 200+ );+ // Saving a new desired scope does not change the active listener or its port.+ store+ .configure(ConsoleListenerDesiredV1::default())+ .unwrap();+ let still_live = mint(json!({})).data.unwrap()["url"]+ .as_str()+ .unwrap()+ .to_owned();+ assert!(still_live.starts_with(&format!("{expected}/launch?code=")));+ }+ console.shutdown();+ role.shutdown();+ }+}diff --git a/crates/daemon/src/console/mod.rs b/crates/daemon/src/console/mod.rsnew file mode 100644index 00000000..68efec11--- /dev/null+++ b/crates/daemon/src/console/mod.rs@@ -0,0 +1,16 @@+//! Authenticated product sessions. The standalone composition owns listener lifetime.+mod assets;+pub mod auth;+pub(crate) mod authority;+mod contexts;+pub mod control;+mod host_settings;+mod http;+mod server;+mod transport;+pub use server::ConsoleService;++#[cfg(all(test, unix))]+mod listener_tests;+#[cfg(all(test, unix))]+mod tests;diff --git a/crates/daemon/src/console/server.rs b/crates/daemon/src/console/server.rsnew file mode 100644index 00000000..b63f9fe0--- /dev/null+++ b/crates/daemon/src/console/server.rs@@ -0,0 +1,218 @@+use super::{+ assets::Assets,+ auth::{AuthError, LaunchTarget},+ contexts::Contexts,+ control::{ConsoleControl, ConsoleEndpoint},+ transport::Connections,+};+use hiroute_diagnostics::context::DiagnosticHandle;+use hiroute_host_runtime::{+ ConsoleListenerDesiredV1, ConsoleListenerMode, ConsoleListenerStore, StandaloneLayout,+};+use hiroute_product_session::HostAuthority;+use std::{+ net::{SocketAddr, TcpListener},+ path::PathBuf,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+};+use tokio_util::sync::CancellationToken;++pub(super) struct Server {+ pub control: Arc<ConsoleControl>,+ pub client: hiroute_client_core::Client,+ pub authority: Arc<dyn HostAuthority>,+ pub diagnostics: DiagnosticHandle,+ pub assets: Option<Assets>,+ pub contexts: Contexts,+ pub layout: StandaloneLayout,+ pub diagnostic_runtime: Option<Arc<hiroute_diagnostics::runtime::DiagnosticRuntime>>,+ pub stop: CancellationToken,+ pub connections: Connections,+ runtime: tokio::runtime::Handle,+ running: AtomicBool,+ endpoints: Mutex<Endpoints>,+ desired: ConsoleListenerDesiredV1,+ store: ConsoleListenerStore,+}+#[derive(Default)]+struct Endpoints {+ primary: Option<SocketAddr>,+ loopback: Option<SocketAddr>,+}+pub struct ConsoleService {+ pub(super) server: Arc<Server>,+ worker: Option<std::thread::JoinHandle<()>>,+}+impl ConsoleService {+ pub fn start(+ role: &crate::RoleAllHandle,+ layout: StandaloneLayout,+ assets: PathBuf,+ diagnostics: Option<Arc<hiroute_diagnostics::runtime::DiagnosticRuntime>>,+ ) -> Result<Self, AuthError> {+ let control = Arc::new(ConsoleControl::open(&layout.data_root)?);+ role.set_console_control(control.clone())+ .map_err(|_| AuthError::Unavailable)?;+ let store = ConsoleListenerStore::new(layout.gateway_config_root());+ let desired = store.read().map_err(|_| AuthError::Unavailable)?.desired;+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(2)+ .enable_all()+ .build()+ .map_err(|_| AuthError::Unavailable)?;+ let stop = CancellationToken::new();+ let server = Arc::new(Server {+ control: control.clone(),+ client: role.console_client(),+ authority: role.console_authority(),+ diagnostics: diagnostics+ .as_ref()+ .map(|d| d.handle().clone())+ .unwrap_or_else(DiagnosticHandle::noop),+ assets: Assets::load(&assets).ok(),+ contexts: Contexts::default(),+ layout,+ diagnostic_runtime: diagnostics,+ stop: stop.clone(),+ connections: Connections::default(),+ runtime: runtime.handle().clone(),+ running: AtomicBool::new(true),+ endpoints: Mutex::new(Endpoints::default()),+ desired,+ store,+ });+ control.set_endpoint(Arc::new(LiveEndpoint(Arc::downgrade(&server))))?;+ let state = server.clone();+ let worker=std::thread::Builder::new().name("hiroute-console".into()).spawn(move||{+ runtime.block_on(async {+ let mut tick=tokio::time::interval(Duration::from_secs(30));+ loop {tokio::select!{_ = stop.cancelled()=>break,_ = tick.tick()=>{for context in state.contexts.retire(&state.control.auth,false){tokio::spawn(async move{context.close().await;});}}}}+ let mut closing=tokio::task::JoinSet::new();for context in state.contexts.retire(&state.control.auth,true){closing.spawn(async move{context.close().await;});}+ let _=tokio::time::timeout(Duration::from_secs(35),async{while closing.join_next().await.is_some(){}}).await;+ });+ runtime.shutdown_timeout(Duration::from_secs(2));+ }).map_err(|_|AuthError::Unavailable)?;+ let service = Self {+ server,+ worker: Some(worker),+ };+ let server = &service.server;+ match server.desired.reserve() {+ Ok(Some(listener)) => {+ let address = listener.local_addr().map_err(|_| AuthError::Unavailable)?;+ server.listen(listener)?;+ let loopback = if server.desired.mode == ConsoleListenerMode::Loopback {+ Some(address)+ } else {+ // Establish the local recovery/shell path at startup as well.+ // Failure here leaves the primary network console usable.+ ConsoleListenerDesiredV1::loopback()+ .reserve()+ .ok()+ .flatten()+ .and_then(|listener| {+ let local = listener.local_addr().ok()?;+ server.listen(listener).ok()?;+ Some(local)+ })+ };+ *server+ .endpoints+ .lock()+ .map_err(|_| AuthError::Unavailable)? = Endpoints {+ primary: Some(address),+ loopback,+ };+ let _ = server.store.mark_applied(Some(address));+ }+ Ok(None) => {+ let _ = server.store.mark_applied(None);+ }+ Err(_) => {+ let _ = server.store.mark_failed();+ }+ }+ Ok(service)+ }+ pub fn shutdown(&mut self) {+ self.server.running.store(false, Ordering::Release);+ self.server.stop.cancel();+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ }+}+impl Drop for ConsoleService {+ fn drop(&mut self) {+ self.shutdown();+ }+}+struct LiveEndpoint(std::sync::Weak<Server>);+impl ConsoleEndpoint for LiveEndpoint {+ fn launch_target(&self, loopback_only: bool) -> Result<LaunchTarget, AuthError> {+ self.0+ .upgrade()+ .ok_or(AuthError::Unavailable)?+ .launch_target(loopback_only)+ }+}+impl Server {+ fn launch_target(&self, loopback_only: bool) -> Result<LaunchTarget, AuthError> {+ if !self.running.load(Ordering::Acquire) {+ return Err(AuthError::Unavailable);+ }+ let bound = self.endpoints.lock().map_err(|_| AuthError::Unavailable)?;+ let address = if loopback_only {+ bound.loopback+ } else {+ bound+ .primary+ .map(|address| self.desired.advertised_socket(address))+ }+ .ok_or(AuthError::ListenerUnavailable)?;+ if address.ip().is_unspecified() {+ return Err(AuthError::ListenerUnavailable);+ }+ Ok(LaunchTarget::new(address, address.ip().is_loopback()))+ }+ /// Advertisement is scoped to the established primary port, not a companion.+ pub(super) fn advertised_on(&self, local: SocketAddr) -> Option<SocketAddr> {+ let bound = self.endpoints.lock().ok()?;+ let primary = bound.primary?;+ (self.desired.mode == ConsoleListenerMode::Network+ && primary.port() == local.port()+ && (primary.ip().is_unspecified() || primary.ip() == local.ip()))+ .then(|| self.desired.advertised_socket(primary))+ }+}+impl Server {+ fn listen(self: &Arc<Self>, listener: TcpListener) -> Result<(), AuthError> {+ listener+ .set_nonblocking(true)+ .map_err(|_| AuthError::Unavailable)?;+ // The OnceLock contains this same Arc. A listener owns only service state, never role-all.+ let entered = self.runtime.enter();+ let listener =+ tokio::net::TcpListener::from_std(listener).map_err(|_| AuthError::Unavailable)?;+ drop(entered);+ let endpoint = self.clone();+ self.runtime.spawn(async move{+ loop{+ let connection=tokio::select!{_ = endpoint.stop.cancelled()=>break,result=listener.accept()=>result};+ let Ok((stream,peer))=connection else{break;};+ let Ok(permit)=endpoint.connections.acquire(peer.ip())else{continue;};+ let Ok(local)=stream.local_addr()else{continue;};let state=endpoint.clone();+ tokio::spawn(async move{+ let _permit=permit;+ let service=hyper::service::service_fn(move|request|super::http::handle(state.clone(),request,peer,local));+ let _=super::transport::serve(stream,service).await;+ });+ }+ });+ Ok(())+ }+}diff --git a/crates/daemon/src/console/tests.rs b/crates/daemon/src/console/tests.rsnew file mode 100644index 00000000..c3d438e6--- /dev/null+++ b/crates/daemon/src/console/tests.rs@@ -0,0 +1,367 @@+//! Real role-all / Local Control / HTTP composition; installed acceptance is a separate gate.+use super::*;+use hiroute_application_api::*;+use hiroute_client_core::{Client, LocalEndpoint};+use hiroute_host_runtime::StandaloneLayout;+use serde_json::{Value, json};+use std::{+ io::{Read, Write},+ net::{SocketAddr, TcpListener, TcpStream},+ time::Duration,+};+pub(super) fn request(operation: &str, payload: Value) -> LocalControlWireRequestV2 {+ LocalControlWireRequestV2 {+ schema_version: LOCAL_CONTROL_SCHEMA_V2,+ request_id: format!("console-{operation}"),+ operation_id: operation.into(),+ payload,+ protected_grant: None,+ }+}+pub(super) fn http(+ address: SocketAddr,+ path: &str,+ body: Option<Value>,+ bearer: Option<&str>,+ extra: &str,+) -> (u16, Value, String) {+ let mut stream = TcpStream::connect(address).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ let body = body.map(|v| v.to_string()).unwrap_or_default();+ let authorization = bearer+ .map(|b| format!("Authorization: Bearer {b}\r\n"))+ .unwrap_or_default();+ write!(stream,"{} {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\nContent-Type: application/json\r\nX-HiRoute-Context: 1234567890abcdef\r\n{authorization}{extra}Content-Length: {}\r\n\r\n{body}",if body.is_empty(){"GET"}else{"POST"},body.len()).unwrap();+ let mut raw = String::new();+ stream.read_to_string(&mut raw).unwrap();+ let (status, content) = raw.split_once("\r\n\r\n").unwrap();+ let code = status.split_whitespace().nth(1).unwrap().parse().unwrap();+ (+ code,+ serde_json::from_str(content).unwrap_or(Value::Null),+ status.into(),+ )+}+// KnownFolders cannot be redirected on Windows; its installed composition uses+// the native standard-user acceptance route instead of this isolated Unix home.+#[cfg(unix)]+#[test]+fn real_role_all_keeps_external_gate_and_console_auth_authority_separate() {+ #[cfg(unix)]+ if crate::test_support::isolated_agent_home(+ "console::tests::real_role_all_keeps_external_gate_and_console_auth_authority_separate",+ ) {+ return;+ }+ if installed_test_layout(+ "console::tests::real_role_all_keeps_external_gate_and_console_auth_authority_separate",+ ) {+ return;+ }+ let directory = crate::test_support::private_tempdir();+ let layout = StandaloneLayout::from_values(+ false,+ Some(directory.path().to_path_buf()),+ None,+ None,+ None,+ )+ .unwrap();+ let held = TcpListener::bind("127.0.0.1:0").unwrap();+ let gateway = held.local_addr().unwrap();+ drop(held);+ let mut role = crate::start_role_all(+ crate::RoleAllConfig::new(+ layout.storage_root(),+ layout.runtime_root.clone(),+ gateway,+ layout.gateway_lkg(),+ )+ .with_released_commands_only(),+ )+ .unwrap();+ let assets = directory.path().join("assets");+ std::fs::create_dir(&assets).unwrap();+ std::fs::write(+ assets.join("index.html"),+ b"<!doctype html><title>HiRoute</title>",+ )+ .unwrap();+ hiroute_host_runtime::ConsoleListenerStore::new(layout.gateway_config_root())+ .configure(hiroute_host_runtime::ConsoleListenerDesiredV1::loopback())+ .unwrap();+ let mut console = ConsoleService::start(&role, layout.clone(), assets, None).unwrap();+ let runtime = tokio::runtime::Runtime::new().unwrap();+ let external = Client::new(+ "cli",+ LocalEndpoint::from_runtime_root(&layout.runtime_root),+ );+ let denied = runtime+ .block_on(external.call_wire(request("GetClientServiceStatus", json!({}))))+ .unwrap();+ assert_eq!(denied.error.unwrap().code, ErrorCode::UnknownCommand);+ let internal = runtime+ .block_on(+ role.console_client()+ .call_wire(request("GetClientServiceStatus", json!({}))),+ )+ .unwrap();+ assert!(internal.error.is_none(), "{:?}", internal.error);+ let mut agent = request("CreateConsoleLaunch", json!({}));+ agent.protected_grant = Some(ProtectedClientGrantV2 {+ principal_kind: PrincipalKind::SealedCollaboration,+ capability: "not-an-owner".into(),+ });+ assert_eq!(+ runtime+ .block_on(external.call_wire(agent))+ .unwrap()+ .error+ .unwrap()+ .code,+ ErrorCode::CapabilityDenied+ );+ let launch = runtime+ .block_on(external.call_wire(request("CreateConsoleLaunch", json!({}))))+ .unwrap()+ .data+ .unwrap();+ let url = launch["url"].as_str().unwrap();+ let (address, code) = url+ .strip_prefix("http://")+ .unwrap()+ .split_once("/launch?code=")+ .unwrap();+ let address: SocketAddr = address.parse().unwrap();+ assert_eq!(+ http(+ address,+ "/api/console/v1/session/launch",+ Some(json!({"code":code})),+ None,+ "Origin: http://evil.example\r\n"+ )+ .0,+ 403+ );+ let (status, exchange, headers) = http(+ address,+ "/api/console/v1/session/launch",+ Some(json!({"code":code})),+ None,+ "",+ );+ assert_eq!(status, 200);+ assert!(+ headers+ .to_ascii_lowercase()+ .contains("content-security-policy:")+ );+ assert!(!headers.to_ascii_lowercase().contains("set-cookie"));+ let bearer = exchange["bearer"].as_str().unwrap();+ assert_eq!(+ http(+ address,+ "/api/console/v1/session/launch",+ Some(json!({"code":code})),+ None,+ ""+ )+ .0,+ 401+ );+ assert_eq!(+ http(address, "/api/console/v1/session", None, None, "").0,+ 401+ );+ assert_eq!(+ http(+ address,+ "/api/console/v1/command/quit_desktop",+ Some(json!({})),+ Some(bearer),+ ""+ )+ .0,+ 404+ );+ let (status, snapshot, _) = http(+ address,+ "/api/console/v1/command/desktop_snapshot",+ Some(json!({})),+ Some(bearer),+ "",+ );+ assert_eq!(status, 200);+ assert_eq!(snapshot["trusted_authority"], true);+ // The same optional native-target arguments used by Desktop must reach the+ // shared session over HTTP, rather than being dropped by the host adapter.+ let missing_profile = directory.path().join("missing-hermes");+ let target = serde_json::to_value(hiroute_domain::AgentNativeTargetV1::Hermes {+ config_root: missing_profile.to_str().unwrap().into(),+ })+ .unwrap();+ let (status, agents, _) = http(+ address,+ "/api/console/v1/command/agent_snapshot",+ Some(json!({"nativeTargets":[target]})),+ Some(bearer),+ "",+ );+ assert_eq!(status, 200, "{agents}");+ let unavailable = agents["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|agent| agent["native_target"] == target)+ .expect("the selected unavailable profile must not fall back");+ assert_eq!(unavailable["configuration_state"], "profile_unavailable");+ assert!(!missing_profile.exists());+ let (status, scan, _) = http(+ address,+ "/api/console/v1/command/compute_scan",+ Some(json!({"nativeTarget":null})),+ Some(bearer),+ "",+ );+ assert_eq!(status, 200, "{scan}");+ assert!(scan["connections"].is_array(), "{scan}");+ assert!(scan.get("sources").is_none());+ let secret = "console-fixture-secret-must-not-be-logged";+ let (status, input, _) = http(+ address,+ "/api/console/v1/command/register_protected_model_input",+ Some(json!({"secret":secret,"sourceId":null})),+ Some(bearer),+ "",+ );+ assert_eq!(status, 200, "{input}");+ assert!(!input.to_string().contains(secret));+ // Exercise capacity through OS-trusted minting and the real HTTP exchange,+ // rather than creating sessions directly in the authentication fixture.+ let login = || {+ let launch = runtime+ .block_on(external.call_wire(request("CreateConsoleLaunch", json!({}))))+ .unwrap()+ .data+ .unwrap();+ let code = launch["url"]+ .as_str()+ .unwrap()+ .split_once("?code=")+ .unwrap()+ .1;+ let (status, session, _) = http(+ address,+ "/api/console/v1/session/launch",+ Some(json!({"code":code})),+ None,+ "",+ );+ assert_eq!(status, 200, "new login must not require a daemon restart");+ session["bearer"].as_str().unwrap().to_owned()+ };+ let sessions: Vec<_> = (0..16).map(|_| login()).collect();+ assert_eq!(+ http(address, "/api/console/v1/session", None, Some(bearer), "").0,+ 401+ );+ assert_eq!(+ http(+ address,+ "/api/console/v1/session",+ None,+ Some(&sessions[0]),+ ""+ )+ .0,+ 200+ );+ let newest = login();+ assert_eq!(+ http(+ address,+ "/api/console/v1/session",+ None,+ Some(&sessions[1]),+ ""+ )+ .0,+ 401+ );+ assert_eq!(+ http(+ address,+ "/api/console/v1/session",+ None,+ Some(&sessions[0]),+ ""+ )+ .0,+ 200+ );+ assert_eq!(+ http(address, "/api/console/v1/session", None, Some(&newest), "").0,+ 200+ );+ role.upgrade_status(hiroute_host_runtime::UpgradeAction::Prepare, "test".into())+ .unwrap();+ assert!(+ runtime+ .block_on(+ role.console_client()+ .call_wire(request("GetClientServiceStatus", json!({})))+ )+ .unwrap()+ .error+ .is_some()+ );+ role.upgrade_status(hiroute_host_runtime::UpgradeAction::Cancel, "test".into())+ .unwrap();+ let audit = std::fs::read_to_string(layout.data_root.join("console/audit.jsonl")).unwrap();+ assert!(audit.contains("register_protected_model_input"));+ assert!(!audit.contains(secret));+ assert!(!audit.contains(bearer));+ assert!(!audit.contains(code));+ assert!(!audit.contains(&newest));+ console.shutdown();+ role.shutdown();+ role.join(Duration::from_secs(30)).unwrap();+}++/// Standalone admission authenticates the adjacent CLI and stable entry even+/// when a composition test never executes the CLI. Reexec in a private layout;+/// never create an alias beside Cargo's shared test binaries. This native test+/// image is only a layout fixture, not installed CLI or provider-call evidence.+#[cfg(unix)]+pub(super) fn installed_test_layout(test: &str) -> bool {+ const CHILD: &str = "HIROUTE_CONSOLE_LAYOUT_TEST";+ if std::env::var(CHILD).as_deref() == Ok(test) {+ return false;+ }+ assert_eq!(+ std::env::var("HIROUTE_ISOLATED_DAEMON_TEST").as_deref(),+ Ok(test)+ );+ let home = crate::control::native_agent_home().unwrap();+ let staged = crate::test_support::private_tempdir();+ let daemon = staged.path().join("hirouted");+ let cli = staged.path().join("hiroute");+ std::fs::copy(std::env::current_exe().unwrap(), &daemon).unwrap();+ std::fs::copy(&daemon, &cli).unwrap();+ let bin = home.join(".local/bin");+ std::fs::create_dir_all(&bin).unwrap();+ std::os::unix::fs::symlink(&cli, bin.join("hiroute")).unwrap();+ let status = std::process::Command::new(&daemon)+ .args(["--exact", test, "--nocapture", "--test-threads=1"])+ .env(CHILD, test)+ .status()+ .unwrap();+ assert!(+ status.success(),+ "installed-layout console composition failed"+ );+ true+}diff --git a/crates/daemon/src/console/transport.rs b/crates/daemon/src/console/transport.rsnew file mode 100644index 00000000..549cf766--- /dev/null+++ b/crates/daemon/src/console/transport.rs@@ -0,0 +1,147 @@+//! Bounded peer admission and socket write progress, independent of request execution.+use bytes::Bytes;+use http::{Request, Response};+use http_body_util::Full;+use hyper::{body::Incoming, service::Service};+use std::{+ convert::Infallible,+ future::Future,+ io::{self, IoSlice},+ net::IpAddr,+ pin::Pin,+ sync::Arc,+ task::{Context, Poll},+ time::Duration,+};+use tokio::{+ io::{AsyncRead, AsyncWrite, ReadBuf},+ sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError},+ time::Sleep,+};++const CONNECTIONS_PER_SCOPE: usize = 64;+const WRITE_PROGRESS_TIMEOUT: Duration = Duration::from_secs(30);++pub(super) struct Connections {+ loopback: Arc<Semaphore>,+ network: Arc<Semaphore>,+}+impl Default for Connections {+ fn default() -> Self {+ Self {+ loopback: Arc::new(Semaphore::new(CONNECTIONS_PER_SCOPE)),+ network: Arc::new(Semaphore::new(CONNECTIONS_PER_SCOPE)),+ }+ }+}+impl Connections {+ pub fn acquire(&self, peer: IpAddr) -> Result<OwnedSemaphorePermit, TryAcquireError> {+ if peer.is_loopback() {+ &self.loopback+ } else {+ &self.network+ }+ .clone()+ .try_acquire_owned()+ }+}++pub(super) async fn serve<I, S>(stream: I, service: S) -> Result<(), hyper::Error>+where+ I: AsyncRead + AsyncWrite + Unpin,+ S: Service<Request<Incoming>, Response = Response<Full<Bytes>>, Error = Infallible>,+{+ hyper::server::conn::http1::Builder::new()+ .timer(hyper_util::rt::TokioTimer::new())+ .header_read_timeout(Duration::from_secs(10))+ .max_buf_size(64 * 1024)+ .serve_connection(+ hyper_util::rt::TokioIo::new(WriteProgress::new(stream)),+ service,+ )+ .await+}++struct WriteProgress<I> {+ inner: I,+ stalled: Option<Pin<Box<Sleep>>>,+}+impl<I> WriteProgress<I> {+ fn new(inner: I) -> Self {+ Self {+ inner,+ stalled: None,+ }+ }+ fn written(+ &mut self,+ cx: &mut Context<'_>,+ result: Poll<io::Result<usize>>,+ ) -> Poll<io::Result<usize>> {+ match result {+ Poll::Pending => {+ // Arm only when bytes cannot reach the socket, never while a service+ // is awaiting an operation or a user confirmation.+ let deadline = self+ .stalled+ .get_or_insert_with(|| Box::pin(tokio::time::sleep(WRITE_PROGRESS_TIMEOUT)));+ if deadline.as_mut().poll(cx).is_ready() {+ Poll::Ready(Err(io::Error::new(+ io::ErrorKind::TimedOut,+ "console response write made no progress",+ )))+ } else {+ Poll::Pending+ }+ }+ ready => {+ if matches!(ready, Poll::Ready(Ok(count)) if count > 0) {+ self.stalled = None;+ }+ ready+ }+ }+ }+}+impl<I: AsyncRead + Unpin> AsyncRead for WriteProgress<I> {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buffer: &mut ReadBuf<'_>,+ ) -> Poll<io::Result<()>> {+ Pin::new(&mut self.get_mut().inner).poll_read(cx, buffer)+ }+}+impl<I: AsyncWrite + Unpin> AsyncWrite for WriteProgress<I> {+ fn poll_write(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ bytes: &[u8],+ ) -> Poll<io::Result<usize>> {+ let this = self.get_mut();+ let result = Pin::new(&mut this.inner).poll_write(cx, bytes);+ this.written(cx, result)+ }+ fn poll_write_vectored(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buffers: &[IoSlice<'_>],+ ) -> Poll<io::Result<usize>> {+ let this = self.get_mut();+ let result = Pin::new(&mut this.inner).poll_write_vectored(cx, buffers);+ this.written(cx, result)+ }+ fn is_write_vectored(&self) -> bool {+ self.inner.is_write_vectored()+ }+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ // TCP flush is a ready no-op, not evidence that pending response bytes moved.+ Pin::new(&mut self.get_mut().inner).poll_flush(cx)+ }+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/daemon/src/console/transport/tests.rs b/crates/daemon/src/console/transport/tests.rsnew file mode 100644index 00000000..3366eb31--- /dev/null+++ b/crates/daemon/src/console/transport/tests.rs@@ -0,0 +1,249 @@+use super::*;+use hiroute_product_session::web_confirmation::{ConfirmationBroker, WebConfirmationPrompt};+use hyper::service::service_fn;+use tokio::{+ io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, DuplexStream},+ task::JoinHandle,+};++fn connect<S>(+ connections: &Connections,+ peer: &str,+ service: S,+) -> (+ BufReader<DuplexStream>,+ JoinHandle<Result<(), hyper::Error>>,+)+where+ S: Service<Request<Incoming>, Response = Response<Full<Bytes>>, Error = Infallible>+ + Send+ + 'static,+ S::Future: Send,+{+ // Deliberately small buffers make socket backpressure deterministic. The+ // production Hyper owner, write watchdog and permit lifetime remain intact.+ let (client, server) = tokio::io::duplex(1024);+ let permit = connections.acquire(peer.parse().unwrap()).unwrap();+ let task = tokio::spawn(async move {+ let _permit = permit;+ serve(server, service).await+ });+ (BufReader::new(client), task)+}++async fn send(client: &mut BufReader<DuplexStream>, path: &str) {+ client+ .get_mut()+ .write_all(format!("GET {path} HTTP/1.1\r\nHost: localhost\r\n\r\n").as_bytes())+ .await+ .unwrap();+}++async fn response(client: &mut BufReader<DuplexStream>) -> Vec<u8> {+ let mut line = String::new();+ client.read_line(&mut line).await.unwrap();+ assert!(line.starts_with("HTTP/1.1 200 "), "{line:?}");+ let mut length = None;+ loop {+ line.clear();+ assert_ne!(client.read_line(&mut line).await.unwrap(), 0);+ if line == "\r\n" {+ break;+ }+ if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ length = Some(value.trim().parse::<usize>().unwrap());+ }+ }+ let mut bytes = vec![0; length.expect("full response has a known length")];+ client.read_exact(&mut bytes).await.unwrap();+ bytes+}++#[test]+fn peer_pools_have_independent_limits_and_release_on_drop() {+ let connections = Connections::default();+ let network = (0..CONNECTIONS_PER_SCOPE)+ .map(|_| connections.acquire("192.0.2.1".parse().unwrap()).unwrap())+ .collect::<Vec<_>>();+ assert!(connections.acquire("2001:db8::1".parse().unwrap()).is_err());+ let loopback = (0..CONNECTIONS_PER_SCOPE)+ .map(|index| {+ let peer = if index % 2 == 0 { "127.0.0.1" } else { "::1" };+ connections.acquire(peer.parse().unwrap()).unwrap()+ })+ .collect::<Vec<_>>();+ assert!(connections.acquire("127.0.0.1".parse().unwrap()).is_err());+ drop(network);+ assert!(connections.acquire("192.0.2.1".parse().unwrap()).is_ok());+ assert!(connections.acquire("::1".parse().unwrap()).is_err());+ drop(loopback);+ assert!(connections.acquire("::1".parse().unwrap()).is_ok());+}++#[tokio::test(start_paused = true)]+async fn stalled_network_responses_leave_loopback_usable_and_release_their_permits() {+ let connections = Connections::default();+ let mut clients = Vec::new();+ let mut tasks = Vec::new();+ for _ in 0..CONNECTIONS_PER_SCOPE {+ let (mut client, task) = connect(+ &connections,+ "192.0.2.1",+ service_fn(|_| async {+ Ok::<_, Infallible>(Response::new(Full::new(Bytes::from(vec![b'x'; 64 * 1024]))))+ }),+ );+ send(&mut client, "/bundle.js").await;+ clients.push(client); // No response bytes are read from these peers.+ tasks.push(task);+ }+ tokio::task::yield_now().await;+ assert_eq!(connections.network.available_permits(), 0);+ assert!(connections.acquire("192.0.2.2".parse().unwrap()).is_err());++ let (mut local, local_task) = connect(+ &connections,+ "127.0.0.1",+ service_fn(|_| async {+ Ok::<_, Infallible>(Response::new(Full::new(Bytes::from_static(b"local ready"))))+ }),+ );+ send(&mut local, "/").await;+ assert_eq!(response(&mut local).await, b"local ready");+ drop(local);+ local_task.await.unwrap().unwrap();++ tokio::time::advance(WRITE_PROGRESS_TIMEOUT + Duration::from_secs(1)).await;+ for task in tasks {+ let result = tokio::time::timeout(Duration::from_secs(1), task)+ .await+ .expect("stalled write must close without the peer disconnecting")+ .unwrap();+ assert!(result.is_err(), "stalled write must close");+ }+ assert_eq!(+ connections.network.available_permits(),+ CONNECTIONS_PER_SCOPE+ );+ assert_eq!(clients.len(), CONNECTIONS_PER_SCOPE);+ // Reclamation happened while all unread peers were still open.+ assert!(connections.acquire("192.0.2.2".parse().unwrap()).is_ok());+}++#[tokio::test(start_paused = true)]+async fn successful_byte_progress_refreshes_the_write_deadline() {+ let (mut reader, writer) = tokio::io::duplex(1);+ let writer = tokio::spawn(async move { WriteProgress::new(writer).write_all(b"abcdef").await });+ tokio::task::yield_now().await;+ let mut received = Vec::new();+ for _ in 0..6 {+ tokio::time::advance(Duration::from_secs(20)).await;+ received.push(reader.read_u8().await.unwrap());+ tokio::task::yield_now().await;+ }+ // Total transfer time exceeds both the progress timeout and the former+ // connection lifetime, but each stalled interval is shorter than 30 s.+ writer.await.unwrap().unwrap();+ assert_eq!(received, b"abcdef");+}++#[tokio::test(start_paused = true)]+async fn ready_flush_does_not_refresh_a_stalled_vectored_write() {+ let (_reader, writer) = tokio::io::duplex(1);+ let mut writer = WriteProgress::new(writer);+ writer.write_all(b"x").await.unwrap();+ let buffers = [IoSlice::new(b"y"), IoSlice::new(b"z")];+ let poll_write = |writer: &mut WriteProgress<DuplexStream>| {+ let mut context = Context::from_waker(std::task::Waker::noop());+ Pin::new(writer).poll_write_vectored(&mut context, &buffers)+ };+ assert!(poll_write(&mut writer).is_pending());+ tokio::time::advance(Duration::from_secs(29)).await;+ writer.flush().await.unwrap();+ tokio::time::advance(Duration::from_secs(2)).await;+ match poll_write(&mut writer) {+ Poll::Ready(Err(error)) => assert_eq!(error.kind(), io::ErrorKind::TimedOut),+ result => panic!("a no-op flush cannot extend a stalled write: {result:?}"),+ }+}++#[tokio::test(start_paused = true)]+async fn aged_keep_alive_keeps_the_full_confirmation_window() {+ let connections = Connections::default();+ let broker = Arc::new(ConfirmationBroker::default());+ let confirmations = broker.clone();+ let (mut client, task) = connect(+ &connections,+ "::1",+ service_fn(move |request: Request<Incoming>| {+ let broker = confirmations.clone();+ async move {+ let body = if request.uri().path() == "/confirm" {+ assert!(+ broker+ .request(+ "owner",+ WebConfirmationPrompt {+ title: "Apply verified change".into(),+ message: "Confirm the exact previewed intent.".into(),+ confirm_label: "Apply".into(),+ cancel_label: "Cancel".into(),+ }+ )+ .await+ );+ b"accepted".as_slice()+ } else {+ b"ready".as_slice()+ };+ Ok::<_, Infallible>(Response::new(Full::new(Bytes::from_static(body))))+ }+ }),+ );+ send(&mut client, "/").await;+ assert_eq!(response(&mut client).await, b"ready");+ for _ in 0..12 {+ tokio::time::advance(Duration::from_secs(9)).await;+ send(&mut client, "/").await;+ assert_eq!(response(&mut client).await, b"ready");+ }+ send(&mut client, "/confirm").await;+ tokio::task::yield_now().await;+ let prompt = broker+ .snapshot("owner")+ .expect("service is awaiting confirmation");+ tokio::time::advance(Duration::from_secs(59)).await;+ assert!(+ !task.is_finished(),+ "confirmation wait must not arm a write timer"+ );+ assert!(broker.snapshot("owner").is_some());+ broker+ .resolve("owner", &prompt.confirmation_id, true)+ .unwrap();+ assert_eq!(response(&mut client).await, b"accepted");+ send(&mut client, "/").await;+ assert_eq!(response(&mut client).await, b"ready");+ drop(client);+ task.await.unwrap().unwrap();+}++#[tokio::test(start_paused = true)]+async fn idle_headers_still_expire_and_release_the_connection() {+ let connections = Connections::default();+ let (client, task) = connect(+ &connections,+ "127.0.0.1",+ service_fn(|_| async {+ Ok::<_, Infallible>(Response::new(Full::new(Bytes::from_static(b"ready"))))+ }),+ );+ tokio::task::yield_now().await;+ tokio::time::advance(Duration::from_secs(11)).await;+ assert!(task.await.unwrap().is_err());+ assert_eq!(+ connections.loopback.available_permits(),+ CONNECTIONS_PER_SCOPE+ );+ drop(client);+}diff --git a/crates/daemon/src/control/bin.rs b/crates/daemon/src/control/bin.rsindex 7efd6542..7beb89ab 100644--- a/crates/daemon/src/control/bin.rs+++ b/crates/daemon/src/control/bin.rs@@ -39,6 +39,8 @@ const PROTECTED_FRAME_DEADLINE: Duration = Duration::from_secs(2);struct Arguments {role: Option<String>,standalone: bool,+ #[cfg(debug_assertions)]+ console_assets: Option<PathBuf>,#[cfg(windows)]windows_service: Option<String>,#[cfg(windows)]@@ -198,13 +200,13 @@ fn run_daemon(None => None,};// Diagnostics start as soon as the root is known and never wait for business readiness.- let diagnostics = DiagnosticRuntime::start(RuntimeConfig {+ let diagnostics = std::sync::Arc::new(DiagnosticRuntime::start(RuntimeConfig {root: diagnostics_root(&arguments),role: hiroute_diagnostics::event::ProcessRole::Daemon,component: Component::Daemon,parent_session_id: parent_session,level_override,- });+ }));hiroute_diagnostics::panic::install_panic_hook(diagnostics.handle().clone());let result = match arguments.role.as_deref() {Some("control") => run_control(arguments, &diagnostics),@@ -324,7 +326,7 @@ fn run_control(arguments: Arguments, diagnostics: &DiagnosticRuntime) -> Result<fn run_all(arguments: Arguments,- diagnostics: &DiagnosticRuntime,+ diagnostics: &std::sync::Arc<DiagnosticRuntime>,#[cfg(windows)] service: Option<hiroute_platform::windows::service::ServiceShutdown>,) -> Result<(), StartupError> {if arguments.standalone {@@ -508,6 +510,8 @@ fn parse_arguments() -> Arguments {match name {"--role" => parsed.role = value(&mut arguments),"--standalone" => parsed.standalone = true,+ #[cfg(debug_assertions)]+ "--console-assets" => parsed.console_assets = value(&mut arguments).map(PathBuf::from),#[cfg(windows)]"--windows-service" => {parsed.windows_service = Some(value(&mut arguments).unwrap_or_else(|| exit_usage()))diff --git a/crates/daemon/src/control/in_process.rs b/crates/daemon/src/control/in_process.rsnew file mode 100644index 00000000..2fe4737b--- /dev/null+++ b/crates/daemon/src/control/in_process.rs@@ -0,0 +1,34 @@+//! The console alone receives this dispatcher. External sockets retain their release gate.+use super::*;+use hiroute_client_core::ControlDispatch;+pub(crate) struct InProcessControl {+ pub daemon: LocalControlDaemon,+ pub budgets: ControlConnectionBudgets,+}+impl ControlDispatch for InProcessControl {+ fn dispatch(&self, request: LocalControlWireRequestV2) -> MachineEnvelopeV2<serde_json::Value> {+ let reject =+ |code| MachineEnvelopeV2::failed(ErrorV1::new(code), Some(request.request_id.clone()));+ if request.schema_version != LOCAL_CONTROL_SCHEMA_V2+ || serde_json::to_vec(&request).map_or(true, |bytes| {+ bytes.len() + 1 > LOCAL_CONTROL_MAX_FRAME_BYTES+ })+ {+ return reject(ErrorCode::InvalidArguments);+ }+ let Some(_upgrade) = self.daemon.upgrade.enter(false) else {+ return reject(ErrorCode::DaemonUnavailable);+ };+ let Some(mut admission) = self.budgets.try_accept() else {+ return reject(ErrorCode::DaemonUnavailable);+ };+ let _wait = match admission.classify(&request.operation_id) {+ Ok(permit) => permit,+ Err(code) => return reject(code),+ };+ let mut daemon = self.daemon.clone();+ daemon.released_commands_only = false;+ daemon.diagnostic_client = Some(hiroute_diagnostics::event::ControlClientName::Console);+ daemon.dispatch_wire(request)+ }+}diff --git a/crates/daemon/src/control/managed.rs b/crates/daemon/src/control/managed.rsindex 3362351e..ef4c9948 100644--- a/crates/daemon/src/control/managed.rs+++ b/crates/daemon/src/control/managed.rs@@ -27,6 +27,8 @@ pub enum ManagedControlPhase {}pub struct ManagedControlHandle {+ pub(crate) daemon: LocalControlDaemon,+ pub(crate) budgets: ControlConnectionBudgets,endpoint: super::ControlEndpoint,phase: Arc<std::sync::Mutex<ManagedControlPhase>>,shutdown: Arc<AtomicBool>,@@ -143,10 +145,13 @@ fn start_control_inner(let worker_phase = Arc::clone(&phase);let worker_shutdown = Arc::clone(&shutdown);let (completion_tx, completion) = std::sync::mpsc::channel();+ let handle_daemon = daemon.clone();+ let budgets = ControlConnectionBudgets::default();+ let worker_budgets = budgets.clone();let worker = std::thread::Builder::new().name("hiroute-local-control".to_owned()).spawn(move || {- let budgets = ControlConnectionBudgets::default();+ let budgets = worker_budgets;let (raw_listener, raw_guard, resolver) = match raw {Some((listener, guard, resolver)) => (Some(listener), Some(guard), Some(resolver)),None => (None, None, None),@@ -174,6 +179,8 @@ fn start_control_inner(}).map_err(|error| ManagedControlError::Start(error.to_string()))?;Ok(ManagedControlHandle {+ daemon: handle_daemon,+ budgets,endpoint,phase,shutdown,diff --git a/crates/daemon/src/control/mod.rs b/crates/daemon/src/control/mod.rsindex b5a49020..76005c67 100644--- a/crates/daemon/src/control/mod.rs+++ b/crates/daemon/src/control/mod.rs@@ -28,7 +28,7 @@ use std::os::unix::net::{UnixListener as LocalListener, UnixStream as LocalStrea#[cfg(any(unix, windows))]mod managed;-mod runtime;+pub(crate) mod runtime;#[cfg(any(unix, windows))]pub(crate) use managed::start_control_with_agent_grants;@@ -96,7 +96,7 @@ impl Drop for CapacityPermit {#[cfg(any(unix, windows))]#[derive(Clone)]-struct ControlConnectionBudgets {+pub(crate) struct ControlConnectionBudgets {total: CapacityCounter,waits: CapacityCounter,unclassified: CapacityCounter,@@ -211,6 +211,8 @@ pub struct LocalControlDaemon {upgrade: Arc<hiroute_host_runtime::UpgradeDrain>,application: ApplicationService,released_commands_only: bool,+ diagnostic_client: Option<hiroute_diagnostics::event::ControlClientName>,+ pub(crate) console: Arc<std::sync::OnceLock<Arc<crate::console::control::ConsoleControl>>>,/// Receive-side diagnostics; a no-op handle keeps every existing host unchanged.diagnostics: DiagnosticHandle,}@@ -221,6 +223,8 @@ impl LocalControlDaemon {upgrade: Arc::new(hiroute_host_runtime::UpgradeDrain::default()),application,released_commands_only: false,+ diagnostic_client: None,+ console: Arc::default(),diagnostics: DiagnosticHandle::noop(),}}@@ -257,6 +261,7 @@ impl LocalControlDaemon {let response = self.dispatch_wire_inner(request);self.diagnostics.try_emit(DiagnosticEvent::ControlCallEnd(ControlCallEnd {+ client_name: self.diagnostic_client,operation,request_token,submission: DiagnosticSubmissionState::Sent,@@ -282,6 +287,29 @@ impl LocalControlDaemon {Some(request.request_id),);}+ if matches!(+ request.operation_id.as_str(),+ "CreateConsoleLaunch"+ | "CreateConsoleToken"+ | "ListConsoleTokens"+ | "RevokeConsoleToken"+ ) {+ if request.protected_grant.is_some() {+ return MachineEnvelopeV2::failed(+ ErrorV1::new(ErrorCode::CapabilityDenied),+ Some(request.request_id),+ );+ }+ if let Some(console) = self.console.get()+ && let Some(response) = console.dispatch(&request)+ {+ return response;+ }+ return MachineEnvelopeV2::failed(+ ErrorV1::new(ErrorCode::DaemonUnavailable),+ Some(request.request_id),+ );+ }let grant_allowed = matches!(request.operation_id.as_str(),"ListWorkPlans"@@ -1250,3 +1278,6 @@ mod tests {server.join().unwrap();}}++mod in_process;+pub(crate) use in_process::InProcessControl;diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rsindex fa96dd39..b9b8d636 100644--- a/crates/daemon/src/control/runtime.rs+++ b/crates/daemon/src/control/runtime.rs@@ -825,15 +825,10 @@ impl ProductionControlRuntime {/// Application receives this registrar or can mint a capability.pub(crate) fn register_apply_capability(&self,- registration: ApplyCapabilityRegistrationV1,+ registration: hiroute_local_storage::ApplyCapabilityRegistrationV1,) -> Result<(), String> {- self.adapter- .stores- .lock()- .map_err(|_| "capability registrar is unavailable".to_owned())?- .apply_capability_registrar()- .register(registration)- .map_err(|error| error.to_string())+ self.protected_authority()+ .register_apply_capability(registration)}}@@ -1682,3 +1677,19 @@ mod worker_dependencies_tests;#[cfg(test)]#[path = "runtime_early_cancel_tests.rs"]mod early_cancel_tests;++pub(crate) use protected_inputs::RuntimeAuthority;+impl RuntimeAuthority {+ pub(crate) fn register_apply_capability(+ &self,+ registration: ApplyCapabilityRegistrationV1,+ ) -> Result<(), String> {+ self.adapter+ .stores+ .lock()+ .map_err(|_| "capability registrar is unavailable".to_owned())?+ .apply_capability_registrar()+ .register(registration)+ .map_err(|error| error.to_string())+ }+}diff --git a/crates/daemon/src/control/runtime/protected_inputs.rs b/crates/daemon/src/control/runtime/protected_inputs.rsindex d34f307c..b2e0bb73 100644--- a/crates/daemon/src/control/runtime/protected_inputs.rs+++ b/crates/daemon/src/control/runtime/protected_inputs.rs@@ -1,6 +1,29 @@use super::*;+#[derive(Clone)]+pub(crate) struct RuntimeAuthority {+ pub(super) adapter: Arc<LocalControlAdapter>,+}impl ProductionControlRuntime {+ pub(crate) fn protected_authority(&self) -> RuntimeAuthority {+ RuntimeAuthority {+ adapter: self.adapter.clone(),+ }+ }+ pub(crate) fn register_manual_protected_input(+ &self,+ candidate: hiroute_application_api::ComputeCandidateRefV2,+ secret: hiroute_domain::ProtectedSecret,+ ) -> Result<(), String> {+ self.protected_authority()+ .register_manual_protected_input(candidate, secret)+ }+ pub(crate) fn release_manual_protected_input(&self, candidate_ref: &str) -> Result<(), String> {+ self.protected_authority()+ .release_manual_protected_input(candidate_ref)+ }+}+impl RuntimeAuthority {pub(crate) fn register_manual_protected_input(&self,candidate: hiroute_application_api::ComputeCandidateRefV2,diff --git a/crates/daemon/src/control/standalone.rs b/crates/daemon/src/control/standalone.rsindex c978a11b..8d374c39 100644--- a/crates/daemon/src/control/standalone.rs+++ b/crates/daemon/src/control/standalone.rs@@ -103,6 +103,7 @@ impl ProtectedInputServer {pub(super) fn run(#[allow(unused_mut)] mut self,mut role: hiroute_daemon::RoleAllHandle,+ mut console: Option<hiroute_daemon::console::ConsoleService>,#[cfg(windows)] service: Option<hiroute_platform::windows::service::ServiceShutdown>,) -> Result<(), String> {let result = (|| {@@ -128,7 +129,7 @@ impl ProtectedInputServer {}#[cfg(windows)]if let Some(server) = self.lifecycle.as_ref()- && server.poll_stop()?+ && server.poll_stop(&role)?{break Ok(());}@@ -142,6 +143,9 @@ impl ProtectedInputServer {std::thread::sleep(Duration::from_millis(20));}})();+ if let Some(console) = console.as_mut() {+ console.shutdown();+ }role.shutdown();let joined = role.join(Duration::from_secs(30))diff --git a/crates/daemon/src/control/standalone/bootstrap.rs b/crates/daemon/src/control/standalone/bootstrap.rsindex 434a223e..0dbe5d11 100644--- a/crates/daemon/src/control/standalone/bootstrap.rs+++ b/crates/daemon/src/control/standalone/bootstrap.rs@@ -140,7 +140,7 @@ fn standalone_private_directory(_path: &std::path::Path) -> Result<(), String> {#[cfg(any(unix, windows))]pub(crate) fn run_all_standalone(arguments: Arguments,- diagnostics: &DiagnosticRuntime,+ diagnostics: &std::sync::Arc<DiagnosticRuntime>,#[cfg(windows)] service: Option<hiroute_platform::windows::service::ServiceShutdown>,) -> Result<(), StartupError> {diagnostics.stage_begin(StartupStage::RootValidate);@@ -223,9 +223,22 @@ pub(crate) fn run_all_standalone(outcome: StartupOutcome::Success,elapsed_ms: diagnostics_elapsed_ms(diagnostics),}));+ let assets = hiroute_host_runtime::read_standalone_install_record(&layout.marker_path)+ .map(|installation| installation.install_root.join("console"))+ .unwrap_or_default();+ #[cfg(debug_assertions)]+ let assets = arguments.console_assets.unwrap_or(assets);+ let console = hiroute_daemon::console::ConsoleService::start(+ &role,+ layout.clone(),+ assets,+ Some(diagnostics.clone()),+ )+ .ok();server.run(role,+ console,#[cfg(windows)]service,)diff --git a/crates/daemon/src/control/standalone/windows.rs b/crates/daemon/src/control/standalone/windows.rsindex 42be2a44..58dd6203 100644--- a/crates/daemon/src/control/standalone/windows.rs+++ b/crates/daemon/src/control/standalone/windows.rs@@ -5,7 +5,7 @@ use std::sync::mpsc::{self, Receiver};use std::time::Instant;use hiroute_platform::local_record::{self, Channel, Direction};-use hiroute_platform::windows::lifecycle::{MAXIMUM, Request, Response, SCHEMA};+use hiroute_platform::windows::lifecycle::{MAXIMUM, Request, Response, SCHEMA, UpgradeResponse};use hiroute_platform::windows::pipe::{Listener, Stream};pub(super) struct LifecycleServer {@@ -33,9 +33,9 @@ impl LifecycleServer {Ok(Self { listener })}- pub(super) fn poll_stop(&self) -> Result<bool, String> {+ pub(super) fn poll_stop(&self, role: &hiroute_daemon::RoleAllHandle) -> Result<bool, String> {match self.listener.accept() {- Ok((stream, _)) => Ok(handle_connection(stream).unwrap_or(false)),+ Ok((stream, _)) => Ok(handle_connection(stream, role).unwrap_or(false)),Err(error)if matches!(error.kind(),@@ -49,7 +49,10 @@ impl LifecycleServer {}}-fn handle_connection(mut stream: Stream) -> Result<bool, String> {+fn handle_connection(+ mut stream: Stream,+ role: &hiroute_daemon::RoleAllHandle,+) -> Result<bool, String> {// Listener verifies the client's actual process SID before returning this stream.stream.set_deadline(Some(Instant::now() + super::IO_TIMEOUT))@@ -58,16 +61,40 @@ fn handle_connection(mut stream: Stream) -> Result<bool, String> {.map_err(|_| "standalone lifecycle request read failed")?;let request: Request =serde_json::from_slice(&body).map_err(|_| "standalone lifecycle request is invalid")?;- if request.schema != SCHEMA || !matches!(request.action.as_str(), "status" | "stop") {+ if request.schema != SCHEMA+ || !matches!(+ request.action.as_str(),+ "status" | "stop" | "upgrade-prepare" | "upgrade-status" | "upgrade-cancel"+ )+ {return Err("standalone lifecycle request is invalid".into());}let stop = request.action == "stop";- let response = serde_json::to_vec(&Response {- schema: SCHEMA.into(),- action: request.action,- pid: std::process::id(),- accepted: true,- })+ let response = if request.action.starts_with("upgrade-") {+ use hiroute_host_runtime::UpgradeAction;+ let action = match request.action.as_str() {+ "upgrade-prepare" => UpgradeAction::Prepare,+ "upgrade-status" => UpgradeAction::Status,+ _ => UpgradeAction::Cancel,+ };+ let status = role.upgrade_status(action, "windows-install".into())?;+ serde_json::to_vec(&UpgradeResponse {+ schema: SCHEMA.into(),+ action: request.action,+ pid: std::process::id(),+ accepted: true,+ paused: status.paused,+ active_calls: status.active_calls,+ active_tasks: status.active_tasks,+ })+ } else {+ serde_json::to_vec(&Response {+ schema: SCHEMA.into(),+ action: request.action,+ pid: std::process::id(),+ accepted: true,+ })+ }.map_err(|_| "standalone lifecycle response is invalid")?;local_record::write(&mut stream,diff --git a/crates/daemon/src/lib.rs b/crates/daemon/src/lib.rsindex 3a09085a..591e46da 100644--- a/crates/daemon/src/lib.rs+++ b/crates/daemon/src/lib.rs@@ -16,3 +16,5 @@ mod publication_failpoint;#[cfg(test)]mod test_support;++pub mod console;diff --git a/crates/daemon/src/role_all.rs b/crates/daemon/src/role_all.rsindex eb471fa1..068019d6 100644--- a/crates/daemon/src/role_all.rs+++ b/crates/daemon/src/role_all.rs@@ -164,6 +164,32 @@ impl ClassifierDiagnosticPort for GatewayClassifierDiagnostic {}impl RoleAllHandle {+ pub(crate) fn console_client(&self) -> hiroute_client_core::Client {+ hiroute_client_core::Client::in_process(+ "console",+ Arc::new(crate::control::InProcessControl {+ daemon: self.control.daemon.clone(),+ budgets: self.control.budgets.clone(),+ }),+ )+ }+ pub(crate) fn console_authority(&self) -> Arc<dyn hiroute_product_session::HostAuthority> {+ Arc::new(crate::console::authority::ConsoleAuthority(+ self._runtime.protected_authority(),+ ))+ }++ pub fn set_console_control(+ &self,+ console: Arc<crate::console::control::ConsoleControl>,+ ) -> Result<(), String> {+ self.control+ .daemon+ .console+ .set(console)+ .map_err(|_| "CONSOLE_ALREADY_STARTED".to_owned())+ }+pub fn control_endpoint(&self) -> &crate::ControlEndpoint {self.control.endpoint()}diff --git a/crates/daemon/tests/pre_gateway_compute_routing.rs b/crates/daemon/tests/pre_gateway_compute_routing.rsindex 8dd5ca53..4e50dd3c 100644--- a/crates/daemon/tests/pre_gateway_compute_routing.rs+++ b/crates/daemon/tests/pre_gateway_compute_routing.rs@@ -321,6 +321,8 @@ fn run_production_path(root: &Path) {assert_eq!(cli, desktop);control.shutdown();control.join(Duration::from_secs(5)).unwrap();+ // The managed handle also owns the in-process dispatcher and its stores.+ drop(control);let options_envelope = request(&application,diff --git a/crates/daemon/tests/support/collaboration_product.py b/crates/daemon/tests/support/collaboration_product.pyindex 4355d622..2c2ae56b 100644--- a/crates/daemon/tests/support/collaboration_product.py+++ b/crates/daemon/tests/support/collaboration_product.py@@ -50,7 +50,8 @@ def run_main_agent(product, binary, upstream, fixture):stdout,_ = prompt(product,[str(binary),'--profile','acp','--patch',str(patch)],fixture['main_marker']+': Read hiroute-collaboration and delegate the native receipt task.','hiroute-main-acceptance/'+upstream.model,- env=dict(product.env,HIROUTE_DSH_MAIN_TOKEN=upstream.token))+ env=dict(product.env,HIROUTE_DSH_MAIN_TOKEN=upstream.token,+ DSH_PERMISSION_MODE='danger-full-access'))assert ('MAIN-AGENT-COMPLETED-'+fixture['artifact']['receipt']).encode() in stdoutreturnif HARNESS == 'pi':diff --git a/crates/daemon/tests/support/dsh_native_context.py b/crates/daemon/tests/support/dsh_native_context.pyindex 6d4a4317..a511c483 100644--- a/crates/daemon/tests/support/dsh_native_context.py+++ b/crates/daemon/tests/support/dsh_native_context.py@@ -1,6 +1,7 @@"""DSH's fixture-owned public patch and opaque history; common journeys own assertions."""import jsonimport os+import subprocessfrom pathlib import Pathfrom native_context_fixture import write_new, protect_configuration@@ -39,6 +40,10 @@ def source_credentials(config, token):return active, (default, home_patch)def prepare_context(product, fixture):+ # DSH roots project Skills at the nearest Git repository. Keep the owned test+ # project independent of any repository above the host's temporary directory.+ subprocess.run(['git', 'init', '--quiet', '--template=', str(fixture['project'])],+ env=product.env, check=True, capture_output=True)root = Path(fixture['config'])fixture['product_storage'] = str(product.storage)write_new(root/'cordis.patch.yml','[]\n')diff --git a/crates/daemon/tests/support/native_acp_client.py b/crates/daemon/tests/support/native_acp_client.pyindex ce04bedf..ab570f11 100644--- a/crates/daemon/tests/support/native_acp_client.py+++ b/crates/daemon/tests/support/native_acp_client.py@@ -4,13 +4,18 @@ import osimport selectimport signalimport subprocess+import sysimport timeimport tempfiledef prompt(product, command, text, selector=None, env=None, timeout=190):stderr = tempfile.TemporaryFile()- process = subprocess.Popen(command,cwd=product.project,env=env or product.env,- stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=stderr,start_new_session=True,umask=0o077)+ # Set the child's private creation mask before exec without preexec_fn (unsafe+ # in threaded fixtures) or Popen's umask argument, absent on Python 3.8.+ private_command = [sys.executable, '-c',+ 'import os,sys;os.umask(0o077);os.execvp(sys.argv[1],sys.argv[1:])', *command]+ process = subprocess.Popen(private_command,cwd=product.project,env=env or product.env,+ stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=stderr,start_new_session=True)pending = bytearray()deadline, updates, counter = time.monotonic()+timeout, [], 0def request(method,params):diff --git a/crates/daemon/tests/support/native_compaction_product.py b/crates/daemon/tests/support/native_compaction_product.pyindex fa1fbaca..0a907ebd 100644--- a/crates/daemon/tests/support/native_compaction_product.py+++ b/crates/daemon/tests/support/native_compaction_product.py@@ -10,6 +10,7 @@ import secretsimport shleximport subprocessimport sys+import timefrom delegation_product import configure_worker_installation, wait_for_worker_result, worker_clifrom native_context_boundaries import source_events@@ -120,6 +121,25 @@ def assert_pi_compaction(path, receipt, recovery=False):return [{'pre_tokens':compact[0]['tokensBefore'],'summary_preserved':True}]+def wait_for_length_prefix(product, fixture, timeout=10):+ """Exercise accepted-stream recovery, independent of TCP frame coalescing."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ run_id = fixture.get('compaction_run_id')+ if run_id:+ code, response = worker_cli(product,+ 'worker read --run ' + run_id + ' --max-bytes 16384 --output json', success=False)+ if code == 0:+ content = response['data']+ if content['content_state'] == 'available' and 'incomplete attempt' in content.get('text', ''):+ fixture['length_prefix_observed'] = True+ return+ else:+ assert response.get('error', {}).get('code') == 'OBSERVATION_UNAVAILABLE', response+ time.sleep(.05)+ raise AssertionError('real Worker did not expose the length-recovery prefix before its terminal frame')++def run(repository, candidate):harness = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')recovery = os.environ.get('HIROUTE_PRODUCT_PI_RECOVERY') == '1'@@ -162,6 +182,8 @@ def run(repository, candidate):protect_configuration(fixture, [script])(product.root / 'native-context.json').write_text(json.dumps(fixture))upstream.reply = oracle.reply+ if recovery:+ upstream.before_incomplete = lambda: wait_for_length_prefix(product, fixture)stage = 'automatic-compaction-in-real-worker'command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project) +' --run-timeout 120 --no-wait --submission-key qoder-compaction --file - --output json')@@ -169,12 +191,16 @@ def run(repository, candidate):fixture['compaction_prompt'] + ': Execute the requested read-only receipt tool, then finish the task.')first = accepted['data']fixture['task_id'] = first['task_id']+ fixture['compaction_run_id'] = first['run_id']result = wait_for_worker_result(product, first['run_id'], timeout=150)assert 'compacted-' + fixture['receipt'] in result['result'], 'missing compacted Worker result'wait_for_resumable_task(product, first['task_id'], first['run_id'])history = exact_history(fixture)report['native_compaction_boundaries'] = (assert_pi_compaction(history[0], oracle.summary_receipt, recovery) if harness == 'pi' else assert_native_compaction(history[0], oracle.summary_receipt))report['recovery_context_edit'] = recovery+ if recovery:+ assert fixture.get('length_prefix_observed'), 'length stop was not an accepted Worker stream'+ report['length_prefix_observed_through_public_cli'] = Truestage = 'continue-native-compacted-history'command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run ' + first['run_id'] +' --run-timeout 120 --no-wait --submission-key qoder-compaction-continue --file - --output json')diff --git a/crates/daemon/tests/support/native_context_fixture.py b/crates/daemon/tests/support/native_context_fixture.pyindex e8abce46..3111f4b7 100644--- a/crates/daemon/tests/support/native_context_fixture.py+++ b/crates/daemon/tests/support/native_context_fixture.py@@ -337,6 +337,7 @@ class NativeContextUpstream:self.controls = Path(controls)self.lock = threading.Lock()self.reply = decision+ self.before_incomplete = Noneself.requests = 0self.rejected_requests = 0self.proxy_trap = None@@ -390,7 +391,9 @@ class NativeContextUpstream:self.send_header('Content-Type', 'text/event-stream')self.send_header('Content-Length', str(sum(map(len, encoded))))self.end_headers()- for frame in encoded:+ for (kind, _), frame in zip(frames, encoded):+ if kind == 'response.incomplete' and owner.before_incomplete is not None:+ owner.before_incomplete()self.wfile.write(frame)self.wfile.flush()diff --git a/crates/daemon/tests/support/pi_discovery_product.py b/crates/daemon/tests/support/pi_discovery_product.pyindex a7050cfd..06c04301 100644--- a/crates/daemon/tests/support/pi_discovery_product.py+++ b/crates/daemon/tests/support/pi_discovery_product.py@@ -59,7 +59,10 @@ def use_imported_route(product, binary, source, saved):providers = next(r['config']['providers'] for r in read_patch(Path(product.env['DSH_HOME'])/'profiles/web/cordis.patch.yml') if r['id']=='llm-pi-ai')else:- providers = json.loads((Path(product.env['DSH_HOME' if HARNESS=='dsh' else 'PI_CODING_AGENT_DIR']) / 'models.json').read_text().removeprefix(NATIVE_PREFIX))['providers']+ text = (Path(product.env['PI_CODING_AGENT_DIR']) / 'models.json').read_text()+ if text.startswith(NATIVE_PREFIX):+ text = text[len(NATIVE_PREFIX):]+ providers = json.loads(text)['providers']ids = [name for name, provider in providers.items() if name.startswith(namespace + '-') and any(m.get('id') == plan['model_alias'] for m in provider.get('models', []))]assert len(ids) == 1selector = ids[0] + '/' + plan['model_alias']diff --git a/crates/daemon/tests/support/quickstart_decision.py b/crates/daemon/tests/support/quickstart_decision.pyindex b0420093..a1577939 100644--- a/crates/daemon/tests/support/quickstart_decision.py+++ b/crates/daemon/tests/support/quickstart_decision.py@@ -60,7 +60,7 @@ def user_prompt(product, candidate, value, expected=0, format='bearer'):raise AssertionError('protected user prompt did not finish')assert sentassert termios.tcgetattr(terminal) == original, 'terminal state was not restored'- assert os.waitstatus_to_exitcode(status) == expected+ assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == expectedoutput = stdout.read_bytes()errors = stderr.read_bytes()product.outputs.extend((bytes(transcript), output, errors))diff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.pyindex 18b1ef05..fb44d5c7 100644--- a/crates/daemon/tests/support/standalone_headless_product.py+++ b/crates/daemon/tests/support/standalone_headless_product.py@@ -343,6 +343,13 @@ for line in sys.stdin:'packages': [{'id': 'fixture:cpa@1'}],'documents': [{'sha256': '0' * 64}],}, sort_keys=True) + '\n')+ console_assets = self.repo / 'apps/desktop/dist'+ assert (console_assets / 'index.html').is_file(), 'build the candidate console frontend before installed-product acceptance'+ staged_console = package_source / 'console'+ shutil.copytree(console_assets, staged_console, symlinks=True)+ for path in staged_console.rglob('*'):+ if path.is_file() and not path.is_symlink():+ path.chmod(0o600)candidate_hiroute = self.root / 'candidate-hiroute'candidate_hirouted = self.root / 'candidate-hirouted'shutil.copy2(source_bin / 'hiroute', candidate_hiroute)@@ -372,7 +379,8 @@ for line in sys.stdin:'--hirouted', str(candidate_hirouted),'--cpa-binary', str(cpa), '--cpa-version', '8.0.4-hiroute.4','--cpa-license', str(license_path),- '--notices', str(package_source / 'notices'), '--output', str(self.package),+ '--notices', str(package_source / 'notices'), '--console-assets', str(staged_console),+ '--output', str(self.package),], cwd=self.repo, env=self.env, capture_output=True, timeout=90)self.outputs.extend((package.stdout, package.stderr))assert package.returncode == 0, package.stderr.decode(errors='replace')diff --git a/crates/daemon/tests/support/windows_background_fixture.rs b/crates/daemon/tests/support/windows_background_fixture.rsindex 6a7859e5..4870153d 100644--- a/crates/daemon/tests/support/windows_background_fixture.rs+++ b/crates/daemon/tests/support/windows_background_fixture.rs@@ -413,6 +413,7 @@ pub fn entry() {| "transaction-verify"| "transaction-fail-install"| "transaction-upgrade-install" => transactions::run(&request),+ "install" | "uninstall" => transactions::maintenance(&request),"command" => {let program = request.program.unwrap();let args = requestdiff --git a/crates/daemon/tests/support/windows_background_standard.rs b/crates/daemon/tests/support/windows_background_standard.rsindex 9c43750f..4aaea0b7 100644--- a/crates/daemon/tests/support/windows_background_standard.rs+++ b/crates/daemon/tests/support/windows_background_standard.rs@@ -32,6 +32,7 @@ pub(super) fn current_owner(request: fixture::Request, bound: Duration) -> Valuelet stage = match request.action.as_str() {"layout" => "layout","command" => "command",+ "install" | "uninstall" => "maintenance","inspect" => "inspect","crash" => "crash","forced-stop" => "forced-stop",@@ -439,14 +440,12 @@ impl Cleanup<'_> {"standard Task cleanup refuses a changed or missing candidate marker");accepted(- command(- &self.input.python,- vec![- self.input.installer.to_string_lossy().into_owned(),- "uninstall".into(),- "--cli".into(),- self.cli.to_string_lossy().into_owned(),- ],+ current_owner(+ fixture::Request {+ action: "uninstall".into(),+ program: Some(self.input.admin_cli.clone()),+ arguments: vec![],+ },Duration::from_secs(90),),"uninstall",@@ -556,13 +555,7 @@ fn task_real_standard_logged_on_owner_installs_runs_recovers_and_uninstalls() {.name;task_absent(fresh_name.clone(), "initial-task");let installed = accepted(- command(- &input.python,- std::iter::once(input.installer.to_string_lossy().into_owned())- .chain(input.install_arguments(false))- .collect(),- Duration::from_secs(90),- ),+ current_owner(input.install_request("install"), Duration::from_secs(90)),"install",);assert!(@@ -576,7 +569,7 @@ fn task_real_standard_logged_on_owner_installs_runs_recovers_and_uninstalls() {let manifest: Value = serde_json::from_slice(&std::fs::read(&input.manifest).unwrap()).unwrap();assert!(record.install_root == cli_path.parent().unwrap()- && record.target == "x86_64-pc-windows-msvc"+ && record.target == hiroute_platform::windows::install::native_target().unwrap()&& Some(record.version.as_str()) == manifest["version"].as_str()&& record.service_definition== layout.data_root.join("service/windows-background.json")@@ -785,9 +778,7 @@ fn task_real_standard_logged_on_owner_installs_runs_recovers_and_uninstalls() {status(cli_path, false);let uninstalled = cleanup.uninstall();assert!(- uninstalled["uninstalled"] == true- && uninstalled["state_preserved"].as_str().map(Path::new)- == Some(cleanup.layout.state_root.as_path()),+ uninstalled["uninstalled"] == true && uninstalled["state_preserved"] == true,"uninstall must succeed while preserving user state");cleanup.armed = false;@@ -819,7 +810,13 @@ fn assert_gui_daemon(path: &Path) {file.read_exact(&mut pe).unwrap();assert_eq!(&pe[..4], b"PE\0\0");assert!(u16::from_le_bytes(pe[20..22].try_into().unwrap()) >= 70);- assert_eq!(u16::from_le_bytes(pe[4..6].try_into().unwrap()), 0x8664);+ assert_eq!(+ u16::from_le_bytes(pe[4..6].try_into().unwrap()),+ hiroute_host_runtime::standalone_install::windows_machine(+ hiroute_platform::windows::install::native_target().unwrap()+ )+ .unwrap()+ );assert_eq!(u16::from_le_bytes(pe[24..26].try_into().unwrap()), 0x20b);assert_eq!(u16::from_le_bytes(pe[92..94].try_into().unwrap()),diff --git a/crates/daemon/tests/support/windows_background_transactions.rs b/crates/daemon/tests/support/windows_background_transactions.rsindex 8eabccc2..4f0929ad 100644--- a/crates/daemon/tests/support/windows_background_transactions.rs+++ b/crates/daemon/tests/support/windows_background_transactions.rs@@ -1,5 +1,5 @@//! Native owner transaction faults and proofs around the shipped installer.-//! This fixture does not edit a journal or invoke a private Python recovery API.+//! Exercises the Rust maintenance CLI; no fixture edits the installation journal.use std::ffi::OsString;use std::fs::File;use std::io::Read;@@ -122,12 +122,6 @@ pub(super) fn run(request: &Request) -> Value {verify_published(&layout)}"transaction-fail-install" | "transaction-upgrade-install" => {- let program = request.program.as_ref().unwrap();- let arguments = request- .arguments- .iter()- .map(OsString::from)- .collect::<Vec<_>>();let before = snapshot(&layout);assert_eq!(before["definition"]["manager"], "task");assert!(before["journal"].is_null());@@ -153,15 +147,7 @@ pub(super) fn run(request: &Request) -> Value {} else {None};- let command = process(- None,- program,- &arguments,- None,- false,- Duration::from_secs(75),- false,- );+ let command = maintenance(request);if let Some(old) = old_daemon {assert!(old.wait(Duration::from_secs(10)).unwrap(),@@ -196,3 +182,32 @@ pub(super) fn run(request: &Request) -> Value {_ => panic!("unknown transaction fixture action"),}}++/// Both real logged-on and alternate-token owners invoke the same private product entry.+pub(super) fn maintenance(request: &Request) -> Value {+ let uninstall = request.action == "uninstall";+ let body = if uninstall {+ assert!(request.arguments.is_empty());+ json!({"schema":"hiroute.windows-uninstall-request/v1"})+ } else {+ assert_eq!(request.arguments.len(), 1);+ json!({"schema":"hiroute.windows-install-request/v1",+ "package_directory":request.arguments[0],"autostart":false})+ };+ process(+ None,+ request.program.as_ref().unwrap(),+ &[+ OsString::from(if uninstall {+ "__windows-uninstall"+ } else {+ "__windows-install"+ }),+ OsString::from("--request-stdin"),+ ],+ Some(&serde_json::to_vec(&body).unwrap()),+ false,+ Duration::from_secs(75),+ false,+ )+}diff --git a/crates/daemon/tests/support/windows_background_upgrade.rs b/crates/daemon/tests/support/windows_background_upgrade.rsindex b305d8e2..534e0f92 100644--- a/crates/daemon/tests/support/windows_background_upgrade.rs+++ b/crates/daemon/tests/support/windows_background_upgrade.rs@@ -9,7 +9,7 @@ pub(super) mod transport;use super::windows_background_upgrade_business::Business;use super::{- Cleanup, Inputs, assert_status, fixture, windows_account, windows_background_task,+ Inputs, assert_status, fixture, windows_account, windows_background_task,windows_token_launcher,};use transport::{Cleanup as TaskCleanup, Owner};@@ -246,206 +246,3 @@ fn task_upgrade(owner: Owner<'_>, session: u32) {"actual committed candidate upgrade: prepared fault/old package rollback, exact saved Source/Key/binding/route/operation/Agent restore identities, authenticated Gateway and retained public usage receipts, untouched external Agent restoration, new entry FileIDs and actual old daemon exit verified");}--/// The independently verified baseline administrator package must be available;-/// the candidate CLI cannot establish trust for different baseline host bytes.-#[test]-#[ignore = "optional SCM upgrade; current-user logged-on Task is the required background contract"]-fn scm_native_two_phase_candidate_upgrade_preserves_saved_route_secret_and_receipts() {- let _privileges = windows_account::Privileges::enable();- let candidate = Inputs::load();- let mut baseline = Inputs::baseline();- let baseline_manifest: Value =- serde_json::from_slice(&std::fs::read(&baseline.manifest).unwrap()).unwrap();- let candidate_manifest: Value =- serde_json::from_slice(&std::fs::read(&candidate.manifest).unwrap()).unwrap();- assert_eq!(baseline_manifest["target"], candidate_manifest["target"]);- assert_ne!(- baseline_manifest["revision"],- candidate_manifest["revision"]- );- assert_ne!(baseline.version_directory, candidate.version_directory);- baseline.admin_cli = fixture::required("HIROUTE_WINDOWS_BASELINE_ADMIN_CLI");- assert_eq!(baseline.admin_cli.file_name().unwrap(), "hiroute.exe");- for (path, name) in [- (baseline.admin_cli.clone(), "bin/hiroute.exe"),- (- baseline.admin_cli.with_file_name("hirouted.exe"),- "bin/hirouted.exe",- ),- (- baseline- .admin_cli- .parent()- .unwrap()- .parent()- .unwrap()- .join("libexec/cliproxyapi.exe"),- "libexec/cliproxyapi.exe",- ),- ] {- super::windows_execution_host::image(&path);- use sha2::{Digest, Sha256};- use std::io::Read;- let mut image = hiroute_platform::windows::security::open_identity(&path, false).unwrap();- let mut hash = Sha256::new();- let mut buffer = [0; 64 * 1024];- loop {- let count = image.read(&mut buffer).unwrap();- if count == 0 {- break;- }- hash.update(&buffer[..count]);- }- assert_eq!(- format!("{:x}", hash.finalize()),- baseline_manifest["files"][name]["sha256"],- "baseline administrator package differs from the actual verified baseline manifest"- );- }- let account = windows_account::Account::create();- let token = account.token.as_ref().unwrap();- let staged = windows_token_launcher::StagedFixture::create(token);- let layout = candidate.owner_layout(token);- let old_cli = baseline.owner_cli(&layout);- assert_eq!(layout["sid"], account.sid);- let pending = baseline.install(token, true);- let mut cleanup = Cleanup {- inputs: &baseline,- token,- cli: old_cli.clone(),- account: Some(&account),- armed: true,- };- assert_eq!(pending["pending_admin"], true);- assert_eq!(pending["completed"], false);- baseline.admin(&account, "install", None);- assert_eq!(baseline.finalize(token, &old_cli)["completed"], true);- fixture::cli(token, &old_cli, &["service", "start"]);- let first = fixture::inspect(token, false);- assert_eq!(first["sid"], account.sid);- assert_eq!(first["session"], 0);- let port = desired_port(&first["gateway"]);- let configured = fixture::cli(- token,- &old_cli,- &[- "gateway",- "set",- "--address",- "127.0.0.1",- "--port",- &port.to_string(),- ],- );- assert_eq!(configured["ready"], true);- let old = fixture::transaction_snapshot(token, true);- let mut business = Business::save(token, &old_cli);- // Preparation invokes the production exact-owner stop, then publishes the- // genuine candidate. No new business runtime is admitted before admin proof.- let prepared = candidate.install(token, true);- cleanup.inputs = &candidate;- let new_cli = candidate.owner_cli(&layout);- cleanup.cli = new_cli.clone();- assert_eq!(prepared["pending_admin"], true);- assert_eq!(prepared["completed"], false);- let pending_snapshot = fixture::transaction_snapshot(token, false);- assert_eq!(pending_snapshot["journal"]["old_marker"], old["marker"]);- assert_eq!(- pending_snapshot["journal"]["old_definition"],- old["definition"]- );- assert_ne!(- pending_snapshot["marker"]["install_root"],- old["marker"]["install_root"]- );- assert_ne!(pending_snapshot["cli_identity"], old["cli_identity"]);- assert_ne!(pending_snapshot["daemon_identity"], old["daemon_identity"]);- let denied = fixture::command(- token,- &new_cli,- vec![- "service".into(),- "start".into(),- "--output".into(),- "json".into(),- ],- );- assert_ne!(- denied["code"], 0,- "prepared SCM upgrade admitted a business runtime"- );- assert_eq!(- candidate.install(token, true),- prepared,- "SCM prepared upgrade was not idempotent"- );- assert_eq!(- fixture::transaction_snapshot(token, false)["journal"],- pending_snapshot["journal"]- );- candidate.admin(&account, "install", None);- assert_eq!(- candidate.install(token, true),- prepared,- "registered upgrade skipped owner finalization"- );- assert_eq!(- fixture::transaction_snapshot(token, false)["journal"],- pending_snapshot["journal"]- );- let denied = fixture::command(- token,- &new_cli,- vec![- "service".into(),- "start".into(),- "--output".into(),- "json".into(),- ],- );- assert_ne!(- denied["code"], 0,- "SCM machine registration alone admitted upgraded business"- );- let finished = candidate.finalize(token, &new_cli);- assert_eq!(finished["completed"], true);- assert_eq!(finished["operation"], "install");- assert_eq!(finished["started"], false);- let upgraded = fixture::transaction_snapshot(token, true);- assert_eq!(upgraded["manifest"], candidate_manifest);- assert_eq!(upgraded["cli_identity"], pending_snapshot["cli_identity"]);- assert_eq!(- upgraded["daemon_identity"],- pending_snapshot["daemon_identity"]- );- assert_status(token, &new_cli, "windows-scm-user", false);- fixture::cli(token, &new_cli, &["service", "start"]);- let current = fixture::inspect(token, false);- assert_eq!(current["sid"], account.sid);- assert_eq!(current["session"], 0);- assert!(current["pid"] != first["pid"] || current["creation_time"] != first["creation_time"]);- assert_eq!(desired_port(¤t["gateway"]), port);- assert_eq!(- current["gateway"]["config"]["desired"],- configured["config"]["desired"]- );- business.recovered(token, &new_cli, false);- business.restore(token, &new_cli);- fixture::cli(token, &new_cli, &["service", "stop"]);- assert_eq!(- candidate.uninstall(token, &new_cli, true)["pending_admin"],- true- );- candidate.admin(&account, "uninstall", None);- assert_eq!(candidate.finalize(token, &new_cli)["completed"], true);- cleanup.armed = false;- super::assert_native_service_absent(upgraded["definition"]["name"].as_str().unwrap());- assert!(!PathBuf::from(layout["marker"].as_str().unwrap()).exists());- drop(cleanup);- drop(staged);- drop(account);- println!(- "actual SCM two-package upgrade: authenticated baseline/candidate administrator packages, prepared/registered reentry, owner finalization, session-zero new daemon, retained Source/Secret/fixed route/Agent restoration and original public request facts verified"- );-}diff --git a/crates/daemon/tests/support/windows_background_upgrade_transport.rs b/crates/daemon/tests/support/windows_background_upgrade_transport.rsindex facdf43b..fc492634 100644--- a/crates/daemon/tests/support/windows_background_upgrade_transport.rs+++ b/crates/daemon/tests/support/windows_background_upgrade_transport.rs@@ -71,49 +71,25 @@ impl Owner<'_> {if let Self::Token(token) = self {return input.install(token, false);}- let result = self.python(input, input.install_arguments(false));+ let result = self.request(input.install_request("install"), Duration::from_secs(90));accepted(&result, "install").clone()}pub(in super::super) fn transaction_install(self, input: &Inputs, action: &str) -> Value {- if let Self::Token(token) = self {- return input.transaction_install(token, action);- }- self.request(+ self.request(input.install_request(action), Duration::from_secs(90))+ }++ pub(in super::super) fn uninstall(self, input: &Inputs, _cli: &Path) -> Value {+ let result = self.request(fixture::Request {- action: action.into(),- program: Some(input.python.clone()),- arguments: std::iter::once(input.installer.to_string_lossy().into_owned())- .chain(input.install_arguments(false))- .collect(),+ action: "uninstall".into(),+ program: Some(input.admin_cli.clone()),+ arguments: vec![],},Duration::from_secs(90),- )- }-- pub(in super::super) fn uninstall(self, input: &Inputs, cli: &Path) -> Value {- if let Self::Token(token) = self {- return input.uninstall(token, cli, false);- }- let result = self.python(- input,- vec![- "uninstall".into(),- "--cli".into(),- cli.to_string_lossy().into_owned(),- ],);accepted(&result, "uninstall").clone()}-- fn python(self, input: &Inputs, arguments: Vec<String>) -> Value {- self.command(- &input.python,- std::iter::once(input.installer.to_string_lossy().into_owned())- .chain(arguments)- .collect(),- )- }}fn accepted<'a>(result: &'a Value, stage: &'static str) -> &'a Value {@@ -140,7 +116,6 @@ impl<'a> Cleanup<'a> {inputs: input,token,cli,- account: None,armed: true,}),Owner::Current => {@@ -190,7 +165,7 @@ fn verified_record(&& record.install_root.file_name().unwrap() == input.version_directory.as_str()&& record.service_definition== layout.data_root.join("service/windows-background.json")- && record.target == "x86_64-pc-windows-msvc",+ && record.target == hiroute_platform::windows::install::native_target().unwrap(),"standard upgrade cleanup requires its exact selected package root and definition");recorddiff --git a/crates/daemon/tests/support/windows_candidate_source.rs b/crates/daemon/tests/support/windows_candidate_source.rsindex 572f8f17..030f6ee0 100644--- a/crates/daemon/tests/support/windows_candidate_source.rs+++ b/crates/daemon/tests/support/windows_candidate_source.rs@@ -7,11 +7,9 @@ use std::path::{Component, Path, PathBuf};use hiroute_platform::windows::security;use sha2::{Digest, Sha256};-const INSTALLER: &[u8] = include_bytes!("../../../../scripts/install-standalone-windows.py");const PACKAGER: &[u8] = include_bytes!("../../../../scripts/package-standalone.py");pub struct Sources {- installer: PathBuf,// Deny mutation/removal through the complete scenario, including owner reexec._held: Vec<File>,}@@ -47,26 +45,18 @@ impl Sources {.unwrap(),};// Explicitly reject a replaced/junction source ancestor before opening files.- let installer = root.join("scripts/install-standalone-windows.py");- let mut held = installer+ let packager = root.join("scripts/package-standalone.py");+ let mut held = packager.parent().unwrap().ancestors().map(retain_directory).collect::<Vec<_>>();- held.push(exact_source(&installer, INSTALLER));held.push(exact_source(&root.join("scripts/package-standalone.py"),PACKAGER,));- Self {- installer,- _held: held,- }- }-- pub fn installer(&self) -> PathBuf {- self.installer.clone()+ Self { _held: held }}pub fn revision() -> Option<&'static str> {@@ -111,7 +101,7 @@ fn exact_source(path: &Path, expected: &[u8]) -> File {let identity = security::open_identity(path, false).unwrap();let mut held = OpenOptions::new().read(true)- // FILE_SHARE_READ only: Python may read, nobody can replace or write.+ // FILE_SHARE_READ only: The packager may read, nobody can replace or write..share_mode(1).open(path).unwrap();@@ -129,7 +119,7 @@ fn exact_source(path: &Path, expected: &[u8]) -> File {assert_eq!(Sha256::digest(&actual),Sha256::digest(expected),- "candidate installer/dependency bytes differ from the compiled source"+ "candidate package producer bytes differ from the compiled source");held}diff --git a/crates/daemon/tests/support/windows_packaged_foreground.rs b/crates/daemon/tests/support/windows_packaged_foreground.rsindex bb6732ea..53fc447b 100644--- a/crates/daemon/tests/support/windows_packaged_foreground.rs+++ b/crates/daemon/tests/support/windows_packaged_foreground.rs@@ -225,7 +225,7 @@ impl Packaged {let manifest: Value = serde_json::from_slice(&bytes).unwrap();assert!(manifest["schema"] == "hiroute.standalone-package/v1");assert!(manifest["distribution"] == "integration-candidate");- assert!(manifest["target"] == "x86_64-pc-windows-msvc");+ assert!(manifest["target"] == hiroute_platform::windows::install::native_target().unwrap());let Some(compiled) = option_env!("HIROUTE_BUILD_SOURCE_SHA") else {panic!("complete-package gate requires its compiled candidate revision")};@@ -239,7 +239,7 @@ impl Packaged {verify_file(&mut archive, &manifest["archive"], MAX_ARCHIVE);let prepared_cli = required("HIROUTE_WINDOWS_ADMIN_CLI");assert!(prepared_cli.file_name().unwrap() == "hiroute.exe");- let prepared = prepared_cli.parent().unwrap().parent().unwrap();+ let prepared = prepared_cli.parent().unwrap();let layout = StandaloneLayout::from_environment().unwrap();let stable = hiroute_host_runtime::standalone_cli_binary(&layout.home.join(".local/bin"));let stable_daemon =@@ -279,7 +279,8 @@ impl Packaged {);for (name, facts) in files {let relative = portable_member(name);- let mut source = held_input(&prepared.join(&relative));+ let mut source =+ held_input(&prepared.join(relative.strip_prefix("bin").unwrap_or(&relative)));verify_file(&mut source, facts, MAX_FILE);if matches!(name.as_str(),@@ -455,7 +456,12 @@ fn verify_pe(file: &mut File) {let mut pe = [0; 6];file.read_exact(&mut pe).unwrap();assert!(- &pe[..4] == b"PE\0\0" && u16::from_le_bytes(pe[4..6].try_into().unwrap()) == 0x8664,+ &pe[..4] == b"PE\0\0"+ && u16::from_le_bytes(pe[4..6].try_into().unwrap())+ == hiroute_host_runtime::standalone_install::windows_machine(+ hiroute_platform::windows::install::native_target().unwrap()+ )+ .unwrap(),"packaged executable is not the actual x64 PE target");}diff --git a/crates/daemon/tests/windows_background.rs b/crates/daemon/tests/windows_background.rsindex 27b7893d..521c02e7 100644--- a/crates/daemon/tests/windows_background.rs+++ b/crates/daemon/tests/windows_background.rs@@ -50,10 +50,8 @@ fn assert_no_secret(bytes: &[u8]) {}struct Inputs {- python: PathBuf,- installer: PathBuf,+ package_directory: PathBuf,manifest: PathBuf,- archive: PathBuf,admin_cli: PathBuf,version_directory: String,_source: windows_candidate_source::Sources,@@ -73,10 +71,13 @@ impl Inputs {}fn from_package(manifest_name: &str, archive_name: &str) -> Self {let manifest = fixture::required(manifest_name);- let archive = fixture::required(archive_name);+ let _archive = fixture::required(archive_name);let document: Value = serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();assert_eq!(document["distribution"], "integration-candidate");- assert_eq!(document["target"], "x86_64-pc-windows-msvc");+ assert_eq!(+ document["target"],+ hiroute_platform::windows::install::native_target().unwrap()+ );let version = document["version"].as_str().unwrap();let revision = document["revision"].as_str().unwrap();assert!(revision.len() >= 12);@@ -93,135 +94,54 @@ impl Inputs {let admin_cli = fixture::prepared_cli();windows_execution_host::image(&admin_cli);windows_execution_host::image(&admin_cli.with_file_name("hirouted.exe"));- windows_execution_host::image(- &admin_cli- .parent()- .unwrap()- .parent()- .unwrap()- .join("libexec/cliproxyapi.exe"),- );+ windows_execution_host::image(&admin_cli.parent().unwrap().join("libexec/cliproxyapi.exe"));Self {- python: fixture::required("HIROUTE_WINDOWS_PYTHON"),- installer: source.installer(),+ package_directory: PathBuf::from(+ std::env::var_os(if manifest_name == "HIROUTE_WINDOWS_PACKAGE_MANIFEST" {+ "HIROUTE_WINDOWS_PACKAGE_DIRECTORY"+ } else {+ "HIROUTE_WINDOWS_BASELINE_PACKAGE_DIRECTORY"+ })+ .expect("native transaction package required"),+ ),manifest,- archive,admin_cli,version_directory: format!("{version}-{}", &revision[..12]),_source: source,}}- fn python(&self, token: &File, arguments: Vec<String>) -> Value {- fixture::command(- token,- &self.python,- std::iter::once(self.installer.to_string_lossy().into_owned())- .chain(arguments)- .collect(),- )- }- fn install_arguments(&self, scm: bool) -> Vec<String> {- let mut args = vec![- "install".into(),- "--manifest".into(),- self.manifest.to_string_lossy().into_owned(),- "--archive".into(),- self.archive.to_string_lossy().into_owned(),- ];- if scm {- args.extend([- "--manager".into(),- "scm".into(),- "--external-manager".into(),- ]);+ fn install_request(&self, action: &str) -> fixture::Request {+ fixture::Request {+ action: action.into(),+ program: Some(self.admin_cli.clone()),+ arguments: vec![self.package_directory.to_string_lossy().into_owned()],}- args}fn install(&self, token: &File, scm: bool) -> Value {- fixture::accepted(&self.python(token, self.install_arguments(scm))).clone()+ assert!(!scm, "SCM installation is not offered");+ fixture::accepted(&fixture::owner(+ token,+ self.install_request("install"),+ Duration::from_secs(90),+ ))+ .clone()}fn transaction_install(&self, token: &File, action: &str) -> Value {- fixture::owner(+ fixture::owner(token, self.install_request(action), Duration::from_secs(90))+ }+ fn uninstall(&self, token: &File, _cli: &std::path::Path, scm: bool) -> Value {+ assert!(!scm, "SCM installation is not offered");+ fixture::accepted(&fixture::owner(token,fixture::Request {- action: action.into(),- program: Some(self.python.clone()),- arguments: std::iter::once(self.installer.to_string_lossy().into_owned())- .chain(self.install_arguments(false))- .collect(),+ action: "uninstall".into(),+ program: Some(self.admin_cli.clone()),+ arguments: vec![],},Duration::from_secs(90),- )- }- fn finalize(&self, token: &File, cli: &std::path::Path) -> Value {- fixture::accepted(&self.python(- token,- vec![- "finalize".into(),- "--cli".into(),- cli.to_string_lossy().into_owned(),- ],)).clone()}- fn uninstall(&self, token: &File, cli: &std::path::Path, scm: bool) -> Value {- let mut args = vec![- "uninstall".into(),- "--cli".into(),- cli.to_string_lossy().into_owned(),- ];- if scm {- args.extend([- "--manager".into(),- "scm".into(),- "--external-manager".into(),- ]);- }- fixture::accepted(&self.python(token, args)).clone()- }- fn admin_attempt(- &self,- account: &windows_account::Account,- operation: &str,- enabled: Option<bool>,- ) -> Value {- let mut args = vec![- self.installer.as_os_str().to_owned(),- "admin-scm".into(),- "--cli".into(),- self.admin_cli.as_os_str().to_owned(),- "--account".into(),- OsString::from(&account.account),- "--operation".into(),- operation.into(),- "--password-stdin".into(),- ];- if let Some(enabled) = enabled {- args.extend([- "--enabled".into(),- if enabled { "on" } else { "off" }.into(),- ]);- }- // Only this anonymous stdin carries synthetic credentials. Neither owner- // subprocess environment nor argv nor package/journal contains them.- fixture::process(- None,- &self.python,- &args,- Some(account.password.as_bytes()),- true,- Duration::from_secs(75),- false,- )- }- fn admin(- &self,- account: &windows_account::Account,- operation: &str,- enabled: Option<bool>,- ) -> Value {- fixture::accepted(&self.admin_attempt(account, operation, enabled)).clone()- }fn owner_layout(&self, token: &File) -> Value {fixture::owner(token,@@ -245,7 +165,6 @@ struct Cleanup<'a> {inputs: &'a Inputs,token: &'a File,cli: PathBuf,- account: Option<&'a windows_account::Account>,armed: bool,}impl Drop for Cleanup<'_> {@@ -258,14 +177,7 @@ impl Drop for Cleanup<'_> {// deletion of the runner's existing profile as a cleanup fallback.let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {let _ = fixture::cli(self.token, &self.cli, &["service", "stop"]);- let pending = self- .inputs- .uninstall(self.token, &self.cli, self.account.is_some());- if let Some(account) = self.account {- assert_eq!(pending["pending_admin"], true);- self.inputs.admin(account, "uninstall", None);- self.inputs.finalize(self.token, &self.cli);- }+ self.inputs.uninstall(self.token, &self.cli, false);}));if result.is_err() {eprintln!(@@ -316,36 +228,6 @@ fn subscription_cli(result["result"].clone()}-fn assert_native_service_absent(name: &str) {- use std::ptr::null;- use windows_sys::Win32::Foundation::{ERROR_SERVICE_DOES_NOT_EXIST, GetLastError};- use windows_sys::Win32::System::Services::{- CloseServiceHandle, OpenSCManagerW, OpenServiceW, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS,- };- let manager = unsafe { OpenSCManagerW(null(), null(), SC_MANAGER_CONNECT) };- assert!(!manager.is_null(), "native SCM observation failed");- let service = unsafe {- OpenServiceW(- manager,- windows_account::wide(name).as_ptr(),- SERVICE_QUERY_STATUS,- )- };- let error = unsafe { GetLastError() };- if !service.is_null() {- unsafe {- CloseServiceHandle(service);- }- }- unsafe {- CloseServiceHandle(manager);- }- assert!(- service.is_null() && error == ERROR_SERVICE_DOES_NOT_EXIST,- "candidate must have no native SCM registration before successful authenticated install"- );-}-fn await_actual_restart(token: &File,cli: &std::path::Path,@@ -413,7 +295,6 @@ fn task_native_background_lua_gateway_control_stop_crash_recovery_and_autostart(inputs: &input,token: &token,cli: cli.clone(),- account: None,armed: true,};assert_eq!(installed["installed"], true);@@ -504,205 +385,3 @@ fn task_native_background_lua_gateway_control_stop_crash_recovery_and_autostart("actual Task product gate: fresh Lua state, WTS session, Gateway v2, Local Control, graceful stop, forced recovery, autostart, installation deletion verified; user state preserved");}--/// Fresh native non-admin SAM owner; every user operation actually executes in-/// that token. Admin credentials are authenticated by the production stdin helper.-#[test]-fn scm_standard_owner_pending_admin_finalize_session_zero_gateway_control_and_delete() {- let _privileges = windows_account::Privileges::enable();- let input = Inputs::load();- let account = windows_account::Account::create();- let token = account.token.as_ref().unwrap();- let staged = windows_token_launcher::StagedFixture::create(token);- let layout = input.owner_layout(token);- assert_eq!(layout["sid"], account.sid);- assert_eq!(- PathBuf::from(layout["home"].as_str().unwrap()),- account.profile- );- let cli = input.owner_cli(&layout);- let pending = input.install(token, true);- let mut cleanup = Cleanup {- inputs: &input,- token,- cli: cli.clone(),- account: Some(&account),- armed: true,- };- assert_eq!(pending["pending_admin"], true);- assert_eq!(pending["completed"], false);- assert_eq!(pending["owner_sid"], account.sid);- let journal = fixture::transaction_snapshot(token, false)["journal"].clone();- let reopened = input.install(token, true);- assert_eq!(- reopened, pending,- "prepared SCM installation must reopen without manufacturing completion"- );- assert_eq!(- fixture::transaction_snapshot(token, false)["journal"],- journal- );- let denied = fixture::command(- token,- &cli,- vec![- "service".into(),- "start".into(),- "--output".into(),- "json".into(),- ],- );- assert_ne!(- denied["code"], 0,- "prepared maintenance must refuse business startup"- );- // The standard owner can alter their own binaries but cannot turn these- // mutable bytes into an SCM host. The independently verified admin package- // supplies the privileged source, and mismatch must have no machine writes.- let altered = fixture::owner(- token,- fixture::Request {- action: "tamper-daemon".into(),- program: None,- arguments: vec![],- },- Duration::from_secs(60),- );- let bad_host = PathBuf::from(altered["definition"]["service_host"].as_str().unwrap());- assert!(- !bad_host.parent().unwrap().exists(),- "tampered host cache must begin absent"- );- assert_native_service_absent(altered["definition"]["name"].as_str().unwrap());- let rejected = input.admin_attempt(&account, "install", None);- let restored = fixture::owner(- token,- fixture::Request {- action: "restore-daemon".into(),- program: None,- arguments: vec![],- },- Duration::from_secs(60),- );- assert_eq!(restored["modified"], true);- assert_ne!(- rejected["code"], 0,- "tampered owner image cannot publish a privileged host"- );- assert_native_service_absent(altered["definition"]["name"].as_str().unwrap());- assert!(- !bad_host.parent().unwrap().exists(),- "tampered_owner_image_cannot_publish_privileged_host: rejection must precede every machine host/cache write"- );- input.admin(&account, "install", None);- let reopened = input.install(token, true);- assert_eq!(- reopened, pending,- "actual SCM registration still requires owner finalization on reentry"- );- assert_eq!(- fixture::transaction_snapshot(token, false)["journal"],- journal- );- // Registration alone is insufficient: owner admission stays closed until- // its real machine-definition/hash verification commits the prepared journal.- let denied = fixture::command(- token,- &cli,- vec![- "service".into(),- "start".into(),- "--output".into(),- "json".into(),- ],- );- assert_ne!(denied["code"], 0);- let finished = input.finalize(token, &cli);- assert_eq!(finished["completed"], true);- assert_eq!(finished["operation"], "install");- assert_eq!(finished["started"], false);- fixture::transaction_snapshot(token, true);- assert_eq!(- assert_status(token, &cli, "windows-scm-user", false)["autostart_enabled"],- false- );- // Owner can query/start/stop; machine ChangeConfig remains admin-only.- let denied = fixture::command(- token,- &cli,- vec![- "service".into(),- "autostart".into(),- "enable".into(),- "--output".into(),- "json".into(),- ],- );- assert_ne!(denied["code"], 0);- input.admin(&account, "set_autostart", Some(true));- assert_eq!(- assert_status(token, &cli, "windows-scm-user", false)["autostart_enabled"],- true- );- input.admin(&account, "set_autostart", Some(false));- assert_eq!(- assert_status(token, &cli, "windows-scm-user", false)["autostart_enabled"],- false- );- fixture::cli(token, &cli, &["service", "start"]);- let first = fixture::inspect(token, false);- assert_eq!(first["sid"], account.sid);- assert_eq!(- first["session"], 0,- "real SCM business runtime must operate without an interactive owner logon"- );- assert_status(token, &cli, "windows-scm-user", true);- windows_gateway_recovery::exercise(token, &cli, &first, &account.sid, 0);- let oauth_pending = windows_subscription_login::run_before_restart(&mut |args, request| {- subscription_cli(token, &cli, args, request)- });- fixture::cli(token, &cli, &["service", "stop"]);- assert_status(token, &cli, "windows-scm-user", false);- fixture::cli(token, &cli, &["service", "start"]);- windows_subscription_login::assert_after_restart(- &mut |args, request| subscription_cli(token, &cli, args, request),- oauth_pending,- );- let crashed = fixture::inspect(token, true);- let recovered = await_actual_restart(token, &cli, "windows-scm-user", &crashed);- assert_eq!(recovered["session"], 0);- fixture::cli(token, &cli, &["service", "stop"]);- let removal = input.uninstall(token, &cli, true);- assert_eq!(removal["pending_admin"], true);- assert_eq!(removal["operation"], "uninstall");- assert_eq!(- input.uninstall(token, &cli, true),- removal,- "prepared removal reentry must preserve the exact pending administrator operation"- );- let too_early = input.python(- token,- vec![- "finalize".into(),- "--cli".into(),- cli.to_string_lossy().into_owned(),- ],- );- assert_ne!(- too_early["code"], 0,- "owner cannot declare an existing SCM registration removed"- );- input.admin(&account, "uninstall", None);- let removed = input.finalize(token, &cli);- assert_eq!(removed["completed"], true);- assert_eq!(removed["operation"], "uninstall");- cleanup.armed = false;- drop(cleanup);- assert!(!PathBuf::from(layout["marker"].as_str().unwrap()).exists());- assert!(!account.profile.join(".local/bin/hiroute.exe").exists());- drop(staged);- account.finish();- println!(- "actual SCM product gate: authenticated standard owner, pending admission, finalize, session 0 medium daemon, Gateway v2, Local Control, graceful stop, forced recovery, machine autostart, confirmed deletion verified"- );-}diff --git a/crates/daemon/tests/windows_desktop.rs b/crates/daemon/tests/windows_desktop.rsnew file mode 100644index 00000000..44e14dcb--- /dev/null+++ b/crates/daemon/tests/windows_desktop.rs@@ -0,0 +1,270 @@+#![cfg(windows)]+//! Bounded NSIS acceptance in the configured, already logged-on standard session.+//! This does not cover WebView interaction, Agent restoration or update recovery.++#[path = "support/windows_account.rs"]+#[allow(dead_code)]+mod windows_account;++use hiroute_host_runtime::{StandaloneInstallRecordV1, StandaloneLayout};+use hiroute_platform::windows::{background, install, shell_login, task};+use serde_json::{Value, json};+use sha2::{Digest, Sha256};+use std::{+ fs::File,+ io::{Read, Write},+ net::{SocketAddr, TcpStream},+ path::{Path, PathBuf},+ process::{Command, Stdio},+ thread,+ time::{Duration, Instant},+};+use windows_sys::Win32::Security::{+ CreateWellKnownSid, EqualSid, TOKEN_GROUPS, TokenGroups, WinBuiltinAdministratorsSid,+};++fn standard_session() {+ install::require_x64().unwrap();+ let token = windows_account::process_token(std::process::id());+ let sid = background::sid_string(&windows_account::token_sid(&token)).unwrap();+ assert_ne!(windows_account::assert_standard(&token, &sid), 0);+ let mut admin = [0_usize; 9];+ let mut size = std::mem::size_of_val(&admin) as u32;+ // SAFETY: aligned native SID buffer with its actual writable capacity.+ assert_ne!(+ unsafe {+ CreateWellKnownSid(+ WinBuiltinAdministratorsSid,+ std::ptr::null_mut(),+ admin.as_mut_ptr().cast(),+ &mut size,+ )+ },+ 0+ );+ let groups = windows_account::information(&token, TokenGroups);+ // SAFETY: GetTokenInformation returned this aligned, complete TOKEN_GROUPS.+ let groups = unsafe { &*groups.as_ptr().cast::<TOKEN_GROUPS>() };+ for group in+ unsafe { std::slice::from_raw_parts(groups.Groups.as_ptr(), groups.GroupCount as usize) }+ {+ assert_eq!(+ unsafe { EqualSid(group.Sid, admin.as_mut_ptr().cast()) },+ 0,+ "standard-user evidence rejects deny-only Administrators membership too"+ );+ }+}++fn hash(path: &Path) -> String {+ let mut input = File::open(path).unwrap();+ let mut hash = Sha256::new();+ let mut bytes = [0; 64 * 1024];+ loop {+ let count = input.read(&mut bytes).unwrap();+ if count == 0 {+ break;+ }+ hash.update(&bytes[..count]);+ }+ format!("{hash:x}", hash = hash.finalize())+}++fn run(program: &Path, args: &[&str], evidence: &Path, phase: &str) -> Vec<u8> {+ let output = evidence.join(format!("{phase}.stdout"));+ let error = evidence.join(format!("{phase}.stderr"));+ let mut child = Command::new(program)+ .args(args)+ .stdin(Stdio::null())+ .stdout(File::create(&output).unwrap())+ .stderr(File::create(error).unwrap())+ .spawn()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(150);+ loop {+ if let Some(status) = child.try_wait().unwrap() {+ assert!(status.success(), "native phase {phase} failed: {status}");+ return std::fs::read(output).unwrap();+ }+ if Instant::now() >= deadline {+ // Only our still-held installer/CLI child is stopped. Keep its native+ // installation and evidence for the normal product recovery path.+ child.kill().unwrap();+ child.wait().unwrap();+ panic!("native phase {phase} exceeded its whole-process watchdog");+ }+ thread::sleep(Duration::from_millis(100));+ }+}++fn cli(program: &Path, args: &[&str], evidence: &Path, phase: &str) -> Value {+ let args: Vec<_> = args.iter().copied().chain(["--output", "json"]).collect();+ let envelope: Value = serde_json::from_slice(&run(program, &args, evidence, phase)).unwrap();+ assert_eq!(envelope["status"], "succeeded");+ assert!(envelope["error"].is_null());+ envelope["data"].clone()+}++fn console_ready(cli_path: &Path, evidence: &Path, phase: &str) {+ let system = cli(+ cli_path,+ &["system", "status"],+ evidence,+ &format!("{phase}-system"),+ );+ assert_eq!(system["gateway"], "ready");+ let console = cli(+ cli_path,+ &["console", "status"],+ evidence,+ &format!("{phase}-console"),+ );+ assert_eq!(console["desired"]["mode"], "loopback");+ assert!(console["failure_code"].is_null());+ let address: SocketAddr = console["applied_address"]+ .as_str()+ .unwrap()+ .parse()+ .unwrap();+ assert!(address.ip().is_loopback());+ let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(5)).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ stream+ .write_all(+ format!("GET / HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n").as_bytes(),+ )+ .unwrap();+ let mut reply = String::new();+ stream.take(128 * 1024).read_to_string(&mut reply).unwrap();+ assert!(reply.starts_with("HTTP/1.1 200 "));+ assert!(+ reply+ .to_ascii_lowercase()+ .contains("content-security-policy:")+ );+ assert!(+ reply.contains("/assets/"),+ "actual packaged console assets must be served"+ );+}++#[test]+#[ignore = "requires the verified NSIS bundle and a fresh existing standard-user session"]+fn actual_nsis_silent_install_repeat_console_and_uninstall_preserve_data() {+ standard_session();+ let layout = StandaloneLayout::from_environment().unwrap();+ let programs = background::local_app_data()+ .unwrap()+ .join("Programs/HiRoute");+ for path in [+ &programs,+ &layout.data_root,+ &layout.state_root,+ &layout.home.join(".local/bin/hiroute.exe"),+ ] {+ assert!(+ !path.exists(),+ "native NSIS case must not adopt an existing profile"+ );+ }+ let bundle = PathBuf::from(std::env::var_os("HIROUTE_VALIDATION_PRODUCT_BIN_DIR").unwrap());+ let evidence = PathBuf::from(std::env::var_os("HIROUTE_VALIDATION_EVIDENCE_DIR").unwrap());+ let installer = bundle.join("installer.exe");+ let manifest: Value =+ serde_json::from_slice(&std::fs::read(bundle.join("manifest.json")).unwrap()).unwrap();+ assert_eq!(manifest["installer_format"], "nsis");+ assert_eq!(+ manifest["files"]["installer.exe"]["sha256"],+ hash(&installer)+ );+ let revision = manifest["source_revision"].as_str().unwrap();+ assert_eq!(Some(revision), option_env!("HIROUTE_BUILD_SOURCE_SHA"));+ let shell_sha256 = manifest["shell_sha256"].as_str().unwrap();+ assert_eq!(shell_sha256.len(), 64);++ run(&installer, &["/S"], &evidence, "install");+ assert!(programs.join("hiroute-shell.exe").is_file());+ assert_eq!(hash(&programs.join("hiroute-shell.exe")), shell_sha256);+ assert!(!programs.starts_with(&layout.state_root));+ assert!(!layout.state_root.starts_with(&programs));+ let cli_path = layout.home.join(".local/bin/hiroute.exe");+ let record: StandaloneInstallRecordV1 =+ serde_json::from_slice(&std::fs::read(&layout.marker_path).unwrap()).unwrap();+ assert!(+ record+ .install_root+ .file_name()+ .unwrap()+ .to_string_lossy()+ .ends_with(&revision[..12])+ );+ assert_eq!(+ hash(&cli_path),+ manifest["files"]["hiroute.exe"]["sha256"].as_str().unwrap()+ );+ assert_eq!(+ hash(&record.install_root.join("hirouted.exe")),+ manifest["files"]["hirouted.exe"]["sha256"]+ .as_str()+ .unwrap()+ );+ let definition = background::read_definition(&record.service_definition).unwrap();+ assert_eq!(definition.manager, background::Manager::Task);+ assert!(task::active(&definition).unwrap());+ assert!(task::autostart(&definition).unwrap());+ assert!(shell_login::enabled(&programs.join("hiroute-shell.exe")).unwrap());+ let preferences: Value =+ serde_json::from_slice(&std::fs::read(programs.join("shell-install.json")).unwrap())+ .unwrap();+ assert_eq!(preferences["tray_enabled"], true);+ console_ready(&cli_path, &evidence, "fresh");+ run(&installer, &["/S"], &evidence, "repeat");+ assert_eq!(hash(&programs.join("hiroute-shell.exe")), shell_sha256);+ console_ready(&cli_path, &evidence, "repeated");+ hiroute_platform::windows::lifecycle::drain(+ &layout.lifecycle_endpoint(),+ &record.install_root.join("hirouted.exe"),+ Duration::from_secs(30),+ )+ .unwrap();+ run(&installer, &["/P", "/UPDATE"], &evidence, "passive-update");+ assert_eq!(hash(&programs.join("hiroute-shell.exe")), shell_sha256);+ console_ready(&cli_path, &evidence, "passive-updated");++ let sentinel = layout.state_root.join("nsis-preserved-data.txt");+ std::fs::write(&sentinel, b"native NSIS acceptance data").unwrap();+ let uninstall = programs.join("uninstall.exe");+ run(&uninstall, &["/S"], &evidence, "uninstall");+ let deadline = Instant::now() + Duration::from_secs(30);+ while programs.join("hiroute-shell.exe").exists() && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(100));+ }+ assert!(!programs.join("hiroute-shell.exe").exists());+ assert!(!layout.marker_path.exists());+ assert!(!record.service_definition.exists());+ assert!(!cli_path.exists());+ assert!(+ !record.install_root.exists(),+ "uninstall left its versioned package behind"+ );+ assert_eq!(+ std::fs::read(&sentinel).unwrap(),+ b"native NSIS acceptance data"+ );+ assert!(!shell_login::enabled(&programs.join("hiroute-shell.exe")).unwrap());+ std::fs::write(+ evidence.join("nsis-result.json"),+ serde_json::to_vec_pretty(&json!({+ "revision":revision,"installer_sha256":hash(&installer),"standard_user":true,+ "silent_defaults":"green","repeat_install":"green","console_gateway_ready":"green",+ "passive_update":"green","versioned_package_removed":"green",+ "uninstall_preserves_data":"green","agent_restore":"not_executed",+ "native_webview":"not_executed","update_recovery":"not_executed",+ "preserved_state":true+ }))+ .unwrap(),+ )+ .unwrap();+}diff --git a/crates/daemon/tests/windows_headless.rs b/crates/daemon/tests/windows_headless.rsindex a03f084c..9950cb41 100644--- a/crates/daemon/tests/windows_headless.rs+++ b/crates/daemon/tests/windows_headless.rs@@ -923,7 +923,7 @@ fn public_headless_business(include_claude: bool) {.starts_with("sha256:"));let commands = manifest["commands"].as_array().unwrap();- assert_eq!(commands.len(), 55);+ assert_eq!(commands.len(), 59);for command_id in ["prices.effective","prices.override.preview",diff --git a/crates/diagnostics/src/event/control.rs b/crates/diagnostics/src/event/control.rsindex b5160a25..56b93974 100644--- a/crates/diagnostics/src/event/control.rs+++ b/crates/diagnostics/src/event/control.rs@@ -98,6 +98,8 @@ pub struct ApplyEvent {#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct ControlCallEnd {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub client_name: Option<ControlClientName>,pub operation: ControlOperation,#[serde(default, skip_serializing_if = "Option::is_none")]pub request_token: Option<CorrelationToken>,@@ -107,6 +109,13 @@ pub struct ControlCallEnd {pub elapsed_ms: u64,}+/// A closed attribution label, never an arbitrary client-supplied string.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ControlClientName {+ Console,+}+/// Submission state mirrored from Client Core without reinterpreting its semantics.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]diff --git a/crates/host-runtime/Cargo.toml b/crates/host-runtime/Cargo.tomlindex 595482bf..3b607b20 100644--- a/crates/host-runtime/Cargo.toml+++ b/crates/host-runtime/Cargo.toml@@ -7,6 +7,7 @@ rust-version.workspace = true[dependencies]getrandom.workspace = true+fs2.workspace = truehiroute-platform = { path = "../platform" }nix.workspace = trueserde.workspace = truediff --git a/crates/host-runtime/src/console_listener.rs b/crates/host-runtime/src/console_listener.rsnew file mode 100644index 00000000..47b74fc0--- /dev/null+++ b/crates/host-runtime/src/console_listener.rs@@ -0,0 +1,270 @@+//! Persisted management exposure. Only service startup binds the configured listener.+use serde::{Deserialize, Serialize};+use std::{+ io::Read,+ net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener},+ path::{Path, PathBuf},+};+#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ConsoleListenerMode {+ #[default]+ Off,+ Loopback,+ Network,+}+#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ConsolePortMode {+ #[default]+ Automatic,+ Explicit,+}+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleListenerDesiredV1 {+ pub mode: ConsoleListenerMode,+ pub port_mode: ConsolePortMode,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub address: Option<IpAddr>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub advertise_address: Option<IpAddr>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub port: Option<u16>,+ #[serde(default)]+ pub allow_plaintext_network: bool,+}+impl ConsoleListenerDesiredV1 {+ pub fn loopback() -> Self {+ Self {+ mode: ConsoleListenerMode::Loopback,+ ..Self::default()+ }+ }+ pub fn validate(&self) -> Result<IpAddr, ConsoleListenerError> {+ if matches!(self.port_mode, ConsolePortMode::Explicit) && self.port.is_none_or(|p| p == 0)+ || matches!(self.port_mode, ConsolePortMode::Automatic) && self.port.is_some()+ {+ return Err(ConsoleListenerError);+ }+ match self.mode {+ ConsoleListenerMode::Off | ConsoleListenerMode::Loopback+ if self+ .address+ .is_none_or(|a| a == IpAddr::V4(Ipv4Addr::LOCALHOST))+ && self.advertise_address.is_none() =>+ {+ Ok(IpAddr::V4(Ipv4Addr::LOCALHOST))+ }+ ConsoleListenerMode::Network if self.allow_plaintext_network => {+ let address = self.address.ok_or(ConsoleListenerError)?;+ let advertised = self.advertise_address.unwrap_or(address);+ if address.is_loopback()+ || address.is_multicast()+ || advertised.is_loopback()+ || (self.advertise_address.is_some() && advertised.is_unspecified())+ || advertised.is_multicast()+ || advertised == IpAddr::V4(Ipv4Addr::BROADCAST)+ || advertised.is_ipv4() != address.is_ipv4()+ {+ return Err(ConsoleListenerError);+ }+ Ok(address)+ }+ _ => Err(ConsoleListenerError),+ }+ }+ pub fn validate_configuration(&self) -> Result<(), ConsoleListenerError> {+ let address = self.validate()?;+ if self.mode == ConsoleListenerMode::Network+ && address.is_unspecified()+ && self.advertise_address.is_none()+ {+ return Err(ConsoleListenerError);+ }+ Ok(())+ }+ /// The actual port comes from the socket, never from pending desired settings.+ pub fn advertised_socket(&self, bound: SocketAddr) -> SocketAddr {+ SocketAddr::new(self.advertise_address.unwrap_or(bound.ip()), bound.port())+ }+ pub fn reserve(&self) -> Result<Option<TcpListener>, ConsoleListenerError> {+ let address = self.validate()?;+ if self.mode == ConsoleListenerMode::Off {+ return Ok(None);+ }+ let listener = match self.port_mode {+ ConsolePortMode::Explicit => TcpListener::bind(SocketAddr::new(+ address,+ self.port.ok_or(ConsoleListenerError)?,+ )),+ ConsolePortMode::Automatic => TcpListener::bind(SocketAddr::new(address, 5838))+ .or_else(|_| TcpListener::bind(SocketAddr::new(address, 0))),+ }+ .map_err(|_| ConsoleListenerError)?;+ Ok(Some(listener))+ }+}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ConsoleListenerConfigV1 {+ pub schema: String,+ pub desired: ConsoleListenerDesiredV1,+ pub applied_address: Option<SocketAddr>,+ pub failure_code: Option<String>,+}+impl Default for ConsoleListenerConfigV1 {+ fn default() -> Self {+ Self {+ schema: "hiroute.console-listener/v1".into(),+ desired: ConsoleListenerDesiredV1::default(),+ applied_address: None,+ failure_code: None,+ }+ }+}+#[derive(Debug, thiserror::Error)]+#[error("CONSOLE_LISTENER_UNAVAILABLE")]+pub struct ConsoleListenerError;+#[derive(Clone)]+pub struct ConsoleListenerStore {+ root: PathBuf,+}+impl ConsoleListenerStore {+ pub fn new(root: impl AsRef<Path>) -> Self {+ Self {+ root: root.as_ref().to_path_buf(),+ }+ }+ pub fn path(&self) -> PathBuf {+ self.root.join("console-listener.json")+ }+ pub fn read(&self) -> Result<ConsoleListenerConfigV1, ConsoleListenerError> {+ let mut file = match hiroute_platform::private_fs::open_private_file(&self.path()) {+ Ok(file) => file,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ return Ok(ConsoleListenerConfigV1::default());+ }+ Err(_) => return Err(ConsoleListenerError),+ };+ hiroute_platform::private_fs::verify_single_link(&file)+ .map_err(|_| ConsoleListenerError)?;+ let mut bytes = Vec::new();+ file.by_ref()+ .take(16 * 1024 + 1)+ .read_to_end(&mut bytes)+ .map_err(|_| ConsoleListenerError)?;+ if bytes.len() > 16 * 1024 {+ return Err(ConsoleListenerError);+ }+ let config: ConsoleListenerConfigV1 =+ serde_json::from_slice(&bytes).map_err(|_| ConsoleListenerError)?;+ if config.schema != "hiroute.console-listener/v1"+ || config+ .failure_code+ .as_deref()+ .is_some_and(|c| c != "CONSOLE_LISTENER_UNAVAILABLE")+ {+ return Err(ConsoleListenerError);+ }+ config.desired.validate()?;+ Ok(config)+ }+ fn write(&self, config: &ConsoleListenerConfigV1) -> Result<(), ConsoleListenerError> {+ hiroute_platform::private_fs::prepare_storage_directory(&self.root)+ .map_err(|_| ConsoleListenerError)?;+ let bytes = serde_json::to_vec(config).map_err(|_| ConsoleListenerError)?;+ hiroute_platform::durable::write_private_atomic(&self.path(), &bytes)+ .map_err(|_| ConsoleListenerError)+ }+ pub fn configure(+ &self,+ desired: ConsoleListenerDesiredV1,+ ) -> Result<ConsoleListenerConfigV1, ConsoleListenerError> {+ desired.validate_configuration()?;+ let mut config = self.read()?;+ config.desired = desired;+ self.write(&config)?;+ Ok(config)+ }+ pub fn mark_applied(&self, address: Option<SocketAddr>) -> Result<(), ConsoleListenerError> {+ let mut c = self.read()?;+ c.applied_address = address;+ c.failure_code = None;+ self.write(&c)+ }+ pub fn mark_failed(&self) -> Result<(), ConsoleListenerError> {+ let mut c = self.read()?;+ c.applied_address = None;+ c.failure_code = Some("CONSOLE_LISTENER_UNAVAILABLE".into());+ self.write(&c)+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn off_by_default_and_explicit_network_confirmation_precedes_writes() {+ let root = tempfile::tempdir().unwrap();+ let store = ConsoleListenerStore::new(root.path());+ assert_eq!(store.read().unwrap().desired.mode, ConsoleListenerMode::Off);+ assert!(store.read().unwrap().desired.reserve().unwrap().is_none());+ let mut desired = ConsoleListenerDesiredV1 {+ mode: ConsoleListenerMode::Network,+ address: Some("0.0.0.0".parse().unwrap()),+ advertise_address: Some("192.0.2.1".parse().unwrap()),+ ..Default::default()+ };+ assert!(store.configure(desired.clone()).is_err());+ assert!(!store.path().exists());+ desired.allow_plaintext_network = true;+ store.configure(desired).unwrap();+ assert_eq!(+ store.read().unwrap().desired.mode,+ ConsoleListenerMode::Network+ );+ }+ #[test]+ fn network_advertisement_is_concrete_and_does_not_change_the_actual_port() {+ let mut desired = ConsoleListenerDesiredV1 {+ mode: ConsoleListenerMode::Network,+ address: Some("0.0.0.0".parse().unwrap()),+ allow_plaintext_network: true,+ ..Default::default()+ };+ assert!(desired.validate_configuration().is_err());+ for invalid in [+ "0.0.0.0",+ "127.0.0.1",+ "224.0.0.1",+ "255.255.255.255",+ "::1",+ "2001:db8::1",+ ] {+ desired.advertise_address = Some(invalid.parse().unwrap());+ assert!(desired.validate().is_err(), "{invalid}");+ }+ desired.advertise_address = Some("192.0.2.1".parse().unwrap());+ assert!(desired.validate().is_ok());+ assert_eq!(+ desired.advertised_socket("0.0.0.0:43210".parse().unwrap()),+ "192.0.2.1:43210".parse().unwrap()+ );+ }+ #[test]+ fn loopback_port_collision_fails_and_auto_falls_back() {+ let held = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = held.local_addr().unwrap().port();+ let d = ConsoleListenerDesiredV1 {+ port_mode: ConsolePortMode::Explicit,+ port: Some(port),+ ..ConsoleListenerDesiredV1::loopback()+ };+ assert!(d.reserve().is_err());+ let automatic = ConsoleListenerDesiredV1::loopback()+ .reserve()+ .unwrap()+ .unwrap();+ assert!(automatic.local_addr().unwrap().ip().is_loopback());+ }+}diff --git a/crates/host-runtime/src/lib.rs b/crates/host-runtime/src/lib.rsindex ec4ac7f7..b97ef9fe 100644--- a/crates/host-runtime/src/lib.rs+++ b/crates/host-runtime/src/lib.rs@@ -9,6 +9,7 @@mod desktop_package;mod gateway_listener;mod releases;+mod releases_v3;mod service_proxy;mod standalone;mod upgrade;@@ -16,6 +17,7 @@ mod upgrade;pub use desktop_package::*;pub use gateway_listener::*;pub use releases::*;+pub use releases_v3::*;pub use service_proxy::*;pub use standalone::*;pub use upgrade::*;@@ -25,3 +27,7 @@ pub use storage_progress::StorageUpgradePhase;mod subscription_proxy;pub use subscription_proxy::*;++mod console_listener;+pub use console_listener::*;+pub mod standalone_install;diff --git a/crates/host-runtime/src/releases.rs b/crates/host-runtime/src/releases.rsindex fda2c49c..68673b87 100644--- a/crates/host-runtime/src/releases.rs+++ b/crates/host-runtime/src/releases.rs@@ -282,7 +282,11 @@ mod tests {#[test]fn current_website_catalog_is_the_upgrade_reader_contract() {let bytes = include_bytes!("../../../apps/website/data/releases.json");- let catalog = WebsiteReleasesV2::parse(bytes).unwrap();+ let projection = crate::WebsiteReleasesV3::parse(bytes)+ .unwrap()+ .v2_projection()+ .unwrap();+ let catalog = WebsiteReleasesV2::parse(&projection).unwrap();let original: serde_json::Value = serde_json::from_slice(bytes).unwrap();for architecture in ["arm64", "x86_64"] {let update = catalogdiff --git a/crates/host-runtime/src/releases_v3.rs b/crates/host-runtime/src/releases_v3.rsnew file mode 100644index 00000000..44d5e660--- /dev/null+++ b/crates/host-runtime/src/releases_v3.rs@@ -0,0 +1,283 @@+//! Windows consumes V3; released macOS readers retain the V2 projection unchanged.+use crate::{MAX_RELEASE_FEED_BYTES, ReleaseNotes, WebsiteReleasesV2};+use semver::Version;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::collections::BTreeSet;+pub const WINDOWS_RELEASE_FEED: &str = "https://hiroute.ai/releases-v3.json";++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WebsiteReleasesV3 {+ schema: String,+ releases: Vec<ReleaseV3>,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ReleaseV3 {+ version: String,+ channel: String,+ published_at: String,+ notes: ReleaseNotes,+ artifacts: Vec<Value>,+}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct WindowsDesktopRelease {+ pub version: String,+ pub notes: ReleaseNotes,+ pub architecture: String,+ pub distribution: String,+ pub filename: String,+ pub sha256: String,+ pub size: u64,+}+impl WindowsDesktopRelease {+ pub fn revision_prefix(&self) -> Result<&str, &'static str> {+ let prefix = format!("HiRoute-{}-", self.version);+ let revision = self+ .filename+ .strip_prefix(&prefix)+ .and_then(|s| s.strip_suffix("-windows-x86_64-setup.exe"))+ .ok_or("UPGRADE_ARTIFACT_INVALID")?;+ if Version::parse(&self.version).is_err()+ || self.version.len() > 64+ || self.architecture != "x86_64"+ || self.distribution != "unsigned"+ || !facts(&self.filename, &self.sha256, self.size)+ || !revision_id(revision)+ {+ return Err("UPGRADE_ARTIFACT_INVALID");+ }+ Ok(revision)+ }+ pub fn download_url(&self) -> String {+ format!(+ "https://hiroute.ai/releases/{}/{}",+ self.version, self.filename+ )+ }+}+#[derive(Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]+enum WindowsArtifact {+ Desktop {+ platform: String,+ architecture: String,+ format: String,+ distribution: String,+ filename: String,+ sha256: String,+ size: u64,+ },+}+fn facts(name: &str, sha: &str, size: u64) -> bool {+ !name.is_empty()+ && name.len() <= 240+ && name+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))+ && sha.len() == 64+ && sha+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ && size > 0+ && size <= 2 * 1024 * 1024 * 1024+}+fn revision_id(value: &str) -> bool {+ value.len() == 12+ && value+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}+impl WebsiteReleasesV3 {+ pub fn parse(bytes: &[u8]) -> Result<Self, &'static str> {+ let invalid = || "UPGRADE_CATALOG_INVALID";+ if bytes.is_empty() || bytes.len() > MAX_RELEASE_FEED_BYTES {+ return Err(invalid());+ }+ let catalog: Self = serde_json::from_slice(bytes).map_err(|_| invalid())?;+ if catalog.schema != "hiroute.website.releases/v3" || catalog.releases.len() > 64 {+ return Err(invalid());+ }+ let mut versions = BTreeSet::new();+ for release in &catalog.releases {+ let version = Version::parse(&release.version).map_err(|_| invalid())?;+ if release.version.len() > 64+ || !versions.insert(&release.version)+ || !matches!(release.channel.as_str(), "stable" | "preview")+ || (release.channel == "stable" && !version.pre.is_empty())+ || release.published_at.is_empty()+ || release.published_at.len() > 64+ || [&release.notes.zh, &release.notes.en]+ .iter()+ .any(|s| s.trim().is_empty() || s.len() > 64 * 1024)+ || release.artifacts.is_empty()+ || release.artifacts.len() > 16+ {+ return Err(invalid());+ }+ let mut names = BTreeSet::new();+ for value in &release.artifacts {+ let filename = value["filename"].as_str().ok_or_else(invalid)?;+ if !names.insert(filename) {+ return Err(invalid());+ }+ if let Some(name) = value.get("manifest_filename")+ && !names.insert(name.as_str().ok_or_else(invalid)?)+ {+ return Err(invalid());+ }+ if value["platform"] != "Windows" {+ continue;+ }+ match serde_json::from_value::<WindowsArtifact>(value.clone())+ .map_err(|_| invalid())?+ {+ WindowsArtifact::Desktop {+ platform,+ architecture,+ format,+ distribution,+ filename,+ sha256,+ size,+ } => {+ if platform != "Windows" || format != "nsis" {+ return Err(invalid());+ }+ WindowsDesktopRelease {+ version: release.version.clone(),+ notes: release.notes.clone(),+ architecture,+ distribution,+ filename,+ sha256,+ size,+ }+ .revision_prefix()+ .map_err(|_| invalid())?;+ }+ }+ }+ }+ WebsiteReleasesV2::parse(&catalog.v2_projection()?)?;+ Ok(catalog)+ }+ pub fn v2_projection(&self) -> Result<Vec<u8>, &'static str> {+ let releases: Vec<_> = self+ .releases+ .iter()+ .filter_map(|release| {+ let mut release = release.clone();+ release.artifacts.retain(|a| a["platform"] != "Windows");+ (!release.artifacts.is_empty()).then_some(release)+ })+ .collect();+ serde_json::to_vec(&json!({"schema":"hiroute.website.releases/v2","releases":releases}))+ .map_err(|_| "UPGRADE_CATALOG_INVALID")+ }+ pub fn windows_update(+ &self,+ current: &str,+ ) -> Result<Option<WindowsDesktopRelease>, &'static str> {+ let current = Version::parse(current).map_err(|_| "UPGRADE_VERSION_INVALID")?;+ let mut selected: Option<(Version, WindowsDesktopRelease)> = None;+ for release in &self.releases {+ let version =+ Version::parse(&release.version).map_err(|_| "UPGRADE_CATALOG_INVALID")?;+ if release.channel != "stable"+ || version <= current+ || selected.as_ref().is_some_and(|(v, _)| v >= &version)+ {+ continue;+ }+ let candidates: Vec<_> = release+ .artifacts+ .iter()+ .filter(|a| a["kind"] == "desktop" && a["platform"] == "Windows")+ .collect();+ if candidates.len() > 1 {+ return Err("UPGRADE_ARTIFACT_AMBIGUOUS");+ }+ if let Some(value) = candidates.first() {+ let artifact: WindowsArtifact = serde_json::from_value((*value).clone())+ .map_err(|_| "UPGRADE_CATALOG_INVALID")?;+ let WindowsArtifact::Desktop {+ architecture,+ distribution,+ filename,+ sha256,+ size,+ ..+ } = artifact;+ selected = Some((+ version,+ WindowsDesktopRelease {+ version: release.version.clone(),+ notes: release.notes.clone(),+ architecture,+ distribution,+ filename,+ sha256,+ size,+ },+ ));+ }+ }+ Ok(selected.map(|(_, value)| value))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ fn fixture() -> Value {+ json!({"schema":"hiroute.website.releases/v3","releases":[{"version":"0.4.0","channel":"stable","published_at":"2026-10-01T00:00:00Z","notes":{"zh":"测试","en":"Test"},"artifacts":[{"kind":"desktop","platform":"Windows","architecture":"x86_64","format":"nsis","distribution":"unsigned","filename":"HiRoute-0.4.0-aaaaaaaaaaaa-windows-x86_64-setup.exe","sha256":"a".repeat(64),"size":100}]}]})+ }+ #[test]+ fn windows_selection_and_legacy_projection_remain_separate() {+ let catalog = WebsiteReleasesV3::parse(&serde_json::to_vec(&fixture()).unwrap()).unwrap();+ assert!(WebsiteReleasesV2::parse(&catalog.v2_projection().unwrap()).is_ok());+ let update = catalog.windows_update("0.3.1").unwrap().unwrap();+ assert_eq!(update.revision_prefix().unwrap(), "aaaaaaaaaaaa");+ assert!(+ update+ .download_url()+ .starts_with("https://hiroute.ai/releases/0.4.0/")+ );+ assert!(catalog.windows_update("0.4.0").unwrap().is_none());+ }+ #[test]+ fn windows_standalone_archives_of_either_architecture_are_never_public() {+ for architecture in ["x86_64", "aarch64"] {+ let mut value = fixture();+ let target = format!("{architecture}-pc-windows-msvc");+ let name = format!("hiroute-0.4.0-aaaaaaaaaaaa-{target}.tar.gz");+ value["releases"][0]["artifacts"][0] = json!({"kind":"standalone","platform":"Windows",+ "architecture":architecture,"target":target,"format":"tar.gz","distribution":"unsigned",+ "filename":name,"sha256":"a".repeat(64),"size":100,+ "manifest_filename":format!("{name}.json"),"manifest_sha256":"b".repeat(64),"manifest_size":200});+ assert!(WebsiteReleasesV3::parse(&serde_json::to_vec(&value).unwrap()).is_err());+ }+ }+ #[test]+ fn invalid_windows_artifacts_cannot_be_selected_or_smuggled_into_a_catalog() {+ for (field, value) in [+ ("architecture", json!("aarch64")),+ ("distribution", json!("self-signed")),+ ("format", json!("exe")),+ ("filename", json!("../setup.exe")),+ ("sha256", json!("bad")),+ ("size", json!(0)),+ ("minimum_os", json!("any")),+ ] {+ let mut fixture = fixture();+ fixture["releases"][0]["artifacts"][0][field] = value;+ assert!(+ WebsiteReleasesV3::parse(&serde_json::to_vec(&fixture).unwrap()).is_err(),+ "{field}"+ );+ }+ }+}diff --git a/crates/host-runtime/src/standalone_install/cleanup.rs b/crates/host-runtime/src/standalone_install/cleanup.rsnew file mode 100644index 00000000..5bd3d12b--- /dev/null+++ b/crates/host-runtime/src/standalone_install/cleanup.rs@@ -0,0 +1,222 @@+//! Remove only manifest-owned versioned payloads, retaining recovery sources until commit.+use super::*;+use serde::Serialize;+use std::{collections::BTreeSet, fs, path::PathBuf};++#[derive(Default, Serialize)]+pub struct PackageCleanup {+ pub removed: Vec<PathBuf>,+ pub preserved: Vec<PathBuf>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++impl PackageCleanup {+ #[cfg(any(windows, test))]+ pub(crate) fn best_effort(result: io::Result<Self>) -> Self {+ result.unwrap_or_else(|error| Self {+ error: Some(error.to_string()),+ ..Self::default()+ })+ }+}++pub fn prune_packages(+ base: &Path,+ target: &str,+ retained: &[PathBuf],+) -> io::Result<PackageCleanup> {+ windows_machine(target)?;+ let mut report = PackageCleanup::default();+ // The regular-file helper also admits every ancestor without following links.+ regular(&base.join("package-manifest.json"))?;+ let entries = match fs::read_dir(base) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(report),+ Err(error) => return Err(error),+ };+ for entry in entries {+ let root = entry?.path();+ if retained.contains(&root) {+ continue;+ }+ match remove_package(&root, target) {+ Ok(()) => report.removed.push(root),+ // Modified, foreign, busy or unrecognised material remains available for repair.+ Err(_) => report.preserved.push(root),+ }+ }+ Ok(report)+}++fn inventory(root: &Path, expected: &BTreeSet<PathBuf>) -> io::Result<()> {+ regular(&root.join("package-manifest.json"))?;+ for entry in fs::read_dir(root)? {+ let path = entry?.path();+ if !expected.contains(&path) {+ return Err(invalid());+ }+ let metadata = fs::symlink_metadata(&path)?;+ if metadata.is_dir() {+ inventory(&path, expected)?;+ } else {+ regular(&path)?.ok_or_else(invalid)?;+ }+ }+ Ok(())+}++fn remove_package(root: &Path, target: &str) -> io::Result<()> {+ let manifest = root.join("package-manifest.json");+ let package: Package = read_json(&manifest, 1024 * 1024)?.ok_or_else(invalid)?;+ package.validate()?;+ if root.file_name() != Some(std::ffi::OsStr::new(&package.directory_name()))+ || package.target != target+ {+ return Err(invalid());+ }+ #[cfg(windows)]+ if let Some(cli) = regular(&root.join("hiroute.exe"))? {+ let running =+ hiroute_platform::windows::security::open_identity(&std::env::current_exe()?, false)?;+ if hiroute_platform::windows::security::file_identity(&cli)?+ == hiroute_platform::windows::security::file_identity(&running)?+ {+ return Err(io::Error::other("INSTALL_PACKAGE_IN_USE"));+ }+ }+ let mut directories = BTreeSet::new();+ let mut expected = BTreeSet::from([manifest.clone()]);+ let mut files = vec![];+ for (name, facts) in &package.files {+ let path = root.join(Package::relative(name));+ expected.insert(path.clone());+ let mut parent = path.parent().ok_or_else(invalid)?;+ while parent != root {+ directories.insert(parent.to_owned());+ expected.insert(parent.to_owned());+ parent = parent.parent().ok_or_else(invalid)?;+ }+ if let Some(file) = regular(&path)? {+ if file.metadata()?.len() != facts.size+ || digest(&path)?.as_ref() != Some(&facts.sha256)+ {+ return Err(invalid());+ }+ files.push((path, facts.sha256.clone()));+ }+ }+ // Admit the entire remaining inventory before the first deletion. Missing owned+ // entries are allowed so a power loss during committed cleanup is resumable.+ inventory(root, &expected)?;+ let manifest_digest = digest(&manifest)?.ok_or_else(invalid)?;+ for (path, expected) in files {+ if digest(&path)?.as_ref() != Some(&expected) {+ return Err(invalid());+ }+ remove_owned(&path)?;+ }+ let mut directories: Vec<_> = directories.into_iter().collect();+ directories.sort_by_key(|path| std::cmp::Reverse(path.components().count()));+ for path in directories {+ match fs::remove_dir(&path) {+ Ok(()) => {}+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}+ Err(error) => return Err(error),+ }+ }+ if digest(&manifest)?.as_ref() != Some(&manifest_digest) {+ return Err(invalid());+ }+ remove_owned(&manifest)?;+ fs::remove_dir(root)+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn inaccessible_package_base_reports_cleanup_without_failing_the_committed_operation() {+ let temp = tempfile::tempdir().unwrap();+ let base = temp.path().join("not-a-directory");+ fs::write(&base, b"preserve unknown material").unwrap();+ let report =+ PackageCleanup::best_effort(prune_packages(&base, "x86_64-pc-windows-msvc", &[]));+ assert!(report.error.is_some());+ assert!(report.removed.is_empty());+ assert_eq!(fs::read(base).unwrap(), b"preserve unknown material");+ }+ fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {+ let temp = tempfile::tempdir().unwrap();+ let base = temp.path().canonicalize().unwrap().join("packages");+ fs::create_dir(&base).unwrap();+ let (source, package) =+ super::super::package::tests::fixture("x86_64-pc-windows-msvc", 0x8664);+ let root = base.join(package.directory_name());+ fs::rename(source.path(), &root).unwrap();+ (temp, base, root)+ }+ #[test]+ fn current_and_shell_rollback_sources_survive_until_their_owners_commit() {+ let (_temp, base, root) = fixture();+ let report =+ prune_packages(&base, "x86_64-pc-windows-msvc", std::slice::from_ref(&root)).unwrap();+ assert!(report.removed.is_empty());+ assert!(root.join("hirouted.exe").exists());+ let report = prune_packages(&base, "x86_64-pc-windows-msvc", &[]).unwrap();+ assert_eq!(report.removed.as_slice(), std::slice::from_ref(&root));+ assert!(!root.exists());+ assert!(+ prune_packages(&base, "x86_64-pc-windows-msvc", &[])+ .unwrap()+ .removed+ .is_empty()+ );+ }+ #[test]+ fn interrupted_cleanup_resumes_using_the_retained_manifest() {+ let (_temp, base, root) = fixture();+ fs::remove_file(root.join("hiroute.exe")).unwrap();+ assert_eq!(+ prune_packages(&base, "x86_64-pc-windows-msvc", &[])+ .unwrap()+ .removed+ .as_slice(),+ std::slice::from_ref(&root)+ );+ assert!(!root.exists());+ }+ #[test]+ fn changed_files_foreign_entries_and_other_targets_are_preserved_before_any_deletion() {+ for kind in ["changed", "foreign", "directory", "target"] {+ let (_temp, base, root) = fixture();+ let target = if kind == "target" {+ "aarch64-pc-windows-msvc"+ } else {+ "x86_64-pc-windows-msvc"+ };+ match kind {+ "changed" => fs::write(root.join("hirouted.exe"), b"changed").unwrap(),+ "foreign" => fs::write(root.join("my-file"), b"foreign").unwrap(),+ "directory" => fs::create_dir(root.join("my-directory")).unwrap(),+ _ => {}+ }+ let report = prune_packages(&base, target, &[]).unwrap();+ assert_eq!(report.preserved.as_slice(), std::slice::from_ref(&root));+ assert!(root.join("hiroute.exe").exists());+ assert!(root.join("package-manifest.json").exists());+ }+ }+ #[cfg(unix)]+ #[test]+ fn linked_payload_roots_never_redirect_cleanup() {+ use std::os::unix::fs::symlink;+ let (_temp, base, root) = fixture();+ let original = root.with_extension("foreign");+ fs::rename(&root, &original).unwrap();+ symlink(&original, &root).unwrap();+ let report = prune_packages(&base, "x86_64-pc-windows-msvc", &[]).unwrap();+ assert_eq!(report.preserved.len(), 2);+ assert!(original.join("hiroute.exe").exists());+ }+}diff --git a/crates/host-runtime/src/standalone_install/files.rs b/crates/host-runtime/src/standalone_install/files.rsnew file mode 100644index 00000000..d2607586--- /dev/null+++ b/crates/host-runtime/src/standalone_install/files.rs@@ -0,0 +1,189 @@+use super::invalid;+use sha2::{Digest, Sha256};+use std::{+ fs::{self, File},+ io::{self, Read, Write},+ path::{Path, PathBuf},+};++pub(crate) fn regular(path: &Path) -> io::Result<Option<File>> {+ for ancestor in path.ancestors() {+ match fs::symlink_metadata(ancestor) {+ Ok(metadata) => {+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes() & 0x400 != 0 {+ return Err(invalid());+ }+ }+ if metadata.file_type().is_symlink() {+ return Err(invalid());+ }+ }+ Err(e) if e.kind() == io::ErrorKind::NotFound => {}+ Err(e) => return Err(e),+ }+ }+ #[cfg(windows)]+ let result = hiroute_platform::windows::security::open_identity(path, false);+ #[cfg(not(windows))]+ let result = File::open(path);+ match result {+ Ok(file) if file.metadata()?.is_file() => Ok(Some(file)),+ Ok(_) => Err(invalid()),+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),+ Err(e) => Err(e),+ }+}+pub(crate) fn digest(path: &Path) -> io::Result<Option<String>> {+ let Some(mut file) = regular(path)? else {+ return Ok(None);+ };+ let mut sha = Sha256::new();+ let mut buffer = [0; 64 * 1024];+ loop {+ let count = file.read(&mut buffer)?;+ if count == 0 {+ break;+ }+ sha.update(&buffer[..count]);+ }+ Ok(Some(format!("{:x}", sha.finalize())))+}+pub(crate) fn read_json<T: serde::de::DeserializeOwned>(+ path: &Path,+ maximum: u64,+) -> io::Result<Option<T>> {+ let Some(mut file) = regular(path)? else {+ return Ok(None);+ };+ if file.metadata()?.len() > maximum {+ return Err(invalid());+ }+ let mut bytes = Vec::new();+ Read::by_ref(&mut file)+ .take(maximum + 1)+ .read_to_end(&mut bytes)?;+ if bytes.len() as u64 > maximum {+ return Err(invalid());+ }+ let value = unique_json(&bytes)?;+ serde_json::from_value(value)+ .map(Some)+ .map_err(|_| invalid())+}++fn unique_json(bytes: &[u8]) -> io::Result<serde_json::Value> {+ use serde::{+ Deserialize,+ de::{self, MapAccess, SeqAccess, Visitor},+ };+ struct Unique(serde_json::Value);+ impl<'de> Deserialize<'de> for Unique {+ fn deserialize<D: de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ struct V;+ impl<'de> Visitor<'de> for V {+ type Value = Unique;+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str("JSON with unique object keys")+ }+ fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<Unique, A::Error> {+ let mut map = serde_json::Map::new();+ while let Some((key, value)) = a.next_entry::<String, Unique>()? {+ if map.insert(key, value.0).is_some() {+ return Err(de::Error::custom("duplicate JSON key"));+ }+ }+ Ok(Unique(serde_json::Value::Object(map)))+ }+ fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<Unique, A::Error> {+ let mut values = vec![];+ while let Some(value) = a.next_element::<Unique>()? {+ values.push(value.0);+ }+ Ok(Unique(serde_json::Value::Array(values)))+ }+ fn visit_bool<E: de::Error>(self, v: bool) -> Result<Unique, E> {+ Ok(Unique(v.into()))+ }+ fn visit_i64<E: de::Error>(self, v: i64) -> Result<Unique, E> {+ Ok(Unique(v.into()))+ }+ fn visit_u64<E: de::Error>(self, v: u64) -> Result<Unique, E> {+ Ok(Unique(v.into()))+ }+ fn visit_f64<E: de::Error>(self, v: f64) -> Result<Unique, E> {+ serde_json::Number::from_f64(v)+ .map(|n| Unique(n.into()))+ .ok_or_else(|| de::Error::custom("non-finite number"))+ }+ fn visit_str<E: de::Error>(self, v: &str) -> Result<Unique, E> {+ Ok(Unique(v.into()))+ }+ fn visit_none<E: de::Error>(self) -> Result<Unique, E> {+ Ok(Unique(serde_json::Value::Null))+ }+ fn visit_unit<E: de::Error>(self) -> Result<Unique, E> {+ self.visit_none()+ }+ }+ d.deserialize_any(V)+ }+ }+ serde_json::from_slice::<Unique>(bytes)+ .map(|v| v.0)+ .map_err(|_| invalid())+}+pub(crate) fn directory(path: &Path) -> io::Result<()> {+ #[cfg(windows)]+ {+ let _ = hiroute_platform::windows::security::ensure_private_directory(path)?;+ }+ #[cfg(not(windows))]+ {+ fs::create_dir_all(path)?;+ }+ Ok(())+}+pub(crate) fn write_json(path: &Path, value: &impl serde::Serialize) -> io::Result<()> {+ let bytes = serde_json::to_vec(value).map_err(|_| invalid())?;+ if bytes.len() as u64 > super::MAX_RECORD {+ return Err(invalid());+ }+ #[cfg(windows)]+ return hiroute_platform::windows::background::write_private_record(path, &bytes);+ #[cfg(not(windows))]+ hiroute_platform::durable::write_private_atomic(path, &bytes)+}+pub(crate) fn nonce() -> io::Result<String> {+ let mut bytes = [0; 16];+ getrandom::fill(&mut bytes).map_err(|e| io::Error::other(e.to_string()))?;+ Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())+}+pub(crate) fn copy_new(source: &Path, target: &Path) -> io::Result<()> {+ let mut input = regular(source)?.ok_or_else(invalid)?;+ let mut output = fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(target)?;+ io::copy(&mut input, &mut output)?;+ output.flush()?;+ output.sync_all()+}+pub(crate) fn sibling(path: &Path) -> io::Result<PathBuf> {+ let name = path.file_name().ok_or_else(invalid)?.to_string_lossy();+ Ok(path.with_file_name(format!(".{name}.{}.stage", nonce()?)))+}+pub(crate) fn remove_owned(path: &Path) -> io::Result<()> {+ #[cfg(windows)]+ {+ let file = hiroute_platform::windows::security::open_delete(path, false)?;+ hiroute_platform::windows::security::delete_by_handle(&file)+ }+ #[cfg(not(windows))]+ {+ fs::remove_file(path)?;+ hiroute_platform::durable::directory_barrier(path.parent().ok_or_else(invalid)?)+ }+}diff --git a/crates/host-runtime/src/standalone_install/journal.rs b/crates/host-runtime/src/standalone_install/journal.rsnew file mode 100644index 00000000..cfaee18b--- /dev/null+++ b/crates/host-runtime/src/standalone_install/journal.rs@@ -0,0 +1,351 @@+use super::*;+use crate::{StandaloneInstallRecordV1, StandaloneLayout};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::{collections::BTreeSet, fs, path::PathBuf};++#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum Operation {+ Install,+ Uninstall,+}+#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum Phase {+ Prepared,+ Committed,+}+#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum EntryKind {+ Hardlink,+ Copy,+ Remove,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct Entry {+ pub destination: PathBuf,+ pub source: PathBuf,+ pub backup: PathBuf,+ pub old_sha256: Option<String>,+ pub new_sha256: Option<String>,+ pub kind: EntryKind,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct Journal {+ pub schema: String,+ pub operation: Operation,+ pub phase: Phase,+ pub old_marker: Option<StandaloneInstallRecordV1>,+ pub new_marker: StandaloneInstallRecordV1,+ pub old_definition: Option<Value>,+ pub new_definition: Value,+ pub files: Vec<Entry>,+}++/// Native manager effects stay at the Windows leaf; this core owns byte/recovery ordering.+pub trait ManagerHost {+ fn quiesce(&mut self, definitions: &[&Value]) -> io::Result<()>;+ fn register(&mut self, definition: &Value, previous: Option<&Value>) -> io::Result<()>;+ fn unregister(&mut self, definition: &Value) -> io::Result<()>;+}+impl Journal {+ pub fn path(layout: &StandaloneLayout) -> PathBuf {+ layout.data_root.join("service/install-journal.json")+ }+ pub fn read(layout: &StandaloneLayout) -> io::Result<Option<Self>> {+ #[cfg(windows)]+ if Self::path(layout).try_exists()? {+ hiroute_platform::windows::security::verify_owner_only(&Self::path(layout), false)?;+ }+ let journal: Option<Self> = read_json(&Self::path(layout), MAX_RECORD)?;+ if let Some(value) = &journal {+ value.validate(layout)?;+ }+ Ok(journal)+ }+ pub fn validate(&self, layout: &StandaloneLayout) -> io::Result<()> {+ let root = layout.home.join(".local/lib/hiroute");+ let definition = layout.data_root.join("service/windows-background.json");+ let skills: Vec<_> = [".agents", ".claude"]+ .iter()+ .map(|p| layout.home.join(p).join("skills/hiroute-management"))+ .collect();+ if self.schema != JOURNAL_SCHEMA+ || self.files.len() > 64+ || self.old_marker.is_some() != self.old_definition.is_some()+ {+ return Err(invalid());+ }+ for marker in self+ .old_marker+ .iter()+ .chain(std::iter::once(&self.new_marker))+ {+ marker.validate().map_err(|_| invalid())?;+ windows_machine(&marker.target)?;+ if marker.target != self.new_marker.target+ || marker.service_definition != definition+ || !within(&marker.install_root, &root)+ || marker.install_root == root+ || marker.install_root.parent() != Some(root.as_path())+ || marker.installed_skills != skills+ || marker.cpa_binary.as_ref()+ != Some(&marker.install_root.join("libexec/cliproxyapi.exe"))+ {+ return Err(invalid());+ }+ }+ let mut destinations = BTreeSet::new();+ for item in &self.files {+ let allowed = item.destination == layout.home.join(".local/bin/hiroute.exe")+ || item.destination == layout.home.join(".local/bin/hirouted.exe")+ || item.destination == layout.data_root.join("package-manifest.json")+ || within(&item.destination, &layout.data_root.join("licenses"))+ || within(&item.destination, &layout.data_root.join("docs"))+ || skills+ .iter()+ .any(|p| item.destination == p.join("SKILL.md"));+ if !allowed+ || !destinations.insert(&item.destination)+ || !within(+ &item.backup,+ &layout.data_root.join("service/install-backups"),+ )+ || item.backup == layout.data_root.join("service/install-backups")+ || !std::iter::once(&self.new_marker)+ .chain(self.old_marker.iter())+ .any(|m| within(&item.source, &m.install_root))+ || item+ .old_sha256+ .iter()+ .chain(item.new_sha256.iter())+ .any(|s| !hex(s))+ {+ return Err(invalid());+ }+ regular(&item.destination)?;+ regular(&item.backup)?;+ regular(&item.source)?;+ }+ Ok(())+ }+ pub fn persist(&self, layout: &StandaloneLayout) -> io::Result<()> {+ self.validate(layout)?;+ write_json(&Self::path(layout), self)+ }+ pub fn apply_files(&self) -> io::Result<()> {+ // Admit every current digest before replacing the first entry.+ for entry in &self.files {+ entry.check_current()?;+ }+ for entry in &self.files {+ entry.replace(false)?;+ }+ Ok(())+ }+ pub fn commit(&mut self, layout: &StandaloneLayout) -> io::Result<()> {+ self.phase = Phase::Committed;+ self.persist(layout)+ }+ pub fn finish(&self, layout: &StandaloneLayout) -> io::Result<()> {+ if self.phase != Phase::Committed {+ return Err(invalid());+ }+ if self.operation == Operation::Uninstall {+ self.remove_metadata(layout)?;+ }+ self.finish_backups(layout)+ }+ fn finish_backups(&self, layout: &StandaloneLayout) -> io::Result<()> {+ for item in &self.files {+ if let Some(actual) = digest(&item.backup)? {+ if Some(&actual) != item.old_sha256.as_ref() {+ return Err(invalid());+ }+ remove_owned(&item.backup)?;+ }+ }+ if Self::path(layout).try_exists()? {+ remove_owned(&Self::path(layout))?;+ }+ Ok(())+ }+ fn remove_metadata(&self, layout: &StandaloneLayout) -> io::Result<()> {+ let old = self.old_marker.as_ref().ok_or_else(invalid)?;+ let pairs = [+ (+ layout.marker_path.clone(),+ serde_json::to_value(old).map_err(|_| invalid())?,+ ),+ (+ old.service_definition.clone(),+ self.old_definition.clone().ok_or_else(invalid)?,+ ),+ ];+ for (path, expected) in pairs {+ if let Some(actual) = read_json::<Value>(&path, MAX_RECORD)? {+ if actual != expected {+ return Err(invalid());+ }+ remove_owned(&path)?;+ }+ }+ Ok(())+ }+ /// Prepared install rolls back; prepared uninstall completes.+ pub fn recover(+ mut self,+ layout: &StandaloneLayout,+ host: &mut impl ManagerHost,+ ) -> io::Result<()> {+ self.validate(layout)?;+ if self.phase == Phase::Committed {+ return self.finish(layout);+ }+ for entry in &self.files {+ entry.check_current()?;+ }+ let mut definitions = vec![&self.new_definition];+ if let Some(old) = &self.old_definition {+ definitions.push(old);+ }+ host.quiesce(&definitions)?;+ if self.operation == Operation::Uninstall {+ host.unregister(self.old_definition.as_ref().ok_or_else(invalid)?)?;+ self.apply_files()?;+ self.commit(layout)?;+ return self.finish(layout);+ }+ if let Some(old) = &self.old_marker {+ let old_definition = self.old_definition.as_ref().ok_or_else(invalid)?;+ host.register(old_definition, Some(&self.new_definition))?;+ write_json(&old.service_definition, old_definition)?;+ write_json(&layout.marker_path, old)?;+ } else {+ host.unregister(&self.new_definition)?;+ }+ for entry in self.files.iter().rev() {+ entry.replace(true)?;+ }+ if self.old_marker.is_none() {+ for path in [&layout.marker_path, &self.new_marker.service_definition] {+ if path.try_exists()? {+ let actual: Value = read_json(path, MAX_RECORD)?.ok_or_else(invalid)?;+ let expected = if path == &layout.marker_path {+ serde_json::to_value(&self.new_marker).map_err(|_| invalid())?+ } else {+ self.new_definition.clone()+ };+ if actual != expected {+ return Err(invalid());+ }+ remove_owned(path)?;+ }+ }+ }+ self.finish_backups(layout)+ }+}+impl Entry {+ fn check_current(&self) -> io::Result<()> {+ if let Some(actual) = digest(&self.destination)?+ && Some(&actual) != self.old_sha256.as_ref()+ && Some(&actual) != self.new_sha256.as_ref()+ {+ return Err(invalid());+ }+ Ok(())+ }+ pub fn replace(&self, rollback: bool) -> io::Result<()> {+ self.check_current()?;+ let expected = if rollback {+ &self.old_sha256+ } else {+ &self.new_sha256+ };+ if expected.is_none() {+ if self.destination.try_exists()? {+ remove_owned(&self.destination)?;+ }+ return Ok(());+ }+ let source = if rollback { &self.backup } else { &self.source };+ if digest(source)?.as_ref() != expected.as_ref() {+ return Err(invalid());+ }+ let stage = sibling(&self.destination)?;+ if self.kind == EntryKind::Hardlink {+ fs::hard_link(source, &stage)?;+ } else {+ copy_new(source, &stage)?;+ }+ let result = hiroute_platform::durable::rename(&stage, &self.destination);+ if stage.try_exists()? {+ remove_owned(&stage)?;+ }+ result+ }+}+/// Plan ownership first, then snapshot admitted entries. `source` already belongs to a verified package.+pub fn plan(+ entries: Vec<(PathBuf, PathBuf, EntryKind, String)>,+ layout: &StandaloneLayout,+ old: Option<&Package>,+ uninstall: bool,+) -> io::Result<Vec<Entry>> {+ let backup = layout+ .data_root+ .join("service/install-backups")+ .join(nonce()?);+ let mut result = Vec::new();+ for (index, (destination, source, kind, name)) in entries.into_iter().enumerate() {+ let actual = digest(&destination)?;+ if let Some(actual) = &actual {+ let owned = if name == "__package_manifest__" {+ read_json::<Value>(&destination, 1024 * 1024)?+ == old+ .map(serde_json::to_value)+ .transpose()+ .map_err(|_| invalid())?+ } else {+ old.and_then(|p| p.files.get(&name))+ .is_some_and(|facts| &facts.sha256 == actual)+ };+ if !owned {+ return Err(invalid());+ }+ }+ let new = if uninstall {+ None+ } else {+ Some(digest(&source)?.ok_or_else(invalid)?)+ };+ result.push(Entry {+ destination,+ source,+ backup: backup.join(index.to_string()),+ old_sha256: actual,+ new_sha256: new,+ kind,+ });+ }+ directory(&backup)?;+ for item in &result {+ directory(item.destination.parent().ok_or_else(invalid)?)?;+ if item.old_sha256.is_some() {+ if item.kind == EntryKind::Hardlink {+ fs::hard_link(&item.destination, &item.backup)?;+ } else {+ copy_new(&item.destination, &item.backup)?;+ }+ }+ }+ Ok(result)+}++#[cfg(test)]+mod tests;diff --git a/crates/host-runtime/src/standalone_install/journal/tests.rs b/crates/host-runtime/src/standalone_install/journal/tests.rsnew file mode 100644index 00000000..87ec4396--- /dev/null+++ b/crates/host-runtime/src/standalone_install/journal/tests.rs@@ -0,0 +1,268 @@+use super::*;+use serde_json::json;++#[derive(Default)]+struct Manager {+ calls: Vec<&'static str>,+}+impl ManagerHost for Manager {+ fn quiesce(&mut self, _: &[&Value]) -> io::Result<()> {+ self.calls.push("stop");+ Ok(())+ }+ fn register(&mut self, _: &Value, _: Option<&Value>) -> io::Result<()> {+ self.calls.push("register");+ Ok(())+ }+ fn unregister(&mut self, _: &Value) -> io::Result<()> {+ self.calls.push("unregister");+ Ok(())+ }+}+fn fixture() -> (tempfile::TempDir, StandaloneLayout, Journal) {+ let temp = tempfile::tempdir().unwrap();+ let home = temp.path().canonicalize().unwrap();+ let layout =+ StandaloneLayout::from_values(false, Some(home.clone()), None, None, None).unwrap();+ let root = home.join(".local/lib/hiroute/0.3.1-aaaaaaaaaaaa");+ directory(&root).unwrap();+ directory(&layout.data_root.join("service")).unwrap();+ directory(&home.join(".local/bin")).unwrap();+ let source = root.join("hiroute.exe");+ fs::write(&source, b"new").unwrap();+ let marker = StandaloneInstallRecordV1 {+ schema_version: crate::STANDALONE_INSTALL_SCHEMA_V1.into(),+ version: "0.3.1".into(),+ target: "x86_64-pc-windows-msvc".into(),+ install_root: root.clone(),+ service_definition: layout.data_root.join("service/windows-background.json"),+ installed_skills: [".agents", ".claude"]+ .iter()+ .map(|p| home.join(p).join("skills/hiroute-management"))+ .collect(),+ cpa_binary: Some(root.join("libexec/cliproxyapi.exe")),+ cpa_sha256: Some("a".repeat(64)),+ };+ let entries = vec![Entry {+ destination: home.join(".local/bin/hiroute.exe"),+ source,+ backup: layout.data_root.join("service/install-backups/batch/0"),+ old_sha256: None,+ new_sha256: Some(format!("{:x}", sha2::Sha256::digest(b"new"))),+ kind: EntryKind::Hardlink,+ }];+ let journal = Journal {+ schema: JOURNAL_SCHEMA.into(),+ operation: Operation::Install,+ phase: Phase::Prepared,+ old_marker: None,+ new_marker: marker,+ old_definition: None,+ new_definition: json!({"manager":"task"}),+ files: entries,+ };+ (temp, layout, journal)+}+use sha2::Digest;+#[test]+fn pending_manager_delete_keeps_prepared_journal_and_all_owned_files() {+ struct Pending;+ impl ManagerHost for Pending {+ fn quiesce(&mut self, _: &[&Value]) -> io::Result<()> {+ Ok(())+ }+ fn register(&mut self, _: &Value, _: Option<&Value>) -> io::Result<()> {+ unreachable!()+ }+ fn unregister(&mut self, _: &Value) -> io::Result<()> {+ Err(io::Error::other("deletion pending"))+ }+ }+ let (_temp, layout, mut journal) = fixture();+ journal.apply_files().unwrap();+ journal.operation = Operation::Uninstall;+ journal.old_marker = Some(journal.new_marker.clone());+ journal.old_definition = Some(journal.new_definition.clone());+ journal.files[0].old_sha256 = journal.files[0].new_sha256.take();+ journal.persist(&layout).unwrap();+ assert!(journal.recover(&layout, &mut Pending).is_err());+ assert!(Journal::read(&layout).unwrap().unwrap().phase == Phase::Prepared);+ assert_eq!(+ fs::read(layout.home.join(".local/bin/hiroute.exe")).unwrap(),+ b"new"+ );+}+#[test]+fn duplicate_json_object_keys_are_rejected() {+ let (_temp, layout, _) = fixture();+ fs::write(+ Journal::path(&layout),+ br#"{"schema":"first","schema":"second"}"#,+ )+ .unwrap();+ assert!(Journal::read(&layout).is_err());+}+#[test]+fn first_install_crash_before_or_after_each_file_rolls_back_without_changing_business_data() {+ for applied in [false, true] {+ let (_temp, layout, journal) = fixture();+ let mut manager = Manager::default();+ directory(&layout.state_root).unwrap();+ fs::write(layout.state_root.join("business"), b"keep").unwrap();+ journal.persist(&layout).unwrap();+ if applied {+ journal.apply_files().unwrap();+ write_json(&layout.marker_path, &journal.new_marker).unwrap();+ }+ Journal::read(&layout)+ .unwrap()+ .unwrap()+ .recover(&layout, &mut manager)+ .unwrap();+ assert!(!journal.files[0].destination.exists());+ assert!(!layout.marker_path.exists());+ assert_eq!(+ fs::read(layout.state_root.join("business")).unwrap(),+ b"keep"+ );+ assert_eq!(manager.calls, ["stop", "unregister"]);+ assert!(Journal::read(&layout).unwrap().is_none());+ }+}+#[test]+fn prepared_upgrade_restores_exact_old_bytes_and_registration() {+ for replaced in [false, true] {+ let (_temp, layout, mut journal) = fixture();+ let old_root = layout.home.join(".local/lib/hiroute/0.3.0-bbbbbbbbbbbb");+ directory(&old_root).unwrap();+ let old = old_root.join("hiroute.exe");+ fs::write(&old, b"old").unwrap();+ let entry = &mut journal.files[0];+ fs::write(&entry.destination, b"old").unwrap();+ directory(entry.backup.parent().unwrap()).unwrap();+ copy_new(&old, &entry.backup).unwrap();+ entry.old_sha256 = digest(&old).unwrap();+ let mut marker = journal.new_marker.clone();+ marker.install_root = old_root.clone();+ marker.version = "0.3.0".into();+ marker.cpa_binary = Some(old_root.join("libexec/cliproxyapi.exe"));+ journal.old_marker = Some(marker.clone());+ journal.old_definition = Some(json!({"manager":"task","old":true}));+ journal.persist(&layout).unwrap();+ if replaced {+ journal.apply_files().unwrap();+ }+ let mut host = Manager::default();+ Journal::read(&layout)+ .unwrap()+ .unwrap()+ .recover(&layout, &mut host)+ .unwrap();+ assert_eq!(fs::read(&journal.files[0].destination).unwrap(), b"old");+ assert_eq!(+ read_json::<StandaloneInstallRecordV1>(&layout.marker_path, MAX_RECORD).unwrap(),+ Some(marker)+ );+ assert_eq!(host.calls, ["stop", "register"]);+ }+}+#[test]+fn foreign_change_refuses_all_replacement_and_recovery_without_deleting_it() {+ let (_temp, layout, journal) = fixture();+ journal.persist(&layout).unwrap();+ fs::write(&journal.files[0].destination, b"foreign").unwrap();+ assert!(journal.apply_files().is_err());+ assert!(journal.recover(&layout, &mut Manager::default()).is_err());+ assert_eq!(+ fs::read(layout.home.join(".local/bin/hiroute.exe")).unwrap(),+ b"foreign"+ );+ assert!(Journal::path(&layout).exists());+}+#[test]+fn committed_install_never_replays_file_effects_or_registration() {+ let (_temp, layout, mut journal) = fixture();+ journal.apply_files().unwrap();+ journal.commit(&layout).unwrap();+ let mut host = Manager::default();+ Journal::read(&layout)+ .unwrap()+ .unwrap()+ .recover(&layout, &mut host)+ .unwrap();+ assert!(host.calls.is_empty());+ assert_eq!(fs::read(&journal.files[0].destination).unwrap(), b"new");+}+#[test]+fn prepared_uninstall_completes_after_each_crash_boundary_and_keeps_data() {+ for already_removed in [false, true] {+ let (_temp, layout, mut journal) = fixture();+ journal.apply_files().unwrap();+ write_json(&layout.marker_path, &journal.new_marker).unwrap();+ write_json(+ &journal.new_marker.service_definition,+ &journal.new_definition,+ )+ .unwrap();+ journal.operation = Operation::Uninstall;+ journal.old_marker = Some(journal.new_marker.clone());+ journal.old_definition = Some(journal.new_definition.clone());+ let entry = &mut journal.files[0];+ entry.old_sha256 = entry.new_sha256.take();+ directory(entry.backup.parent().unwrap()).unwrap();+ copy_new(&entry.source, &entry.backup).unwrap();+ journal.persist(&layout).unwrap();+ if already_removed {+ journal.apply_files().unwrap();+ }+ let mut host = Manager::default();+ journal.recover(&layout, &mut host).unwrap();+ assert_eq!(host.calls, ["stop", "unregister"]);+ assert!(!layout.marker_path.exists());+ assert!(!layout.home.join(".local/bin/hiroute.exe").exists());+ }+}+#[test]+fn current_journal_has_closed_fields_and_refuses_escaped_paths() {+ let (_temp, layout, journal) = fixture();+ let bytes = serde_json::to_value(&journal).unwrap();+ assert_eq!(+ bytes+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from([+ "files",+ "new_definition",+ "new_marker",+ "old_definition",+ "old_marker",+ "operation",+ "phase",+ "schema"+ ])+ );+ for field in ["destination", "source", "backup"] {+ let mut changed = bytes.clone();+ changed["files"][0][field] = json!(layout.home.join("foreign/entry"));+ assert!(+ serde_json::from_value::<Journal>(changed)+ .unwrap()+ .validate(&layout)+ .is_err()+ );+ }+ let mut changed = bytes.clone();+ changed["secret"] = json!("unexpected");+ assert!(serde_json::from_value::<Journal>(changed).is_err());+ let mut changed = bytes;+ changed["schema"] = json!("hiroute.windows-install-journal/v2");+ assert!(+ serde_json::from_value::<Journal>(changed)+ .unwrap()+ .validate(&layout)+ .is_err()+ );+}diff --git a/crates/host-runtime/src/standalone_install/mod.rs b/crates/host-runtime/src/standalone_install/mod.rsnew file mode 100644index 00000000..ebce3ef3--- /dev/null+++ b/crates/host-runtime/src/standalone_install/mod.rs@@ -0,0 +1,49 @@+//! The single Windows installation transaction and its current journal schema.+mod cleanup;+mod files;+mod journal;+mod package;+#[cfg(any(windows, test))]+mod uninstall;+pub use cleanup::{PackageCleanup, prune_packages};+pub(crate) use files::*;+pub use journal::{Entry, EntryKind, Journal, ManagerHost, Operation, Phase, plan};+pub use package::{Package, PackageFile};+use std::{io, path::Path};+#[cfg(windows)]+pub mod windows;++pub const JOURNAL_SCHEMA: &str = "hiroute.windows-install-journal/v1";+pub fn windows_machine(target: &str) -> io::Result<u16> {+ match target {+ "x86_64-pc-windows-msvc" => Ok(0x8664),+ "aarch64-pc-windows-msvc" => Ok(0xaa64),+ _ => Err(io::Error::other("INSTALL_ARCHITECTURE_UNSUPPORTED")),+ }+}+pub const MAX_RECORD: u64 = 64 * 1024;+pub(crate) fn invalid() -> io::Error {+ io::Error::new(io::ErrorKind::InvalidData, "INSTALL_OWNERSHIP_CONFLICT")+}+pub(crate) fn portable(value: &str, limit: usize) -> bool {+ !value.is_empty()+ && value.len() <= limit+ && value != "."+ && value != ".."+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))+}+pub(crate) fn hex(value: &str) -> bool {+ value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit())+}+pub(crate) fn within(path: &Path, root: &Path) -> bool {+ path.is_absolute()+ && path.starts_with(root)+ && !path.components().any(|p| {+ matches!(+ p,+ std::path::Component::ParentDir | std::path::Component::CurDir+ )+ })+}diff --git a/crates/host-runtime/src/standalone_install/package.rs b/crates/host-runtime/src/standalone_install/package.rsnew file mode 100644index 00000000..278183b2--- /dev/null+++ b/crates/host-runtime/src/standalone_install/package.rs@@ -0,0 +1,212 @@+use super::*;+use serde::{Deserialize, Serialize};+use std::{+ collections::{BTreeMap, BTreeSet},+ fs,+ io::{Read, Seek, SeekFrom},+ path::PathBuf,+};++#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct PackageFile {+ pub sha256: String,+ pub size: u64,+ pub mode: String,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct Archive {+ filename: String,+ sha256: String,+ size: u64,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct Cpa {+ version: String,+ sha256: String,+}+#[derive(Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct Package {+ pub schema: String,+ pub version: String,+ pub revision: String,+ pub target: String,+ archive: Archive,+ pub files: BTreeMap<String, PackageFile>,+ cpa: Cpa,+ distribution: String,+}+impl Package {+ pub fn directory_name(&self) -> String {+ format!(+ "{}-{}",+ self.version,+ &self.revision[..self.revision.len().min(12)]+ )+ }+ pub fn read(directory: &Path) -> io::Result<Self> {+ let value: Self = read_json(&directory.join("package-manifest.json"), 1024 * 1024)?+ .ok_or_else(invalid)?;+ value.validate()?;+ value.verify_directory(directory)?;+ Ok(value)+ }+ pub fn validate(&self) -> io::Result<()> {+ windows_machine(&self.target)?;+ let base: BTreeSet<&str> = [+ "bin/hiroute.exe",+ "bin/hirouted.exe",+ "libexec/cliproxyapi.exe",+ "licenses/CLIProxyAPI-LICENSE",+ "licenses/HiRoute-LICENSE",+ "licenses/THIRD-PARTY-LICENSES.txt",+ "licenses/third-party-licenses.json",+ "skills/hiroute-management/SKILL.md",+ "docs/standalone-cli.md",+ ]+ .into_iter()+ .collect();+ if self.schema != "hiroute.standalone-package/v1"+ || !portable(&self.version, 64)+ || !portable(&self.revision, 128)+ || self.distribution != "integration-candidate"+ || self.archive.filename.len() > 240+ || !self.archive.filename.ends_with(".tar.gz")+ || self.archive.filename.contains(['/', '\\'])+ || !hex(&self.archive.sha256)+ || self.archive.size == 0+ || self.archive.size > 1024 * 1024 * 1024+ || self.cpa.version.is_empty()+ || self.cpa.version.len() > 128+ || self.cpa.version.chars().any(char::is_control)+ || !hex(&self.cpa.sha256)+ || self.files.len() > base.len() + 2048+ || base.iter().any(|name| !self.files.contains_key(*name))+ {+ return Err(invalid());+ }+ let mut total = 0_u64;+ let mut console = 0;+ for (name, file) in &self.files {+ if !base.contains(name.as_str()) {+ if !name.starts_with("console/")+ || name.len() > 240+ || name.split('/').any(|part| {+ !portable(part, 240)+ && !(part.contains('@')+ && part.bytes().all(|b| {+ b.is_ascii_alphanumeric()+ || matches!(b, b'.' | b'_' | b'-' | b'@')+ }))+ })+ || file.size > 16 * 1024 * 1024+ {+ return Err(invalid());+ }+ console += file.size;+ }+ if !hex(&file.sha256)+ || file.mode+ != if name.starts_with("bin/") || name.starts_with("libexec/") {+ "executable"+ } else {+ "read_only"+ }+ {+ return Err(invalid());+ }+ total = total.checked_add(file.size).ok_or_else(invalid)?;+ }+ if total > 1024 * 1024 * 1024+ || console > 64 * 1024 * 1024+ || (console > 0 && !self.files.contains_key("console/index.html"))+ || self.files["libexec/cliproxyapi.exe"].sha256 != self.cpa.sha256+ {+ return Err(invalid());+ }+ Ok(())+ }+ pub fn relative(name: &str) -> &str {+ name.strip_prefix("bin/").unwrap_or(name)+ }+ pub fn verify_directory(&self, directory: &Path) -> io::Result<()> {+ let mut expected: BTreeSet<PathBuf> = self+ .files+ .keys()+ .map(|name| PathBuf::from(Self::relative(name)))+ .collect();+ expected.insert("package-manifest.json".into());+ if walk(directory, directory)? != expected {+ return Err(invalid());+ }+ for (name, facts) in &self.files {+ let path = directory.join(Self::relative(name));+ let file = regular(&path)?.ok_or_else(invalid)?;+ if file.metadata()?.len() != facts.size+ || digest(&path)?.as_deref() != Some(&facts.sha256)+ {+ return Err(invalid());+ }+ if facts.mode == "executable" {+ pe_machine(file, windows_machine(&self.target)?)?;+ }+ }+ Ok(())+ }+ pub fn cpa_digest(&self) -> &str {+ &self.cpa.sha256+ }+ /// The current producer serializes one closed manifest shape.+ pub fn canonical(&self) -> io::Result<Vec<u8>> {+ serde_json::to_vec(self).map_err(|_| invalid())+ }+}+fn walk(root: &Path, current: &Path) -> io::Result<BTreeSet<PathBuf>> {+ let mut files = BTreeSet::new();+ for entry in fs::read_dir(current)? {+ let entry = entry?;+ let path = entry.path();+ let metadata = fs::symlink_metadata(&path)?;+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes() & 0x400 != 0 {+ return Err(invalid());+ }+ }+ if metadata.file_type().is_symlink() {+ return Err(invalid());+ }+ if metadata.is_dir() {+ files.extend(walk(root, &path)?);+ } else {+ let _ = regular(&path)?.ok_or_else(invalid)?;+ files.insert(path.strip_prefix(root).map_err(|_| invalid())?.to_owned());+ }+ if files.len() > 2060 {+ return Err(invalid());+ }+ }+ Ok(files)+}+fn pe_machine(mut file: fs::File, machine: u16) -> io::Result<()> {+ let mut dos = [0; 64];+ file.read_exact(&mut dos)?;+ let offset = u32::from_le_bytes(dos[60..64].try_into().map_err(|_| invalid())?);+ if &dos[..2] != b"MZ" || !(64..=16 * 1024 * 1024).contains(&offset) {+ return Err(invalid());+ }+ file.seek(SeekFrom::Start(u64::from(offset)))?;+ let mut pe = [0; 6];+ file.read_exact(&mut pe)?;+ if &pe[..4] != b"PE\0\0" || u16::from_le_bytes([pe[4], pe[5]]) != machine {+ return Err(invalid());+ }+ Ok(())+}++#[cfg(test)]+pub(super) mod tests;diff --git a/crates/host-runtime/src/standalone_install/package/tests.rs b/crates/host-runtime/src/standalone_install/package/tests.rsnew file mode 100644index 00000000..25adf557--- /dev/null+++ b/crates/host-runtime/src/standalone_install/package/tests.rs@@ -0,0 +1,92 @@+use super::*;+use sha2::{Digest, Sha256};++fn image(machine: u16) -> Vec<u8> {+ let mut bytes = vec![0; 70];+ bytes[..2].copy_from_slice(b"MZ");+ bytes[60..64].copy_from_slice(&64_u32.to_le_bytes());+ bytes[64..68].copy_from_slice(b"PE\0\0");+ bytes[68..70].copy_from_slice(&machine.to_le_bytes());+ bytes+}+pub(crate) fn fixture(target: &str, machine: u16) -> (tempfile::TempDir, Package) {+ let root = tempfile::tempdir().unwrap();+ let mut files = BTreeMap::new();+ for name in [+ "bin/hiroute.exe",+ "bin/hirouted.exe",+ "libexec/cliproxyapi.exe",+ "licenses/CLIProxyAPI-LICENSE",+ "licenses/HiRoute-LICENSE",+ "licenses/THIRD-PARTY-LICENSES.txt",+ "licenses/third-party-licenses.json",+ "skills/hiroute-management/SKILL.md",+ "docs/standalone-cli.md",+ ] {+ let executable = name.ends_with(".exe");+ let bytes = if executable {+ image(machine)+ } else {+ b"resource".to_vec()+ };+ let path = root.path().join(Package::relative(name));+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, &bytes).unwrap();+ files.insert(+ name.into(),+ PackageFile {+ sha256: format!("{:x}", Sha256::digest(&bytes)),+ size: bytes.len() as u64,+ mode: if executable {+ "executable"+ } else {+ "read_only"+ }+ .into(),+ },+ );+ }+ let package = Package {+ schema: "hiroute.standalone-package/v1".into(),+ version: "0.3.1".into(),+ revision: "a".repeat(40),+ target: target.into(),+ archive: Archive {+ filename: "package.tar.gz".into(),+ sha256: "b".repeat(64),+ size: 1,+ },+ cpa: Cpa {+ version: "fixture".into(),+ sha256: files["libexec/cliproxyapi.exe"].sha256.clone(),+ },+ files,+ distribution: "integration-candidate".into(),+ };+ fs::write(+ root.path().join("package-manifest.json"),+ package.canonical().unwrap(),+ )+ .unwrap();+ (root, package)+}+#[test]+fn both_windows_targets_verify_complete_native_inventories() {+ for (target, machine) in [+ ("x86_64-pc-windows-msvc", 0x8664),+ ("aarch64-pc-windows-msvc", 0xaa64),+ ] {+ let (root, _) = fixture(target, machine);+ assert_eq!(Package::read(root.path()).unwrap().target, target);+ }+}+#[test]+fn declared_target_cannot_accept_the_other_executable_architecture() {+ for (target, machine) in [+ ("x86_64-pc-windows-msvc", 0xaa64),+ ("aarch64-pc-windows-msvc", 0x8664),+ ] {+ let (root, _) = fixture(target, machine);+ assert!(Package::read(root.path()).is_err());+ }+}diff --git a/crates/host-runtime/src/standalone_install/uninstall.rs b/crates/host-runtime/src/standalone_install/uninstall.rsnew file mode 100644index 00000000..22487491--- /dev/null+++ b/crates/host-runtime/src/standalone_install/uninstall.rs@@ -0,0 +1,176 @@+//! Restoration policy is separate from native Task effects and never opens user stores.+use crate::StandaloneLayout;+use std::{fs, io, path::Path};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Restoration {+ NotNeeded,+ Restored,+ Unverified,+}++fn present(path: &Path) -> io::Result<bool> {+ // A dangling ancestor must not turn unknown/restorable state into proof+ // that this is a pristine installation. Do not follow links or junctions.+ for ancestor in path.ancestors() {+ match fs::symlink_metadata(ancestor) {+ Ok(metadata) => {+ if metadata.file_type().is_symlink() {+ return Err(super::invalid());+ }+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes() & 0x400 != 0 {+ return Err(super::invalid());+ }+ }+ }+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}+ Err(error) => return Err(error),+ }+ }+ match fs::symlink_metadata(path) {+ Ok(_) => Ok(true),+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error),+ }+}++pub(super) fn restore(+ layout: &StandaloneLayout,+ allow_unavailable: bool,+ remove_data: bool,+ start: impl FnOnce() -> io::Result<()>,+ restore: impl FnOnce() -> io::Result<()>,+) -> io::Result<Restoration> {+ // Exceptional removal must retain the complete restoration material.+ if allow_unavailable && remove_data {+ return Err(io::Error::other("AGENT_RESTORE_DATA_REQUIRED"));+ }+ if !present(&layout.storage_root())?+ && !present(&layout.state_root.join("storage.upgrade-backups"))?+ {+ return Ok(Restoration::NotNeeded);+ }+ match start().and_then(|()| restore()) {+ Ok(()) => Ok(Restoration::Restored),+ Err(error) if allow_unavailable && error.to_string() == "AGENT_CONTROL_UNAVAILABLE" => {+ Ok(Restoration::Unverified)+ }+ Err(error) => Err(error),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ fn layout() -> (tempfile::TempDir, StandaloneLayout) {+ let temp = tempfile::tempdir().unwrap();+ let home = temp.path().canonicalize().unwrap();+ let layout = StandaloneLayout::from_values(false, Some(home), None, None, None).unwrap();+ (temp, layout)+ }+ #[test]+ fn first_install_without_agent_storage_never_requires_a_daemon() {+ let (_temp, layout) = layout();+ assert_eq!(+ restore(+ &layout,+ false,+ false,+ || panic!("daemon start"),+ || panic!("Agent query")+ )+ .unwrap(),+ Restoration::NotNeeded+ );+ assert!(!layout.state_root.exists());+ }+ #[cfg(unix)]+ #[test]+ fn a_dangling_state_ancestor_is_not_evidence_of_an_empty_installation() {+ let (_temp, layout) = layout();+ fs::create_dir_all(layout.state_root.parent().unwrap()).unwrap();+ std::os::unix::fs::symlink(layout.home.join("missing"), &layout.state_root).unwrap();+ assert!(+ restore(+ &layout,+ false,+ false,+ || panic!("start"),+ || panic!("restore")+ )+ .is_err()+ );+ assert!(+ fs::symlink_metadata(&layout.state_root)+ .unwrap()+ .file_type()+ .is_symlink()+ );+ }+ #[test]+ fn unavailable_service_requires_consent_and_preserves_all_recovery_material() {+ for backup in [false, true] {+ let (_temp, layout) = layout();+ let root = if backup {+ layout.state_root.join("storage.upgrade-backups")+ } else {+ layout.storage_root()+ };+ fs::create_dir_all(&root).unwrap();+ let sentinel = root.join("keep");+ fs::write(&sentinel, b"restore material").unwrap();+ for allowed in [false, true] {+ let result = restore(+ &layout,+ allowed,+ false,+ || Err(io::Error::other("AGENT_CONTROL_UNAVAILABLE")),+ || panic!("unavailable service"),+ );+ if allowed {+ assert_eq!(result.unwrap(), Restoration::Unverified);+ } else {+ assert_eq!(result.unwrap_err().to_string(), "AGENT_CONTROL_UNAVAILABLE");+ }+ assert_eq!(fs::read(&sentinel).unwrap(), b"restore material");+ }+ assert_eq!(+ restore(+ &layout,+ true,+ true,+ || panic!("start"),+ || panic!("restore")+ )+ .unwrap_err()+ .to_string(),+ "AGENT_RESTORE_DATA_REQUIRED"+ );+ }+ }+ #[test]+ fn consent_never_bypasses_an_enumerated_conflict_or_foreign_registration() {+ let (_temp, layout) = layout();+ fs::create_dir_all(layout.storage_root()).unwrap();+ for reason in [+ "AGENT_RESTORE_REQUIRED:[\"codex\"]",+ "INSTALL_OWNERSHIP_CONFLICT",+ ] {+ let result = restore(+ &layout,+ true,+ false,+ || Ok(()),+ || Err(io::Error::other(reason)),+ );+ assert_eq!(result.unwrap_err().to_string(), reason);+ }+ assert_eq!(+ restore(&layout, false, false, || Ok(()), || Ok(())).unwrap(),+ Restoration::Restored+ );+ }+}diff --git a/crates/host-runtime/src/standalone_install/windows.rs b/crates/host-runtime/src/standalone_install/windows.rsnew file mode 100644index 00000000..730536fc--- /dev/null+++ b/crates/host-runtime/src/standalone_install/windows.rs@@ -0,0 +1,556 @@+//! Current-account Task installation. SCM ownership is never adopted by this path.+use super::*;+use crate::{+ ConsoleListenerDesiredV1, ConsoleListenerStore, StandaloneInstallRecordV1, StandaloneLayout,+};+use fs2::FileExt;+use hiroute_platform::windows::{+ background::{self, Definition, Manager},+ lifecycle, security, task,+};+use serde::Deserialize;+use serde_json::{Value, json};+use std::{+ fs::{self, File},+ path::PathBuf,+ time::Duration,+};++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct InstallRequest {+ pub schema: String,+ pub package_directory: PathBuf,+ #[serde(default = "yes")]+ pub autostart: bool,+ #[serde(default)]+ pub console_loopback: bool,+ #[serde(default)]+ pub allow_legacy_stop: bool,+ #[serde(default)]+ pub defer_package_cleanup: bool,+ #[serde(default = "timeout")]+ pub timeout_ms: u64,+}+#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UninstallRequest {+ pub schema: String,+ #[serde(default)]+ pub remove_data: bool,+ #[serde(default)]+ pub allow_legacy_stop: bool,+ #[serde(default)]+ pub allow_unavailable_agent_restore: bool,+ #[serde(default = "timeout")]+ pub timeout_ms: u64,+}+fn yes() -> bool {+ true+}+fn timeout() -> u64 {+ 30_000+}+fn deadline(value: u64) -> io::Result<Duration> {+ if !(100..=300_000).contains(&value) {+ return Err(invalid());+ }+ Ok(Duration::from_millis(value))+}+fn layout() -> io::Result<StandaloneLayout> {+ StandaloneLayout::from_environment().map_err(|_| invalid())+}+fn definition_path(layout: &StandaloneLayout) -> PathBuf {+ layout.data_root.join("service/windows-background.json")+}+fn definition(value: &Value) -> io::Result<Definition> {+ let value: Definition = serde_json::from_value(value.clone()).map_err(|_| invalid())?;+ value.validate()?;+ if value.manager != Manager::Task {+ return Err(io::Error::other("INSTALL_SCM_MANAGED"));+ }+ Ok(value)+}+fn admit_existing(layout: &StandaloneLayout) -> io::Result<()> {+ let path = definition_path(layout);+ if path.try_exists()? {+ let value = background::read_definition(&path)?;+ if value.manager != Manager::Task {+ return Err(io::Error::other("INSTALL_SCM_MANAGED"));+ }+ }+ if let Some(journal) = Journal::read(layout)? {+ definition(&journal.new_definition)?;+ if let Some(old) = &journal.old_definition {+ definition(old)?;+ }+ if journal.new_marker.target != hiroute_platform::windows::install::native_target()? {+ return Err(io::Error::other("INSTALL_ARCHITECTURE_UNSUPPORTED"));+ }+ }+ if let Some(marker) = read_json::<StandaloneInstallRecordV1>(&layout.marker_path, MAX_RECORD)? {+ marker.validate().map_err(|_| invalid())?;+ if marker.target != hiroute_platform::windows::install::native_target()? {+ return Err(io::Error::other("INSTALL_ARCHITECTURE_UNSUPPORTED"));+ }+ }+ Ok(())+}+pub fn preflight() -> io::Result<()> {+ admit_existing(&layout()?)+}+fn lock(layout: &StandaloneLayout) -> io::Result<File> {+ // Admission is deliberately before creation of directories or the lock file.+ admit_existing(layout)?;+ let file = lock_file(layout)?;+ admit_existing(layout)?;+ Ok(file)+}+fn lock_file(layout: &StandaloneLayout) -> io::Result<File> {+ security::initialize_current_process_private_defaults()?;+ let parent = security::ensure_private_directory(&layout.data_root.join("service"))?;+ let path = layout.data_root.join("service/install.lock");+ let file = match security::open_read_write(&path) {+ Ok(file) => file,+ Err(e) if e.kind() == io::ErrorKind::NotFound => {+ security::create_owner_only_file_at(&parent, std::ffi::OsStr::new("install.lock"))?+ }+ Err(e) => return Err(e),+ };+ file.try_lock_exclusive()+ .map_err(|_| io::Error::other("INSTALL_MAINTENANCE_BUSY"))?;+ Ok(file)+}++struct NativeHost<'a> {+ layout: &'a StandaloneLayout,+ timeout: Duration,+ allow_legacy_stop: bool,+ allow_unavailable_stop: bool,+}+impl ManagerHost for NativeHost<'_> {+ fn quiesce(&mut self, values: &[&Value]) -> io::Result<()> {+ let mut mismatch = false;+ for value in values {+ let value = definition(value)?;+ match task::active(&value) {+ Ok(false) => return Ok(()),+ Ok(true) => {+ let endpoint = self.layout.lifecycle_endpoint();+ match lifecycle::drain(&endpoint, &value.daemon, self.timeout) {+ Ok(()) => {}+ Err(e)+ if e.kind() == io::ErrorKind::Unsupported && self.allow_legacy_stop => {+ }+ Err(e)+ if self.allow_unavailable_stop+ && matches!(+ e.kind(),+ io::ErrorKind::NotFound+ | io::ErrorKind::TimedOut+ | io::ErrorKind::ConnectionRefused+ | io::ErrorKind::ConnectionReset+ | io::ErrorKind::NotConnected+ | io::ErrorKind::BrokenPipe+ ) =>+ {+ // Only the exact owner/image-verified Task can be stopped here.+ task::force_stop(&value)?;+ let deadline = std::time::Instant::now() + self.timeout;+ while task::active(&value)? {+ if std::time::Instant::now() >= deadline {+ return Err(io::ErrorKind::TimedOut.into());+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ return Ok(());+ }+ Err(e) => return Err(e),+ }+ let stopped = lifecycle::stop_with_fallback(+ &endpoint,+ &value.daemon,+ self.timeout,+ || task::force_stop(&value),+ );+ if stopped.is_err() {+ let _ = lifecycle::upgrade(+ &endpoint,+ &value.daemon,+ "upgrade-cancel",+ Duration::from_secs(2),+ );+ }+ return stopped;+ }+ Err(_) => mismatch = true,+ }+ }+ if mismatch { Err(invalid()) } else { Ok(()) }+ }+ fn register(&mut self, value: &Value, previous: Option<&Value>) -> io::Result<()> {+ let value = definition(value)?;+ let previous = previous.map(definition).transpose()?;+ value.verify_image()?;+ task::register(&value, previous.as_ref())+ }+ fn unregister(&mut self, value: &Value) -> io::Result<()> {+ task::unregister(&definition(value)?)+ }+}+/// Resume an interrupted installer only through its explicit maintenance entry.+pub fn recover_pending() -> io::Result<()> {+ let layout = layout()?;+ let _lock = lock(&layout)?;+ let mut host = NativeHost {+ layout: &layout,+ timeout: Duration::from_secs(30),+ allow_legacy_stop: false,+ allow_unavailable_stop: false,+ };+ if let Some(journal) = Journal::read(&layout)? {+ journal.recover(&layout, &mut host)?;+ }+ Ok(())+}+fn cleanup_locked(layout: &StandaloneLayout) -> io::Result<PackageCleanup> {+ let mut retained = vec![];+ if let Some(marker) = read_json::<StandaloneInstallRecordV1>(&layout.marker_path, MAX_RECORD)? {+ marker.validate().map_err(|_| invalid())?;+ retained.push(marker.install_root);+ }+ if let Some(journal) = Journal::read(layout)? {+ retained.push(journal.new_marker.install_root);+ retained.extend(journal.old_marker.map(|marker| marker.install_root));+ }+ prune_packages(+ &layout.home.join(".local/lib/hiroute"),+ hiroute_platform::windows::install::native_target()?,+ &retained,+ )+}+/// Called by the shell only after its own rollback sources are no longer needed.+pub fn cleanup_packages() -> io::Result<PackageCleanup> {+ let layout = layout()?;+ let _lock = lock(&layout)?;+ cleanup_locked(&layout)+}+fn current(+ layout: &StandaloneLayout,+) -> io::Result<Option<(StandaloneInstallRecordV1, Value, Package)>> {+ let marker: Option<StandaloneInstallRecordV1> = read_json(&layout.marker_path, MAX_RECORD)?;+ let value: Option<Value> = read_json(&definition_path(layout), MAX_RECORD)?;+ let package: Option<Package> =+ read_json(&layout.data_root.join("package-manifest.json"), 1024 * 1024)?;+ match (marker, value, package) {+ (None, None, None) => Ok(None),+ (Some(marker), Some(value), Some(package)) => {+ let native = definition(&value)?;+ package.validate()?;+ marker.validate().map_err(|_| invalid())?;+ if native.daemon != marker.install_root.join("hirouted.exe")+ || marker.service_definition != definition_path(layout)+ || marker.target != hiroute_platform::windows::install::native_target()?+ || package.target != marker.target+ || package.version != marker.version+ || !within(+ &marker.install_root,+ &layout.home.join(".local/lib/hiroute"),+ )+ {+ return Err(invalid());+ }+ Ok(Some((marker, value, package)))+ }+ _ => Err(invalid()),+ }+}+fn entries(+ root: &Path,+ layout: &StandaloneLayout,+ package: &Package,+) -> Vec<(PathBuf, PathBuf, EntryKind, String)> {+ let mut entries = vec![];+ for name in ["hiroute.exe", "hirouted.exe"] {+ entries.push((+ layout.home.join(".local/bin").join(name),+ root.join(name),+ EntryKind::Hardlink,+ format!("bin/{name}"),+ ));+ }+ for prefix in [".agents", ".claude"] {+ let name = "skills/hiroute-management/SKILL.md";+ entries.push((+ layout.home.join(prefix).join(name),+ root.join(name),+ EntryKind::Copy,+ name.into(),+ ));+ }+ for name in package+ .files+ .keys()+ .filter(|n| n.starts_with("licenses/") || n.starts_with("docs/"))+ {+ entries.push((+ layout.data_root.join(name),+ root.join(name),+ EntryKind::Copy,+ name.clone(),+ ));+ }+ entries.push((+ layout.data_root.join("package-manifest.json"),+ root.join("package-manifest.json"),+ EntryKind::Copy,+ "__package_manifest__".into(),+ ));+ entries+}+fn publish_package(source: &Path, root: &Path, package: &Package) -> io::Result<()> {+ if root.try_exists()? {+ return package.verify_directory(root);+ }+ directory(root.parent().ok_or_else(invalid)?)?;+ let stage = sibling(root)?;+ directory(&stage)?;+ for name in package.files.keys() {+ let relative = Package::relative(name);+ let target = stage.join(relative);+ directory(target.parent().ok_or_else(invalid)?)?;+ copy_new(&source.join(relative), &target)?;+ }+ hiroute_platform::durable::write_private_new(+ &stage.join("package-manifest.json"),+ &package.canonical()?,+ )?;+ package.verify_directory(&stage)?;+ hiroute_platform::durable::rename(&stage, root)+}+pub fn install(request: InstallRequest) -> io::Result<Value> {+ if request.schema != "hiroute.windows-install-request/v1" {+ return Err(invalid());+ }+ let package = Package::read(&request.package_directory)?;+ if package.target != hiroute_platform::windows::install::native_target()? {+ return Err(io::Error::other("INSTALL_ARCHITECTURE_UNSUPPORTED"));+ }+ let timeout = deadline(request.timeout_ms)?;+ let layout = layout()?;+ let _lock = lock(&layout)?;+ let mut host = NativeHost {+ layout: &layout,+ timeout,+ allow_legacy_stop: request.allow_legacy_stop,+ allow_unavailable_stop: false,+ };+ if let Some(journal) = Journal::read(&layout)? {+ journal.recover(&layout, &mut host)?;+ }+ let old = current(&layout)?;+ let root = layout+ .home+ .join(".local/lib/hiroute")+ .join(package.directory_name());+ publish_package(&request.package_directory, &root, &package)?;+ let native = Definition::new(Manager::Task, root.join("hirouted.exe"))?;+ let marker = StandaloneInstallRecordV1 {+ schema_version: crate::STANDALONE_INSTALL_SCHEMA_V1.into(),+ version: package.version.clone(),+ target: package.target.clone(),+ install_root: root,+ service_definition: definition_path(&layout),+ installed_skills: [".agents", ".claude"]+ .iter()+ .map(|p| layout.home.join(p).join("skills/hiroute-management"))+ .collect(),+ cpa_binary: Some(+ native+ .daemon+ .parent()+ .ok_or_else(invalid)?+ .join("libexec/cliproxyapi.exe"),+ ),+ cpa_sha256: Some(package.cpa_digest().into()),+ };+ let planned = journal::plan(+ entries(&marker.install_root, &layout, &package),+ &layout,+ old.as_ref().map(|o| &o.2),+ false,+ )?;+ let mut journal = Journal {+ schema: JOURNAL_SCHEMA.into(),+ operation: Operation::Install,+ phase: Phase::Prepared,+ old_marker: old.as_ref().map(|o| o.0.clone()),+ old_definition: old.as_ref().map(|o| o.1.clone()),+ new_marker: marker,+ new_definition: serde_json::to_value(&native).map_err(|_| invalid())?,+ files: planned,+ };+ let was_active = journal+ .old_definition+ .as_ref()+ .map(definition)+ .transpose()?+ .as_ref()+ .map(task::active)+ .transpose()?+ .unwrap_or(false);+ // Drain precedes preparation: an old daemon refusal cannot leave its admission blocked.+ if let Some(old) = &journal.old_definition {+ host.quiesce(&[old])?;+ }+ if let Err(error) = journal.persist(&layout) {+ if was_active && let Some(old) = &journal.old_definition {+ let _ = task::start(&definition(old)?);+ }+ return Err(error);+ }+ let result = (|| {+ journal.apply_files()?;+ write_json(&layout.marker_path, &journal.new_marker)?;+ host.register(&journal.new_definition, journal.old_definition.as_ref())?;+ write_json(+ &journal.new_marker.service_definition,+ &journal.new_definition,+ )?;+ task::set_autostart(&native, request.autostart)?;+ journal.commit(&layout)?;+ journal.finish(&layout)+ })();+ if let Err(error) = result {+ if journal.recover(&layout, &mut host).is_ok()+ && was_active+ && let Some(old) = &old+ {+ let _ = task::start(&definition(&old.1)?);+ }+ return Err(error);+ }+ if request.console_loopback {+ ConsoleListenerStore::new(layout.gateway_config_root())+ .configure(ConsoleListenerDesiredV1::loopback())+ .map_err(|_| invalid())?;+ }+ let cleanup = if request.defer_package_cleanup {+ None+ } else {+ Some(PackageCleanup::best_effort(cleanup_locked(&layout)))+ };+ Ok(+ json!({"schema":"hiroute.windows-install-result/v1","installed":true,"version":package.version,"manager":"task","cli":layout.home.join(".local/bin/hiroute.exe"),"started":false,"package_cleanup":cleanup}),+ )+}+pub fn uninstall(+ request: UninstallRequest,+ restore_agents: impl FnOnce(&StandaloneLayout) -> io::Result<()>,+) -> io::Result<Value> {+ if request.schema != "hiroute.windows-uninstall-request/v1" {+ return Err(invalid());+ }+ if request.allow_unavailable_agent_restore && request.remove_data {+ return Err(io::Error::other("AGENT_RESTORE_DATA_REQUIRED"));+ }+ let timeout = deadline(request.timeout_ms)?;+ let layout = layout()?;+ let lock = lock(&layout)?;+ let mut host = NativeHost {+ layout: &layout,+ timeout,+ allow_legacy_stop: request.allow_legacy_stop,+ allow_unavailable_stop: false,+ };+ if let Some(journal) = Journal::read(&layout)? {+ journal.recover(&layout, &mut host)?;+ }+ let Some((marker, value, package)) = current(&layout)? else {+ let cleanup = PackageCleanup::best_effort(cleanup_locked(&layout));+ return Ok(+ json!({"schema":"hiroute.windows-uninstall-result/v1","uninstalled":true,"already_absent":true,"package_cleanup":cleanup}),+ );+ };+ let native = definition(&value)?;+ if let Some(installed_cli) = regular(&marker.install_root.join("hiroute.exe"))? {+ let running_cli = security::open_identity(&std::env::current_exe()?, false)?;+ if security::file_identity(&installed_cli)? == security::file_identity(&running_cli)? {+ return Err(io::Error::other("INSTALL_PACKAGE_IN_USE"));+ }+ }+ let restoration = super::uninstall::restore(+ &layout,+ request.allow_unavailable_agent_restore,+ request.remove_data,+ || {+ if !task::active(&native)? {+ task::start(&native).map_err(|_| io::Error::other("AGENT_CONTROL_UNAVAILABLE"))?;+ }+ Ok(())+ },+ || restore_agents(&layout),+ )?;+ host.allow_unavailable_stop = restoration != super::uninstall::Restoration::Restored;+ let planned = journal::plan(+ entries(&marker.install_root, &layout, &package),+ &layout,+ Some(&package),+ true,+ )?;+ host.quiesce(&[&value])?;+ let mut journal = Journal {+ schema: JOURNAL_SCHEMA.into(),+ operation: Operation::Uninstall,+ phase: Phase::Prepared,+ old_marker: Some(marker.clone()),+ new_marker: marker,+ old_definition: Some(value.clone()),+ new_definition: value,+ files: planned,+ };+ if let Err(error) = journal.persist(&layout) {+ // No uninstall record became durable: restore the service stopped for preparation.+ let _ = task::start(&native);+ return Err(error);+ }+ host.unregister(&journal.new_definition)?;+ journal.apply_files()?;+ journal.commit(&layout)?;+ journal.finish(&layout)?;+ hiroute_platform::windows::shell_login::remove()?;+ let cleanup = PackageCleanup::best_effort(cleanup_locked(&layout));+ drop(host);+ drop(lock);+ if request.remove_data {+ remove_tree(&layout.data_root)?;+ remove_tree(&layout.state_root)?;+ }+ Ok(+ json!({"schema":"hiroute.windows-uninstall-result/v1","uninstalled":true,"data_removed":request.remove_data,"state_preserved":!request.remove_data,"agent_restoration_unverified":restoration == super::uninstall::Restoration::Unverified,"package_cleanup":cleanup}),+ )+}+fn remove_tree(root: &Path) -> io::Result<()> {+ fn admit(path: &Path) -> io::Result<()> {+ let _held = security::open_identity(path, true)?;+ for entry in fs::read_dir(path)? {+ let path = entry?.path();+ let metadata = fs::symlink_metadata(&path)?;+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes() & 0x400 != 0 {+ return Err(invalid());+ }+ if metadata.is_dir() {+ admit(&path)?;+ } else {+ let _held = regular(&path)?.ok_or_else(invalid)?;+ }+ }+ Ok(())+ }+ if root.try_exists()? {+ admit(root)?;+ fs::remove_dir_all(root)?;+ }+ Ok(())+}diff --git a/crates/host-runtime/tests/fixtures/website-releases-v2-reader.md b/crates/host-runtime/tests/fixtures/website-releases-v2-reader.mdnew file mode 100644index 00000000..3c96ea91--- /dev/null+++ b/crates/host-runtime/tests/fixtures/website-releases-v2-reader.md@@ -0,0 +1,3 @@+# Released website catalog reader++`website_releases_v2_031.rs` preserves the production reader before its unit-test module from `crates/host-runtime/src/releases.rs` at supported release v0.3.1, commit `13856abd873da5b4373d39322493b4cc105c4867`. The extracted source SHA-256 is `10122ae6e3844b447e85b5333250dbd21c0dd82b2c0e1d98e4816dcacbd6cd1e`. The compatibility test feeds the current V2 projection into that frozen reader and checks macOS DMG selection.diff --git a/crates/host-runtime/tests/fixtures/website_releases_v2_031.rs b/crates/host-runtime/tests/fixtures/website_releases_v2_031.rsnew file mode 100644index 00000000..64dba252--- /dev/null+++ b/crates/host-runtime/tests/fixtures/website_releases_v2_031.rs@@ -0,0 +1,278 @@+//! Read the website's one current release catalog; URLs are native-derived, never IPC input.+use semver::Version;+use serde::{Deserialize, Serialize};++pub const RELEASE_FEED: &str = "https://hiroute.ai/releases.json";+pub const MAX_RELEASE_FEED_BYTES: usize = 1024 * 1024;++#[derive(Clone, Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WebsiteReleasesV2 {+ schema: String,+ releases: Vec<WebsiteReleaseV2>,+}+#[derive(Clone, Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct WebsiteReleaseV2 {+ version: String,+ channel: String,+ published_at: String,+ notes: ReleaseNotes,+ artifacts: Vec<ReleaseArtifactV2>,+}+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ReleaseNotes {+ pub zh: String,+ pub en: String,+}+#[derive(Clone, Debug, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]+enum ReleaseArtifactV2 {+ Desktop {+ platform: String,+ architecture: String,+ format: String,+ minimum_os: String,+ distribution: String,+ filename: String,+ sha256: String,+ size: u64,+ },+ Standalone {+ platform: String,+ architecture: String,+ target: String,+ format: String,+ distribution: String,+ filename: String,+ sha256: String,+ size: u64,+ manifest_filename: String,+ manifest_sha256: String,+ manifest_size: u64,+ },+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct DesktopRelease {+ pub version: String,+ pub notes: ReleaseNotes,+ pub architecture: String,+ pub distribution: String,+ pub filename: String,+ pub sha256: String,+ pub size: u64,+}+impl DesktopRelease {+ pub fn download_url(&self) -> String {+ format!(+ "https://hiroute.ai/releases/{}/{}",+ self.version, self.filename+ )+ }+ pub fn revision_prefix(&self) -> Result<&str, &'static str> {+ let prefix = format!("HiRoute-{}-", self.version);+ let suffix = match self.distribution.as_str() {+ "self-signed" => "trial",+ "developer-id" => "developer-id",+ _ => return Err("UPGRADE_ARTIFACT_INVALID"),+ };+ let tail = format!("-macos-{}-{suffix}.dmg", self.architecture);+ let revision = self+ .filename+ .strip_prefix(&prefix)+ .and_then(|s| s.strip_suffix(&tail))+ .ok_or("UPGRADE_ARTIFACT_INVALID")?;+ if semver::Version::parse(&self.version).is_err()+ || !matches!(self.architecture.as_str(), "arm64" | "x86_64")+ || !sized_digest(&self.filename, &self.sha256, self.size)+ || revision.len() != 12+ || !revision+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ {+ return Err("UPGRADE_ARTIFACT_INVALID");+ }+ Ok(revision)+ }+}+fn digest(value: &str) -> bool {+ value.len() == 64+ && value+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}+fn filename(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 240+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))+}+fn sized_digest(name: &str, sha: &str, size: u64) -> bool {+ filename(name) && digest(sha) && size > 0 && size <= 2 * 1024 * 1024 * 1024+}+impl WebsiteReleasesV2 {+ pub fn parse(bytes: &[u8]) -> Result<Self, &'static str> {+ if bytes.is_empty() || bytes.len() > MAX_RELEASE_FEED_BYTES {+ return Err("UPGRADE_CATALOG_INVALID");+ }+ let result: Self = serde_json::from_slice(bytes).map_err(|_| "UPGRADE_CATALOG_INVALID")?;+ result.validate()?;+ Ok(result)+ }+ fn validate(&self) -> Result<(), &'static str> {+ let invalid = || "UPGRADE_CATALOG_INVALID";+ if self.schema != "hiroute.website.releases/v2" || self.releases.len() > 64 {+ return Err(invalid());+ }+ let mut versions = std::collections::BTreeSet::new();+ for release in &self.releases {+ let version = Version::parse(&release.version).map_err(|_| invalid())?;+ if !versions.insert(&release.version)+ || release.version.len() > 64+ || !matches!(release.channel.as_str(), "stable" | "preview")+ || (release.channel == "stable" && !version.pre.is_empty())+ || release.published_at.is_empty()+ || release.published_at.len() > 64+ || [&release.notes.zh, &release.notes.en]+ .iter()+ .any(|n| n.trim().is_empty() || n.len() > 64 * 1024)+ || release.artifacts.is_empty()+ || release.artifacts.len() > 16+ {+ return Err(invalid());+ }+ let mut names = std::collections::BTreeSet::new();+ for artifact in &release.artifacts {+ match artifact {+ ReleaseArtifactV2::Desktop {+ platform,+ architecture,+ format,+ minimum_os,+ distribution,+ filename,+ sha256,+ size,+ } => {+ let suffix = match distribution.as_str() {+ "self-signed" => "trial",+ "developer-id" => "developer-id",+ _ => return Err(invalid()),+ };+ let prefix = format!("HiRoute-{}-", release.version);+ let tail = format!("-macos-{architecture}-{suffix}.dmg");+ let revision = filename+ .strip_prefix(&prefix)+ .and_then(|s| s.strip_suffix(&tail))+ .ok_or_else(invalid)?;+ if platform != "macOS"+ || !matches!(architecture.as_str(), "arm64" | "x86_64")+ || format != "dmg"+ || minimum_os != "15.0"+ || !sized_digest(filename, sha256, *size)+ || revision.len() != 12+ || !revision+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ || !names.insert(filename.as_str())+ {+ return Err(invalid());+ }+ }+ ReleaseArtifactV2::Standalone {+ platform,+ architecture,+ target,+ format,+ distribution,+ filename,+ sha256,+ size,+ manifest_filename,+ manifest_sha256,+ manifest_size,+ } => {+ let expected_target = match architecture.as_str() {+ "x86_64" => "x86_64-unknown-linux-gnu",+ "aarch64" => "aarch64-unknown-linux-gnu",+ _ => return Err(invalid()),+ };+ let prefix = format!("hiroute-{}-", release.version);+ let tail = format!("-{target}.tar.gz");+ let revision = filename+ .strip_prefix(&prefix)+ .and_then(|s| s.strip_suffix(&tail))+ .ok_or_else(invalid)?;+ if platform != "Linux"+ || target != expected_target+ || format != "tar.gz"+ || distribution != "unsigned"+ || !sized_digest(filename, sha256, *size)+ || !sized_digest(manifest_filename, manifest_sha256, *manifest_size)+ || manifest_filename != &format!("{filename}.json")+ || revision.len() != 12+ || !revision+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ || !names.insert(filename.as_str())+ || !names.insert(manifest_filename.as_str())+ {+ return Err(invalid());+ }+ }+ }+ }+ }+ Ok(())+ }+ pub fn desktop_update(+ &self,+ current: &str,+ architecture: &str,+ ) -> Result<Option<DesktopRelease>, &'static str> {+ let current = Version::parse(current).map_err(|_| "UPGRADE_VERSION_INVALID")?;+ let mut selected: Option<(Version, DesktopRelease)> = None;+ for release in self.releases.iter().filter(|r| r.channel == "stable") {+ let version =+ Version::parse(&release.version).map_err(|_| "UPGRADE_CATALOG_INVALID")?;+ if version <= current || selected.as_ref().is_some_and(|(v, _)| v >= &version) {+ continue;+ }+ let matches = release+ .artifacts+ .iter()+ .filter_map(|a| match a {+ ReleaseArtifactV2::Desktop {+ architecture: arch,+ distribution,+ filename,+ sha256,+ size,+ ..+ } if arch == architecture => Some(DesktopRelease {+ version: release.version.clone(),+ notes: release.notes.clone(),+ architecture: arch.clone(),+ distribution: distribution.clone(),+ filename: filename.clone(),+ sha256: sha256.clone(),+ size: *size,+ }),+ _ => None,+ })+ .collect::<Vec<_>>();+ if matches.len() > 1 {+ return Err("UPGRADE_ARTIFACT_AMBIGUOUS");+ }+ if let Some(artifact) = matches.into_iter().next() {+ selected = Some((version, artifact));+ }+ }+ Ok(selected.map(|(_, release)| release))+ }+}+diff --git a/crates/host-runtime/tests/release_catalog_compatibility.rs b/crates/host-runtime/tests/release_catalog_compatibility.rsnew file mode 100644index 00000000..2d960abc--- /dev/null+++ b/crates/host-runtime/tests/release_catalog_compatibility.rs@@ -0,0 +1,21 @@+#[path = "fixtures/website_releases_v2_031.rs"]+#[allow(dead_code)]+#[rustfmt::skip]+mod released;+use hiroute_host_runtime::WebsiteReleasesV3;+#[test]+fn supported_macos_reader_accepts_the_current_v2_projection_and_selects_its_dmg() {+ let current =+ WebsiteReleasesV3::parse(include_bytes!("../../../apps/website/data/releases.json"))+ .unwrap();+ let bytes = current.v2_projection().unwrap();+ let old = released::WebsiteReleasesV2::parse(&bytes).unwrap();+ for architecture in ["arm64", "x86_64"] {+ let update = old.desktop_update("0.0.0", architecture).unwrap().unwrap();+ assert!(+ update+ .filename+ .ends_with(&format!("-macos-{architecture}-trial.dmg"))+ );+ }+}diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.tomlindex da82ebd9..54902fd7 100644--- a/crates/platform/Cargo.toml+++ b/crates/platform/Cargo.toml@@ -17,6 +17,7 @@ zeroize.workspace = truenix.workspace = true[target.'cfg(windows)'.dependencies]+url = "=2.5.8"windows-sys = { version = "0.61.2", features = ["Wdk_Foundation","Wdk_Storage_FileSystem",@@ -25,6 +26,9 @@ windows-sys = { version = "0.61.2", features = ["Win32_Security_Authorization","Win32_Storage_FileSystem","Win32_System_Threading",+ "Win32_System_Registry",+ "Win32_UI_Shell",+ "Win32_UI_WindowsAndMessaging","Win32_System_SystemInformation","Win32_System_JobObjects","Win32_System_Console",diff --git a/crates/platform/README.md b/crates/platform/README.mdindex f12271a9..7f1028e8 100644--- a/crates/platform/README.md+++ b/crates/platform/README.md@@ -6,6 +6,13 @@ not select an Agent, authorize a business command, or own business state.adapters, fixed Known Folder resolution, and their closed installation definitions.The CLI and host runtime select lifecycle policy and maintain installation journals.+`windows::install` supplies native x64 admission and the per-account NSIS/recovery+guard. `shell_login` owns only the fixed current-user Run value for an admitted+Programs-directory shell. `user_path` merges/removes only the fixed CLI entry and+broadcasts the environment change. `shell_open` admits bounded HTTP(S) URLs before+the native browser association. These leaves do not mint console credentials,+select releases or authorize product operations.+`private_fs` is the cross-platform entry for new private directories/files, storagedirectory preparation, regular/private handle reads, single-link checks and ownedtemporary directory removal. Unix and Windows implementations stay in separate@@ -84,7 +91,9 @@ attach a console or change this foreground policy.Background lifecycle messages authenticate a held process image, creation time,and pipe peer identity. Task mode uses the same interactive account at LUA level;-SCM mode authenticates a qualified owner account and uses a restricted business+SCM primitives are retained without a supported installation entry or user+installation guide in this release; the Rust transaction refuses SCM ownership+before writes. The retained SCM code authenticates a qualified owner account and uses a restricted businesstoken beneath an administrator protected service host. `scm_owner` reads theowner's private prepared journal only while impersonating that authenticatedaccount, then reverts before machine registration. Sealed publication copies adiff --git a/crates/platform/src/windows/install.rs b/crates/platform/src/windows/install.rsnew file mode 100644index 00000000..3d9ee19c--- /dev/null+++ b/crates/platform/src/windows/install.rs@@ -0,0 +1,63 @@+//! Installation admission uses the native architecture, including under emulation.+use sha2::{Digest, Sha256};+use std::io;+use std::{fs::File, os::windows::io::FromRawHandle};+use windows_sys::Win32::System::Threading::{GetCurrentProcess, IsWow64Process2};++pub fn native_target() -> io::Result<&'static str> {+ let mut process = 0_u16;+ let mut native = 0_u16;+ // SAFETY: current process and two correctly sized IMAGE_FILE_MACHINE outputs.+ if unsafe { IsWow64Process2(GetCurrentProcess(), &mut process, &mut native) } == 0 {+ return Err(io::Error::last_os_error());+ }+ match native {+ 0x8664 => Ok("x86_64-pc-windows-msvc"),+ 0xaa64 => Ok("aarch64-pc-windows-msvc"),+ _ => Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "INSTALL_ARCHITECTURE_UNSUPPORTED",+ )),+ }+}+pub fn require_x64() -> io::Result<()> {+ if native_target()? != "x86_64-pc-windows-msvc" || !cfg!(target_arch = "x86_64") {+ return Err(io::Error::other("INSTALL_ARCHITECTURE_UNSUPPORTED"));+ }+ Ok(())+}+pub fn desktop_mutex_name() -> io::Result<String> {+ Ok(format!(+ "Global\\HiRouteDesktopInstall-{:x}",+ Sha256::digest(super::security::current_user_sid()?)+ ))+}+pub struct DesktopInstallGuard {+ _handle: File,+}+/// NSIS holds the same named object for its complete process lifetime, across helpers.+pub fn desktop_install_guard() -> io::Result<DesktopInstallGuard> {+ use windows_sys::Win32::{+ Foundation::{ERROR_ALREADY_EXISTS, GetLastError},+ System::Threading::CreateMutexW,+ };+ let name: Vec<u16> = desktop_mutex_name()?+ .encode_utf16()+ .chain(Some(0))+ .collect();+ // SAFETY: fixed per-account namespace, no borrowed pointers or initial mutex ownership.+ let handle = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) };+ if handle.is_null() {+ return Err(io::Error::last_os_error());+ }+ let exists = unsafe { GetLastError() } == ERROR_ALREADY_EXISTS;+ // SAFETY: this unique kernel handle is closed by File; no file operations are exposed.+ let file = unsafe { File::from_raw_handle(handle.cast()) };+ if exists {+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ "INSTALL_MAINTENANCE_BUSY",+ ));+ }+ Ok(DesktopInstallGuard { _handle: file })+}diff --git a/crates/platform/src/windows/lifecycle.rs b/crates/platform/src/windows/lifecycle.rsindex d1b639d2..f2f92e83 100644--- a/crates/platform/src/windows/lifecycle.rs+++ b/crates/platform/src/windows/lifecycle.rs@@ -34,6 +34,129 @@ pub struct Response {pub accepted: bool,}+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UpgradeResponse {+ pub schema: String,+ pub action: String,+ pub pid: u32,+ pub accepted: bool,+ pub paused: bool,+ pub active_calls: u64,+ pub active_tasks: u64,+}+impl UpgradeResponse {+ pub fn drained(&self) -> bool {+ self.paused && self.active_calls == 0 && self.active_tasks == 0+ }+}++pub fn upgrade(+ endpoint: &Path,+ image: &Path,+ action: &str,+ timeout: Duration,+) -> io::Result<UpgradeResponse> {+ if !matches!(+ action,+ "upgrade-prepare" | "upgrade-status" | "upgrade-cancel"+ ) {+ return Err(io::ErrorKind::InvalidInput.into());+ }+ let mut stream = pipe::Stream::connect_timeout(endpoint, timeout)?;+ stream.set_deadline(Some(Instant::now() + timeout))?;+ let process = DaemonProcess::from_pipe(&stream, image, false)?;+ let request = serde_json::to_vec(&Request {+ schema: SCHEMA.into(),+ action: action.into(),+ })+ .map_err(io::Error::other)?;+ local_record::write(+ &mut stream,+ Channel::Lifecycle,+ Direction::Request,+ &request,+ MAXIMUM,+ )?;+ let bytes = local_record::read(+ &mut stream,+ Channel::Lifecycle,+ Direction::Response,+ MAXIMUM,+ )+ .map_err(|error| {+ if matches!(+ error.kind(),+ io::ErrorKind::UnexpectedEof+ | io::ErrorKind::BrokenPipe+ | io::ErrorKind::ConnectionReset+ ) {+ io::Error::new(io::ErrorKind::Unsupported, "DRAIN_UNSUPPORTED")+ } else {+ error+ }+ })?;+ let response: UpgradeResponse = serde_json::from_slice(&bytes).map_err(io::Error::other)?;+ if response.schema != SCHEMA+ || response.action != action+ || response.pid != process.pid+ || !response.accepted+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "invalid upgrade response",+ ));+ }+ local_record::acknowledge(&mut stream)?;+ Ok(response)+}++/// No forced stop on active work. Any failed drain resumes normal admission.+pub fn drain(endpoint: &Path, image: &Path, timeout: Duration) -> io::Result<()> {+ let deadline = Instant::now() + timeout;+ let cancel = || {+ let _ = upgrade(endpoint, image, "upgrade-cancel", Duration::from_secs(2));+ };+ let mut status = match upgrade(+ endpoint,+ image,+ "upgrade-prepare",+ timeout.min(Duration::from_secs(2)),+ ) {+ Ok(status) => status,+ Err(error) => {+ if error.kind() != io::ErrorKind::Unsupported {+ cancel();+ }+ return Err(error);+ }+ };+ while !status.drained() {+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ cancel();+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ "UPGRADE_ACTIVE_WORK",+ ));+ }+ std::thread::sleep(remaining.min(Duration::from_millis(50)));+ status = match upgrade(+ endpoint,+ image,+ "upgrade-status",+ remaining.min(Duration::from_secs(2)),+ ) {+ Ok(status) => status,+ Err(error) => {+ cancel();+ return Err(error);+ }+ };+ }+ Ok(())+}+pub struct DaemonProcess {file: File,pub pid: u32,diff --git a/crates/platform/src/windows/mod.rs b/crates/platform/src/windows/mod.rsindex 4f883739..fd51cc40 100644--- a/crates/platform/src/windows/mod.rs+++ b/crates/platform/src/windows/mod.rs@@ -4,6 +4,7 @@ pub mod console;pub mod diagnostic_files;pub mod durable;pub(crate) mod file_security;+pub mod install;pub mod job;pub mod launcher;pub mod lifecycle;@@ -14,4 +15,7 @@ pub mod scm_owner;pub mod sealed_host;pub mod security;pub mod service;+pub mod shell_login;+pub mod shell_open;pub mod task;+pub mod user_path;diff --git a/crates/platform/src/windows/shell_login.rs b/crates/platform/src/windows/shell_login.rsnew file mode 100644index 00000000..caa16d1e--- /dev/null+++ b/crates/platform/src/windows/shell_login.rs@@ -0,0 +1,161 @@+//! The shell's fixed current-user login entry. No script or arbitrary registry API.+use std::{+ io,+ path::{Path, PathBuf},+};+use windows_sys::Win32::{+ Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS},+ System::Registry::{+ HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegDeleteKeyValueW, RegGetValueW, RegSetKeyValueW,+ },+};+const KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";+const NAME: &str = "HiRoute";+fn wide(value: &str) -> Vec<u16> {+ value.encode_utf16().chain(Some(0)).collect()+}+fn checked_binary(path: &Path) -> io::Result<()> {+ let expected = super::background::local_app_data()?.join("Programs/HiRoute/hiroute-shell.exe");+ if !path.is_absolute()+ || path != expected+ || path+ .components()+ .any(|p| matches!(p, std::path::Component::ParentDir))+ {+ return Err(io::Error::new(+ io::ErrorKind::PermissionDenied,+ "SHELL_LOGIN_CONFLICT",+ ));+ }+ Ok(())+}+fn command_line(binary: &Path) -> String {+ // Always quote, including ordinary profiles whose path contains no spaces.+ format!("\"{}\" --background", binary.to_string_lossy())+}+fn command() -> io::Result<Option<String>> {+ let key = wide(KEY);+ let name = wide(NAME);+ let mut buffer = [0_u16; 32768];+ let mut size = (buffer.len() * 2) as u32;+ // SAFETY: fixed HKCU subkey, bounded UTF-16 output, no borrowed pointers escape.+ let status = unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ name.as_ptr(),+ RRF_RT_REG_SZ,+ std::ptr::null_mut(),+ buffer.as_mut_ptr().cast(),+ &mut size,+ )+ };+ if status == ERROR_FILE_NOT_FOUND {+ return Ok(None);+ }+ if status != ERROR_SUCCESS || size < 2 || size as usize > buffer.len() * 2 || size % 2 != 0 {+ return Err(io::Error::other("SHELL_LOGIN_UNAVAILABLE"));+ }+ let count = size as usize / 2;+ if buffer[count - 1] != 0 {+ return Err(io::Error::other("SHELL_LOGIN_CONFLICT"));+ }+ String::from_utf16(&buffer[..count - 1])+ .map(Some)+ .map_err(io::Error::other)+}+pub fn configured_binary() -> io::Result<Option<PathBuf>> {+ let Some(command) = command()? else {+ return Ok(None);+ };+ let value = command+ .strip_prefix('"')+ .and_then(|s| s.strip_suffix("\" --background"))+ .ok_or_else(|| io::Error::other("SHELL_LOGIN_CONFLICT"))?;+ let path = PathBuf::from(value);+ checked_binary(&path)?;+ Ok(Some(path))+}+pub fn enabled(binary: &Path) -> io::Result<bool> {+ checked_binary(binary)?;+ match configured_binary()? {+ Some(path) if path != binary => Err(io::Error::other("SHELL_LOGIN_CONFLICT")),+ value => Ok(value.is_some()),+ }+}+pub fn set(binary: &Path, enabled: bool) -> io::Result<()> {+ checked_binary(binary)?;+ if let Some(existing) = configured_binary()?+ && existing != binary+ {+ return Err(io::Error::other("SHELL_LOGIN_CONFLICT"));+ }+ if !enabled {+ return remove();+ }+ let _held = super::security::open_identity(binary, false)?;+ let value = wide(&command_line(binary));+ let key = wide(KEY);+ let name = wide(NAME);+ // SAFETY: fixed HKCU Run value and live, NUL-terminated UTF-16 data.+ let status = unsafe {+ RegSetKeyValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ name.as_ptr(),+ REG_SZ,+ value.as_ptr().cast(),+ (value.len() * 2) as u32,+ )+ };+ if status == ERROR_SUCCESS {+ Ok(())+ } else {+ Err(io::Error::from_raw_os_error(status as i32))+ }+}+pub fn remove() -> io::Result<()> {+ match configured_binary() {+ Ok(None) => return Ok(()),+ Err(error) if error.to_string() == "SHELL_LOGIN_CONFLICT" => return Ok(()),+ Err(error) => return Err(error),+ Ok(Some(_)) => {}+ }+ let key = wide(KEY);+ let name = wide(NAME);+ // SAFETY: deletes only the admitted fixed current-user Run value.+ let status = unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, key.as_ptr(), name.as_ptr()) };+ if matches!(status, ERROR_SUCCESS | ERROR_FILE_NOT_FOUND) {+ Ok(())+ } else {+ Err(io::Error::from_raw_os_error(status as i32))+ }+}+#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn fixed_login_command_is_quoted_even_for_paths_without_spaces() {+ let binary = super::super::background::local_app_data()+ .unwrap()+ .join("Programs/HiRoute/hiroute-shell.exe");+ let command = command_line(&binary);+ let decoded = command+ .strip_prefix('"')+ .and_then(|s| s.strip_suffix("\" --background"))+ .unwrap();+ assert_eq!(Path::new(decoded), binary);+ assert!(checked_binary(&binary).is_ok());+ assert!(+ checked_binary(+ &binary+ .parent()+ .unwrap()+ .parent()+ .unwrap()+ .join("Other/hiroute-shell.exe")+ )+ .is_err()+ );+ }+}diff --git a/crates/platform/src/windows/shell_open.rs b/crates/platform/src/windows/shell_open.rsnew file mode 100644index 00000000..769e67a8--- /dev/null+++ b/crates/platform/src/windows/shell_open.rs@@ -0,0 +1,46 @@+use std::{io, ptr};+use windows_sys::Win32::UI::Shell::ShellExecuteW;+pub fn url(value: &str) -> io::Result<()> {+ let url = url::Url::parse(value).map_err(io::Error::other)?;+ if value.len() > 2048+ || value.chars().any(|c| c.is_control() || c.is_whitespace())+ || !matches!(url.scheme(), "http" | "https")+ || url.host_str().is_none()+ || !url.username().is_empty()+ || url.password().is_some()+ {+ return Err(io::ErrorKind::PermissionDenied.into());+ }+ let operation: Vec<u16> = "open\0".encode_utf16().collect();+ let url: Vec<u16> = value.encode_utf16().chain(Some(0)).collect();+ // SAFETY: fixed shell association verb, admitted URL, live UTF-16 buffers.+ let result = unsafe {+ ShellExecuteW(+ ptr::null_mut(),+ operation.as_ptr(),+ url.as_ptr(),+ ptr::null(),+ ptr::null(),+ 1,+ )+ };+ if result as isize <= 32 {+ Err(io::Error::other("BROWSER_UNAVAILABLE"))+ } else {+ Ok(())+ }+}+pub fn startup_failure() {+ use windows_sys::Win32::UI::WindowsAndMessaging::{MB_ICONERROR, MB_OK, MessageBoxW};+ let title: Vec<u16> = "HiRoute\0".encode_utf16().collect();+ let message:Vec<u16>="HiRoute could not open its Windows window (SHELL_RUNTIME_UNAVAILABLE). Repair Microsoft Edge WebView2 Runtime or reinstall HiRoute. Existing service data is preserved.\0".encode_utf16().collect();+ // SAFETY: fixed diagnostic text and a native-owned modal; no caller HTML or commands.+ unsafe {+ MessageBoxW(+ ptr::null_mut(),+ message.as_ptr(),+ title.as_ptr(),+ MB_OK | MB_ICONERROR,+ );+ }+}diff --git a/crates/platform/src/windows/user_path.rs b/crates/platform/src/windows/user_path.rsnew file mode 100644index 00000000..3bf49534--- /dev/null+++ b/crates/platform/src/windows/user_path.rs@@ -0,0 +1,114 @@+//! Only the fixed current-account standalone CLI directory enters the user PATH.+use std::{io, ptr};+use windows_sys::Win32::{+ Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS},+ System::Registry::{+ HKEY_CURRENT_USER, REG_EXPAND_SZ, REG_SZ, RRF_NOEXPAND, RRF_RT_REG_EXPAND_SZ,+ RRF_RT_REG_SZ, RegGetValueW, RegSetKeyValueW,+ },+ UI::WindowsAndMessaging::{+ HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETTINGCHANGE,+ },+};+fn wide(value: &str) -> Vec<u16> {+ value.encode_utf16().chain(Some(0)).collect()+}+pub fn configure(enabled: bool) -> io::Result<bool> {+ let entry = super::background::profile()?+ .join(".local/bin")+ .to_string_lossy()+ .replace('/', "\\");+ let key = wide("Environment");+ let name = wide("Path");+ let mut buffer = [0_u16; 32768];+ let mut size = (buffer.len() * 2) as u32;+ let mut kind = REG_EXPAND_SZ;+ // SAFETY: fixed current-user Environment value and bounded buffers.+ let status = unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ name.as_ptr(),+ RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND,+ &mut kind,+ buffer.as_mut_ptr().cast(),+ &mut size,+ )+ };+ let original = if status == ERROR_FILE_NOT_FOUND {+ String::new()+ } else {+ if status != ERROR_SUCCESS || size < 2 || size % 2 != 0 || size as usize > buffer.len() * 2+ {+ return Err(io::Error::other("USER_PATH_UNAVAILABLE"));+ }+ if buffer[size as usize / 2 - 1] != 0 {+ return Err(io::Error::other("USER_PATH_UNAVAILABLE"));+ }+ String::from_utf16(&buffer[..size as usize / 2 - 1]).map_err(io::Error::other)?+ };+ let normalized = |v: &str| {+ v.trim()+ .trim_matches('"')+ .trim_end_matches('\\')+ .to_lowercase()+ };+ let wanted = normalized(&entry);+ let present = original.split(';').any(|v| normalized(v) == wanted);+ if enabled == present {+ return Ok(false);+ }+ let value = if enabled {+ format!(+ "{}{}{}",+ original,+ if original.is_empty() || original.ends_with(';') {+ ""+ } else {+ ";"+ },+ entry+ )+ } else {+ original+ .split(';')+ .filter(|v| normalized(v) != wanted)+ .collect::<Vec<_>>()+ .join(";")+ };+ let value = wide(&value);+ if value.len() > 32767 {+ return Err(io::Error::other("USER_PATH_UNAVAILABLE"));+ }+ if !matches!(kind, REG_SZ | REG_EXPAND_SZ) {+ return Err(io::Error::other("USER_PATH_UNAVAILABLE"));+ }+ // SAFETY: replace the fixed current-user PATH, preserving all unrelated entries and type.+ let status = unsafe {+ RegSetKeyValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ name.as_ptr(),+ kind,+ value.as_ptr().cast(),+ (value.len() * 2) as u32,+ )+ };+ if status != ERROR_SUCCESS {+ return Err(io::Error::from_raw_os_error(status as i32));+ }+ let environment = wide("Environment");+ // SAFETY: advisory broadcast, bounded timeout, immutable UTF-16 environment label.+ unsafe {+ SendMessageTimeoutW(+ HWND_BROADCAST,+ WM_SETTINGCHANGE,+ 0,+ environment.as_ptr() as isize,+ SMTO_ABORTIFHUNG,+ 2000,+ ptr::null_mut(),+ );+ }+ Ok(true)+}diff --git a/crates/product-session/Cargo.toml b/crates/product-session/Cargo.tomlnew file mode 100644index 00000000..ca6e9d31--- /dev/null+++ b/crates/product-session/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "hiroute-product-session"+version = "0.1.0"+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[features]+test-support = []++[dependencies]+hiroute-client-core = { path = "../client-core" }+hiroute-diagnostics = { path = "../diagnostics" }+hiroute-application-api = { path = "../application-api" }+hiroute-domain = { path = "../domain" }+serde.workspace = true+serde_json.workspace = true+tokio.workspace = true+zeroize.workspace = true+getrandom.workspace = true++[dev-dependencies]+tempfile.workspace = truediff --git a/apps/desktop/src-tauri/src/agent_check_session.rs b/crates/product-session/src/agent_check_session.rssimilarity index 98%rename from apps/desktop/src-tauri/src/agent_check_session.rsrename to crates/product-session/src/agent_check_session.rsindex f693c8b2..df370ebb 100644--- a/apps/desktop/src-tauri/src/agent_check_session.rs+++ b/crates/product-session/src/agent_check_session.rs@@ -1,5 +1,6 @@//! Explicit native Agent checks using the existing confirmation and protected channel.use super::*;+use crate::authority::HostAuthority;#[derive(Deserialize)]#[serde(deny_unknown_fields)]@@ -32,7 +33,7 @@ pub struct AgentCheckCompletion {}impl AgentCheckCompletion {- pub(crate) fn passed(&self) -> bool {+ pub fn passed(&self) -> bool {self.accepted && self.state.as_deref() == Some("passed")}@@ -90,13 +91,13 @@ impl AgentCheckCompletion {}}-pub(crate) struct PendingAgentCheck {+pub struct PendingAgentCheck {client: hiroute_client_core::Client,request: AgentCheckRequestV1,capability: zeroize::Zeroizing<String>,}-pub(crate) enum AgentCheckDispatch {+pub enum AgentCheckDispatch {Cancelled(AgentCheckCompletion),Pending(PendingAgentCheck),}@@ -217,7 +218,7 @@ impl AgentCheckConfirmation {}impl PendingAgentCheck {- pub(crate) async fn execute(self) -> Result<AgentCheckCompletion, DesktopFailure> {+ pub async fn execute(self) -> Result<AgentCheckCompletion, DesktopFailure> {let scope = self.request.scope;let target = self.request.target.clone();let envelope: MachineEnvelopeV2<Value> = self@@ -329,8 +330,7 @@ impl Session {if !snapshot.trusted_authority || !snapshot.service.mutation_available {return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());}- #[cfg(unix)]- if !self.resident.has_authority() {+ if !self.authority.has_authority() {return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());}let digest = CanonicalDigest::of(&request).map_err(|_| "AGENT_INPUT_INVALID")?;@@ -343,7 +343,7 @@ impl Session {})}- pub(crate) fn begin_agent_check(+ pub fn begin_agent_check(&mut self,context: AgentCheckConfirmation,accepted: bool,@@ -354,12 +354,9 @@ impl Session {AgentCheckCompletion::cancelled(scope),));}- #[cfg(unix)]let capability = self- .resident+ .authority.register_agent_check(&context.digest, &context.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> = return Err("UNSUPPORTED_PLATFORM".into());Ok(AgentCheckDispatch::Pending(PendingAgentCheck {client: self.client.clone(),request: context.request,diff --git a/apps/desktop/src-tauri/src/agent_session.rs b/crates/product-session/src/agent_session.rssimilarity index 98%rename from apps/desktop/src-tauri/src/agent_session.rsrename to crates/product-session/src/agent_session.rsindex 11458059..7ec1ab34 100644--- a/apps/desktop/src-tauri/src/agent_session.rs+++ b/crates/product-session/src/agent_session.rs@@ -1,5 +1,6 @@//! Agent-specific native flow over shared Client Core and the existing confirmation/recovery.use super::*;+use crate::authority::HostAuthority;use hiroute_application_api::AgentSettingsStatusV2;#[derive(Deserialize)]@@ -516,18 +517,13 @@ impl Session {{return Err("AGENT_TOKEN_INVALID".into());}- #[cfg(unix)]{- let candidate = self.resident.register_agent_token_input(token)?;+ let candidate = self.authority.register_agent_token_input(token)?;input.spec.access_token = AgentAccessTokenIntentV1::Set {input_slot: candidate.candidate_ref.clone(),};Some(candidate)}- #[cfg(not(unix))]- {- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());- }} else {if matches!(input.spec.access_token,@@ -540,11 +536,10 @@ impl Session {let result = self.preview_agent_settings_registered(input, candidate.clone()).await;- #[cfg(unix)]if !matches!(&result, Ok(AgentPreparation::Ready(_)))&& let Some(candidate) = &candidate{- let _ = self.resident.release_model_input(candidate);+ let _ = self.authority.release_model_input(candidate);}result}@@ -690,9 +685,8 @@ impl Session {accepted: bool,) -> Result<AgentOutcome, DesktopFailure> {if !self.confirmation.finish(&context.permit, accepted)? {- #[cfg(unix)]if let Some(candidate) = &context.token_candidate {- let _ = self.resident.release_model_input(candidate);+ let _ = self.authority.release_model_input(candidate);}return Ok(AgentOutcome {preview: context.preview,@@ -712,7 +706,7 @@ impl Session {// release the login item that version created, as proven by the backend journal.let login_item = if restore && context.preview.resident_service.login_item_removal_required{- Some(crate::login_item::remove_resident_login_item()?)+ Some(self.authority.remove_resident_login_item()?)} else {None};@@ -749,7 +743,6 @@ impl Session {}).await;let mutation = self.reconcile_apply_response(response).await;- #[cfg(unix)]if self.hint.is_none()|| mutation.as_ref()@@ -772,7 +765,7 @@ impl Session {};if definitively_failed && declaration.removes_resident_service() {// The rolled-back connection still needs its owned item at the next login.- crate::login_item::compensate_resident_login_item_removal();+ self.authority.compensate_resident_login_item_removal();}}let mutation = mutation?;diff --git a/crates/product-session/src/authority.rs b/crates/product-session/src/authority.rsnew file mode 100644index 00000000..fd4ba041--- /dev/null+++ b/crates/product-session/src/authority.rs@@ -0,0 +1,298 @@+//! Host effects needed by a product session. Neither transport nor UI supplies grants.+use hiroute_application_api::*;+use std::{+ any::Any,+ collections::BTreeMap,+ sync::{Arc, Mutex},+};+use zeroize::Zeroizing;++pub enum ApplyPurpose {+ AgentPlan,+ SourcePrice,+}++pub trait HostAuthority: Send + Sync + Any {+ fn as_any(&self) -> &dyn Any;+ fn has_authority(&self) -> bool;+ fn register_operation(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ operation: &'static str,+ ) -> Result<Zeroizing<String>, String>;+ fn register_input(+ &self,+ candidate: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String>;+ fn release_model_input(&self, candidate: &ComputeCandidateRefV2) -> Result<(), String>;+ fn remove_resident_login_item(&self) -> Result<AgentLoginItemDeclarationV2, String> {+ Err("SERVICE_UNAVAILABLE".into())+ }+ fn compensate_resident_login_item_removal(&self) {}+ fn register(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "ApplyAgentPlanChange")+ }+ fn register_for(+ &self,+ purpose: ApplyPurpose,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(+ digest,+ revisions,+ match purpose {+ ApplyPurpose::AgentPlan => "ApplyAgentPlanChange",+ ApplyPurpose::SourcePrice => "ApplyPriceOverrideChange",+ },+ )+ }+ fn register_observation(+ &self,+ request: &ObservationReadRequestV2,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ let digest = CanonicalDigest::of(request).map_err(|_| "OBSERVATION_REQUEST_INVALID")?;+ self.register_operation(&digest, revisions, request.protected_operation())+ }+ fn register_classifier_diagnostic(+ &self,+ request: &ClassifierDecisionTestRequestV1,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ let digest = CanonicalDigest::of(request).map_err(|_| "CLASSIFIER_TEST_INVALID")?;+ self.register_operation(&digest, revisions, "TestClassifierDecision")+ }+ fn register_retention(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ apply: bool,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(+ digest,+ revisions,+ if apply {+ "ApplySessionDeletionV2"+ } else {+ "PreviewSessionDeletionV2"+ },+ )+ }+ fn register_agent_settings(+ &self,+ restore: bool,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(+ digest,+ revisions,+ if restore {+ "ApplyAgentConnectionRestore"+ } else {+ "ApplyAgentConnectionChange"+ },+ )+ }+ fn register_model_input(+ &self,+ secret: Zeroizing<String>,+ ) -> Result<ComputeCandidateRefV2, String> {+ self.create_input("candidate/native/", secret)+ }+ fn register_agent_token_input(+ &self,+ secret: Zeroizing<String>,+ ) -> Result<ComputeCandidateRefV2, String> {+ self.create_input("candidate/native/agent-token-", secret)+ }+ fn create_input(+ &self,+ prefix: &str,+ secret: Zeroizing<String>,+ ) -> Result<ComputeCandidateRefV2, String> {+ if secret.is_empty() || secret.len() > 32 * 1024 || !self.has_authority() {+ return Err("PROTECTED_INPUT_INVALID".into());+ }+ let candidate = ComputeCandidateRefV2 {+ candidate_ref: format!("{prefix}{}", crate::random_id()?),+ candidate_revision: 1,+ };+ self.register_input(&candidate, secret)?;+ Ok(candidate)+ }+ fn register_subscription_callback_input(+ &self,+ candidate: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String> {+ if candidate.validate_shape().is_err()+ || candidate.candidate_revision != 1+ || !candidate+ .candidate_ref+ .starts_with("candidate/subscription-login/")+ || secret.is_empty()+ || secret.len() > 32 * 1024+ || !self.has_authority()+ {+ return Err("PROTECTED_INPUT_INVALID".into());+ }+ self.register_input(candidate, secret)+ }+ fn register_agent_check(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "CheckAgentConnection")+ }++ fn register_model_check(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "CheckNativeModelConnection")+ }++ fn register_registered_model_check(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "CheckRegisteredModelConnection")+ }++ fn register_discovered_model_prepare(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "PrepareDiscoveredModelConnection")+ }++ fn register_saved_model_check(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "CheckSavedModelConnection")+ }++ fn register_model_save(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "ApplyComputeSave")+ }++ fn register_subscription_check(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "ApplySubscriptionCheck")+ }++ fn register_subscription_release(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "ReleaseSubscriptionCheck")+ }++ fn register_operation_cancel(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ ) -> Result<Zeroizing<String>, String> {+ self.register_operation(digest, revisions, "CancelOperation")+ }+}++/// Owns every protected input registered through this session, including a pending prompt.+/// Random references retain the released wire format and cannot collide across sessions.+pub struct SessionAuthority {+ host: Arc<dyn HostAuthority>,+ inputs: Mutex<BTreeMap<String, ComputeCandidateRefV2>>,+}+impl SessionAuthority {+ pub fn new(host: Arc<dyn HostAuthority>) -> Self {+ Self {+ host,+ inputs: Mutex::default(),+ }+ }+}+impl HostAuthority for SessionAuthority {+ fn as_any(&self) -> &dyn Any {+ self.host.as_any()+ }+ fn has_authority(&self) -> bool {+ self.host.has_authority()+ }+ fn register_operation(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ operation: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ self.host.register_operation(digest, revisions, operation)+ }+ fn register_input(+ &self,+ candidate: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String> {+ let mut inputs = self+ .inputs+ .lock()+ .map_err(|_| "PROTECTED_INPUT_UNAVAILABLE")?;+ self.host.register_input(candidate, secret)?;+ inputs.insert(candidate.candidate_ref.clone(), candidate.clone());+ Ok(())+ }+ fn release_model_input(&self, candidate: &ComputeCandidateRefV2) -> Result<(), String> {+ candidate+ .validate_shape()+ .map_err(|_| "PROTECTED_INPUT_INVALID")?;+ let mut inputs = self+ .inputs+ .lock()+ .map_err(|_| "PROTECTED_INPUT_UNAVAILABLE")?;+ if let Some(owned) = inputs.get(&candidate.candidate_ref) {+ // Preparation/checking advances the candidate revision without changing+ // ownership of the protected input. Release the registered input by its+ // session-owned identity, just as the host's release protocol does.+ self.host.release_model_input(owned)?;+ inputs.remove(&candidate.candidate_ref);+ }+ Ok(())+ }+ fn remove_resident_login_item(&self) -> Result<AgentLoginItemDeclarationV2, String> {+ self.host.remove_resident_login_item()+ }+ fn compensate_resident_login_item_removal(&self) {+ self.host.compensate_resident_login_item_removal()+ }+}+impl Drop for SessionAuthority {+ fn drop(&mut self) {+ let inputs = self+ .inputs+ .get_mut()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ for candidate in inputs.values() {+ let _ = self.host.release_model_input(candidate);+ }+ }+}diff --git a/crates/product-session/src/authority_tests.rs b/crates/product-session/src/authority_tests.rsnew file mode 100644index 00000000..ea8dcea4--- /dev/null+++ b/crates/product-session/src/authority_tests.rs@@ -0,0 +1,96 @@+use super::authority::*;+use hiroute_application_api::*;+use hiroute_client_core::{Client, LocalEndpoint};+use std::{+ collections::BTreeMap,+ sync::{Arc, Mutex},+};+use zeroize::Zeroizing;+#[derive(Default)]+struct Host(Mutex<BTreeMap<String, String>>);+impl HostAuthority for Host {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }+ fn has_authority(&self) -> bool {+ true+ }+ fn register_operation(+ &self,+ _: &CanonicalDigest,+ _: &RevisionSetV1,+ _: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ Ok(Zeroizing::new(crate::random_id()?))+ }+ fn register_input(+ &self,+ c: &ComputeCandidateRefV2,+ secret: Zeroizing<String>,+ ) -> Result<(), String> {+ assert!(+ self.0+ .lock()+ .unwrap()+ .insert(c.candidate_ref.clone(), secret.to_string())+ .is_none()+ );+ Ok(())+ }+ fn release_model_input(&self, c: &ComputeCandidateRefV2) -> Result<(), String> {+ self.0.lock().unwrap().remove(&c.candidate_ref);+ Ok(())+ }+}+#[test]+fn simultaneous_sessions_release_only_their_own_inputs_including_pending_prompts() {+ let host = Arc::new(Host::default());+ let client = || Client::new("test", LocalEndpoint::from_runtime_root("unused"));+ let first = crate::ProductSession::new(client(), host.clone());+ let second = crate::ProductSession::new(client(), host.clone());+ let a = first+ .authority+ .register_model_input(Zeroizing::new("first".into()))+ .unwrap();+ let b = second+ .authority+ .register_model_input(Zeroizing::new("second".into()))+ .unwrap();+ assert_ne!(a.candidate_ref, b.candidate_ref);+ // A reference from a different session cannot release the second session's input.+ first.authority.release_model_input(&b).unwrap();+ assert_eq!(host.0.lock().unwrap().len(), 2);+ drop(first);+ assert!(!host.0.lock().unwrap().contains_key(&a.candidate_ref));+ assert!(host.0.lock().unwrap().contains_key(&b.candidate_ref));+ drop(second);+ assert!(host.0.lock().unwrap().is_empty());+}++#[test]+fn checked_model_input_releases_after_revision_advances_without_releasing_another_session() {+ let host = Arc::new(Host::default());+ let client = || Client::new("test", LocalEndpoint::from_runtime_root("unused"));+ let first = crate::ProductSession::new(client(), host.clone());+ let second = crate::ProductSession::new(client(), host.clone());+ let mut checked = first+ .authority+ .register_model_input(Zeroizing::new("first".into()))+ .unwrap();+ let foreign = second+ .authority+ .register_model_input(Zeroizing::new("second".into()))+ .unwrap();+ checked.candidate_revision += 1;+ first.authority.release_model_input(&foreign).unwrap();+ assert_eq!(host.0.lock().unwrap().len(), 2);+ first.authority.release_model_input(&checked).unwrap();+ assert!(!host.0.lock().unwrap().contains_key(&checked.candidate_ref));+ assert!(host.0.lock().unwrap().contains_key(&foreign.candidate_ref));+ // Terminal operation polling and session shutdown may both request release.+ first.authority.release_model_input(&checked).unwrap();+ drop(first);+ assert!(host.0.lock().unwrap().contains_key(&foreign.candidate_ref));+ drop(second);+ assert!(host.0.lock().unwrap().is_empty());+}diff --git a/crates/product-session/src/catalog.rs b/crates/product-session/src/catalog.rsnew file mode 100644index 00000000..8070e1a8--- /dev/null+++ b/crates/product-session/src/catalog.rs@@ -0,0 +1,26 @@+//! The checked command contract shared by the native bridge and console route admission.+use serde::Deserialize;+use std::sync::OnceLock;+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CommandArgument {+ pub name: String,+ pub r#type: String,+}+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ProductCommand {+ pub name: String,+ pub args: Vec<CommandArgument>,+ pub result: String,+ pub host_only: bool,+}+pub fn commands() -> &'static [ProductCommand] {+ static COMMANDS: OnceLock<Vec<ProductCommand>> = OnceLock::new();+ COMMANDS.get_or_init(|| {+ serde_json::from_str(include_str!("commands.json")).expect("checked command catalog")+ })+}+pub fn product_command(name: &str) -> Option<&'static ProductCommand> {+ commands().iter().find(|c| c.name == name && !c.host_only)+}diff --git a/crates/product-session/src/commands.json b/crates/product-session/src/commands.jsonnew file mode 100644index 00000000..fc527cc6--- /dev/null+++ b/crates/product-session/src/commands.json@@ -0,0 +1,791 @@+[+ {+ "name": "observation_read",+ "args": [+ {+ "name": "request",+ "type": "hiroute_application_api::ObservationReadRequestV2"+ }+ ],+ "result": "Result<serde_json::Value, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "observation_delete",+ "args": [+ {+ "name": "input",+ "type": "ObservationDeleteInput"+ }+ ],+ "result": "Result<serde_json::Value, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "test_classifier_decision",+ "args": [+ {+ "name": "input",+ "type": "ClassifierDecisionTestInput"+ }+ ],+ "result": "Result<ClassifierDecisionTestResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "decision_services",+ "args": [],+ "result": "Result<crate::session::DecisionServiceList, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "save_decision_service",+ "args": [+ {+ "name": "input",+ "type": "DecisionServiceSaveInput"+ }+ ],+ "result": "Result<ApplyResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "save_classifier_header_secret",+ "args": [+ {+ "name": "input",+ "type": "ClassifierHeaderSecretSaveInput"+ }+ ],+ "result": "Result<ApplyResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "save_classifier_openapi",+ "args": [],+ "result": "Result<ClassifierOpenApiSaveOutcome, DesktopFailure>",+ "host_only": true+ },+ {+ "name": "desktop_snapshot",+ "args": [],+ "result": "Result<DesktopSnapshot, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_rename",+ "args": [+ {+ "name": "input",+ "type": "RenameInput"+ }+ ],+ "result": "Result<MutationOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_plan_editor",+ "args": [+ {+ "name": "input",+ "type": "EditorInput"+ }+ ],+ "result": "Result<MutationOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "refresh_route_references",+ "args": [+ {+ "name": "language",+ "type": "String"+ }+ ],+ "result": "Result<MutationOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "plan_editor_options",+ "args": [+ {+ "name": "input",+ "type": "hiroute_application_api::PlanEditorOptionsRequestV1"+ }+ ],+ "result": "Result<hiroute_application_api::PlanEditorOptionsV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_restore_name",+ "args": [+ {+ "name": "input",+ "type": "RestoreInput"+ }+ ],+ "result": "Result<MutationOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_price_change",+ "args": [+ {+ "name": "input",+ "type": "PriceEditInput"+ }+ ],+ "result": "Result<MutationOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "model_reference_query",+ "args": [+ {+ "name": "input",+ "type": "ModelCatalogQueryV1"+ }+ ],+ "result": "Result<ModelCatalogResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "effective_price_query",+ "args": [+ {+ "name": "input",+ "type": "GetEffectivePricesV2"+ }+ ],+ "result": "Result<PriceDisplayResult, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "compute_management_snapshot",+ "args": [],+ "result": "Result<ComputeManagementSnapshotV3, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "compute_key_masks",+ "args": [+ {+ "name": "query",+ "type": "ComputeKeyMasksQueryV1"+ }+ ],+ "result": "Result<ComputeKeyMasksViewV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "compute_scan",+ "args": [+ {+ "name": "native_target",+ "type": "Option<hiroute_domain::AgentNativeTargetV1>"+ }+ ],+ "result": "Result<WebComputeScanResultV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "prepare_discovered_model_connection",+ "args": [+ {+ "name": "discovery",+ "type": "WebComputeDiscoveryRefV1"+ }+ ],+ "result": "Result<WebComputeCandidateViewV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "compute_connection_options",+ "args": [],+ "result": "Result<ComputeConnectionOptionsResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "register_protected_model_input",+ "args": [+ {+ "name": "secret",+ "type": "String"+ },+ {+ "name": "source_id",+ "type": "Option<String>"+ }+ ],+ "result": "Result<ProtectedModelInputRegistration, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "release_protected_model_input",+ "args": [+ {+ "name": "input",+ "type": "ComputeCandidateRefV2"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_model_connection",+ "args": [+ {+ "name": "request",+ "type": "NativeModelConnectionCheckRequestV1"+ }+ ],+ "result": "Result<ModelConnectionCheckViewV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_registered_model_connection",+ "args": [+ {+ "name": "request",+ "type": "RegisteredModelConnectionCheckRequestV1"+ }+ ],+ "result": "Result<ModelConnectionCheckViewV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_saved_model_connection",+ "args": [+ {+ "name": "request",+ "type": "SavedModelConnectionCheckRequestV1"+ }+ ],+ "result": "Result<ModelConnectionCheckViewV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "cancel_model_connection_check",+ "args": [+ {+ "name": "check_id",+ "type": "String"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_compute_save",+ "args": [+ {+ "name": "change",+ "type": "WebComputeManagementChangeV2"+ }+ ],+ "result": "Result<WebComputeSavePreviewV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "apply_compute_save",+ "args": [+ {+ "name": "request",+ "type": "WebComputeConnectionApplyRequestV1"+ },+ {+ "name": "language",+ "type": "String"+ }+ ],+ "result": "Result<ModelSaveAccepted, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "get_compute_save_result",+ "args": [+ {+ "name": "operation",+ "type": "OperationReferenceV1"+ }+ ],+ "result": "Result<WebComputeSaveResultV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "compute_subscriptions",+ "args": [],+ "result": "Result<WebComputeSubscriptionCandidatesV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "manage_subscription_login",+ "args": [+ {+ "name": "request",+ "type": "ComputeSubscriptionLoginRequestV1"+ }+ ],+ "result": "Result<ComputeSubscriptionLoginResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "submit_subscription_login_callback",+ "args": [+ {+ "name": "login_ref",+ "type": "String"+ },+ {+ "name": "callback",+ "type": "String"+ }+ ],+ "result": "Result<ComputeSubscriptionLoginResultV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_subscription",+ "args": [+ {+ "name": "candidate",+ "type": "ComputeCandidateRefV2"+ },+ {+ "name": "language",+ "type": "String"+ }+ ],+ "result": "Result<WebComputeSubscriptionCheckResultV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "get_subscription_check_result",+ "args": [+ {+ "name": "operation",+ "type": "OperationReferenceV1"+ }+ ],+ "result": "Result<WebComputeSubscriptionCheckResultV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "recover_subscription_check",+ "args": [],+ "result": "Result<Option<WebComputeSubscriptionCheckResultV2>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "close_subscription_check",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "release_subscription_check",+ "args": [+ {+ "name": "validation",+ "type": "WebValidationRefV2"+ }+ ],+ "result": "Result<WebComputeSubscriptionCheckResultV2, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "web_confirmation_snapshot",+ "args": [],+ "result": "Result<Option<WebConfirmationRequest>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "resolve_web_confirmation",+ "args": [+ {+ "name": "input",+ "type": "WebConfirmationDecision"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "agent_snapshot",+ "args": [+ {+ "name": "native_targets",+ "type": "Option<Vec<hiroute_domain::AgentNativeTargetV1>>"+ }+ ],+ "result": "Result<AgentSnapshot, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "preview_agent_settings",+ "args": [+ {+ "name": "input",+ "type": "AgentSettingsInput"+ }+ ],+ "result": "Result<AgentOutcome, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "retry_agent_settings",+ "args": [+ {+ "name": "input",+ "type": "hiroute_application_api::AgentSettingsRetryV1"+ }+ ],+ "result": "Result<Value, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_agent_authentication",+ "args": [+ {+ "name": "input",+ "type": "AgentCheckInput"+ }+ ],+ "result": "Result<bool, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "check_agent_live",+ "args": [+ {+ "name": "input",+ "type": "AgentCheckInput"+ }+ ],+ "result": "Result<AgentCheckCompletion, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_settings_get",+ "args": [],+ "result": "Result<WorkerSettingsV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_settings_set",+ "args": [+ {+ "name": "input",+ "type": "WorkerSettingsV1"+ }+ ],+ "result": "Result<WorkerSettingsV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_plans",+ "args": [+ {+ "name": "input",+ "type": "WorkerPlansRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<WorkPlanListV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_executor_availability",+ "args": [],+ "result": "Result<WorkerExecutorAvailabilityListV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_dependencies_discover",+ "args": [+ {+ "name": "input",+ "type": "WorkerDependenciesDiscoverRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_dependencies_select_prepare",+ "args": [+ {+ "name": "input",+ "type": "WorkerDependenciesSelectRequestV1"+ }+ ],+ "result": "Result<WorkerDependencyConfirmationV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_dependencies_select_confirm",+ "args": [+ {+ "name": "confirmations",+ "type": "State<'_, WorkerDependencyConfirmationState>"+ },+ {+ "name": "input",+ "type": "WorkerDependencyConfirmationInput"+ }+ ],+ "result": "Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_dependencies_select_cancel",+ "args": [+ {+ "name": "input",+ "type": "WorkerDependencyConfirmationInput"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_list",+ "args": [+ {+ "name": "input",+ "type": "WorkerListRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationListV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_status",+ "args": [+ {+ "name": "input",+ "type": "WorkerStatusRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationGetV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_result",+ "args": [+ {+ "name": "input",+ "type": "WorkerResultRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationResultV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_read",+ "args": [+ {+ "name": "input",+ "type": "WorkerReadRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<WorkerReadDataV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_wait",+ "args": [+ {+ "name": "input",+ "type": "WorkerWaitRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationWaitV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_cancel",+ "args": [+ {+ "name": "input",+ "type": "WorkerCancelRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationCancelV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_confirm_residual",+ "args": [+ {+ "name": "input",+ "type": "WorkerResidualConfirmRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationRunViewV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "worker_task_continue",+ "args": [+ {+ "name": "input",+ "type": "WorkerContinueRequestV1"+ }+ ],+ "result": "Result<MachineEnvelopeV2<DelegationAcceptedV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "cli_entry_status",+ "args": [],+ "result": "Result<CliEntryView, DesktopFailure>",+ "host_only": true+ },+ {+ "name": "cli_entry_install",+ "args": [],+ "result": "Result<CliEntryView, DesktopFailure>",+ "host_only": true+ },+ {+ "name": "cli_entry_remove",+ "args": [],+ "result": "Result<CliEntryView, DesktopFailure>",+ "host_only": true+ },+ {+ "name": "gateway_listener_status",+ "args": [],+ "result": "Result<GatewayListenerView, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "subscription_proxy_status",+ "args": [],+ "result": "Result<SubscriptionProxyView, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "subscription_proxy_apply",+ "args": [+ {+ "name": "policy",+ "type": "SubscriptionProxyPolicy"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "gateway_listener_apply",+ "args": [+ {+ "name": "input",+ "type": "GatewayListenerInput"+ }+ ],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "gateway_listener_recover",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": false+ },+ {+ "name": "observe_operation",+ "args": [],+ "result": "Result<Option<ClientOperationViewV1>, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "stop_observing",+ "args": [],+ "result": "Result<(), String>",+ "host_only": false+ },+ {+ "name": "quit_desktop",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": true+ },+ {+ "name": "diagnostic_status",+ "args": [],+ "result": "Result<DiagnosticStatusV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "startup_status",+ "args": [],+ "result": "Result<StartupReport, String>",+ "host_only": true+ },+ {+ "name": "open_startup_recovery_directory",+ "args": [],+ "result": "Result<(), String>",+ "host_only": true+ },+ {+ "name": "update_status",+ "args": [],+ "result": "Result<UpdateView, String>",+ "host_only": true+ },+ {+ "name": "update_check",+ "args": [],+ "result": "Result<UpdateView, String>",+ "host_only": true+ },+ {+ "name": "update_download",+ "args": [],+ "result": "Result<UpdateView, String>",+ "host_only": true+ },+ {+ "name": "update_install",+ "args": [],+ "result": "Result<UpdateView, String>",+ "host_only": true+ },+ {+ "name": "update_cancel",+ "args": [],+ "result": "Result<UpdateView, String>",+ "host_only": true+ },+ {+ "name": "set_diagnostic_level",+ "args": [+ {+ "name": "input",+ "type": "SetDiagnosticLevelInput"+ }+ ],+ "result": "Result<DiagnosticStatusV1, DesktopFailure>",+ "host_only": false+ },+ {+ "name": "open_diagnostic_directory",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": true+ },+ {+ "name": "open_external_url",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": true+ },+ {+ "name": "perform_titlebar_double_click",+ "args": [],+ "result": "Result<(), DesktopFailure>",+ "host_only": true+ }+]diff --git a/crates/product-session/src/commands/action_result_tests.rs b/crates/product-session/src/commands/action_result_tests.rsnew file mode 100644index 00000000..0c3a7a16--- /dev/null+++ b/crates/product-session/src/commands/action_result_tests.rs@@ -0,0 +1,58 @@+use super::{ActionResult, MutationOutcome, mutation_outcome_result, mutation_result};+use hiroute_application_api::{CanonicalDigest, ClientOperationViewV1};++#[test]+fn action_results_and_failures_classify_without_business_text() {+ use crate::failure::DesktopFailure;+ use hiroute_client_core::{ClientFailure, FailureCode};+ use hiroute_diagnostics::error::EventErrorCode;+ assert_eq!(mutation_result("succeeded"), ActionResult::Applied);+ assert_eq!(+ mutation_result("needs_attention"),+ ActionResult::Failed {+ code: EventErrorCode::Recovery+ }+ );+ assert_eq!(+ mutation_result("rolled_back"),+ ActionResult::Failed {+ code: EventErrorCode::ExternalError+ }+ );+ let succeeded = MutationOutcome {+ state: "submitted".into(),+ operation: Some(ClientOperationViewV1 {+ model_budget_conflict: None,+ operation_id: "op_diagnostics".into(),+ state: "succeeded".into(),+ sequence: 1,+ cancellable: false,+ accepted_digest: CanonicalDigest::of_bytes(b"diagnostics"),+ safe_error_code: None,+ }),+ };+ assert_eq!(mutation_outcome_result(&succeeded), ActionResult::Applied);+ let unknown = MutationOutcome {+ state: "response_unknown".into(),+ operation: None,+ };+ assert_eq!(+ mutation_outcome_result(&unknown),+ ActionResult::Failed {+ code: EventErrorCode::ExternalError+ }+ );+ let native = |code: &str| DesktopFailure::Native { code: code.into() };+ assert_eq!(+ native("window_denied").event_code(),+ EventErrorCode::WindowDenied+ );+ assert_eq!(+ native("RESIDENT_UNAVAILABLE").event_code(),+ EventErrorCode::ExternalError+ );+ let transport = DesktopFailure::Transport {+ failure: ClientFailure::before_send(FailureCode::TransportUnavailable),+ };+ assert_eq!(transport.event_code(), EventErrorCode::TransportUnavailable);+}diff --git a/crates/product-session/src/commands/classifier.rs b/crates/product-session/src/commands/classifier.rsnew file mode 100644index 00000000..bcb54db8--- /dev/null+++ b/crates/product-session/src/commands/classifier.rs@@ -0,0 +1,88 @@+use super::{ClientContext, CommandState, DesktopFailure, main_window};+use hiroute_application_api::{ApplyResultV1, ClassifierDecisionTestResultV1};+use hiroute_domain::ComplexityClassifierModeV1;++#[derive(serde::Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ClassifierDecisionTestInput {+ classifier: ComplexityClassifierModeV1,+}++#[derive(serde::Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ClassifierHeaderSecretSaveInput {+ secret_id: String,+ secret: String,+}++#[derive(serde::Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DecisionServiceSaveInput {+ change: hiroute_domain::DecisionServiceChangeV1,+ secret: Option<String>,+}++pub async fn decision_services(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<crate::session::DecisionServiceList, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .decision_services()+ .await+}++pub async fn save_decision_service(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: DecisionServiceSaveInput,+) -> Result<ApplyResultV1, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .save_decision_service(input.change, input.secret.map(zeroize::Zeroizing::new))+ .await+}++/// Explicitly invokes the production classifier path with the product-owned+/// synthetic first turn. No real conversation or business model call is made.+pub async fn test_classifier_decision(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: ClassifierDecisionTestInput,+) -> Result<ClassifierDecisionTestResultV1, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .test_classifier_decision(input.classifier)+ .await+}++pub async fn save_classifier_header_secret(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: ClassifierHeaderSecretSaveInput,+) -> Result<ApplyResultV1, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .save_classifier_header_secret(input.secret_id, zeroize::Zeroizing::new(input.secret))+ .await+}diff --git a/crates/product-session/src/commands/context.rs b/crates/product-session/src/commands/context.rsnew file mode 100644index 00000000..7318e6a8--- /dev/null+++ b/crates/product-session/src/commands/context.rs@@ -0,0 +1,36 @@+use crate::{+ session::Session,+ web_confirmation::{ConfirmationBroker, WebConfirmationRequest},+};+use hiroute_diagnostics::context::DiagnosticHandle;+use std::sync::{Arc, OnceLock, atomic::AtomicU64};+use tokio::sync::Mutex;+pub type ConfirmationNotifier<'a> =+ dyn Fn(&WebConfirmationRequest) -> Result<(), String> + Send + Sync + 'a;+pub struct CommandState<'a>(+ pub &'a Arc<Mutex<Option<Session>>>,+ pub &'a OnceLock<String>,+ pub &'a AtomicU64,+ pub &'a DiagnosticHandle,+);+pub struct ClientContext<'a> {+ pub id: &'a str,+ pub confirmations: &'a ConfirmationBroker,+ pub active: &'a (dyn Fn() -> bool + Send + Sync),+ pub notify: Option<&'a ConfirmationNotifier<'a>>,+}+impl ClientContext<'_> {+ pub fn label(&self) -> &str {+ self.id+ }+ pub fn is_visible(&self) -> Result<bool, String> {+ Ok((self.active)())+ }+}+pub(super) fn main_window(window: &ClientContext<'_>) -> Result<(), String> {+ if window.id.is_empty() {+ Err("CLIENT_CONTEXT_INVALID".into())+ } else {+ Ok(())+ }+}diff --git a/crates/product-session/src/commands/dispatch.rs b/crates/product-session/src/commands/dispatch.rsnew file mode 100644index 00000000..8c0d2e20--- /dev/null+++ b/crates/product-session/src/commands/dispatch.rs@@ -0,0 +1,687 @@+use super::*;+use serde::Deserialize;+use serde_json::Value;+pub async fn dispatch(+ name: &str,+ args: Value,+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ dependencies: &WorkerDependencyConfirmationState,+) -> Result<Value, DesktopFailure> {+ match name {+ "compute_subscriptions" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = compute_subscriptions(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_subscription" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ candidate: ComputeCandidateRefV2,+ language: String,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_subscription(window, state, input.candidate, input.language).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "get_subscription_check_result" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ operation: OperationReferenceV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = get_subscription_check_result(window, state, input.operation).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "recover_subscription_check" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = recover_subscription_check(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "close_subscription_check" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ close_subscription_check(window, state).await?;+ serde_json::to_value(()).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "release_subscription_check" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ validation: WebValidationRefV2,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = release_subscription_check(window, state, input.validation).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "compute_key_masks" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ query: ComputeKeyMasksQueryV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = compute_key_masks(window, state, input.query).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "compute_management_snapshot" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = compute_management_snapshot(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "compute_scan" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ native_target: Option<hiroute_domain::AgentNativeTargetV1>,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = compute_scan(window, state, input.native_target).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "prepare_discovered_model_connection" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ discovery: WebComputeDiscoveryRefV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = prepare_discovered_model_connection(window, state, input.discovery).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "compute_connection_options" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = compute_connection_options(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "register_protected_model_input" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ secret: String,+ source_id: Option<String>,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value =+ register_protected_model_input(window, state, input.secret, input.source_id)+ .await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "release_protected_model_input" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: ComputeCandidateRefV2,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ release_protected_model_input(window, state, input.input).await?;+ serde_json::to_value(()).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_model_connection" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: NativeModelConnectionCheckRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_model_connection(window, state, input.request).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_saved_model_connection" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: SavedModelConnectionCheckRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_saved_model_connection(window, state, input.request).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_registered_model_connection" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: RegisteredModelConnectionCheckRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_registered_model_connection(window, state, input.request).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "cancel_model_connection_check" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ check_id: String,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ cancel_model_connection_check(window, state, input.check_id).await?;+ serde_json::to_value(()).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_compute_save" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ change: WebComputeManagementChangeV2,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_compute_save(window, state, input.change).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "apply_compute_save" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: WebComputeConnectionApplyRequestV1,+ language: String,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = apply_compute_save(window, state, input.request, input.language).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "get_compute_save_result" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ operation: OperationReferenceV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = get_compute_save_result(window, state, input.operation).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "manage_subscription_login" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: ComputeSubscriptionLoginRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = manage_subscription_login(window, state, input.request).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "submit_subscription_login_callback" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ login_ref: String,+ callback: String,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value =+ submit_subscription_login_callback(window, state, input.login_ref, input.callback)+ .await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "observation_delete" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: ObservationDeleteInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = observation_delete(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_settings_get" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_settings_get(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_settings_set" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerSettingsV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_settings_set(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_executor_availability" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_executor_availability(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_plans" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerPlansRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_plans(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_dependencies_discover" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerDependenciesDiscoverRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_dependencies_discover(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_dependencies_select_prepare" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerDependenciesSelectRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value =+ worker_dependencies_select_prepare(window, dependencies, state, input.input)+ .await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_dependencies_select_confirm" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerDependencyConfirmationInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value =+ worker_dependencies_select_confirm(window, state, dependencies, input.input)+ .await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_dependencies_select_cancel" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerDependencyConfirmationInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ worker_dependencies_select_cancel(window, dependencies, input.input).await?;+ serde_json::to_value(()).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_list" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerListRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_list(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_status" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerStatusRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_status(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_result" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerResultRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_result(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_read" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerReadRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_read(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_wait" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerWaitRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_wait(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_confirm_residual" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerResidualConfirmRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_confirm_residual(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_cancel" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerCancelRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_cancel(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "worker_task_continue" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: WorkerContinueRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = worker_task_continue(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "decision_services" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = decision_services(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "save_decision_service" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: DecisionServiceSaveInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = save_decision_service(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "test_classifier_decision" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: ClassifierDecisionTestInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = test_classifier_decision(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "save_classifier_header_secret" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: ClassifierHeaderSecretSaveInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = save_classifier_header_secret(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "desktop_snapshot" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = desktop_snapshot(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "refresh_route_references" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ language: String,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = refresh_route_references(window, state, input.language).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_plan_editor" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: EditorInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_plan_editor(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "plan_editor_options" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: hiroute_application_api::PlanEditorOptionsRequestV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = plan_editor_options(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_rename" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: RenameInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_rename(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_restore_name" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: RestoreInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_restore_name(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_price_change" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: PriceEditInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_price_change(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "model_reference_query" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: ModelCatalogQueryV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = model_reference_query(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "effective_price_query" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: GetEffectivePricesV2,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = effective_price_query(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "agent_snapshot" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ native_targets: Option<Vec<hiroute_domain::AgentNativeTargetV1>>,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = agent_snapshot(window, state, input.native_targets).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "retry_agent_settings" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: hiroute_application_api::AgentSettingsRetryV1,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = retry_agent_settings(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "preview_agent_settings" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: AgentSettingsInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = preview_agent_settings(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_agent_authentication" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: AgentCheckInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_agent_authentication(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "check_agent_live" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ input: AgentCheckInput,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = check_agent_live(window, state, input.input).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "observe_operation" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = observe_operation(window, state).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "stop_observing" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {}+ let _: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ stop_observing(window, state)+ .await+ .map_err(DesktopFailure::from)?;+ serde_json::to_value(()).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "observation_read" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields, rename_all = "camelCase")]+ struct Arguments {+ request: hiroute_application_api::ObservationReadRequestV2,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ let value = observation_read(window, state, input.request).await?;+ serde_json::to_value(value).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "web_confirmation_snapshot" => {+ let _: ClientEmptyRequestV1 = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ serde_json::to_value(window.confirmations.snapshot(window.id))+ .map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+ "resolve_web_confirmation" => {+ #[derive(Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Arguments {+ input: crate::web_confirmation::WebConfirmationDecision,+ }+ let input: Arguments = serde_json::from_value(args)+ .map_err(|_| DesktopFailure::from("REQUEST_INVALID"))?;+ window.confirmations.resolve(+ window.id,+ &input.input.confirmation_id,+ input.input.accepted,+ )?;+ Ok(Value::Null)+ }+ _ => Err("COMMAND_UNKNOWN".into()),+ }+}diff --git a/crates/product-session/src/commands/mod.rs b/crates/product-session/src/commands/mod.rsnew file mode 100644index 00000000..1d1c4a0f--- /dev/null+++ b/crates/product-session/src/commands/mod.rs@@ -0,0 +1,796 @@+//! WebView supplies explicit intent and renders prompts; native preview and typed policy own submission.+use crate::failure::DesktopFailure;+pub use crate::session::{+ AgentCheckCompletion, AgentCheckConfirmation, AgentCheckDispatch, AgentCheckInput,+ AgentConfirmation, AgentOutcome, AgentPreparation, AgentSettingsInput, AgentSnapshot,+ Confirmation, DesktopSnapshot, EditorInput, ModelSaveAccepted, ModelSaveConfirmation,+ MutationOutcome, PriceConfirmation, PriceDisplayResult, PriceEditInput, RenameInput,+ RestoreInput, Session, SubscriptionCheckConfirmation,+};+pub use hiroute_application_api::*;+use hiroute_diagnostics::context::{DiagnosticContext, DiagnosticHandle};+use hiroute_diagnostics::correlation::CorrelationDomain;+use hiroute_diagnostics::error::EventErrorCode;+use hiroute_diagnostics::event::{+ ActionEnd, ActionOperation, ActionResult, ApplyEvent, ApplyPhase, ConfirmationEvent,+ ConfirmationPhase, DiagnosticEvent, PreviewEvent, PreviewPhase,+};+use hiroute_diagnostics::identity::CorrelationToken;+pub use hiroute_domain::ComplexityClassifierModeV1;+use serde_json::Value;+use std::sync::atomic::Ordering;+mod model_connection_web;+pub use model_connection_web::*;+mod model_connections;+pub use model_connections::*;+mod subscription_login;+pub use subscription_login::*;+mod observation;+pub use observation::*;+mod classifier;+pub use classifier::*;+mod worker_tasks;+pub use worker_tasks::*;+mod web_confirmation;+use web_confirmation::*;+mod context;+pub use context::*;+async fn confirmation_session<'a>(+ state: &'a CommandState<'_>,+ epoch: u64,+) -> Result<tokio::sync::MutexGuard<'a, Option<Session>>, DesktopFailure> {+ crate::confirmation::lock_current_session(state.0, state.2, epoch)+ .await+ .map_err(Into::into)+}++/// Diagnostics for one protected native action. Carries the operation family, the real+/// revision and stable results; never confirmation text, payloads, digests or grants.+struct ActionDiagnostics {+ context: DiagnosticContext,+ operation: ActionOperation,+ started: std::time::Instant,+}++impl ActionDiagnostics {+ fn begin(handle: &DiagnosticHandle, operation: ActionOperation) -> Self {+ Self {+ context: handle.context(),+ operation,+ started: std::time::Instant::now(),+ }+ }++ fn preview(&self, phase: PreviewPhase, revision: Option<u64>) {+ self.context.emit(DiagnosticEvent::Preview(PreviewEvent {+ operation: self.operation,+ phase,+ revision,+ }));+ }++ fn confirmation(&self, phase: ConfirmationPhase, accepted: Option<bool>) {+ self.context+ .emit(DiagnosticEvent::Confirmation(ConfirmationEvent {+ operation: self.operation,+ phase,+ accepted,+ }));+ }++ fn apply(&self, phase: ApplyPhase, revision: Option<u64>, result: Option<ActionResult>) {+ self.context.emit(DiagnosticEvent::Apply(ApplyEvent {+ operation: self.operation,+ phase,+ revision,+ result,+ }));+ }++ /// The exact operation this action created, when the product reported one.+ fn token(&self, operation_id: Option<&str>) -> Option<CorrelationToken> {+ operation_id.and_then(|id| self.context.token(CorrelationDomain::Operation, id))+ }++ fn end(&self, result: ActionResult, operation_token: Option<CorrelationToken>) {+ self.context.emit(DiagnosticEvent::ActionEnd(ActionEnd {+ operation: self.operation,+ result,+ operation_token,+ elapsed_ms: self.started.elapsed().as_millis() as u64,+ }));+ }+}++impl NativeOutcome {+ /// The stable result of this action; a denial is not a failure and vice versa. A+ /// non-terminal product state is reported as a failure instead of "applied".+ fn action_result(&self, accepted: bool) -> ActionResult {+ if !accepted {+ return ActionResult::Denied;+ }+ match self {+ Self::Rename(mutation) => mutation_outcome_result(mutation),+ Self::Agent(agent) => match &agent.mutation {+ Some(mutation) => mutation_outcome_result(mutation),+ None => ActionResult::Failed {+ code: EventErrorCode::ExternalError,+ },+ },+ Self::Check(completion) => {+ if completion.passed() {+ ActionResult::Applied+ } else {+ ActionResult::Failed {+ code: EventErrorCode::ExternalError,+ }+ }+ }+ Self::ModelSave(accepted) => mutation_result(&accepted.result.state),+ Self::SubscriptionCheck(result) => match result.status {+ hiroute_application_api::ComputeSubscriptionCheckStatusV2::Verified => {+ ActionResult::Applied+ }+ hiroute_application_api::ComputeSubscriptionCheckStatusV2::SourceChanged => {+ ActionResult::Failed {+ code: EventErrorCode::Conflict,+ }+ }+ hiroute_application_api::ComputeSubscriptionCheckStatusV2::NeedsAuth => {+ ActionResult::Failed {+ code: EventErrorCode::Authorization,+ }+ }+ hiroute_application_api::ComputeSubscriptionCheckStatusV2::Unavailable => {+ ActionResult::Failed {+ code: EventErrorCode::Unavailable,+ }+ }+ _ => ActionResult::Failed {+ code: EventErrorCode::ExternalError,+ },+ },+ }+ }++ /// The exact product operation this action produced, when it reported one.+ fn operation_id(&self) -> Option<&str> {+ match self {+ Self::Rename(mutation) => mutation+ .operation+ .as_ref()+ .map(|operation| operation.operation_id.as_str()),+ Self::Agent(agent) => agent+ .mutation+ .as_ref()+ .and_then(|mutation| mutation.operation.as_ref())+ .map(|operation| operation.operation_id.as_str()),+ Self::ModelSave(accepted) => Some(accepted.operation.operation_id.as_str()),+ Self::SubscriptionCheck(result) => {+ Some(result.approval_operation.operation_id.as_str())+ }+ Self::Check(_) => None,+ }+ }+}++fn mutation_outcome_result(mutation: &MutationOutcome) -> ActionResult {+ mutation.operation.as_ref().map_or_else(+ || mutation_result(&mutation.state),+ |operation| mutation_result(&operation.state),+ )+}++fn mutation_result(state: &str) -> ActionResult {+ match state {+ "succeeded" => ActionResult::Applied,+ "needs_attention" => ActionResult::Failed {+ code: EventErrorCode::Recovery,+ },+ _ => ActionResult::Failed {+ code: EventErrorCode::ExternalError,+ },+ }+}+pub async fn desktop_snapshot(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<DesktopSnapshot, DesktopFailure> {+ main_window(window)?;+ let mut guard = state.0.lock().await;+ let session = guard.as_mut().ok_or_else(|| {+ state+ .1+ .get()+ .cloned()+ .unwrap_or("RESIDENT_UNAVAILABLE".into())+ })?;+ session.resume_observing();+ session.snapshot().await+}+pub async fn refresh_route_references(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ language: String,+) -> Result<MutationOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::PlanEditor);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview_reference_refresh(language)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ confirm(+ window,+ state,+ ActionOperation::PlanEditor,+ NativeConfirmation::Rename(Box::new(context)),+ epoch,+ )+ .await?+ .mutation()+}+pub async fn preview_plan_editor(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: EditorInput,+) -> Result<MutationOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::PlanEditor);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview_editor(input)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ confirm(+ window,+ state,+ ActionOperation::PlanEditor,+ NativeConfirmation::Rename(Box::new(context)),+ epoch,+ )+ .await?+ .mutation()+}+pub async fn plan_editor_options(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: hiroute_application_api::PlanEditorOptionsRequestV1,+) -> Result<hiroute_application_api::PlanEditorOptionsV1, DesktopFailure> {+ main_window(window)?;+ let guard = state.0.lock().await;+ let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;+ crate::session::query(&session.client, "GetPlanEditorOptions", &input).await+}+pub async fn preview_rename(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: RenameInput,+) -> Result<MutationOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::Rename);+ action.preview(PreviewPhase::Begin, None);+ let context = {+ let mut guard = confirmation_session(state, epoch).await?;+ guard+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview(input)+ .await?+ };+ action.preview(PreviewPhase::End, Some(context.revision()));+ confirm(+ window,+ state,+ ActionOperation::Rename,+ NativeConfirmation::Rename(Box::new(context)),+ epoch,+ )+ .await?+ .mutation()+}+pub async fn preview_restore_name(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: RestoreInput,+) -> Result<MutationOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::RestoreName);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview_restore(input)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ confirm(+ window,+ state,+ ActionOperation::RestoreName,+ NativeConfirmation::Rename(Box::new(context)),+ epoch,+ )+ .await?+ .mutation()+}+enum NativeConfirmation {+ Rename(Box<Confirmation>),+ Price(Box<PriceConfirmation>),+ Agent(Box<AgentConfirmation>),+ Check(Box<AgentCheckConfirmation>),+ ModelSave(Box<ModelSaveConfirmation>),+ SubscriptionCheck(Box<SubscriptionCheckConfirmation>),+}+enum NativeOutcome {+ Rename(MutationOutcome),+ Agent(Box<AgentOutcome>),+ Check(AgentCheckCompletion),+ ModelSave(ModelSaveAccepted),+ SubscriptionCheck(Box<hiroute_application_api::ComputeSubscriptionCheckResultV2>),+}+impl NativeOutcome {+ fn mutation(self) -> Result<MutationOutcome, DesktopFailure> {+ match self {+ Self::Rename(value) => Ok(value),+ _ => Err("CONFIRMATION_KIND_MISMATCH".into()),+ }+ }+}+impl NativeConfirmation {+ /// The exact revision this action was previewed against, from the real confirmation+ /// context rather than from any WebView-provided value.+ fn revision(&self) -> u64 {+ match self {+ Self::Rename(context) => context.revision(),+ Self::Price(context) => context.revision(),+ Self::Agent(context) => context.revision(),+ Self::Check(context) => context.revision(),+ Self::ModelSave(context) => context.revision(),+ Self::SubscriptionCheck(context) => context.revision(),+ }+ }++ fn requires_confirmation(&self) -> bool {+ match self {+ Self::Rename(c) => c.requires_confirmation(),+ Self::Price(_) => false,+ Self::Check(c) => c.requires_confirmation(),+ Self::Agent(c) => c.requires_confirmation(),+ Self::ModelSave(c) => c.requires_confirmation(),+ Self::SubscriptionCheck(c) => c.requires_confirmation(),+ }+ }+ fn english(&self) -> bool {+ match self {+ Self::Rename(c) => c.english(),+ Self::Price(c) => c.english(),+ Self::Agent(c) => c.english(),+ Self::Check(c) => c.english(),+ Self::ModelSave(c) => c.english(),+ Self::SubscriptionCheck(c) => c.english(),+ }+ }+ fn message(&self) -> String {+ match self {+ Self::Rename(c) => c.message(),+ Self::Price(c) => c.message(),+ Self::Agent(c) => c.message(),+ Self::Check(c) => c.message(),+ Self::ModelSave(c) => c.message(),+ Self::SubscriptionCheck(c) => c.message(),+ }+ }+}+pub async fn preview_price_change(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: PriceEditInput,+) -> Result<MutationOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::PriceChange);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview_price(input)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ confirm(+ window,+ state,+ ActionOperation::PriceChange,+ NativeConfirmation::Price(Box::new(context)),+ epoch,+ )+ .await?+ .mutation()+}+pub async fn model_reference_query(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: ModelCatalogQueryV1,+) -> Result<ModelCatalogResultV1, DesktopFailure> {+ main_window(window)?;+ let guard = state.0.lock().await;+ let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;+ crate::session::query(&session.client, "ShowModel", &input).await+}+pub async fn effective_price_query(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: GetEffectivePricesV2,+) -> Result<PriceDisplayResult, DesktopFailure> {+ main_window(window)?;+ let guard = state.0.lock().await;+ let session = guard.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;+ Ok(PriceDisplayResult::new(+ crate::session::query(&session.client, "GetEffectivePrices", &input).await?,+ ))+}++pub async fn agent_snapshot(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ native_targets: Option<Vec<hiroute_domain::AgentNativeTargetV1>>,+) -> Result<AgentSnapshot, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .agent_snapshot_for_targets(native_targets.unwrap_or_default())+ .await+}+pub async fn retry_agent_settings(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: hiroute_application_api::AgentSettingsRetryV1,+) -> Result<Value, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .retry_agent_settings(input)+ .await+}+pub async fn preview_agent_settings(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: AgentSettingsInput,+) -> Result<AgentOutcome, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::AgentSettings);+ action.preview(PreviewPhase::Begin, None);+ let prepared = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .preview_agent_settings(input)+ .await?;+ match prepared {+ AgentPreparation::Blocked(preview) => {+ action.preview(PreviewPhase::End, None);+ action.end(+ ActionResult::Failed {+ code: EventErrorCode::ActionRequired,+ },+ None,+ );+ Ok(AgentOutcome {+ preview: *preview,+ mutation: None,+ })+ }+ AgentPreparation::Ready(context) => {+ action.preview(PreviewPhase::End, Some(context.revision()));+ match confirm(+ window,+ state,+ ActionOperation::AgentSettings,+ NativeConfirmation::Agent(context),+ epoch,+ )+ .await?+ {+ NativeOutcome::Agent(value) => Ok(*value),+ _ => unreachable!(),+ }+ }+ }+}+pub async fn check_agent_authentication(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: AgentCheckInput,+) -> Result<bool, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::AgentCheck);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .prepare_agent_check(input)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ match confirm(+ window,+ state,+ ActionOperation::AgentCheck,+ NativeConfirmation::Check(Box::new(context)),+ epoch,+ )+ .await?+ {+ NativeOutcome::Check(result) => Ok(result.passed()),+ _ => unreachable!(),+ }+}++pub async fn check_agent_live(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: AgentCheckInput,+) -> Result<AgentCheckCompletion, DesktopFailure> {+ main_window(window)?;+ if input.scope.as_deref() != Some("live") {+ return Err("AGENT_INPUT_INVALID".into());+ }+ let epoch = state.2.load(Ordering::SeqCst);+ let action = ActionDiagnostics::begin(state.3, ActionOperation::AgentCheck);+ action.preview(PreviewPhase::Begin, None);+ let context = confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .prepare_agent_check(input)+ .await?;+ action.preview(PreviewPhase::End, Some(context.revision()));+ match confirm(+ window,+ state,+ ActionOperation::AgentCheck,+ NativeConfirmation::Check(Box::new(context)),+ epoch,+ )+ .await?+ {+ NativeOutcome::Check(result) => Ok(result),+ _ => unreachable!(),+ }+}++async fn confirm(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ operation: ActionOperation,+ context: NativeConfirmation,+ epoch: u64,+) -> Result<NativeOutcome, DesktopFailure> {+ let action = ActionDiagnostics::begin(state.3, operation);+ if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {+ let mut guard = state.0.lock().await;+ // Recovery may have installed another Session while this callback waited.+ if state.2.load(Ordering::SeqCst) == epoch {+ guard+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .invalidate_confirmation();+ }+ action.confirmation(ConfirmationPhase::Expired, None);+ action.end(ActionResult::Stale, None);+ return Err("CONFIRMATION_STALE".into());+ }+ let revision = context.revision();+ let accepted = if context.requires_confirmation() {+ action.confirmation(ConfirmationPhase::Shown, None);+ let english = context.english();+ let checking = matches!(&context, NativeConfirmation::Check(_));+ let live_checking = matches!(&context, NativeConfirmation::Check(c) if c.is_live());+ let title = if live_checking {+ if english {+ "HiRoute · Verify model access"+ } else {+ "HiRoute · 验证模型接入"+ }+ } else if checking {+ if english {+ "HiRoute · Check compatibility"+ } else {+ "HiRoute · 检查兼容性"+ }+ } else if english {+ "HiRoute · Confirm change"+ } else {+ "HiRoute · 确认更改"+ };+ let confirm_label = if live_checking {+ if english {+ "Run live check"+ } else {+ "开始真实验证"+ }+ } else if checking {+ if english {+ "Start check"+ } else {+ "开始检查"+ }+ } else if let NativeConfirmation::Rename(plan) = &context {+ plan.action_label()+ } else if english {+ "Apply change"+ } else {+ "应用更改"+ };+ let accepted = request_web_confirmation(+ window,+ WebConfirmationPrompt {+ title: title.into(),+ message: context.message(),+ confirm_label: confirm_label.into(),+ cancel_label: if english { "Cancel" } else { "取消" }.into(),+ },+ )+ .await;+ action.confirmation(ConfirmationPhase::Result, Some(accepted));+ accepted+ } else {+ // This context was freshly validated for an explicit action that needs no extra prompt.+ true+ };+ if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {+ let mut guard = state.0.lock().await;+ if state.2.load(Ordering::SeqCst) == epoch {+ guard+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .invalidate_confirmation();+ }+ action.confirmation(ConfirmationPhase::Expired, None);+ action.end(ActionResult::Stale, None);+ return Err("CONFIRMATION_STALE".into());+ }+ action.apply(ApplyPhase::Begin, Some(revision), None);+ let outcome = if let NativeConfirmation::SubscriptionCheck(context) = context {+ let pending = {+ let mut guard = confirmation_session(state, epoch).await?;+ guard+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .begin_subscription_check_confirmation(*context, accepted)+ .await?+ };+ // Operation A performs connector I/O. Keep native close/recovery commands responsive while+ // it runs so close can submit cancellation rather than waiting behind this command.+ let completion = pending.execute().await;+ // Completion belongs to the Session that submitted it, not the window's prompt epoch.+ // Window close must still release an A resource created after the close-time sweep.+ crate::session::complete_subscription_check(state.0, completion)+ .await+ .map(Box::new)+ .map(NativeOutcome::SubscriptionCheck)+ } else if let NativeConfirmation::Check(context) = context {+ let dispatch = {+ let mut guard = confirmation_session(state, epoch).await?;+ guard+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .begin_agent_check(*context, accepted)?+ };+ match dispatch {+ AgentCheckDispatch::Cancelled(result) => Ok(NativeOutcome::Check(result)),+ AgentCheckDispatch::Pending(pending) => {+ pending.execute().await.map(NativeOutcome::Check)+ }+ }+ } else {+ let mut guard = confirmation_session(state, epoch).await?;+ let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;+ match context {+ NativeConfirmation::Agent(context) => session+ .finish_agent_confirmation(*context, accepted)+ .await+ .map(|value| NativeOutcome::Agent(Box::new(value))),+ NativeConfirmation::Check(_) => unreachable!(),+ NativeConfirmation::Rename(context) => session+ .finish_native_confirmation(*context, accepted)+ .await+ .map(NativeOutcome::Rename),+ NativeConfirmation::Price(context) => session+ .finish_price_confirmation(*context, accepted)+ .await+ .map(NativeOutcome::Rename),+ NativeConfirmation::ModelSave(context) => session+ .finish_model_save_confirmation(*context, accepted)+ .await+ .map(NativeOutcome::ModelSave),+ NativeConfirmation::SubscriptionCheck(_) => unreachable!(),+ }+ };+ match &outcome {+ Ok(value) => {+ let result = value.action_result(accepted);+ let token = action.token(value.operation_id());+ action.apply(ApplyPhase::End, Some(revision), Some(result));+ action.end(result, token);+ }+ Err(failure) => {+ let result = ActionResult::Failed {+ code: failure.event_code(),+ };+ action.apply(ApplyPhase::End, Some(revision), Some(result));+ action.end(result, None);+ }+ }+ outcome+}+pub async fn observe_operation(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<Option<ClientOperationViewV1>, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .observe()+ .await+}+pub async fn stop_observing(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<(), String> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .stop_observing();+ Ok(())+}+pub async fn observation_read(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: hiroute_application_api::ObservationReadRequestV2,+) -> Result<serde_json::Value, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .observation_read(request)+ .await+}++mod dispatch;+pub use dispatch::dispatch;++#[cfg(test)]+mod action_result_tests;diff --git a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs b/crates/product-session/src/commands/model_connection_web.rssimilarity index 97%rename from apps/desktop/src-tauri/src/bridge/model_connection_web.rsrename to crates/product-session/src/commands/model_connection_web.rsindex 719f77b8..3840ccf9 100644--- a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs+++ b/crates/product-session/src/commands/model_connection_web.rs@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};/// JavaScript cannot round a server-issued `u64` before returning it to the native bridge.#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeDiscoveryRefV1 {+pub struct WebComputeDiscoveryRefV1 {discovery_ref: String,discovery_revision: String,}@@ -67,7 +67,7 @@ pub(super) struct WebComputeConnectionPointV2 {actions_required: Vec<String>,}#[derive(Serialize)]-pub(super) struct WebComputeScanResultV2 {+pub struct WebComputeScanResultV2 {connections: Vec<WebComputeConnectionPointV2>,diagnostics: Vec<ComputeScanDiagnosticV2>,}@@ -103,7 +103,7 @@ impl From<ComputeScanResultV2> for WebComputeScanResultV2 {/// locators, filesystem paths, endpoint details, and catalog digests deliberately remain in Rust.#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeScanItemV1 {+pub struct WebComputeScanItemV1 {agent_id: String,supported: bool,#[serde(skip_serializing_if = "Option::is_none")]@@ -122,7 +122,7 @@ pub(super) struct WebComputeScanItemV1 {#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeScanResultV1 {+pub struct WebComputeScanResultV1 {items: Vec<WebComputeScanItemV1>,}@@ -150,7 +150,7 @@ impl From<ComputeScanResultV1> for WebComputeScanResultV1 {#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebValidationRefV2 {+pub struct WebValidationRefV2 {approval_operation: OperationReferenceV1,validation_ref: String,validation_revision: String,@@ -187,7 +187,7 @@ impl TryFrom<WebValidationRefV2> for ComputeValidationRefV2 {#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeCandidateViewV2 {+pub struct WebComputeCandidateViewV2 {candidate: ComputeCandidateRefV2,correlation: ComputeCheckCorrelationV2,producer: ComputeCandidateProducerV2,@@ -224,7 +224,7 @@ impl From<ComputeCandidateViewV2> for WebComputeCandidateViewV2 {#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeSubscriptionCandidatesV2 {+pub struct WebComputeSubscriptionCandidatesV2 {candidates: Vec<WebComputeCandidateViewV2>,discovery_state: ComputeSubscriptionDiscoveryStateV2,#[serde(skip_serializing_if = "Option::is_none")]@@ -243,7 +243,7 @@ impl From<ComputeSubscriptionCandidatesV2> for WebComputeSubscriptionCandidatesV#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeSubscriptionCheckResultV2 {+pub struct WebComputeSubscriptionCheckResultV2 {candidate: ComputeCandidateRefV2,approval_operation: OperationReferenceV1,status: ComputeSubscriptionCheckStatusV2,@@ -273,7 +273,7 @@ impl From<ComputeSubscriptionCheckResultV2> for WebComputeSubscriptionCheckResul#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeManagementChangeV2 {+pub struct WebComputeManagementChangeV2 {schema: String,subject: ComputeManagementSubjectV2,expected_revisions: RevisionSetV1,@@ -321,7 +321,7 @@ impl TryFrom<WebComputeManagementChangeV2> for ComputeManagementChangeV2 {#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeSavePreviewV2 {+pub struct WebComputeSavePreviewV2 {#[serde(skip_serializing_if = "Option::is_none")]candidate: Option<ComputeCandidateRefV2>,#[serde(skip_serializing_if = "Option::is_none")]@@ -357,7 +357,7 @@ impl TryFrom<ComputeSavePreviewV2> for WebComputeSavePreviewV2 {#[derive(Deserialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeConnectionApplyRequestV1 {+pub struct WebComputeConnectionApplyRequestV1 {spec: ChangeSpecV1,accept_digest: CanonicalDigest,expected_revisions: RevisionSetV1,@@ -384,7 +384,7 @@ impl TryFrom<WebComputeConnectionApplyRequestV1> for ComputeConnectionApplyReque#[derive(Serialize)]#[serde(deny_unknown_fields)]-pub(super) struct WebComputeSaveResultV2 {+pub struct WebComputeSaveResultV2 {#[serde(skip_serializing_if = "Option::is_none")]candidate: Option<ComputeCandidateRefV2>,#[serde(skip_serializing_if = "Option::is_none")]diff --git a/crates/product-session/src/commands/model_connections.rs b/crates/product-session/src/commands/model_connections.rsnew file mode 100644index 00000000..052174a1--- /dev/null+++ b/crates/product-session/src/commands/model_connections.rs@@ -0,0 +1,590 @@+use super::{ClientContext, CommandState, NativeConfirmation, NativeOutcome, confirm, main_window};+use crate::HostAuthority;+use crate::failure::DesktopFailure;+use crate::session::ModelSaveAccepted;+use hiroute_application_api::*;+use hiroute_diagnostics::event::ActionOperation;+use serde::Serialize;+use std::sync::atomic::Ordering;++use super::model_connection_web::{+ WebComputeCandidateViewV2, WebComputeConnectionApplyRequestV1, WebComputeDiscoveryRefV1,+ WebComputeManagementChangeV2, WebComputeSavePreviewV2, WebComputeSaveResultV2,+ WebComputeScanResultV2, WebComputeSubscriptionCandidatesV2,+ WebComputeSubscriptionCheckResultV2, WebValidationRefV2,+};++#[derive(Serialize)]+pub struct ProtectedModelInputRegistration {+ input_candidate: ComputeCandidateRefV2,+ #[serde(skip_serializing_if = "Option::is_none")]+ key_id: Option<String>,+}++fn erase_envelope<T: Serialize>(+ envelope: MachineEnvelopeV2<T>,+) -> Result<MachineEnvelopeV2<serde_json::Value>, DesktopFailure> {+ Ok(MachineEnvelopeV2 {+ schema_version: envelope.schema_version,+ request_id: envelope.request_id,+ status: envelope.status,+ data: envelope+ .data+ .map(serde_json::to_value)+ .transpose()+ .map_err(|_| "RESPONSE_DATA_INVALID")?,+ operation: envelope.operation,+ warnings: envelope.warnings,+ next_actions: envelope.next_actions,+ error: envelope.error,+ })+}++fn envelope_data<T: Serialize>(envelope: MachineEnvelopeV2<T>) -> Result<T, DesktopFailure> {+ if envelope.error.is_some() {+ return Err(DesktopFailure::backend(erase_envelope(envelope)?));+ }+ envelope.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())+}++pub async fn compute_subscriptions(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<WebComputeSubscriptionCandidatesV2, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(client.compute_subscriptions(&crate::random_id()?).await?).map(Into::into)+}++pub async fn check_subscription(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ candidate: ComputeCandidateRefV2,+ language: String,+) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let (client, close_requested) = {+ let mut guard = super::confirmation_session(state, epoch).await?;+ let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;+ let close_requested = session.resume_subscription_interaction();+ (session.client.clone(), close_requested)+ };+ let preview = envelope_data(+ client+ .preview_subscription_check(&crate::random_id()?, candidate)+ .await?,+ )?;+ let context = super::confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .prepare_subscription_check_confirmation(+ preview,+ language,+ crate::random_id()?,+ close_requested,+ )?;+ match confirm(+ window,+ state,+ ActionOperation::SubscriptionCheck,+ NativeConfirmation::SubscriptionCheck(Box::new(context)),+ epoch,+ )+ .await?+ {+ NativeOutcome::SubscriptionCheck(result) => Ok((*result).into()),+ _ => unreachable!(),+ }+}++pub async fn get_subscription_check_result(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ operation: OperationReferenceV1,+) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(+ client+ .subscription_check_result(&crate::random_id()?, operation.operation_id)+ .await?,+ )+ .map(Into::into)+}++pub async fn recover_subscription_check(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<Option<WebComputeSubscriptionCheckResultV2>, DesktopFailure> {+ main_window(window)?;+ let result = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .recover_subscription_check()+ .await?;+ Ok(result.map(Into::into))+}++pub async fn close_subscription_check(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<(), DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .close_subscription_check()+ .await+}++pub async fn release_subscription_check(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ validation: WebValidationRefV2,+) -> Result<WebComputeSubscriptionCheckResultV2, DesktopFailure> {+ main_window(window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .release_subscription_validation(validation.try_into().map_err(DesktopFailure::from)?)+ .await+ .map(Into::into)+}++pub async fn compute_key_masks(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ query: ComputeKeyMasksQueryV1,+) -> Result<ComputeKeyMasksViewV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ crate::session::query(&client, GET_COMPUTE_KEY_MASKS_OPERATION_V1, &query).await+}++pub async fn compute_management_snapshot(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<ComputeManagementSnapshotV3, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(+ client+ .compute_management_snapshot_v3(+ &crate::random_id()?,+ ComputeManagementQueryV2::default(),+ )+ .await?,+ )+}++pub async fn compute_scan(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ native_target: Option<hiroute_domain::AgentNativeTargetV1>,+) -> Result<WebComputeScanResultV2, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(+ client+ .scan_compute_points(+ &crate::random_id()?,+ ComputeScanRequestV2 {+ schema: COMPUTE_SCAN_REQUEST_SCHEMA_V2.into(),+ native_target,+ },+ )+ .await?,+ )+ .map(Into::into)+}++pub async fn prepare_discovered_model_connection(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ discovery: WebComputeDiscoveryRefV1,+) -> Result<WebComputeCandidateViewV2, DesktopFailure> {+ main_window(window)?;+ let discovery: ComputeDiscoveryRefV1 = discovery.try_into().map_err(DesktopFailure::from)?;+ let digest_suffix = discovery+ .discovery_ref+ .strip_prefix("discovery/")+ .ok_or("REQUEST_INVALID")?;+ let request = PrepareDiscoveredModelConnectionRequestV1 {+ prepare_id: format!("desktop/{digest_suffix}"),+ discovery,+ };+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let status: ClientServiceStatusV1 =+ crate::session::query(&client, "GetClientServiceStatus", &ClientEmptyRequestV1 {}).await?;+ let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;+ let capability = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_discovered_model_prepare(&digest, &status.revisions)?;+ envelope_data(+ client+ .prepare_discovered_model_connection(+ &crate::random_id()?,+ request,+ ProtectedClientGrantV2 {+ principal_kind: PrincipalKind::Desktop,+ capability: capability.to_string(),+ },+ )+ .await?,+ )+ .map(Into::into)+}++pub async fn compute_connection_options(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<ComputeConnectionOptionsResultV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ crate::session::query(+ &client,+ "ListConnectionOptions",+ &ComputeConnectionOptionsRequestV1 { candidate: None },+ )+ .await+}++pub async fn register_protected_model_input(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ secret: String,+ source_id: Option<String>,+) -> Result<ProtectedModelInputRegistration, DesktopFailure> {+ main_window(window)?;+ {+ let candidate = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_model_input(zeroize::Zeroizing::new(secret))?;+ let key_id = source_id+ .as_deref()+ .map(|source| hiroute_domain::managed_key_id(source, &candidate.candidate_ref))+ .transpose()+ .map_err(|_| "CREDENTIAL_INPUT_INVALID")?;+ Ok(ProtectedModelInputRegistration {+ input_candidate: candidate,+ key_id,+ })+ }+}++pub async fn release_protected_model_input(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: ComputeCandidateRefV2,+) -> Result<(), DesktopFailure> {+ main_window(window)?;+ {+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .release_model_input(&input)+ .map_err(Into::into)+ }+}++pub async fn check_model_connection(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: NativeModelConnectionCheckRequestV1,+) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let status: ClientServiceStatusV1 = crate::session::query(+ &client,+ "GetClientServiceStatus",+ &hiroute_application_api::ClientEmptyRequestV1 {},+ )+ .await?;+ let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;+ let capability = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_model_check(&digest, &status.revisions)?;+ envelope_data(+ client+ .check_native_model_connection(+ &crate::random_id()?,+ request,+ ProtectedClientGrantV2 {+ principal_kind: PrincipalKind::Desktop,+ capability: capability.to_string(),+ },+ )+ .await?,+ )+}++pub async fn check_saved_model_connection(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: SavedModelConnectionCheckRequestV1,+) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let status: ClientServiceStatusV1 = crate::session::query(+ &client,+ "GetClientServiceStatus",+ &hiroute_application_api::ClientEmptyRequestV1 {},+ )+ .await?;+ let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;+ let capability = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_saved_model_check(&digest, &status.revisions)?;+ envelope_data(+ client+ .check_saved_model_connection(+ &crate::random_id()?,+ request,+ ProtectedClientGrantV2 {+ principal_kind: PrincipalKind::Desktop,+ capability: capability.to_string(),+ },+ )+ .await?,+ )+}++pub async fn check_registered_model_connection(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: RegisteredModelConnectionCheckRequestV1,+) -> Result<ModelConnectionCheckViewV1, DesktopFailure> {+ main_window(window)?;+ if request.display_name.is_none() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let status: ClientServiceStatusV1 = crate::session::query(+ &client,+ "GetClientServiceStatus",+ &hiroute_application_api::ClientEmptyRequestV1 {},+ )+ .await?;+ let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;+ let capability = state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_registered_model_check(&digest, &status.revisions)?;+ envelope_data(+ client+ .check_registered_model_connection(+ &crate::random_id()?,+ request,+ ProtectedClientGrantV2 {+ principal_kind: PrincipalKind::Desktop,+ capability: capability.to_string(),+ },+ )+ .await?,+ )+}++pub async fn cancel_model_connection_check(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ check_id: String,+) -> Result<(), DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(+ client+ .cancel_native_model_connection_check(&crate::random_id()?, check_id)+ .await?,+ )+}++pub async fn preview_compute_save(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ change: WebComputeManagementChangeV2,+) -> Result<WebComputeSavePreviewV2, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let change = change.try_into().map_err(DesktopFailure::from)?;+ let preview = envelope_data(+ client+ .preview_compute_save(&crate::random_id()?, change)+ .await?,+ )?;+ preview.try_into().map_err(DesktopFailure::from)+}++pub async fn apply_compute_save(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: WebComputeConnectionApplyRequestV1,+ language: String,+) -> Result<ModelSaveAccepted, DesktopFailure> {+ main_window(window)?;+ let request: ComputeConnectionApplyRequestV1 =+ request.try_into().map_err(DesktopFailure::from)?;+ let epoch = state.2.load(Ordering::SeqCst);+ let context = super::confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .prepare_model_save_confirmation(request, language)+ .await?;+ match confirm(+ window,+ state,+ ActionOperation::ModelSave,+ NativeConfirmation::ModelSave(Box::new(context)),+ epoch,+ )+ .await?+ {+ NativeOutcome::ModelSave(value) => Ok(value),+ _ => unreachable!(),+ }+}++pub async fn get_compute_save_result(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ operation: OperationReferenceV1,+) -> Result<WebComputeSaveResultV2, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ envelope_data(+ client+ .get_compute_save_result(&crate::random_id()?, operation)+ .await?,+ )+ .map(Into::into)+}diff --git a/crates/product-session/src/commands/observation.rs b/crates/product-session/src/commands/observation.rsnew file mode 100644index 00000000..b354e2a6--- /dev/null+++ b/crates/product-session/src/commands/observation.rs@@ -0,0 +1,110 @@+use super::web_confirmation::{WebConfirmationPrompt, request_web_confirmation};+use super::{ClientContext, CommandState, DesktopFailure, main_window};+use std::sync::atomic::Ordering;++#[derive(serde::Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ObservationDeleteInput {+ session_id: String,+ data_class: hiroute_application_api::DeletionDataClass,+ #[serde(default)]+ language: Option<String>,+}++pub async fn observation_delete(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: ObservationDeleteInput,+) -> Result<serde_json::Value, DesktopFailure> {+ main_window(window)?;+ {+ let epoch = state.2.load(Ordering::SeqCst);+ let spec = hiroute_application_api::SessionDeletionSpecV1 {+ workspace_id: hiroute_domain::WorkspaceId::default(),+ session_id: hiroute_domain::SessionId::parse(input.session_id)+ .map_err(|_| "SESSION_INVALID")?,+ data_class: input.data_class,+ delete_rollups: false,+ };+ let preview = super::confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .deletion_preview(spec)+ .await?;+ let task_refs: u64 = preview+ .managed_scopes+ .iter()+ .map(|scope| scope.reference_count)+ .sum();+ let english = input.language.as_deref() == Some("en");+ let (title, message, confirm, cancel) = localized_confirmation(+ english,+ &preview.session.spec.data_class,+ preview.session.requests,+ preview.session.content_instances,+ task_refs,+ );+ if !request_web_confirmation(+ window,+ WebConfirmationPrompt {+ title: title.into(),+ message,+ confirm_label: confirm.into(),+ cancel_label: cancel.into(),+ },+ )+ .await+ {+ return Ok(serde_json::json!({"cancelled":true}));+ }+ if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {+ return Err("CONFIRMATION_STALE".into());+ }+ let outcome = super::confirmation_session(state, epoch)+ .await?+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .deletion_apply(preview)+ .await?;+ serde_json::to_value(outcome).map_err(|_| "RESPONSE_DATA_INVALID".into())+ }+}++fn localized_confirmation(+ english: bool,+ data_class: &hiroute_application_api::DeletionDataClass,+ requests: u64,+ content_instances: u64,+ task_refs: u64,+) -> (&'static str, String, &'static str, &'static str) {+ if english {+ let scope = if *data_class == hiroute_application_api::DeletionDataClass::ContentOnly {+ "This removes prompts, answers and tool content while keeping the run record."+ } else {+ "This removes the session and its per-request records."+ };+ (+ "HiRoute · Clear this session",+ format!(+ "{scope}\n\nAffected: {requests} requests, {content_instances} content items and {task_refs} linked task content items.\n\nThis affects only this session and cannot be undone. Your working folders will not be deleted."+ ),+ "Clear session",+ "Cancel",+ )+ } else {+ let scope = if *data_class == hiroute_application_api::DeletionDataClass::ContentOnly {+ "将清理问题、回答和工具内容,保留运行记录。"+ } else {+ "将删除这条会话及其逐请求记录。"+ };+ (+ "HiRoute · 清理此会话",+ format!(+ "{scope}\n\n影响范围:{requests} 个请求、{content_instances} 段会话正文、{task_refs} 条关联任务正文。\n\n只影响这条会话且不可撤销;不会删除工作目录。"+ ),+ "确认清理",+ "取消",+ )+ }+}diff --git a/crates/product-session/src/commands/subscription_login.rs b/crates/product-session/src/commands/subscription_login.rsnew file mode 100644index 00000000..d24aa8e8--- /dev/null+++ b/crates/product-session/src/commands/subscription_login.rs@@ -0,0 +1,105 @@+//! Independent sign-in management. Callback material never enters ordinary Local Control JSON.+use crate::HostAuthority;++use super::{ClientContext, CommandState, main_window};+use crate::failure::DesktopFailure;+use hiroute_application_api::*;++fn login_data(+ envelope: MachineEnvelopeV2<ComputeSubscriptionLoginResultV1>,+) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {+ // The login backend projects only closed reason codes. Do not forward raw OAuth errors or+ // serialize an unexpected envelope, which could accidentally expose an authorization URL.+ if envelope.error.is_some() {+ return Err("SUBSCRIPTION_LOGIN_UNAVAILABLE".into());+ }+ envelope.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())+}++pub async fn manage_subscription_login(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ request: ComputeSubscriptionLoginRequestV1,+) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {+ main_window(window)?;+ if !request.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ login_data(+ client+ .manage_subscription_login(&crate::random_id()?, request)+ .await?,+ )+}++pub async fn submit_subscription_login_callback(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ login_ref: String,+ callback: String,+) -> Result<ComputeSubscriptionLoginResultV1, DesktopFailure> {+ let callback = zeroize::Zeroizing::new(callback);+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let status = login_data(+ client+ .manage_subscription_login(+ &crate::random_id()?,+ ComputeSubscriptionLoginRequestV1::Status {+ login_ref: login_ref.clone(),+ },+ )+ .await?,+ )?;+ let session = status+ .sessions+ .into_iter()+ .find(|session| session.login_ref == login_ref)+ .ok_or("SUBSCRIPTION_LOGIN_STALE")?;+ if session.status != SubscriptionLoginStatusV1::Pending {+ return Err("SUBSCRIPTION_LOGIN_STALE".into());+ }+ let input_candidate = session+ .callback_input_candidate+ .ok_or("SUBSCRIPTION_LOGIN_STALE")?;+ let callback_request_id = crate::random_id()?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .authority+ .register_subscription_callback_input(&input_candidate, callback)?;++ let response = client+ .manage_subscription_login(+ &callback_request_id,+ ComputeSubscriptionLoginRequestV1::Callback {+ login_ref,+ input_candidate: input_candidate.clone(),+ },+ )+ .await;+ // Release even after an uncertain response: a consumed input is already gone, and an+ // unconsumed callback must not remain available to an unrelated later operation.+ if let Some(session) = state.0.lock().await.as_mut() {+ session.authority.release_model_input(&input_candidate)?;+ }+ login_data(response?)+}diff --git a/crates/product-session/src/commands/web_confirmation.rs b/crates/product-session/src/commands/web_confirmation.rsnew file mode 100644index 00000000..dbbbf8da--- /dev/null+++ b/crates/product-session/src/commands/web_confirmation.rs@@ -0,0 +1,25 @@+use super::ClientContext;+use crate::confirmation::CONFIRMATION_TTL;+pub use crate::web_confirmation::*;+pub(super) async fn request_web_confirmation(+ window: &ClientContext<'_>,+ prompt: WebConfirmationPrompt,+) -> bool {+ let state = window.confirmations;+ let Ok((request, receive)) = state.begin(window.label(), prompt) else {+ return false;+ };+ let _pending = state.pending_guard(window.label(), &request);+ let id = request.confirmation_id.clone();+ if window+ .notify+ .is_some_and(|notify| notify(&request).is_err())+ {+ state.cancel(window.label(), &id);+ }+ let decision = tokio::time::timeout(CONFIRMATION_TTL, receive).await;+ if decision.is_err() {+ state.cancel(window.label(), &id);+ }+ decision.ok().and_then(Result::ok).unwrap_or(false)+}diff --git a/apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs b/crates/product-session/src/commands/worker_dependencies_tests.rssimilarity index 100%rename from apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rsrename to crates/product-session/src/commands/worker_dependencies_tests.rsdiff --git a/crates/product-session/src/commands/worker_tasks.rs b/crates/product-session/src/commands/worker_tasks.rsnew file mode 100644index 00000000..9c08d803--- /dev/null+++ b/crates/product-session/src/commands/worker_tasks.rs@@ -0,0 +1,562 @@+use super::{ClientContext, CommandState, main_window};+use crate::failure::DesktopFailure;+use hiroute_application_api::{+ DelegationAcceptedV1, DelegationCancelV1, DelegationGetV1, DelegationListV1,+ DelegationResultV1, DelegationRunViewV1, DelegationWaitV1, MachineEnvelopeV2, WorkPlanListV1,+ WorkerCancelRequestV1, WorkerContinueRequestV1, WorkerDependenciesDiscoverRequestV1,+ WorkerDependenciesSelectRequestV1, WorkerDependenciesViewV1, WorkerExecutorAvailabilityListV1,+ WorkerListRequestV1, WorkerPlansRequestV1, WorkerReadDataV1, WorkerReadRequestV1,+ WorkerResidualConfirmRequestV1, WorkerResultRequestV1, WorkerSettingsV1, WorkerStatusRequestV1,+ WorkerWaitRequestV1,+};+use serde::{Deserialize, Serialize, de::DeserializeOwned};+use std::collections::BTreeMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++const WORKER_DEPENDENCY_CONFIRMATION_SCHEMA_V1: &str =+ "hiroute.worker-dependency-selection-confirmation/v1";+const WORKER_DEPENDENCY_CONFIRMATION_TTL_MS: u64 = 60_000;++#[derive(Clone, Debug, Serialize)]+pub struct WorkerDependencyConfirmationV1 {+ schema: &'static str,+ confirmation_id: String,+ selection: WorkerDependenciesSelectRequestV1,+ expires_at_ms: u64,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkerDependencyConfirmationInput {+ confirmation_id: String,+}++#[derive(Clone)]+struct PendingWorkerDependencyConfirmation {+ window_label: String,+ selection: WorkerDependenciesSelectRequestV1,+ expires_at_ms: u64,+}++#[derive(Default)]+pub struct WorkerDependencyConfirmationState {+ pending: Mutex<BTreeMap<String, PendingWorkerDependencyConfirmation>>,+}++impl WorkerDependencyConfirmationState {+ fn lock(+ &self,+ ) -> std::sync::MutexGuard<'_, BTreeMap<String, PendingWorkerDependencyConfirmation>> {+ self.pending+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ fn prepare(+ &self,+ window_label: &str,+ selection: WorkerDependenciesSelectRequestV1,+ now_ms: u64,+ ) -> Result<WorkerDependencyConfirmationV1, DesktopFailure> {+ let expires_at_ms = now_ms+ .checked_add(WORKER_DEPENDENCY_CONFIRMATION_TTL_MS)+ .ok_or("CLOCK_UNAVAILABLE")?;+ let confirmation_id = format!("worker-dependency-confirmation/{}", crate::random_id()?);+ let mut pending = self.lock();+ pending.retain(|_, entry| entry.window_label != window_label);+ pending.insert(+ confirmation_id.clone(),+ PendingWorkerDependencyConfirmation {+ window_label: window_label.to_owned(),+ selection: selection.clone(),+ expires_at_ms,+ },+ );+ Ok(WorkerDependencyConfirmationV1 {+ schema: WORKER_DEPENDENCY_CONFIRMATION_SCHEMA_V1,+ confirmation_id,+ selection,+ expires_at_ms,+ })+ }++ fn take(+ &self,+ window_label: &str,+ confirmation_id: &str,+ now_ms: u64,+ ) -> Result<WorkerDependenciesSelectRequestV1, DesktopFailure> {+ if !valid_worker_dependency_confirmation_id(confirmation_id) {+ return Err("CONFIRMATION_STALE".into());+ }+ let entry = {+ let mut pending = self.lock();+ if pending+ .get(confirmation_id)+ .is_none_or(|entry| entry.window_label != window_label)+ {+ return Err("CONFIRMATION_STALE".into());+ }+ pending+ .remove(confirmation_id)+ .expect("matching Worker dependency confirmation exists")+ };+ if now_ms > entry.expires_at_ms {+ return Err("CONFIRMATION_EXPIRED".into());+ }+ Ok(entry.selection)+ }++ fn cancel(&self, window_label: &str, confirmation_id: &str) -> Result<(), DesktopFailure> {+ if !valid_worker_dependency_confirmation_id(confirmation_id) {+ return Err("CONFIRMATION_STALE".into());+ }+ let mut pending = self.lock();+ if pending+ .get(confirmation_id)+ .is_some_and(|entry| entry.window_label != window_label)+ {+ return Err("CONFIRMATION_STALE".into());+ }+ pending.remove(confirmation_id);+ Ok(())+ }++ pub fn cancel_window(&self, window_label: &str) {+ self.lock()+ .retain(|_, entry| entry.window_label != window_label);+ }+}++fn valid_worker_dependency_confirmation_id(value: &str) -> bool {+ value+ .strip_prefix("worker-dependency-confirmation/")+ .is_some_and(|id| {+ id.len() == 64+ && id+ .bytes()+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())+ })+}++fn now_ms() -> Result<u64, DesktopFailure> {+ Ok(std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|_| "CLOCK_UNAVAILABLE")?+ .as_millis()+ .try_into()+ .map_err(|_| "CLOCK_UNAVAILABLE")?)+}++fn normalize_worker_dependency_selection(+ request: &WorkerDependenciesSelectRequestV1,+) -> Result<WorkerDependenciesSelectRequestV1, DesktopFailure> {+ if !request.valid() {+ return Err("REQUEST_INVALID".into());+ }+ // The shared launch form requires adapters for Codex/Claude and forbids them for+ // native ACP clients. Only normalize components that the validated shape contains.+ let adapter = request+ .adapter_path+ .as_deref()+ .map(|path| normalize_required_path(Path::new(path), request.node_path.is_none()))+ .transpose()?;+ let cli = normalize_required_path(Path::new(&request.cli_path), true)?;+ let node = request+ .node_path+ .as_deref()+ .map(|path| normalize_required_path(Path::new(path), true))+ .transpose()?;+ let normalized = WorkerDependenciesSelectRequestV1 {+ harness: request.harness,+ adapter_path: adapter.map(normalized_path_string).transpose()?,+ cli_path: normalized_path_string(cli)?,+ node_path: node.map(normalized_path_string).transpose()?,+ expected_selection_revision: request.expected_selection_revision,+ };+ hiroute_application_api::plan_worker_dependency_selection(&normalized)+ .ok_or("REQUEST_INVALID")?;+ Ok(normalized)+}++fn normalize_required_path(+ path: &Path,+ require_executable: bool,+) -> Result<PathBuf, DesktopFailure> {+ let canonical = match fs::canonicalize(path) {+ Ok(path) => path,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return Err("WORKER_DEPENDENCIES_MISSING".into());+ }+ Err(_) => return Err("WORKER_DEPENDENCIES_UNAVAILABLE".into()),+ };+ let metadata = fs::metadata(&canonical).map_err(|_| "WORKER_DEPENDENCIES_UNAVAILABLE")?;+ if !metadata.is_file()+ || (require_executable && !path_is_executable(&metadata))+ || (!require_executable && fs::File::open(&canonical).is_err())+ {+ return Err("WORKER_DEPENDENCIES_INVALID".into());+ }+ Ok(canonical)+}++fn normalized_path_string(path: PathBuf) -> Result<String, DesktopFailure> {+ path.into_os_string()+ .into_string()+ .ok()+ .filter(|value| {+ !value.is_empty()+ && value.len() <= 4096+ && !value.contains(char::is_control)+ && Path::new(value).is_absolute()+ })+ .ok_or_else(|| "WORKER_DEPENDENCIES_INVALID".into())+}++fn path_is_executable(metadata: &fs::Metadata) -> bool {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ metadata.permissions().mode() & 0o111 != 0+ }+ #[cfg(not(unix))]+ {+ metadata.is_file()+ }+}++fn data<R>(envelope: MachineEnvelopeV2<R>) -> Result<R, DesktopFailure>+where+ R: DeserializeOwned + Serialize,+{+ if envelope.error.is_some() {+ let encoded = serde_json::to_value(envelope).map_err(|_| "RESPONSE_DATA_INVALID")?;+ let untyped = serde_json::from_value(encoded).map_err(|_| "RESPONSE_DATA_INVALID")?;+ return Err(DesktopFailure::backend(untyped));+ }+ envelope+ .data+ .ok_or_else(|| DesktopFailure::from("RESPONSE_DATA_MISSING"))+}++pub async fn worker_settings_get(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<WorkerSettingsV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let result = data(client.worker_settings(&crate::random_id()?).await?)?;+ if !result.valid() {+ return Err("RESPONSE_DATA_INVALID".into());+ }+ Ok(result)+}++pub async fn worker_settings_set(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerSettingsV1,+) -> Result<WorkerSettingsV1, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let result = data(+ client+ .set_worker_settings(&crate::random_id()?, &input)+ .await?,+ )?;+ if !result.valid() {+ return Err("RESPONSE_DATA_INVALID".into());+ }+ Ok(result)+}++pub async fn worker_executor_availability(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+) -> Result<WorkerExecutorAvailabilityListV1, DesktopFailure> {+ main_window(window)?;+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ let result = data(+ client+ .worker_executor_availability(&crate::random_id()?)+ .await?,+ )?;+ if !result.valid() {+ return Err("RESPONSE_DATA_INVALID".into());+ }+ Ok(result)+}++pub async fn worker_task_plans(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerPlansRequestV1,+) -> Result<MachineEnvelopeV2<WorkPlanListV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_plans(&crate::random_id()?, &input).await?)+}++pub async fn worker_dependencies_discover(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerDependenciesDiscoverRequestV1,+) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client+ .worker_dependencies_discover(&crate::random_id()?, &input)+ .await?)+}++pub async fn worker_dependencies_select_prepare(+ window: &ClientContext<'_>,+ state: &WorkerDependencyConfirmationState,+ desktop: &CommandState<'_>,+ input: WorkerDependenciesSelectRequestV1,+) -> Result<WorkerDependencyConfirmationV1, DesktopFailure> {+ main_window(window)?;+ let epoch = desktop.2.load(std::sync::atomic::Ordering::SeqCst);+ let session = super::confirmation_session(desktop, epoch).await?;+ session.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;+ let selection = normalize_worker_dependency_selection(&input)?;+ state.prepare(window.label(), selection, now_ms()?)+}++pub async fn worker_dependencies_select_confirm(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ confirmations: &WorkerDependencyConfirmationState,+ input: WorkerDependencyConfirmationInput,+) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {+ main_window(window)?;+ let epoch = state.2.load(std::sync::atomic::Ordering::SeqCst);+ let mut session = super::confirmation_session(state, epoch).await?;+ let selection = confirmations.take(window.label(), &input.confirmation_id, now_ms()?)?;+ session+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .select_worker_dependencies(selection)+ .await+}++pub async fn worker_dependencies_select_cancel(+ window: &ClientContext<'_>,+ state: &WorkerDependencyConfirmationState,+ input: WorkerDependencyConfirmationInput,+) -> Result<(), DesktopFailure> {+ main_window(window)?;+ state.cancel(window.label(), &input.confirmation_id)+}++pub async fn worker_task_list(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerListRequestV1,+) -> Result<MachineEnvelopeV2<DelegationListV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_list(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_status(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerStatusRequestV1,+) -> Result<MachineEnvelopeV2<DelegationGetV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_status(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_result(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerResultRequestV1,+) -> Result<MachineEnvelopeV2<DelegationResultV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_result(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_read(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerReadRequestV1,+) -> Result<MachineEnvelopeV2<WorkerReadDataV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_read(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_wait(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerWaitRequestV1,+) -> Result<MachineEnvelopeV2<DelegationWaitV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_wait(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_confirm_residual(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerResidualConfirmRequestV1,+) -> Result<MachineEnvelopeV2<DelegationRunViewV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client+ .confirm_worker_residual(&crate::random_id()?, &input)+ .await?)+}++pub async fn worker_task_cancel(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerCancelRequestV1,+) -> Result<MachineEnvelopeV2<DelegationCancelV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_cancel(&crate::random_id()?, &input).await?)+}++pub async fn worker_task_continue(+ window: &ClientContext<'_>,+ state: &CommandState<'_>,+ input: WorkerContinueRequestV1,+) -> Result<MachineEnvelopeV2<DelegationAcceptedV1>, DesktopFailure> {+ main_window(window)?;+ if !input.valid() {+ return Err("REQUEST_INVALID".into());+ }+ let client = state+ .0+ .lock()+ .await+ .as_ref()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .client+ .clone();+ Ok(client.worker_continue(&crate::random_id()?, &input).await?)+}++#[cfg(test)]+#[path = "worker_dependencies_tests.rs"]+mod tests;diff --git a/apps/desktop/src-tauri/src/confirmation.rs b/crates/product-session/src/confirmation.rssimilarity index 78%rename from apps/desktop/src-tauri/src/confirmation.rsrename to crates/product-session/src/confirmation.rsindex adaaf1c7..7b99ed26 100644--- a/apps/desktop/src-tauri/src/confirmation.rs+++ b/crates/product-session/src/confirmation.rs@@ -7,11 +7,11 @@ use std::{time::{Duration, Instant},};-pub(crate) const CONFIRMATION_TTL: Duration = Duration::from_secs(60);+pub const CONFIRMATION_TTL: Duration = Duration::from_secs(60);/// Recovery advances the epoch while holding this same mutex. Check only after/// acquiring it, before creating a permit or applying an already accepted decision.-pub(crate) async fn lock_current_session<'a, T>(+pub async fn lock_current_session<'a, T>(sessions: &'a tokio::sync::Mutex<T>,epoch: &AtomicU64,captured: u64,@@ -24,23 +24,31 @@ pub(crate) async fn lock_current_session<'a, T>(}#[derive(Default)]-pub(crate) struct ConfirmationGate {- identity: Arc<()>,+pub struct ConfirmationGate {+ identity: Arc<AtomicU64>,generation: u64,- open: bool,}-pub(crate) struct ConfirmationPermit {- identity: Arc<()>,+pub struct ConfirmationPermit {+ identity: Arc<AtomicU64>,generation: u64,created: Instant,}/// Stable for the owning Session, including after its window confirmations expire.-pub(crate) struct ConfirmationOwner(Arc<()>);+pub struct ConfirmationOwner(Arc<AtomicU64>);+impl Drop for ConfirmationPermit {+ fn drop(&mut self) {+ // A disconnected caller cannot strand its Session in an open preview.+ // A stale permit must never cancel a newer confirmation.+ let _ =+ self.identity+ .compare_exchange(self.generation, 0, Ordering::SeqCst, Ordering::SeqCst);+ }+}impl ConfirmationGate {- pub(crate) fn owner(&self) -> ConfirmationOwner {+ pub fn owner(&self) -> ConfirmationOwner {ConfirmationOwner(self.identity.clone())}- pub(crate) fn check_owner(&self, owner: &ConfirmationOwner) -> Result<(), &'static str> {+ pub fn check_owner(&self, owner: &ConfirmationOwner) -> Result<(), &'static str> {if Arc::ptr_eq(&self.identity, &owner.0) {Ok(())} else {@@ -48,14 +56,17 @@ impl ConfirmationGate {}}pub fn is_open(&self) -> bool {- self.open+ self.identity.load(Ordering::SeqCst) != 0}pub fn begin(&mut self) -> Result<ConfirmationPermit, &'static str> {- if self.open {+ if self.is_open() {return Err("CONFIRMATION_ALREADY_OPEN");}self.generation = self.generation.wrapping_add(1);- self.open = true;+ if self.generation == 0 {+ self.generation = 1;+ }+ self.identity.store(self.generation, Ordering::SeqCst);Ok(ConfirmationPermit {identity: self.identity.clone(),generation: self.generation,@@ -64,7 +75,7 @@ impl ConfirmationGate {}pub fn invalidate(&mut self) {self.generation = self.generation.wrapping_add(1);- self.open = false;+ self.identity.store(0, Ordering::SeqCst);}pub fn finish(&mut self,@@ -72,12 +83,14 @@ impl ConfirmationGate {accepted: bool,) -> Result<bool, &'static str> {if !Arc::ptr_eq(&self.identity, &permit.identity)- || !self.open|| permit.generation != self.generation+ || self+ .identity+ .compare_exchange(permit.generation, 0, Ordering::SeqCst, Ordering::SeqCst)+ .is_err(){return Err("CONFIRMATION_STALE");}- self.open = false;if accepted && permit.created.elapsed() > CONFIRMATION_TTL {return Err("CONFIRMATION_EXPIRED");}@@ -87,6 +100,28 @@ impl ConfirmationGate {#[cfg(test)]mod tests {use super::*;+ #[test]+ fn dropping_an_unfinished_permit_reopens_only_its_own_gate() {+ let mut gate = ConfirmationGate::default();+ let owner = gate.owner();+ let abandoned = gate.begin().unwrap();+ assert!(gate.is_open());+ drop(abandoned);+ assert!(!gate.is_open());+ assert!(gate.check_owner(&owner).is_ok());+ let fresh = gate.begin().unwrap();+ assert!(gate.finish(&fresh, true).unwrap());+ }+ #[test]+ fn dropping_a_stale_permit_preserves_the_new_confirmation() {+ let mut gate = ConfirmationGate::default();+ let old = gate.begin().unwrap();+ gate.invalidate();+ let fresh = gate.begin().unwrap();+ drop(old);+ assert!(gate.is_open());+ assert!(gate.finish(&fresh, true).unwrap());+ }#[tokio::test]async fn queued_preview_cannot_open_a_gate_in_the_replacement_session() {let epoch = AtomicU64::new(0);diff --git a/apps/desktop/src-tauri/src/failure.rs b/crates/product-session/src/failure.rssimilarity index 100%rename from apps/desktop/src-tauri/src/failure.rsrename to crates/product-session/src/failure.rsdiff --git a/crates/product-session/src/fault.rs b/crates/product-session/src/fault.rsnew file mode 100644index 00000000..39be9536--- /dev/null+++ b/crates/product-session/src/fault.rs@@ -0,0 +1,18 @@+use std::cell::Cell;+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum Fault {+ None,+ LoseApplyResponseAndDisconnect,+ LoseBeforeApply,+}+thread_local! { pub static FAULT: Cell<Fault> = const { Cell::new(Fault::None) }; }+pub fn take(fault: Fault) -> bool {+ FAULT.with(|current| {+ if current.get() == fault {+ current.set(Fault::None);+ true+ } else {+ false+ }+ })+}diff --git a/crates/product-session/src/lib.rs b/crates/product-session/src/lib.rsnew file mode 100644index 00000000..2be482a4--- /dev/null+++ b/crates/product-session/src/lib.rs@@ -0,0 +1,22 @@+#![forbid(unsafe_code)]+pub mod authority;+pub mod catalog;+pub mod confirmation;+pub mod failure;+pub mod operation_observation;+pub mod session;+pub mod web_confirmation;+pub use authority::{HostAuthority, SessionAuthority};+pub use session::ProductSession;+#[cfg(feature = "test-support")]+pub mod fault;+pub fn random_id() -> Result<String, String> {+ let mut bytes = zeroize::Zeroizing::new([0u8; 32]);+ getrandom::fill(bytes.as_mut()).map_err(|_| "RANDOM_UNAVAILABLE".to_owned())?;+ Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())+}++#[cfg(test)]+mod authority_tests;++pub mod commands;diff --git a/apps/desktop/src-tauri/src/operation_observation.rs b/crates/product-session/src/operation_observation.rssimilarity index 99%rename from apps/desktop/src-tauri/src/operation_observation.rsrename to crates/product-session/src/operation_observation.rsindex 7fbb4eb6..97f4bbcb 100644--- a/apps/desktop/src-tauri/src/operation_observation.rs+++ b/crates/product-session/src/operation_observation.rs@@ -61,7 +61,7 @@ impl IntentEvidence {}}-pub(crate) async fn lookup(+pub async fn lookup(client: &hiroute_client_core::Client,pending: &mut Option<SubmittedOperation>,) -> Result<Option<hiroute_application_api::ClientOperationViewV1>, crate::failure::DesktopFailure>diff --git a/apps/desktop/src-tauri/src/session.rs b/crates/product-session/src/session.rssimilarity index 93%rename from apps/desktop/src-tauri/src/session.rsrename to crates/product-session/src/session.rsindex fb9c55d2..4aab8d74 100644--- a/apps/desktop/src-tauri/src/session.rs+++ b/crates/product-session/src/session.rs@@ -1,3 +1,4 @@+use crate::authority::HostAuthority;#[path = "agent_check_session.rs"]mod checks;pub use checks::*;@@ -16,7 +17,7 @@ use serde_json::Value;use std::collections::BTreeMap;use std::sync::{Arc, atomic::AtomicBool};mod prices;-pub use prices::{PriceConfirmation, PriceDisplayResult, PriceEditInput};+pub use prices::{DecimalPriceAction, PriceConfirmation, PriceDisplayResult, PriceEditInput};mod authoring;pub use authoring::EditorInput;mod model_save;@@ -102,8 +103,8 @@ impl Confirmation {pub fn action_label(&self) -> &str {&self.action_label}- #[cfg(all(test, target_os = "macos"))]- pub(crate) fn test_key(&self) -> &str {+ #[cfg(feature = "test-support")]+ pub fn test_key(&self) -> &str {&self.request.idempotency_key}pub fn message(&self) -> String {@@ -126,9 +127,8 @@ impl Confirmation {self.input.language == "en"}}-pub struct Session {- #[cfg(unix)]- pub resident: crate::bootstrap::Resident,+pub struct ProductSession {+ pub authority: Arc<crate::authority::SessionAuthority>,pub client: Client,hint: Option<SubmittedOperation>,subscription_hint: Option<SubmittedOperation>,@@ -140,9 +140,8 @@ pub struct Session {subscription_close_requested: Arc<AtomicBool>,subscription_cancel_request: Option<OperationCancelRequestV1>,}-impl Session {- #[cfg(all(unix, feature = "desktop-runtime"))]- pub(crate) async fn deletion_preview(+impl ProductSession {+ pub async fn deletion_preview(&mut self,spec: SessionDeletionSpecV1,) -> Result<SessionDeletionPreviewV2, DesktopFailure> {@@ -155,7 +154,7 @@ impl Session {let request = ObservationDeletePreviewRequestV2 { spec };let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;let token = self- .resident+ .authority.register_retention(&digest, &status.revisions, false)?;let result = self.client@@ -173,8 +172,7 @@ impl Session {}result.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())}- #[cfg(all(unix, feature = "desktop-runtime"))]- pub(crate) async fn deletion_apply(+ pub async fn deletion_apply(&mut self,preview: SessionDeletionPreviewV2,) -> Result<SessionDeletionOutcomeV2, DesktopFailure> {@@ -190,7 +188,7 @@ impl Session {};let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;let token = self- .resident+ .authority.register_retention(&digest, &status.revisions, true)?;let result = self.client@@ -213,7 +211,6 @@ impl Session {&mut self,request: ObservationReadRequestV2,) -> Result<Value, DesktopFailure> {- #[cfg(unix)]{let status: ClientServiceStatusV1 = query(&self.client,@@ -222,7 +219,7 @@ impl Session {).await?;let capability = self- .resident+ .authority.register_observation(&request, &status.revisions)?;let envelope: MachineEnvelopeV2<Value> = self.client@@ -240,18 +237,12 @@ impl Session {}envelope.data.ok_or_else(|| "RESPONSE_DATA_MISSING".into())}- #[cfg(not(unix))]- {- let _ = request;- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }}pub async fn test_classifier_decision(&mut self,classifier: hiroute_domain::ComplexityClassifierModeV1,) -> Result<ClassifierDecisionTestResultV1, DesktopFailure> {- #[cfg(unix)]{let request = ClassifierDecisionTestRequestV1 {schema: CLASSIFIER_DECISION_TEST_SCHEMA_V1.into(),@@ -267,7 +258,7 @@ impl Session {).await?;let capability = self- .resident+ .authority.register_classifier_diagnostic(&request, &status.revisions)?;let envelope: MachineEnvelopeV2<Value> = self.client@@ -289,11 +280,6 @@ impl Session {serde_json::from_value(envelope.data.ok_or("RESPONSE_DATA_MISSING")?).map_err(|_| "RESPONSE_DATA_INVALID".into())}- #[cfg(not(unix))]- {- let _ = classifier;- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }}pub async fn save_classifier_header_secret(@@ -301,9 +287,8 @@ impl Session {secret_id: String,secret: zeroize::Zeroizing<String>,) -> Result<ApplyResultV1, DesktopFailure> {- #[cfg(unix)]{- let candidate = self.resident.register_model_input(secret)?;+ let candidate = self.authority.register_model_input(secret)?;let desired_state = match serde_json::to_value(ClassifierHeaderSecretInputV1 {secret_id,input_slot: candidate.candidate_ref.clone(),@@ -311,7 +296,7 @@ impl Session {}) {Ok(value) => value,Err(_) => {- let _ = self.resident.release_model_input(&candidate);+ let _ = self.authority.release_model_input(&candidate);return Err("CLASSIFIER_SECRET_INVALID".into());}};@@ -330,14 +315,14 @@ impl Session {let preview = match preview {Ok(preview) => preview,Err(error) => {- let _ = self.resident.release_model_input(&candidate);+ let _ = self.authority.release_model_input(&candidate);return Err(error);}};let idempotency_id = match crate::random_id() {Ok(value) => value,Err(error) => {- let _ = self.resident.release_model_input(&candidate);+ let _ = self.authority.release_model_input(&candidate);return Err(error.into());}};@@ -352,14 +337,14 @@ impl Session {let payload = match serde_json::to_value(request) {Ok(value) => value,Err(_) => {- let _ = self.resident.release_model_input(&candidate);+ let _ = self.authority.release_model_input(&candidate);return Err("CLASSIFIER_SECRET_INVALID".into());}};let request_id = match crate::random_id() {Ok(value) => value,Err(error) => {- let _ = self.resident.release_model_input(&candidate);+ let _ = self.authority.release_model_input(&candidate);return Err(error.into());}};@@ -376,7 +361,7 @@ impl Session {// Application runs this transaction synchronously. Once the call returns,// the protected input is no longer needed, including transport and terminal// failures.- let release = self.resident.release_model_input(&candidate);+ let release = self.authority.release_model_input(&candidate);let envelope = match envelope {Ok(envelope) => envelope,Err(error) => {@@ -391,20 +376,14 @@ impl Session {serde_json::from_value(envelope.data.ok_or("RESPONSE_DATA_MISSING")?).map_err(|_| "RESPONSE_DATA_INVALID".into())}- #[cfg(not(unix))]- {- let _ = (secret_id, secret);- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }}- #[cfg(unix)]- pub fn new(resident: crate::bootstrap::Resident) -> Self {+ pub fn new(client: Client, authority: Arc<dyn HostAuthority>) -> Self {let mut cursor = ObservationCursor::default();let observation_generation = cursor.restart();Self {- client: resident.client.clone(),- resident,+ client,+ authority: Arc::new(crate::authority::SessionAuthority::new(authority)),hint: None,subscription_hint: None,confirmation: ConfirmationGate::default(),@@ -446,10 +425,7 @@ impl Session {};// The successful status query came over Client Core's verified owner-only Local Control// peer. Configuration writes use that same transport, not the separate check grant pipe.- #[cfg(unix)]let trusted_authority = true;- #[cfg(not(unix))]- let trusted_authority = false;Ok(DesktopSnapshot {service,catalog,@@ -602,8 +578,8 @@ impl Session {payload: serde_json::to_value(context.request).map_err(|_| "REQUEST_INVALID")?,protected_grant: None,};- #[cfg(all(test, target_os = "macos"))]- if crate::fault_tests::take(crate::fault_tests::Fault::LoseBeforeApply) {+ #[cfg(feature = "test-support")]+ if crate::fault::take(crate::fault::Fault::LoseBeforeApply) {return Err(hiroute_client_core::ClientFailure {code: hiroute_client_core::FailureCode::TransportUnavailable,submission: hiroute_client_core::SubmissionState::MayHaveReachedServer,@@ -611,8 +587,8 @@ impl Session {.into());}let response = self.client.call_wire(request).await;- #[cfg(all(test, target_os = "macos"))]- if crate::fault_tests::take(crate::fault_tests::Fault::LoseApplyResponseAndDisconnect) {+ #[cfg(feature = "test-support")]+ if crate::fault::take(crate::fault::Fault::LoseApplyResponseAndDisconnect) {// Fault boundary: the real daemon processed the request, but the native// session receives neither its response nor a subsequent lookup result.return Err(hiroute_client_core::ClientFailure {@@ -733,7 +709,6 @@ impl Session {.expect("checked model save hint").idempotency_key.clone();- #[cfg(unix)]self.release_pending_model_inputs(&idempotency_key)?;}Ok(result)@@ -780,7 +755,7 @@ async fn read_plan_catalog(client: &Client) -> Result<AgentPlanCatalogViewV2, DeErr("CATALOG_LIMIT_EXCEEDED".into())}-pub(crate) async fn query<P: Serialize, R: serde::de::DeserializeOwned>(+pub async fn query<P: Serialize, R: serde::de::DeserializeOwned>(client: &Client,operation: &str,payload: &P,@@ -825,6 +800,8 @@ fn accepted_operation_view(})}+pub type Session = ProductSession;+#[cfg(test)]mod tests {use super::*;diff --git a/apps/desktop/src-tauri/src/session/agent_discovery.rs b/crates/product-session/src/session/agent_discovery.rssimilarity index 100%rename from apps/desktop/src-tauri/src/session/agent_discovery.rsrename to crates/product-session/src/session/agent_discovery.rsdiff --git a/apps/desktop/src-tauri/src/session/authoring.rs b/crates/product-session/src/session/authoring.rssimilarity index 100%rename from apps/desktop/src-tauri/src/session/authoring.rsrename to crates/product-session/src/session/authoring.rsdiff --git a/apps/desktop/src-tauri/src/session/decision_services.rs b/crates/product-session/src/session/decision_services.rssimilarity index 91%rename from apps/desktop/src-tauri/src/session/decision_services.rsrename to crates/product-session/src/session/decision_services.rsindex 1bbb19a2..ca5734ff 100644--- a/apps/desktop/src-tauri/src/session/decision_services.rs+++ b/crates/product-session/src/session/decision_services.rs@@ -1,4 +1,5 @@use super::*;+use crate::authority::HostAuthority;use hiroute_domain::{DecisionConnectionV1, DecisionServiceChangeV1, DecisionServiceV1};#[derive(Deserialize, Serialize)]@@ -16,7 +17,6 @@ impl Session {mut change: DecisionServiceChangeV1,secret: Option<zeroize::Zeroizing<String>>,) -> Result<ApplyResultV1, DesktopFailure> {- #[cfg(unix)]{if change.input_slot.is_some() {return Err("DECISION_SERVICE_INVALID".into());@@ -41,7 +41,7 @@ impl Session {secret}};- let candidate = self.resident.register_model_input(value)?;+ let candidate = self.authority.register_model_input(value)?;change.input_slot = Some(candidate.candidate_ref.clone());Some(candidate)} else {@@ -49,18 +49,12 @@ impl Session {};let result = self.apply_decision_service_change(change).await;if let Some(candidate) = candidate {- self.resident.release_model_input(&candidate)?;+ self.authority.release_model_input(&candidate)?;}result}- #[cfg(not(unix))]- {- let _ = (change, secret);- Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())- }}- #[cfg(unix)]async fn apply_decision_service_change(&self,change: DecisionServiceChangeV1,diff --git a/apps/desktop/src-tauri/src/session/model_save.rs b/crates/product-session/src/session/model_save.rssimilarity index 99%rename from apps/desktop/src-tauri/src/session/model_save.rsrename to crates/product-session/src/session/model_save.rsindex 47d9c071..13b9f064 100644--- a/apps/desktop/src-tauri/src/session/model_save.rs+++ b/crates/product-session/src/session/model_save.rs@@ -1,4 +1,5 @@use super::{Session, terminal};+use crate::authority::HostAuthority;use crate::confirmation::ConfirmationPermit;use crate::failure::DesktopFailure;use crate::operation_observation::{IntentEvidence, SubmittedOperation};@@ -222,13 +223,11 @@ impl Session {}};if terminal(&operation.state) {- #[cfg(unix)]self.release_pending_model_inputs(&model_save_key)?;}self.resume_observing();Ok(ModelSaveAccepted { result, operation })}- #[cfg(unix)]pub(super) fn release_pending_model_inputs(&mut self,idempotency_key: &str,@@ -237,7 +236,7 @@ impl Session {return Ok(());};for candidate in &candidates {- self.resident.release_model_input(candidate)?;+ self.authority.release_model_input(candidate)?;}self.pending_model_inputs.remove(idempotency_key);Ok(())diff --git a/apps/desktop/src-tauri/src/session/prices.rs b/crates/product-session/src/session/prices.rssimilarity index 70%rename from apps/desktop/src-tauri/src/session/prices.rsrename to crates/product-session/src/session/prices.rsindex ad7ec8bf..22dc6af8 100644--- a/apps/desktop/src-tauri/src/session/prices.rs+++ b/crates/product-session/src/session/prices.rs@@ -274,114 +274,3 @@ impl PriceDisplayResult {}}}--#[cfg(all(test, target_os = "macos"))]-mod production_tests {- use super::*;- #[tokio::test]- async fn native_price_confirmation_uses_real_cli_daemon_and_restart() {- let root = tempfile::Builder::new()- .prefix("hr10-")- .tempdir_in(std::fs::canonicalize("/tmp").unwrap())- .unwrap();- let home = tempfile::tempdir().unwrap();- // The registered external settings target requires an existing owned parent.- std::fs::create_dir(home.path().join(".claude")).unwrap();- let script =- std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/prepare_plan.py");- let preparation = std::process::Command::new("python3")- .arg(script)- .arg(root.path())- .env("HOME", std::fs::canonicalize(home.path()).unwrap())- .output()- .unwrap();- assert!(- preparation.status.success(),- "CLI preparation: {}",- String::from_utf8_lossy(&preparation.stderr)- );- let projection: Value = serde_json::from_slice(- &std::fs::read(root.path().join("compute-projection.json")).unwrap(),- )- .unwrap();- let binding = &projection["binding"];- let binary = std::env::current_exe()- .unwrap()- .parent()- .unwrap()- .parent()- .unwrap()- .join("hirouted");- let open = || Session::new(crate::bootstrap::Resident::open(root.path(), &binary).unwrap());- let input = |revision| PriceEditInput {- target_locator: PriceTargetLocatorV1::Binding {- binding_id: binding["binding_id"].as_str().unwrap().into(),- },- currency: "USD".into(),- valuation_kind: hiroute_domain::PriceValuationKindV1::UsageEstimate,- expected_source_revision: binding["source_revision"].as_u64().unwrap(),- expected_binding_revision: Some(binding["revision"].as_u64().unwrap()),- expected_override_revision: revision,- language: "en".into(),- action: DecimalPriceAction::Set {- input_uncached: "1.200001".into(),- output: "4.8".into(),- cache_read: None,- cache_write: None,- },- };- let mut session = open();- let context = session.preview_price(input(0)).await.unwrap();- assert!(context.message().contains("1.200001"));- let cancelled = session- .finish_price_confirmation(context, false)- .await- .unwrap();- assert_eq!(cancelled.state, "cancelled_before_apply");- assert!(session.hint.is_none());- let context = session.preview_price(input(0)).await.unwrap();- let outcome = session- .finish_price_confirmation(context, true)- .await- .unwrap();- assert_eq!(outcome.operation.unwrap().state, "succeeded");- assert!(session.preview_price(input(0)).await.is_err());- drop(session);- let mut session = open();- let prices: EffectivePricesResultV2 = query(- &session.client,- "GetEffectivePrices",- &GetEffectivePricesV2 {- targets: vec![EffectivePriceTargetQueryV2 {- query_id: "selected".into(),- target_locator: input(1).target_locator,- currency: "USD".into(),- valuation_kind: hiroute_domain::PriceValuationKindV1::UsageEstimate,- }],- },- )- .await- .unwrap();- assert_eq!(- prices.items[0].quote.origin,- hiroute_domain::PriceOriginV1::Manual- );- assert_eq!(- prices.items[0].quote.rates.input_uncached,- TokenRateV1::known(1_200_001)- );- let mut restore = input(1);- restore.action = DecimalPriceAction::FollowCatalog;- let context = session.preview_price(restore).await.unwrap();- assert_eq!(- session- .finish_price_confirmation(context, true)- .await- .unwrap()- .operation- .unwrap()- .state,- "succeeded"- );- }-}diff --git a/apps/desktop/src-tauri/src/session/subscription.rs b/crates/product-session/src/session/subscription.rssimilarity index 95%rename from apps/desktop/src-tauri/src/session/subscription.rsrename to crates/product-session/src/session/subscription.rsindex 29a9e90e..efaa0af2 100644--- a/apps/desktop/src-tauri/src/session/subscription.rs+++ b/crates/product-session/src/session/subscription.rs@@ -1,4 +1,5 @@use super::{Session, query, terminal};+use crate::authority::HostAuthority;use crate::confirmation::{ConfirmationOwner, ConfirmationPermit};use crate::failure::DesktopFailure;use crate::operation_observation::{IntentEvidence, SubmittedOperation};@@ -25,8 +26,7 @@ impl SubscriptionCheckConfirmation {/// An approved A request whose protected call can run without monopolizing the backend Session./// The only shared state is a close signal; no WebView can construct this value.-#[cfg(any(feature = "desktop-runtime", test))]-pub(crate) struct PendingSubscriptionCheck {+pub struct PendingSubscriptionCheck {owner: ConfirmationOwner,client: hiroute_client_core::Client,request_id: String,@@ -35,8 +35,7 @@ pub(crate) struct PendingSubscriptionCheck {close_requested: Arc<AtomicBool>,}-#[cfg(any(feature = "desktop-runtime", test))]-pub(crate) struct SubscriptionCheckCompletion {+pub struct SubscriptionCheckCompletion {owner: ConfirmationOwner,idempotency_key: String,accepted_digest: CanonicalDigest,@@ -44,17 +43,15 @@ pub(crate) struct SubscriptionCheckCompletion {close_requested: Arc<AtomicBool>,}-#[cfg(any(feature = "desktop-runtime", test))]enum SubscriptionCheckSubmission {ClosedBeforeSend,Submitted(Box<Result<MachineEnvelopeV2<ApplyResultV1>, hiroute_client_core::ClientFailure>>),}-#[cfg(any(feature = "desktop-runtime", test))]impl PendingSubscriptionCheck {/// There is deliberately no await between the close check and entering Client Core. Once the/// protected call starts, close follows the normal Operation cancellation/observation policy.- pub(crate) async fn execute(self) -> SubscriptionCheckCompletion {+ pub async fn execute(self) -> SubscriptionCheckCompletion {let idempotency_key = self.request.idempotency_key.clone();let accepted_digest = self.request.accept_digest.clone();let outcome = if self.close_requested.load(Ordering::SeqCst) {@@ -85,8 +82,7 @@ impl PendingSubscriptionCheck {/// The submitted operation's completion entry. Window-close epochs expire new intent,/// while the originating Session still owns cleanup for work already submitted.-#[cfg(any(feature = "desktop-runtime", test))]-pub(crate) async fn complete_subscription_check(+pub async fn complete_subscription_check(sessions: &tokio::sync::Mutex<Option<Session>>,completion: SubscriptionCheckCompletion,) -> Result<ComputeSubscriptionCheckResultV2, DesktopFailure> {@@ -168,8 +164,7 @@ impl Session {/// Consumes native approval and retains the in-memory request identity before returning a protected/// call that the bridge must execute without holding the Session mutex.- #[cfg(any(feature = "desktop-runtime", test))]- pub(crate) async fn begin_subscription_check_confirmation(+ pub async fn begin_subscription_check_confirmation(&mut self,context: SubscriptionCheckConfirmation,accepted: bool,@@ -229,14 +224,10 @@ impl Session {};self.subscription_hint = Some(hint);- #[cfg(unix)]- let capability = self.resident.register_subscription_check(+ let capability = self.authority.register_subscription_check(&context.request.accept_digest,&context.request.expected_revisions,)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> =- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());Ok(PendingSubscriptionCheck {owner: self.confirmation.owner(),client: self.client.clone(),@@ -249,8 +240,7 @@ impl Session {/// Reconciles the exact A identity after the protected request completes. If the page closed/// while A was running, apply the close policy before returning control to the WebView.- #[cfg(any(feature = "desktop-runtime", test))]- pub(crate) async fn finish_subscription_check_confirmation(+ pub async fn finish_subscription_check_confirmation(&mut self,completion: SubscriptionCheckCompletion,) -> Result<ComputeSubscriptionCheckResultV2, DesktopFailure> {@@ -384,13 +374,9 @@ impl Session {).await?;let digest = CanonicalDigest::of(&validation).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]let capability = self- .resident+ .authority.register_subscription_release(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> =- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());let result = envelope_data(self.client.release_subscription_check(@@ -476,13 +462,9 @@ impl Session {).await?;let digest = CanonicalDigest::of(&request).map_err(|_| "REQUEST_INVALID")?;- #[cfg(unix)]let capability = self- .resident+ .authority.register_operation_cancel(&digest, &status.revisions)?;- #[cfg(not(unix))]- let capability: zeroize::Zeroizing<String> =- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());let _ = envelope_data(self.client.cancel_subscription_check(diff --git a/apps/desktop/src-tauri/src/session/subscription/completion_tests.rs b/crates/product-session/src/session/subscription/completion_tests.rssimilarity index 81%rename from apps/desktop/src-tauri/src/session/subscription/completion_tests.rsrename to crates/product-session/src/session/subscription/completion_tests.rsindex 65c2855b..3da5f12a 100644--- a/apps/desktop/src-tauri/src/session/subscription/completion_tests.rs+++ b/crates/product-session/src/session/subscription/completion_tests.rs@@ -7,12 +7,51 @@ use std::os::unix::fs::PermissionsExt;use std::sync::atomic::{AtomicUsize, Ordering};use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tokio::net::UnixListener;+use zeroize::Zeroizing;++const RELEASE_GRANT: &str = "completion-release-grant";++struct CompletionAuthority(Arc<AtomicUsize>);+impl HostAuthority for CompletionAuthority {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }+ fn has_authority(&self) -> bool {+ true+ }+ fn register_operation(+ &self,+ digest: &CanonicalDigest,+ revisions: &RevisionSetV1,+ operation: &'static str,+ ) -> Result<Zeroizing<String>, String> {+ let validation: ComputeValidationRefV2 =+ serde_json::from_value(result(false)["validation"].clone()).unwrap();+ assert_eq!(operation, RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2);+ assert_eq!(digest, &CanonicalDigest::of(&validation).unwrap());+ assert_eq!(revisions.target, 1);+ assert!(revisions.dependencies.is_empty());+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(Zeroizing::new(RELEASE_GRANT.into()))+ }+ fn register_input(+ &self,+ _: &ComputeCandidateRefV2,+ _: Zeroizing<String>,+ ) -> Result<(), String> {+ panic!("completion must not register a new protected input")+ }+ fn release_model_input(&self, _: &ComputeCandidateRefV2) -> Result<(), String> {+ panic!("completion must not release an unrelated protected input")+ }+}struct Fixture {- root: tempfile::TempDir,+ _root: tempfile::TempDir,client: Client,calls: Arc<AtomicUsize>,releases: Arc<AtomicUsize>,+ registrations: Arc<AtomicUsize>,created: Arc<AtomicBool>,server: tokio::task::JoinHandle<()>,}@@ -71,7 +110,9 @@ impl Fixture {}),RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2 => {assert_eq!(request.payload["validation_ref"], "validation-a");- assert!(request.protected_grant.is_some());+ let grant = request.protected_grant.as_ref().unwrap();+ assert_eq!(grant.principal_kind, PrincipalKind::Desktop);+ assert_eq!(grant.capability, RELEASE_GRANT);server_releases.fetch_add(1, Ordering::SeqCst);result(true)}@@ -89,19 +130,20 @@ impl Fixture {}});Self {- root,+ _root: root,client,calls,releases,+ registrations: Arc::new(AtomicUsize::new(0)),created,server,}}fn session(&self) -> Session {- Session::new(crate::bootstrap::session_resident(- self.root.path(),+ Session::new(self.client.clone(),- ))+ Arc::new(CompletionAuthority(self.registrations.clone())),+ )}}impl Drop for Fixture {@@ -175,6 +217,7 @@ async fn close_before_operation_record_releases_late_completed_validation() {session.invalidate_confirmation();session.close_subscription_check().await.unwrap();assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 0);assert!(session.subscription_hint.is_some());fixture.created.store(true, Ordering::SeqCst);let sessions = tokio::sync::Mutex::new(Some(session));@@ -182,6 +225,7 @@ async fn close_before_operation_record_releases_late_completed_validation() {.await.unwrap();assert_eq!(fixture.releases.load(Ordering::SeqCst), 1);+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 1);assert!(sessions.lock()@@ -213,6 +257,7 @@ async fn replacement_session_rejects_completion_before_queries_or_hint_changes()assert!(matches!(failure, DesktopFailure::Native { code } if code == "CONFIRMATION_STALE"));assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 0);assert_eq!(sessions.lock()diff --git a/apps/desktop/src-tauri/src/session/worker_dependencies.rs b/crates/product-session/src/session/worker_dependencies.rssimilarity index 98%rename from apps/desktop/src-tauri/src/session/worker_dependencies.rsrename to crates/product-session/src/session/worker_dependencies.rsindex a92b4b85..6c2d98c1 100644--- a/apps/desktop/src-tauri/src/session/worker_dependencies.rs+++ b/crates/product-session/src/session/worker_dependencies.rs@@ -3,7 +3,7 @@use super::*;impl Session {- pub(crate) async fn select_worker_dependencies(+ pub async fn select_worker_dependencies(&mut self,request: WorkerDependenciesSelectRequestV1,) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {diff --git a/crates/product-session/src/web_confirmation.rs b/crates/product-session/src/web_confirmation.rsnew file mode 100644index 00000000..b6f5ce41--- /dev/null+++ b/crates/product-session/src/web_confirmation.rs@@ -0,0 +1,304 @@+use crate::{confirmation::CONFIRMATION_TTL, failure::DesktopFailure};+use serde::{Deserialize, Serialize};+use std::{+ collections::BTreeMap,+ sync::{+ Mutex,+ atomic::{AtomicU64, Ordering},+ },+};+use tokio::sync::oneshot;+const WEB_CONFIRMATION_SCHEMA: &str = "hiroute.web-confirmation/v1";+pub struct WebConfirmationPrompt {+ pub title: String,+ pub message: String,+ pub confirm_label: String,+ pub cancel_label: String,+}++#[derive(Clone, Debug, Eq, PartialEq, Serialize)]+pub struct WebConfirmationRequest {+ schema: &'static str,+ pub confirmation_id: String,+ title: String,+ message: String,+ confirm_label: String,+ cancel_label: String,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WebConfirmationDecision {+ pub confirmation_id: String,+ pub accepted: bool,+}++struct PendingConfirmation {+ client_context: String,+ request: WebConfirmationRequest,+ sequence: u64,+ response: oneshot::Sender<bool>,+}++#[derive(Default)]+pub struct ConfirmationBroker {+ pending: Mutex<BTreeMap<String, PendingConfirmation>>,+ next_sequence: AtomicU64,+}+pub struct PendingConfirmationGuard<'a> {+ broker: &'a ConfirmationBroker,+ context: &'a str,+ id: String,+}+impl Drop for PendingConfirmationGuard<'_> {+ fn drop(&mut self) {+ self.broker.cancel(self.context, &self.id);+ }+}++impl ConfirmationBroker {+ pub fn pending_guard<'a>(+ &'a self,+ context: &'a str,+ request: &WebConfirmationRequest,+ ) -> PendingConfirmationGuard<'a> {+ PendingConfirmationGuard {+ broker: self,+ context,+ id: request.confirmation_id.clone(),+ }+ }+ fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, PendingConfirmation>> {+ self.pending+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ pub fn begin(+ &self,+ client_context: &str,+ prompt: WebConfirmationPrompt,+ ) -> Result<(WebConfirmationRequest, oneshot::Receiver<bool>), DesktopFailure> {+ let (response, receive) = oneshot::channel();+ let mut pending = self.lock();+ let sequence = self+ .next_sequence+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {+ value.checked_add(1)+ })+ .map_err(|_| DesktopFailure::from("CONFIRMATION_UNAVAILABLE"))?;+ let confirmation_id = loop {+ let candidate = format!("confirmation/{}", crate::random_id()?);+ if !pending.contains_key(&candidate) {+ break candidate;+ }+ };+ let request = WebConfirmationRequest {+ schema: WEB_CONFIRMATION_SCHEMA,+ confirmation_id: confirmation_id.clone(),+ title: prompt.title,+ message: prompt.message,+ confirm_label: prompt.confirm_label,+ cancel_label: prompt.cancel_label,+ };+ pending.insert(+ confirmation_id.clone(),+ PendingConfirmation {+ client_context: client_context.to_owned(),+ request: request.clone(),+ sequence,+ response,+ },+ );+ Ok((request, receive))+ }++ pub fn snapshot(&self, client_context: &str) -> Option<WebConfirmationRequest> {+ self.lock()+ .values()+ .filter(|pending| pending.client_context == client_context)+ .min_by_key(|pending| pending.sequence)+ .map(|pending| pending.request.clone())+ }++ pub fn resolve(+ &self,+ client_context: &str,+ confirmation_id: &str,+ accepted: bool,+ ) -> Result<(), DesktopFailure> {+ if !valid_confirmation_id(confirmation_id) {+ return Err("CONFIRMATION_STALE".into());+ }+ let pending = {+ let mut confirmations = self.lock();+ if confirmations+ .get(confirmation_id)+ .is_none_or(|pending| pending.client_context != client_context)+ {+ return Err("CONFIRMATION_STALE".into());+ }+ confirmations+ .remove(confirmation_id)+ .expect("matching confirmation exists")+ };+ pending+ .response+ .send(accepted)+ .map_err(|_| DesktopFailure::from("CONFIRMATION_STALE"))+ }++ pub fn cancel(&self, client_context: &str, confirmation_id: &str) {+ let pending = {+ let mut confirmations = self.lock();+ if confirmations+ .get(confirmation_id)+ .is_some_and(|pending| pending.client_context == client_context)+ {+ confirmations.remove(confirmation_id)+ } else {+ None+ }+ };+ if let Some(pending) = pending {+ let _ = pending.response.send(false);+ }+ }++ pub fn cancel_context(&self, client_context: &str) {+ let pending = {+ let mut confirmations = self.lock();+ let ids = confirmations+ .iter()+ .filter(|(_, pending)| pending.client_context == client_context)+ .map(|(id, _)| id.clone())+ .collect::<Vec<_>>();+ ids.into_iter()+ .filter_map(|id| confirmations.remove(&id))+ .collect::<Vec<_>>()+ };+ for pending in pending {+ let _ = pending.response.send(false);+ }+ }+}++fn valid_confirmation_id(value: &str) -> bool {+ value.strip_prefix("confirmation/").is_some_and(|id| {+ id.len() == 64+ && id+ .bytes()+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())+ })+}++impl ConfirmationBroker {+ pub async fn request(&self, context: &str, prompt: WebConfirmationPrompt) -> bool {+ let Ok((request, receive)) = self.begin(context, prompt) else {+ return false;+ };+ let _pending = self.pending_guard(context, &request);+ let decision = tokio::time::timeout(CONFIRMATION_TTL, receive).await;+ self.cancel(context, &request.confirmation_id);+ decision.ok().and_then(Result::ok).unwrap_or(false)+ }+}+#[cfg(test)]+mod tests {+ use super::*;++ fn prompt(title: &str) -> WebConfirmationPrompt {+ WebConfirmationPrompt {+ title: title.to_owned(),+ message: "Apply the verified change.".to_owned(),+ confirm_label: "Apply change".to_owned(),+ cancel_label: "Cancel".to_owned(),+ }+ }+ #[tokio::test]+ async fn aborting_a_request_removes_its_prompt_and_preserves_other_contexts() {+ let broker = std::sync::Arc::new(ConfirmationBroker::default());+ let (other, receive) = broker.begin("other", prompt("Other")).unwrap();+ let caller = broker.clone();+ let task = tokio::spawn(async move { caller.request("main", prompt("Abandoned")).await });+ tokio::task::yield_now().await;+ let abandoned = broker.snapshot("main").unwrap();+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ assert!(broker.snapshot("main").is_none());+ assert!(+ broker+ .resolve("main", &abandoned.confirmation_id, true)+ .is_err()+ );+ broker+ .resolve("other", &other.confirmation_id, true)+ .unwrap();+ assert!(receive.await.unwrap());+ }++ #[tokio::test]+ async fn exact_window_and_id_resolve_each_confirmation_once() {+ let state = ConfirmationBroker::default();+ let (request, receive) = state.begin("main", prompt("First")).unwrap();+ let id = request.confirmation_id;+ assert!(id.starts_with("confirmation/"));+ assert_eq!(id.len(), "confirmation/".len() + 64);+ assert!(state.resolve("other", &id, true).is_err());+ state.resolve("main", &id, true).unwrap();+ assert!(receive.await.unwrap());+ assert!(state.resolve("main", &id, true).is_err());+ }++ #[tokio::test]+ async fn closing_one_window_denies_only_its_pending_confirmations() {+ let state = ConfirmationBroker::default();+ let (_, main_one) = state.begin("main", prompt("Main one")).unwrap();+ let (_, main_two) = state.begin("main", prompt("Main two")).unwrap();+ let (other_request, other) = state.begin("other", prompt("Other")).unwrap();+ state.cancel_context("main");+ assert!(!main_one.await.unwrap());+ assert!(!main_two.await.unwrap());+ state+ .resolve("other", &other_request.confirmation_id, true)+ .unwrap();+ assert!(other.await.unwrap());+ }++ #[test]+ fn snapshot_returns_only_the_oldest_confirmation_for_the_exact_window() {+ let state = ConfirmationBroker::default();+ let (first, _) = state.begin("main", prompt("First")).unwrap();+ let (_, _) = state.begin("other", prompt("Other")).unwrap();+ let (_, _) = state.begin("main", prompt("Second")).unwrap();+ assert_eq!(state.snapshot("main"), Some(first));+ assert!(state.snapshot("missing").is_none());+ }++ #[test]+ fn decision_rejects_unknown_fields() {+ let value = serde_json::json!({+ "confirmation_id": format!("confirmation/{}", "0".repeat(64)),+ "accepted": true,+ "injected": "not accepted"+ });+ assert!(serde_json::from_value::<WebConfirmationDecision>(value).is_err());+ }++ #[test]+ fn confirmation_ids_are_exact_lowercase_random_tokens() {+ assert!(valid_confirmation_id(&format!(+ "confirmation/{}",+ "0a".repeat(32)+ )));+ assert!(!valid_confirmation_id("confirmation/1"));+ assert!(!valid_confirmation_id(&format!(+ "confirmation/{}",+ "A0".repeat(32)+ )));+ assert!(!valid_confirmation_id(&format!(+ "other/{}",+ "00".repeat(32)+ )));+ }+}diff --git a/docs/code-map/README.md b/docs/code-map/README.mdindex 1b9b4d51..9c023042 100644--- a/docs/code-map/README.md+++ b/docs/code-map/README.md@@ -29,11 +29,13 @@ results in the relevant run record.| Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Session queries](../../crates/observation/src/query_v2/sessions_tests.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) || Connect, resume or adjust through a terminal/Agent | [CLI journey](../../crates/cli/src/quickstart.rs), [complete Plan recovery](../../crates/cli/src/quickstart/plan_restore.rs), [shared authoring](../../crates/application/src/routing/editor_options.rs), [installed schemas](../../crates/application-api/src/command_schemas.rs), [shared management Skill](../../assets/skills/hiroute-management/SKILL.md) | [Installed Quickstart](../../crates/daemon/tests/support/quickstart_product.py), [effective evidence](../../crates/daemon/src/control/runtime/settings_effective_tests.rs) || Manage the service through CLI or Desktop | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [daemon control](../../crates/daemon/src/control) | [Real control process](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) |-| Install and operate native Windows headless, including background service | [Windows operating guide](../standalone-windows.md), [native kernel owners](../../crates/platform/README.md), [Windows installer](../../scripts/install-standalone-windows.py) | [Actual installed Control/Gateway/restart](../../crates/daemon/tests/windows_headless.rs); Task and SCM have different session and administrator boundaries |+| Configure and open the authenticated console locally or remotely | [Console owner](../../crates/daemon/src/console), [shared product session](../../crates/product-session/src), [console guide](../web-console.md) | [Real role-all authority/HTTP composition](../../crates/daemon/src/console/tests.rs), [production browser scenarios](../../apps/desktop/tests/v3/visual/console-scenarios.mjs) |+| Install and operate native Windows headless, including background service | [Windows operating guide](../standalone-windows.md), [native kernel owners](../../crates/platform/README.md), [Rust installation transaction](../../crates/host-runtime/src/standalone_install) | [Actual installed Control/Gateway/restart](../../crates/daemon/tests/windows_headless.rs); Task is the only offered manager; SCM is refused unchanged and retains low-level tests || Upgrade Desktop and recover a failed installation | [Updater](../../apps/desktop/src-tauri/src/updates.rs), [installer handshake](../../apps/desktop/src-tauri/src/updates/installer.rs), [resident restart](../../apps/desktop/src-tauri/src/bootstrap.rs) | Preflight → orderly stop → explicit commit; [macOS installation and recovery](../macos-installation.md) |+| Install, open or update Windows Desktop | [Windows shell](../../apps/shell/README.md), [shell payload and rollback ownership](../../apps/shell/src-tauri/src/runtime/install_transaction.rs), [local-console recovery and catalog failures](../windows-desktop-installation.md), [Rust Task transaction](../../crates/host-runtime/src/standalone_install), [restoration policy](../../crates/host-runtime/src/standalone_install/uninstall.rs), [owned package cleanup](../../crates/host-runtime/src/standalone_install/cleanup.rs) | [Native NSIS smoke](../../crates/daemon/tests/windows_desktop.rs), [shell page/host scenarios](../../apps/desktop/tests/v3/visual/shell-host-scenarios.mjs), [required native gates](../windows-desktop-installation.md#evidence-and-release-claims) || Maintain agent instructions, shared skills and issue-native planning | [Instruction ownership](../../.agents/README.md), [project workflow](../../issue-spec/project/workflow.md), [feedback routing](../../.agents/skills/hiroute-workflow-improvement/SKILL.md) | Pinned generated manifest, individual Claude links and current GitHub artifacts || Select, execute or diagnose a build/test run | [Validation workflow](../../.agents/skills/hiroute-validation/SKILL.md), [test map](testing.md) | [Selection](../../scripts/test-plan.py), [configured runner](../../scripts/validation.py) and revision-bound reports |-| Build macOS Desktop or Linux / Windows headless release candidates | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md), [independent Unix/Windows candidate jobs](../../.github/workflows/build-release.yml) | [Package-to-publication contract](../../scripts/test-build-release.py), [Linux ABI gate](../../scripts/linux-release-baseline.json), [Windows package/transaction checks](../../scripts/test-standalone-windows.py); final publishing remains in [release.yml](../../.github/workflows/release.yml) |+| Build macOS / Windows Desktop or Linux / Windows headless release candidates | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md), [independent Unix/Windows candidate jobs](../../.github/workflows/build-release.yml) | [Package-to-publication contract](../../scripts/test-build-release.py), [Linux ABI gate](../../scripts/linux-release-baseline.json), [Windows Desktop identity](../../scripts/package-windows-shell.py); final publishing remains in [release.yml](../../.github/workflows/release.yml) |## Read across boundariesdiff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex c977eba9..3b098ca2 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -3,6 +3,40 @@[Code map](README.md) · [Agent/Worker map](worker-context.md) ·[Decision map](decision-foundation.md) · [Test map](testing.md)+## Web console and Windows host++`crates/daemon/src/console` owns the separate HTTP listener, origin/asset admission,+credential stores and per-client product contexts. Service startup exclusively+binds configured sockets, including the local companion in network mode; launch+minting selects live state and never enables listening. Linux installer options+and `console init` persist scope/port in the host-runtime listener store. A wildcard+bind requires a concrete advertised IP for its one-use URL. Launch codes bind that+origin and actual port; the Windows shell explicitly requests the local endpoint.+Request deadlines cover each request independently of connection age; incomplete+headers and bodies have their own bounds. Shared confirmation permits and broker+prompts release on caller cancellation, without approving or affecting another context.+The console transport reserves separate 64-connection pools for loopback and network+peers. Socket writes close after 30 seconds without byte progress; successful writes+reset that deadline, and operation/confirmation waits do not arm it.+Its private in-process Client+Core transport shares Local Control budgets, operation admission and upgrade+drain; external Local Control retains its released-command gate. The frontend+`apps/desktop/src/host` selects the Tauri, browser or Windows-shell transport and+host capabilities. Browser product requests use explicit Bearer/context headers;+native host actions stay in their host adapter.++[`apps/shell`](../../apps/shell/README.md) owns the Windows Tauri window, exact-origin+host IPC, startup/reconnect, tray/login preference and NSIS hooks. The+[Rust standalone transaction](../../crates/host-runtime/src/standalone_install)+owns architecture-matched Task installation and current-schema journal recovery; the shell's separate+inventory/finisher owns its program files and update outcome. Neither owns business+transactions or exposes Local Control to WebView. The+[release catalog](../../apps/website/src/lib/releases.mjs) emits V3 and the registered+Windows-free V2 projection for supported macOS readers. Public Windows artifacts+are x64 NSIS installers only; headless x64/ARM64 archives stay internal. The+installer and tests invoke `__windows-install` / `__windows-uninstall`, with no+Python installer or offered SCM installation entry.+## Shared layers| Responsibility | Production owner | Boundary |@@ -56,7 +90,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi| --- | --- | --- || Add an API connection and choose its models | [Connection directory](../../apps/desktop/src/features/model-connections/ConnectionDirectory.tsx), [form and draft ownership](../../apps/desktop/src/features/model-connections/README.md), [registered check](../../crates/daemon/src/control/runtime/model_connections/registered.rs) | The executable catalog supplies the complete directory. A source name survives check/save; per-product credentials stay in the dialog and protected input. Released public registered probes may omit the name and use the authenticated option label; the current Desktop check requires an explicit label. || Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs), [Hermes reader](../../crates/integrations/src/agents/hermes_sources.rs) | Shared [point grouping](../../crates/integrations/src/agents/native_points.rs) keeps scope/provider/address/protocol/authentication distinct; static scan never executes helpers |-| Display, prepare and save the selected source | [Safe Desktop projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs), [V2 points/catalog qualification](../../crates/daemon/src/control/runtime/model_connections/points.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Exact native/catalog provenance and explicit model selection remain visible; privileged locators stay private; stale facts cannot expand an accepted selection; legacy one-model handles retain their meaning |+| Display, prepare and save the selected source | [Safe shared product projection](../../crates/product-session/src/commands/model_connection_web.rs), [V2 points/catalog qualification](../../crates/daemon/src/control/runtime/model_connections/points.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Exact native/catalog provenance and explicit model selection remain visible; privileged locators stay private; stale facts cannot expand an accepted selection; legacy one-model handles retain their meaning || Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. || Save Key order or use current Keys with an older plan | [Single-save edits](../../apps/desktop/src/features/models/model-draft.ts), [request admission](../../crates/gateway/src/core_runtime/credentials.rs), [current pool authority](../../crates/local-storage/src/control/compute/management/runtime_pool.rs), [safe Key masks](../../crates/daemon/src/control/runtime/model_connections/key_masks.rs) | A request owns its admitted Key IDs and order; later exact leases enforce current source/Key eligibility and generation. Admission retains closed permission denials in the existing request summary. Shared Plan content stays frozen. Masks are a separate authenticated query; saved plaintext never reaches Desktop. || Connect a native Codex or Claude subscription | [Source discovery](../../crates/integrations/src/agents/subscription_sources.rs), [credential adapters](../../crates/cpa-bridge/src), [shared lifecycle](../../crates/daemon/src/control/runtime/subscriptions.rs), [provider runtimes](../../crates/cpa-bridge/src/runtime_set.rs) | Native clients retain refresh authority; only access leases enter isolated CPA instances. Claude Keychain interaction is limited to an explicit check; discovery reads metadata only. Codex borrowing reads file storage only and rejects a configured non-file store even if stale auth.json remains. |@@ -93,6 +127,8 @@ Follow discovery through an ordinary request using the saved source. The[DSH](../../tools/product-e2e/tests/DSH_INTEGRATION.md) acceptance entries coverScan → Prepare → Save → restart → native use, including stale-source rejection.+The shared product-session layer in `crates/product-session` owns Preview composition, confirmation permits, retry identity and protected-input lifetime. Desktop supplies its inherited-channel `HostAuthority` adapter in `apps/desktop/src-tauri/src/bootstrap/authority.rs`; native startup, updater and window authority stay with the Desktop host.+## State and lifecycle boundaries| Boundary | Invariant | Read next |diff --git a/docs/code-map/decision-foundation.md b/docs/code-map/decision-foundation.mdindex e8ee787a..3d67ca7f 100644--- a/docs/code-map/decision-foundation.md+++ b/docs/code-map/decision-foundation.md@@ -13,7 +13,7 @@ with no current runtime or product entry.| Capability | Production owner | Representative evidence || --- | --- | --- |-| Discover CLI presets, securely connect, edit, test or delete a decision model/custom extension | [CLI journey](../../crates/cli/src/quickstart/decision.rs), [shared presets](../../assets/decision-services/providers.v1.json), [terminal credential input](../../crates/cli/src/protected_prompt.rs), [Connection UI](../../apps/desktop/src/features/decision-services/DecisionServicesPage.tsx), [native transaction](../../apps/desktop/src-tauri/src/session/decision_services.rs), [store](../../crates/local-storage/src/control/decision_services.rs) | [Desktop shell scenarios](../../apps/desktop/tests/v3/browser/product-shell-scenarios.mjs), [real CLI lifecycle](../../crates/daemon/tests/support/decision_services_product.py), [installed secure onboarding](../../crates/daemon/tests/support/quickstart_decision.py) |+| Discover CLI presets, securely connect, edit, test or delete a decision model/custom extension | [CLI journey](../../crates/cli/src/quickstart/decision.rs), [shared presets](../../assets/decision-services/providers.v1.json), [terminal credential input](../../crates/cli/src/protected_prompt.rs), [Connection UI](../../apps/desktop/src/features/decision-services/DecisionServicesPage.tsx), [shared product transaction](../../crates/product-session/src/session/decision_services.rs), [store](../../crates/local-storage/src/control/decision_services.rs) | [Desktop shell scenarios](../../apps/desktop/tests/v3/browser/product-shell-scenarios.mjs), [real CLI lifecycle](../../crates/daemon/tests/support/decision_services_product.py), [installed secure onboarding](../../crates/daemon/tests/support/quickstart_decision.py) || Create a connection while editing a route | [DesktopApp](../../apps/desktop/src/product/DesktopApp.tsx), [selector](../../apps/desktop/src/features/decision-services/DecisionSelector.tsx) | Preserve route edits and select the exact saved revision without implicit publication || Configure categories, degree and competence | [Plan editor](../../apps/desktop/src/plan-editor.tsx), [branch editor](../../apps/desktop/src/features/decision-services/BranchRoutingEditor.tsx), [judgment controls](../../apps/desktop/src/features/decision-services/JudgmentSettings.tsx), [domain](../../crates/domain/src/routing/decision.rs) | Existing model picker, collapsed advanced settings, complete overrides and publish validation || Freeze connection, definition and rubric | [Authoring snapshot](../../crates/daemon/src/control/runtime/plan_content_snapshot.rs), [Application compiler](../../crates/application/src/compiler), [Gateway compiler](../../crates/gateway/src/publication/compiler.rs) | [Decision publication contracts](../../crates/gateway/src/publication/tests/decision_contracts.rs), [real publication/restart](../../crates/daemon/tests/publication_process.rs) |diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex ed3cd653..429957ea 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -10,6 +10,16 @@ Windows development execution is owned by [windows-dev.py](../../scripts/windowsand its [native executor](../../scripts/windows-dev-host.py), reached through`validation.py windows`. HOME configuration owns machine/session/client locations;the project owns artifact admission, exact-case execution and revision-bound evidence.+[Orphaned data preparation](../../scripts/windows-dev-profile.py) preserves complete+backups after explicit user authorization; it does not establish a product scenario.+[Native Desktop session actions](../../scripts/windows-desktop-session.py) admit+the installed NSIS member and collect actual Windows UI Automation/screenshot+evidence. Public CLI readback is distinguished from a UI action, and a cross-build+replacement is distinguished from a newer-version update.+The [Windows uninstall restore plan](../../crates/cli/src/service/restore_plan.rs)+keeps Codex root collaboration separate from its model-profile projection; its+portable unit cases cover owner selection and refusal, while the actual NSIS+uninstall remains the native evidence for restoring Agent files.Choose a user promise, then the layer that can observe its failure. Keep testsbeside that owner and preserve independent assertions. A focused filesystem@@ -54,6 +64,53 @@ not substitute a released `bind(0)` probe. Its protected-input channel cannot beattached to an existing Desktop. Prepare that instance first, then use real UImutations. Main-Agent delegation must separately invoke the actual public CLI.+The [shared product session](../../crates/product-session/src) owns confirmation,+exact-digest authority and command orchestration tests. Its permit-drop and+broker-abort cases verify that cancelled callers can retry, while stale permits+cannot cancel a newer prompt or another context. The+[console composition cases](../../crates/daemon/src/console/tests.rs) exercise the+real role-all dispatcher while preserving the external Local Control Released+gate. [Authentication cases](../../crates/daemon/src/console/auth/tests.rs) cover+launch replay, revocation, hash-only storage and rate limits.+The [listener lifecycle cases](../../crates/daemon/src/console/listener_tests.rs)+verify off/failed minting without binds, actual network origins, the pre-established+shell loopback path and desired configuration pending restart. Unix installer+regressions cover explicit exposure validation, omitted-option preservation and+configuration rollback. Network launch authentication tests cover exact origin/port,+remote local-code refusal, expiry, replay and credential redaction.+The [console transport cases](../../crates/daemon/src/console/transport/tests.rs)+exercise independent peer admission, stalled-write permit release, progressing+responses, bounded idle headers and confirmations on aged keep-alive connections+through the production Hyper connection owner and shared confirmation broker.+Browser scenarios+run through both host transports; their production CSS screenshots include the+console and Windows startup/update pages, without establishing native effects.++The [Rust installation journal](../../crates/host-runtime/src/standalone_install/journal/tests.rs)+covers current-schema interruption recovery. Package tests verify x64 and ARM64+inventories and reject a target/executable mismatch. There is no released Windows+Python producer to preserve. The+[frozen release reader](../../crates/host-runtime/tests/release_catalog_compatibility.rs)+proves that the V2 projection remains consumable by supported macOS Desktop.+Windows shell origin/handoff tests live in+[the shell library](../../apps/shell/src-tauri/src/lib.rs); installed NSIS, WebView,+Task and upgrade effects require the separate+[native acceptance inventory](../../scripts/windows-desktop-cases.json), bound to+the actual standard-user OS, candidate and installer hash.+The [shell transaction regression](../../apps/shell/src-tauri/src/runtime/install_transaction.rs)+uses real Windows file sharing to verify backup handles close before hash admission;+the native installer candidate build runs it before exporting the measured bundle.+The [bounded NSIS journey](../../crates/daemon/tests/windows_desktop.rs) uses the+verified development bundle and configured existing standard session to check+silent defaults, repeat install, console/Gateway readiness and uninstall with+data retained. It verifies the installed shell against the NSIS member image hash+after install, repeat and passive update. Its result does not establish WebView, Agent restore or upgrade+recovery acceptance; see the [execution entry](../validation-routing.md#windows-iteration-and-release-validation).+The [Windows package inspector](../../scripts/package-windows-shell.py) extracts the+actual NSIS shell member with 7-Zip for its SHA-256 and CRT audit. The native case+compares that measurement with installed bytes; the workspace executable is not+the artifact identity source.+Keep borrowed user resources, writable native acceptance configuration, freshproduct storage and per-run materials separate. Each product instance needs aprivate runtime/storage namespace. Worker task submissions recover with the original@@ -141,7 +198,9 @@ requires the reusable native Windows matrix before package builds; PR/main pushedo not start that expensive matrix.The [Windows CI entry](../../scripts/windows-headless-ci.ps1) requires nonemptynative inventories for primitives, shared libraries, installed foreground and-Task/SCM business paths, and fixed upstream clients. The+Task business paths, retained low-level SCM tests, and fixed upstream clients.+The Windows 11 ARM install job builds a native ARM64 package and invokes the Rust+transaction; the other Windows 11 jobs retain their explicit x64 replay boundary. The[canonical native link configuration](../../scripts/build-release.py) also ownsthe Debug checks' static CRT; [captured-source inputs](../../scripts/windows-native-artifacts.py)bind its CMake toolchain, and the [PE import gate](../../scripts/windows-native-runtime-audit.py)diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.mdindex e22b563e..7c4984e1 100644--- a/docs/code-map/worker-context.md+++ b/docs/code-map/worker-context.md@@ -13,7 +13,7 @@ a prerequisite, not a model call, installed Skill invocation or resumable task.| --- | --- | --- || Scan, prepare and import model sources | [Source admission map](architecture.md#model-sources-and-native-configuration), [model connection assembly](../../crates/daemon/src/control/runtime/model_connections.rs) | [Pi acceptance](../../tools/product-e2e/tests/PI_INTEGRATION.md), [DSH acceptance](../../tools/product-e2e/tests/DSH_INTEGRATION.md) || Configure, edit and restore models | [Settings transaction](../../crates/application/src/agent_connection/settings), [typed facts](../../crates/daemon/src/control/runtime/settings_facts), [Desktop Agent feature](../../apps/desktop/src/features/agents/README.md) | [Additional native provider guide](../../crates/integrations/src/agents/additional_native/README.md), [saved-model journey](../../crates/daemon/tests/support/additional_model_product.py), [Windows ordinary Pi/DSH clients](../../crates/daemon/tests/support/windows_user_models.rs), [Windows Qoder official-account journey](../../crates/daemon/tests/support/windows_qoder_user_models.rs) |-| Enable, edit or disable task collaboration independently | [CLI intent workflow](../../crates/cli/src/collaboration.rs), [Skill effects](../../crates/application/src/agent_connection), [local checks](../../apps/desktop/src-tauri/src/agent_check_session.rs) | [CLI workflow regressions](../../crates/cli/src/collaboration/tests.rs), [real main-Agent → public CLI → Worker journey](../../crates/daemon/tests/support/collaboration_product.py) |+| Enable, edit or disable task collaboration independently | [CLI intent workflow](../../crates/cli/src/collaboration.rs), [Skill effects](../../crates/application/src/agent_connection), [shared session checks](../../crates/product-session/src/agent_check_session.rs) | [CLI workflow regressions](../../crates/cli/src/collaboration/tests.rs), [real main-Agent → public CLI → Worker journey](../../crates/daemon/tests/support/collaboration_product.py) |Qoder/Pi/DSH saved models use one owned provider per Plan with an explicitResponses/Messages choice. [Route grants](../../crates/domain/src/agents/model_grant.rs)@@ -45,7 +45,7 @@ the existing local Worker CLI and does not become a Worker executor.| Step / question | Production owner | Boundary to preserve || --- | --- | --- |-| Select and confirm an installation | [Desktop preparation](../../apps/desktop/src-tauri/src/bridge/worker_tasks.rs), [protected confirmation](../../apps/desktop/src-tauri/src/session/worker_dependencies.rs), [launch type](../../crates/domain/src/delegation/installation.rs), [storage](../../crates/local-storage/src/control/worker_dependencies.rs) | Exact canonical components, window-bound single-use confirmation and durable selection; discovery is not authority |+| Select and confirm an installation | [Desktop preparation](../../apps/desktop/src-tauri/src/bridge/worker_tasks.rs), [protected confirmation](../../crates/product-session/src/session/worker_dependencies.rs), [launch type](../../crates/domain/src/delegation/installation.rs), [storage](../../crates/local-storage/src/control/worker_dependencies.rs) | Exact canonical components, window-bound single-use confirmation and durable selection; discovery is not authority || Publish the machine-readable request shape | [Worker producer](../../crates/application-api/src/generated/worker.rs), [Plan producer](../../crates/application-api/src/generated/plan_authoring.rs), [CLI generator](../../crates/cli/src/bin/generate_cli_contract.rs) | Typed producer sources generate [CLI contracts](../../contracts/cli); retain native-only forbidden fields and adapter requirements || Submit and admit work | [CLI submission](../../crates/cli/src/worker.rs), [daemon admission](../../crates/daemon/src/control/runtime/delegation_tasks.rs), [Application](../../crates/application/src/delegation) | Daemon admission owns durable key/intent deduplication; CLI preserves returned locators and uses no local receipt || Resolve resources and construct a run | [Installation](../../crates/daemon/src/delegation/installation.rs), [native context](../../crates/daemon/src/delegation/profile/native_context.rs), [profile guide](../../crates/daemon/src/delegation/profile/README.md) | Effective instance HOME/config root supplies resources; per-run overrides supply route, credential and permission policy |@@ -223,7 +223,7 @@ retain independent execution.| Behavior | Start with || --- | --- |-| Installation confirmation, one-shot authority and exact saved selection | [Native bridge tests](../../apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs), [Desktop scenario map](../../apps/desktop/tests/README.md) |+| Installation confirmation, one-shot authority and exact saved selection | [Shared session tests](../../crates/product-session/src/commands/worker_dependencies_tests.rs), [Desktop scenario map](../../apps/desktop/tests/README.md) || Actual user/project Skills and exact Continue after restart or source replacement | [Native context journey](../../crates/daemon/tests/support/native_context_product.py), ecosystem acceptance guide above || Concurrent routes, cancellation isolation and missing-history rejection | [Shared boundary journey](../../crates/daemon/tests/support/native_context_boundaries.py), [assertion guide](../../crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md) || Native tool summarization and compaction remain on the frozen route | [Compaction journey](../../crates/daemon/tests/support/native_compaction_product.py), [Qoder native leaf](../../crates/daemon/tests/support/qoder_compaction_product.py) |@@ -234,6 +234,6 @@ retain independent execution.Use the [test map](testing.md) and selected ecosystem run guide for inputs, writableroots, required outcomes and cleanup. Shared request changes require the configuredMac `desktop-pilot --all-targets` compile gate; ignored native targets need explicit-execution. Native bridge filters are `bridge::worker_tasks::tests`,-`session::checks::tests` and `bridge::model_connection_web::tests`; zero selected+execution. Shared Product Session filters are `commands::worker_tasks::tests`,+`session::checks::tests` and `commands::model_connection_web::tests`; zero selectedtests prove nothing about those consumers.diff --git a/docs/github-actions-validation.md b/docs/github-actions-validation.mdindex 9dce222e..69157ba4 100644--- a/docs/github-actions-validation.md+++ b/docs/github-actions-validation.md@@ -12,8 +12,8 @@ native Windows acceptance uses `scripts/windows-headless-ci.ps1`.| `gateway-core-dedicated.yml` | Manual or reusable | Hosted Linux production stability and socket churn || `p0-gateway-final-gates.yml` | Manual | Aggregate the three current hosted workflows || `build-release.yml` | Manual, exact dispatch SHA | Builds macOS/Linux candidates independently; only Windows archives require the reusable Windows validation gate; uploads candidate assets and integrity evidence for the existing release publisher |-| `build-release-platform.yml` | Reusable, exact caller SHA | Shared per-target candidate build and evidence upload |-| `windows-compile.yml` | Path-filtered PR | One cached x64 MSVC check of CLI, daemon, platform and local-storage, including their test targets and transitive production libraries; no runtime tests |+| `build-release-platform.yml` | Reusable, or explicit manual x64 Windows build | Shared per-target candidate build and evidence upload; the manual defaults build only an NSIS acceptance input with an `awaiting_runtime` identity |+| `windows-compile.yml` | Path-filtered PR or manual | One cached x64 MSVC check of CLI, daemon, platform, local-storage and the console shell, including test targets and transitive production libraries. The shell compile excludes release payload resources; packaging validates the real payload separately. No runtime tests. || `windows-headless.yml` | Release-candidate call, explicit manual diagnosis | Native MSVC primitives, shared business libraries, foreground control/Gateway and fixed upstream clients; complete background artifacts with explicit deferred Task acceptance; x64 artifact replay on Windows 11 ARM64 |PR and main pushes do not automatically run the Windows matrix. During normal@@ -31,6 +31,13 @@ The reusable release entry accepts no scope input and always runs all five scopeNeither manual mode publishes packages or establishes the separately requireduser/account acceptance.+For installer iteration, manually dispatch **build-release-platform** with its+default x64 Windows target, Windows runner and Desktop option. This uses the same+release builder without starting the other platform or headless assessment jobs.+Its uploaded installer is an acceptance input. The identity remains incomplete+until the required Windows 11 x64 and Server standard-user scenarios pass, and+the release publisher still enforces those artifact-bound results.+Native Windows jobs enable sccache's GitHub Actions backend so compiler objectscan be reused across runs. Cargo targets remain local to each checkout; artifactsource, executable-byte and runtime-import verification still run for every candidate.@@ -49,7 +56,10 @@ binary tests, three ordinary integration-test groups, Gateway E2E, Product smokeremaining doctest/contract/transport gates. Each Cargo test shard keeps the full workspacepackage and all-features context. `ci-shards.py check` compares every non-Desktop Cargointegration target with the explicit shard inventory; a missing, duplicate or same-name-cross-shard target fails selection instead of being silently omitted. The required+cross-shard target fails selection instead of being silently omitted. The frontend job+exports its exact candidate console build; the daemon integration shard downloads those+bytes for the installed Linux package scenario. Backend shards keep their configured+Rust runners and depend on the frontend result without rebuilding it there. The required`backend` status is a small aggregate job, so the public branch-protection contract remainsstable while individual shard jobs can run concurrently.diff --git a/docs/release-builds.md b/docs/release-builds.mdindex 398270e5..c6431525 100644--- a/docs/release-builds.md+++ b/docs/release-builds.md@@ -1,8 +1,9 @@# Release candidate buildsThe candidate entry builds macOS Desktop DMGs (`arm64`, `x86_64`) and Linux or Windows-headless archives (`x86_64`, `aarch64`). Desktop for Windows/Linux is outside this-build entry. A target's package integrity is separate from its required native runtime+headless archives (`x86_64`, `aarch64`) and a separate x64 Windows Desktop NSIS+installer. Windows headless archives are internal installer/test payloads only;+Windows publication consists solely of the x64 NSIS installer. A target's package integrity is separate from its required native runtimeacceptance and does not by itself authorize publishing that target. All components of one release must come from the same clean,committed source revision, with CPA built from `vendor/cpa/source.json` and itschecked patch.@@ -31,6 +32,9 @@ python3 scripts/build-release.py \python3 scripts/build-release.py \--target aarch64-unknown-linux-gnu --cpa-source-repo /path/to/CLIProxyAPI++python scripts/build-release.py --windows-desktop \+ --target x86_64-pc-windows-msvc --cpa-source-repo C:/sources/CLIProxyAPI```The same entry accepts `aarch64-apple-darwin`, `x86_64-unknown-linux-gnu`,@@ -40,7 +44,11 @@ CLI, daemon and CPA. Its builder uses a checkout-local native file lock; it doesimport the Unix workbench lock implementation. The CPA probe retains the actual nativeSystemRoot and uses isolated profile/temp paths. Windows candidates remain`awaiting_runtime` until the installed foreground/background and feature gates pass;-see [Windows operating and evidence boundaries](standalone-windows.md).+see [Windows operating and evidence boundaries](standalone-windows.md). Internal+Windows builds write `internal-payloads/` and `publication: internal-only`, without+an `assets` directory or `website_artifact` row. They cannot be added to a release+catalog: both native and website validators reject Windows standalone entries+and Windows ARM64 packages.The native x64 Windows Release invocation selects static CRT for Rust and itsCMake dependencies and rejects ambient compiler overrides. The complete archive'sthree EXEs are checked for both ordinary and delay imports of Debug CRT or VC@@ -54,6 +62,23 @@ through [package-desktop.py](../scripts/package-desktop.py) as documented in the[macOS installation guide](macos-installation.md); the matrix entry uses nativehosts so its probes execute on the selected architecture.+`--windows-desktop` requires native x64 Windows and adds the shell to the same+static-CRT/image checks. It stages the verified standalone archive, including+console assets, under the shell's ignored resources, builds the pinned Tauri shell,+and bundles NSIS in `currentUser` mode without code signing. The output name is+`HiRoute-VERSION-REV12-windows-x86_64-setup.exe`. This stays separate from the+headless archive jobs. 7-Zip (`7z` or `7zz`) is required to extract and audit the+actual embedded shell image for its SHA-256, architecture and CRT imports. The+read-only `package-windows-shell.py image --installer INSTALLER.exe` entry repeats+that measurement for an existing immutable artifact. Its identity sidecar remains `awaiting_runtime` until the+required Windows 11 x64 and Server standard-user selections pass for that exact+installer. See the [native acceptance boundaries](windows-desktop-installation.md#evidence-and-release-claims).++The single source `apps/website/data/releases.json` uses V3. Website preparation+emits `releases-v3.json` for the Windows shell and a V2 `releases.json` projection+excluding every Windows artifact. Supported released macOS readers reject Windows+artifacts in V2, so that projection is retained in the compatibility register.+Each attempt is retained under `target/release-candidate/SHA/TARGET/ROUND/`.`assets/` contains the DMG or archive plus companion manifest; `result.json`records the full source revision, host, checks, timing, and the measured@@ -66,14 +91,21 @@ container; the HOME is removed afterwards. Logs and package evidence are retaineRun the **build-release-candidates** workflow on the public candidate branch.Unix candidate builds start independently of the reusable **windows-headless**-workflow at the same source commit. All five native scopes and their Windows 11-x64-artifact replay must succeed before Windows package-build jobs can start.+workflow at the same source commit. All five native scopes, their selected Windows 11+x64-artifact replays and the native ARM64 Rust-installation job must succeed before Windows package-build jobs can start.Both groups use **build-release-platform** for the same per-target build steps. This expensive Windows matrixdoes not run automatically on PR or main pushes; ordinary iteration uses the[cross-compilation and development-machine path](validation-routing.md#windows-iteration-and-release-validation).Hosted background compile-only cases and real accounts retain their separateruntime gates; the CI dependency does not establish those results.+To prepare only an x64 NSIS installer for development-machine acceptance, dispatch+**build-release-platform** on the exact candidate branch with its default x64+Windows target, Windows runner and `windows_desktop: true` option. It uploads+the installer and build evidence, and leaves the identity `awaiting_runtime`.+It performs no publication and does not replace the required native acceptance+or the release-candidate matrix.+Every package matrix job checks out the dispatch's exact `github.sha`, uses a nativerunner and uploads its own assets and evidence. Ubuntu runner labels select onlythe native Docker host. Both Linux architectures build against Debian 11 / glibc@@ -157,10 +189,11 @@ API-key model call on the intended deployment host, using the same frozen archivthat live result is separate from the offline build gate. Rebuild after integratingproduct fixes and retain each result at its actual source revision.-1. Require the Windows validation gate and all six package matrix jobs to succeed+1. Require the Windows validation gate and every selected package job to succeedfor the same SHA. Keep the exact sourcecommit available; internal master and an exported public commit may differ.-2. Download each job's `assets/` and `result.json`. Use the measured+2. Download public package jobs' `assets/` and `result.json`. Keep Windows+ headless `internal-payloads/` out of the release. Use the measured`website_artifact` rows in a new release record in`apps/website/data/releases.json`, with the intended version/channel/date/notes.Preserve historical records and regenerate website content twice, checking@@ -170,6 +203,9 @@ product fixes and retain each result at its actual source revision.The existing [publish-release workflow](../.github/workflows/release.yml)verifies tag/package identity and digests, then publishes OSS/site links andproposes the [release contract snapshot](release-contracts.md).+ Windows Desktop also attaches its `INSTALLER.exe.identity.json`; publication+ verifies the installer digest, source revision and complete native case evidence.+ An incomplete or misbound sidecar cannot publish a Windows Desktop artifact.The build workflow only stores Actions artifacts. It does not publish a GitHubRelease, alter the stable catalog, or replace any immutable distribution object.diff --git a/docs/standalone-cli.md b/docs/standalone-cli.mdindex d9a72e0b..b0afc6fa 100644--- a/docs/standalone-cli.md+++ b/docs/standalone-cli.md@@ -7,13 +7,22 @@ CLI, role-all `hirouted` daemon, Local Control, Gateway, business storage, and oform one control and execution loop. It uses the local control socket's OS access permissions, needs nosecond “CLI management token,” and exposes no second Agent-management API.-Standalone and HiRoute Desktop must not manage the same user installation at the same time. It does not-provide a system-wide multi-user install, a Windows installer, runtime downloads, or automatic-updates. macOS can use the same candidate-package mechanism, but this page and the Quickstart-are validated for Linux.+Linux standalone and macOS HiRoute Desktop must not manage the same user installation+at the same time. The Linux package provides neither a system-wide multi-user install+nor runtime downloads or automatic updates. Windows has a separate+[current-user Desktop installer](windows-desktop-installation.md) that shares its+headless installation. macOS can use the same candidate-package mechanism, but this+page and the Quickstart are validated for Linux.## Installation+The installed daemon also provides the [Web console](web-console.md). It defaults+to off on Linux. Configure its scope and port with installer options or+`hiroute console init`, then start/restart the service. `hiroute console open`+returns a one-use URL for the actual local or remote listener without starting+listening. Remote HTTP also accepts owner-created CLI access tokens and displays+plaintext warnings. It does not change the Gateway listener.+Install the latest stable Linux package for `x86_64` or ARM64 (`aarch64`) from[hiroute.ai](https://hiroute.ai/en/download/):@@ -47,6 +56,7 @@ python3 scripts/package-standalone.py build \--cpa-version PINNED_VERSION \--cpa-license /absolute/path/CLIProxyAPI-LICENSE \--notices /absolute/output/notices \+ --console-assets /absolute/path/apps/desktop/dist \--output /absolute/outputpython3 scripts/install-standalone.py install \diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.mdindex 36b58608..3e0c0d39 100644--- a/docs/standalone-cli.zh-CN.md+++ b/docs/standalone-cli.zh-CN.md@@ -11,6 +11,11 @@ Standalone 与 HiRoute Desktop 不应同时管理同一用户的安装,不提## 安装+安装的 daemon 同时提供 [Web 控制台](web-console.md)。Linux 默认关闭;可在安装时通过+`--console-mode`、`--console-listen`、`--console-port` 配置,或安装后运行+`hiroute console init`,再启动/重启服务。`hiroute console open` 只为实际已监听的+本地或远程端点生成一次性登录 URL,不会启动监听。远程 HTTP 会持续提示明文传输风险。+从 [hiroute.ai](https://hiroute.ai/download/) 安装适用于 `x86_64` 或 ARM64(`aarch64`)的最新稳定 Linux 版本:diff --git a/docs/standalone-windows.md b/docs/standalone-windows.mdindex b2e8415f..1f8d9478 100644--- a/docs/standalone-windows.md+++ b/docs/standalone-windows.md@@ -1,182 +1,114 @@-# Windows headless HiRoute+# HiRoute on Windows-Windows standalone uses the same `hiroute.exe`, role-all `hirouted.exe`, Application,-Gateway, business stores and observations as the other headless hosts. It does not-require Desktop or WSL. This page describes the implementation candidate; a release-claim requires the native acceptance gates below to pass at the published revision.+The Windows x64 Desktop installer is the only supported Windows installation+path in this release. It includes the CLI, daemon, CPA, Skills, Web console and+Desktop shell. A standard user needs neither Python, WSL nor administrator rights.+Users who only need the CLI and daemon install the same package and can quit the+shell afterwards; the background service keeps running.-## Install a verified candidate+## Install-Use native Windows Python 3 and a distributor-provided archive and companion manifest-from one exact source revision. The installer checks the archive size and SHA-256,-closed file inventory, every file digest and the architecture of all three executable-images before changing an installation. Do not infer an unpublished download URL.+Download `HiRoute-<version>-<rev12>-windows-x86_64-setup.exe` from the+[download page](https://hiroute.ai/en/download/) when a validated release is+available. Follow the [Windows Desktop guide](windows-desktop-installation.md)+for SHA-256 verification and the unsigned publisher/SmartScreen prompt.-```powershell-python scripts/install-standalone-windows.py install `- --manifest C:\packages\PACKAGE.tar.gz.json --archive C:\packages\PACKAGE.tar.gz-```--The default manager is Task Scheduler. The ordinary user installs and starts it without-administrator privileges. `hiroute.exe` and `hirouted.exe` have stable hardlink entry-points under the actual profile's `.local\bin`; versioned binaries live under-`.local\lib\hiroute`. Add the stable directory to the user PATH, or invoke the full path.-User PATH changes are not required for daemon-managed executable discovery.--The native Profile and LocalAppData KnownFolders select the installation and runtime.-Environment variables named HOME or XDG do not redirect an installed Windows service.-An installation maintenance journal blocks daemon admission until file publication and-the actual manager registration agree. Retained prepared journals require repair or-completion; a successful file copy is not a completed installation.+Run the installer in your ordinary logged-on account. Login start and tray+residency are enabled by default and can be deselected independently. The shell+opens after the service is ready. The installer adds the fixed user CLI directory+to PATH; open a new terminal afterwards:```powershell-hiroute service start --output json-hiroute service status --output jsonhiroute system status --output json-hiroute gateway show --output json-hiroute service autostart enable --output json-hiroute service stop --output json+hiroute service status --output json+hiroute console open```-Starting, stopping, restarting, logs and doctor use the same CLI family. Business-readiness requires Local Control to answer and the actual Gateway listener to be ready.-Task registration or a successful process-manager call alone cannot establish readiness.-The verified Task action supervises a separate business process under the same user.-It waits for the complete child Job to stop and retries an unexpected exit up to three-times, with a one-minute interval. A normal runtime stop ends the action; stopping the-owned Task also stops its child tree and cancels a pending retry. Scheduler failure-settings remain useful for action-launch failures, but do not establish runtime recovery.-Foreground operation remains available through `hiroute service run`.-`service logs` returns at most the last 256 KiB of `daemon/current.jsonl` and-`daemon/previous-1.jsonl`. It reads existing diagnostic objects through held directory-handles and refuses reparse points and multiply linked log files; settings, correlation-keys and unrelated files are not log content.--## Background manager policy--| Manager | Identity and permissions | Lifetime |-| --- | --- | --- |-| Task Scheduler, default | Current user's SID, InteractiveToken, least privilege | Survives terminal exit; demand start and login autostart are separate. Requires that user's interactive session; logout ends this mode |-| Windows service, optional | Authenticated owner account; administrator registers a sealed service host; business child has the same SID, medium integrity, disabled administrative group and reduced privileges | Runs in service session zero, including without an interactive login; manual and automatic SCM startup are separate |--For a standard user who needs a service, prepare the installation as the owner:+For an unattended installation, verify the installer first, then run the same+package with `/S`. This uses the default choices without prompts. The process+exit code reports failure; a successful install starts a healthy service.```powershell-python scripts/install-standalone-windows.py install `- --manifest C:\packages\PACKAGE.tar.gz.json --archive C:\packages\PACKAGE.tar.gz `- --manager scm --external-manager+$process = Start-Process -FilePath .\YOUR-INSTALLER.exe -ArgumentList '/S' -Wait -PassThru+$process.ExitCode```-The result is `pending_admin`. In an elevated administrator session, use a CLI obtained-and verified independently by that administrator:--```powershell-python scripts/install-standalone-windows.py admin-scm `- --cli C:\admin-verified-package\bin\hiroute.exe `- --account COMPUTER\owner --operation install-```+The NSIS installer only supports native x64 hosts and refuses other architectures+before product writes. Windows headless archives for x64 and ARM64 are internal+build/test payloads, not downloads or a separate supported installation path.-The installer prompts for that owner's password; automation may use `--password-stdin`.-Use the qualified local or domain account and its Windows password. A Windows Hello-PIN is not a LogonUser password. The default Task mode needs no account password.-Passwords do not belong in command arguments, environment variables, task XML or files.-Never elevate the CLI from a standard user's writable installation directory. Keep the-administrator's verified `hirouted.exe` beside that CLI: the sealed host must come from-that trusted package and match the candidate installed by the owner.-The helper authenticates through LogonUser, derives the SID from the returned token,-loads the profile, reads the owner's private marker and held image while impersonating-the owner, and leaves impersonation before changing machine service state.+## Service and console-Return to the ordinary owner's session to finalize, using the prepared versioned CLI:+Task Scheduler runs the service as the current logged-on user with an+InteractiveToken and least privilege. Ordinary start and stop require no account+password or elevation. Closing the launching terminal does not stop it; logging+off ends its session. Starting now and starting at login are separate controls:```powershell-python scripts/install-standalone-windows.py finalize `- --cli C:\Users\owner\.local\lib\hiroute\VERSION\hiroute.exe+hiroute service start --output json+hiroute service stop --output json+hiroute service autostart enable --output json+hiroute service autostart disable --output json+hiroute service doctor --output json+hiroute service logs --output json```-Finalization verifies the actual SCM account, binary path, sealed host and descriptor-before committing the private installation definition. Upgrades use the same prepared-transaction. Uninstall prepares as the owner, uses administrator `admin-scm --operation-uninstall`, then finalizes as the owner only after SCM removal is confirmed. A pending-service deletion retains the journal instead of reporting completion.--The SCM host runs from an administrator-protected ProgramFiles directory. It executes-the verified owner image only in its restricted business child; it never interprets a-user-selected executable path while privileged. Service-account profile loading is an-[SCM responsibility](https://learn.microsoft.com/en-us/windows/win32/services/service-user-accounts);-the separate authenticated helper explicitly follows-[LoadUserProfile requirements](https://learn.microsoft.com/en-us/windows/win32/shell/local-user-profiles).--## Native boundaries and feature coverage--Application behavior, routing, model/plan management, subscription login, observations,-configuration transactions and Worker workflows retain their existing owners. Windows-adapters supply the OS mechanisms those owners require:--- Private named pipes carry Control, protected input, lifecycle and grants. Account SID,- held runtime-directory identity and kernel peer identity bind the endpoint. Remote- clients and occupied endpoints are rejected; bounded records replace Unix half-close.-- Job Objects contain daemon, CPA, native Agent and tool process trees. Membership and- explicit inherited handles are assigned during creation. A leader exit does not mean- surviving descendants are stopped; cancellation waits for the Job to become empty.-- Business processes set new-object owner/default ACL to their actual user SID before- third-party code runs. This covers Go auth files and SQLite sidecars without changing- the parent shell token. CPA-generated inherited private files have a narrow reader;- protected HiRoute files and borrowed native-client credentials keep separate rules.-- Reparse-free, handle-relative file operations bind reads, creation, rename, diagnostics- and cleanup to held objects. Private new objects receive their ACL at creation.- Existing accessible native configurations retain their ACLs during discovery.-- Windows configuration fingerprints include actual owner/DACL/read-only facts. Windows- V5 artifact markers authenticate these facts in backup AAD and restore them conditionally.- Unix V4 fingerprints and registered V2/V3 recovery adapters retain their released bytes.-- Executable discovery resolves native PE binaries and declared Node entry points. Shell- metacharacters in user paths/arguments cannot be turned into a managed shell command.- Codex, Claude Code, Qoder, Pi and DSH retain separate native adapters and capability probes.--Protected CLI carriers use pointer-width inherited handles on Windows:-`--capability-handle`, setup `--spec-handle`, and protected-input `--secret-handle`.-These accept private, non-stdio pipes with explicit inheritance and bounded bytes/EOF;-they do not accept credential text, a pathname or an arbitrary numeric PID as authority.-Unix descriptor flags keep their existing behavior. JSON request files/stdin remain-ordinary bounded request sources and cannot grant authority.--## CI and ongoing maintenance--Native CI binds each report to the full product SHA, validation SHA, runner image,-Windows version, CPU architecture, toolchain and selected cases. Missing or zero-selected-required cases fail. Build checks, fixture tests and production business acceptance are-separate evidence. Windows Server results establish those server runs; Windows 11 and-each promised executable architecture require their own recorded native runs.--Required gates cover pipe identity/deadlines, junction and hardlink refusal, native ACL-restore/authentication, complete file publication, process-tree cancellation, literal-argv, diagnostics rotation, actual installed foreground Control/Gateway/input/restart,-Logged-on Task lifecycle, installation upgrade/recovery,-and the five native Agent adapters. Subscription/provider tests use controlled endpoints;-actual account login/refresh and upstream native clients require their own authorized-acceptance evidence and pinned version records.--Native Agent CI installs the committed `tools/windows-agent-fixtures` dependency lock.-Pi 1.0.2's SDK requires pi-codemode 1.0.2; the fixture overrides only that transitive-dependency because 1.2.0 removed an export still imported by this SDK. The selected-CLI's actual SDK must pass capability admission. A working bundled CLI or a substituted-SDK fixture cannot establish Worker, Continue or native tool support.--The installed business journey covers fixed, smart-saving and custom plans,-decision revisions, model ratings, Gateway receipts and observation after restart.-Background login tests use the actual packaged CPA to check official authorization-URLs, PKCE, cancellation and expiry after restart. Completing provider authorization,-refresh and paid or free provider inference needs a real authorized account.-Qoder's fixed ACP client also requires its own official login; custom model settings-do not establish that login. Supplying a PAT in the child environment does not create-the persistent profile used by a separately isolated Worker. Its lifecycle, tools-and Main-agent account recipes form the explicitly selected `accounts` scope, bound-to an officially prepared private profile. Missing profile prerequisites fail that-scope. These account gates remain separate from native OS and account-free business-acceptance and must pass before claiming full upstream-account acceptance.--Future features use the shared business owner and extend the affected platform adapter-and native gate together. CI catches deterministic OS and contract regressions without-a personal Windows computer. Fresh runner profiles do not represent every enterprise-policy, antivirus product or upgrade history; any field failure needs a retained,-reproducible fixture before it becomes an ongoing regression gate.+The Task and Desktop use the same instance, data and Gateway. The shell's login+preference manages both the Task and its own login entry. The authenticated+[Web console](web-console.md) can also be opened in a browser.++SCM service installation is not offered. Installation, update and uninstall refuse+an existing SCM-managed installation before modifying it and explain the refusal.++## Ownership, updates and removal++Windows KnownFolders determine the actual account Profile and LocalAppData;+HOME and XDG variables cannot redirect an installed instance. Shell program files+live in `%LOCALAPPDATA%\Programs\HiRoute`. Standalone state lives separately in+`%LOCALAPPDATA%\HiRoute\cli`; versioned CLI/daemon/CPA files and shared data remain+under the user's `.local` directories. The install directory never contains or+sits inside the standalone state directory.++The Rust installation transaction verifies the complete inventory, revision,+digests and executable architecture before publishing stable entries. The package+target must match the native host. An existing unreleased Task installation is+adopted only when its layout and journal match the current schema; incompatible+or changed material requires repair/reinstallation and is preserved for diagnosis.+There are no released Windows Python-installer or ARM64 installations to migrate.++Updates from Settings or a manually downloaded newer installer use the same+journaled transaction. Active calls and accepted Worker tasks drain before stop;+cancelling resumes admission without killing or replaying work. Rerun the+installer after interruption. A prepared `hiroute.windows-install-journal/v1`+blocks business startup until files, record and actual Task registration agree.++Use **Installed apps → HiRoute → Uninstall**. HiRoute first restores managed Agent+access through its existing restore flow. Conflicts stop removal and list the+Agents that need a decision. Uninstall removes owned program files, Task, shell+login entry and the CLI PATH entry it added. Data is preserved by default. Explicit+data removal affects only standalone data/state, never Agent files or projects.++If the service is unavailable, the interactive installer or uninstaller can offer+an explicit, default-No choice to continue without verified Agent restoration.+Configured Agents may need manual repair and stopping the owned Task may interrupt+work. Continuing retains all data; unattended mode refuses this exception. An+enumerated restoration conflict still stops removal. A first-install rollback+with no Agent storage does not require a running service.++After a successful upgrade, obsolete verified version directories are removed+once shell rollback no longer needs them. Uninstall removes the current verified+version too. Changed or foreign entries are preserved for repair.++## Native evidence++[Validation routing](validation-routing.md#windows-iteration-and-release-validation)+owns native execution. Record the actual source SHA, artifact hashes, OS/build,+processor and account/session. Windows Server x64, Windows 11 x64 and native ARM64+are separate evidence. The Windows 11 ARM CI installation case uses an ARM64+package through `__windows-install` / `__windows-uninstall`; internal test payloads+do not establish a released ARM64 Desktop. Retained SCM kernel/daemon/CLI code and+low-level tests do not establish a supported SCM installation flow.++Real native clients and provider authorization require their own execution.+Fixtures, compilation, manager registration and action launch cannot prove a+healthy Gateway, installation, upgrade or real model call.diff --git a/docs/validation-routing.md b/docs/validation-routing.mdindex 4d9e1b3b..2729d60e 100644--- a/docs/validation-routing.md+++ b/docs/validation-routing.md@@ -131,6 +131,9 @@ modules. `doctor` reports the actual OS and existing sessions; select the intendsession in HOME rather than silently falling back to SSH service context. Anadministrator session is not standard-user evidence. The configured account mustbe able to read the bundles and register a task for its existing login session.+Use a separate workbench `root` for each native account. Its private evidence+directory must grant that account inheritable access; the runner rejects an+inaccessible directory before creating a Task and preserves its existing ACL.```shpython3 scripts/validation.py windows doctor@@ -138,6 +141,7 @@ python3 scripts/validation.py windows doctorpython3 scripts/validation.py windows bundle --result /path/to/run/result.json \--log /path/to/run/command.log --output /path/to/development-bundle.zippython3 scripts/validation.py windows stage /path/to/development-bundle.zip+python3 scripts/validation.py windows inspect-installation --product PRODUCT_BUNDLE_IDpython3 scripts/validation.py windows run --harness HARNESS_BUNDLE_ID \--product PRODUCT_BUNDLE_ID --binary windows_headless.exe \--case actual_windows_complete_public_headless_business --ignored@@ -147,6 +151,97 @@ python3 scripts/validation.py windows collect RUN_ID --output artifacts/windows-python3 scripts/validation.py windows finish RUN_ID```+For an installed NSIS candidate, `windows desktop-session --product BUNDLE_ID+--action launch` opens the measured installed shell in that same session.+`--action snapshot` collects its native Windows UI Automation tree and a window+screenshot. `invoke`/`text` require an exact Runtime ID from a recent successful+`--observation-run`; changed processes, elements and image digests are refused.+Use the observed UI for product actions; this entry does not inject page scripts+or replace the WebView with HTTP assertions. `close` uses the native window-close+pattern. Collect and finish each bounded operation before the next one.+Desktop operations use the configured Python runtime's `pythonw.exe` sibling and+hidden console children so the observer cannot obscure the product window. A+native accessibility hit test supplements incomplete WebView fragment traversal.+If needed, `click` requires coordinates from a recent screenshot of that exact+foreground window; it refuses changed geometry. `native-files` captures a bounded,+read-only Codex/Claude configuration and collaboration Skill inventory for restore+comparisons, including absence before a product-created file.+`quit` uses the visible HiRoute notification icon and the measured process's+native Quit menu item, then requires that process to exit. It does not kill a+process or stop the background service; an unavailable or ambiguous icon/menu+is an observation failure that must be inspected before retrying.++`--action install` runs the measured NSIS `/S` entry. For a different installed+candidate, `--from-product OLD_BUNDLE_ID` verifies the old images before invoking+the new installer. Preserve existing data and identify both packages in the+result. Different source revisions carrying the same semantic version prove a+cross-build replacement, not a newer-version catalog selection or N-to-N+1 update.+`--action cli --cli-args PRIVATE_JSON_FILE` executes a bounded argument array+through the installed public CLI for preparation and effect readback; it does+not establish a UI action. The selected standard account must have no+Administrators SID, including deny-only membership. All native observations and+screenshots remain in ignored, private evidence.+`native-files` captures the fixed Codex/Claude configuration files and inventories+both collaboration and management Skill directories for restoration readback.+`scroll` uses a recent screenshot's window geometry and pointer coordinates, plus+an explicit `--scroll-direction up|down`; it sends a bounded native mouse wheel+event to that foreground window. `codex-call` runs the configured real Codex CLI+with a fixed `Get-Location` tool prompt, a read-only sandbox and no approvals. It+requires saved configuration selecting the local HiRoute Gateway and rejects+authentication/routing environment overrides. Use `--codex-profile hiroute` for+the product-owned standalone `hiroute.config.toml`, or omit it for the default+`config.toml`. The native inventory records both files independently; root config+preservation is expected when using the standalone profile. This optional+scenario needs Python 3.11+ and verifies the completed tool output and nonce-bearing+answer; the completed command must be `Get-Location` and report the actual run+directory. Process exit alone is insufficient. Preserve its actual client image hash,+product revision and native output. It does not alter sandbox configuration or+substitute a model fixture for a real upstream.+`codex-inference` is a separate pure model-call scenario using the same saved+configuration, client identity and sandbox. It requests no tools and requires a+completed turn with the exact per-run answer. It establishes no native tool+execution and cannot replace or waive a failed `codex-call` result.+The runner records the actual client version before the call and preserves partial+stdout/stderr when its bounded wait expires. Such a timeout is a failed attempt,+not an inference verdict. The bounded public-CLI action also accepts `sessions`+for product receipt readback; protected content still uses the product's authority.+For a connection failure, `network-probe --source-id SOURCE` resolves one ready+saved HTTPS source through the installed CLI and performs a bounded, verified TLS+handshake in the same account. It sends no HTTP request or credentials, changes no+trust settings, and records the certificate-store count, TLS result and error.+This is diagnostics only; it cannot establish a product model call.+`--native-tls` compares Windows `SslStream` verification under the existing system+trust policy. Normal Windows certificate-chain caching may occur; the probe does+not import a trust anchor or override verification.+For a failed NSIS attempt with a prepared shell transaction, `installer-resume`+captures the actual post-install adapter's output. It requires the matching+recent inspection in `--observation-run`, the exact retained `--from-product`,+the measured replacement shell/CLI/daemon and no running shell. It resumes the+normal Rust installation entry with the captured login/tray defaults; it does+not force a stop or bypass restoration. This mutates the prepared installation+and is diagnostic evidence, never a successful full NSIS result. Inspect its+output and resulting transaction before any further installation attempt.+If that failed unreleased producer never registered its generated uninstaller,+manual `installer-quarantine` can preserve that one file in the run's evidence.+It requires the same inspection/prior-product admission and an independently+extracted digest from the verified failed NSIS artifact in+`--generated-uninstaller-sha256`. A changed file, missing verified old backup or+already registered replacement is refused. This changes no journal or business+data and is manual preparation, not a compatibility reader or an installation+result; the Rust transaction still owns all restoration and installation.+To test a normal NSIS retry over that prepared replacement, `install` accepts+`--recover-product INTERRUPTED_BUNDLE` with `--from-product RETAINED_BUNDLE` and+the recent matching `--observation-run`. It verifies both retained and interrupted+product images before launching the new installer. Recovery itself remains the+normal NSIS/Rust path; this admission does not repair files or journals.+Before native input, the runner checks that the existing session's input desktop+is accessible and matches its ordinary desktop. `--action desktop-state` reads+that prerequisite without unlocking or creating a login. UI observations require+the measured window to be foreground and use only its visible native controls.+Content-addressed validator helpers are verified and published once by atomic+rename. Wait/status/collection never overwrite helper files that a running+standard-user task may be importing.+Stage separate product and harness bundles when reusing an unchanged product fora test-only repair. Results record both full revisions, binary hashes, driver hash,client hashes, actual OS/session/elevation and exactly one test outcome. Zero exit@@ -154,6 +249,55 @@ without the selected passing case is failure. Archive entries must be flat,manifested x64 executables with matching size/hash; partial stages cannot be reused.Cross-built artifacts never become native CI producers.+`inspect-installation` runs a read-only inventory in the configured account. Collect+and finish it normally; its success is inspection evidence, not a product scenario.+When the user explicitly authorizes clearing old validation data, use+`windows archive-installation-data INSPECTION_RUN_ID --product PRODUCT_BUNDLE_ID`.+It requires a recent matching standard-account inspection, no installed product,+no product processes/tasks and no native Agent references to the old data. It moves+only the three fixed HiRoute data, CLI state and shell state directories into private run evidence, with+complete before/after hashes; native settings remain unchanged. Installed products+must use their normal uninstall entry first. For the exact measured candidate,+`windows uninstall-candidate INSPECTION_RUN_ID --product PRODUCT_BUNDLE_ID+--shell-sha256 MEASURED_SHELL_SHA` invokes its actual NSIS `/S` entry, preserving+data. It pins the installed CLI/daemon, shell and uninstaller inventory, rejects+other active work, and waits for the owned installation to disappear. It cannot+force an unavailable restore or remove business data. It copies the verified+uninstaller outside the program directory and uses NSIS's final `_?=` argument+to observe the actual uninstall process and exit code instead of its detached+launcher. `--adapter-diagnostic` is a separate **mutating** diagnostic: it runs a+verified shell copy's existing uninstall adapter and retains its typed result;+it does not run the rest of NSIS or establish complete uninstall success.+Read-only probing remains `--probe-only` and cannot be combined with that option.+These operations create no account. A preparation record alone establishes no+upgrade, Agent restoration or migration acceptance; business acceptance also+requires actual before/after Agent files, Operation/status and package identity.++For the NSIS candidate, manually dispatch `build-release-platform.yml` with its+default x64 Windows/Desktop options. Its `artifacts/windows-desktop` upload+contains a `development-bundle.zip` made from the measured installer, final shell image hash, embedded+product binaries and exact compiled installer test. The explicitly declared NSIS+entry has an x86 bootstrap stub; ordinary product and test images remain x64.+Stage this bundle with the same `windows stage` entry, then select:++```sh+python3 scripts/validation.py windows run --harness BUNDLE_ID --product BUNDLE_ID \+ --binary windows_desktop.exe \+ --case actual_nsis_silent_install_repeat_console_and_uninstall_preserve_data --ignored+```++This bounded case requires a fresh profile in the configured existing standard+session, including an absent or empty versioned-package base. Retained payloads+are refused before installer invocation so backlog cleanup cannot consume the+bounded fresh-install scenario. It rejects even deny-only Administrators membership, and uses the actual+NSIS `/S` entry for installation, repeat installation and uninstall. It verifies+default login/tray choices, production Control/Gateway and packaged console+readiness, and data preservation. Its result explicitly leaves WebView interaction,+Agent restoration and update recovery unassessed. Preserved standalone data stays+in that test profile after uninstall; `finish` does not remove it. The complete+[Windows Desktop inventory](../scripts/windows-desktop-cases.json) retains its+separate native obligations and artifact-bound release gate.+Execution uses a one-off `Interactive`/`Limited` Task, with no startup trigger orsaved password. One workbench lock prevents overlapping product mutation. Productprofile and request deadlines remain intact; `run --timeout` is only a whole-test@@ -195,6 +339,9 @@ Transport uses SSH host-key verification, hashed uploaded scripts/JSON and encodPowerShell invocation. Interrupted submission is an unknown outcome: inspect itsrun/task/lock before retrying. Missing Python, clients, login session or accountaccess is a prerequisite gap, not permission to substitute a different identity.+Large bootstrap scripts use a bounded encoded bridge with source passed through+stdin, so publishing a new helper cannot exceed the Windows SSH shell's command+length limit. Helper hash checks and atomic publication still apply.#### Compilation and release boundary@@ -206,6 +353,10 @@ retains an explicit manual entry for diagnosis. PR and main pushes retain theirordinary Linux/frontend selection without automatically starting that matrix.Affected PRs also run one cached Windows headless compile check; it runs nobusiness or account acceptance.+That job also runs only the filtered package/journal/restoration-policy component+fixtures from `hiroute-host-runtime`. It records OS/build, architecture and token+elevation; fixture success never satisfies native installation or standard-user+acceptance. The full native matrix remains release/manual-only.1. Record the comparison base, committed candidate, affected consumers and nativecases from `test-plan.py --integration`. Run affected Linux tests as selected;@@ -376,6 +527,13 @@ explicit rollback path and is never run automatically after a DAG failure. Otherselectors, profiles and filters use the ordinary runner. A bridge over the oldthree-slot locks keeps legacy and eight-slot workers mutually exclusive.+The installed Linux package scenario requires the same candidate's production frontend+at `apps/desktop/dist`. Build it through the configured frontend target, then stage those+bytes into the inactive managed backend checkout under its checkout lease before running+`installed_standalone_cli_completes_the_headless_management_loop`. Do not replace them with+a dummy page or install a second frontend toolchain on the backend. Hosted full CI uses+its frontend artifact handoff for this prerequisite.+## Pilot from either development machine### Reuse one build across scenariosdiff --git a/docs/web-console.md b/docs/web-console.mdnew file mode 100644index 00000000..d8dab04e--- /dev/null+++ b/docs/web-console.md@@ -0,0 +1,146 @@+# HiRoute Web console++The console is served by the installed role-all `hirouted`. It uses the shared+product session and the same Application transactions as Desktop. The Gateway,+Local Control and ordinary CLI remain available independently of console assets,+listener or authentication failures. Browser pages do not connect directly to Local+Control. The external Local Control Released-command gate remains unchanged.++## Configure during installation or initialization++A fresh unattended Linux installation keeps the console off. Choose its scope and+port explicitly when installing a complete package containing `console/`:++```sh+curl -fsSL https://hiroute.ai/install.sh | sh -s -- --console-mode loopback --console-port 5838+```++After installation, the equivalent initialization is:++```sh+hiroute console init --mode loopback --port 5838+hiroute service start --output json+hiroute console open+```++Open the printed single-use URL on the service host. `console open --browser` also+asks that host's default browser to open it. Initialization only saves settings;+service startup establishes the listener. `open` never starts a daemon or listener.+If it is off or failed to bind, inspect `console status`, configure it and restart+the service. Changes saved while running take effect at the next service start;+`open` continues returning the actual live address until then.++Omit `--port` for automatic selection: prefer 5838, then another free port. An+occupied explicit port fails without falling back. `console enable` also saves a+configuration, and `console disable` saves off for the next start. Upgrading with+no console installation options preserves existing settings byte for byte.++## Access from another device++Configure the service host's network IP and port before starting it:++```sh+hiroute console init --mode network --listen 192.0.2.10 --port 5838 --allow-plaintext-network+hiroute service restart --output json+hiroute console open+```++Replace the documentation address with the service host's actual reachable IP.+The printed URL now targets that **live network listener**. Open it on your own+computer; no desktop or browser is needed on the server. Its launch code expires+after two minutes and can be exchanged once, only at that origin and actual port.+The page removes the code from the URL before exchange. A local-only launch code+cannot be redeemed remotely. Do not share or log either kind of link.++For a wildcard bind, also configure the concrete IP to advertise in the URL:++```sh+hiroute console init --mode network --listen 0.0.0.0 --advertise-address 192.0.2.10 --port 5838 --allow-plaintext-network+```++The install-time equivalents are `--console-mode`, `--console-listen`,+`--console-advertise-address`, `--console-port` and `--allow-plaintext-network`.+They persist settings without starting the service. The advertised address must+have the bind address's IP family. DNS names and wildcard login URLs are not used.+Network reachability still depends on the host's routing and firewall.++An owner on the service host can run `hiroute console open --loopback-only` to use+its already-bound local recovery endpoint while network mode remains configured.+This selects a local one-use URL and preserves the separate local sign-in budget;+it does not create a listener or change the network configuration.++For repeated logins, an owner can alternatively create a named access token:++```sh+hiroute console token create --name workstation --expires 7 --output json+hiroute console token list --output json+hiroute console token revoke TOKEN_ID --output json+```++Open the console's network URL without a code and enter the token. There is no+username/password login. Token secrets are shown only at creation; the service+stores hashes. Revoking a token ends its derived sessions immediately. A daemon+restart ends every browser session and outstanding launch code. Collaboration or+Skill-authorized callers cannot mint launch codes or tokens.++Remote HTTP is unencrypted. The page warns before token entry, keeps a visible+plaintext banner after login (including login by link), and warns on secret-entry+forms while allowing authorized entry. Continue only on a trusted network; the+product does not require TLS or a password unlock.++An SSH tunnel is an alternative. Initialize loopback mode and forward the same+port printed by `console open` (5838 below):++```sh+ssh -N -L 5838:127.0.0.1:5838 user@service-host+```++Use the fresh local launch URL through that tunnel. Its browser Host and port+must match; if the local port is busy, configure a different server port and use+the same port for forwarding before obtaining a fresh link.++## Sessions and confirmations++The session bearer is stored in `sessionStorage` and sent as a Bearer header.+Cookies and persistent browser storage do not carry authentication. Each tab has+its own product context. Several clients can operate concurrently; a stale edit+shows a revision conflict, refreshes actual facts and retains the unsubmitted+draft. It does not automatically merge or replay the mutation.++Up to 16 sessions stay active. A successful new login at capacity ends the least+recently used session; closing a tab alone does not sign it out. Sessions expire+after 12 hours idle or seven days total. Failed logins are limited per address+and globally, with independent loopback and network budgets.++An authenticated console session has the same protected-operation authority as+macOS Desktop. Every protected operation still presents its page confirmation and+registers authority for the exact digest. There is no password or unlock step.+Protected uses and credential lifecycle changes are audited without credentials,+secret input or conversation bodies. Closing or expiring a context releases its+protected inputs and approvals.++The browser exposes the shared model, routing, Agent, Worker, conversation and+settings workflows. Host-only update, CLI-entry, quit, login-start and titlebar+controls are absent. Directory actions show a path on the service host. OpenAPI+saving downloads the canonical file; clipboard failures expose manual copying.++Windows Desktop wraps the local console, checks the actual Gateway and creates+fresh one-time launch codes itself. A service restart returns it through the+bundled startup page and reconnects without credential entry. See+[Windows Desktop installation](windows-desktop-installation.md).++## Troubleshooting++- **Files unavailable:** reinstall the complete matching package. The service's+ API and Gateway do not depend on frontend assets being present.+- **Session ended:** create a fresh local launch URL or enter a valid access token.+ A browser does not silently acquire replacement owner credentials.+- **Too many failed sign-ins:** wait one minute before retrying. Network failures+ do not block a local launch link. Sign out before closing an unused console tab;+ a new login at the session limit retires the least recently used session.+- **Port/listener failure:** inspect the desired and applied console addresses;+ correct the saved listener and restart the service. Gateway settings are separate.+- **Origin denied:** use the actual console address and port. Requests with a+ foreign Host/Origin are refused; cross-origin management is not enabled.+- **A response was lost:** query the original Operation. Closing a browser or+ reconnecting does not cancel, retry or resubmit accepted work.diff --git a/docs/windows-desktop-installation.md b/docs/windows-desktop-installation.mdnew file mode 100644index 00000000..542459a1--- /dev/null+++ b/docs/windows-desktop-installation.md@@ -0,0 +1,149 @@+# Windows Desktop installation and updates++The [English installation guide](../apps/website/content/guides/install-windows.en.md)+and [Chinese installation guide](../apps/website/content/guides/install-windows.zh.md)+own the user steps, SHA-256 verification and SmartScreen prompts. The NSIS package+supports native Windows x64 and installs for the current ordinary user without+Python, WSL or administrator privileges.++The shell's program directory is fixed at `%LOCALAPPDATA%\Programs\HiRoute`.+Standalone service state remains under `%LOCALAPPDATA%\HiRoute\cli`; neither root+can contain the other. The native adapter checks KnownFolders, architecture,+existing manager ownership and reparse-free paths before product writes. An+SCM-managed installation is refused unchanged because SCM installation is not+offered in this release.++The installer verifies the complete embedded standalone package and uses its+native Rust transaction, the single Windows installation producer. The core+requires the package target to match the native host; the NSIS package and public+Desktop target alone are x64-only. Only the current+`hiroute.windows-install-journal/v1` schema is read. An unreleased Task installation+is adopted when its layout and journal match; incompatible material requires+repair/reinstallation. A prepared journal blocks business startup until recovery reconciles+files, the marker and actual Task registration. No new business mutations are+replayed during installation recovery.++The separate shell inventory records only its installed files and digests. Its+private preparation journal retains matching previous bytes until installation,+login settings and actual Control/Gateway readiness succeed. Changed/foreign+entries are preserved and require repair. Committed cleanup does not replay+installation or roll back a successfully committed package.+After NSIS overlays a replacement, obsolete owned frontend asset paths are removed+only when both their current bytes and retained backups match the old inventory.+This happens before the new payload's strict closed-file-set verification. A retry+recovers any pending shell transaction first. If the standalone core still matches+the previous installation, shell rollback restores its captured settings and files+without reinstalling or draining that unchanged core.+Once both owners commit, the shell atomically records the successful outcome before+retiring its journal. A successful manual repair replaces an earlier failure in+startup and Settings; committed-phase recovery safely repeats that reporting step.++Recovery and uninstall run a verified shell copy outside the program directory.+A failed first installation can therefore roll back before `shell-package.json`+exists, without trying to delete a running shell or CLI. When no Agent storage or+storage-upgrade backup exists, rollback does not need to start the daemon.++After both transactions commit, the Rust core prunes obsolete versioned payloads+under `%USERPROFILE%\.local\lib\hiroute`. It retains the previous package until+shell rollback is no longer possible. Uninstall uses the bundled CLI outside the+version root and removes the verified current payload too. Cleanup resumes from+the current manifest after interruption and preserves changed, foreign or linked+entries. The shell records cleanup results in+`%LOCALAPPDATA%\HiRoute\shell\package-cleanup.json` for diagnosis.+After uninstall commits, package cleanup errors are reported without undoing the+uninstall or skipping an explicitly requested removal of standalone data.++The installer accepts `/S` for unattended installation with the default login-start+and tray choices and no prompts. Failures return a nonzero process exit code.++Login-start and tray choices default on and can be deselected independently.+Login start updates the user's Task and the fixed HKCU Run command together,+compensating a failed Run update. Disabling the tray makes window close exit the+shell; a background login launch then opens a visible window. Quit never stops the+service. A second launch focuses the existing window.++## Local console unavailable++The service binds its console at startup. Disabling the console with+`hiroute console disable` or `hiroute console init --mode off` therefore prevents+the shell from opening it after the next service restart. An occupied explicit+console port has the same effect, while Control and Gateway remain independent.+The bundled page identifies this local-console failure and shows the log path.+Recheck does not change the saved configuration or create a temporary listener.++To restore the local interface with automatic port selection, run in PowerShell:++```powershell+hiroute console init --mode loopback+hiroute service restart+```++Restart can interrupt active calls and tasks. After it completes, select Recheck+in the shell. Keeping the console disabled remains an explicit owner choice.++## Update ordering and recovery++The host selects a newer stable x64 NSIS entry from `releases-v3.json`. The page+cannot supply a download URL, install directory or executable. Downloading and+size/SHA-256 verification finish in private staging while the service runs. Native+lifecycle preparation pauses new admissions and reports active calls/tasks. The+user can cancel; cancellation resumes admission and leaves work untouched.++A missing or retired Windows catalog (HTTP 404/410) is shown as an unavailable+update check. The current installation and service remain usable; retry later.+The shell does not call that a failed installation, claim the current version is+latest, or use the macOS V2 feed as a Windows fallback.++After drain, a private native finisher acknowledges readiness and requires a+generation-bound explicit commit. It waits for the shell to exit, rechecks the+staged installer and runs NSIS passively with its update+flag. The installer repeats drain before stopping the owned daemon. A manual+installer uses that same hook and a bounded wait. An older daemon without drain+support requires a separate explicit interactive confirmation; passive updates+refuse it.+Passive updates skip the login/tray options page and reuse the saved choices;+silent `/S` installations continue to use the documented defaults.++Pre-stop failures resume admission. Replacement failure attempts the old package+and Task through the same Rust journal core; it never rewrites a marker to pretend+recovery succeeded. The next shell start reads the private outcome and can recover+an interrupted transaction after the installer is no longer active. An unresolved+file or service conflict stays on the bundled failure page with a diagnostics path.++## Uninstall boundaries++Agent restoration uses production Preview/Apply and waits for the resulting+Operation before service or file removal. A blocked restore reports the Agent IDs+and leaves the installation available for a user decision. The Task, exact owned+shell login command and recorded files are removed; a foreign Run command or file+is preserved. User PATH removal applies only when the installer added that fixed+entry. Data removal is an explicit unchecked option and does not turn the headless+state root into the NSIS program directory.++Restoration includes each independently managed model, collaboration Skill and+management Skill. Codex's model profile and original root are distinct contexts:+profile status displays both root-owned Skill facets, so uninstall restores those+through the root and any model profile separately. Explicit native profile targets+from discovery remain bound to status, Preview and Apply. Incomplete or conflicting+managed state blocks uninstall before any restore is applied.++If the service cannot start or Agent state cannot be enumerated, interactive+recovery/uninstall offers a separate confirmation with **No** selected by default.+It explains that configured Agents may need manual restoration, affected Agents+cannot be listed, and stopping the owned unresponsive Task may interrupt work.+Continuing always retains all business data, including restoration material.+Silent/passive mode refuses this exception; a known restoration conflict cannot+be bypassed by it. Retry the installer to recover an interrupted installation.++## Evidence and release claims++The native acceptance inventory is+[`windows-desktop-cases.json`](../scripts/windows-desktop-cases.json). Windows 11+x64 and Server selections require real standard-user execution, the candidate SHA,+installer digest, OS/build and architecture. A Server result is not Windows 11+evidence. Browser fixtures, Cargo checks and package construction do not establish+installation, native authorization, upgrade recovery or a live model call.++The [release builder](release-builds.md) keeps a Desktop installer separate from+the headless archive. Release publication requires both native selections and+refuses an identity sidecar that is incomplete or bound to another artifact.diff --git a/e2e/product/schema/contract-set.v1.json b/e2e/product/schema/contract-set.v1.jsonindex 248fdfbc..544e2bfe 100644--- a/e2e/product/schema/contract-set.v1.json+++ b/e2e/product/schema/contract-set.v1.json@@ -1,10 +1,10 @@{- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","files": {"dependency-gate.v1.json": "sha256:b8ac81155266dca921f159d1cfabec6605f2e4bab0320ad6b23a3dbee51e6fa1","product-action.v1.schema.json": "sha256:faf815b27fd292e564a7d51de20c5a2825abbe710315a2364a9932ae3b5e4b7e","product-oracle-evidence.v1.schema.json": "sha256:faab6582bf3fba307b0f9f2949c51726409a209b0fa62e847114e0c6301038c6",- "product-oracle-manifest.v1.json": "sha256:ba3b1fd3c817246edaee08d7682db3042b9b60adcda20da9c606d9b63e1fe376",+ "product-oracle-manifest.v1.json": "sha256:c24352f80e39b359480fe653d5bee1885f83fcce9af8111eacb3b28fc81c3601","product-result.v1.schema.json": "sha256:72fc76be77572e40eed7516754911b45fdc9d55a8c089ba74c21427a33809def"},"schema_version": {diff --git a/e2e/product/schema/product-oracle-manifest.v1.json b/e2e/product/schema/product-oracle-manifest.v1.jsonindex 5fce153e..94ecd628 100644--- a/e2e/product/schema/product-oracle-manifest.v1.json+++ b/e2e/product/schema/product-oracle-manifest.v1.json@@ -1,7 +1,11 @@{- "descriptor_digest": "sha256:40921e7e63889bbe1d604e35e186d5c23400f9711ffa247388b05276e4e29268",+ "descriptor_digest": "sha256:1dc2a7d9545598d10a2074d108eaeb32c140b5b070bf1d4fb70ffd22b853fdb8","expected_red_reasons": [],"planned_commands": [+ "console.open",+ "console.token.create",+ "console.token.list",+ "console.token.revoke","schema.list","schema.show","system.client-status",@@ -102,6 +106,10 @@"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009","proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300","public_commands": [+ "console.open",+ "console.token.create",+ "console.token.list",+ "console.token.revoke","schema.list","schema.show","operations.find",diff --git a/issue-spec/specs/control-plane-changes/spec.md b/issue-spec/specs/control-plane-changes/spec.mdindex fd1e853b..eb4a81c2 100644--- a/issue-spec/specs/control-plane-changes/spec.md+++ b/issue-spec/specs/control-plane-changes/spec.md@@ -123,6 +123,28 @@ journal CAS bind stable input. One current core model receives strictly validatesupported legacy data at its conversion boundary. Reader removal requires explicitsupport retirement with a viable upgrade/recovery path and registry/test updates.+### Requirement: Console mutations keep confirmation, secret and conflict semantics++Console mutations SHALL use the existing Preview/admission, idempotency, revision and recovery contracts. A destructive or authority-changing action that requires confirmation SHALL use a daemon-issued single-use challenge bound to the session, the exact previewed intent and an expiry; expired, reused or mismatched challenges SHALL be rejected without effect. Secrets submitted through the console SHALL enter the existing protected input path, SHALL NOT be echoed in responses, logs, diagnostics or browser storage, and SHALL be released when the request ends. Several console sessions, the CLI and a host shell MAY manage the same instance concurrently; a stale revision SHALL produce a conflict that identifies the changed object instead of overwriting it.++#### Scenario: Confirmation replay++- **WHEN** a confirmed deletion challenge is submitted a second time or after the target changed+- **THEN** the second submission is rejected and the current state is unchanged.++#### Scenario: Secret custody++- **WHEN** the owner saves an API connection key through the console+- **THEN** the connection becomes usable, and the key does not appear in any console response, daemon log, diagnostic bundle or browser storage.++#### Scenario: Concurrent edit++- **WHEN** two browser tabs edit the same plan and the second saves after the first+- **THEN** the second save reports a revision conflict and the first saved content remains.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219729524+## Implementation references- [Application operation workflows](../../../crates/application/src/operations) anddiff --git a/issue-spec/specs/getting-started/spec.md b/issue-spec/specs/getting-started/spec.mdindex 35af92d1..d70cf133 100644--- a/issue-spec/specs/getting-started/spec.md+++ b/issue-spec/specs/getting-started/spec.md@@ -170,6 +170,147 @@ and exits. Deleting the App alone preserves data; optional cleanup cannot deleteprojects or native Agent credentials. Package construction alone is not signing,notarization, native installation, or live-Agent evidence.+### Requirement: Windows x64 Desktop installs per user and opens ready to use++HiRoute SHALL provide a Windows x64 Desktop installer that a standard user can run without administrator rights, Python or a terminal. In this release it is the only supported Windows installation path. It SHALL verify the package, publish the user-owned Windows standalone installation (CLI, daemon, CPA and Skills), register the default Task Scheduler manager, add the Desktop shell, start the service and open the shell when the service is ready. Login start and tray residency SHALL be enabled by default and SHALL be optional during installation. An unattended mode SHALL install with the defaults without prompts. An existing Task Scheduler installation for the same user SHALL be upgraded in place with its data and Agent recovery references preserved. SCM service installation is not offered in this release: an existing SCM-managed installation SHALL be refused before writing, with an explanation, and SHALL remain unchanged. The installer SHALL refuse non-x64 systems before writing. A missing WebView2 runtime SHALL be installed or explained. An interrupted installation SHALL be repairable by running the installer again. Uninstall SHALL restore managed Agent access before removing the manager registration, shell and entries, and SHALL preserve business data unless the user explicitly selects its removal. When neither Agent storage nor its upgrade backup exists, first-install recovery SHALL NOT require a working daemon. If the service is unavailable and Agent state cannot be enumerated, recovery or uninstall SHALL offer a separate default-No interactive confirmation to stop the owned unresponsive Task and proceed with restoration unverified. It SHALL warn that affected Agents cannot be enumerated, configured Agents may need manual restoration and active work may be interrupted; this continuation SHALL retain all business data. Silent and passive modes SHALL refuse this continuation, and enumerated restore conflicts SHALL still block removal. Verified obsolete versioned packages SHALL be pruned only after both installation owners commit; rollback sources SHALL be retained until then. Uninstall SHALL remove its verified current package and preserve changed or foreign files.++#### Scenario: Fresh standard-user installation++- **WHEN** a standard user without Python runs the installer on Windows x64 and accepts the defaults+- **THEN** installation completes without elevation, the HiRoute window opens with a healthy service, and `hiroute` in a new terminal reaches the same instance.++#### Scenario: Existing user installation++- **WHEN** the user already has a Task Scheduler installation of HiRoute with saved sources and plans+- **THEN** installation keeps that data and manager, and the console shows the same sources and plans.++#### Scenario: Existing SCM installation++- **WHEN** the installer finds an SCM-managed HiRoute installation for the user+- **THEN** it stops before writing any file, explains that SCM service installation is not offered in this release, and leaves that installation unchanged.++#### Scenario: Unattended installation++- **WHEN** an administrator or script runs the installer in its unattended mode on Windows x64+- **THEN** installation completes with the default choices without prompts, and the service is healthy afterwards.++#### Scenario: Unsupported architecture++- **WHEN** the installer runs on a Windows ARM64 system+- **THEN** it stops before writing any file and explains that only x64 is supported.++#### Scenario: Interrupted installation++- **WHEN** installation stops after files were partially published+- **THEN** the service is not admitted with mixed files, and rerunning the installer repairs or completes the installation without losing data.++#### Scenario: Unavailable service during recovery or uninstall++- **WHEN** the service cannot start or Agent state cannot be enumerated+- **THEN** recovery or uninstall requires separate explicit interactive consent to continue without verified restoration, explains the possible Agent and active-work effects, and retains all business data; silent/passive execution refuses this exception.++#### Scenario: Restore conflict remains protected++- **WHEN** a managed Agent has an enumerated restoration conflict+- **THEN** uninstall stops before removal and reports the affected Agent; unavailable-service consent cannot bypass the conflict.++#### Scenario: Versioned package cleanup++- **WHEN** installation commits or uninstall removes its package+- **THEN** verified obsolete payloads are removed, rollback sources survive until both owners commit, interrupted cleanup can resume, and changed or foreign entries remain untouched.++#### Scenario: Replacement changes frontend resource names++- **WHEN** an existing Windows Desktop installation is replaced by a verified package with different hashed frontend asset filenames+- **THEN** the installer durably backs up the prior owned files before retiring obsolete payload paths, validates the complete new package without accepting foreign or modified content, and preserves the old versioned core until both installation owners commit.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219731276++### Requirement: The Windows shell is a thin host for the console++The Windows Desktop shell SHALL run as a single instance, show the console in an embedded WebView after the service is ready, and offer tray actions to open the window, open the console in the default browser and quit the shell. It SHALL obtain console sessions through the private named-pipe Local Control path and SHALL NOT persist session or launch credentials. Quitting the shell SHALL NOT stop the service. When the service is stopped or unhealthy, the shell SHALL start it through the installed manager and show progress, failure and the location of logs. The shell SHALL NOT execute business operations of its own; product actions go through the console and its HTTP control interface. Host-only features available in the shell, such as update and login-start preference, SHALL be exposed to the console as explicit host capabilities. If Control and Gateway are ready but no local console listener is bound, the shell SHALL identify the console-listener failure separately from service startup and show explicit owner CLI configuration and restart instructions. Retrying SHALL NOT change saved listener settings or start a temporary listener, and the owner SHALL retain the ability to disable the console.++#### Scenario: Second launch++- **WHEN** the user starts HiRoute again while the shell is running+- **THEN** the existing window is focused and no second shell or service is started.++#### Scenario: Service stopped++- **WHEN** the shell starts while the background service is stopped+- **THEN** the shell starts it through the manager and opens the console once Local Control and Gateway are ready, or shows the failure with its log location.++#### Scenario: Quit the shell++- **WHEN** the user quits from the tray+- **THEN** the shell exits while the Gateway keeps serving configured Agents.++#### Scenario: Open in browser++- **WHEN** the user selects open in browser+- **THEN** the default browser opens a fresh single-use launch link and reaches an authenticated console session.++#### Scenario: Local console disabled or unable to bind++- **WHEN** the service is healthy but the saved console is off or its explicit port could not bind+- **THEN** the shell identifies the missing local console, shows how to save loopback with automatic port selection and restart the service, and warns that restart may interrupt active work. Retry only rechecks; it does not overwrite the owner configuration.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219733037++### Requirement: Windows Desktop updates verify unsigned packages by catalog digest++The Windows shell SHALL select a newer stable Windows x64 Desktop release from the trusted website release catalog and download it over HTTPS while the service keeps running. Before any stop it SHALL verify byte count and SHA-256 against the catalog. Windows packages are not code-signed; package origin SHALL be established by the HTTPS catalog and digest, and HiRoute SHALL NOT claim a publisher identity. Release pages SHALL publish each package SHA-256, and documentation SHALL guide users through the unknown-publisher prompt. Replacement SHALL follow the existing orderly-stop handoff: preflight, drain active requests and accepted Worker work with user cancellation, stop the shell and service, replace through the journaled installation transaction, run storage validation and migration, restart and report health. A failure before replacement SHALL restore the old running service; an interrupted replacement SHALL be repaired on the next start or installer run. A manually downloaded newer installer SHALL use the same transaction. The in-app passive update SHALL preserve the existing login-start and tray choices and SHALL NOT wait on an interactive options page. In this release, Windows publication SHALL consist only of the x64 Desktop installer named `HiRoute-<version>-<rev12>-windows-x86_64-setup.exe`. Windows standalone archives of any architecture and Windows ARM64 packages SHALL NOT be published, and release catalog validation SHALL reject a Windows standalone artifact. An unavailable or invalid catalog SHALL be reported as an update-check failure while the current application and service remain usable. A missing or retired Windows catalog SHALL NOT be presented as a failed installation or as proof that no update exists, and the shell SHALL NOT fall back to the released V2 catalog.++#### Scenario: Digest mismatch++- **WHEN** a downloaded package size or SHA-256 differs from the catalog+- **THEN** the update fails before stopping the service and the existing version remains in use.++#### Scenario: Cancel while draining++- **WHEN** the user cancels while accepted Worker work is still running+- **THEN** the work is neither killed nor resubmitted and normal admission resumes.++#### Scenario: Replacement failure++- **WHEN** file replacement fails after the service stopped+- **THEN** the previous verified version is restored and restarted, and the failure stage is reported.++#### Scenario: Successful update++- **WHEN** an update completes+- **THEN** the new version starts with existing sources, plans, Agent configuration and observations intact, and the shell reopens the console.++#### Scenario: Windows standalone archive in a release++- **WHEN** a release catalog candidate contains a Windows standalone archive or a Windows ARM64 package+- **THEN** catalog validation rejects it before publication and released readers never receive it.++#### Scenario: Passive update preserves preferences++- **WHEN** the shell hands off a verified update to the passive installer+- **THEN** installation proceeds without an interactive options page, retains the existing login-start and tray preferences, and returns to a healthy service.++#### Scenario: Windows catalog not available++- **WHEN** the trusted Windows catalog returns HTTP 404 or 410+- **THEN** the page reports that the Windows update catalog is unavailable and offers retry, without claiming that installation failed or that the latest version is installed, changing product data, stopping the service or selecting a V2 artifact.++#### Scenario: Shell replacement fails before the core changes++- **WHEN** a prepared shell replacement fails while the standalone marker and verified Task still refer to the previous installation+- **THEN** recovery restores the verified shell files and captured login/tray/listener settings without reinstalling or draining that unchanged core, retains active work and business data, and a subsequent installer run can proceed through the same ownership checks.++#### Scenario: Manual repair supersedes a prior failure++- **WHEN** recovery reported an earlier replacement failure and a subsequent manual installer commits the verified new core and shell+- **THEN** the persisted startup and Settings outcome reflects the committed installation instead of claiming that the prior version was restored, and interrupted committed-phase reporting completes idempotently through recovery.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219734656+## Implementation references- [Native updater](../../../apps/desktop/src-tauri/src/updates.rs) anddiff --git a/issue-spec/specs/shared-client-access/spec.md b/issue-spec/specs/shared-client-access/spec.mdindex ba8cfea3..8e7454bc 100644--- a/issue-spec/specs/shared-client-access/spec.md+++ b/issue-spec/specs/shared-client-access/spec.md@@ -47,18 +47,21 @@ may close transport. These limits do not alter Worker execution concurrency.### Requirement: Local management trusts OS access with typed native boundaries-Local Control accepts processes that can access its socket, without extra peer-UID,-owner/mode checks or client-source-specific Apply capability. CLI and Desktop share-the same user/idempotency/recovery scope. Application still verifies normalized-intent, current versions, and exact admission; Preview/cancelled confirmation does-not write. Model grants and remote collaboration authority remain separate.--WebView may invoke only purpose-specific Tauri ACL commands. It cannot self-assert-principal, obtain arbitrary Local Control/shell/file/SQL access, or give remote-content local management authority. Domain pages expose real capabilities and-explicit unsupported/unavailable state, never fixture-backed success. The shell-can open offline and present implemented recovery without requiring internal-component knowledge; provider communication stays outside WebView.+Local Control accepts processes that can access its socket or private named pipe, without extra peer-UID, owner/mode checks or client-source-specific Apply capability. CLI, Desktop and console sessions share the same user/idempotency/recovery scope. Application still verifies normalized intent, current versions, and exact admission; Preview/cancelled confirmation does not write. Model grants and remote collaboration authority remain separate.++The HTTP console is the only network-reachable management path. It MUST authenticate every management request through a console session derived from a Local Control launch credential or an owner access token; network reachability, a Gateway grant or a page origin alone MUST NOT grant management authority.++WebView and browser pages may invoke only purpose-specific Tauri ACL commands or authenticated console operations. They cannot self-assert principal, obtain arbitrary Local Control/shell/file/SQL access, or give remote content local management authority beyond the authenticated console session. Domain pages expose real capabilities and explicit unsupported/unavailable state, never fixture-backed success. A host shell can open offline and present implemented recovery without requiring internal component knowledge; provider communication stays outside WebView and browser pages.++Authenticated console sessions have the same protected-operation authority as macOS Desktop, without a password or unlock step. Protected operations retain in-page confirmation and exact-digest registration. Collaboration/Skill-authorized callers cannot mint console credentials. Protected uses are audited without credentials, secret input or conversation bodies.++#### Scenario: Network peer without a console session++- **WHEN** a process reaches the console listener over the network but presents no valid console session+- **THEN** no management operation or product data is available to it, while OS-trusted Local Control access remains unchanged.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219725852### Requirement: Clients observe work without automatically repeating it@@ -489,39 +492,153 @@ Source SPEC comments:### Requirement: Windows headless preserves the logged-on user's native authority-Windows standalone MUST use the actual user's Profile and LocalAppData KnownFolders-for installation and runtime ownership. HOME/XDG values cannot redirect an installed-instance. Native headless operation uses the shared CLI, role-all daemon, Application,-Gateway and business stores without requiring Desktop or WSL.--The default Task Scheduler manager runs as the current logged-on user with an-InteractiveToken and least privilege. Ordinary install/start/stop does not require-administrator access or an account password. The background process MUST survive-closure of its launching terminal. Its lifetime requires that user's logged-on-session; login-start preference and starting now remain separate operations.-Unexpected business-process exit uses bounded recovery, while an explicit stop-terminates the owned child tree and cancels pending recovery. Manager registration-or action launch alone is not proof of healthy Control and Gateway service.--Installation MUST verify the complete package inventory, source revision, file-digests and native executable architecture before publishing stable entries.-A prepared replacement blocks business startup until package files, installation-record and actual manager definition agree. Repair/rollback preserves saved Sources,-secrets, routes, Agent recovery references and observations instead of replaying-business mutations or initializing empty stores. Uninstall preserves business data-and unrelated native configuration.--Local Control, lifecycle and protected input use private named pipes bound to the-account SID, held runtime objects and verified native peers. Protected credential-carriers use explicitly inherited non-stdio pipe handles with bounded input and EOF;-argv, environment variables and ordinary JSON input do not supply that authority.-Remote peers, replaced objects and occupied endpoints cannot impersonate the instance.--An optional SCM installation is a separate administrator operation over verified-administrator-controlled package bytes. Its privileged host cannot execute an-arbitrary user-selected image. Task acceptance cannot establish service-account,-logout or SCM acceptance; native OS, architecture and real-provider claims require-their own revision-bound execution evidence.+Windows standalone MUST use the actual user's Profile and LocalAppData KnownFolders for installation and runtime ownership. HOME/XDG values cannot redirect an installed instance. Native headless operation uses the shared CLI, role-all daemon, Application, Gateway and business stores without requiring Desktop or WSL. Windows installation, update and uninstall are performed by the native installation transaction used by the Windows Desktop installer; no separate Windows headless installer or Python runtime is required, and a user who needs only the CLI and daemon installs the same package.++The default Task Scheduler manager runs as the current logged-on user with an InteractiveToken and least privilege. Ordinary install/start/stop does not require administrator access or an account password. The background process MUST survive closure of its launching terminal. Its lifetime requires that user's logged-on session; login-start preference and starting now remain separate operations. Unexpected business-process exit uses bounded recovery, while an explicit stop terminates the owned child tree and cancels pending recovery. Manager registration or action launch alone is not proof of healthy Control and Gateway service.++Installation MUST verify the complete package inventory, source revision, file digests and native executable architecture before publishing stable entries. A prepared replacement blocks business startup until package files, installation record and actual manager definition agree. Repair/rollback preserves saved Sources, secrets, routes, Agent recovery references and observations instead of replaying business mutations or initializing empty stores. Uninstall preserves business data and unrelated native configuration.++Local Control, lifecycle and protected input use private named pipes bound to the account SID, held runtime objects and verified native peers. Protected credential carriers use explicitly inherited non-stdio pipe handles with bounded input and EOF; argv, environment variables and ordinary JSON input do not supply that authority. Remote peers, replaced objects and occupied endpoints cannot impersonate the instance.++Task Scheduler is the only installation manager offered in this release. SCM service installation has no supported entry point or user documentation; installation, update and uninstall refuse to modify an SCM-managed installation and explain why. Retained SCM platform code MUST NOT execute an arbitrary user-selected image while privileged. Task acceptance cannot establish service-account, logout or SCM acceptance; native OS, architecture and real-provider claims require their own revision-bound execution evidence.++#### Scenario: Install without Python++- **WHEN** a standard user on Windows x64 without Python installs HiRoute+- **THEN** the native installation transaction publishes and registers the Task Scheduler installation, and the CLI and daemon run headless without Desktop being opened.++#### Scenario: SCM installation is not offered++- **WHEN** a user looks for a way to install HiRoute as a Windows service, or the installer finds an SCM-managed installation+- **THEN** no supported command or documented path installs an SCM service, and the existing SCM installation is refused unchanged with an explanation.++#### Scenario: Task lifetime++- **WHEN** the user closes the terminal that started the service and later logs off+- **THEN** the service survives the terminal and stops with the user's session, and login start remains a separate preference.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6228861461++### Requirement: The daemon serves the shared product console++A role-all `hirouted` on Linux and Windows SHALL be able to serve the HiRoute product frontend and its control operations over HTTP on a console listener that is separate from the Gateway listener. Console pages SHALL use the same Application owners, typed operations, results and failure codes as CLI and Desktop, and SHALL present the same saved state. Gateway credentials SHALL NOT authenticate console requests and console sessions SHALL NOT authorize model requests. On Linux standalone the console SHALL be disabled until the owner explicitly configures it during installation or initialization; enabling it SHALL NOT start the daemon implicitly. Host-only features unavailable in the current host, such as in-app update, window behavior and login items, SHALL be absent or explicitly unavailable rather than failing or reporting fixture success.++#### Scenario: Open the console from the Linux CLI++- **WHEN** the console is configured, the standalone service has established its listener and the owner runs the documented console open command+- **THEN** the command returns a single-use link for the actual local or explicitly configured network listener; opening it in a browser shows the product pages with the current service status, sources, plans, Agents, Workers and sessions.++#### Scenario: Cross-client consistency++- **WHEN** a source or plan is changed through the CLI while a console page is open+- **THEN** after refresh the console shows the same saved revision the CLI reports, and a console edit based on the old revision is rejected as a conflict.++#### Scenario: Credential separation++- **WHEN** a request presents a Gateway grant key to the console or a console session to the Gateway+- **THEN** the request is rejected without returning data or executing a model request.++#### Scenario: Service not ready++- **WHEN** the console listener answers while Local Control or the Gateway is not ready+- **THEN** the console shows the actual unavailable state and recovery action instead of an empty or successful page.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219723541++### Requirement: Console sessions require explicit owner authentication++Every console request other than static frontend assets and the credential exchange SHALL require an authenticated session. A launch credential SHALL be issued only through the OS-trusted Local Control path for an actually listening console. It SHALL be single-use, expire after two minutes, and be bound to the selected console origin including its actual port. The owner CLI SHALL return a local or remote login URL according to that live listener. A network-origin credential MAY be exchanged remotely only when network listening was explicitly configured; a loopback-origin credential SHALL NOT be redeemed remotely. A mismatched origin or port SHALL NOT consume an otherwise valid code. The page SHALL remove the code from its URL before exchange. The resulting session credential SHALL be bound to the console origin including its port. The session credential SHALL be held only in browser sessionStorage and sent in an explicit Bearer request header. It SHALL NOT be placed in cookies, URLs, localStorage or other persistent browser storage, so cross-site requests and other services on the same host never receive console authority. The owner SHALL be able to create, list, expire and revoke named access tokens through the CLI; token secrets SHALL be shown only at creation and SHALL NOT be stored in recoverable form. Revoking a token SHALL end the sessions derived from it. State-changing requests SHALL be rejected when Host or Origin does not match the configured console or when cross-site request protection fails. Console operations SHALL carry a distinct principal identity that operation history and diagnostics can attribute; this increment supports a single owner principal.++An authenticated console session SHALL have the same protected-operation authority as macOS Desktop, without a password or unlock step. Every protected operation SHALL retain its in-page confirmation and exact-digest authority registration. Callers operating under collaboration or Skill authorization SHALL NOT mint console launch credentials or access tokens. Protected-operation uses SHALL be audited without credentials, secret input or conversation bodies.++Sessions SHALL remain in memory only, expire after 12 hours idle or seven days total, and be bounded to 16 active sessions. A valid new login at capacity SHALL retire and audit the least recently used session. Invalid credentials SHALL NOT evict a session. Failed exchanges SHALL be limited per peer and globally within independent loopback and network budgets, so network failures cannot block a local launch credential.++#### Scenario: Launch credential replay++- **WHEN** a launch link that was already exchanged, or has expired, is opened again+- **THEN** no session is created and the page explains how to obtain a new link.++#### Scenario: Launch credential target binding++- **WHEN** a launch credential is presented at a different host or port, or a local-only credential is submitted remotely+- **THEN** no session is created, the credential is not consumed, and it remains usable once at its original authorized origin until expiry.++#### Scenario: Foreign origin++- **WHEN** a page from another origin submits a state-changing console request using the owner's browser session+- **THEN** the request is rejected and no Operation is admitted.++#### Scenario: Other local services++- **WHEN** the owner's browser holds a console session and visits another web service on the same host but a different port+- **THEN** no console credential is sent to that service, and the console session remains unaffected.++#### Scenario: Token revocation++- **WHEN** the owner revokes an access token while a remote browser session created from it is open+- **THEN** the next request from that session is rejected and requires new authentication.++#### Scenario: Unauthenticated request++- **WHEN** a client calls a console operation without a valid session+- **THEN** the response contains no product data and an authentication-required result.++#### Scenario: Abandoned sessions at capacity++- **WHEN** the owner successfully signs in after 16 sessions have accumulated+- **THEN** the least recently used session ends, recently used sessions remain valid, and the new session works without restarting the daemon.++#### Scenario: Network login failures++- **WHEN** network peers exhaust the failed-exchange budget+- **THEN** further network exchanges are limited while a valid local launch credential remains usable; existing authenticated sessions remain usable.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219725852++### Requirement: Console exposure beyond loopback is explicit++On Linux, the console SHALL remain disabled on a fresh unattended installation unless the owner explicitly chooses a scope and port during installation or initialization. Enabling without a network address SHALL select loopback. Installation upgrades without console options SHALL preserve existing settings. Listening SHALL begin only at service startup using the persisted scope and port. `hiroute console open` SHALL NOT create a listener or start a service: it SHALL issue a single-use login URL from actual live listener state or return an actionable unavailable result. Binding to a non-loopback address SHALL require explicit persisted owner configuration and plaintext-network consent. Remote sessions SHALL require an owner CLI-issued single-use credential bound to that network origin or a named access token. A wildcard bind SHALL require a concrete advertised address for a usable login URL. The owner CLI SHALL allow explicit selection of the already-listening loopback endpoint for local recovery in network mode, without changing configuration or creating a socket. Changing desired settings while a service is running SHALL NOT change the default URL until that service applies the configuration. An occupied explicit port SHALL NOT silently fall back to another port. TLS SHALL NOT be required. When a session is served over a non-loopback connection without TLS, the console SHALL persistently indicate that traffic is unencrypted and SHALL show an additional warning before secret entry, while still allowing it. A configured address or port that cannot be bound SHALL produce an explicit listener failure without changing Gateway or Local Control availability.++#### Scenario: Default exposure++- **WHEN** the console is enabled without address configuration+- **THEN** it is reachable only through loopback, and connections to other interfaces are refused.++#### Scenario: Remote access++- **WHEN** the owner configures a network address and port during installation or initialization, starts the service and runs `console open`+- **THEN** it returns a one-use URL for that live network origin, works from another computer and shows the unencrypted-connection indicator; a request without a valid launch credential, token or session is rejected.++#### Scenario: Open does not enable listening++- **WHEN** the console is off or its configured port failed to bind+- **THEN** repeated `console open` calls fail with setup or restart guidance and do not open any listener or change configuration.++#### Scenario: Live configuration and upgrade++- **WHEN** desired scope or port changes during a running service, or the installer upgrades without console options+- **THEN** `console open` still uses the actual bound origin until restart, and an upgrade preserves the chosen configuration.++#### Scenario: Wildcard advertisement++- **WHEN** a network listener binds a wildcard address+- **THEN** initialization requires a concrete advertised address, the returned URL uses that address and the actual bound port, and Host/Origin checks admit only the configured console origin or its bound local origin.++#### Scenario: Secret entry over plaintext++- **WHEN** a remote plaintext session opens an API key or credential form+- **THEN** the form warns that the secret will cross the network unencrypted and accepts submission only after that warning is presented.++#### Scenario: Port unavailable++- **WHEN** the configured console port is occupied+- **THEN** the console reports a listener failure while the Gateway and CLI continue to work.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/132#issuecomment-6219727813## Implementation referencesdiff --git a/scripts/build-release.py b/scripts/build-release.pyindex a49e32c3..28fb848c 100644--- a/scripts/build-release.py+++ b/scripts/build-release.py@@ -95,8 +95,9 @@ def windows_release_environment(target, inherited):class Candidate:- def __init__(self, target, source_repo):+ def __init__(self, target, source_repo, windows_desktop=False):self.target = target+ self.windows_desktop = windows_desktopself.source_repo = source_repo.resolve(strict=True)self.revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO, text=True).strip()parent = REPO / "target/release-candidate" / self.revision / target@@ -109,10 +110,10 @@ class Candidate:self.environment = dict(os.environ, RUSTC_WRAPPER="sccache", CARGO_INCREMENTAL="0",HIROUTE_BUILD_SOURCE_SHA=self.revision, LC_ALL="C")- def run(self, *arguments, env=None, timeout=None):+ def run(self, *arguments, env=None, timeout=None, cwd=None):started = time.monotonic()print(f"Running {Path(str(arguments[0])).name} {' '.join(map(str, arguments[1:3]))}", file=sys.stderr, flush=True)- result = subprocess.run(list(map(str, arguments)), cwd=REPO, env=env or self.environment,+ result = subprocess.run(list(map(str, arguments)), cwd=cwd or REPO, env=env or self.environment,text=True, capture_output=True, timeout=timeout)self.result["timings"].append({"command": list(map(str, arguments[:3])),"seconds": round(time.monotonic() - started, 3),@@ -126,6 +127,8 @@ class Candidate:return self.run(sys.executable, REPO / "scripts" / f"{name}.py", *args)def preflight(self):+ if self.windows_desktop and self.target != STATIC_CRT_TARGET:+ raise ValueError("Windows Desktop supports only x86_64-pc-windows-msvc")if self.target not in TARGETS or host_target() != self.target:raise ValueError(f"native host required for {self.target}; host is {host_target()}")if self.run("git", "status", "--porcelain", "--untracked-files=normal"):@@ -165,6 +168,10 @@ class Candidate:def standalone(self):windows = self.target.endswith("-pc-windows-msvc")+ frontend = REPO / "apps/desktop"+ npm = "npm.cmd" if windows else "npm"+ self.run(npm, "ci", "--prefix", frontend)+ self.run(npm, "run", "build", "--prefix", frontend)cpa = self.output / ("cliproxyapi.exe" if windows else "cliproxyapi")provenance = json.loads(self.script("build-cpa", "--source-repo", self.source_repo,"--target", self.target, "--output", cpa))@@ -201,12 +208,13 @@ class Candidate:inspect_elf(binary, self.target)notices = self.output / "notices"self.script("collect-third-party-licenses", "--cargo-target", self.target,- "--cpa-source-repo", self.source_repo, "--output", notices)+ "--cpa-source-repo", self.source_repo,+ "--npm-root", frontend, "--output", notices)packaged = json.loads(self.script("package-standalone", "build", "--version", self.version, "--revision", self.revision,"--target", self.target, "--hiroute", binaries / ("hiroute" + suffix), "--hirouted", binaries / ("hirouted" + suffix),"--cpa-binary", cpa, "--cpa-version", pin["version"], "--cpa-license", cpa.with_suffix(".LICENSE"),- "--notices", notices, "--output", self.output))+ "--notices", notices, "--console-assets", frontend / "dist", "--output", self.output))archive, manifest = Path(packaged["archive"]), Path(packaged["manifest"])packager = module("package-standalone")verified = packager.verify(manifest, archive)@@ -232,8 +240,46 @@ class Candidate:"target": self.target, "format": "tar.gz", "distribution": "unsigned",**verified["archive"], "manifest_filename": manifest.name,"manifest_sha256": packager.digest(manifest), "manifest_size": manifest.stat().st_size}+ if windows:+ self.result["internal_payload"] = {"target": self.target, "archive": archive.name, "manifest": manifest.name}+ artifact = Nonereturn artifact, [archive, manifest]+ def desktop_windows(self):+ _, files = self.standalone()+ archive, manifest = files+ shell = REPO / "apps/shell"+ packager = module("package-windows-shell")+ package = packager.stage(manifest, archive, shell / "src-tauri/resources/standalone")+ environment = windows_release_environment(self.target, self.environment)+ self.run("npm.cmd", "ci", cwd=shell)+ self.run("npm.cmd", "run", "tauri", "--", "build", "--ci", "--target", self.target,+ "--features", "shell-runtime", "--no-bundle", "--", "--locked", cwd=shell, env=environment)+ self.run("npm.cmd", "run", "tauri", "--", "bundle", "--ci", "--target", self.target,+ "--features", "shell-runtime", "--bundles", "nsis", "--no-sign", cwd=shell, env=environment)+ # Tauri CLI 2.11.4 uses product_version_arch-setup.exe. Select that+ # exact candidate path; retained installers from other versions are irrelevant.+ produced = REPO / "target" / self.target / "release/bundle/nsis" / f"HiRoute_{self.version}_x64-setup.exe"+ if not produced.is_file() or produced.is_symlink():+ raise ValueError("Windows Desktop bundle did not produce its exact installer")+ name = f"HiRoute-{self.version}-{self.revision[:12]}-windows-x86_64-setup.exe"+ installer = self.output / name+ shutil.copyfile(produced, installer)+ # The bundler's NSIS input can differ from the workspace executable.+ # Measure and audit the immutable artifact that users actually install.+ image = packager.shell_image(installer, self.run)+ identity = {"schema": packager.SCHEMA, "version": self.version, "revision": self.revision,+ "architecture": "x86_64", "distribution": "unsigned", "installer_sha256": packager.digest(installer),+ "installer_size": installer.stat().st_size, "integrity": "green", "embedded_components": "awaiting_runtime",+ "native_runtime": "not_executed", "shell_image": image, "standalone_revision": package["revision"],+ "standalone_manifest_sha256": packager.digest(manifest)}+ identity_path = self.output / (name + ".identity.json")+ identity_path.write_text(json.dumps(identity, indent=2) + "\n")+ self.result["desktop_result"] = identity+ artifact = {"kind": "desktop", "platform": "Windows", "architecture": "x86_64", "format": "nsis", "distribution": "unsigned",+ "filename": name, "sha256": identity["installer_sha256"], "size": identity["installer_size"]}+ return artifact, [installer, identity_path]+def build(self):try:self.preflight()@@ -243,14 +289,17 @@ class Candidate:module("package-desktop").ensure_sccache_server()lock = windows_build_lock() if self.target.endswith("-pc-windows-msvc") else module("local-rust").Store().locked(REPO)with lock:- artifact, files = self.standalone()- assets = self.output / "assets"+ artifact, files = self.desktop_windows() if self.windows_desktop else self.standalone()+ assets = self.output / ("internal-payloads" if artifact is None else "assets")assets.mkdir()for path in files:shutil.copyfile(path, assets / path.name)status = "completed" if self.target.endswith("apple-darwin") else "awaiting_runtime"- self.result.update(status=status, package_integrity="green",- website_artifact=artifact, assets=str(assets))+ self.result.update(status=status, package_integrity="green")+ if artifact is None:+ self.result.update(publication="internal-only", internal_payloads=str(assets))+ else:+ self.result.update(website_artifact=artifact, assets=str(assets))return self.resultexcept Exception as error:self.result["error"] = str(error)@@ -264,6 +313,7 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--target", choices=TARGETS, required=True)parser.add_argument("--cpa-source-repo", type=Path, required=True)+ parser.add_argument("--windows-desktop", action="store_true", help="Build the x64 NSIS Desktop installer instead of the headless archive")args = parser.parse_args()try:if args.target.endswith("linux-gnu") and not os.environ.get("HIROUTE_LINUX_BASELINE_IMAGE"):@@ -271,7 +321,7 @@ def main():else:if args.target.endswith("linux-gnu"):Path.home().mkdir(parents=True, exist_ok=True)- candidate = Candidate(args.target, args.cpa_source_repo)+ candidate = Candidate(args.target, args.cpa_source_repo, args.windows_desktop)result = candidate.build()if args.target.endswith("linux-gnu"):Path(os.environ["HIROUTE_RELEASE_RESULT"]).write_text(json.dumps({diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.pyindex c85d985e..55bb7f5c 100755--- a/scripts/check-contract-convergence.py+++ b/scripts/check-contract-convergence.py@@ -18,6 +18,7 @@ EXPECTED_DATABASE_SCHEMA_VERSION = 29VERSION_SUFFIX = re.compile(r"/v[0-9]+")INTERNAL_CONTRACT = re.compile(r"hiroute(?:\.[a-z0-9][a-z0-9-]*)+/v[0-9]+")VALID_MODES = {+ "projection","frozen_fixture","recovery_read_only","rejection_fixture",diff --git a/scripts/ci-shards.py b/scripts/ci-shards.pyindex 4300bfd8..6a44b54a 100755--- a/scripts/ci-shards.py+++ b/scripts/ci-shards.py@@ -52,6 +52,7 @@ INTEGRATION_SHARDS = {("hiroute-integrations", "pre_gateway_compute"),("hiroute-integrations", "release_facts"),("hiroute-local-storage", "canonical_compat"),+ ("hiroute-host-runtime", "release_catalog_compatibility"),},"integration-daemon": {("hiroute-daemon", "discovered_model_product"),@@ -60,6 +61,7 @@ INTEGRATION_SHARDS = {("hiroute-daemon", "subscription_management_product"),("hiroute-daemon", "windows_headless"),("hiroute-daemon", "windows_background"),+ ("hiroute-daemon", "windows_desktop"),},"integration-gateway": {("hiroute-gateway-core", "attempt_exchange"),diff --git a/scripts/install-standalone-windows.py b/scripts/install-standalone-windows.pydeleted file mode 100644index 187a3793..00000000--- a/scripts/install-standalone-windows.py+++ /dev/null@@ -1,557 +0,0 @@-#!/usr/bin/env python3-"""Verified current-account Windows install/repair/uninstall (Python 3.9+).--The native CLI owns profile/SID resolution, private record publication and typed-manager calls. Python never evaluates a PowerShell expression or serializes a-password into argv, XML, environment or the recovery journal.-"""-import argparse-from contextlib import contextmanager-import getpass-import hashlib-import importlib.util-import json-import os-from pathlib import Path-import shutil-import subprocess-import sys-import tempfile-import uuid--sys.dont_write_bytecode = True-spec = importlib.util.spec_from_file_location("hiroute_standalone_package", Path(__file__).with_name("package-standalone.py"))-package = importlib.util.module_from_spec(spec)-spec.loader.exec_module(package)-JOURNAL_SCHEMA = "hiroute.windows-install-journal/v1"-MARKER_SCHEMA = "hiroute.standalone-install/v1"---def regular(path):- """Reject symlinks, junctions and other reparse points, including ancestors."""- path = Path(path)- if ".." in path.parts:- raise ValueError("installation path contains parent traversal")- for component in (path, *path.parents):- try:- value = component.lstat()- except FileNotFoundError:- continue- if component.is_symlink() or getattr(value, "st_file_attributes", 0) & 0x400:- raise ValueError("installation path contains a reparse point")- if path.exists() and not path.is_file():- raise ValueError("owned installation entry is not a regular file")- return path---def native(cli, arguments, payload=None, secret=None):- if payload is not None and secret is not None:- raise ValueError("mixed native stdin sources")- body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else secret- result = subprocess.run([str(cli), "service", *arguments, "--output", "json"], input=body,- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=65, check=False)- if result.returncode:- # Do not replay arbitrary CLI stderr or secret input into installer logs.- raise ValueError("native installation or service operation failed")- envelope = package.load_json_bytes(result.stdout)- if envelope.get("status") != "succeeded" or not isinstance(envelope.get("data"), dict):- raise ValueError("native installation response is invalid")- return envelope["data"]---def internal(cli, verb, request, schema, operation):- """Internal fixed native entry; owner credentials exist only in stdin."""- body = json.dumps(request, separators=(",", ":")).encode("utf-8")- if len(body) > 16 * 1024:- raise ValueError("internal maintenance request is oversized")- result = subprocess.run([str(cli), verb, "--request-stdin"], input=body,- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=65, check=False)- if result.returncode or len(result.stdout) > 16 * 1024:- raise ValueError("native administrator or owner maintenance failed")- response = package.load_json_bytes(result.stdout)- if not isinstance(response, dict) or set(response) != {"schema", "operation", "definition", "completed"} or response["schema"] != schema or response["operation"] != operation or response["completed"] is not True or not isinstance(response["definition"], dict):- raise ValueError("internal maintenance response is invalid")- return response---def owner_finalize(cli, operation):- return internal(cli, "__windows-background-finalize",- {"schema": "hiroute.windows-owner-finalize-request/v1", "operation": operation},- "hiroute.windows-owner-finalize-result/v1", operation)---def pending_admin(layout, journal):- print(json.dumps({"completed": False, "pending_admin": True, "operation": journal["operation"],- "owner_sid": journal["new_definition"]["owner_sid"],- "marker": layout["marker_path"], "journal": str(Path(layout["data_root"]) / "service/install-journal.json"),- "next": "administrator runs admin-scm with their verified CLI, then the owner runs finalize"}, sort_keys=True))---def read_json(path):- regular(path)- if not Path(path).exists():- return None- if Path(path).stat().st_size > 64 * 1024:- raise ValueError("installation record is oversized")- return package.load_json_bytes(Path(path).read_bytes())---def write_record(cli, path, record):- native(cli, ["write-record", "--path", str(path), "--request-stdin"], payload=record)---def publish_marker(cli, record):- native(cli, ["publish-install", "--request-stdin"], payload=record)---def manager_install(cli, manager, password):- arguments = ["install", "--manager", manager]- if manager == "scm":- arguments.append("--password-stdin")- native(cli, arguments, secret=password if manager == "scm" else None)---@contextmanager-def maintenance_lock(data):- import msvcrt- path = regular(Path(data) / "service/install.lock")- if not path.exists():- with path.open("xb") as stream:- stream.write(b"0")- stream.flush()- os.fsync(stream.fileno())- with path.open("r+b") as stream:- stream.seek(0)- msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)- try:- yield- finally:- stream.seek(0)- msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)---def validate_journal(value, layout):- if not isinstance(value, dict) or set(value) != {- "schema", "operation", "phase", "old_marker", "new_marker", "old_definition", "new_definition", "files"- } or value["schema"] != JOURNAL_SCHEMA or value["operation"] not in {"install", "uninstall"} or value["phase"] not in {"prepared", "committed"} or not isinstance(value["files"], list):- raise ValueError("installation journal is invalid; preserve it for repair")- home = Path(layout["home"])- data = Path(layout["data_root"])- allowed = [home / ".local/bin", data, home / ".agents/skills/hiroute-management", home / ".claude/skills/hiroute-management"]- for item in value["files"]:- if not isinstance(item, dict) or set(item) != {"destination", "source", "backup", "old_sha256", "new_sha256", "kind"} or item["kind"] not in {"hardlink", "copy", "remove"}:- raise ValueError("installation journal entry is invalid")- destination = Path(item["destination"])- backup = Path(item["backup"])- if not destination.is_absolute() or not any(root == destination or root in destination.parents for root in allowed) or data / "service/install-backups" not in backup.parents:- raise ValueError("installation journal escapes owned directories")- regular(destination)- regular(backup)- for digest in (item["old_sha256"], item["new_sha256"]):- if digest is not None and (not isinstance(digest, str) or not package.HEX_SHA256.fullmatch(digest)):- raise ValueError("installation journal digest is invalid")- return value---def replace_owned(item, rollback=False):- destination = Path(item["destination"])- regular(destination)- expected = item["old_sha256"] if rollback else item["new_sha256"]- source = Path(item["backup"] if rollback else item["source"])- if destination.exists():- actual = package.digest(destination)- if actual not in {item["old_sha256"], item["new_sha256"]}:- raise ValueError("owned installation entry changed; preserve it for repair")- if expected is None:- if destination.exists():- destination.unlink()- return- regular(source)- if not source.is_file() or package.digest(source) != expected:- raise ValueError("installation replacement source differs from journal")- stage = destination.with_name("." + destination.name + "." + uuid.uuid4().hex + ".stage")- if item["kind"] == "hardlink":- os.link(source, stage)- else:- shutil.copyfile(source, stage)- with stage.open("r+b") as stream:- os.fsync(stream.fileno())- try:- os.replace(stage, destination)- finally:- if stage.exists():- stage.unlink()---def finish_journal(journal_path, journal):- for item in journal["files"]:- backup = Path(item["backup"])- regular(backup)- if backup.exists():- if package.digest(backup) != item["old_sha256"]:- raise ValueError("installation backup changed; preserve it for repair")- backup.unlink()- journal_path.unlink()---def finish_uninstall_metadata(layout, journal):- paths = [(Path(layout["marker_path"]), journal["old_marker"]),- (Path(layout["service_definition"]), journal["old_definition"])]- for path, expected in paths:- current = read_json(path)- if current is not None:- if current != expected:- raise ValueError("installation metadata changed; preserve it for repair")- path.unlink()- manifest_path = Path(layout["data_root"]) / "package-manifest.json"- current = read_json(manifest_path)- if current is not None:- if current.get("version") != journal["old_marker"]["version"] or current.get("target") != journal["old_marker"]["target"]:- raise ValueError("package metadata changed; preserve it for repair")- manifest_path.unlink()---def recover(cli, layout, password, external_manager=False):- path = Path(layout["data_root"]) / "service/install-journal.json"- journal = read_json(path)- if journal is None:- return- validate_journal(journal, layout)- if journal["phase"] == "committed":- if journal["operation"] == "uninstall":- finish_uninstall_metadata(layout, journal)- finish_journal(path, journal)- return- if external_manager and journal["new_definition"].get("manager") == "scm":- current = read_json(layout["marker_path"])- if current not in (journal["old_marker"], journal["new_marker"]):- raise ValueError("prepared SCM installation marker changed; preserve it for repair")- # Before first publication the old marker still identifies its actual- # daemon. After new publication, ordering already required that old- # daemon to stop; prepared admission prevents a new business startup.- if current is not None and current == journal["old_marker"]:- native(cli, ["stop"])- if journal["operation"] == "install":- for item in journal["files"]:- replace_owned(item)- publish_marker(cli, journal["new_marker"])- pending_admin(layout, journal)- return True- if journal["operation"] == "uninstall":- native(cli, ["uninstall"])- for item in journal["files"]:- replace_owned(item)- journal["phase"] = "committed"- write_record(cli, path, journal)- finish_uninstall_metadata(layout, journal)- finish_journal(path, journal)- return- old = journal["old_marker"]- new = journal["new_marker"]- definition_path = Path(layout["service_definition"])- if old is None:- # First-install rollback only touches the exact new registration/image.- publish_marker(cli, new)- write_record(cli, definition_path, journal["new_definition"])- native(cli, ["uninstall"])- else:- # Accept either exact old/new registration after a process crash. Native- # typed verification refuses a foreign registration in both cases.- try:- native(cli, ["stop"])- except ValueError:- # Registration may already reference the new image. Admission is- # blocked by prepared journal; exact native old/new verification in- # manager_install still rejects a live or foreign registration.- pass- write_record(cli, definition_path, journal["new_definition"] or journal["old_definition"])- publish_marker(cli, old)- manager_install(cli, journal["old_definition"]["manager"], password)- for item in reversed(journal["files"]):- replace_owned(item, rollback=True)- if old is None:- for target in (Path(layout["marker_path"]), definition_path):- regular(target)- if target.exists():- target.unlink()- finish_journal(path, journal)---def destinations(root, layout, manifest):- names = package.executable_names(manifest["target"])- home, data = Path(layout["home"]), Path(layout["data_root"])- result = [(home / ".local/bin/hiroute.exe", root / "hiroute.exe", "hardlink", names["hiroute"]),- (home / ".local/bin/hirouted.exe", root / "hirouted.exe", "hardlink", names["hirouted"])]- for prefix in (".agents", ".claude"):- result.append((home / prefix / "skills/hiroute-management/SKILL.md", root / "skills/hiroute-management/SKILL.md", "copy", "skills/hiroute-management/SKILL.md"))- for name in sorted(manifest["files"]):- if name.startswith(("licenses/", "docs/")):- result.append((data / name, root / name, "copy", name))- result.append((data / "package-manifest.json", root / "package-manifest.json", "copy", "__package_manifest__"))- return result---def plan_files(entries, data, old_manifest, uninstall=False):- backup_root = Path(data) / "service/install-backups" / uuid.uuid4().hex- backup_root.mkdir(parents=True)- result = []- for index, (destination, source, kind, name) in enumerate(entries):- regular(destination)- destination.parent.mkdir(parents=True, exist_ok=True)- old_digest = None- backup = backup_root / str(index)- if destination.exists():- owned_manifest = name == "__package_manifest__" and read_json(destination) == old_manifest- if old_manifest is None or (not owned_manifest and (name not in old_manifest["files"] or package.digest(destination) != old_manifest["files"][name]["sha256"])):- raise ValueError("installer refuses to replace a foreign or changed entry")- old_digest = package.digest(destination)- if kind == "hardlink":- os.link(destination, backup)- else:- shutil.copyfile(destination, backup)- with backup.open("r+b") as stream:- os.fsync(stream.fileno())- result.append({"destination": str(destination), "source": str(source), "backup": str(backup),- "old_sha256": old_digest, "new_sha256": None if uninstall else package.digest(source), "kind": kind})- return result---def stage_package(manifest, archive, staging):- for name, (body, _) in package.safe_members(archive, manifest["files"]).items():- relative = name[4:] if name.startswith("bin/") else name- target = staging / relative- target.parent.mkdir(parents=True, exist_ok=True)- with target.open("xb") as stream:- stream.write(body)- stream.flush()- os.fsync(stream.fileno())---def password_input(args):- if args.manager != "scm":- return None- if args.password_stdin:- value = sys.stdin.buffer.read(4097)- if not value or len(value) > 4096:- raise ValueError("service password input is invalid")- return value- return getpass.getpass("Windows account password (stored only by SCM): ").encode("utf-8")---def install(args):- manifest = package.verify(args.manifest, args.archive)- if not manifest["target"].endswith("-pc-windows-msvc"):- raise ValueError("package is not a Windows candidate")- if args.external_manager and args.manager != "scm":- raise ValueError("external administrator maintenance is only available for SCM")- password = None if args.external_manager else password_input(args)- with tempfile.TemporaryDirectory(prefix="hiroute-verified-") as temporary:- staging = Path(temporary)- stage_package(manifest, args.archive, staging)- cli = staging / "hiroute.exe"- layout = native(cli, ["prepare-install"])- if layout["target"] != manifest["target"]:- raise ValueError("package differs from native host target")- data, home = Path(layout["data_root"]), Path(layout["home"])- with maintenance_lock(data):- if recover(cli, layout, password, args.external_manager):- return- old = read_json(layout["marker_path"])- old_definition = read_json(layout["service_definition"])- old_manifest = read_json(data / "package-manifest.json")- if (old is None) != (old_definition is None) or (old is None) != (old_manifest is None):- raise ValueError("installation ownership metadata is incomplete; preserve it for repair")- if old and old_definition["manager"] != args.manager:- raise ValueError("uninstall the previous manager before switching modes")- root = home / ".local/lib/hiroute" / (manifest["version"] + "-" + manifest["revision"][:12])- if root.exists():- for name, facts in manifest["files"].items():- relative = name[4:] if name.startswith("bin/") else name- source = regular(root / relative)- if not source.is_file() or package.digest(source) != facts["sha256"]:- raise ValueError("existing versioned package differs; never overwrite it")- else:- candidate = root.with_name("." + root.name + "." + uuid.uuid4().hex + ".stage")- shutil.copytree(staging, candidate)- for copied in candidate.rglob("*"):- if copied.is_file():- with copied.open("r+b") as stream:- os.fsync(stream.fileno())- os.replace(candidate, root)- metadata = root / "package-manifest.json"- body = json.dumps(manifest, separators=(",", ":"), sort_keys=True).encode()- if metadata.exists():- if metadata.read_bytes() != body:- raise ValueError("versioned package metadata differs; never overwrite it")- else:- with metadata.open("xb") as stream:- stream.write(body)- stream.flush()- os.fsync(stream.fileno())- cli = root / "hiroute.exe"- new = {"schema_version": MARKER_SCHEMA, "version": manifest["version"], "target": manifest["target"],- "install_root": str(root), "service_definition": layout["service_definition"],- "installed_skills": [str(home / prefix / "skills/hiroute-management/SKILL.md") for prefix in (".agents", ".claude")],- "cpa_binary": str(root / "libexec/cliproxyapi.exe"), "cpa_sha256": manifest["cpa"]["sha256"]}- new_definition = native(cli, ["describe-install", "--manager", args.manager, "--daemon", str(root / "hirouted.exe")])- journal = {"schema": JOURNAL_SCHEMA, "operation": "install", "phase": "prepared", "old_marker": old, "new_marker": new,- "old_definition": old_definition, "new_definition": new_definition,- "files": plan_files(destinations(root, layout, manifest), data, old_manifest)}- journal_path = data / "service/install-journal.json"- write_record(cli, journal_path, journal)- try:- if old:- native(Path(old["install_root"]) / "hiroute.exe", ["stop"])- for item in journal["files"]:- replace_owned(item)- publish_marker(cli, new)- if args.external_manager:- pending_admin(layout, journal)- return- manager_install(cli, args.manager, password)- journal["phase"] = "committed"- write_record(cli, journal_path, journal)- finish_journal(journal_path, journal)- except Exception:- if not args.external_manager:- recover(cli, layout, password)- raise- print(json.dumps({"installed": True, "version": manifest["version"], "manager": args.manager,- "cli": str(home / ".local/bin/hiroute.exe"), "started": False}, sort_keys=True))---def uninstall(args):- cli = Path(args.cli).resolve(strict=True)- layout = native(cli, ["layout"])- data = Path(layout["data_root"])- with maintenance_lock(data):- if recover(cli, layout, None if args.external_manager else password_input(args), args.external_manager):- return- old = read_json(layout["marker_path"])- definition = read_json(layout["service_definition"])- manifest = read_json(data / "package-manifest.json")- if old is None or definition is None or manifest is None:- raise ValueError("installation ownership is unavailable")- if args.external_manager and definition["manager"] != "scm":- raise ValueError("external administrator maintenance is only available for SCM")- native(cli, ["stop"])- journal = {"schema": JOURNAL_SCHEMA, "operation": "uninstall", "phase": "prepared", "old_marker": old, "new_marker": old,- "old_definition": definition, "new_definition": definition,- "files": plan_files(destinations(Path(old["install_root"]), layout, manifest), data, manifest, uninstall=True)}- journal_path = data / "service/install-journal.json"- write_record(cli, journal_path, journal)- if args.external_manager:- pending_admin(layout, journal)- return- try:- native(cli, ["uninstall"])- for item in journal["files"]:- replace_owned(item)- journal["phase"] = "committed"- write_record(cli, journal_path, journal)- finish_uninstall_metadata(layout, journal)- finish_journal(journal_path, journal)- except Exception:- # Keep the prepared journal and exact binaries for the next repair;- # SCM deletion can remain pending and must never be called complete.- raise- print(json.dumps({"uninstalled": True, "state_preserved": layout["state_root"]}, sort_keys=True))---def finalize(args):- cli = regular(Path(args.cli).resolve(strict=True))- layout = native(cli, ["layout"])- data = Path(layout["data_root"])- with maintenance_lock(data):- path = data / "service/install-journal.json"- journal = read_json(path)- if journal is None:- raise ValueError("no prepared owner maintenance exists")- validate_journal(journal, layout)- if journal["new_definition"].get("manager") != "scm":- raise ValueError("owner finalization requires a prepared SCM operation")- if journal["phase"] == "prepared":- if journal["operation"] == "install":- # Reopen after a crash at any user-file boundary. Manager proof- # is still required before declaring the transaction committed.- for item in journal["files"]:- replace_owned(item)- publish_marker(cli, journal["new_marker"])- response = owner_finalize(cli, journal["operation"])- if response["definition"] != journal["new_definition"]:- raise ValueError("machine registration differs from prepared owner maintenance")- if journal["operation"] == "uninstall":- for item in journal["files"]:- replace_owned(item)- journal["phase"] = "committed"- write_record(cli, path, journal)- if journal["operation"] == "uninstall":- finish_uninstall_metadata(layout, journal)- finish_journal(path, journal)- print(json.dumps({"completed": True, "operation": journal["operation"], "manager": "scm", "started": False}, sort_keys=True))---def admin_scm(args):- # This is a deliberate administrator-operated bootstrap. Never derive the- # executable from the standard owner's mutable installation marker.- cli = regular(Path(args.cli).resolve(strict=True))- if args.operation == "set_autostart":- if args.enabled is None:- raise ValueError("set_autostart requires explicit --enabled on or off")- enabled = args.enabled == "on"- else:- if args.enabled is not None:- raise ValueError("autostart choice is only allowed for set_autostart")- enabled = None- password = password_input(args)- if not args.account or len(args.account) > 512 or "\\" not in args.account:- raise ValueError("qualified Windows owner account is required")- secret = password.decode("utf-8").rstrip("\r\n")- request = {"schema": "hiroute.windows-scm-owner-request/v1", "operation": args.operation,- "account": args.account, "password": secret, "enabled": enabled}- result = internal(cli, "__windows-scm-owner-install", request, "hiroute.windows-scm-owner-result/v1", args.operation)- # Response contains no credentials. Native helper authenticates the account,- # inspects its profile while impersonating it and changes only its fixed SCM.- print(json.dumps(result, sort_keys=True))---def main():- if sys.platform != "win32":- raise ValueError("Windows installation requires a native Windows process")- parser = argparse.ArgumentParser(description=__doc__)- sub = parser.add_subparsers(dest="command", required=True)- create = sub.add_parser("install")- create.add_argument("--manifest", type=Path, required=True)- create.add_argument("--archive", type=Path, required=True)- remove = sub.add_parser("uninstall")- remove.add_argument("--cli", type=Path, required=True, help="versioned hiroute.exe, not the stable hardlink being removed")- for leaf in (create, remove):- leaf.add_argument("--manager", choices=("task", "scm"), default="task")- leaf.add_argument("--password-stdin", action="store_true")- leaf.add_argument("--external-manager", action="store_true", help="prepare SCM maintenance for a separate administrator, then run finalize as this owner")- finish = sub.add_parser("finalize", help="owner verifies actual SCM install/removal and commits prepared maintenance")- finish.add_argument("--cli", type=Path, required=True, help="prepared versioned CLI, never the stable hardlink being removed")- admin = sub.add_parser("admin-scm", help="run as administrator using the administrator's independently verified HiRoute CLI")- admin.add_argument("--cli", type=Path, required=True, help="administrator's independently verified CLI; do not use the standard owner's writable executable")- admin.add_argument("--account", required=True, help="qualified MACHINE\\owner or DOMAIN\\owner")- admin.add_argument("--operation", choices=("install", "uninstall", "set_autostart"), required=True)- admin.add_argument("--enabled", choices=("on", "off"))- admin.add_argument("--password-stdin", action="store_true")- admin.set_defaults(manager="scm")- args = parser.parse_args()- if args.command == "install":- install(args)- elif args.command == "uninstall":- uninstall(args)- elif args.command == "finalize":- finalize(args)- else:- admin_scm(args)---if __name__ == "__main__":- try:- main()- except (ValueError, OSError, subprocess.SubprocessError) as error:- print(str(error), file=sys.stderr)- sys.exit(1)diff --git a/scripts/install-standalone.py b/scripts/install-standalone.pyindex 3e427b36..7fcc8512 100755--- a/scripts/install-standalone.py+++ b/scripts/install-standalone.py@@ -6,6 +6,7 @@ from contextlib import contextmanagerimport fcntlimport hashlibimport http.client+import ipaddressimport jsonimport osfrom pathlib import Path@@ -267,7 +268,7 @@ def validate_manifest_shape(manifest):or type(archive.get("size")) is not intor not 0 < archive["size"] <= MAX_ARCHIVEor not isinstance(files, dict)- or set(files) != EXPECTED_FILES+ or not valid_inventory(files)or not isinstance(cpa, dict)or set(cpa) != {"version", "sha256"}or not isinstance(cpa.get("version"), str)@@ -279,7 +280,7 @@ def validate_manifest_shape(manifest):):raise ValueError("package manifest is invalid for this host")total = 0- for name in EXPECTED_FILES:+ for name in files:facts = files[name]if (not isinstance(facts, dict)@@ -308,15 +309,25 @@ def validate_manifest(manifest, archive):return manifest+def valid_inventory(files):+ extra = set(files) - EXPECTED_FILES+ return (EXPECTED_FILES <= set(files) and len(extra) <= 2048+ and (not extra or "console/index.html" in extra)+ and all(len(name) <= 240 and name.startswith("console/")+ and all(re.fullmatch(r"[[email protected]]+", part) and part not in {".", ".."}+ for part in name.split("/")) for name in extra))++def extract_verified(manifest, archive, staging):seen = set()+ inventory = set(manifest["files"])with tarfile.open(archive, "r:gz") as bundle:for member in bundle:- if len(seen) >= len(EXPECTED_FILES):+ if len(seen) >= len(inventory):raise ValueError("archive inventory is unsafe or differs from manifest")relative = Path(member.name)if (- member.name not in EXPECTED_FILES+ member.name not in inventoryor member.name in seenor not member.isfile()or relative.is_absolute()@@ -346,7 +357,7 @@ def extract_verified(manifest, archive, staging):mode = 0o755 if manifest["files"][member.name].get("mode") == "executable" else 0o644destination.chmod(mode)seen.add(member.name)- if seen != EXPECTED_FILES:+ if seen != inventory:raise ValueError("archive is incomplete")@@ -617,10 +628,79 @@ def replace_components(components):shutil.rmtree(backup_root, ignore_errors=True)+def console_desired(args):+ """Validate explicit Linux exposure before acquiring the install write lock."""+ mode = getattr(args, "console_mode", None)+ listen = getattr(args, "console_listen", None)+ port = getattr(args, "console_port", None)+ advertise = getattr(args, "console_advertise_address", None)+ plaintext = getattr(args, "allow_plaintext_network", False)+ if all(value is None for value in (mode, listen, port, advertise)) and not plaintext:+ return None+ if platform.system() != "Linux":+ raise ValueError("console installation options are supported only on Linux")+ def address(value):+ if value is None:+ return None+ if "%" in value:+ raise ValueError("console addresses must be IP literals without a scope identifier")+ return ipaddress.ip_address(value)+ ip, advertised = address(listen), address(advertise)+ mode = mode or ("network" if ip and not ip.is_loopback else "loopback")+ if port is not None and not 1 <= port <= 65535:+ raise ValueError("console port must be between 1 and 65535")+ if mode == "network":+ if not plaintext:+ raise ValueError("network console requires --allow-plaintext-network")+ if ip is None or ip.is_loopback or ip.is_multicast:+ raise ValueError("network console requires a non-loopback --console-listen IP")+ advertised = advertised or ip+ if (advertised.is_unspecified or advertised.is_loopback or advertised.is_multicast+ or str(advertised) == "255.255.255.255" or advertised.version != ip.version):+ raise ValueError("network console requires a concrete --console-advertise-address of the same address family")+ elif mode not in ("off", "loopback") or (ip is not None and str(ip) != "127.0.0.1") or advertised:+ raise ValueError("off/loopback console accepts only 127.0.0.1 and no advertised address")+ desired = {"mode": mode, "port_mode": "explicit" if port is not None else "automatic", "allow_plaintext_network": plaintext}+ if ip is not None:+ desired["address"] = str(ip)+ if advertise is not None:+ desired["advertise_address"] = str(advertised)+ if port is not None:+ desired["port"] = port+ return desired+++def console_component(paths, desired):+ if desired is None:+ return None+ destination = paths["state"] / "console-listener.json"+ config = {"schema": "hiroute.console-listener/v1", "applied_address": None, "failure_code": None}+ try:+ descriptor = os.open(destination, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)+ except FileNotFoundError:+ pass+ else:+ with os.fdopen(descriptor, "rb") as source:+ metadata = os.fstat(source.fileno())+ if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid()+ or metadata.st_mode & 0o077 or metadata.st_nlink != 1):+ raise ValueError("existing console configuration is not a private single-link file")+ content = source.read(16 * 1024 + 1)+ if len(content) > 16 * 1024:+ raise ValueError("existing console configuration exceeds its size bound")+ config = load_json_bytes(content)+ if (not isinstance(config, dict) or config.get("schema") != "hiroute.console-listener/v1"+ or set(config) - {"schema", "desired", "applied_address", "failure_code"}):+ raise ValueError("existing console configuration has an unsupported schema")+ config["desired"] = desired+ return staged_file(destination, (json.dumps(config, sort_keys=True) + "\n").encode(), 0o600), destination++def install(args):home = Path(os.environ.get("HOME", ""))if not home.is_absolute() or not home.is_dir():raise ValueError("HOME must identify the current user's absolute home directory")+ desired_console = console_desired(args)paths = layout(home)with installation_lock(paths), tempfile.TemporaryDirectory(prefix="hiroute-install-verify-"@@ -660,8 +740,13 @@ def install(args):staged_data = Path(tempfile.mkdtemp(prefix=f".{version}.", dir=resource_parent))staged_components = []try:+ configured_console = console_component(paths, desired_console)+ if configured_console is not None:+ staged_components.append(configured_console)shutil.copy2(staging / "bin/hiroute", staged_bin / "hiroute")shutil.copy2(staging / "bin/hirouted", staged_bin / "hirouted")+ if (staging / "console").is_dir():+ shutil.copytree(staging / "console", staged_bin / "console")for relative in ("libexec", "licenses", "docs", "skills"):shutil.copytree(staging / relative, staged_data / relative)staged_components.extend(@@ -821,6 +906,11 @@ def parser():add.add_argument("--manifest", type=Path)add.add_argument("--archive", type=Path)add.add_argument("--manifest-url")+ add.add_argument("--console-mode", choices=("off", "loopback", "network"))+ add.add_argument("--console-listen", help="console bind IP; defaults to loopback when enabled")+ add.add_argument("--console-port", type=int, help="explicit console port (otherwise prefer 5838, then a free port)")+ add.add_argument("--console-advertise-address", help="reachable IP for a wildcard network bind")+ add.add_argument("--allow-plaintext-network", action="store_true")sub.add_parser("uninstall")return resultdiff --git a/scripts/package-desktop.py b/scripts/package-desktop.pyindex b8a898ed..5c80b5fc 100644--- a/scripts/package-desktop.py+++ b/scripts/package-desktop.py@@ -37,13 +37,17 @@ def validate_release_versions(version):# ProcessStart uses the diagnostics library's compiled package version.for relative in ("crates/application-api/Cargo.toml", "crates/cli/Cargo.toml","crates/daemon/Cargo.toml", "apps/desktop/src-tauri/Cargo.toml",- "crates/diagnostics/Cargo.toml"):+ "crates/diagnostics/Cargo.toml", "apps/shell/src-tauri/Cargo.toml"):section = re.search(r"(?ms)^\[package\]\s*\n(.*?)(?=^\[|\Z)",(REPO / relative).read_text())declared = re.search(r'^version\s*=\s*"([^"]+)"\s*$', section[1], re.M) if section else Noneactual = declared[1] if declared else Noneif actual != version:raise ValueError(f"release version mismatch: {relative} is {actual}, expected {version}")+ for relative in ("apps/shell/package.json", "apps/shell/src-tauri/tauri.conf.json"):+ actual = json.loads((REPO / relative).read_text())["version"]+ if actual != version:+ raise ValueError(f"release version mismatch: {relative} is {actual}, expected {version}")def run(*args, cwd=REPO, env=None, timeout=None):diff --git a/scripts/package-standalone.py b/scripts/package-standalone.pyindex 805fd324..72b236e8 100755--- a/scripts/package-standalone.py+++ b/scripts/package-standalone.py@@ -54,6 +54,42 @@ def expected_files(target):return (EXPECTED_FILES - {"bin/hiroute", "bin/hirouted", "libexec/cliproxyapi"}) | set(names.values())+def console_name(name):+ return (isinstance(name, str) and len(name) <= 240 and name.startswith("console/")+ and all(re.fullmatch(r"[[email protected]]+", part) and part not in {".", ".."}+ for part in name.split("/")))+++def valid_inventory(names, target):+ base = expected_files(target)+ extra = set(names) - base+ # V1 archives without console files remain readable during upgrades.+ return (base <= set(names) and len(extra) <= 2048+ and (not extra or "console/index.html" in extra)+ and all(console_name(name) for name in extra))+++def console_payload(directory):+ if directory.is_symlink() or not directory.is_dir():+ raise ValueError("console assets must be a real directory")+ result = {}+ for path in sorted(directory.rglob("*")):+ if path.is_symlink():+ raise ValueError("console assets cannot contain links")+ if path.is_dir():+ continue+ name = "console/" + path.relative_to(directory).as_posix()+ if not console_name(name) or len(result) >= 2048:+ raise ValueError("console asset inventory is invalid")+ source = checked_source(path)+ if source.stat().st_size > 16 * 1024 * 1024:+ raise ValueError("console asset exceeds its size bound")+ result[name] = source+ if "console/index.html" not in result or sum(path.stat().st_size for path in result.values()) > 64 * 1024 * 1024:+ raise ValueError("console assets are incomplete or too large")+ return result++def verify_windows_image(path, target):with Path(path).open("rb") as stream:verify_windows_stream(stream, target)@@ -94,7 +130,7 @@ def digest(path):def host_target():- machine = {"AMD64": "x86_64", "arm64": "aarch64"}.get(+ machine = {"AMD64": "x86_64", "ARM64": "aarch64", "arm64": "aarch64"}.get(platform.machine(), platform.machine())system = {"Linux": "unknown-linux-gnu", "Darwin": "apple-darwin", "Windows": "pc-windows-msvc"}.get(@@ -159,6 +195,8 @@ def payload(args, notices):}for name in sorted(NOTICE_FILES):files[f"licenses/{name}"] = checked_source(notices / name)+ if getattr(args, "console_assets", None) is not None:+ files.update(console_payload(args.console_assets))if args.target.endswith("-pc-windows-msvc"):for key in names.values():verify_windows_image(files[key], args.target)@@ -261,7 +299,6 @@ def safe_members(archive, expected):def verify(manifest_path, archive_path):manifest = load_json_bytes(Path(manifest_path).read_bytes())archive = Path(archive_path)- inventory = expected_files(manifest.get("target", ""))if (not isinstance(manifest, dict)or set(manifest)@@ -276,7 +313,7 @@ def verify(manifest_path, archive_path):or len(manifest["revision"]) > 128or manifest.get("distribution") != "integration-candidate"or not isinstance(manifest.get("files"), dict)- or set(manifest["files"]) != inventory+ or not valid_inventory(manifest["files"], manifest["target"])or not isinstance(manifest.get("archive"), dict)or set(manifest["archive"]) != {"filename", "sha256", "size"}or not isinstance(manifest.get("cpa"), dict)@@ -356,6 +393,7 @@ def parser():create.add_argument("--cpa-version", required=True)create.add_argument("--cpa-license", type=Path, required=True)create.add_argument("--notices", type=Path, required=True)+ create.add_argument("--console-assets", type=Path, required=True)create.add_argument("--output", type=Path, required=True)check = sub.add_parser("verify")check.add_argument("manifest", type=Path)diff --git a/scripts/package-windows-shell.py b/scripts/package-windows-shell.pynew file mode 100644index 00000000..7b0c0b45--- /dev/null+++ b/scripts/package-windows-shell.py@@ -0,0 +1,169 @@+#!/usr/bin/env python3+"""Stage verified standalone bytes and audit Windows Desktop package identity."""+import argparse+import hashlib+import importlib.util+import json+from pathlib import Path, PurePosixPath+import re+import shutil+import subprocess+import sys+import tempfile++sys.dont_write_bytecode = True+ROOT = Path(__file__).resolve().parent.parent+SCHEMA = "hiroute.windows-desktop-package/v1"+++def module(name):+ spec = importlib.util.spec_from_file_location(name.replace("-", "_"), ROOT / "scripts" / (name + ".py"))+ value = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(value)+ return value+++def digest(path):+ sha = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ sha.update(chunk)+ return sha.hexdigest()+++def regular(path):+ for item in (path, *path.parents):+ if item.exists() and (item.is_symlink() or getattr(item.lstat(), "st_file_attributes", 0) & 0x400):+ raise ValueError("package staging contains a link or reparse point")+ if path.exists() and not path.is_file():+ raise ValueError("package staging entry is not a regular file")+++def stage(manifest, archive, destination):+ packager = module("package-standalone")+ package = packager.verify(manifest, archive)+ if package["target"] != "x86_64-pc-windows-msvc" or "console/index.html" not in package["files"]:+ raise ValueError("Windows Desktop requires the x64 package and console assets")+ payload = {name.removeprefix("bin/"): data for name, (data, _) in packager.safe_members(archive, package["files"]).items()}+ payload["package-manifest.json"] = manifest.read_bytes()+ record = destination.parent / "standalone-stage.json"+ if record.exists():+ regular(record)+ old = json.loads(record.read_text())+ if old.get("schema") != "hiroute.windows-shell-stage/v1" or not isinstance(old.get("files"), dict):+ raise ValueError("unknown standalone stage ownership")+ for name, expected in old["files"].items():+ if not safe_name(name):+ raise ValueError("unsafe stage ownership entry")+ file = destination / name+ regular(file)+ if not file.is_file() or digest(file) != expected:+ raise ValueError("an owned standalone stage entry changed")+ entries = list(destination.rglob("*"))+ if any(p.is_symlink() or getattr(p.lstat(), "st_file_attributes", 0) & 0x400 for p in entries):+ raise ValueError("standalone stage contains a link or reparse point")+ actual = {p.relative_to(destination).as_posix() for p in entries if p.is_file()}+ if actual != set(old["files"]):+ raise ValueError("foreign standalone stage entries must be preserved")+ for name in old["files"]:+ (destination / name).unlink()+ elif destination.exists() and any(destination.rglob("*")):+ raise ValueError("refuse an unowned standalone staging directory")+ for name, data in payload.items():+ if not safe_name(name):+ raise ValueError("unsafe standalone entry")+ file = destination / name+ regular(file)+ file.parent.mkdir(parents=True, exist_ok=True)+ file.write_bytes(data)+ record.write_text(json.dumps({"schema": "hiroute.windows-shell-stage/v1", "revision": package["revision"],+ "files": {name: hashlib.sha256(data).hexdigest() for name, data in payload.items()}}, indent=2) + "\n")+ return package+++def safe_name(name):+ return isinstance(name, str) and not PurePosixPath(name).is_absolute() and "\\" not in name and all(+ part not in ("", ".", "..") and re.fullmatch(r"[A-Za-z0-9_.@-]+", part) for part in name.split("/"))+++def shell_image(installer, run=None):+ """Audit the actual NSIS member, without executing the installer."""+ regular(installer)+ extractor = shutil.which("7z") or shutil.which("7zz")+ if not extractor:+ raise ValueError("7-Zip is required to audit the embedded NSIS shell")+ with tempfile.TemporaryDirectory(prefix="nsis-shell-", dir=installer.parent) as temporary:+ args = (extractor, "x", "-y", "-bd", "-r", "-o" + temporary,+ str(installer.resolve()), "hiroute-shell.exe")+ if run:+ run(*args)+ else:+ subprocess.run(args, check=True, capture_output=True, text=True)+ images = list(Path(temporary).rglob("hiroute-shell.exe"))+ if len(images) != 1:+ raise ValueError("NSIS must contain exactly one shell image")+ regular(images[0])+ image = module("windows-native-runtime-audit").image_record(+ images[0].read_bytes(), "hiroute-shell.exe", "windows-desktop-release")+ if (image["pe_machine"] != 0x8664 or image["imports"]["debug_crt"]+ or image["imports"]["release_vc_runtime"]):+ raise ValueError("Windows Desktop has an unexpected architecture or CRT dependency")+ return image+++def verify(installer, identity, revision):+ if not isinstance(identity, dict):+ raise ValueError("Windows Desktop identity must be an object")+ regular(installer)+ expected = {"schema": SCHEMA, "revision": revision, "architecture": "x86_64", "distribution": "unsigned",+ "installer_sha256": digest(installer), "installer_size": installer.stat().st_size,+ "integrity": "green", "embedded_components": "green", "native_runtime": "green"}+ if not re.fullmatch(r"[0-9a-f]{40}", revision) or any(identity.get(k) != v for k, v in expected.items()):+ raise ValueError("Windows Desktop identity lacks matching native acceptance")+ if installer.name != f'HiRoute-{identity.get("version")}-{revision[:12]}-windows-x86_64-setup.exe':+ raise ValueError("Windows Desktop installer identity differs from its filename")+ evidence = identity.get("native_evidence", {})+ runs = evidence.get("runs", []) if isinstance(evidence, dict) else []+ required = json.loads((ROOT / "scripts/windows-desktop-cases.json").read_text())+ if (not isinstance(runs, list) or len(runs) != len(required) or any(not isinstance(run, dict) for run in runs)+ or {run.get("platform") for run in runs} != set(required)):+ raise ValueError("native evidence must cover Windows 11 x64 and the Server selection")+ for native in runs:+ scenarios = native.get("scenarios", {})+ if (native.get("revision") != revision or native.get("installer_sha256") != expected["installer_sha256"]+ or native.get("standard_user") is not True or native.get("architecture") != "AMD64"+ or not native.get("os_version") or not isinstance(scenarios, dict)+ or any(scenarios.get(case) != "green" for case in required[native["platform"]])+ or any(value != "green" for value in scenarios.values())):+ raise ValueError("native evidence does not bind all standard-user scenarios to this artifact")+ return identity+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="action", required=True)+ p = sub.add_parser("stage")+ for name in ("manifest", "archive", "destination"):+ p.add_argument("--" + name, type=Path, required=True)+ p = sub.add_parser("verify")+ p.add_argument("--installer", type=Path, required=True)+ p.add_argument("--identity", type=Path, required=True)+ p.add_argument("--revision", required=True)+ p = sub.add_parser("image")+ p.add_argument("--installer", type=Path, required=True)+ args = parser.parse_args()+ if args.action == "image":+ result = shell_image(args.installer)+ elif args.action == "stage":+ result = stage(args.manifest, args.archive, args.destination)+ else:+ result = verify(args.installer, json.loads(args.identity.read_text()), args.revision)+ print(json.dumps(result, indent=2))+++if __name__ == "__main__":+ try:+ main()+ except (OSError, ValueError) as error:+ print(str(error), file=sys.stderr)+ raise SystemExit(1)diff --git a/scripts/release-contracts.py b/scripts/release-contracts.pyindex 2711d30f..1e5f38b8 100644--- a/scripts/release-contracts.py+++ b/scripts/release-contracts.py@@ -61,7 +61,7 @@ def create_snapshot(repo, release, manifest, revision, repository):require(resolved == revision, "tag differs from the verified package source")channel = "preview" if release["isPrerelease"] else "stable"require(channel != "stable" or "-" not in tag, "prerelease tag cannot advance stable baseline")- require(manifest.get("schema") == "hiroute.website.releases/v2", "unknown release manifest")+ require(manifest.get("schema") in {"hiroute.website.releases/v2", "hiroute.website.releases/v3"}, "unknown release manifest")records = [item for item in manifest["releases"] if item["version"] == tag[1:]]require(len(records) == 1, "release manifest must contain exactly one matching version")record = records[0]diff --git a/scripts/test-build-release.py b/scripts/test-build-release.pyindex 06441538..e698038a 100644--- a/scripts/test-build-release.py+++ b/scripts/test-build-release.py@@ -3,6 +3,7 @@from contextlib import nullcontext, redirect_stdoutimport importlib.utilimport io+import hashlibimport jsonimport osimport re@@ -19,7 +20,7 @@ REPO = Path(__file__).resolve().parent.parentspec = importlib.util.spec_from_file_location("build_release", REPO / "scripts/build-release.py")builder = importlib.util.module_from_spec(spec)spec.loader.exec_module(builder)-MODULES = {name: builder.module(name) for name in ("package-desktop", "package-standalone", "build-cpa", "local-rust", "linux-release-abi", "windows-native-runtime-audit")}+MODULES = {name: builder.module(name) for name in ("package-desktop", "package-standalone", "package-windows-shell", "build-cpa", "local-rust", "linux-release-abi", "windows-native-runtime-audit")}PE_FIXTURES = builder.module("test-windows-native-runtime-audit")@@ -76,6 +77,16 @@ class CandidateTests(unittest.TestCase):return json.dumps({"target_directory": str(self.root / "target")})if args[0] in ("cargo", "rustc") and args[1] == "--version":return "fixture toolchain"+ if args[0] in ("npm", "npm.cmd"):+ if args[1:3] == ("run", "build"):+ assets = self.root / "apps/desktop/dist"+ (assets / "assets").mkdir(parents=True)+ (assets / "index.html").write_text('<script src="/assets/app.js"></script>')+ (assets / "assets/app.js").write_text('console.info("fixture")')+ for path in assets.rglob("*"):+ if path.is_file():+ path.chmod(0o644)+ return ""if args[:2] == ("cargo", "build"):self.assertIn("--locked", args)self.assertEqual(args[args.index("--target") + 1], self.target)@@ -125,6 +136,9 @@ class CandidateTests(unittest.TestCase):self.assertEqual(result["status"], "awaiting_runtime")self.assertEqual(set(result["linux_abi"]["files"]), {"bin/hiroute", "bin/hirouted", "libexec/cliproxyapi"})self.assertEqual(result["website_artifact"]["architecture"], "aarch64")+ self.assertEqual(sum(args[:3] == ("npm", "run", "build") for args in self.commands), 1)+ manifest = next(Path(result["assets"]).glob("*.json"))+ self.assertIn("console/index.html", json.loads(manifest.read_text())["files"])artifacts = list(Path(result["assets"]).iterdir())self.assertEqual(len(artifacts), 2)catalog = self.root / "releases.json"@@ -200,23 +214,16 @@ class CandidateTests(unittest.TestCase):def test_windows_candidate_is_verified_as_native_pe_and_consumed_by_release_verifier(self):result = self.build_windows_candidate()self.assertEqual(result["status"], "awaiting_runtime")- self.assertEqual(result["website_artifact"]["platform"], "Windows")- self.assertEqual(result["website_artifact"]["target"], self.target)+ self.assertNotIn("website_artifact", result)+ self.assertNotIn("assets", result)+ self.assertEqual(result["publication"], "internal-only")+ self.assertEqual(result["internal_payload"]["target"], self.target)+ self.assertEqual(len(list(Path(result["internal_payloads"]).iterdir())), 2)self.assertNotIn("linux_abi", result)crt = result["windows_crt_build"]self.assertEqual(crt["dependency_gate"], "green")self.assertEqual({image["path"] for image in crt["images"]},{"bin/hiroute.exe", "bin/hirouted.exe", "libexec/cliproxyapi.exe"})- catalog = self.root / "releases.json"- catalog.write_text(json.dumps({"schema": "hiroute.website.releases/v2", "releases": [{- "version": self.version, "channel": "stable", "published_at": "2026-10-08T00:00:00Z",- "notes": {"zh": "测试", "en": "Fixture"}, "artifacts": [result["website_artifact"]],- }]}))- verified = subprocess.run(["node", str(REPO / "apps/website/scripts/release-manifest.mjs"),- "verify-assets", str(catalog), "--tag", f"v{self.version}", "--revision", "a" * 40,- "--asset-dir", result["assets"]], text=True, capture_output=True)- self.assertEqual(verified.returncode, 0, verified.stderr)- self.assertIn("2 release asset(s) verified", verified.stdout)def test_release_vc_dependency_in_delayed_daemon_import_cannot_publish_assets(self):with self.assertRaisesRegex(ValueError, "unexpected CRT dependency"):@@ -226,6 +233,104 @@ class CandidateTests(unittest.TestCase):self.assertNotIn("website_artifact", result)self.assertFalse((self.candidate.output / "assets").exists())+ def test_windows_shell_stage_uses_verified_package_bytes_and_preserves_foreign_files(self):+ result = self.build_windows_candidate()+ assets = Path(result["internal_payloads"])+ archive = next(assets.glob("*.tar.gz"))+ manifest = next(assets.glob("*.json"))+ destination = self.root / "shell-resources/standalone"+ packager = MODULES["package-windows-shell"]+ value = packager.stage(manifest, archive, destination)+ self.assertEqual(value["revision"], "a" * 40)+ self.assertTrue((destination / "hiroute.exe").read_bytes().startswith(b"MZ"))+ self.assertEqual((destination / "package-manifest.json").read_bytes(), manifest.read_bytes())+ self.assertTrue((destination / "console/index.html").is_file())+ packager.stage(manifest, archive, destination)+ foreign = destination / "personal.txt"+ foreign.write_text("preserve me")+ with self.assertRaisesRegex(ValueError, "foreign"):+ packager.stage(manifest, archive, destination)+ self.assertEqual(foreign.read_text(), "preserve me")+ (destination / "hiroute.exe").write_bytes(b"changed owned entry")+ with self.assertRaisesRegex(ValueError, "owned standalone stage entry changed"):+ packager.stage(manifest, archive, destination)+ self.assertEqual((destination / "hiroute.exe").read_bytes(), b"changed owned entry")++ def test_windows_shell_identity_measures_actual_nsis_member_and_crt_imports(self):+ result = self.build_windows_candidate()+ payloads = Path(result["internal_payloads"])+ files = [next(payloads.glob("*.tar.gz")), next(payloads.glob("*.json"))]+ executable = self.root / "target" / self.target / "release/hiroute-shell.exe"+ delayed = []++ def command(*args, **kwargs):+ if "--no-bundle" in args:+ pe(executable, 0x8664)+ if "bundle" in args:+ pe(executable, 0x8664)+ executable.write_bytes(executable.read_bytes() + b"workspace PE resources")+ installer = executable.parent / "bundle/nsis" / f"HiRoute_{self.version}_x64-setup.exe"+ installer.parent.mkdir(parents=True, exist_ok=True)+ installer.write_bytes(b"fixture NSIS package")+ if args[0] == "7z-fixture":+ directory = Path(next(a[2:] for a in args if a.startswith("-o")))+ pe(directory / "hiroute-shell.exe", 0x8664, delayed)+ image = directory / "hiroute-shell.exe"+ image.write_bytes(image.read_bytes() + b"actual NSIS member")+ return ""++ with patch.object(self.candidate, "standalone", return_value=(None, files)), \+ patch.object(self.candidate, "run", side_effect=command), \+ patch.object(MODULES["package-windows-shell"].shutil, "which", return_value="7z-fixture"):+ self.candidate.desktop_windows()+ identity = self.candidate.result["desktop_result"]+ self.assertEqual(identity["shell_image"]["sha256"], hashlib.sha256(PE_FIXTURES.image() + b"actual NSIS member").hexdigest())+ self.assertNotEqual(identity["shell_image"]["sha256"], MODULES["package-windows-shell"].digest(executable))+ delayed.append("VCRUNTIME140_1.dll")+ with self.assertRaisesRegex(ValueError, "CRT dependency"):+ self.candidate.desktop_windows()++ def test_nsis_shell_audit_rejects_missing_tool_or_ambiguous_members(self):+ packager = MODULES["package-windows-shell"]+ installer = self.root / "fixture.exe"+ installer.write_bytes(b"fixture NSIS package")+ with patch.object(packager.shutil, "which", return_value=None):+ with self.assertRaisesRegex(ValueError, "7-Zip is required"):+ packager.shell_image(installer)+ for count in (0, 2):+ def extract(*args):+ directory = Path(next(a[2:] for a in args if a.startswith("-o")))+ for i in range(count):+ pe(directory / str(i) / "hiroute-shell.exe", 0x8664)+ with patch.object(packager.shutil, "which", return_value="7z-fixture"):+ with self.assertRaisesRegex(ValueError, "exactly one shell image"):+ packager.shell_image(installer, extract)++ def test_desktop_publication_rejects_partial_or_misbound_native_attestation(self):+ # Verifier-shape regression only; fabricated JSON is never installation evidence.+ packager = MODULES["package-windows-shell"]+ installer = self.root / f"HiRoute-{self.version}-aaaaaaaaaaaa-windows-x86_64-setup.exe"+ installer.write_bytes(b"fixture installer")+ identity = {"schema": packager.SCHEMA, "version": self.version, "revision": "a" * 40,+ "architecture": "x86_64", "distribution": "unsigned", "integrity": "green",+ "embedded_components": "green", "native_runtime": "green", "installer_sha256": packager.digest(installer),+ "installer_size": installer.stat().st_size}+ with self.assertRaisesRegex(ValueError, "Windows 11"):+ packager.verify(installer, identity, "a" * 40)+ required = json.loads((REPO / "scripts/windows-desktop-cases.json").read_text())+ identity["native_evidence"] = {"runs": [{"platform": platform_name, "revision": "a" * 40,+ "installer_sha256": packager.digest(installer), "standard_user": True, "architecture": "AMD64",+ "os_version": "fixture-only", "scenarios": dict.fromkeys(cases, "green")} for platform_name, cases in required.items()]}+ self.assertIs(packager.verify(installer, identity, "a" * 40), identity)+ for key, value in (("revision", "b" * 40), ("standard_user", False), ("architecture", "ARM64")):+ altered = json.loads(json.dumps(identity))+ altered["native_evidence"]["runs"][0][key] = value+ with self.assertRaisesRegex(ValueError, "all standard-user"):+ packager.verify(installer, altered, "a" * 40)+ identity["native_evidence"]["runs"][0]["scenarios"].pop("update.killed-resume")+ with self.assertRaisesRegex(ValueError, "all standard-user"):+ packager.verify(installer, identity, "a" * 40)+def test_windows_release_rejects_ambient_compiler_overrides_without_affecting_other_contexts(self):for name in ("RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS", "CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS","CMAKE_TOOLCHAIN_FILE", "HOST_CMAKE_TOOLCHAIN_FILE", "CXXFLAGS_x86_64_pc_windows_msvc"):@@ -333,10 +438,10 @@ class HostedReleasePolicyTests(unittest.TestCase):events = re.findall(r'^ ([a-z_]+):', triggers, re.M)self.assertEqual(set(events), {'workflow_dispatch', 'workflow_call'})self.assertNotIn('continue-on-error:', workflow)- self.assertEqual(workflow.count('ref: ${{ github.sha }}'), 2)+ self.assertEqual(workflow.count('ref: ${{ github.sha }}'), 3)self.assertEqual(workflow.count("-Phase '${{ inputs.scope != '' && inputs.scope != 'all' && 'focused' || 'final' }}'"), 2)- self.assertEqual(workflow.count('-ExpectedSha $env:GITHUB_SHA'), 2)+ self.assertEqual(workflow.count('-ExpectedSha $env:GITHUB_SHA'), 3)def test_manual_scope_cannot_narrow_the_reusable_release_gate(self):workflow = (REPO / '.github/workflows/windows-headless.yml').read_text()@@ -349,7 +454,9 @@ class HostedReleasePolicyTests(unittest.TestCase):matrix = ("scope: ${{ fromJSON(inputs.scope != '' && inputs.scope != 'all' && ""format('[\"{0}\"]', inputs.scope) || ""'[\"components\",\"core\",\"product\",\"background\",\"agents\"]') }}")- self.assertEqual(workflow.count(matrix), 2)+ self.assertEqual(workflow.count(matrix), 1)+ self.assertIn("windows11-arm-install:", workflow)+ self.assertIn("-Scope install", workflow)def test_windows_replay_requires_successful_producers(self):workflow = (REPO / '.github/workflows/windows-headless.yml').read_text()@@ -357,7 +464,8 @@ class HostedReleasePolicyTests(unittest.TestCase):self.assertRegex(replay, r'(?m)^ needs: native$')# Default job success admission skips replay after failed or cancelled# producers; always() remains appropriate only for evidence upload steps.- self.assertNotRegex(replay, r'(?m)^ (if|continue-on-error):')+ self.assertIn("if: inputs.scope != 'background'", replay)+ self.assertNotRegex(replay, r'(?m)^ continue-on-error:')def test_only_windows_assets_require_windows_validation(self):workflow = (REPO / '.github/workflows/build-release.yml').read_text()@@ -389,7 +497,8 @@ class HostedReleasePolicyTests(unittest.TestCase):def test_pr_windows_check_is_bounded_cached_and_fails_closed(self):workflow = (REPO / '.github/workflows/windows-compile.yml').read_text()triggers = workflow.split('\non:\n', 1)[1].split('\npermissions:', 1)[0]- self.assertEqual(re.findall(r'^ ([a-z_]+):', triggers, re.M), ['pull_request'])+ self.assertEqual(re.findall(r'^ ([a-z_]+):', triggers, re.M), ['workflow_dispatch', 'pull_request'])+ self.assertIn('github.event.pull_request.number || github.run_id', workflow)for path in ('crates/**', 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml','.cargo/**', 'assets/**', 'vendor/**', 'tools/**', 'scripts/**','.github/workflows/windows-compile.yml'):@@ -405,7 +514,16 @@ class HostedReleasePolicyTests(unittest.TestCase):'-p hiroute-cli -p hiroute-daemon -p hiroute-platform ''-p hiroute-local-storage --all-targets', workflow)self.assertIn("if ($LASTEXITCODE -ne 0) { throw", workflow)- self.assertNotIn('cargo test', workflow)+ component_tests = [line.strip() for line in workflow.splitlines()+ if line.strip().startswith('cargo test ')]+ self.assertEqual(component_tests, [+ 'cargo test --locked --target x86_64-pc-windows-msvc '+ '-p hiroute-host-runtime --lib standalone_install::'])+ self.assertIn("throw 'Windows installation component regressions failed'", workflow)+ self.assertIn('component fixtures, not standard-user installation acceptance', workflow)+ self.assertNotIn('--ignored', workflow)+ self.assertNotIn('--test windows_headless', workflow)+ self.assertNotIn('--test windows_desktop', workflow)self.assertNotIn('windows-headless-ci.ps1', workflow)diff --git a/scripts/test-linux-release.py b/scripts/test-linux-release.pyindex 0ebe0966..613a6380 100644--- a/scripts/test-linux-release.py+++ b/scripts/test-linux-release.py@@ -200,11 +200,16 @@ else: raise SystemExit(2)'packages': [{'name': 'fixture'}], 'documents': [{'name': 'fixture'}],}))for path in notices.iterdir(): path.chmod(0o644)+ console = self.root / 'console'+ console.mkdir(exist_ok=True)+ (console / 'index.html').write_text('<main>Runtime fixture</main>')+ (console / 'index.html').chmod(0o644)args = self.packager.parser().parse_args(['build', '--version', '0.2.0', '--revision', 'a' * 40, '--target', self.target,'--hiroute', str(executable), '--hirouted', str(executable), '--cpa-binary', str(executable),'--cpa-version', 'fixture', '--cpa-license', str(license_path),- '--notices', str(notices), '--output', str(self.root / 'package'),+ '--notices', str(notices), '--console-assets', str(console),+ '--output', str(self.root / 'package'),])output = io.StringIO()with redirect_stdout(output), patch.object(self.packager, 'REPO', self.root):diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.pyindex 2181294b..d2ac191a 100644--- a/scripts/test-native-context-product.py+++ b/scripts/test-native-context-product.py@@ -8,6 +8,7 @@ from pathlib import Pathimport subprocessimport sysimport tempfile+import threadingimport unittestfrom unittest.mock import Mock, patch@@ -244,6 +245,40 @@ with patch('publication_product.secrets.SystemRandom') as chooser:def test_messages_native_wire_has_typed_terminal_frames(self):self.assert_native_wire('claude', 'messages')+ def test_length_terminal_waits_for_the_stream_prefix_witness(self):+ (self.root / 'native-context.json').write_text('{}')+ server = fixture.NativeContextUpstream(self.root)+ connection = http.client.HTTPConnection(*server.server.server_address, timeout=3)+ entered, release = threading.Event(), threading.Event()+ server.reply = lambda *_: dict(kind='text', text='incomplete attempt',+ recoverable_length=True, input_tokens=10000)++ def before_incomplete():+ entered.set()+ assert release.wait(3), 'stream prefix witness was never released'++ server.before_incomplete = before_incomplete+ try:+ connection.request('POST', '/v1/responses', json.dumps({'model': server.model}),+ {'Authorization': 'Bearer ' + server.token})+ response = connection.getresponse()+ prefix = []+ while True:+ line = response.readline().decode()+ self.assertTrue(line, 'stream ended before the text prefix')+ prefix.append(line)+ if line.startswith('data: ') and 'response.output_text.delta' in line:+ break+ self.assertIn('incomplete attempt', ''.join(prefix))+ self.assertNotIn('response.incomplete', ''.join(prefix))+ self.assertTrue(entered.wait(1), 'length terminal did not wait for its witness')+ release.set()+ self.assertIn('response.incomplete', response.read().decode())+ finally:+ release.set()+ connection.close()+ server.close()+def test_loopback_server_rejects_wrong_route_and_records_old_context_red(self):value = self.context('codex')(self.root / 'native-context.json').write_text(json.dumps(value))diff --git a/scripts/test-plan.py b/scripts/test-plan.pyindex a2c65494..1df5800a 100644--- a/scripts/test-plan.py+++ b/scripts/test-plan.py@@ -80,7 +80,7 @@ def project_agent_tooling(path):WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}RELEASE_BUILD_TESTS = ("test-build-cpa.py", "test-build-release.py", "test-linux-release.py", "test-package-desktop.py",- "test-standalone-install.py", "test-standalone-windows.py", "test-windows-ci-package.py", "test-third-party-licenses.py")+ "test-standalone-install.py", "test-windows-ci-package.py", "test-third-party-licenses.py")RELEASE_BUILD_TOOLING = {"scripts/linux-release-abi.py", "scripts/linux-release-runtime.py","scripts/linux-release-container.py", "scripts/linux-release-baseline.json","scripts/linux-release.Dockerfile", ".github/workflows/build-release.yml",@@ -89,7 +89,7 @@ RELEASE_BUILD_TOOLING = {"scripts/linux-release-abi.py", "scripts/linux-release-".github/workflows/windows-headless.yml", "scripts/build-release.py","scripts/build-cpa.py", "scripts/package-desktop.py","scripts/package-standalone.py", "scripts/install-standalone.py",- "scripts/install-standalone-windows.py", "scripts/windows-ci-package.py",+ "scripts/windows-ci-package.py","scripts/collect-third-party-licenses.py",*("scripts/" + name for name in RELEASE_BUILD_TESTS)}WEBSITE_PREFIXES = ("apps/website/", ".github/scripts/", "news/", "experiments/")@@ -103,6 +103,7 @@ HOSTED_BACKEND_EXECUTION = {}VALIDATION_TOOLING = {"scripts/validation.py", "scripts/validation-host.py", "scripts/test-validation.py","scripts/windows-dev.py", "scripts/windows-dev-host.py", "scripts/test-windows-dev.py",+ "scripts/windows-desktop-session.py", "scripts/windows-dev-profile.py","scripts/validation-report.py", "scripts/test-validation-report.py","scripts/ci-run.py", "scripts/test-ci-run.py","scripts/ci-shards.py", "scripts/test-ci-shards.py",diff --git a/scripts/test-standalone-install.py b/scripts/test-standalone-install.pyindex b1dc12fb..2a37c744 100755--- a/scripts/test-standalone-install.py+++ b/scripts/test-standalone-install.py@@ -85,7 +85,7 @@ class StandaloneFixture(unittest.TestCase):for path in self.notices.iterdir():path.chmod(0o644)- def build(self, version="0.1.0"):+ def build(self, version="0.1.0", console_assets=None):args = argparse.Namespace(target=installer.host_target(),version=version,@@ -97,6 +97,7 @@ class StandaloneFixture(unittest.TestCase):cpa_license=self.license,notices=self.notices,output=self.output,+ console_assets=console_assets,)with patch.object(package, "REPO", self.repo), patch("builtins.print"):package.build(args)@@ -122,7 +123,98 @@ class StandaloneFixture(unittest.TestCase):)+class ConsoleInstallationTests(StandaloneFixture):+ @patch.object(installer.platform, "system", return_value="Linux")+ def test_console_configuration_is_private_preserved_and_transactionally_rolled_back(self, _system):+ manifest, archive = self.build()+ args = self.install_args(manifest, archive)+ args.console_mode = "network"+ args.console_listen = "0.0.0.0"+ args.console_advertise_address = "192.0.2.10"+ args.console_port = 8123+ args.allow_plaintext_network = True+ with self.environment(), patch.object(installer, "desktop_conflict", return_value=False), patch.object(installer.subprocess, "run"), patch("builtins.print"):+ installer.install(args)+ config = self.home / ".state/hiroute/console-listener.json"+ original = config.read_bytes()+ value = json.loads(original)+ self.assertEqual(value["desired"]["mode"], "network")+ self.assertEqual(value["desired"]["port"], 8123)+ self.assertEqual(value["desired"]["advertise_address"], "192.0.2.10")+ self.assertEqual(config.stat().st_mode & 0o777, 0o600)+ installer.install(self.install_args(manifest, archive))+ self.assertEqual(config.read_bytes(), original, "an upgrade without options must preserve the exact configuration")+ args.console_port = 8124+ replace = installer.os.replace+ failed = False+ def fail_marker(source, destination):+ nonlocal failed+ if Path(destination).name == "standalone.json" and not failed:+ failed = True+ raise OSError("injected commit failure")+ return replace(source, destination)+ with patch.object(installer.os, "replace", side_effect=fail_marker):+ with self.assertRaisesRegex(OSError, "injected"):+ installer.install(args)+ self.assertTrue(failed)+ self.assertEqual(config.read_bytes(), original, "configuration participates in the install rollback")++ @patch.object(installer.platform, "system", return_value="Linux")+ def test_invalid_console_options_fail_before_install_writes(self, _system):+ cases = [+ ["--console-mode", "network", "--console-listen", "192.0.2.1"],+ ["--console-mode", "network", "--console-listen", "0.0.0.0", "--allow-plaintext-network"],+ ["--console-listen", "::", "--console-advertise-address", "192.0.2.1", "--allow-plaintext-network"],+ ["--console-mode", "loopback", "--console-listen", "192.0.2.1"],+ ["--console-port", "0"], ["--console-port", "65536"],+ ]+ for options in cases:+ args = installer.parser().parse_args(["install", *options])+ with self.environment(), self.assertRaises(ValueError), patch.object(installer, "acquire") as acquire:+ installer.install(args)+ acquire.assert_not_called()+ self.assertFalse((self.home / ".local").exists())++ @patch.object(installer.platform, "system", return_value="Linux")+ def test_explicit_configuration_refuses_foreign_link_without_modifying_it(self, _system):+ manifest, archive = self.build()+ args = self.install_args(manifest, archive)+ args.console_mode = "loopback"+ state = self.home / ".state/hiroute"+ state.mkdir(parents=True, mode=0o700)+ foreign = self.root / "foreign.json"+ foreign.write_text("foreign")+ config = state / "console-listener.json"+ config.symlink_to(foreign)+ with self.environment(), patch.object(installer, "desktop_conflict", return_value=False), self.assertRaises(OSError):+ installer.install(args)+ self.assertEqual(foreign.read_text(), "foreign")+ self.assertTrue(config.is_symlink())+ self.assertFalse((self.home / ".local/share/hiroute/standalone.json").exists())++class PackageTests(StandaloneFixture):+ def test_console_assets_are_verified_and_installed_with_the_existing_package(self):+ assets = self.root / "console"+ (assets / "assets").mkdir(parents=True)+ (assets / "index.html").write_text('<script src="/assets/app.js"></script>')+ (assets / "assets/app.js").write_text('console.info("test")')+ for path in assets.rglob("*"):+ if path.is_file():+ path.chmod(0o644)+ manifest, archive = self.build(console_assets=assets)+ verified = package.verify(manifest, archive)+ self.assertEqual(verified["files"]["console/index.html"]["sha256"], package.digest(assets / "index.html"))+ with self.environment(), patch.object(installer, "desktop_conflict", return_value=False), patch.object(installer.subprocess, "run"), patch("builtins.print"):+ installer.install(self.install_args(manifest, archive))+ marker = json.loads((self.home / ".local/share/hiroute/standalone.json").read_text())+ self.assertEqual((Path(marker["install_root"]) / "console/assets/app.js").read_bytes(), (assets / "assets/app.js").read_bytes())+ for name in ("console/../escape", "console/.hidden/../escape", "console//bad", "console/bad\\name", "unexpected.txt"):+ self.assertFalse(package.valid_inventory(package.expected_files(installer.host_target()) | {"console/index.html", name}, installer.host_target()))+ (assets / "unsafe.js").symlink_to(assets / "index.html")+ with self.assertRaisesRegex(ValueError, "links"):+ package.console_payload(assets)+def test_archive_is_deterministic_and_tampering_is_rejected(self):manifest, archive = self.build()first = archive.read_bytes()diff --git a/scripts/test-standalone-windows.py b/scripts/test-standalone-windows.pydeleted file mode 100644index e9317db7..00000000--- a/scripts/test-standalone-windows.py+++ /dev/null@@ -1,254 +0,0 @@-#!/usr/bin/env python3-"""Deterministic package and install-recovery guards; no product-green claim."""-import importlib.util-import json-from pathlib import Path-import struct-import tempfile-import unittest-from unittest.mock import patch-from contextlib import nullcontext-from types import SimpleNamespace---def load(name, filename):- spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---package = load("windows_package", "package-standalone.py")-installer = load("windows_install", "install-standalone-windows.py")---class WindowsPackage(unittest.TestCase):- def test_windows_package_publishes_its_platform_guide_under_the_existing_logical_name(self):- with tempfile.TemporaryDirectory() as directory:- root = Path(directory)- inputs = ["LICENSE", "CPA-LICENSE", "assets/skills/hiroute-management/SKILL.md",- "docs/standalone-cli.md", "docs/standalone-windows.md"]- for name in inputs:- path = root / name; path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(name); path.chmod(0o644)- for name in package.NOTICE_FILES:- path = root / "notices" / name; path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(name); path.chmod(0o644)- image = root / "image.exe"- body = bytearray(70); body[:2] = b"MZ"; struct.pack_into("<I", body, 0x3C, 64)- body[64:68] = b"PE\0\0"; struct.pack_into("<H", body, 68, 0x8664)- image.write_bytes(body); image.chmod(0o755)- arguments = SimpleNamespace(target="x86_64-pc-windows-msvc", hiroute=image,- hirouted=image, cpa_binary=image, cpa_license=root / "CPA-LICENSE")- with patch.object(package, "REPO", root):- windows = package.payload(arguments, root / "notices")- self.assertEqual(windows["docs/standalone-cli.md"].read_text(), "docs/standalone-windows.md")- arguments.target = "x86_64-unknown-linux-gnu"- linux = package.payload(arguments, root / "notices")- self.assertEqual(linux["docs/standalone-cli.md"].read_text(), "docs/standalone-cli.md")-- def test_inventory_is_closed_and_keeps_one_package_schema(self):- self.assertEqual(package.SCHEMA, "hiroute.standalone-package/v1")- files = package.expected_files("x86_64-pc-windows-msvc")- self.assertIn("bin/hiroute.exe", files)- self.assertIn("bin/hirouted.exe", files)- self.assertIn("libexec/cliproxyapi.exe", files)- self.assertNotIn("bin/hiroute", files)- self.assertEqual(len(files), len(package.EXPECTED_FILES))-- def test_pe_architecture_is_verified_before_packaging(self):- with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "hiroute.exe"- body = bytearray(70)- body[:2] = b"MZ"- struct.pack_into("<I", body, 0x3C, 64)- body[64:68] = b"PE\0\0"- struct.pack_into("<H", body, 68, 0x8664)- path.write_bytes(body)- package.verify_windows_image(path, "x86_64-pc-windows-msvc")- with self.assertRaises(ValueError):- package.verify_windows_image(path, "aarch64-pc-windows-msvc")- path.write_bytes(b"not an executable")- with self.assertRaises(ValueError):- package.verify_windows_image(path, "x86_64-pc-windows-msvc")-- def test_external_archive_cannot_hide_another_pe_machine_behind_matching_hashes(self):- with tempfile.TemporaryDirectory() as directory:- root = Path(directory).resolve(); target = "x86_64-pc-windows-msvc"- files = {}- for index, name in enumerate(sorted(package.expected_files(target))):- path = root / str(index)- if name in package.executable_names(target).values():- body = bytearray(70); body[:2] = b"MZ"; struct.pack_into("<I", body, 0x3C, 64)- body[64:68] = b"PE\0\0"; struct.pack_into("<H", body, 68, 0xAA64)- path.write_bytes(body)- else:- path.write_bytes(b"synthetic package fixture")- files[name] = path- archive = root / "candidate.tar.gz"; again = root / "again.tar.gz"- package.deterministic_archive(archive, files); package.deterministic_archive(again, files)- self.assertEqual(archive.read_bytes(), again.read_bytes())- inventory = {name: {"sha256": package.digest(path), "size": path.stat().st_size,- "mode": "executable" if name.startswith(("bin/", "libexec/")) else "read_only"} for name, path in files.items()}- manifest = {"schema": package.SCHEMA, "version": "0.1.0", "revision": "fixture",- "target": target, "distribution": "integration-candidate", "files": inventory,- "archive": {"filename": archive.name, "sha256": package.digest(archive), "size": archive.stat().st_size},- "cpa": {"version": "fixture", "sha256": inventory[package.executable_names(target)["cpa"]]["sha256"]}}- path = root / "manifest.json"; path.write_text(json.dumps(manifest))- with self.assertRaisesRegex(ValueError, "architecture"):- package.verify(path, archive)---class WindowsRecovery(unittest.TestCase):- def fixture(self, directory, operation="install", old=True):- root = Path(directory).resolve(); data = root / "data"; (data / "service").mkdir(parents=True)- bin_root = root / ".local/bin"; bin_root.mkdir(parents=True)- marker = data / "standalone.json"; definition = data / "service/windows-background.json"- layout = {"home": str(root), "data_root": str(data), "marker_path": str(marker), "service_definition": str(definition)}- old_marker = {"version": "0.1.0", "target": "x86_64-pc-windows-msvc", "install_root": str(root / "old")} if old else None- old_definition = {"manager": "task", "daemon": "old"} if old else None- new_marker = {"version": "0.2.0", "target": "x86_64-pc-windows-msvc", "install_root": str(root / "new")}- new_definition = {"manager": "task", "daemon": "new"}- destination = bin_root / "hiroute.exe"; source = root / "source"; source.write_bytes(b"new")- backup = data / "service/install-backups/transaction/0"; backup.parent.mkdir(parents=True)- if old:- backup.write_bytes(b"old")- destination.write_bytes(b"new")- item = {"destination": str(destination), "source": str(source), "backup": str(backup),- "old_sha256": package.digest(backup) if old else None, "new_sha256": package.digest(source), "kind": "hardlink"}- journal = {"schema": installer.JOURNAL_SCHEMA, "operation": operation, "phase": "prepared",- "old_marker": old_marker, "new_marker": new_marker, "old_definition": old_definition,- "new_definition": new_definition, "files": [item]}- journal_path = data / "service/install-journal.json"; journal_path.write_text(json.dumps(journal))- marker.write_text(json.dumps(new_marker)); definition.write_text(json.dumps(new_definition))- return layout, journal, journal_path, destination-- @staticmethod- def write_record(_cli, path, value):- Path(path).write_text(json.dumps(value))-- def test_first_install_recovery_removes_only_published_new_entries(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory, old=False)- with patch.object(installer, "native", return_value={}) as native, patch.object(installer, "write_record", self.write_record), patch.object(installer, "publish_marker", lambda _cli, value: self.write_record(_cli, layout["marker_path"], value)):- installer.recover(Path(directory) / "hiroute.exe", layout, None)- native.assert_called_once_with(Path(directory) / "hiroute.exe", ["uninstall"])- self.assertFalse(destination.exists()); self.assertFalse(path.exists())- self.assertFalse(Path(layout["marker_path"]).exists()); self.assertFalse(Path(layout["service_definition"]).exists())-- def test_upgrade_recovery_republishes_old_marker_and_registration_before_rollback(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory)- registrations = []- def register(_cli, manager, _password):- self.assertEqual(installer.read_json(layout["marker_path"]), journal["old_marker"])- self.assertEqual(installer.read_json(layout["service_definition"]), journal["new_definition"])- registrations.append(manager)- self.write_record(_cli, layout["service_definition"], journal["old_definition"])- with patch.object(installer, "native", return_value={}), patch.object(installer, "write_record", self.write_record), patch.object(installer, "publish_marker", lambda _cli, value: self.write_record(_cli, layout["marker_path"], value)), patch.object(installer, "manager_install", register):- installer.recover(Path(directory) / "hiroute.exe", layout, None)- self.assertEqual(registrations, ["task"]); self.assertEqual(destination.read_bytes(), b"old")- self.assertFalse(path.exists())-- def test_pending_manager_delete_retains_prepared_journal_and_owned_files(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory, operation="uninstall")- with patch.object(installer, "native", side_effect=ValueError("service deletion pending")):- with self.assertRaises(ValueError):- installer.recover(Path(directory) / "hiroute.exe", layout, None)- self.assertEqual(installer.read_json(path), journal); self.assertEqual(destination.read_bytes(), b"new")-- def test_committed_install_cleans_backups_without_reverting_new_bytes(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory)- journal["phase"] = "committed"; path.write_text(json.dumps(journal))- with patch.object(installer, "native") as native:- installer.recover(Path(directory) / "hiroute.exe", layout, None)- native.assert_not_called(); self.assertEqual(destination.read_bytes(), b"new")- self.assertFalse(path.exists()); self.assertFalse(Path(journal["files"][0]["backup"]).exists())-- def test_external_scm_reopen_replays_publication_but_keeps_admission_journal(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory)- journal["new_definition"] = {"manager": "scm", "owner_sid": "S-1-5-21-fixture"}- path.write_text(json.dumps(journal)); Path(layout["marker_path"]).write_text(json.dumps(journal["old_marker"]))- destination.write_bytes(b"old")- with patch.object(installer, "native", return_value={}) as native, patch.object(installer, "publish_marker", lambda cli, value: self.write_record(cli, layout["marker_path"], value)), patch.object(installer, "pending_admin") as pending:- self.assertTrue(installer.recover(Path(directory) / "hiroute.exe", layout, None, external_manager=True))- native.assert_called_once_with(Path(directory) / "hiroute.exe", ["stop"])- pending.assert_called_once(); self.assertEqual(destination.read_bytes(), b"new")- self.assertEqual(installer.read_json(path)["phase"], "prepared")- self.assertEqual(installer.read_json(layout["marker_path"]), journal["new_marker"])-- def test_owner_finalize_requires_native_machine_proof_before_commit(self):- with tempfile.TemporaryDirectory() as directory:- layout, journal, path, destination = self.fixture(directory)- journal["new_definition"] = {"manager": "scm", "owner_sid": "S-1-5-21-fixture"}; path.write_text(json.dumps(journal))- cli = Path(directory) / "hiroute.exe"; cli.write_bytes(b"fixture")- args = SimpleNamespace(cli=cli)- with patch.object(installer, "native", return_value=layout), patch.object(installer, "maintenance_lock", lambda _data: nullcontext()), patch.object(installer, "publish_marker", lambda cli, value: self.write_record(cli, layout["marker_path"], value)), patch.object(installer, "owner_finalize", side_effect=ValueError("SCM not actually registered")):- with self.assertRaises(ValueError):- installer.finalize(args)- self.assertEqual(installer.read_json(path)["phase"], "prepared")- self.assertTrue(Path(journal["files"][0]["backup"]).exists())-- def test_internal_admin_credentials_are_stdin_only_and_response_is_closed(self):- password = 'literal"; $(must-not-run) & no-shell'- request = {"schema": "request", "operation": "install", "password": password}- response = {"schema": "response", "operation": "install", "definition": {}, "completed": True}- process = SimpleNamespace(returncode=0, stdout=json.dumps(response).encode())- with patch.object(installer.subprocess, "run", return_value=process) as run:- installer.internal(Path("trusted-cli.exe"), "fixed-internal-verb", request, "response", "install")- argv = run.call_args.args[0]; self.assertNotIn(password, argv)- self.assertEqual(json.loads(run.call_args.kwargs["input"])["password"], password)- self.assertNotIn("shell", run.call_args.kwargs)- process.stdout = json.dumps({**response, "password": password}).encode()- with patch.object(installer.subprocess, "run", return_value=process), self.assertRaises(ValueError):- installer.internal(Path("trusted-cli.exe"), "fixed-internal-verb", request, "response", "install")-- def test_partial_publish_rolls_back_exact_old_bytes_and_preserves_foreign_edit(self):- with tempfile.TemporaryDirectory() as directory:- root = Path(directory).resolve()- old, new, dest = (root / value for value in ("backup", "source", "destination"))- old.write_bytes(b"old"); new.write_bytes(b"new"); dest.write_bytes(b"old")- item = {"destination": str(dest), "source": str(new), "backup": str(old),- "old_sha256": package.digest(old), "new_sha256": package.digest(new), "kind": "copy"}- installer.replace_owned(item)- self.assertEqual(dest.read_bytes(), b"new")- installer.replace_owned(item, rollback=True)- self.assertEqual(dest.read_bytes(), b"old")- dest.write_bytes(b"foreign")- with self.assertRaises(ValueError):- installer.replace_owned(item, rollback=True)- self.assertEqual(dest.read_bytes(), b"foreign")-- def test_journal_rejects_unknown_fields_and_escaping_owned_paths(self):- with tempfile.TemporaryDirectory() as directory:- root = Path(directory).resolve()- layout = {"home": str(root), "data_root": str(root / "data")}- journal = {"schema": installer.JOURNAL_SCHEMA, "operation": "install", "phase": "prepared",- "old_marker": None, "new_marker": {}, "old_definition": None, "new_definition": {}, "files": []}- installer.validate_journal(journal, layout)- with self.assertRaises(ValueError):- installer.validate_journal({**journal, "password": "must never persist"}, layout)- item = {"destination": str(root / "foreign"), "source": "ignored", "backup": str(root / "data/service/install-backups/x/1"), "old_sha256": None, "new_sha256": None, "kind": "remove"}- with self.assertRaises(ValueError):- installer.validate_journal({**journal, "files": [item]}, layout)-- def test_committed_uninstall_reopens_and_finishes_metadata_cleanup(self):- with tempfile.TemporaryDirectory() as directory:- root = Path(directory).resolve(); data = root / "data"; data.mkdir()- marker = data / "standalone.json"; definition = data / "definition.json"- old = {"version": "0.1.0", "target": "x86_64-pc-windows-msvc"}- previous_definition = {"manager": "task"}- marker.write_text(json.dumps(old)); definition.write_text(json.dumps(previous_definition))- (data / "package-manifest.json").write_text(json.dumps(old))- layout = {"marker_path": str(marker), "service_definition": str(definition), "data_root": str(data)}- journal = {"old_marker": old, "old_definition": previous_definition}- installer.finish_uninstall_metadata(layout, journal)- installer.finish_uninstall_metadata(layout, journal)- self.assertFalse(marker.exists()); self.assertFalse(definition.exists())---if __name__ == "__main__":- unittest.main()diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.pyindex fa81f7e5..e512b9fe 100644--- a/scripts/test-test-plan.py+++ b/scripts/test-test-plan.py@@ -307,7 +307,8 @@ class SelectionTests(unittest.TestCase):def test_windows_development_runner_does_not_select_product_or_hosted_matrix(self):result = plan.select(['scripts/windows-dev.py', 'scripts/windows-dev-host.py',- 'scripts/test-windows-dev.py'])+ 'scripts/test-windows-dev.py', 'scripts/windows-desktop-session.py',+ 'scripts/windows-dev-profile.py'])self.assertFalse(result['rust'])self.assertFalse(result['frontend'])self.assertEqual(result['product_checks'], [])diff --git a/scripts/test-windows-ci-package.py b/scripts/test-windows-ci-package.pyindex 794544b2..75052a38 100644--- a/scripts/test-windows-ci-package.py+++ b/scripts/test-windows-ci-package.py@@ -41,6 +41,7 @@ class RestagedBaseline(unittest.TestCase):patch.object(staging.platform, 'system', return_value='Windows').start()patch.object(staging, 'command', side_effect=self.command).start()patch.object(staging, 'module', return_value=packager).start()+ patch.object(packager, 'host_target', return_value='x86_64-pc-windows-msvc').start()patch.object(staging, 'trusted_extraction', side_effect=self.extract).start()self.package(BASELINE)@@ -58,7 +59,7 @@ class RestagedBaseline(unittest.TestCase):verified = owner.verify(manifest, archive)destination.mkdir(parents=True, exist_ok=False)for name, (payload, _) in owner.safe_members(archive, verified['files']).items():- path = destination / name+ path = destination / name.removeprefix("bin/")path.parent.mkdir(parents=True, exist_ok=True)path.write_bytes(payload)self.extractions.append(destination)diff --git a/scripts/test-windows-dev.py b/scripts/test-windows-dev.pyindex a04fc07a..bae81a23 100644--- a/scripts/test-windows-dev.py+++ b/scripts/test-windows-dev.py@@ -1,13 +1,18 @@#!/usr/bin/env python3"""Development-runner admission regressions, not native product evidence."""import base64+import contextlib+import io+import hashlibimport importlib.utilimport jsonimport osfrom pathlib import Pathimport struct+import sysimport tempfileimport time+import typesimport unittestfrom unittest.mock import patchimport zipfile@@ -21,6 +26,9 @@ def load(name):controller, host = load('windows-dev'), load('windows-dev-host')+images = load('test-windows-native-runtime-audit')+profiles = load('windows-dev-profile')+desktop = load('windows-desktop-session')class Runner(unittest.TestCase):@@ -63,6 +71,339 @@ class Runner(unittest.TestCase):host.stage(self.root, archive, '0' * 64)self.assertFalse((self.root / 'bundles').exists())+ def test_desktop_observation_admits_installed_bytes_and_rejects_changed_shell(self):+ home = self.root / 'home'+ programs = home / 'local/Programs/HiRoute'+ package = home / '.local/lib/hiroute/0.3.1-aaaaaaaaaaaa'+ data = home / '.local/share/hiroute'+ for path in (programs, package, data):+ path.mkdir(parents=True)+ files = {}+ for name in ('hiroute.exe', 'hirouted.exe'):+ (package / name).write_bytes(name.encode())+ files[name] = dict(sha256=profiles.digest(package / name))+ shell = programs / 'hiroute-shell.exe'+ shell.write_bytes(b'measured NSIS member')+ checksum = profiles.digest(shell)+ (programs / 'shell-package.json').write_text(json.dumps(dict(files={'hiroute-shell.exe': checksum})))+ (data / 'standalone.json').write_text(json.dumps(dict(install_root=str(package),+ service_definition=str(package / 'task.json'), target='x86_64-pc-windows-msvc')))+ manifest = dict(source_revision='a' * 40, target='x86_64-pc-windows-msvc', files=files, shell_sha256=checksum)+ with patch.object(desktop.Path, 'home', return_value=home), patch.dict(os.environ, LOCALAPPDATA=str(home / 'local')):+ self.assertEqual(desktop.installed(profiles, self.root, manifest)[2], shell)+ shell.write_bytes(b'changed')+ with self.assertRaisesRegex(ValueError, 'shell differs'):+ desktop.installed(profiles, self.root, manifest)+ shell.write_bytes(b'measured NSIS member')+ (package / 'hiroute.exe').write_bytes(b'changed')+ with self.assertRaisesRegex(ValueError, 'binary changed'):+ desktop.installed(profiles, self.root, manifest)++ def test_desktop_refuses_filtered_administrator_before_native_actions(self):+ with self.assertRaisesRegex(ValueError, 'filtered administrator'), patch.object(desktop.subprocess, 'run') as run:+ desktop.execute({}, self.root, self.root, {}, profiles, {'administrator_groups': True}, host.manifest, self.root)+ run.assert_not_called()++ def test_desktop_helper_requires_the_exact_committed_hash(self):+ path = self.root / 'desktop.py'+ path.write_text('raise RuntimeError("must not import")')+ with self.assertRaisesRegex(ValueError, 'committed request'):+ host.desktop_helper(dict(desktop_helper_path=str(path), desktop_helper_sha256='0' * 64))++ def test_missing_windowless_runtime_refuses_before_task_or_lock_creation(self):+ request = dict(config=dict(python=str(self.root / 'python.exe')), run_id='a' * 32,+ harness='b' * 12 + '-' + 'c' * 12, product='d' * 12 + '-' + 'e' * 12,+ timeout=120, binary='hiroute.exe', case='native_desktop_snapshot', operation='desktop')+ with patch.object(host, 'manifest', return_value={}), \+ patch.object(host, 'pe', side_effect=FileNotFoundError('pythonw.exe')), \+ patch.object(host, 'private_runs') as prepare, self.assertRaises(FileNotFoundError):+ host.start(self.root, request)+ prepare.assert_not_called()+ self.assertFalse((self.root / 'active.json').exists())++ def test_desktop_cleanup_keeps_the_exact_windowless_action_identity(self):+ run_id = 'a' * 32+ run = self.root / 'runs' / run_id+ run.mkdir(parents=True)+ request = dict(config=dict(python=str(self.root / 'python.exe')),+ operation='desktop', driver_path=str(self.root / 'driver.py'))+ (run / 'request.json').write_text(json.dumps(request))+ lock = self.root / 'active.json'+ lock.write_text(json.dumps(dict(run_id=run_id)))+ with patch.object(host, 'ps', side_effect=RuntimeError('active or differs')):+ with self.assertRaises(RuntimeError):+ host.finish(self.root, run_id)+ self.assertTrue(lock.exists())+ with patch.object(host, 'ps') as ps:+ self.assertTrue(host.finish(self.root, run_id)['task_removed'])+ self.assertIn(str(self.root / 'pythonw.exe'), ps.call_args.args[0])+ self.assertIn("$t.State -ne 'Ready'", ps.call_args.args[0])+ self.assertFalse(lock.exists())++ def test_nsis_uninstall_waits_on_the_staged_program_and_preserves_the_final_path_tail(self):+ command = host.nsis_uninstall_command(r'C:\Private Runs\nsis-uninstaller.exe', r'C:\Users\Standard User\AppData\Local\Programs\HiRoute')+ self.assertEqual(command, '"C:\\Private Runs\\nsis-uninstaller.exe" /S _?=C:\\Users\\Standard User\\AppData\\Local\\Programs\\HiRoute')+ for invalid in ('path\nother', 'path"other', 'path\0other'):+ with self.assertRaises(ValueError):+ host.nsis_uninstall_command('uninstaller.exe', invalid)++ def test_locked_input_desktop_refuses_before_any_native_ui_process(self):+ with patch.object(desktop, 'desktop_state', return_value={'interactive':False,'input_desktop':None}), \+ patch.object(desktop.subprocess, 'run') as run, self.assertRaisesRegex(RuntimeError, 'unlock'):+ desktop.ui_action(self.root, {'desktop_action':'snapshot'}, Path('shell.exe'), 42)+ run.assert_not_called()+ self.assertFalse(json.loads((self.root / 'desktop-state.json').read_text())['interactive'])++ def test_scroll_requires_direction_and_keeps_observed_geometry(self):+ request = dict(desktop_action='scroll', x=250, y=200)+ observed = dict(handle=42, width=755, height=600)+ with patch.object(desktop, 'desktop_state', return_value={'interactive':True}), \+ patch.object(desktop.subprocess, 'run') as run:+ with self.assertRaisesRegex(ValueError, 'explicit direction'):+ desktop.ui_action(self.root, request, Path('shell.exe'), 12, observed=observed)+ run.assert_not_called()+ request['scroll_direction'] = 'down'+ run.return_value = desktop.subprocess.CompletedProcess([], 0, b'{}', b'')+ desktop.ui_action(self.root, request, Path('shell.exe'), 12, observed=observed)+ query = json.loads((self.root / 'ui-request.json').read_text())+ self.assertEqual((query['window'],query['width'],query['height'],query['x'],query['y'],query['direction']),+ (42,755,600,250,200,'down'))++ def test_codex_real_call_refuses_foreign_provider_profile_or_endpoint(self):+ document = dict(model_provider='hiroute', model_providers={'hiroute':{'base_url':'http://127.0.0.1:8317/v1'}},+ profiles={'hiroute':{'model_provider':'hiroute'}})+ self.assertEqual(desktop.codex_gateway(document, None), 'http://127.0.0.1:8317/v1')+ self.assertEqual(desktop.codex_gateway(document, 'hiroute'), 'http://127.0.0.1:8317/v1')+ for changes,profile in (({'model_provider':'openai'},None), ({},'foreign'),+ ({'model_providers':{'hiroute':{'base_url':'https://example.com/v1'}}},None),+ ({'model_providers':{'hiroute':{'base_url':'http://127.0.0.1/v1'}}},None),+ ({'model_providers':{'hiroute':{'base_url':'http://user:[email protected]:8317/v1'}}},None)):+ with self.subTest(changes=changes,profile=profile), self.assertRaises(ValueError):+ desktop.codex_gateway({**document,**changes},profile)++ def test_codex_profile_call_reads_the_standalone_native_file_and_preserves_root(self):+ original = self.root / '.codex/config.toml'+ original.parent.mkdir()+ original.write_bytes(b'model_provider = "openai"\n')+ selected = desktop.codex_config_path(self.root, 'hiroute')+ self.assertEqual(selected, original.with_name('hiroute.config.toml'))+ self.assertEqual(desktop.codex_config_path(self.root, None), original)+ document = {'model_provider':'hiroute', 'model_providers':{'hiroute':{'base_url':'http://127.0.0.1:8317/v1'}}}+ self.assertEqual(desktop.codex_gateway(document, 'hiroute'), 'http://127.0.0.1:8317/v1')+ self.assertEqual(original.read_bytes(), b'model_provider = "openai"\n')+ self.assertFalse(selected.exists())++ def test_codex_timeout_preserves_both_partial_streams_before_propagating(self):+ failure = desktop.subprocess.TimeoutExpired(['measured-codex'], 150,+ output=b'{"type":"thread.started"}\n', stderr=b'bounded native failure\n')+ with patch.object(desktop.subprocess, 'run', side_effect=failure), \+ self.assertRaises(desktop.subprocess.TimeoutExpired):+ desktop.codex_process(self.root, ['measured-codex'], {})+ self.assertEqual((self.root / 'codex.stdout').read_bytes(), failure.stdout)+ self.assertEqual((self.root / 'codex.stderr').read_bytes(), failure.stderr)++ def test_tls_diagnostics_retain_verification_failure_without_http_or_credentials(self):+ import ssl+ import socket+ with patch.object(socket, 'create_connection', side_effect=OSError('connection refused')):+ with self.assertRaisesRegex(RuntimeError, 'before any authenticated or HTTP'):+ desktop.probe_tls(self.root, dict(scheme='https', authority='example.com', port=443))+ result = json.loads((self.root / 'tls-probe.json').read_text())+ self.assertFalse(result['tls_verified'])+ self.assertFalse(result['http_request_sent'])+ self.assertFalse(result['authenticated'])+ with self.assertRaisesRegex(ValueError, 'saved HTTPS DNS target'):+ desktop.probe_tls(self.root, dict(scheme='https', authority='user:[email protected]', port=443))++ def test_native_tls_diagnostic_uses_saved_target_and_preserves_failure(self):+ completed = desktop.subprocess.CompletedProcess([], 0,+ b'{"tls_verified":false,"authenticated":false,"http_request_sent":false,"error":"untrusted chain"}', b'')+ with patch.object(desktop.subprocess, 'run', return_value=completed), \+ self.assertRaisesRegex(RuntimeError, 'Windows system TLS verification failed'):+ desktop.probe_windows_tls(self.root, dict(scheme='https', authority='example.com', port=443))+ result = json.loads((self.root / 'tls-probe.native.json').read_text())+ self.assertFalse(result['tls_verified'])+ self.assertFalse(result['authenticated'])+ self.assertEqual(json.loads((self.root / 'tls-target.json').read_text())['authority'], 'example.com')++ def test_codex_real_call_requires_completed_turn_tool_and_exact_nonce(self):+ expected = 'HiRoute-Windows-test:ok'+ events = [{'type':'item.completed','item':{'type':'command_execution','status':'completed','exit_code':0,+ 'command':'pwsh -Command Get-Location','aggregated_output':'C:\\acceptance\\bounded-run\n'}},+ {'type':'item.completed','item':{'type':'agent_message','text':expected}}, {'type':'turn.completed'}]+ def evidence(values):+ return desktop.codex_call_evidence(('\n'.join(json.dumps(value) for value in values)).encode(), expected, 'bounded-run')+ self.assertTrue(all(evidence(events).values()))+ for index in range(len(events)):+ self.assertFalse(all(evidence(events[:index]+events[index+1:]).values()))+ events[1]['item']['text'] = '42'+ self.assertFalse(evidence(events)['answer'])+ events[0]['item']['status'] = 'failed'+ self.assertFalse(evidence(events)['shell_tool'])+ events[0]['item'].update(status='completed',exit_code=1)+ self.assertFalse(evidence(events)['shell_tool'])++ def test_codex_real_call_refuses_environment_override_before_process_start(self):+ request = dict(config=dict(environment={},path=[]))+ with patch.dict(os.environ,OPENAI_BASE_URL='https://example.com/v1'), \+ patch.object(desktop.subprocess, 'run') as run, self.assertRaisesRegex(ValueError,'environment overrides'):+ desktop.codex_call(self.root,request,profiles)+ run.assert_not_called()++ def native_codex_inference(self, action, completed=True, answer=True):+ home = self.root / 'native-home'+ config = home / '.codex/hiroute.config.toml'+ config.parent.mkdir(parents=True, exist_ok=True)+ config.write_text('model_provider = "hiroute"\n[model_providers.hiroute]\n'+ 'base_url = "http://127.0.0.1:65140/v1"\n')+ binary = self.root / 'codex.exe'+ binary.write_bytes(b'measured native client')+ run_id = 'a' * 32+ events = [{'type':'item.completed','item':{'type':'agent_message',+ 'text':'HiRoute-Windows-' + run_id + ':ok' if answer else 'unrelated answer'}}]+ if completed:+ events.append({'type':'turn.completed'})+ output = ('\n'.join(json.dumps(value) for value in events)).encode()+ request = dict(run_id=run_id, desktop_action=action, codex_profile='hiroute',+ config=dict(environment={'HIROUTE_WORKER_CODEX_BINARY':str(binary)}, path=[]))+ parser = types.SimpleNamespace(loads=lambda text: dict(model_provider='hiroute',+ model_providers={'hiroute':{'base_url':'http://127.0.0.1:65140/v1'}}))+ version = types.SimpleNamespace(returncode=0, stdout=b'codex-cli test\n', stderr=b'')+ process = types.SimpleNamespace(returncode=0, stdout=output, stderr=b'')+ with patch.dict(os.environ, {'PATH':os.defpath}, clear=True), \+ patch.dict(sys.modules, {'tomllib':parser}), \+ patch.object(desktop.Path, 'home', return_value=home), \+ patch.object(desktop.subprocess, 'run', return_value=version), \+ patch.object(desktop, 'codex_process', return_value=process) as execute:+ try:+ return desktop.codex_call(self.root, request, profiles)+ finally:+ command = execute.call_args.args[1]+ self.assertEqual(command[command.index('--sandbox') + 1], 'read-only')+ self.assertIn('approval_policy="never"', command)+ self.assertEqual(command[command.index('--profile') + 1], 'hiroute')+ self.assertEqual('Do not use any tools' in command[-1], action == 'codex-inference')++ def test_pure_inference_is_distinct_from_the_unmodified_native_tool_gate(self):+ evidence = self.native_codex_inference('codex-inference')+ self.assertEqual(evidence['scope'], 'inference_only')+ self.assertTrue(evidence['turn_completed'] and evidence['answer'])+ self.assertFalse(evidence['shell_tool'])+ with self.assertRaisesRegex(RuntimeError, 'real tool and answer'):+ self.native_codex_inference('codex-call')++ def test_pure_inference_requires_both_completed_turn_and_exact_per_run_answer(self):+ for completed, answer in [(False, True), (True, False)]:+ with self.subTest(completed=completed, answer=answer), \+ self.assertRaisesRegex(RuntimeError, 'turn and exact answer'):+ self.native_codex_inference('codex-inference', completed, answer)++ def test_inspection_keeps_bounded_transaction_and_diagnostic_evidence_without_mutation(self):+ home = self.root / 'home'+ local = self.root / 'local'+ journal = home / '.local/share/hiroute/service/install-journal.json'+ journal.parent.mkdir(parents=True)+ journal.write_text('{"phase":"prepared","schema":"current"}')+ log = local / 'HiRoute/cli/diagnostics/daemon/current.jsonl'+ log.parent.mkdir(parents=True)+ log.write_bytes(b'x' * 70000 + b'\n{"code":"EXPECTED_INSTALL_FAILURE"}\n')+ original = (journal.read_bytes(), log.read_bytes())+ result = profiles.inspect_installation(home,local)+ self.assertEqual(result['install-journal.json']['record']['phase'],'prepared')+ self.assertEqual(result['diagnostics_tail']['daemon/current.jsonl']['records'],+ [{'code':'EXPECTED_INSTALL_FAILURE'}])+ self.assertEqual(original,(journal.read_bytes(),log.read_bytes()))++ def test_installer_resume_requires_recent_matching_evidence_before_process_start(self):+ observed = self.root / 'runs' / ('a' * 32)+ observed.mkdir(parents=True)+ (observed / 'result.json').write_text(json.dumps(dict(passed=True,assessment='inspection_only')))+ (observed / 'request.json').write_text(json.dumps(dict(product='b' * 12 + '-' + 'c' * 12,+ config=dict(session_id=3))))+ request = dict(observation_run='a' * 32,from_product='d' * 12 + '-' + 'e' * 12,+ product='b' * 12 + '-' + 'c' * 12,config=dict(session_id=4))+ with patch.object(desktop.subprocess,'run') as run, self.assertRaisesRegex(ValueError,'matching installation'):+ desktop.installer_resume(request,self.root,{},profiles,{},host.manifest,self.root)+ run.assert_not_called()++ with patch.object(desktop.subprocess,'run') as run, self.assertRaisesRegex(ValueError,'explicit inspection'):+ desktop.installer_resume({**request,'observation_run':'../other'},self.root,{},profiles,{},host.manifest,self.root)+ run.assert_not_called()++ def test_installer_resume_preserves_recorded_login_and_tray_choices(self):+ facts = {'install-pending.json': {'record': {'previous_autostart': False}},+ 'shell-install.json': {'record': {'tray_enabled': False}}}+ shell = self.root / 'hiroute-shell.exe'+ completed = desktop.subprocess.CompletedProcess([], 0, b'installed', b'')+ with patch.object(desktop, 'prepared_installer_replacement', return_value=(facts, self.root, shell)), \+ patch.object(desktop.subprocess, 'run', return_value=completed) as run, \+ patch.object(profiles, 'inspect_installation', return_value={}), \+ patch.dict(os.environ, LOCALAPPDATA=str(self.root)):+ desktop.installer_resume({}, self.root, {}, profiles, {}, host.manifest, self.root)+ self.assertEqual(run.call_args.args[0], [str(shell), '--installer-install', '--no-login-start', '--no-tray'])+ self.assertEqual((self.root / 'installer-resume.stdout').read_bytes(), b'installed')++ def test_nsis_retry_admits_the_exact_interrupted_product_before_normal_install(self):+ interrupted = 'b' * 12 + '-' + 'c' * 12+ request = dict(product='a' * 12 + '-' + 'd' * 12, from_product='e' * 12 + '-' + 'f' * 12,+ recover_product=interrupted, observation_run='1' * 32)+ with patch.object(profiles, 'inspect_installation', return_value={}), \+ patch.dict(os.environ, LOCALAPPDATA=str(self.root)), \+ patch.object(desktop, 'prepared_installer_replacement') as admission, \+ patch.object(desktop, 'installed') as installed:+ desktop.admit_nsis_install(request, profiles, {}, lambda _: {'image': 'measured'}, self.root)+ self.assertEqual(admission.call_args.args[0], {**request, 'product': interrupted})+ self.assertEqual(admission.call_args.args[1], {'image': 'measured'})+ installed.assert_not_called()+ admission.side_effect = ValueError('changed interrupted image')+ with self.assertRaisesRegex(ValueError, 'changed interrupted image'):+ desktop.admit_nsis_install(request, profiles, {}, lambda _: {}, self.root)++ def test_manual_generated_file_quarantine_preserves_backup_and_refuses_changed_bytes(self):+ programs, state, output = (self.root / name for name in ('program','state','evidence'))+ programs.mkdir();(state / 'install-backups').mkdir(parents=True);output.mkdir()+ source = programs / 'uninstall.exe';source.write_bytes(b'verified generated image')+ backup = state / 'install-backups/uninstall.exe';backup.write_bytes(b'previous verified image')+ old = profiles.digest(backup);expected = profiles.digest(source)+ pending = {'old':{'uninstall.exe':old},'new':{}}+ with self.assertRaisesRegex(ValueError,'identity changed'):+ desktop.quarantine_generated_uninstaller(programs,state,output,'0'*64,pending,profiles)+ self.assertTrue(source.is_file());self.assertEqual(profiles.digest(backup),old)+ result = desktop.quarantine_generated_uninstaller(programs,state,output,expected,pending,profiles)+ self.assertEqual(result['sha256'],expected);self.assertFalse(source.exists())+ self.assertEqual(profiles.digest(output / 'unregistered-uninstaller.bin'),expected)+ self.assertEqual(profiles.digest(backup),old)++ def test_bootstrap_publishes_once_and_preserves_changed_content(self):+ destination = self.root / 'helper.py'+ temporary = self.root / 'upload'+ payload = b'validated helper'+ checksum = hashlib.sha256(payload).hexdigest()+ entries = [dict(path=str(destination),sha256=checksum)]+ def execute(publication=None):+ output=io.StringIO()+ with contextlib.redirect_stdout(output):+ exec(controller.bootstrap_code(str(self.root), entries, publication), {})+ return json.loads(output.getvalue())+ self.assertEqual(execute(), [])+ temporary.write_bytes(payload)+ self.assertEqual(execute(dict(path=str(destination),temporary=str(temporary),sha256=checksum)),[checksum])+ before=destination.stat().st_mtime_ns+ self.assertEqual(execute(), [checksum])+ self.assertEqual(destination.stat().st_mtime_ns,before)+ destination.write_bytes(b'changed')+ with self.assertRaisesRegex(ValueError,'identity changed'):+ execute()+ self.assertEqual(destination.read_bytes(),b'changed')++ def test_wait_bootstrap_does_not_upload_over_live_helpers(self):+ remote=controller.Remote(dict(root=str(self.root),python='python.exe',identity_file='key'))+ checksums=[controller.digest(Path(__file__).with_name(name)) for name in+ ('windows-dev-host.py','windows-dev-profile.py','windows-desktop-session.py')]+ with patch.object(remote,'execute',return_value=json.dumps(checksums)),patch.object(remote,'upload') as upload:+ remote.bootstrap()+ upload.assert_not_called()+def test_archive_traversal_and_unmanifested_entries_fail(self):for name in ('../escape', '/absolute', 'C:/absolute', 'dir\\file.exe', 'other.exe'):with self.subTest(name=name):@@ -87,6 +428,107 @@ class Runner(unittest.TestCase):with self.assertRaises(ValueError):host.pe(binary)+ def test_nsis_stub_is_admitted_only_as_the_declared_installer(self):+ payload = bytearray(70)+ payload[:2] = b'MZ'+ struct.pack_into('<I', payload, 60, 64)+ payload[64:] = b'PE\0\0\x4c\x01'+ entry = dict(sha256=hashlib.sha256(payload).hexdigest(), bytes=len(payload))+ for declaration in (None, 'nsis'):+ def mutate(value):+ value['files']['installer.exe'] = entry+ if declaration:+ value['installer_format'] = declaration+ archive = self.archive(extra=('installer.exe', payload), mutate=mutate)+ if declaration:+ staged = host.stage(self.root, archive, controller.digest(archive))+ self.assertIn('installer.exe', staged['files'])+ path = self.root / 'bundles' / staged['bundle'] / 'installer.exe'+ with self.assertRaises(ValueError):+ host.pe(path) # Ordinary product/harness admission stays x64.+ else:+ with self.assertRaisesRegex(ValueError, 'explicit NSIS'):+ host.stage(self.root, archive, controller.digest(archive))++ def test_desktop_bundle_binds_installer_and_compiled_harness_to_the_candidate(self):+ sha = 'a' * 40+ binaries = self.root / 'target/x86_64-pc-windows-msvc/release'+ binaries.mkdir(parents=True)+ harness = binaries / 'windows_desktop.exe'+ harness.write_bytes(images.image())+ payload = self.root / 'apps/shell/src-tauri/resources/standalone'+ payload.mkdir(parents=True)+ for name in ('hiroute.exe', 'hirouted.exe'):+ (payload / name).write_bytes(b'embedded-' + name.encode())+ (payload / 'package-manifest.json').write_text(json.dumps(dict(revision=sha,+ target='x86_64-pc-windows-msvc', files={+ 'bin/' + name: dict(sha256=controller.digest(payload / name), size=(payload / name).stat().st_size)+ for name in ('hiroute.exe', 'hirouted.exe')})))+ assets = self.root / 'target/candidate/assets'+ assets.mkdir(parents=True)+ installer = assets / 'candidate.exe'+ installer.write_bytes(b'component-nsis-fixture')+ result = dict(revision=sha, target='x86_64-pc-windows-msvc', status='awaiting_runtime',+ package_integrity='green', assets=str(assets),+ desktop_result=dict(revision=sha, native_runtime='not_executed',+ shell_image=dict(sha256='c' * 64),+ installer_sha256=controller.digest(installer), installer_size=installer.stat().st_size,+ standalone_manifest_sha256=controller.digest(payload / 'package-manifest.json')),+ website_artifact=dict(kind='desktop', format='nsis', platform='Windows', architecture='x86_64',+ filename=installer.name, sha256=controller.digest(installer)))+ record = self.root / 'result.json'+ record.write_text(json.dumps(result))+ log = self.root / 'compiler.jsonl'+ log.write_text(json.dumps(dict(reason='compiler-artifact', target=dict(name='windows_desktop'),+ profile=dict(test=True), executable=str(harness))) + '\n')+ with patch.object(controller, 'REPO', self.root), \+ patch.object(controller.subprocess, 'check_output', return_value=sha):+ output = self.root / 'desktop.zip'+ exported = controller.bundle_desktop(record, log, output)+ self.assertEqual(exported['native_acceptance'], 'not_executed')+ with zipfile.ZipFile(output) as archive:+ manifest = json.loads(archive.read('manifest.json'))+ self.assertEqual(manifest['installer_format'], 'nsis')+ self.assertEqual(manifest['shell_sha256'], 'c' * 64)+ self.assertEqual(archive.read('hirouted.exe'), b'embedded-hirouted.exe')+ harness.write_bytes(images.image(('KERNEL32.dll', 'VCRUNTIME140.dll')))+ with self.assertRaisesRegex(ValueError, 'static CRT'):+ controller.bundle_desktop(record, log, self.root / 'dynamic-harness.zip')+ harness.write_bytes(images.image())+ installer.write_bytes(b'changed installer')+ with self.assertRaisesRegex(ValueError, 'measured build identity'):+ controller.bundle_desktop(record, log, self.root / 'changed.zip')+ self.assertFalse((self.root / 'changed.zip').exists())+ installer.write_bytes(b'component-nsis-fixture')+ (payload / 'hirouted.exe').write_bytes(b'changed daemon')+ with self.assertRaisesRegex(ValueError, 'Embedded product bytes'):+ controller.bundle_desktop(record, log, self.root / 'changed-product.zip')++ def test_installation_inspection_reads_owned_paths_without_starting_or_changing_them(self):+ native_home, local = self.root / 'account', self.root / 'local'+ data = native_home / '.local/share/hiroute'+ data.mkdir(parents=True)+ install = native_home / '.local/lib/hiroute/version'+ install.mkdir(parents=True)+ (install / 'hiroute.exe').write_bytes(b'existing-cli')+ definition = install / 'task.json'+ definition.write_text('{"manager":"task"}')+ marker = data / 'standalone.json'+ marker.write_text(json.dumps(dict(install_root=str(install), service_definition=str(definition))))+ facts = profiles.inspect_installation(native_home, local)+ self.assertTrue(facts['data']['exists'])+ self.assertFalse(facts['state']['exists'])+ self.assertEqual(facts['installed_cli']['sha256'], controller.digest(install / 'hiroute.exe'))+ self.assertEqual(facts['definition']['text'], '{"manager":"task"}')+ self.assertTrue(marker.exists())+ self.assertFalse(local.exists())+ foreign = self.root / 'foreign'+ foreign.mkdir()+ (local / 'Programs').mkdir(parents=True)+ (local / 'Programs/HiRoute').symlink_to(foreign, target_is_directory=True)+ with self.assertRaisesRegex(ValueError, 'Reparse'):+ profiles.inspect_installation(native_home, local)+def test_symlink_and_multiple_links_are_not_runner_storage(self):archive = self.archive()value = host.stage(self.root, archive, controller.digest(archive))@@ -98,6 +540,148 @@ class Runner(unittest.TestCase):with self.assertRaises(ValueError):host.plain(self.root / 'linked/sample.exe')+ def orphaned_profile(self):+ native_home, local = self.root / 'native', self.root / 'appdata'+ roots = profiles.locations(native_home, local)+ for name in ('data', 'state', 'shell_state'):+ roots[name].mkdir(parents=True)+ (roots[name] / 'retained.txt').write_bytes(name.encode())+ evidence = self.root / 'private-evidence'+ evidence.mkdir()+ return native_home, local, roots, evidence++ def test_candidate_uninstall_requires_measured_images_and_rejects_other_active_work(self):+ native_home, local, roots, _ = self.orphaned_profile()+ sha = 'a' * 40+ installed = native_home / '.local/lib/hiroute' / ('0.3.1-' + sha[:12])+ installed.mkdir(parents=True)+ files = {}+ for name in ('hiroute.exe', 'hirouted.exe'):+ (installed / name).write_bytes(name.encode())+ files[name] = dict(sha256=controller.digest(installed / name))+ definition = roots['data'] / 'task.json'+ definition.write_text(json.dumps(dict(manager='task', name='HiRoute-candidate')))+ marker = dict(schema_version='hiroute.standalone-install/v1', target='x86_64-pc-windows-msvc',+ install_root=str(installed), service_definition=str(definition))+ (roots['data'] / 'standalone.json').write_text(json.dumps(marker))+ roots['programs'].mkdir(parents=True)+ for name in ('hiroute-shell.exe', 'uninstall.exe'):+ (roots['programs'] / name).write_bytes(name.encode())+ inventory = {n: controller.digest(roots['programs'] / n) for n in ('hiroute-shell.exe', 'uninstall.exe')}+ (roots['programs'] / 'shell-package.json').write_text(json.dumps(dict(files=inventory)))+ inspected = profiles.inspect_installation(native_home, local)+ product = dict(source_revision=sha, target=marker['target'], files=files)+ activity = dict(administrator_groups=False, processes=[], tasks=[])+ result = profiles.candidate_uninstaller(native_home, local, inspected, product,+ inventory['hiroute-shell.exe'], activity)+ self.assertEqual(result, (roots['programs'] / 'uninstall.exe', installed))+ with self.assertRaisesRegex(ValueError, 'measured inventory'):+ profiles.candidate_uninstaller(native_home, local, inspected, product, 'f' * 64, activity)+ activity['processes'] = [dict(ExecutablePath=str(roots['programs'] / 'hiroute-shell.exe'))]+ with self.assertRaisesRegex(ValueError, 'Another product or installer'):+ profiles.candidate_uninstaller(native_home, local, inspected, product,+ inventory['hiroute-shell.exe'], activity)+ self.assertTrue((installed / 'hirouted.exe').exists())++ def test_archive_long_paths_use_extended_drive_and_unc_forms(self):+ self.assertEqual(profiles.extended_windows_path(r'C:\account\data'), r'\\?\C:\account\data')+ self.assertEqual(profiles.extended_windows_path(r'\\server\share\data'), r'\\?\UNC\server\share\data')+ self.assertEqual(profiles.extended_windows_path(r'\\?\C:\data'), r'\\?\C:\data')++ def test_fresh_nsis_case_rejects_old_payloads_before_installation(self):+ native_home = self.root / 'account'+ profiles.require_fresh_nsis_packages(native_home)+ packages = native_home / '.local/lib/hiroute'+ packages.mkdir(parents=True)+ profiles.require_fresh_nsis_packages(native_home)+ old = packages / 'old-version'+ old.mkdir()+ with self.assertRaisesRegex(ValueError, 'retained package roots'):+ profiles.require_fresh_nsis_packages(native_home)+ self.assertTrue(old.exists())++ def test_orphaned_data_is_archived_with_complete_hashes_and_native_files_untouched(self):+ native_home, local, roots, evidence = self.orphaned_profile()+ native = native_home / '.codex/config.toml'+ native.parent.mkdir()+ native.write_text('model="unrelated"')+ inspected = profiles.inspect_installation(native_home, local)+ result = profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False, processes=[], tasks=[]))+ self.assertEqual(result['assessment'], 'preparation_only')+ for name in ('data', 'state', 'shell_state'):+ self.assertFalse(roots[name].exists())+ self.assertEqual((evidence / ('previous-' + name) / 'retained.txt').read_bytes(), name.encode())+ manifest = json.loads((evidence / 'profile-backup.json').read_text())+ self.assertEqual(manifest['paths'][0]['inventory']['retained.txt']['sha256'],+ hashlib.sha256(b'data').hexdigest())+ self.assertEqual(native.read_text(), 'model="unrelated"')++ def test_orphaned_partial_shell_backup_is_preserved_with_its_hash(self):+ native_home, local, roots, evidence = self.orphaned_profile()+ backup = roots['shell_state'] / 'install-backups/hiroute-shell.exe'+ backup.parent.mkdir()+ backup.write_bytes(b"retained previous shell")+ inspected = profiles.inspect_installation(native_home, local)+ profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False))+ self.assertEqual((evidence / 'previous-shell_state/install-backups/hiroute-shell.exe').read_bytes(),+ b"retained previous shell")+ manifest = json.loads((evidence / 'profile-backup.json').read_text())+ shell = next(p for p in manifest['paths'] if p['source'] == str(roots['shell_state']))+ self.assertEqual(shell['inventory'][str(Path('install-backups/hiroute-shell.exe'))]['sha256'],+ hashlib.sha256(b"retained previous shell").hexdigest())+ self.assertFalse(roots['shell_state'].exists())++ def test_live_installation_activity_and_agent_references_prevent_archival(self):+ native_home, local, roots, evidence = self.orphaned_profile()+ inspected = profiles.inspect_installation(native_home, local)+ for activity in [dict(administrator_groups=True),+ dict(administrator_groups=False, processes=[123]),+ dict(administrator_groups=False, tasks=['HiRoute-task'])]:+ with self.assertRaises(ValueError):+ profiles.archive_orphaned_data(native_home, local, evidence, inspected, activity)+ self.assertTrue(roots['state'].exists())+ native = native_home / '.codex/config.toml'+ native.parent.mkdir()+ native.write_text(str(roots['state']))+ with self.assertRaisesRegex(ValueError, 'Native Agent configuration'):+ profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False))+ self.assertFalse((evidence / 'profile-backup.json').exists())++ def test_changed_or_linked_orphaned_data_is_preserved_before_any_move(self):+ native_home, local, roots, evidence = self.orphaned_profile()+ inspected = profiles.inspect_installation(native_home, local)+ (roots['state'] / 'new.txt').touch()+ with self.assertRaisesRegex(ValueError, 'changed since inspection'):+ profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False))+ (roots['state'] / 'dangling').symlink_to(self.root / 'missing')+ inspected = profiles.inspect_installation(native_home, local)+ with self.assertRaisesRegex(ValueError, 'Reparse'):+ profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False))+ self.assertTrue(roots['data'].exists())+ self.assertFalse((evidence / 'previous-data').exists())++ def test_failed_second_archive_move_restores_the_first_directory(self):+ native_home, local, roots, evidence = self.orphaned_profile()+ inspected = profiles.inspect_installation(native_home, local)+ rename = Path.rename+ def fail_second(source, target):+ if source == roots['state']:+ raise PermissionError('fixture file lock')+ return rename(source, target)+ with patch.object(Path, 'rename', fail_second), self.assertRaises(PermissionError):+ profiles.archive_orphaned_data(native_home, local, evidence, inspected,+ dict(administrator_groups=False))+ self.assertEqual((roots['data'] / 'retained.txt').read_bytes(), b'data')+ self.assertEqual((roots['state'] / 'retained.txt').read_bytes(), b'state')+ self.assertFalse((evidence / 'previous-data').exists())+ outcome = json.loads((evidence / 'profile-backup-outcome.json').read_text())+ self.assertEqual(outcome['outcome'], 'restored_after_error')+def test_config_contains_paths_not_tokens_and_lives_in_home(self):identity = self.root / 'key'identity.touch()@@ -132,6 +716,31 @@ class Runner(unittest.TestCase):self.assertEqual(base64.b64decode(command.split()[-1]).decode('utf-16le'), script)self.assertEqual(controller.ps_literal(value), "'C:/space '' $env:PATH ; directory/file.py'")+ def test_long_remote_source_uses_stdin_before_windows_shell_command_limit(self):+ remote = controller.Remote(dict(host='windows.example.test', identity_file='key'))+ for script in ("Write-Output 'short'", "# 中文 ' $env:PATH ;\n" * 2000):+ reply = controller.subprocess.CompletedProcess([], 0, stdout='observed', stderr='')+ with patch.object(controller.subprocess, 'run', return_value=reply) as run:+ self.assertEqual(remote.execute(script), 'observed')+ command = run.call_args.args[0][-1]+ self.assertLess(len(command), 6000)+ payload = run.call_args.kwargs.get('input')+ if len(controller.powershell(script)) > 6000:+ self.assertEqual(base64.b64decode(payload).decode('utf-8'), script)+ bridge = base64.b64decode(command.split()[-1]).decode('utf-16le')+ self.assertIn('[Console]::In.ReadToEnd()', bridge)+ else:+ self.assertIsNone(payload)+ self.assertEqual(base64.b64decode(command.split()[-1]).decode('utf-16le'), script)++ def test_long_remote_submission_failure_is_not_replayed(self):+ remote = controller.Remote(dict(host='windows.example.test', identity_file='key'))+ reply = controller.subprocess.CompletedProcess([], 1, stdout='', stderr='unknown outcome')+ with patch.object(controller.subprocess, 'run', return_value=reply) as run:+ with self.assertRaisesRegex(RuntimeError, 'no automatic replay'):+ remote.execute('# source\n' * 2000)+ self.assertEqual(run.call_count, 1)+def test_unknown_task_outcome_retains_owner_lock(self):archive = self.archive()value = host.stage(self.root, archive, controller.digest(archive))diff --git a/scripts/test-windows-native-artifacts.py b/scripts/test-windows-native-artifacts.pyindex d29ea93e..b079bebc 100644--- a/scripts/test-windows-native-artifacts.py+++ b/scripts/test-windows-native-artifacts.py@@ -230,7 +230,7 @@ class NativeArtifactReceipts(unittest.TestCase):foreign["build"]["source_sha"] = "b" * 40with self.assertRaisesRegex(ValueError, "build SHA"):self.verify(foreign)- for name in ("Cargo.lock", "scripts/install-standalone-windows.py", "scripts/package-standalone.py"):+ for name in ("Cargo.lock", "crates/cli/src/service/windows/install.rs", "scripts/package-standalone.py"):with self.subTest(name=name):path = self.root / nameoriginal = path.read_bytes()diff --git a/scripts/windows-ci-package.py b/scripts/windows-ci-package.pyindex af392e1d..bf42c165 100644--- a/scripts/windows-ci-package.py+++ b/scripts/windows-ci-package.py@@ -36,9 +36,10 @@ def trusted_extraction(packager, manifest, archive, trusted):verified = packager.verify(manifest, archive)trusted.mkdir(parents=True, exist_ok=False)for name, (payload, _) in packager.safe_members(archive, verified["files"]).items():- path = trusted / name+ path = trusted / name.removeprefix("bin/")path.parent.mkdir(parents=True, exist_ok=True)path.write_bytes(payload)+ shutil.copyfile(manifest, trusted / "package-manifest.json")# Inheritance flags apply to directories. Applying (OI)(CI) recursively to# regular files can leave an empty DACL while icacls reports success.for entry in [trusted] + sorted(trusted.rglob("*")):@@ -61,14 +62,14 @@ def restage(args):package_revision = args.package_revision or args.expected_shaif not re.fullmatch(r"[a-f0-9]{40}", package_revision):raise ValueError("Restaging requires an exact committed package revision")- if verified["revision"] != package_revision or verified["target"] != "x86_64-pc-windows-msvc":- raise ValueError("Replay requires the explicitly bound verified x64 package")+ if verified["revision"] != package_revision or verified["target"] != packager.host_target():+ raise ValueError("Replay requires the explicitly bound host-matching Windows package")trusted = args.output.resolve() / "administrator-package"trusted_extraction(packager, manifest, archive, trusted)return dict(source_revision=package_revision, consumer_revision=args.expected_sha,target=verified["target"], manifest=str(manifest),- archive=str(archive), administrator_cli=str(trusted / "bin/hiroute.exe"),- worker_daemon=str(trusted / "bin/hirouted.exe"), python=sys.executable,+ archive=str(archive), administrator_cli=str(trusted / "hiroute.exe"),+ worker_daemon=str(trusted / "hirouted.exe"), package_directory=str(trusted),archive_sha256=packager.digest(archive), manifest_sha256=packager.digest(manifest),production_runtime="not_executed", permission_source="fresh_verified_complete_extraction")@@ -82,8 +83,8 @@ def prepare(args):command("git", "diff", "--exit-code", "HEAD", "--")packager = module("package-standalone")target = packager.host_target()- if target != "x86_64-pc-windows-msvc":- raise ValueError("This package acceptance fixture requires native Windows x64")+ if target not in ("x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"):+ raise ValueError("Native Windows package target required")pin, _ = module("build-cpa").pinned_source()output = args.output.resolve()output.mkdir(parents=True, exist_ok=False)@@ -113,16 +114,20 @@ def prepare(args):passed.append(event["Test"])if sorted(passed) != ["TestLocalMachinePasswordPreservesRemotePolicy", "TestLocalManagementPasswordPipeBounds"]:raise ValueError("Original CPA native build lacks the required bootstrap security cases")+ frontend = ROOT / "apps/desktop"+ command("npm.cmd", "ci", "--prefix", frontend)+ command("npm.cmd", "run", "build", "--prefix", frontend)notices = output / "notices"command(sys.executable, ROOT / "scripts/collect-third-party-licenses.py", "--cargo-target", target,- "--cpa-source-repo", args.source_repo.resolve(strict=True), "--output", notices)+ "--cpa-source-repo", args.source_repo.resolve(strict=True),+ "--npm-root", frontend, "--output", notices)version = json.loads((ROOT / "apps/desktop/src-tauri/tauri.conf.json").read_text())["version"]base = [sys.executable, ROOT / "scripts/package-standalone.py", "build","--version", version, "--revision", revision, "--target", target,"--hiroute", ROOT / "target/debug/hiroute.exe","--hirouted", ROOT / "target/debug/hirouted.exe", "--cpa-binary", cpa,"--cpa-version", pin["version"], "--cpa-license", previous / "CPA.LICENSE",- "--notices", notices]+ "--notices", notices, "--console-assets", frontend / "dist"]first = json.loads(command(*base, "--output", output / "package"))second = json.loads(command(*base, "--output", output / "repeated-package"))archive, manifest = Path(first["archive"]), Path(first["manifest"])@@ -135,8 +140,8 @@ def prepare(args):trusted_extraction(packager, manifest, archive, trusted)result = dict(version=1, source_revision=revision, target=target,manifest=str(manifest), archive=str(archive),- administrator_cli=str(trusted / "bin/hiroute.exe"),- worker_daemon=str(trusted / "bin/hirouted.exe"), python=sys.executable,+ administrator_cli=str(trusted / "hiroute.exe"),+ worker_daemon=str(trusted / "hirouted.exe"), package_directory=str(trusted),archive_sha256=packager.digest(archive), manifest_sha256=packager.digest(manifest),deterministic_publication="green", production_runtime="not_executed",cpa_original_run=provenance.get("build_run_id", args.cpa_original_run),diff --git a/scripts/windows-desktop-cases.json b/scripts/windows-desktop-cases.jsonnew file mode 100644index 00000000..d913ff98--- /dev/null+++ b/scripts/windows-desktop-cases.json@@ -0,0 +1,20 @@+{+ "windows11": [+ "install.standard-user",+ "install.console-ready",+ "console.source-plan-agent",+ "update.success",+ "update.digest-before-stop",+ "update.cancel-active-worker",+ "update.replace-rollback",+ "update.killed-resume",+ "update.manual-installer",+ "uninstall.restore-agent"+ ],+ "server": [+ "install.standard-user",+ "install.console-ready",+ "console.source-plan-agent",+ "uninstall.restore-agent"+ ]+}diff --git a/scripts/windows-desktop-session.py b/scripts/windows-desktop-session.pynew file mode 100644index 00000000..47683313--- /dev/null+++ b/scripts/windows-desktop-session.py@@ -0,0 +1,704 @@+#!/usr/bin/env python3+"""Bounded native Desktop acceptance in an existing validation session.++Uses the installed NSIS product, Windows UI Automation and window screenshots.+It never injects browser scripts, creates a login or changes native data roots.+"""+import json+import ctypes+import os+from pathlib import Path+import re+import subprocess+import time+from urllib.parse import urlsplit+++def desktop_state():+ """Read the input desktop in the selected user's actual session; never unlock it."""+ user = ctypes.WinDLL('user32', use_last_error=True)+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)+ user.OpenInputDesktop.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]+ user.OpenInputDesktop.restype = ctypes.c_void_p+ user.GetThreadDesktop.argtypes = [ctypes.c_ulong]+ user.GetThreadDesktop.restype = ctypes.c_void_p+ user.GetUserObjectInformationW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p,+ ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)]+ user.CloseDesktop.argtypes = [ctypes.c_void_p]+ user.GetForegroundWindow.restype = ctypes.c_void_p+ def name(handle):+ text = ctypes.create_unicode_buffer(256)+ size = ctypes.c_ulong()+ if not user.GetUserObjectInformationW(handle, 2, text, ctypes.sizeof(text), ctypes.byref(size)):+ raise ctypes.WinError(ctypes.get_last_error())+ return text.value+ current = name(user.GetThreadDesktop(kernel.GetCurrentThreadId()))+ input_desktop = user.OpenInputDesktop(0, False, 1)+ if not input_desktop:+ return dict(thread_desktop=current, input_desktop=None, interactive=False,+ win32_error=ctypes.get_last_error(), foreground=user.GetForegroundWindow())+ try:+ actual = name(input_desktop)+ return dict(thread_desktop=current, input_desktop=actual, interactive=actual == current == 'Default',+ foreground=user.GetForegroundWindow())+ finally:+ user.CloseDesktop(input_desktop)+++UI = r'''+$ErrorActionPreference='Stop'+[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)+Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type -AssemblyName System.Drawing+Add-Type @'+using System;+using System.Runtime.InteropServices;+public class DesktopWindow {+ [StructLayout(LayoutKind.Sequential)] public struct Rect {public int Left,Top,Right,Bottom;}+ [StructLayout(LayoutKind.Sequential)] public struct MenuBar {public uint Size;public Rect Bounds;public IntPtr Menu,Window;public uint Flags;}+ [StructLayout(LayoutKind.Sequential)] public struct Point {public int X,Y;public Point(int x,int y){X=x;Y=y;}}+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window,int command);+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y);+ [DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint dx,uint dy,uint data,UIntPtr extra);+ [DllImport("user32.dll")] public static extern bool GetMenuBarInfo(IntPtr window,int kind,int item,ref MenuBar info);+ [DllImport("user32.dll")] public static extern int GetMenuItemCount(IntPtr menu);+ [DllImport("user32.dll",CharSet=CharSet.Unicode)] public static extern int GetMenuString(IntPtr menu,uint item,System.Text.StringBuilder text,int capacity,uint flags);+ [DllImport("user32.dll")] public static extern uint GetMenuState(IntPtr menu,uint item,uint flags);+ [DllImport("user32.dll")] public static extern bool GetMenuItemRect(IntPtr window,IntPtr menu,uint item,out Rect rect);+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);+}+'@+$q=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'ui-request.json') -Raw | ConvertFrom-Json+$p=Get-Process -Id $q.pid -ErrorAction Stop+if($p.Path -ne $q.image){throw 'Desktop image changed'}+$p.Refresh()+if($q.action -eq 'tray-observe') {+ $desktop=[Windows.Automation.AutomationElement]::RootElement+ $tops=@($desktop.FindAll([Windows.Automation.TreeScope]::Children,[Windows.Automation.Condition]::TrueCondition))+ $windows=@($tops | Where-Object {($_.Current.ClassName -in @('Shell_TrayWnd','NotifyIconOverflowWindow','TopLevelWindowForOverflowXamlIsland') -or ($_.Current.ClassName -eq '#32768' -and $_.Current.ProcessId -eq $q.pid)) -and -not $_.Current.IsOffscreen})+ $nodes=@(foreach($w in $windows){foreach($e in $w.FindAll([Windows.Automation.TreeScope]::Descendants,[Windows.Automation.Condition]::TrueCondition)){+ @{name=$e.Current.Name;type=$e.Current.ControlType.ProgrammaticName;automation_id=$e.Current.AutomationId;offscreen=$e.Current.IsOffscreen;runtime_id=($e.GetRuntimeId() -join '.');rect=@($e.Current.BoundingRectangle.X,$e.Current.BoundingRectangle.Y,$e.Current.BoundingRectangle.Width,$e.Current.BoundingRectangle.Height)}+ }})+ if($nodes.Count -gt 1600){throw 'Notification observation exceeds its bound'}+ $rect=[Windows.Rect]::Empty+ foreach($w in $windows){$rect.Union($w.Current.BoundingRectangle)}+ if($rect.Width -lt 1 -or $rect.Height -lt 1 -or $rect.Width -gt 4096 -or $rect.Height -gt 4096){throw 'Notification area is not capturable'}+ $bitmap=New-Object Drawing.Bitmap ([int]$rect.Width),([int]$rect.Height)+ $graphics=[Drawing.Graphics]::FromImage($bitmap)+ try {$graphics.CopyFromScreen([int]$rect.X,[int]$rect.Y,0,0,$bitmap.Size);$bitmap.Save((Join-Path $PSScriptRoot 'tray.png'),[Drawing.Imaging.ImageFormat]::Png)}+ finally {$graphics.Dispose();$bitmap.Dispose()}+ @{pid=$p.Id;nodes=$nodes;top_windows=@(foreach($w in $tops){@{name=$w.Current.Name;class=$w.Current.ClassName;pid=$w.Current.ProcessId}})}|ConvertTo-Json -Depth 6 -Compress+ exit 0+}+if($q.action -eq 'quit') {+ $desktop=[Windows.Automation.AutomationElement]::RootElement+ $class=[Windows.Automation.AutomationElement]::ClassNameProperty+ $name=[Windows.Automation.AutomationElement]::NameProperty+ $children=[Windows.Automation.TreeScope]::Children+ $descendants=[Windows.Automation.TreeScope]::Descendants+ function NativeQuit {+ $menus=@($desktop.FindAll($children,[Windows.Automation.Condition]::TrueCondition) | Where-Object {$_.Current.ProcessId -eq $q.pid -and $_.Current.ClassName -eq '#32768' -and -not $_.Current.IsOffscreen})+ if($menus.Count -eq 0){return $false}+ if($menus.Count -ne 1){throw 'More than one measured-process popup menu is visible'}+ $window=[IntPtr]$menus[0].Current.NativeWindowHandle+ $bar=[DesktopWindow+MenuBar]::new()+ $bar.Size=[Runtime.InteropServices.Marshal]::SizeOf($bar)+ # Documented OBJID_CLIENT reads the real popup menu; no app command is injected.+ if(-not [DesktopWindow]::GetMenuBarInfo($window,-4,0,[ref]$bar)){throw 'Cannot inspect the owned native popup menu'}+ $count=[DesktopWindow]::GetMenuItemCount($bar.Menu)+ if($count -lt 1 -or $count -gt 32){throw 'Native popup menu exceeds its bound'}+ $items=@(for($i=0;$i -lt $count;$i++) {+ $text=[Text.StringBuilder]::new(512)+ [void][DesktopWindow]::GetMenuString($bar.Menu,[uint32]$i,$text,512,0x400)+ $rect=[DesktopWindow+Rect]::new()+ if(-not [DesktopWindow]::GetMenuItemRect([IntPtr]::Zero,$bar.Menu,[uint32]$i,[ref]$rect)){throw 'Native menu geometry is unavailable'}+ @{name=$text.ToString();index=$i;state=[DesktopWindow]::GetMenuState($bar.Menu,[uint32]$i,0x400);left=$rect.Left;top=$rect.Top;right=$rect.Right;bottom=$rect.Bottom}+ })+ $items | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $PSScriptRoot 'menu-native-before.json') -Encoding UTF8+ $choice=@($items | Where-Object {$_.name.Replace('&','') -eq 'Quit'})+ if($choice.Count -ne 1 -or ($choice[0].state -band 3) -ne 0){throw 'One enabled native Quit item is required'}+ $item=$choice[0]+ $point=[DesktopWindow+Point]::new([int](($item.left+$item.right)/2),[int](($item.top+$item.bottom)/2))+ if([DesktopWindow]::WindowFromPoint($point) -ne $window){throw 'The observed native menu is obscured'}+ [void][DesktopWindow]::SetCursorPos($point.X,$point.Y)+ [DesktopWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero)+ [DesktopWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero)+ if(-not $p.WaitForExit(10000)){throw 'Native Quit did not exit the measured Desktop'}+ return $true+ }+ if(NativeQuit){@{quit=$true;pid=$p.Id;menu_item='Quit';method='native popup readback and mouse click'}|ConvertTo-Json -Compress;exit 0}+ function QuitItems {+ $windows=$desktop.FindAll($children,[Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::ProcessIdProperty,[int]$q.pid))+ $items=@()+ foreach($w in $windows){$items+=@($w.FindAll($descendants,[Windows.Automation.Condition]::TrueCondition))}+ $menuItems=@($items | Where-Object {$_.Current.ControlType -eq [Windows.Automation.ControlType]::MenuItem -and -not $_.Current.IsOffscreen} | Sort-Object {($_.GetRuntimeId() -join '.')} -Unique)+ @($menuItems | ForEach-Object {@{name=$_.Current.Name;runtime_id=($_.GetRuntimeId() -join '.')}}) | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $PSScriptRoot 'menu-before.json') -Encoding UTF8+ return @($menuItems | Where-Object {$_.Current.Name -eq 'Quit'})+ }+ $quit=@(QuitItems)+ if($quit.Count -eq 0) {+ $bar=$desktop.FindFirst($children,[Windows.Automation.PropertyCondition]::new($class,'Shell_TrayWnd'))+ if($null -eq $bar){throw 'No native notification area'}+ $find=[Windows.Automation.PropertyCondition]::new($name,'HiRoute')+ $icons=@($bar.FindAll($descendants,$find) | Where-Object {-not $_.Current.IsOffscreen})+ $overflowClasses=@('NotifyIconOverflowWindow','TopLevelWindowForOverflowXamlIsland')+ foreach($className in $overflowClasses) {+ $overflow=$desktop.FindFirst($children,[Windows.Automation.PropertyCondition]::new($class,$className))+ if($null -ne $overflow -and -not $overflow.Current.IsOffscreen){$icons+=@($overflow.FindAll($descendants,$find) | Where-Object {-not $_.Current.IsOffscreen})}+ }+ if($icons.Count -eq 0) {+ $chevrons=@($bar.FindAll($descendants,[Windows.Automation.Condition]::TrueCondition) | Where-Object {+ $_.Current.AutomationId -eq 'SystemTrayIcon' -and $_.Current.Name -in @('Show hidden icons','显示隐藏的图标')+ })+ if($chevrons.Count -ne 1){throw 'Observe the notification area before continuing; icon is unavailable'}+ $chevrons[0].GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()+ Start-Sleep -Milliseconds 500+ foreach($className in $overflowClasses) {+ $overflow=$desktop.FindFirst($children,[Windows.Automation.PropertyCondition]::new($class,$className))+ if($null -ne $overflow -and -not $overflow.Current.IsOffscreen){$icons+=@($overflow.FindAll($descendants,$find) | Where-Object {-not $_.Current.IsOffscreen})}+ }+ }+ if($icons.Count -ne 1){throw 'Exactly one visible HiRoute notification icon is required'}+ $icons[0].GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()+ Start-Sleep -Milliseconds 500+ if(NativeQuit){@{quit=$true;pid=$p.Id;menu_item='Quit';method='native popup readback and mouse click'}|ConvertTo-Json -Compress;exit 0}+ $quit=@(QuitItems)+ }+ if($quit.Count -ne 1){throw "The measured Desktop exposed $($quit.Count) native Quit menu items; inspect menu-before.json"}+ $quit[0].GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()+ if(-not $p.WaitForExit(10000)){throw 'Native Quit did not exit the measured Desktop'}+ @{quit=$true;pid=$p.Id;menu_item='Quit'}|ConvertTo-Json -Compress+ exit 0+}+if($p.MainWindowHandle -eq 0){throw 'No visible native Desktop window'}+[void][DesktopWindow]::ShowWindow($p.MainWindowHandle,9)+[void][DesktopWindow]::SetForegroundWindow($p.MainWindowHandle)+Start-Sleep -Milliseconds 500+if([DesktopWindow]::GetForegroundWindow() -ne $p.MainWindowHandle) {+ $r=[Windows.Automation.AutomationElement]::FromHandle($p.MainWindowHandle).Current.BoundingRectangle+ $point=[DesktopWindow+Point]::new([int]($r.X+100),[int]($r.Y+14))+ $owner=[uint32]0+ [void][DesktopWindow]::GetWindowThreadProcessId([DesktopWindow]::WindowFromPoint($point),[ref]$owner)+ if($owner -eq $q.pid) {+ [void][DesktopWindow]::SetCursorPos($point.X,$point.Y)+ [DesktopWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero)+ [DesktopWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero)+ Start-Sleep -Milliseconds 500+ }+}+if([DesktopWindow]::GetForegroundWindow() -ne $p.MainWindowHandle) {+ # Windows may deny a background observer foreground activation. Use the+ # actual taskbar button for this installed AppUserModelID, without attaching+ # another application's input queue or sending it keyboard events.+ $desktop=[Windows.Automation.AutomationElement]::RootElement+ $bar=$desktop.FindFirst([Windows.Automation.TreeScope]::Children,[Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::ClassNameProperty,'Shell_TrayWnd'))+ if($null -ne $bar) {+ $buttons=@($bar.FindAll([Windows.Automation.TreeScope]::Descendants,[Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::AutomationIdProperty,'Appid: ai.hiroute.desktop')) | Where-Object {-not $_.Current.IsOffscreen -and $_.Current.Name.StartsWith('HiRoute')})+ if($buttons.Count -eq 1) {+ if([DesktopWindow]::GetForegroundWindow() -ne $p.MainWindowHandle) {+ $r=$buttons[0].Current.BoundingRectangle+ if($r.Width -lt 2 -or $r.Height -lt 2){throw 'The HiRoute taskbar button has no visible geometry'}+ $point=[DesktopWindow+Point]::new([int]($r.X+$r.Width/2),[int]($r.Y+$r.Height/2))+ $owner=[uint32]0+ [void][DesktopWindow]::GetWindowThreadProcessId([DesktopWindow]::WindowFromPoint($point),[ref]$owner)+ if($owner -ne $bar.Current.ProcessId){throw 'The observed HiRoute taskbar button is obscured'}+ [void][DesktopWindow]::SetCursorPos($point.X,$point.Y)+ [DesktopWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero)+ [DesktopWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero)+ Start-Sleep -Milliseconds 750+ }+ }+ }+}+if([DesktopWindow]::GetForegroundWindow() -ne $p.MainWindowHandle){+ $foreground=[Windows.Automation.AutomationElement]::FromHandle([DesktopWindow]::GetForegroundWindow())+ @{expected=$p.MainWindowHandle.ToInt64();foreground=@{handle=[DesktopWindow]::GetForegroundWindow().ToInt64();pid=$foreground.Current.ProcessId;name=$foreground.Current.Name;class=$foreground.Current.ClassName}}|ConvertTo-Json -Depth 4|Set-Content -LiteralPath (Join-Path $PSScriptRoot 'focus.json') -Encoding UTF8+ throw 'Native Desktop is not foreground; inspect focus.json'+}+$root=[Windows.Automation.AutomationElement]::FromHandle($p.MainWindowHandle)+function Observe($root) {+ $all=$root.FindAll([Windows.Automation.TreeScope]::Descendants,[Windows.Automation.Condition]::TrueCondition)+ # Some WebView2 fragment roots are reachable by a native accessibility hit+ # test before their host HWND exposes a complete descendant tree.+ $r=$root.Current.BoundingRectangle+ $hit=[Windows.Automation.AutomationElement]::FromPoint([Windows.Point]::new($r.X+80,$r.Y+160))+ if($hit.Current.ProcessId -eq $q.pid -or $hit.Current.FrameworkId -eq 'Chrome') {+ $top=$hit+ for($i=0;$i -lt 40;$i++) {+ if($top.Current.ControlType -eq [Windows.Automation.ControlType]::Document){+ return @($all)+@($top)+@($top.FindAll([Windows.Automation.TreeScope]::Descendants,[Windows.Automation.Condition]::TrueCondition))+ }+ $top=[Windows.Automation.TreeWalker]::RawViewWalker.GetParent($top)+ if($null -eq $top -or $top.Equals($root)){break}+ }+ }+ return @($all)+}+$all=@(Observe $root)+if($all.Count -gt 1600){throw 'UI Automation tree exceeds observation bound'}+if($q.action -in @('invoke','text','close','click','scroll')) {+ if($q.action -eq 'close') {+ $root.GetCurrentPattern([Windows.Automation.WindowPattern]::Pattern).Close()+ } elseif($q.action -in @('click','scroll')) {+ $r=$root.Current.BoundingRectangle+ if($q.window -ne $p.MainWindowHandle.ToInt64() -or $q.width -ne $r.Width -or $q.height -ne $r.Height){throw 'Observed window geometry changed'}+ if($q.x -lt 0 -or $q.y -lt 0 -or $q.x -ge $r.Width -or $q.y -ge $r.Height){throw 'Click is outside the observed window'}+ [void][DesktopWindow]::SetCursorPos([int]($r.X+$q.x),[int]($r.Y+$q.y))+ if($q.action -eq 'scroll') {+ if($q.direction -notin @('up','down')){throw 'Invalid scroll direction'}+ $delta=if($q.direction -eq 'down'){-480}else{480}+ $data=[BitConverter]::ToUInt32([BitConverter]::GetBytes([int]$delta),0)+ [DesktopWindow]::mouse_event(0x0800,0,0,$data,[UIntPtr]::Zero)+ } else {+ [DesktopWindow]::mouse_event(2,0,0,0,[UIntPtr]::Zero)+ [DesktopWindow]::mouse_event(4,0,0,0,[UIntPtr]::Zero)+ }+ } else {+ $matches=@($all | Where-Object {($_.GetRuntimeId() -join '.') -eq $q.element.runtime_id} | Select-Object -First 1)+ if($matches.Count -ne 1){throw 'Observed element is no longer unique'}+ $e=$matches[0]+ if($e.Current.Name -ne $q.element.name -or $e.Current.ControlType.ProgrammaticName -ne $q.element.type){throw 'Observed element changed'}+ if(-not $e.Current.IsEnabled -or $e.Current.IsOffscreen){throw 'Element is not interactable'}+ if($q.action -eq 'text') {+ $e.GetCurrentPattern([Windows.Automation.ValuePattern]::Pattern).SetValue($q.text)+ } else {+ $pattern=$null+ if($e.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern,[ref]$pattern)){$pattern.Invoke()}+ elseif($e.TryGetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern,[ref]$pattern)){$pattern.Select()}+ elseif($e.TryGetCurrentPattern([Windows.Automation.TogglePattern]::Pattern,[ref]$pattern)){$pattern.Toggle()}+ elseif($e.TryGetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern,[ref]$pattern)){$pattern.Expand()}+ else {throw 'Element has no supported native action'}+ }+ }+ Start-Sleep -Milliseconds 750+ $p.Refresh()+ if($p.MainWindowHandle -eq 0){@{closed=$true;pid=$p.Id}|ConvertTo-Json -Compress;exit 0}+ $root=[Windows.Automation.AutomationElement]::FromHandle($p.MainWindowHandle)+ $all=@(Observe $root)+}+$nodes=@(foreach($e in $all){+ $c=$e.Current+ @{runtime_id=($e.GetRuntimeId() -join '.');name=$c.Name;type=$c.ControlType.ProgrammaticName;+ automation_id=$c.AutomationId;enabled=$c.IsEnabled;offscreen=$c.IsOffscreen;+ rect=@($c.BoundingRectangle.X,$c.BoundingRectangle.Y,$c.BoundingRectangle.Width,$c.BoundingRectangle.Height)}+})+$r=$root.Current.BoundingRectangle+if($r.Width -lt 100 -or $r.Height -lt 100 -or $r.Width -gt 4096 -or $r.Height -gt 4096){throw 'Window is not capturable'}+$bitmap=New-Object Drawing.Bitmap ([int]$r.Width),([int]$r.Height)+$graphics=[Drawing.Graphics]::FromImage($bitmap)+try {+ $graphics.CopyFromScreen([int]$r.X,[int]$r.Y,0,0,$bitmap.Size)+ $bitmap.Save((Join-Path $PSScriptRoot 'window.png'),[Drawing.Imaging.ImageFormat]::Png)+} finally {$graphics.Dispose();$bitmap.Dispose()}+@{pid=$p.Id;handle=$p.MainWindowHandle.ToInt64();width=$r.Width;height=$r.Height;window=$root.Current.Name;nodes=$nodes}|ConvertTo-Json -Depth 6 -Compress+'''+++def installed(helper, product, pm):+ """Admit actual files, not a process name, window title or a marker alone."""+ roots = helper.locations(Path.home(), Path(os.environ['LOCALAPPDATA']))+ facts = helper.inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA']))+ record = facts.get('marker', {}).get('record', {})+ install = helper.plain(Path(record.get('install_root', '')))+ if (not install.is_absolute() or install.parent != Path.home() / '.local/lib/hiroute'+ or not install.name.endswith(pm['source_revision'][:12])+ or record.get('target') != pm['target']):+ raise ValueError('Installed Desktop does not match the selected product')+ for name in ('hiroute.exe', 'hirouted.exe'):+ if helper.digest(helper.plain(install / name)) != pm['files'][name]['sha256']:+ raise ValueError('Installed product binary changed')+ shell = helper.plain(roots['programs'] / 'hiroute-shell.exe')+ expected = facts.get('shell-package.json', {}).get('record', {}).get('files', {})+ if (helper.digest(shell) != pm['shell_sha256'] or expected.get('hiroute-shell.exe') != pm['shell_sha256']+ or facts.get('shell_inventory_mismatches')):+ raise ValueError('Installed shell differs from measured NSIS member')+ return roots, facts, shell+++def ui_action(run, request, shell, pid, element=None, observed=None):+ state = desktop_state()+ (run / 'desktop-state.json').write_text(json.dumps(state, indent=2), encoding='utf-8')+ if not state['interactive']:+ raise RuntimeError('The existing session input desktop is unavailable; unlock it before native UI acceptance')+ query = dict(pid=pid, image=str(shell), action=request['desktop_action'], element=element,+ text=request.get('text'))+ if request['desktop_action'] in ('click', 'scroll'):+ if request['desktop_action'] == 'scroll' and request.get('scroll_direction') not in ('up', 'down'):+ raise ValueError('Scrolling requires an explicit direction')+ query.update(window=observed['handle'], width=observed['width'], height=observed['height'],+ x=request['x'], y=request['y'], direction=request.get('scroll_direction'))+ (run / 'ui-request.json').write_text(json.dumps(query), encoding='utf-8')+ script = run / 'ui.ps1'+ script.write_text(UI, encoding='utf-8-sig')+ completed = subprocess.run(['powershell.exe', '-NoProfile', '-NonInteractive', '-File', str(script)],+ capture_output=True, timeout=60, creationflags=0x08000000)+ (run / 'ui.stderr').write_bytes(completed.stderr)+ if completed.returncode:+ raise RuntimeError('Native UI Automation failed; inspect ui.stderr before retrying')+ observed = json.loads(completed.stdout.decode('utf-8-sig'))+ (run / 'ui.json').write_text(json.dumps(observed, ensure_ascii=False, indent=2), encoding='utf-8')+ return observed+++def codex_config_path(home, profile):+ if profile not in (None, 'hiroute'):+ raise ValueError('Only the product-owned Codex profile is accepted')+ return home / '.codex' / ('hiroute.config.toml' if profile else 'config.toml')+++def codex_gateway(document, profile):+ codex_config_path(Path.home(), profile)+ selected = document+ target = document.get('model_providers', {}).get('hiroute', {}).get('base_url', '')+ address = urlsplit(target)+ if (selected.get('model_provider') != 'hiroute' or address.scheme != 'http'+ or address.hostname not in ('127.0.0.1', 'localhost', '::1')+ or not address.port or address.username or address.password):+ raise ValueError('Saved Codex configuration must select the local HiRoute Gateway')+ return target+++def codex_call_evidence(stdout, expected, directory_token):+ events = [json.loads(line) for line in stdout.decode('utf-8-sig').splitlines() if line.strip()]+ items = [event.get('item', {}) for event in events if event.get('type') == 'item.completed']+ return dict(turn_completed=any(event.get('type') == 'turn.completed' for event in events),+ answer=any(item.get('type') == 'agent_message' and item.get('text', '').strip() == expected for item in items),+ shell_tool=any(item.get('type') == 'command_execution' and item.get('status') == 'completed'+ and item.get('exit_code') == 0+ and re.search(r'\bGet-Location\b', item.get('command', ''), re.I)+ and directory_token in item.get('aggregated_output', '') for item in items))+++def codex_process(run, command, environment):+ try:+ done = subprocess.run(command, cwd=run, stdin=subprocess.DEVNULL, capture_output=True,+ timeout=150, env=environment, creationflags=0x08000000)+ except subprocess.TimeoutExpired as error:+ (run / 'codex.stdout').write_bytes(error.stdout or b'')+ (run / 'codex.stderr').write_bytes(error.stderr or b'')+ raise+ (run / 'codex.stdout').write_bytes(done.stdout)+ (run / 'codex.stderr').write_bytes(done.stderr)+ return done+++def codex_call(run, request, helper):+ environment = os.environ.copy()+ environment.update(request['config']['environment'])+ environment['PATH'] = ';'.join(request['config']['path']) + ';' + environment['PATH']+ if any(environment.get(name) for name in ('CODEX_HOME', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'CODEX_API_KEY')):+ raise ValueError('Native acceptance requires saved configuration without auth or routing environment overrides')+ import tomllib # This optional native scenario requires the configured Python 3.11+ runtime.+ profile = request.get('codex_profile')+ config = helper.plain(codex_config_path(Path.home(), profile))+ if config.stat().st_size > 4 * 1024 * 1024:+ raise ValueError('Native configuration exceeds evidence bound')+ endpoint = codex_gateway(tomllib.loads(config.read_text(encoding='utf-8-sig')), profile)+ binary = helper.plain(Path(environment['HIROUTE_WORKER_CODEX_BINARY']))+ checksum = helper.digest(binary)+ version = subprocess.run([str(binary), '--version'], stdin=subprocess.DEVNULL,+ capture_output=True, timeout=15, env=environment, creationflags=0x08000000)+ (run / 'codex-version.stdout').write_bytes(version.stdout)+ (run / 'codex-version.stderr').write_bytes(version.stderr)+ if version.returncode or not version.stdout.strip() or len(version.stdout) > 1024:+ raise RuntimeError('The configured native client version could not be measured')+ identity = dict(binary_sha256=checksum, client_version=version.stdout.decode('utf-8-sig').strip(),+ profile=profile, gateway_endpoint=endpoint)+ (run / 'codex-input.json').write_text(json.dumps(identity, indent=2), encoding='utf-8')+ expected = 'HiRoute-Windows-' + request['run_id'] + ':ok'+ inference_only = request.get('desktop_action') == 'codex-inference'+ prompt = (('Do not use any tools or read or modify files. Reply with exactly ' if inference_only else+ 'Do not read or modify any files or change directories. Use your shell tool to run '+ 'the read-only PowerShell command Get-Location in the current working directory. '+ 'Then reply with exactly ') + expected)+ command = [str(binary), 'exec', '--json', '--skip-git-repo-check', '--sandbox', 'read-only',+ '--config', 'approval_policy="never"']+ if profile:+ command += ['--profile', profile]+ command.append(prompt)+ done = codex_process(run, command, environment)+ evidence = codex_call_evidence(done.stdout, expected, run.name)+ evidence.update(identity, exit_code=done.returncode,+ scope='inference_only' if inference_only else 'tool_and_inference',+ native_entry='configured Codex exec; read-only sandbox')+ filename = 'codex-inference.json' if inference_only else 'codex-call.json'+ (run / filename).write_text(json.dumps(evidence, indent=2), encoding='utf-8')+ required = ('turn_completed', 'answer') if inference_only else ('turn_completed', 'answer', 'shell_tool')+ if (helper.digest(binary) != checksum or done.returncode != 0+ or not all(evidence[key] for key in required)):+ if inference_only:+ raise RuntimeError('Native Codex inference did not complete the turn and exact answer checks; inspect private evidence')+ raise RuntimeError('Native Codex call did not complete the real tool and answer checks; inspect private evidence')+ return evidence+++def prepared_installer_replacement(request, pm, helper, activity, manifest, root):+ if (not re.fullmatch(r'[a-f0-9]{32}', request.get('observation_run') or '')+ or not re.fullmatch(r'[a-f0-9]{12}-[a-f0-9]{12}', request.get('from_product') or '')):+ raise ValueError('Installer resume requires explicit inspection and prior product identities')+ observed = root / 'runs' / request['observation_run']+ before = json.loads((observed / 'result.json').read_text(encoding='utf-8'))+ old_request = json.loads((observed / 'request.json').read_text(encoding='utf-8'))+ if (before.get('passed') is not True or before.get('assessment') != 'inspection_only'+ or old_request['product'] != request['product']+ or old_request['config']['session_id'] != request['config']['session_id']+ or time.time() - (observed / 'result.json').stat().st_mtime > 600):+ raise ValueError('Installer resume requires a recent matching installation inspection')+ facts = helper.inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA']))+ for name in ('marker', 'install-pending.json'):+ if facts.get(name, {}).get('sha256') != before['installation'].get(name, {}).get('sha256'):+ raise ValueError('Installation changed after inspection')+ pending = facts.get('install-pending.json', {}).get('record', {})+ if pending.get('schema') != 'hiroute.windows-shell-transaction/v1' or pending.get('phase') != 'prepared':+ raise ValueError('Only the exact prepared shell installation can be resumed')+ prior = manifest(root / 'bundles' / request['from_product'])+ marker = facts['marker']['record']+ previous = helper.plain(Path(marker['install_root']))+ if (previous != Path(pending.get('previous_package') or '') or not previous.name.endswith(prior['source_revision'][:12])+ or previous.parent != Path.home() / '.local/lib/hiroute'):+ raise ValueError('The retained previous package does not match the requested product')+ for name in ('hiroute.exe', 'hirouted.exe'):+ if helper.digest(previous / name) != prior['files'][name]['sha256']:+ raise ValueError('The retained previous product changed')+ programs = helper.plain(Path(facts['programs']['path']))+ shell = helper.plain(programs / 'hiroute-shell.exe')+ if (helper.digest(shell) != pm['shell_sha256'] or pending.get('new', {}).get('hiroute-shell.exe') != pm['shell_sha256']+ or any(Path(p.get('ExecutablePath') or '') == shell for p in activity.get('processes', []))):+ raise ValueError('The measured replacement shell must be present and stopped')+ for name in ('hiroute.exe', 'hirouted.exe'):+ path = helper.plain(programs / 'standalone' / name)+ if helper.digest(path) != pm['files'][name]['sha256']:+ raise ValueError('The replacement product changed')+ return facts, programs, shell+++def quarantine_generated_uninstaller(programs, state, run, expected, pending, helper):+ if (not re.fullmatch(r'[a-f0-9]{64}', expected or '')+ or 'uninstall.exe' in pending.get('new', {}) or not pending.get('old', {}).get('uninstall.exe')):+ raise ValueError('Only an unregistered generated uninstaller can be quarantined manually')+ source = helper.plain(programs / 'uninstall.exe')+ backup = helper.plain(state / 'install-backups/uninstall.exe')+ if (helper.digest(source) != expected or helper.digest(backup) != pending['old']['uninstall.exe']+ or expected == pending['old']['uninstall.exe']):+ raise ValueError('Generated-file or retained-backup identity changed; no file was moved')+ destination = run / 'unregistered-uninstaller.bin'+ if destination.exists():+ raise ValueError('Quarantine destination already exists')+ source.rename(destination)+ if helper.digest(destination) != expected:+ if not source.exists():+ destination.rename(source)+ raise ValueError('Quarantined generated file changed')+ return dict(native_entry='manual quarantine of an independently verified generated file; not installation acceptance',+ sha256=expected, previous_backup_preserved=True, business_data_untouched=True)+++def installer_resume(request, run, pm, helper, activity, manifest, root):+ facts, programs, shell = prepared_installer_replacement(request, pm, helper, activity, manifest, root)+ pending = facts['install-pending.json']['record']+ command = [str(shell), '--installer-install']+ if pending.get('previous_autostart') is False:+ command.append('--no-login-start')+ if facts.get('shell-install.json', {}).get('record', {}).get('tray_enabled') is False:+ command.append('--no-tray')+ done = subprocess.run(command, stdin=subprocess.DEVNULL,+ capture_output=True, timeout=180, creationflags=0x08000000)+ (run / 'installer-resume.stdout').write_bytes(done.stdout)+ (run / 'installer-resume.stderr').write_bytes(done.stderr)+ (run / 'installer-resume.after.json').write_text(json.dumps(+ helper.inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA'])),indent=2),encoding='utf-8')+ if done.returncode:+ raise RuntimeError('The real post-install phase failed; inspect installer-resume.stdout before any further action')+ return dict(native_entry='measured installer post-install phase; not a full NSIS result', exit_code=done.returncode)+++def probe_tls(run, target):+ import hashlib+ import socket+ import ssl+ host, port = target.get('authority', ''), target.get('port')+ if (target.get('scheme') != 'https' or not re.fullmatch(r'[A-Za-z0-9.-]{1,253}', host)+ or not isinstance(port, int) or not 1 <= port <= 65535):+ raise ValueError('TLS diagnostics require a saved HTTPS DNS target')+ context = ssl.create_default_context()+ context.set_alpn_protocols(['h2', 'http/1.1'])+ result = dict(host=host, port=port, certificate_store=context.cert_store_stats(),+ authenticated=False, http_request_sent=False, tls_verified=False)+ try:+ with socket.create_connection((host, port), timeout=8) as stream:+ with context.wrap_socket(stream, server_hostname=host) as secured:+ result.update(tls_verified=True, tls_version=secured.version(),+ alpn=secured.selected_alpn_protocol(),+ peer_certificate_sha256=hashlib.sha256(secured.getpeercert(binary_form=True)).hexdigest())+ except (OSError, ssl.SSLError) as error:+ result.update(error_type=type(error).__name__, error=str(error)[:1024],+ verify_code=getattr(error, 'verify_code', None))+ (run / 'tls-probe.json').write_text(json.dumps(result, indent=2), encoding='utf-8')+ if not result['tls_verified']:+ raise RuntimeError('TLS verification failed before any authenticated or HTTP request; inspect tls-probe.json')+ return result+++def probe_windows_tls(run, target):+ if (target.get('scheme') != 'https'+ or not re.fullmatch(r'[A-Za-z0-9.-]{1,253}', target.get('authority', ''))+ or not isinstance(target.get('port'), int) or not 1 <= target['port'] <= 65535):+ raise ValueError('TLS diagnostics require a saved HTTPS DNS target')+ (run / 'tls-target.json').write_text(json.dumps(target), encoding='utf-8')+ script = run / 'tls-native.ps1'+ script.write_text(r'''+$ErrorActionPreference='Stop'+[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)+$q=Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'tls-target.json') | ConvertFrom-Json+$tcp=[Net.Sockets.TcpClient]::new();$ssl=$null+$result=@{tls_verified=$false;authenticated=$false;http_request_sent=$false;stack='Windows SslStream'}+try {+ $connect=$tcp.ConnectAsync([string]$q.authority,[int]$q.port)+ if(-not $connect.Wait(8000)){throw 'TCP connect timeout'}+ $connect.GetAwaiter().GetResult() | Out-Null+ $ssl=[Net.Security.SslStream]::new($tcp.GetStream(),$false)+ $handshake=$ssl.AuthenticateAsClientAsync([string]$q.authority)+ if(-not $handshake.Wait(8000)){throw 'TLS handshake timeout'}+ $handshake.GetAwaiter().GetResult() | Out-Null+ $result.tls_verified=$true;$result.tls_version=$ssl.SslProtocol.ToString()+} catch {$result.error=$_.Exception.GetBaseException().Message}+finally {if($null -ne $ssl){$ssl.Dispose()};$tcp.Dispose()}+$result | ConvertTo-Json -Compress+''', encoding='utf-8-sig')+ done = subprocess.run(['powershell.exe', '-NoProfile', '-NonInteractive', '-File', str(script)],+ capture_output=True, timeout=30, creationflags=0x08000000)+ (run / 'tls-native.stderr').write_bytes(done.stderr)+ done.check_returncode()+ result = json.loads(done.stdout.decode('utf-8-sig'))+ (run / 'tls-probe.native.json').write_text(json.dumps(result, indent=2), encoding='utf-8')+ if not result.get('tls_verified'):+ raise RuntimeError('Windows system TLS verification failed; inspect tls-probe.native.json')+ return result+++def network_probe(request, run, roots):+ done = subprocess.run([str(roots['stable_cli']), 'compute', 'list', '--output', 'json'],+ capture_output=True, timeout=30, creationflags=0x08000000)+ done.check_returncode()+ envelope = json.loads(done.stdout)+ matches = [s for s in envelope.get('data', {}).get('sources', [])+ if s.get('source_id') == request.get('source_id') and s.get('state') == 'ready']+ if envelope.get('status') != 'succeeded' or len(matches) != 1:+ raise ValueError('Select one ready saved source for unauthenticated TLS diagnosis')+ probe = probe_windows_tls if request.get('native_tls') else probe_tls+ return probe(run, matches[0]['target'])+++def admit_nsis_install(request, helper, activity, manifest, root):+ facts = helper.inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA']))+ previous = request.get('from_product')+ interrupted = request.get('recover_product')+ if interrupted:+ if not previous or not re.fullmatch(r'[a-f0-9]{12}-[a-f0-9]{12}', interrupted):+ raise ValueError('Prepared recovery requires explicit previous and interrupted products')+ prepared_installer_replacement({**request, 'product': interrupted},+ manifest(root / 'bundles' / interrupted), helper, activity, manifest, root)+ elif previous:+ old = root / 'bundles' / previous+ _, _, shell = installed(helper, old, manifest(old))+ if any(Path(p.get('ExecutablePath') or '') == shell for p in activity.get('processes', [])):+ raise ValueError('Quit the old Desktop through its native UI before upgrade')+ elif 'marker' in facts or facts['programs']['exists'] or facts['stable_cli']['exists']:+ raise ValueError('Fresh Desktop installation must not adopt an existing product')+++def execute(request, run, product, pm, helper, activity, manifest, root):+ if activity.get('administrator_groups') is not False:+ raise ValueError('Native Desktop evidence requires a standard account, not a filtered administrator')+ action = request['desktop_action']+ if action not in ('install', 'installer-resume', 'installer-quarantine', 'launch', 'snapshot', 'invoke', 'text', 'click', 'scroll', 'close', 'quit', 'tray-observe', 'desktop-state', 'cli', 'native-files', 'codex-call', 'codex-inference', 'network-probe'):+ raise ValueError('Unknown native Desktop action')+ if action == 'desktop-state':+ return dict(native_entry='read-only input desktop inspection', state=desktop_state())+ if action == 'native-files':+ files = {}+ for relative in ('.codex/config.toml', '.codex/hiroute.config.toml', '.claude/settings.json',+ '.agents/skills/hiroute-collaboration', '.claude/skills/hiroute-collaboration',+ '.agents/skills/hiroute-management', '.claude/skills/hiroute-management'):+ path = helper.plain(Path.home() / relative)+ if not path.exists():+ files[relative] = dict(exists=False)+ elif path.is_file():+ if path.stat().st_size > 4 * 1024 * 1024:+ raise ValueError('Native configuration exceeds evidence bound')+ name = 'native-' + relative.replace('/', '_').lstrip('.')+ (run / name).write_bytes(path.read_bytes())+ files[relative] = dict(exists=True, sha256=helper.digest(path), bytes=path.stat().st_size)+ else:+ files[relative] = dict(exists=True, inventory=helper.inventory(path))+ (run / 'native-files.json').write_text(json.dumps(files, indent=2), encoding='utf-8')+ return dict(native_entry='read-only native configuration inventory', files=files)+ if action == 'installer-resume':+ return installer_resume(request, run, pm, helper, activity, manifest, root)+ if action == 'installer-quarantine':+ facts, programs, _ = prepared_installer_replacement(request, pm, helper, activity, manifest, root)+ return quarantine_generated_uninstaller(programs, Path(facts['shell_state']['path']), run,+ request.get('generated_uninstaller_sha256'), facts['install-pending.json']['record'], helper)+ if action == 'install':+ admit_nsis_install(request, helper, activity, manifest, root)+ previous = request.get('from_product')+ with (run / 'installer.stdout').open('xb') as out, (run / 'installer.stderr').open('xb') as err:+ done = subprocess.run([str(product / 'installer.exe'), '/S'], stdin=subprocess.DEVNULL,+ stdout=out, stderr=err, timeout=150, check=True)+ _, after, _ = installed(helper, product, pm)+ return dict(native_entry='NSIS /S', exit_code=done.returncode, installation=after,+ upgrade_from=previous, recovery_from=request.get('recover_product'),+ installer_sha256=pm['files']['installer.exe']['sha256'])+ roots, facts, shell = installed(helper, product, pm)+ if action == 'network-probe':+ return network_probe(request, run, roots)+ if action in ('codex-call', 'codex-inference'):+ return codex_call(run, request, helper)+ if action == 'launch':+ child = subprocess.Popen([str(shell)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL)+ # A second launch uses the product's single-instance protocol. Discover+ # its real window, rather than assuming this new PID owns the WebView.+ time.sleep(4)+ return dict(native_entry='installed Desktop', launched_pid=child.pid,+ shell_sha256=helper.digest(shell))+ if action == 'cli':+ args = request['cli_args']+ if (not isinstance(args, list) or not args or len(args) > 40+ or any(not isinstance(a, str) or len(a) > 64 * 1024 or '\x00' in a for a in args)+ or args[0] not in ('system', 'service', 'agents', 'agent', 'plans', 'routing', 'gateway', 'compute', 'operations', 'console', 'sessions')):+ raise ValueError('Only bounded public product CLI families are accepted')+ environment = os.environ.copy()+ environment.update(request['config']['environment'])+ environment['PATH'] = ';'.join(request['config']['path']) + ';' + environment['PATH']+ done = subprocess.run([str(roots['stable_cli']), *args], capture_output=True, timeout=150,+ env=environment, creationflags=0x08000000)+ (run / 'cli.stdout').write_bytes(done.stdout)+ (run / 'cli.stderr').write_bytes(done.stderr)+ return dict(native_entry='installed public CLI', exit_code=done.returncode)+ candidates = [p for p in activity.get('processes', []) if Path(p.get('ExecutablePath') or '') == shell]+ if len(candidates) != 1:+ raise ValueError('Exactly one measured installed Desktop process is required')+ pid = candidates[0]['ProcessId']+ element = None+ observed = None+ if action in ('invoke', 'text', 'click', 'scroll'):+ parent = root / 'runs' / request['observation_run']+ old_request = json.loads((parent / 'request.json').read_text(encoding='utf-8'))+ old_result = json.loads((parent / 'result.json').read_text(encoding='utf-8'))+ observed = json.loads((parent / 'ui.json').read_text(encoding='utf-8'))+ if (not old_result.get('passed') or old_request['product'] != request['product']+ or old_request['config']['session_id'] != request['config']['session_id']+ or observed['pid'] != pid or time.time() - (parent / 'ui.json').stat().st_mtime > 600):+ raise ValueError('A recent observation of this exact Desktop process is required')+ if action not in ('click', 'scroll'):+ matches = [e for e in observed['nodes'] if e['runtime_id'] == request['element']]+ if not matches:+ raise ValueError('Choose one observed native UI element')+ element = matches[0]+ return dict(native_entry='Windows UI Automation', observation=ui_action(run, request, shell, pid, element, observed),+ shell_sha256=helper.digest(shell))diff --git a/scripts/windows-dev-host.py b/scripts/windows-dev-host.pyindex b5b33144..ea75e642 100644--- a/scripts/windows-dev-host.py+++ b/scripts/windows-dev-host.py@@ -39,14 +39,15 @@ def identifier(value, pattern=r'[a-f0-9]{32}'):return value-def pe(path):+def pe(path, installer=False):with path.open('rb') as stream:header = stream.read(64)if len(header) != 64 or header[:2] != b'MZ':raise ValueError('Expected a native executable')stream.seek(struct.unpack_from('<I', header, 60)[0])- if stream.read(6) != b'PE\0\0\x64\x86':- raise ValueError('Expected an x64 PE artifact')+ expected = b'PE\0\0\x4c\x01' if installer else b'PE\0\0\x64\x86'+ if stream.read(6) != expected:+ raise ValueError('Expected an NSIS x86 stub' if installer else 'Expected an x64 PE artifact')def manifest(directory):@@ -60,7 +61,10 @@ def manifest(directory):file = plain(directory / name)if file.stat().st_nlink != 1 or file.stat().st_size != expected['bytes'] or digest(file) != expected['sha256']:raise ValueError('Artifact identity differs from its manifest')- pe(file)+ installer = name == 'installer.exe' and value.get('installer_format') == 'nsis'+ if name == 'installer.exe' and not installer:+ raise ValueError('Installer requires an explicit NSIS bundle declaration')+ pe(file, installer=installer)return value@@ -103,7 +107,8 @@ def stage(root, archive, checksum):def ps(script):result = subprocess.run(['powershell.exe', '-NoProfile', '-NonInteractive', '-EncodedCommand',base64.b64encode(script.encode('utf-16le')).decode()],- capture_output=True, text=True, errors='replace', timeout=30)+ capture_output=True, text=True, errors='replace', timeout=30,+ creationflags=0x08000000 if os.name == 'nt' else 0)if result.returncode:raise RuntimeError('Scheduled task operation failed: ' + result.stderr[-1800:])return result.stdout.strip()@@ -130,6 +135,20 @@ def directory(root, run_id):return plain(root / 'runs' / identifier(run_id))+def worker_image(request):+ path = Path(request['config']['python'])+ return path.with_name('pythonw.exe') if request.get('operation') == 'desktop' else path+++def nsis_uninstall_command(executable, programs):+ # NSIS documents an unquoted, last _?= tail to suppress its detached copy.+ # CreateProcess receives this directly; there is no command shell involved.+ value = str(programs)+ if any(c in value for c in '\x00\r\n"'):+ raise ValueError('Invalid native installation directory')+ return subprocess.list2cmdline([str(executable), '/S']) + ' _?=' + value++def private_runs(root, user):path = plain(root / 'runs')# Raw native output stays under a private runner-owned parent. Never repair@@ -159,6 +178,17 @@ foreach($rule in $acl.GetAccessRules($true,$true,$sid)){throw 'Runner evidence directory admits an unrelated identity'}}+$inherit=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'+$full=[Security.AccessControl.FileSystemRights]::FullControl+$ownerRules=@($acl.GetAccessRules($true,$false,$sid)|Where-Object {+ $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Value -eq $target.Value -and+ ($_.FileSystemRights -band $full) -eq $full -and+ ($_.InheritanceFlags -band $inherit) -eq $inherit -and+ $_.PropagationFlags -eq [Security.AccessControl.PropagationFlags]::None+})+if($ownerRules.Count -eq 0){+ throw 'Runner evidence directory does not grant the configured account inheritable access. Use a separate HOME-configured root for this account.'+}'''ps(script)@@ -185,6 +215,9 @@ def start(root, request):manifest(root / 'bundles' / request[field])identifier(request['binary'], r'[A-Za-z0-9_-]+\.exe')identifier(request['case'], r'[A-Za-z0-9_:]+')+ worker_python = plain(worker_image(request))+ if request.get('operation') == 'desktop':+ pe(worker_python)private_runs(root, config['user'])lock = root / 'active.json'# A disconnected controller must not permit concurrent mutation of the same@@ -198,7 +231,7 @@ def start(root, request):script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';"script += '$name=' + literal(task_name(run_id)) + ';'script += "if(Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue){throw 'Task already exists'};"- script += '$a=New-ScheduledTaskAction -Execute ' + literal(config['python']) + ' -Argument ' + literal(arguments) + ';'+ script += '$a=New-ScheduledTaskAction -Execute ' + literal(worker_python) + ' -Argument ' + literal(arguments) + ';'script += '$p=New-ScheduledTaskPrincipal -UserId ' + literal(config['user']) + ' -LogonType Interactive -RunLevel Limited;'script += '$s=New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds ' + str(request['timeout'] + 90) + ') -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries;'script += 'Register-ScheduledTask -TaskName $name -Action $a -Principal $p -Settings $s|Out-Null;Start-ScheduledTask -TaskName $name'@@ -206,6 +239,58 @@ def start(root, request):return dict(run_id=run_id, state='submitted', task=task_name(run_id))+def profile_helper(request):+ import importlib.util+ path = plain(request['profile_helper_path'])+ if digest(path) != request['profile_helper_sha256']:+ raise ValueError('Profile helper differs from the committed request')+ spec = importlib.util.spec_from_file_location('windows_dev_profile', path)+ helper = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(helper)+ return helper+++def desktop_helper(request):+ import importlib.util+ path = plain(request['desktop_helper_path'])+ if digest(path) != request['desktop_helper_sha256']:+ raise ValueError('Desktop helper differs from the committed request')+ spec = importlib.util.spec_from_file_location('windows_desktop_session', path)+ helper = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(helper)+ return helper+++def profile_activity(config, run_id):+ native_home = Path.home()+ roots = [native_home / '.local/share/hiroute', Path(os.environ['LOCALAPPDATA']) / 'HiRoute/cli',+ Path(os.environ['LOCALAPPDATA']) / 'Programs/HiRoute']+ script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';"+ script += '$roots=@(' + ','.join(literal(p) for p in roots) + ');'+ script += '$session=' + str(config['session_id']) + ';$ownTask=' + literal(task_name(run_id)) + ';'+ script += r"""+$identity=[Security.Principal.WindowsIdentity]::GetCurrent()+function InProductPath($value) {+ if(-not $value){return $false}+ foreach($root in $roots){if($value.StartsWith($root+'\',[StringComparison]::OrdinalIgnoreCase)){return $true}}+ return $false+}+$processes=@(Get-CimInstance Win32_Process | Where-Object {+ (InProductPath $_.ExecutablePath) -or ($_.SessionId -eq $session -and $_.Name -in @('hiroute.exe','hirouted.exe','hiroute-shell.exe','hiroute-preflight.exe','hiroute-uninstall-helper.exe','installer.exe','cliproxyapi.exe','windows_headless.exe','windows_desktop.exe'))+} | Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,@{Name='installer_verb';Expression={+ if($_.CommandLine -match '--installer-[a-z-]+|__windows-(?:install|uninstall)'){$Matches[0]}+}},@{Name='created_at';Expression={$_.CreationDate.ToUniversalTime().ToString('o')}})+$tasks=@(Get-ScheduledTask | Where-Object {+ $principal=$_.Principal.UserId+ $ours=$principal -eq $identity.User.Value -or $principal -eq $identity.Name -or $principal -eq $env:USERNAME+ $_.TaskName -ne $ownTask -and $ours -and $_.TaskName -like 'HiRoute*' -and+ ($_.TaskName -notlike 'HiRoute-Dev-*' -or $_.State -eq 'Running')+} | Select-Object TaskName,State)+@{administrator_groups=($identity.Groups.Value -contains 'S-1-5-32-544');processes=$processes;tasks=$tasks}|ConvertTo-Json -Depth 5 -Compress+"""+ return json.loads(ps(script))++def worker(request):config = request['config']root = plain(config['root'])@@ -232,12 +317,101 @@ def worker(request):harness_files=hm['files'], product_files=pm['files'])if request['binary'] not in hm['files'] or not {'hiroute.exe', 'hirouted.exe'} <= set(pm['files']):raise ValueError('The selected manifests do not include required binaries')+ if request.get('operation') == 'desktop':+ if pm.get('installer_format') != 'nsis' or not re.fullmatch(r'[a-f0-9]{64}', pm.get('shell_sha256', '')):+ raise ValueError('Desktop acceptance requires a measured NSIS bundle')+ activity = profile_activity(config, request['run_id'])+ result['profile_activity'] = activity+ outcome = desktop_helper(request).execute(request, run, product, pm, profile_helper(request),+ activity, manifest, root)+ assessment = {'codex-call':'native_codex_gateway_call', 'codex-inference':'native_codex_gateway_inference',+ 'installer-quarantine':'preparation_only',+ 'network-probe':'diagnostic_only'}+ result.update(passed=True, assessment=assessment.get(request.get('desktop_action'),'native_desktop_observation'), desktop=outcome)+ return 0+ if request.get('operation') == 'inspect':+ result.update(passed=True, assessment='inspection_only',+ installation=profile_helper(request).inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA'])),+ profile_activity=profile_activity(config, request['run_id']))+ return 0+ if request.get('operation') in ('archive', 'uninstall', 'probe', 'uninstall-adapter'):+ parent = directory(root, request['inspection_run'])+ inspected = json.loads((parent / 'result.json').read_text(encoding='utf-8'))+ original = json.loads((parent / 'request.json').read_text(encoding='utf-8'))+ if (not inspected.get('passed') or inspected.get('assessment') != 'inspection_only'+ or original.get('operation') != 'inspect'+ or original['config']['user'] != config['user']+ or original['config']['session_id'] != config['session_id']+ or original['product'] != request['product']+ or inspected.get('administrator') is not False+ or time.time() - (parent / 'result.json').stat().st_mtime > 3600):+ raise ValueError('A recent inspection of this standard account and product is required')+ activity = profile_activity(config, request['run_id'])+ result['profile_activity'] = activity+ if request['operation'] in ('uninstall', 'probe', 'uninstall-adapter'):+ helper = profile_helper(request)+ uninstaller, installed = helper.candidate_uninstaller(+ Path.home(), Path(os.environ['LOCALAPPDATA']), inspected['installation'],+ pm, request['shell_sha256'], activity)+ before = helper.locations(Path.home(), Path(os.environ['LOCALAPPDATA']))+ if request['operation'] == 'probe':+ probes = []+ for verb in ('--installer-preflight', '--installer-options'):+ completed = subprocess.run([str(before['programs'] / 'hiroute-shell.exe'), verb],+ stdin=subprocess.DEVNULL, capture_output=True,+ timeout=60, text=True, errors='replace')+ probes.append(dict(verb=verb, exit_code=completed.returncode,+ stdout=completed.stdout[:4096], stderr=completed.stderr[:4096]))+ result.update(passed=True, assessment='read_only_probe', probes=probes)+ return 0+ if request['operation'] == 'uninstall-adapter':+ source = before['programs'] / 'hiroute-shell.exe'+ adapter = run / 'uninstall-adapter.exe'+ shutil.copyfile(plain(source), adapter)+ if digest(adapter) != request['shell_sha256']:+ raise ValueError('Staged native adapter differs from the installed shell')+ with (run / 'adapter.stdout').open('xb') as out, (run / 'adapter.stderr').open('xb') as err:+ completed = subprocess.run([str(adapter), '--installer-uninstall'], stdin=subprocess.DEVNULL,+ stdout=out, stderr=err, timeout=150)+ result.update(passed=completed.returncode == 0, assessment='native_uninstall_adapter_only',+ native_entry='packaged --installer-uninstall', exit_code=completed.returncode,+ installation=helper.inspect_installation(Path.home(), Path(os.environ['LOCALAPPDATA'])))+ return 0 if result['passed'] else 1+ staged = run / 'nsis-uninstaller.exe'+ shutil.copyfile(plain(uninstaller), staged)+ if digest(staged) != digest(uninstaller):+ raise ValueError('Staged NSIS uninstaller differs from its verified inventory')+ deadline = time.monotonic() + request['timeout']+ with (run / 'uninstall.stdout').open('xb') as out, (run / 'uninstall.stderr').open('xb') as err:+ completed = subprocess.run(nsis_uninstall_command(staged, before['programs']), executable=str(staged),+ stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=150, check=True)+ removed = [Path(inspected['installation']['marker']['path']), installed,+ before['stable_cli'], before['programs'] / 'hiroute-shell.exe',+ Path(inspected['installation']['definition']['path'])]+ while any(path.exists() for path in removed):+ if time.monotonic() >= deadline:+ raise TimeoutError('Candidate uninstall did not remove its owned installation')+ time.sleep(0.2)+ result.update(passed=True, assessment='preparation_only', native_entry='NSIS /S',+ exit_code=completed.returncode, versioned_package_removed=True,+ state_preserved=before['state'].exists(),+ inspection_sha256=digest(parent / 'result.json'))+ return 0+ archived = profile_helper(request).archive_orphaned_data(+ Path.home(), Path(os.environ['LOCALAPPDATA']), run,+ inspected['installation'], activity)+ result.update(passed=True, assessment='preparation_only', archival=archived,+ inspection_sha256=digest(parent / 'result.json'))+ return 0# Never manufacture HOME or remove an existing installation to make a gate pass.home = Path.home()for path in (Path(os.environ['LOCALAPPDATA']) / 'HiRoute/cli',home / '.local/share/hiroute/standalone.json', home / '.local/bin/hiroute.exe'):if path.exists():raise ValueError('Disposable installed-product gate found an existing installation')+ if (request['binary'] == 'windows_desktop.exe' and+ request['case'] == 'actual_nsis_silent_install_repeat_console_and_uninstall_preserve_data'):+ profile_helper(request).require_fresh_nsis_packages(home)environment = os.environ.copy()environment.update(config['environment'])for path in config['environment'].values():@@ -305,7 +479,7 @@ def finish(root, run_id):expected = subprocess.list2cmdline([request['driver_path'], '--worker', str(run / 'request.json')])script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';"script += '$t=Get-ScheduledTask -TaskName ' + literal(task_name(run_id)) + ';'- script += "if($t.State -ne 'Ready' -or $t.Actions.Execute -ne " + literal(config['python'])+ script += "if($t.State -ne 'Ready' -or $t.Actions.Execute -ne " + literal(worker_image(request))script += ' -or $t.Actions.Arguments -ne ' + literal(expected) + "){throw 'Owned task is active or differs'};"script += '$t|Unregister-ScheduledTask -Confirm:$false'ps(script)diff --git a/scripts/windows-dev-profile.py b/scripts/windows-dev-profile.pynew file mode 100644index 00000000..b6966b6a--- /dev/null+++ b/scripts/windows-dev-profile.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""Inspect and reversibly archive orphaned HiRoute data for native validation."""+import hashlib+import json+import os+from pathlib import Path+import stat+++def digest(path):+ value = hashlib.sha256()+ with Path(path).open('rb') as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b''):+ value.update(block)+ return value.hexdigest()+++def extended_windows_path(value):+ if value.startswith('\\\\?\\'):+ return value+ if value.startswith('\\\\'):+ return '\\\\?\\UNC\\' + value[2:]+ return '\\\\?\\' + value+++def plain(path):+ path = Path(path)+ for entry in (path, *path.parents):+ try:+ info = entry.lstat()+ except FileNotFoundError:+ continue+ if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 1024:+ raise ValueError('Reparse paths cannot be inspected or archived')+ return path+++def locations(native_home, local_app_data):+ return {'data': native_home / '.local/share/hiroute',+ 'state': local_app_data / 'HiRoute/cli',+ 'shell_state': local_app_data / 'HiRoute/shell',+ 'programs': local_app_data / 'Programs/HiRoute',+ 'stable_cli': native_home / '.local/bin/hiroute.exe'}+++def inspect_installation(native_home, local_app_data):+ """Read this account's installation facts without starting the product."""+ paths, facts = locations(native_home, local_app_data), {}+ for name, path in paths.items():+ plain(path)+ facts[name] = dict(path=str(path), exists=path.exists())+ if path.is_dir():+ facts[name]['entries'] = sorted(p.name for p in path.iterdir())[:50]+ elif path.is_file():+ facts[name].update(sha256=digest(path), bytes=path.stat().st_size)+ marker = plain(paths['data'] / 'standalone.json')+ if marker.is_file():+ if marker.stat().st_size > 64 * 1024:+ raise ValueError('Installation marker exceeds its format bound')+ record = json.loads(marker.read_text(encoding='utf-8'))+ facts['marker'] = dict(path=str(marker), sha256=digest(marker), record=record)+ for name, path in [('installed_cli', Path(record['install_root']) / 'hiroute.exe'),+ ('definition', Path(record['service_definition']))]:+ plain(path)+ facts[name] = dict(path=str(path), exists=path.exists())+ if path.is_file():+ facts[name].update(sha256=digest(path), bytes=path.stat().st_size)+ if name == 'definition' and path.stat().st_size <= 64 * 1024:+ facts[name]['text'] = path.read_text(encoding='utf-8', errors='replace')+ for name in ('shell-package.json', 'shell-install.json', 'uninstall.exe'):+ path = plain(paths['programs'] / name)+ if path.is_file():+ facts[name] = dict(path=str(path), sha256=digest(path), bytes=path.stat().st_size)+ if name.endswith('.json') and path.stat().st_size <= 64 * 1024:+ facts[name]['record'] = json.loads(path.read_text(encoding='utf-8'))+ for name in ('install-pending.json', 'package-cleanup.json', 'update-outcome.json'):+ path = plain(local_app_data / 'HiRoute/shell' / name)+ if path.is_file():+ facts[name] = dict(sha256=digest(path), bytes=path.stat().st_size,+ modified_unix=path.stat().st_mtime)+ if path.stat().st_size <= 64 * 1024:+ facts[name]['record'] = json.loads(path.read_text(encoding='utf-8'))+ journal = plain(paths['data'] / 'service/install-journal.json')+ if journal.is_file():+ facts['install-journal.json'] = dict(sha256=digest(journal), bytes=journal.stat().st_size)+ if journal.stat().st_size <= 64 * 1024:+ facts['install-journal.json']['record'] = json.loads(journal.read_text(encoding='utf-8'))+ diagnostics = plain(paths['state'] / 'diagnostics')+ tails = {}+ if diagnostics.is_dir():+ for path in diagnostics.rglob('*.jsonl'):+ plain(path)+ if len(tails) == 16:+ break+ if path.is_file():+ size = path.stat().st_size+ with path.open('rb') as stream:+ stream.seek(max(0, size - 64 * 1024))+ lines = stream.read(64 * 1024).decode('utf-8', errors='replace').splitlines()+ records = []+ for line in lines:+ try:+ records.append(json.loads(line))+ except ValueError:+ pass # A concurrently written or clipped first/last record is incomplete.+ tails[str(path.relative_to(diagnostics))] = dict(bytes=size, records=records)+ facts['diagnostics_tail'] = tails+ expected = facts.get('shell-package.json', {}).get('record', {}).get('files', {})+ mismatches = []+ for name, wanted in expected.items():+ if (len(name) >= 512 or '\\' in name or any(p in ('', '.', '..') for p in name.split('/'))):+ raise ValueError('Unsafe shell inventory path')+ path = plain(paths['programs'] / name)+ if path.exists() and digest(path) != wanted:+ mismatches.append(name)+ if expected:+ facts['shell_inventory_mismatches'] = mismatches+ backups = plain(local_app_data / 'HiRoute/shell/install-backups')+ if backups.is_dir():+ facts['shell_backup_entries'] = sorted(str(p.relative_to(backups)) for p in backups.rglob('*') if p.is_file())[:100]+ return facts+++def inventory(root):+ """Reject links/special entries before walking or hashing any child."""+ if os.name == 'nt':+ root = Path(extended_windows_path(os.path.abspath(root)))+ def fail(error):+ raise error+ rows = {}+ for directory, children, files in os.walk(plain(root), followlinks=False, onerror=fail):+ for path in (Path(directory), *(Path(directory) / n for n in children + files)):+ plain(path)+ info = path.lstat()+ key = str(path.relative_to(root))+ if stat.S_ISDIR(info.st_mode):+ rows[key] = {'kind': 'directory'}+ elif stat.S_ISREG(info.st_mode):+ rows[key] = dict(kind='file', bytes=info.st_size, sha256=digest(path))+ else:+ raise ValueError('Unknown filesystem entry; retain the original data')+ return rows+++def candidate_uninstaller(native_home, local_app_data, inspected, product, shell_sha256, activity):+ """Admit only the measured candidate's normal, data-preserving NSIS entry."""+ if activity.get('administrator_groups') is not False:+ raise ValueError('Candidate cleanup requires a standard account')+ current = inspect_installation(native_home, local_app_data)+ if current != inspected:+ raise ValueError('Installation changed since inspection')+ marker = current.get('marker', {}).get('record', {})+ install = Path(marker.get('install_root', ''))+ roots = locations(native_home, local_app_data)+ if (marker.get('schema_version') != 'hiroute.standalone-install/v1'+ or marker.get('target') != product['target']+ or install.parent != native_home / '.local/lib/hiroute'+ or not install.name.endswith('-' + product['source_revision'][:12])):+ raise ValueError('Installed product differs from the selected candidate')+ for name in ('hiroute.exe', 'hirouted.exe'):+ if digest(plain(install / name)) != product['files'][name]['sha256']:+ raise ValueError('Installed binary differs from the selected candidate')+ shell = plain(roots['programs'] / 'hiroute-shell.exe')+ uninstaller = plain(roots['programs'] / 'uninstall.exe')+ expected = current.get('shell-package.json', {}).get('record', {}).get('files', {})+ if (digest(shell) != shell_sha256 or expected.get('hiroute-shell.exe') != shell_sha256+ or digest(uninstaller) != expected.get('uninstall.exe')):+ raise ValueError('Uninstaller or shell differs from its measured inventory')+ definition = json.loads(current['definition']['text'])+ if definition.get('manager') != 'task':+ raise ValueError('Only the owned Task candidate can be removed')+ if any(Path(p.get('ExecutablePath') or '') != install / 'hirouted.exe'+ for p in activity.get('processes', [])):+ raise ValueError('Another product or installer is active; preserve it')+ if any(t.get('TaskName') != definition['name'] for t in activity.get('tasks', [])):+ raise ValueError('Another validation or product Task is active; preserve it')+ return uninstaller, install+++def require_fresh_nsis_packages(native_home):+ packages = plain(native_home / '.local/lib/hiroute')+ if packages.exists() and (not packages.is_dir() or next(packages.iterdir(), None) is not None):+ raise ValueError('Fresh NSIS acceptance requires no retained package roots; use the Rust cleanup entry first')+++def archive_orphaned_data(native_home, local_app_data, destination, inspected, activity):+ """Preserve every byte; installed products and live/managed data are refused."""+ if activity.get('administrator_groups') is not False:+ raise ValueError('A standard account without Administrators membership is required')+ if activity.get('processes') or activity.get('tasks'):+ raise ValueError('HiRoute activity remains; use the owning product stop/uninstall entry')+ current = inspect_installation(native_home, local_app_data)+ if current != inspected:+ raise ValueError('Installation facts changed since inspection; inspect again')+ if 'marker' in current or current['programs']['exists'] or current['stable_cli']['exists']:+ raise ValueError('An installed product remains; use its normal uninstall entry first')+ paths = locations(native_home, local_app_data)+ # Moving a managed artifact would invalidate its native Agent reference.+ archived = ('data', 'state', 'shell_state')+ roots = [str(paths[n]).replace('/', '\\').casefold() for n in archived]+ for name in ('.codex/config.toml', '.claude/settings.json',+ '.agents/skills/hiroute-collaboration/SKILL.md'):+ path = plain(native_home / name)+ if path.is_file():+ if path.stat().st_size > 4 * 1024 * 1024:+ raise ValueError('Native configuration needs manual inspection')+ text = path.read_text(encoding='utf-8').replace('\\\\', '\\').replace('/', '\\').casefold()+ if any(root in text for root in roots):+ raise ValueError('Native Agent configuration still references the old data; restore it first')+ plans = []+ for name in archived:+ source, target = paths[name], plain(destination / ('previous-' + name))+ if not source.exists():+ continue+ if not source.is_dir():+ raise ValueError('Unexpected installation data entry; preserve it')+ if target.exists() or source.stat().st_dev != destination.stat().st_dev:+ raise ValueError('Backup needs an unused location on the same volume')+ plans.append((source, target, inventory(source)))+ record = dict(operation='archive_orphaned_installation_data', native_configuration='unchanged',+ paths=[dict(source=str(s), backup=str(t), inventory=rows) for s, t, rows in plans])+ manifest = destination / 'profile-backup.json'+ with manifest.open('x', encoding='utf-8') as stream:+ stream.write(json.dumps(record, indent=2))+ stream.flush()+ os.fsync(stream.fileno())+ moved = []+ try:+ for source, target, expected in plans:+ if inventory(source) != expected:+ raise ValueError('Data changed before archival; preserve it')+ source.rename(target)+ moved.append((source, target))+ if inventory(target) != expected:+ raise ValueError('Archived data differs; restore the preserved directory')+ except Exception:+ for source, target in reversed(moved):+ if not source.exists():+ target.rename(source)+ (destination / 'profile-backup-outcome.json').write_text(json.dumps(dict(+ outcome='restored_after_error', manifest_sha256=digest(manifest))), encoding='utf-8')+ raise+ (destination / 'profile-backup-outcome.json').write_text(json.dumps(dict(+ outcome='archived_and_verified', manifest_sha256=digest(manifest))), encoding='utf-8')+ return dict(archived=[str(t) for _, t in moved], backup_manifest='profile-backup.json',+ native_configuration='unchanged', assessment='preparation_only')diff --git a/scripts/windows-dev.py b/scripts/windows-dev.pyindex c322d1c4..e842ff28 100644--- a/scripts/windows-dev.py+++ b/scripts/windows-dev.py@@ -3,6 +3,7 @@import argparseimport base64import hashlib+import importlib.utilimport jsonimport osfrom pathlib import Path, PureWindowsPath@@ -94,6 +95,39 @@ def python_command(binary, code):encoded + '\'))"; exit $LASTEXITCODE')+def bootstrap_code(root, entries, publish=None):+ """Publish a content-addressed helper once; wait/status never rewrite it."""+ return ('bootstrap_root=' + repr(root) + '\nbootstrap_entries=' + repr(entries) ++ '\nbootstrap_publication=' + repr(publish) + '\n') + '''from pathlib import Path+import hashlib,json,stat+def plain(value):+ p=Path(value)+ for entry in [p,*p.parents]:+ try: info=entry.lstat()+ except FileNotFoundError: continue+ if stat.S_ISLNK(info.st_mode) or getattr(info,'st_file_attributes',0)&1024: raise ValueError('Reparse bootstrap path')+ return p+root=plain(bootstrap_root)+root.mkdir(parents=True,exist_ok=True)+def verify(value,checksum):+ p=plain(value)+ if not p.is_file() or p.stat().st_nlink!=1 or hashlib.sha256(p.read_bytes()).hexdigest()!=checksum: raise ValueError('Bootstrap helper identity changed')+if bootstrap_publication:+ source=plain(bootstrap_publication['temporary']);target=plain(bootstrap_publication['path']);checksum=bootstrap_publication['sha256']+ verify(source,checksum)+ if target.exists():+ verify(target,checksum)+ source.unlink()+ else: source.rename(target)+present=[]+for entry in bootstrap_entries:+ p=plain(entry['path'])+ if p.exists():+ verify(p,entry['sha256']);present.append(entry['sha256'])+print(json.dumps(present))+'''++class Remote:def __init__(self, config):self.config = config@@ -102,8 +136,20 @@ class Remote:'-i', config['identity_file']]def execute(self, script, timeout=65):- result = subprocess.run(['ssh', *self.options, self.config['host'], powershell(script)],- capture_output=True, text=True, timeout=timeout)+ command = powershell(script)+ payload = None+ if len(command) > 6000:+ # Windows OpenSSH may enter through cmd.exe's 8191-character limit.+ # Keep argv bounded; the encoded bridge reads source data to EOF.+ payload = base64.b64encode(script.encode('utf-8')).decode()+ command = powershell(+ "$ErrorActionPreference='Stop';"+ "$source=[Text.Encoding]::UTF8.GetString("+ "[Convert]::FromBase64String([Console]::In.ReadToEnd()));"+ "& ([ScriptBlock]::Create($source))")+ result = subprocess.run(['ssh', *self.options, self.config['host'], command],+ input=payload, capture_output=True, text=True,+ errors='replace', timeout=timeout)if result.returncode:raise RuntimeError('Windows transport failed; no automatic replay was attempted: ' +result.stderr[-2000:])@@ -117,23 +163,38 @@ class Remote:# Uploading source avoids Windows command-line length limits. Only a small# bootstrap enters argv; request data is a separately hashed JSON file.root = self.config['root']- code = "from pathlib import Path; import os; p=Path(" + repr(root) + "); " + (- "assert all(not x.exists() or not (x.lstat().st_file_attributes & 1024) "- "for x in [p,*p.parents]); p.mkdir(parents=True,exist_ok=True)")- self.execute(python_command(self.config['python'], code))source = REPO / 'scripts/windows-dev-host.py'self.driver_hash = digest(source)self.driver = root + '/driver-' + self.driver_hash + '.py'- self.upload(source, self.driver)+ profile = REPO / 'scripts/windows-dev-profile.py'+ self.profile_hash = digest(profile)+ self.profile_helper = root + '/profile-' + self.profile_hash + '.py'+ desktop = REPO / 'scripts/windows-desktop-session.py'+ self.desktop_hash = digest(desktop)+ self.desktop_helper = root + '/desktop-' + self.desktop_hash + '.py'+ sources = [(source,self.driver,self.driver_hash),(profile,self.profile_helper,self.profile_hash),+ (desktop,self.desktop_helper,self.desktop_hash)]+ entries = [dict(path=path,sha256=checksum) for _,path,checksum in sources]+ present = json.loads(self.execute(python_command(self.config['python'], bootstrap_code(root, entries))))+ for local,path,checksum in sources:+ if checksum in present:+ continue+ temporary = path + '.upload-' + uuid.uuid4().hex+ self.upload(local, temporary)+ publication = dict(path=path,temporary=temporary,sha256=checksum)+ self.execute(python_command(self.config['python'], bootstrap_code(root, entries, publication)))def call(self, action, **arguments):- paths = ['scripts/windows-dev.py', 'scripts/windows-dev-host.py', 'scripts/validation.py']+ paths = ['scripts/windows-dev.py', 'scripts/windows-dev-host.py',+ 'scripts/windows-dev-profile.py', 'scripts/windows-desktop-session.py', 'scripts/validation.py']if action == 'run':subprocess.run(['git', 'ls-files', '--error-unmatch', *paths], cwd=REPO,stdout=subprocess.DEVNULL, check=True)if subprocess.check_output(['git', 'status', '--porcelain', '--', *paths], cwd=REPO):raise ValueError('Commit the runner before native product execution')request = dict(action=action, config=self.config, driver_sha256=self.driver_hash,+ profile_helper_path=self.profile_helper, profile_helper_sha256=self.profile_hash,+ desktop_helper_path=self.desktop_helper, desktop_helper_sha256=self.desktop_hash,driver_revision=subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip(),driver_path=self.driver, **arguments)# SSH identity and host never need to reach the Windows execution process.@@ -190,6 +251,68 @@ def bundle(result_path, log_path, output):return dict(bundle_sha256=digest(output), source_revision=sha, files=list(images))+def bundle_desktop(result_path, log_path, output):+ """Export a native release candidate and its exact compiled installer test."""+ result = json.loads(result_path.read_text())+ sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip()+ identity = result.get('desktop_result', {})+ shell_sha256 = identity.get('shell_image', {}).get('sha256', '')+ artifact = result.get('website_artifact', {})+ if (result.get('revision') != sha or result.get('target') != 'x86_64-pc-windows-msvc'+ or result.get('status') != 'awaiting_runtime' or result.get('package_integrity') != 'green'+ or identity.get('revision') != sha or identity.get('native_runtime') != 'not_executed'+ or not re.fullmatch('[a-f0-9]{64}', shell_sha256)+ or artifact.get('kind') != 'desktop' or artifact.get('format') != 'nsis'+ or artifact.get('platform') != 'Windows' or artifact.get('architecture') != 'x86_64'):+ raise ValueError('A matching unassessed native x64 NSIS candidate is required')+ installer = Path(result['assets']) / artifact['filename']+ installer.resolve(strict=True).relative_to(REPO.resolve() / 'target')+ if (digest(installer) != identity.get('installer_sha256') or digest(installer) != artifact.get('sha256')+ or installer.stat().st_size != identity.get('installer_size')):+ raise ValueError('Installer differs from the measured build identity')+ tests = set()+ for line in log_path.read_text().splitlines():+ try:+ row = json.loads(line)+ except ValueError:+ continue+ if (row.get('reason') == 'compiler-artifact' and row.get('target', {}).get('name') == 'windows_desktop'+ and row.get('profile', {}).get('test') is True and row.get('executable')):+ tests.add(Path(row['executable']).resolve(strict=True))+ if len(tests) != 1:+ raise ValueError('Exactly one compiled Windows Desktop test artifact is required')+ binaries = REPO / 'target/x86_64-pc-windows-msvc/release'+ harness = tests.pop()+ harness.relative_to(binaries.resolve(strict=True))+ spec = importlib.util.spec_from_file_location('runtime_audit', Path(__file__).with_name('windows-native-runtime-audit.py'))+ audit = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(audit)+ imports = audit.pe_imports(harness.read_bytes())+ if imports['debug_crt'] or imports['release_vc_runtime']:+ raise ValueError('The native acceptance harness must use static CRT without external VC runtime DLLs')+ payload = REPO / 'apps/shell/src-tauri/resources/standalone'+ if digest(payload / 'package-manifest.json') != identity.get('standalone_manifest_sha256'):+ raise ValueError('Embedded package differs from the installer build identity')+ package = json.loads((payload / 'package-manifest.json').read_text())+ if package.get('revision') != sha or package.get('target') != result['target']:+ raise ValueError('Embedded package source differs from the installer')+ for name in ('hiroute.exe', 'hirouted.exe'):+ expected = package['files']['bin/' + name]+ if digest(payload / name) != expected['sha256'] or (payload / name).stat().st_size != expected['size']:+ raise ValueError('Embedded product bytes differ from the measured package')+ files = {'installer.exe': installer, 'windows_desktop.exe': harness,+ **{name: payload / name for name in ('hiroute.exe', 'hirouted.exe')}}+ manifest = dict(source_revision=sha, target='x86_64-pc-windows-msvc', installer_format='nsis',+ shell_sha256=shell_sha256, native_ci_assessment='not_assessed', files={})+ with zipfile.ZipFile(output, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=1) as archive:+ for name, path in files.items():+ manifest['files'][name] = dict(sha256=digest(path), bytes=path.stat().st_size)+ archive.write(path, name)+ archive.writestr('manifest.json', json.dumps(manifest))+ return dict(bundle_sha256=digest(output), source_revision=sha, files=list(files),+ native_acceptance='not_executed')++def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--config', type=Path, default=CONFIG)@@ -197,6 +320,34 @@ def main():commands.add_parser('doctor')stage = commands.add_parser('stage')stage.add_argument('archive', type=Path)+ inspect = commands.add_parser('inspect-installation')+ inspect.add_argument('--product', required=True)+ archive = commands.add_parser('archive-installation-data')+ archive.add_argument('inspection_run')+ archive.add_argument('--product', required=True)+ uninstall = commands.add_parser('uninstall-candidate')+ uninstall.add_argument('inspection_run')+ uninstall.add_argument('--product', required=True)+ uninstall.add_argument('--shell-sha256', required=True)+ uninstall.add_argument('--probe-only', action='store_true')+ uninstall.add_argument('--adapter-diagnostic', action='store_true', help='Run the verified mutating shell uninstall adapter and retain its typed result; this is not a full NSIS uninstall')+ desktop = commands.add_parser('desktop-session', help='Measured installed Desktop and native UI acceptance')+ desktop.add_argument('--product', required=True)+ desktop.add_argument('--action', dest='desktop_action', required=True,+ choices=('install', 'installer-resume', 'installer-quarantine', 'launch', 'snapshot', 'invoke', 'text', 'click', 'scroll', 'close', 'quit', 'tray-observe', 'desktop-state', 'cli', 'native-files', 'codex-call', 'codex-inference', 'network-probe'))+ desktop.add_argument('--from-product', help='Exact installed bundle admitted before a cross-build upgrade')+ desktop.add_argument('--recover-product', help='Exact interrupted bundle, with a recent inspection, before normal NSIS recovery')+ desktop.add_argument('--observation-run')+ desktop.add_argument('--element', help='Runtime ID from a recent native UI observation')+ desktop.add_argument('--text')+ desktop.add_argument('--x', type=int)+ desktop.add_argument('--y', type=int)+ desktop.add_argument('--scroll-direction', choices=('up', 'down'))+ desktop.add_argument('--codex-profile', choices=('hiroute',), help='Use the product-owned Codex profile instead of the default configuration')+ desktop.add_argument('--source-id', help='One ready saved source for unauthenticated TLS diagnosis')+ desktop.add_argument('--native-tls', action='store_true', help='Compare the Windows system TLS verifier without changing trust policy')+ desktop.add_argument('--generated-uninstaller-sha256', help='Digest independently extracted from the verified failed NSIS artifact, for manual quarantine only')+ desktop.add_argument('--cli-args', type=Path, help='Private JSON array of public CLI arguments')run = commands.add_parser('run')run.add_argument('--harness', required=True)run.add_argument('--product', required=True)@@ -218,8 +369,14 @@ def main():export.add_argument('--result', type=Path, required=True)export.add_argument('--log', type=Path, required=True)export.add_argument('--output', type=Path, required=True)+ export = commands.add_parser('bundle-desktop')+ export.add_argument('--result', type=Path, required=True)+ export.add_argument('--log', type=Path, required=True)+ export.add_argument('--output', type=Path, required=True)args = parser.parse_args()- if args.action == 'bundle':+ if args.action == 'bundle-desktop':+ value = bundle_desktop(args.result, args.log, args.output)+ elif args.action == 'bundle':value = bundle(args.result, args.log, args.output)else:remote = Remote(configuration(args.config))@@ -232,6 +389,67 @@ def main():destination = remote.config['root'] + '/upload-' + checksum + '.zip'remote.upload(args.archive, destination)values = dict(archive=destination, sha256=checksum)+ elif args.action == 'inspect-installation':+ values = dict(run_id=uuid.uuid4().hex, harness=args.product, product=args.product,+ binary='hiroute.exe', case='installation_profile_inspection',+ operation='inspect', ignored=False, timeout=120)+ args.action = 'run'+ elif args.action == 'desktop-session':+ if args.from_product:+ identifier = r'[a-f0-9]{12}-[a-f0-9]{12}'+ if not re.fullmatch(identifier, args.from_product):+ raise ValueError('Expected an explicit prior product bundle')+ if args.recover_product and (args.desktop_action != 'install' or not args.from_product+ or not re.fullmatch(r'[a-f0-9]{12}-[a-f0-9]{12}', args.recover_product)+ or not re.fullmatch(r'[a-f0-9]{32}', args.observation_run or '')):+ raise ValueError('Prepared NSIS recovery requires exact products and a recent inspection')+ if args.desktop_action in ('invoke', 'text'):+ if (not args.observation_run or not re.fullmatch(r'[a-f0-9]{32}', args.observation_run)+ or not args.element or not re.fullmatch(r'[0-9.]+', args.element)):+ raise ValueError('Native interaction requires an observed Runtime ID and run')+ if args.desktop_action == 'network-probe' and (+ not args.source_id or not re.fullmatch(r'source/[A-Za-z0-9._:-]{1,240}', args.source_id)):+ raise ValueError('TLS diagnostics require an explicit saved source identity')+ if args.desktop_action in ('installer-resume', 'installer-quarantine') and (+ not args.from_product or not args.observation_run+ or not re.fullmatch(r'[a-f0-9]{32}', args.observation_run)):+ raise ValueError('Installer resume requires the prior product and a recent installation inspection')+ if args.desktop_action == 'installer-quarantine' and not re.fullmatch(+ r'[a-f0-9]{64}', args.generated_uninstaller_sha256 or ''):+ raise ValueError('Manual quarantine requires the independently measured generated-uninstaller digest')+ if args.desktop_action == 'text' and (args.text is None or len(args.text) > 4096):+ raise ValueError('Native text input requires bounded text')+ if args.desktop_action in ('click', 'scroll'):+ if (not args.observation_run or not re.fullmatch(r'[a-f0-9]{32}', args.observation_run)+ or args.x is None or args.y is None or not 0 <= args.x < 4096 or not 0 <= args.y < 4096):+ raise ValueError('Pointer input requires a recent observed window and bounded coordinates')+ if args.desktop_action == 'scroll' and args.scroll_direction is None:+ raise ValueError('Scrolling requires an explicit direction')+ values.update(run_id=uuid.uuid4().hex, harness=args.product, binary='hiroute.exe',+ case='native_desktop_' + args.desktop_action.replace('-', '_'), operation='desktop', ignored=False, timeout=240)+ values.pop('cli_args')+ if args.desktop_action == 'cli':+ if args.cli_args is None:+ raise ValueError('Public CLI acceptance requires a private argument file')+ values['cli_args'] = json.loads(args.cli_args.read_text(encoding='utf-8'))+ args.action = 'run'+ elif args.action in ('archive-installation-data', 'uninstall-candidate'):+ uninstall = args.action == 'uninstall-candidate'+ values = dict(run_id=uuid.uuid4().hex, harness=args.product, product=args.product,+ binary='hiroute.exe', case='candidate_uninstallation' if uninstall else 'orphaned_installation_data_archival',+ operation='uninstall' if uninstall else 'archive', inspection_run=args.inspection_run,+ ignored=False, timeout=600 if uninstall else 300)+ if uninstall:+ if not re.fullmatch(r'[a-f0-9]{64}', args.shell_sha256):+ raise ValueError('Expected the measured shell SHA-256')+ values['shell_sha256'] = args.shell_sha256+ if args.adapter_diagnostic:+ if args.probe_only:+ raise ValueError('Read-only probing and mutating adapter diagnostics are distinct operations')+ values.update(operation='uninstall-adapter', case='native_uninstall_adapter_diagnostic')+ if args.probe_only:+ values.update(operation='probe', case='candidate_read_only_probe')+ args.action = 'run'elif args.action == 'run':values['run_id'] = uuid.uuid4().hexelif args.action == 'collect':diff --git a/scripts/windows-headless-ci.ps1 b/scripts/windows-headless-ci.ps1index 0e99c977..f1166bea 100644--- a/scripts/windows-headless-ci.ps1+++ b/scripts/windows-headless-ci.ps1@@ -1,5 +1,5 @@param(- [ValidateSet('components','product','background','core','agents','accounts','upgrade')][string]$Scope,+ [ValidateSet('components','product','background','core','agents','accounts','upgrade','install')][string]$Scope,[Parameter(Mandatory)][string]$ExpectedSha,[Parameter(Mandatory)][string]$Evidence,[string]$Plan = 'windows-headless',@@ -48,6 +48,7 @@ from pathlib import Pathspec = importlib.util.spec_from_file_location('native_release_context', Path('scripts/build-release.py'))module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)+# CRT flags are architecture-independent; the native rustc host selects the target.context = module.windows_release_environment('x86_64-pc-windows-msvc', dict(os.environ))print(json.dumps({key: context[key] for key in ('CARGO_ENCODED_RUSTFLAGS', 'CMAKE_TOOLCHAIN_FILE')}))'@@@ -359,7 +360,7 @@ if ($Scope -eq 'components') {foreach ($package in (Get-WindowsCorePackages)) {Invoke-LibraryTests $package}-} elseif ($Scope -in @('background','upgrade')) {+} elseif ($Scope -in @('background','upgrade','install')) {if (-not $InventoryOnly) {cargo build --locked -p hiroute-cli --bin hiroute -p hiroute-daemon --bin hirouted 2>&1 | Tee-Object "$evidence/headless-link.log"if ($LASTEXITCODE -ne 0) { throw 'Production background binaries failed to build' }@@ -377,13 +378,17 @@ if ($Scope -eq 'components') {python scripts/windows-ci-package.py @packageArgs > "$evidence/package-result.json"if ($LASTEXITCODE -ne 0) { throw 'Production package prerequisites failed; background scenarios not executed' }$package = Get-Content "$evidence/package-result.json" -Raw | ConvertFrom-Json+ $env:HIROUTE_WINDOWS_PACKAGE_TARGET = $package.target$env:HIROUTE_WINDOWS_PACKAGE_MANIFEST = $package.manifest$env:HIROUTE_WINDOWS_PACKAGE_ARCHIVE = $package.archive- $env:HIROUTE_WINDOWS_PYTHON = $package.python+ $env:HIROUTE_WINDOWS_PACKAGE_DIRECTORY = $package.package_directory$env:HIROUTE_WINDOWS_ADMIN_CLI = $package.administrator_cli$env:HIROUTE_WORKER_DAEMON_BINARY = $package.worker_daemon}- if ($Scope -eq 'background') {+ if ($Scope -eq 'install') {+ $case = 'task_native_background_lua_gateway_control_stop_crash_recovery_and_autostart'+ Invoke-RequiredTests 'native-install' @('-p','hiroute-daemon','--test','windows_background',$case) @($case) @('--exact','--nocapture')+ } elseif ($Scope -eq 'background') {Invoke-RequiredTests 'background-capture' @('-p','hiroute-daemon','--test','windows_background','windows_token_launcher::capture_tests::') @('windows_token_launcher::capture_tests::native_capture_requires_last_writer_close_for_eof','windows_token_launcher::capture_tests::native_capture_bounds_output_and_never_reports_unknown_stage_data')@@ -634,7 +639,7 @@ if ($Scope -eq 'components') {if ($CaptureArtifacts) {$artifactArgs = @('finalize','--expected-sha',$ExpectedSha,'--evidence',$evidence)if ($Scope -in @('product','background','upgrade','agents','accounts')) { $artifactArgs += '--include-product-binaries' }- if ($Scope -in @('background','upgrade') -and (Test-Path "$evidence/package-result.json") -and (Get-Item "$evidence/package-result.json").Length -gt 0) {+ if ($Scope -in @('background','upgrade','install') -and (Test-Path "$evidence/package-result.json") -and (Get-Item "$evidence/package-result.json").Length -gt 0) {$artifactArgs += @('--package-result',"$evidence/package-result.json")}python scripts/windows-native-artifacts.py @artifactArgs > "$evidence/artifact-finalization.json"diff --git a/scripts/windows-native-artifacts.py b/scripts/windows-native-artifacts.pyindex 17903ee7..21d47a17 100644--- a/scripts/windows-native-artifacts.py+++ b/scripts/windows-native-artifacts.py@@ -28,7 +28,8 @@ MAX_JSON = 32 * 1024 * 1024SOURCE_FILES = ("scripts/build-release.py","scripts/windows-release-toolchain.cmake",- "scripts/install-standalone-windows.py",+ "crates/cli/src/service/windows/install.rs",+ "crates/host-runtime/src/standalone_install/windows.rs","scripts/package-standalone.py","scripts/package-standalone-windows.py","scripts/windows-ci-package.py",diff --git a/scripts/windows-native-replay.ps1 b/scripts/windows-native-replay.ps1index 8939accf..3e317ecd 100644--- a/scripts/windows-native-replay.ps1+++ b/scripts/windows-native-replay.ps1@@ -96,10 +96,11 @@ if ($Scope -in @('background','upgrade')) {python scripts/windows-ci-package.py --restage-only --expected-sha $ExpectedSha --manifest $packageManifest --archive $packageArchive --output "$evidence/package" > "$evidence/package-result.json"if ($LASTEXITCODE -ne 0) { throw 'Fresh administrator package trust could not be established' }$package = Get-Content "$evidence/package-result.json" -Raw | ConvertFrom-Json+ $env:HIROUTE_WINDOWS_PACKAGE_TARGET = $package.target$env:HIROUTE_WINDOWS_PACKAGE_MANIFEST = $package.manifest$env:HIROUTE_WINDOWS_PACKAGE_ARCHIVE = $package.archive$env:HIROUTE_WINDOWS_ADMIN_CLI = $package.administrator_cli- $env:HIROUTE_WINDOWS_PYTHON = $package.python+ $env:HIROUTE_WINDOWS_PACKAGE_DIRECTORY = $package.package_directory$env:HIROUTE_WORKER_DAEMON_BINARY = $package.worker_daemonif ($Scope -eq 'upgrade') {Initialize-WindowsUpgradeBaseline -ExpectedSha $ExpectedSha -BaselineRevision $BaselineRevision -BaselineManifest $BaselineManifest -BaselineArchive $BaselineArchive -Evidence $evidencediff --git a/scripts/windows-native-scopes.ps1 b/scripts/windows-native-scopes.ps1index 1a78db6e..ab34cc47 100644--- a/scripts/windows-native-scopes.ps1+++ b/scripts/windows-native-scopes.ps1@@ -78,6 +78,7 @@ function Get-WindowsRequiredRecipes {'core' { return @(Get-WindowsCorePackages | ForEach-Object { $_ -replace '^hiroute-','core-' }) }'background' { return @((Get-WindowsBackgroundDisposition).Keys) }'upgrade' { return @('upgrade') }+ 'install' { return @('native-install') }'accounts' { return @(Get-WindowsQoderAccountRecipes | ForEach-Object { $_.name }) }'agents' {return @('agent-private-root','agent-private-node','agent-path-identity','agent-managed-path','agent-account-fixture','agent-pi-sdk',diff --git a/scripts/windows-upgrade-inputs.ps1 b/scripts/windows-upgrade-inputs.ps1index b707837b..04ee9600 100644--- a/scripts/windows-upgrade-inputs.ps1+++ b/scripts/windows-upgrade-inputs.ps1@@ -15,10 +15,11 @@ function Initialize-WindowsUpgradeBaseline {if ($LASTEXITCODE -ne 0) { throw 'Fresh baseline administrator trust could not be established' }$baseline = Get-Content -LiteralPath "$Evidence/baseline-package-result.json" -Raw | ConvertFrom-Jsonif ($baseline.source_revision -cne $BaselineRevision -or $baseline.consumer_revision -cne $ExpectedSha -or- $baseline.target -cne 'x86_64-pc-windows-msvc' -or+ $baseline.target -cne $env:HIROUTE_WINDOWS_PACKAGE_TARGET -or$baseline.permission_source -cne 'fresh_verified_complete_extraction' -or$baseline.production_runtime -cne 'not_executed') { throw 'Baseline trust receipt differs from the explicit upgrade inputs' }$env:HIROUTE_WINDOWS_BASELINE_PACKAGE_MANIFEST = $manifest$env:HIROUTE_WINDOWS_BASELINE_PACKAGE_ARCHIVE = $archive$env:HIROUTE_WINDOWS_BASELINE_ADMIN_CLI = $baseline.administrator_cli+ $env:HIROUTE_WINDOWS_BASELINE_PACKAGE_DIRECTORY = $baseline.package_directory}diff --git a/tools/product-e2e/tests/DSH_INTEGRATION.md b/tools/product-e2e/tests/DSH_INTEGRATION.mdindex 63ab3f99..de338a3a 100644--- a/tools/product-e2e/tests/DSH_INTEGRATION.md+++ b/tools/product-e2e/tests/DSH_INTEGRATION.md@@ -35,6 +35,13 @@ credential values. This proves the persisted public configuration is usable;it does not claim DSH's own Web UI was exercised. Desktop acceptance must alsoconfigure and read back the real HiRoute UI and observe a real delegated task.+Native project journeys initialize their owned project as a Git repository.+DSH discovers project Skills from the nearest Git root, so an ancestor repository+must not determine the fixture's project scope.+The controlled main-Agent journey explicitly selects DSH's `danger-full-access`+mode for its fixture-owned commands, matching the Worker journey's `approve-all`+policy. It does not establish `workspace-write` sandbox support on the host.+The initial research/acceptance installation is `0.2.0-rc.2`. Record the actualCLI version and full HiRoute SHA in each run. Production checks required publiccapabilities, not this label. No multi-version matrix, native-history decoder ordiff --git a/tools/product-e2e/tests/PI_INTEGRATION.md b/tools/product-e2e/tests/PI_INTEGRATION.mdindex 4cd48de9..372b47a6 100644--- a/tools/product-e2e/tests/PI_INTEGRATION.md+++ b/tools/product-e2e/tests/PI_INTEGRATION.md@@ -103,6 +103,10 @@ only when handing it to the user.Recovery acceptance also forces a recoverable length stop through the real Pi SDK,requires its persisted `context_edit` omission, and continues the exact recovered session.This is separate from threshold compaction; fixture-only history parsing is not native recovery proof.+The controlled upstream waits for the public Worker read command to expose the+real streamed text before emitting the length terminal frame. This selects the+accepted-stream recovery case independently of TCP frame coalescing; an incomplete+response received before Gateway commits its prefix remains an upstream failure.## Dual-protocol acceptance