Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(desktop): integrate native app and TEST prerelease pipeline (#2062)

Max4e385a10cc62
diff --git a/.github/workflows/desktop-package.yml b/.github/workflows/desktop-package.yml
new file mode 100644
index 000000000..01c7bea46
--- /dev/null
+++ b/.github/workflows/desktop-package.yml
@@ -0,0 +1,270 @@
+name: desktop-self-contained-package
+
+# Manual artifacts retain optional Apple identity signing. Reusable TEST builds
+# receive no signing secrets and always use an ad-hoc app / unsigned installer.
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: SemVer version stamped into the desktop application and installer
+ required: true
+ type: string
+ workflow_call:
+ inputs:
+ version:
+ required: true
+ type: string
+ source_sha:
+ description: Exact peeled commit of the validated TEST tag
+ required: true
+ type: string
+ release_tag:
+ description: Canonical gh-vX.Y.ZrcN TEST tag
+ required: true
+ type: string
+
+permissions:
+ contents: read
+
+env:
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+ CARGO_TERM_COLOR: always
+
+jobs:
+ package:
+ name: ${{ matrix.target }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: aarch64-apple-darwin
+ os: macos-15
+ bundle: app
+ artifact_glob: desktop/target/release/bundle/dmg/*.dmg
+ - target: x86_64-apple-darwin
+ os: macos-15-intel
+ bundle: app
+ artifact_glob: desktop/target/release/bundle/dmg/*.dmg
+ - target: x86_64-pc-windows-msvc
+ os: windows-latest
+ bundle: nsis
+ artifact_glob: desktop/target/release/bundle/nsis/*setup.exe
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+ with:
+ fetch-depth: 0
+ ref: ${{ inputs.source_sha || github.sha }}
+
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
+ with:
+ node-version: "22.23.1"
+ cache: npm
+ cache-dependency-path: |
+ ui/package-lock.json
+ desktop/package-lock.json
+
+ - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
+ with:
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
+ with:
+ path: |
+ ~/.cargo/registry/index
+ ~/.cargo/registry/cache
+ ~/.cargo/git/db
+ desktop/target
+ key: ${{ runner.os }}-${{ matrix.target }}-desktop-package-${{ hashFiles('desktop/Cargo.lock') }}
+ restore-keys: ${{ runner.os }}-${{ matrix.target }}-desktop-package-
+
+ - name: Build Workbench
+ working-directory: ui
+ run: |
+ npm ci
+ npm run build
+
+ - name: Build bootstrap UI
+ working-directory: desktop
+ run: |
+ npm ci
+ npm run build
+
+ - name: Prepare package version
+ shell: bash
+ env:
+ AVIBE_DESKTOP_VERSION: ${{ inputs.version }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ SOURCE_SHA: ${{ inputs.source_sha }}
+ run: |
+ python scripts/desktop_release.py prepare \
+ --version "$AVIBE_DESKTOP_VERSION" --tag "$RELEASE_TAG" \
+ --source-sha "$SOURCE_SHA" --config desktop/tauri.release.conf.json \
+ --env-file "$GITHUB_ENV"
+
+ - name: Build verified private Runtime
+ run: >
+ python desktop/scripts/build-runtime-bundle.py
+ --target "${{ matrix.target }}"
+
+ - name: Clean prior bundle output
+ shell: bash
+ run: rm -rf desktop/target/release/bundle
+
+ # Secrets that are unset expand to the empty string, which tauri-bundler
+ # would read as a present-but-empty certificate and fail on. Export each
+ # variable only when its secret is non-empty, so absence keeps the
+ # unsigned acceptance path exactly as before.
+ - name: Export Apple signing credentials when configured
+ if: runner.os == 'macOS' && inputs.release_tag == ''
+ shell: bash
+ env:
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
+ APPLE_API_PRIVATE_KEY: ${{ secrets.APPLE_API_PRIVATE_KEY }}
+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
+ run: |
+ set -eu
+ # Validate the credential set atomically. Half-configured sets must
+ # fail the build rather than silently produce a lesser artifact:
+ # certificate without notarization credentials would ship
+ # Developer-ID-signed but unnotarized; notarization credentials
+ # without the certificate would submit the unsigned acceptance
+ # build to Apple. All-or-nothing.
+ # Any-set implies all-set within each group; then the two groups
+ # must agree. A partially populated group is an operator error and
+ # fails loudly instead of silently passing as "absent".
+ cert_vars="APPLE_CERTIFICATE:$APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD:$APPLE_CERTIFICATE_PASSWORD"
+ api_vars="APPLE_API_KEY:$APPLE_API_KEY APPLE_API_ISSUER:$APPLE_API_ISSUER APPLE_API_PRIVATE_KEY:$APPLE_API_PRIVATE_KEY"
+ check_group() {
+ group_name="$1"; shift
+ set_count=0; total=0; missing=""
+ for pair in "$@"; do
+ name="${pair%%:*}"; value="${pair#*:}"
+ total=$((total + 1))
+ if [ -n "$value" ]; then set_count=$((set_count + 1)); else missing="$missing $name"; fi
+ done
+ if [ "$set_count" -gt 0 ] && [ "$set_count" -ne "$total" ]; then
+ echo "::error::${group_name} credential group is partially configured; missing:$missing. Set the whole group, or none of it."
+ exit 1
+ fi
+ [ "$set_count" -eq "$total" ]
+ }
+ if check_group "Apple signing" $cert_vars; then have_cert=1; else have_cert=0; fi
+ if check_group "Apple notarization" $api_vars; then have_api=1; else have_api=0; fi
+ if [ "$have_cert" != "$have_api" ]; then
+ echo "::error::Apple credentials are half-configured: the signing group (APPLE_CERTIFICATE + APPLE_CERTIFICATE_PASSWORD) and the notarization group (APPLE_API_KEY + APPLE_API_ISSUER + APPLE_API_PRIVATE_KEY) must be set together or omitted together."
+ exit 1
+ fi
+ if [ "$have_cert" = "1" ]; then
+ echo "APPLE_CERTIFICATE=$APPLE_CERTIFICATE" >> "$GITHUB_ENV"
+ echo "APPLE_CERTIFICATE_PASSWORD=$APPLE_CERTIFICATE_PASSWORD" >> "$GITHUB_ENV"
+ if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then
+ echo "APPLE_SIGNING_IDENTITY=$APPLE_SIGNING_IDENTITY" >> "$GITHUB_ENV"
+ fi
+ # The ApiKey notarization auth needs the .p8 private key ON DISK at
+ # APPLE_API_KEY_PATH; without it tauri-bundler falls back to
+ # searching ./private_keys and $HOME, which the runner never has,
+ # and notarization is skipped with only a warning.
+ key_dir="$(mktemp -d)"
+ key_file="$key_dir/AuthKey_${APPLE_API_KEY}.p8"
+ printf '%s' "$APPLE_API_PRIVATE_KEY" > "$key_file"
+ echo "APPLE_API_KEY=$APPLE_API_KEY" >> "$GITHUB_ENV"
+ echo "APPLE_API_ISSUER=$APPLE_API_ISSUER" >> "$GITHUB_ENV"
+ echo "APPLE_API_KEY_PATH=$key_file" >> "$GITHUB_ENV"
+ echo "apple_signing=enabled" >> "$GITHUB_ENV"
+ else
+ echo "apple_signing=absent" >> "$GITHUB_ENV"
+ fi
+
+ - name: Build self-contained installer
+ working-directory: desktop
+ run: >
+ npm run tauri --
+ build
+ --bundles "${{ matrix.bundle }}"
+ --features bundled-runtime
+ --config tauri.release.conf.json
+
+ # Assert the inner app matches the credentials that were exported. NOTE
+ # the layer boundary recorded here: this describes the .app INSIDE the
+ # DMG only. The DMG image itself and the Mach-O binaries inside the
+ # embedded runtime.zip are NOT signed/notarized by this workflow yet —
+ # those layers are tracked in the distribution-signing-completion issue
+ # and remain release gates.
+ - name: Verify macOS app signature matches the signing path
+ if: runner.os == 'macOS'
+ working-directory: desktop
+ shell: bash
+ run: |
+ set -eu
+ app="target/release/bundle/macos/Avibe.app"
+ [ -d "$app" ] || { echo "Avibe.app not found at $app" >&2; exit 1; }
+ # Same detection as create-macos-dmg.sh: identity signatures print
+ # `Signature size=...` and Authority lines (verbose=4); only ad-hoc
+ # prints `Signature=adhoc`.
+ adhoc="$(codesign -dv "$app" 2>&1 | sed -n 's/^Signature=adhoc$/p' || true)"
+ authority="$(codesign -dv --verbose=4 "$app" 2>&1 | sed -n 's/^Authority=//p' | head -1 || true)"
+ if [ "${apple_signing:-absent}" = "enabled" ]; then
+ if [ -n "$adhoc" ] || [ -z "$authority" ]; then
+ echo "signing credentials were exported but Avibe.app is not identity-signed" >&2
+ exit 1
+ fi
+ codesign --verify --deep --strict "$app"
+ echo "signature_state=app-identity-signed (${authority})" >> "$GITHUB_ENV"
+ else
+ # Seal the complete app before DMG staging and prove the TEST layer.
+ codesign --force --deep --sign - "$app"
+ codesign --verify --deep --strict "$app"
+ codesign -dv "$app" 2>&1 | grep -q '^Signature=adhoc$'
+ echo "signature_state=app-adhoc" >> "$GITHUB_ENV"
+ fi
+
+ - name: Create headless-safe DMG
+ if: runner.os == 'macOS'
+ working-directory: desktop
+ run: >
+ sh scripts/create-macos-dmg.sh
+ target/release/bundle/macos/Avibe.app
+ "target/release/bundle/dmg/Avibe_${{ inputs.version }}_${{ matrix.target }}.dmg"
+
+ - name: Verify unsigned Windows installer
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ $installers = @(Get-ChildItem desktop/target/release/bundle/nsis/*setup.exe)
+ if ($installers.Count -ne 1) { throw "Expected exactly one NSIS installer" }
+ $signature = Get-AuthenticodeSignature $installers[0].FullName
+ if ($signature.Status -ne 'NotSigned') { throw "Expected an unsigned TEST installer" }
+
+ - name: Record artifact hashes
+ shell: bash
+ env:
+ AVIBE_DESKTOP_VERSION: ${{ inputs.version }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ TARGET: ${{ matrix.target }}
+ RUNNER_OS: ${{ runner.os }}
+ run: |
+ set -euo pipefail
+ installers=(${{ matrix.artifact_glob }})
+ [ "${#installers[@]}" -eq 1 ] || { echo "Expected exactly one installer" >&2; exit 1; }
+ if [ "$RUNNER_OS" = "macOS" ]; then
+ signing="${signature_state}"$'\ndmg-unsigned-unnotarized'
+ else
+ signing="installer-unsigned"
+ fi
+ python scripts/desktop_release.py record \
+ --version "$AVIBE_DESKTOP_VERSION" --target "$TARGET" --tag "$RELEASE_TAG" \
+ --source-sha "$(git rev-parse HEAD)" --installer "${installers[0]}" \
+ --runtime desktop/src-tauri/resources/runtime --output desktop-package \
+ --signing "$signing"
+
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: avibe-desktop-${{ inputs.version }}-${{ matrix.target }}
+ path: desktop-package/
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/desktop-shell.yml b/.github/workflows/desktop-shell.yml
new file mode 100644
index 000000000..01a29e50c
--- /dev/null
+++ b/.github/workflows/desktop-shell.yml
@@ -0,0 +1,103 @@
+name: desktop-shell
+
+# The desktop shell is the one part of Avibe that cannot be validated on Linux:
+# it links the system WebView (WKWebView on macOS, WebView2 on Windows). This
+# workflow proves it compiles and passes its own tests on both, and nothing more
+# — bundling and signing belong to a release workflow, not to a PR gate.
+
+on:
+ pull_request:
+ paths:
+ - "desktop/**"
+ - "ui/src/i18n/en.json"
+ - "ui/src/i18n/zh.json"
+ - ".github/workflows/desktop-shell.yml"
+ - ".github/workflows/desktop-package.yml"
+ push:
+ branches:
+ - master
+ paths:
+ - "desktop/**"
+ - "ui/src/i18n/en.json"
+ - "ui/src/i18n/zh.json"
+ - ".github/workflows/desktop-shell.yml"
+ - ".github/workflows/desktop-package.yml"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+env:
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+ CARGO_TERM_COLOR: always
+
+jobs:
+ shell:
+ name: ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [macos-15, windows-latest]
+ defaults:
+ run:
+ working-directory: desktop
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
+ with:
+ node-version: "22.14.0"
+ cache: "npm"
+ cache-dependency-path: desktop/package-lock.json
+
+ # Paths here are workspace-relative; `defaults.run.working-directory`
+ # applies to `run` steps only.
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
+ with:
+ path: |
+ ~/.cargo/registry/index
+ ~/.cargo/registry/cache
+ ~/.cargo/git/db
+ desktop/target
+ key: ${{ runner.os }}-desktop-cargo-${{ hashFiles('desktop/Cargo.lock') }}
+ restore-keys: ${{ runner.os }}-desktop-cargo-
+
+ - name: Report toolchain
+ run: |
+ rustc --version
+ cargo --version
+ node --version
+
+ - name: Install bootstrap UI dependencies
+ run: npm ci
+
+ - name: Verify bootstrap localization contract
+ run: npm run test:i18n
+
+ - name: Validate private Runtime build inputs
+ working-directory: .
+ run: |
+ python -c "import json, pathlib; json.loads(pathlib.Path('desktop/runtime-sources.json').read_text(encoding='utf-8'))"
+ python -m py_compile desktop/scripts/build-runtime-bundle.py
+
+ # Must precede every cargo step: `tauri::generate_context!` embeds
+ # `frontendDist` (../dist) at compile time, so the shell does not compile
+ # until the bootstrap UI has been built.
+ - name: Build bootstrap UI
+ run: npm run build
+
+ - name: Check Rust formatting
+ run: cargo fmt --all -- --check
+
+ - name: Lint Rust
+ run: cargo clippy --workspace --all-targets --all-features -- -D warnings
+
+ - name: Test Rust
+ run: cargo test --workspace --all-features
+
+ - name: Build the shell
+ run: cargo build --workspace
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 754e54b1c..f6ead7629 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -449,3 +449,54 @@ jobs:
if (-not (Select-String -Path vibe-version.log -Pattern 'avibe-os ' -Quiet)) {
throw "vibe version output missing expected marker"
}
+
+ windows-control-ipc:
+ runs-on: windows-latest
+ needs: build-linux-artifacts
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+
+ - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5
+ with:
+ name: vibe-wheel-linux
+ path: dist
+
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+ cache: "pip"
+ cache-dependency-path: |
+ pyproject.toml
+ uv.lock
+
+ - name: Install package and focused test dependency
+ shell: pwsh
+ run: |
+ $wheel = (Get-ChildItem dist\*.whl | Select-Object -First 1).FullName
+ if (-not $wheel) {
+ throw "Missing wheel artifact"
+ }
+ python -m pip install $wheel pytest
+
+ - name: Verify Windows Controller control IPC
+ run: python -m pytest tests/test_control_ipc.py -q
+
+ # Windows byte-range locks are mandatory and per-handle, so a lock taken
+ # over the bytes of a record makes that record unreadable to every other
+ # handle -- including this process's own. Nothing on Linux can observe
+ # that: POSIX file locks are advisory and never deny a read. This is the
+ # one place in CI where the service lock's readability can be tested at
+ # all, and it needs neither a packaged Runtime nor an installer.
+ - name: Verify the Windows service lock keeps its record readable
+ run: python -m pytest tests/test_service_lock_record.py -q
+
+ # `vibe stop` walks every process on the machine before it signals
+ # anything. On Linux a process whose command line psutil cannot read
+ # costs a /proc read; on Windows it cost a `powershell` launch, and a
+ # second `pwsh` when the first said nothing. Only a real Windows process
+ # table holds enough unreadable processes to turn that into a stop that
+ # produces no output and never returns, which is how gh-v3.1.1rc10 died
+ # -- and like the two steps above, showing it needs neither a packaged
+ # Runtime nor an installer, so it does not have to cost a release.
+ - name: Verify the process scan stays off the external shell
+ run: python -m pytest tests/test_runtime_process_scan.py -q
diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.yml
index db53292b8..2b8a54c8b 100644
--- a/.github/workflows/release_ai.yml
+++ b/.github/workflows/release_ai.yml
@@ -27,7 +27,39 @@ permissions:
pull-requests: read
jobs:
+ resolve-desktop-release:
+ if: startsWith(github.event.inputs.tag || github.ref_name, 'gh-v')
+ runs-on: ubuntu-latest
+ outputs:
+ source_sha: ${{ steps.resolve.outputs.source_sha }}
+ version: ${{ steps.resolve.outputs.version }}
+ tag: ${{ steps.resolve.outputs.tag }}
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+ with:
+ # Resolve the requested tag with the tooling that tag carries. An
+ # unpinned checkout would run a dispatched branch's resolver against a
+ # tag it never belonged to. fetch-depth keeps the tag history the
+ # resolver walks.
+ ref: ${{ github.event.inputs.tag || github.ref_name }}
+ fetch-depth: 0
+ - name: Resolve exact TEST source and versions
+ id: resolve
+ env:
+ RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }}
+ run: python scripts/desktop_release.py resolve --tag "$RELEASE_TAG" --output "$GITHUB_OUTPUT"
+
+ desktop-packages:
+ needs: resolve-desktop-release
+ uses: ./.github/workflows/desktop-package.yml
+ with:
+ source_sha: ${{ needs.resolve-desktop-release.outputs.source_sha }}
+ version: ${{ needs.resolve-desktop-release.outputs.version }}
+ release_tag: ${{ needs.resolve-desktop-release.outputs.tag }}
+ # Deliberately no secrets: TEST signing is independent of repository identities.
+
resolve-show-runtime-ref:
+ needs: resolve-desktop-release
if: startsWith(github.event.inputs.tag || github.ref_name, 'gh-v')
runs-on: ubuntu-latest
outputs:
@@ -111,13 +143,14 @@ jobs:
build-assets:
needs:
+ - resolve-desktop-release
- show-runtime-bundles
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
- ref: ${{ github.event.inputs.tag || github.ref }}
+ ref: ${{ needs.resolve-desktop-release.outputs.source_sha }}
- name: Checkout release verification
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
@@ -228,17 +261,28 @@ jobs:
path: dist/
release:
- needs: build-assets
+ needs: [build-assets, resolve-desktop-release, desktop-packages]
+ concurrency:
+ group: avibe-gh-release-${{ github.event.inputs.tag || github.ref_name }}
+ cancel-in-progress: false
# Official assets belong to publish.yml; only previews require this build.
if: >-
${{ !cancelled() && (needs.build-assets.result == 'success' ||
(needs.build-assets.result == 'skipped' &&
- !startsWith(github.event.inputs.tag || github.ref_name, 'gh-v'))) }}
+ !startsWith(github.event.inputs.tag || github.ref_name, 'gh-v'))) &&
+ (!startsWith(github.event.inputs.tag || github.ref_name, 'gh-v') ||
+ (needs.resolve-desktop-release.result == 'success' && needs.desktop-packages.result == 'success')) }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
+ # Publish with the release tooling and installation guidance the
+ # released source carries. resolve-desktop-release is skipped on the
+ # official v* path, so its output is empty there and the requested tag
+ # is the pin. fetch-depth keeps the tag and commit history that notes
+ # generation and the tag/source equality check walk.
+ ref: ${{ needs.resolve-desktop-release.outputs.source_sha || github.event.inputs.tag || github.ref_name }}
fetch-depth: 0
- name: Resolve tag
@@ -579,14 +623,36 @@ jobs:
name: release-dist
path: dist/
+ - name: Download desktop TEST artifacts
+ if: startsWith(steps.tag.outputs.tag, 'gh-v')
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
+ with:
+ pattern: avibe-desktop-${{ needs.resolve-desktop-release.outputs.version }}-*
+ path: desktop-dist/
+ merge-multiple: true
+
+ - name: Validate desktop TEST assets and append installation guidance
+ if: startsWith(steps.tag.outputs.tag, 'gh-v')
+ env:
+ RELEASE_TAG: ${{ steps.tag.outputs.tag }}
+ SOURCE_SHA: ${{ needs.resolve-desktop-release.outputs.source_sha }}
+ run: |
+ test "$(git rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" = "$SOURCE_SHA"
+ python scripts/desktop_release.py verify \
+ --directory desktop-dist --tag "$RELEASE_TAG" --source-sha "$SOURCE_SHA"
+ cat docs/desktop-test-installation.md >> release.md
+
- name: Create GitHub-only Release
if: startsWith(steps.tag.outputs.tag, 'gh-v')
env:
GH_TOKEN: ${{ github.token }}
+ SOURCE_SHA: ${{ needs.resolve-desktop-release.outputs.source_sha }}
shell: bash
run: |
set -euo pipefail
TAG="${{ steps.tag.outputs.tag }}"
+ python scripts/desktop_release.py check-remote \
+ --directory desktop-dist --tag "$TAG" --source-sha "$SOURCE_SHA" --repo "$GITHUB_REPOSITORY"
python scripts/github_release.py update-notes \
--repo "$GITHUB_REPOSITORY" \
--tag "$TAG" \
@@ -603,6 +669,7 @@ jobs:
dist/show-runtime-manifest.json
dist/avibe_os-*.whl dist/avibe_os-*.tar.gz
dist/avibe_memory-*-py3-none-any.whl
+ desktop-dist/*
)
# Packages and runtimes share the same immutable publication boundary.
# Validate every existing byte before uploading even a missing asset.
@@ -637,6 +704,9 @@ jobs:
gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" "${package_to_upload[@]}"
fi
+ python scripts/desktop_release.py check-remote \
+ --directory desktop-dist --tag "$TAG" --source-sha "$SOURCE_SHA" \
+ --repo "$GITHUB_REPOSITORY" --complete
python scripts/github_release.py finalize \
--repo "$GITHUB_REPOSITORY" \
--tag "$TAG" \
diff --git a/config/paths.py b/config/paths.py
index b7816fd1b..090c7ca26 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -190,6 +190,17 @@ def get_runtime_doctor_path() -> Path:
return get_runtime_dir() / "doctor.json"
+def get_runtime_control_ipc_endpoint_path() -> Path:
+ # The Controller hardens the directory holding this descriptor, not just the
+ # file, so that nobody with write access to the directory can swap the
+ # endpoint out from under it. That hardening is only safe over a directory
+ # whose every entry control_ipc created itself, which is why the descriptor
+ # and its lock live one level down instead of in the runtime root. Stamping
+ # the runtime root orphaned the service lock, the captured stdio logs and
+ # the model-hub tree, and that is how gh-v3.1.1rc9 died on Windows.
+ return get_runtime_dir() / "control-ipc" / "endpoint.json"
+
+
def get_config_path() -> Path:
return get_config_dir() / "config.json"
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 8fd096caa..d5432950e 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -101,13 +101,50 @@ class AppCompatConfig:
return [self.platform]
-def to_app_config(v2: V2Config) -> AppCompatConfig:
+def _runtime_agent_cli_path(
+ configured: str | None,
+ default: str,
+ *,
+ resolve_agent_paths: bool,
+) -> str:
+ """Project one saved selector to the executable used by desktop Runtime."""
+
+ selected = str(configured or default)
+ from vibe.upgrade import is_desktop_managed_runtime
+
+ if not resolve_agent_paths or not is_desktop_managed_runtime():
+ return selected
+
+ # GUI-launched processes do not inherit the user's shell PATH. Use the same
+ # resolver as Settings so "installed" and the executable actually launched
+ # by Claude, Codex, or OpenCode can never disagree.
+ from vibe.cli_paths import resolve_cli_path
+
+ # ``include_npm_global`` is the only branch of the resolver that spawns a
+ # process: it shells out to ``npm config get prefix`` with a five-second
+ # timeout, uncached, and only when the CLI was not found by any cheap means.
+ # ``to_app_config`` is reached from async request paths, so that call would
+ # block an event loop for up to five seconds per missing backend. The cheap
+ # candidates it keeps -- ~/.local/bin, ~/.bun/bin, Homebrew, /usr/local/bin
+ # and every NVM version -- already cover what a GUI-launched Runtime needs.
+ return resolve_cli_path(selected, include_npm_global=False) or selected
+
+
+def to_app_config(
+ v2: V2Config,
+ *,
+ resolve_agent_paths: bool = True,
+) -> AppCompatConfig:
claude = ClaudeCompatConfig(
enabled=v2.agents.claude.enabled,
permission_mode="bypassPermissions",
cwd=v2.runtime.default_cwd,
system_prompt=None,
- cli_path=v2.agents.claude.cli_path,
+ cli_path=_runtime_agent_cli_path(
+ v2.agents.claude.cli_path,
+ "claude",
+ resolve_agent_paths=resolve_agent_paths,
+ ),
idle_timeout_seconds=v2.agents.claude.idle_timeout_seconds,
# Forward V2Config auth fields so ``session_handler`` can inject the
# right ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_BASE_URL`` env vars when
@@ -122,7 +159,11 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
if v2.agents.codex.enabled:
codex = CodexCompatConfig(
enabled=True,
- binary=v2.agents.codex.cli_path,
+ binary=_runtime_agent_cli_path(
+ v2.agents.codex.cli_path,
+ "codex",
+ resolve_agent_paths=resolve_agent_paths,
+ ),
extra_args=[],
idle_timeout_seconds=v2.agents.codex.idle_timeout_seconds,
auth_mode=v2.agents.codex.auth_mode,
@@ -131,7 +172,11 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
if v2.agents.opencode.enabled:
opencode = OpenCodeCompatConfig(
enabled=True,
- binary=v2.agents.opencode.cli_path,
+ binary=_runtime_agent_cli_path(
+ v2.agents.opencode.cli_path,
+ "opencode",
+ resolve_agent_paths=resolve_agent_paths,
+ ),
port=4096,
request_timeout_seconds=60,
default_reasoning_effort=v2.agents.opencode.default_reasoning_effort,
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 2b28d6ec0..21a4076b5 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -99,7 +99,12 @@ class NativeCredentialLease:
not stat.S_ISREG(info.st_mode)
or info.st_nlink != 1
or (hasattr(os, "getuid") and info.st_uid != os.getuid())
- or info.st_mode & 0o077
+ # POSIX-only: Windows synthesizes st_mode from file
+ # attributes, so a writable file always reports 0o666 and the
+ # 0o600 above cannot change it. Asserting it there would
+ # reject every lease rather than describe one. The equivalent
+ # guarantee on Windows is an ACL check, not a mode mask.
+ or (os.name == "posix" and info.st_mode & 0o077)
):
raise OSError("Unsafe native lease file")
if not _try_lock(handle):
diff --git a/core/control_ipc.py b/core/control_ipc.py
new file mode 100644
index 000000000..4f57f06a9
--- /dev/null
+++ b/core/control_ipc.py
@@ -0,0 +1,1162 @@
+"""Cross-platform transport contract for the Controller's internal HTTP API."""
+
+from __future__ import annotations
+
+import errno
+import hmac
+import json
+import os
+import re
+import secrets
+import socket
+import stat
+import tempfile
+from abc import ABC, abstractmethod
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Callable, Iterator, Optional
+
+from config import paths
+
+CONTROL_IPC_SCHEMA_VERSION = 1
+CONTROL_IPC_INSTANCE_HEADER = "X-Avibe-Control-Instance"
+MAX_DESCRIPTOR_BYTES = 4096
+_SOCKET_MODE = 0o600
+_SOCKET_UMASK_MODE = 0o700
+_UNSUPPORTED_SOCKET_CHMOD_ERRNOS = frozenset(
+ value
+ for value in (
+ errno.EINVAL,
+ getattr(errno, "ENOTSUP", None),
+ getattr(errno, "EOPNOTSUPP", None),
+ )
+ if value is not None
+)
+_DESCRIPTOR_FIELDS = frozenset(
+ {
+ "schema_version",
+ "transport",
+ "host",
+ "port",
+ "instance_id",
+ "bearer_token",
+ }
+)
+_INSTANCE_ID_RE = re.compile(r"[0-9a-f]{32}")
+_BEARER_TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{43,128}")
+
+
+class ControlIpcDescriptorError(ValueError):
+ """Raised when the Windows endpoint descriptor is absent or invalid."""
+
+
+class ControlIpcSecurityError(PermissionError):
+ """Raised when a Windows control IPC path is not private to its owner."""
+
+
+@dataclass(frozen=True)
+class ControlIpcDescriptor:
+ schema_version: int
+ transport: str
+ host: str
+ port: int
+ instance_id: str
+ bearer_token: str = field(repr=False)
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "schema_version": self.schema_version,
+ "transport": self.transport,
+ "host": self.host,
+ "port": self.port,
+ "instance_id": self.instance_id,
+ "bearer_token": self.bearer_token,
+ }
+
+
+@dataclass(frozen=True)
+class BoundControlIpc:
+ listener: socket.socket
+ transport: str
+ socket_path: Optional[Path] = None
+ descriptor: Optional[ControlIpcDescriptor] = None
+
+
+@dataclass(frozen=True)
+class ControlIpcClientEndpoint:
+ transport: str
+ socket_path: Optional[Path] = None
+ descriptor: Optional[ControlIpcDescriptor] = None
+
+ @property
+ def base_url(self) -> str:
+ if self.descriptor is None:
+ return "http://localhost"
+ return f"http://{self.descriptor.host}:{self.descriptor.port}"
+
+ @property
+ def headers(self) -> dict[str, str]:
+ if self.descriptor is None:
+ return {}
+ return {"Authorization": f"Bearer {self.descriptor.bearer_token}"}
+
+
+def default_unix_socket_path() -> Path:
+ override = os.environ.get("VIBE_INTERNAL_DISPATCH_SOCKET")
+ if override:
+ return Path(override).expanduser()
+ return paths.get_state_dir() / "dispatch.sock"
+
+
+def default_descriptor_path() -> Path:
+ return paths.get_runtime_control_ipc_endpoint_path()
+
+
+class ControlIpcHost(ABC):
+ """Own one pre-bound listener and its discoverable endpoint lifecycle."""
+
+ instance_id: Optional[str] = None
+ bearer_token: Optional[str] = None
+
+ @abstractmethod
+ def bind(self) -> BoundControlIpc:
+ raise NotImplementedError
+
+ @abstractmethod
+ def publish(self, bound: BoundControlIpc) -> None:
+ raise NotImplementedError
+
+ @abstractmethod
+ def cleanup(self, bound: BoundControlIpc) -> None:
+ raise NotImplementedError
+
+
+class PosixUnixSocketHost(ControlIpcHost):
+ def __init__(self, socket_path: Optional[Path] = None):
+ self.socket_path = (socket_path or default_unix_socket_path()).expanduser().resolve()
+
+ def bind(self) -> BoundControlIpc:
+ target = self.socket_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _remove_stale_owned_socket(target)
+
+ previous_umask = os.umask(0o077)
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ listener.bind(str(target))
+ listener.listen(2048)
+ listener.setblocking(False)
+ try:
+ os.chmod(target, _SOCKET_MODE)
+ except OSError as error:
+ if error.errno not in _UNSUPPORTED_SOCKET_CHMOD_ERRNOS:
+ raise
+ _verify_owned_socket(target, allow_umask_mode=True)
+ else:
+ _verify_owned_socket(target)
+ return BoundControlIpc(
+ listener=listener,
+ transport="unix",
+ socket_path=target,
+ )
+ except Exception:
+ listener.close()
+ _remove_socket_after_bind_failure(target)
+ raise
+ finally:
+ os.umask(previous_umask)
+
+ def publish(self, bound: BoundControlIpc) -> None:
+ if bound.transport != "unix" or bound.socket_path != self.socket_path:
+ raise ValueError("bound endpoint does not belong to this Unix socket host")
+
+ def cleanup(self, bound: BoundControlIpc) -> None:
+ try:
+ bound.listener.close()
+ except OSError:
+ pass
+ target = bound.socket_path
+ if target is None:
+ return
+ try:
+ _verify_owned_socket(target, allow_umask_mode=True)
+ target.unlink()
+ except FileNotFoundError:
+ return
+ except OSError:
+ pass
+
+
+def _remove_stale_owned_socket(target: Path) -> None:
+ try:
+ metadata = target.lstat()
+ except FileNotFoundError:
+ return
+ if hasattr(os, "getuid") and metadata.st_uid != os.getuid():
+ raise OSError("control IPC socket owner mismatch")
+ target.unlink()
+
+
+def _remove_socket_after_bind_failure(target: Path) -> None:
+ try:
+ metadata = target.lstat()
+ if stat.S_ISSOCK(metadata.st_mode) and (
+ not hasattr(os, "getuid") or metadata.st_uid == os.getuid()
+ ):
+ target.unlink()
+ except (FileNotFoundError, OSError):
+ return
+
+
+def _verify_owned_socket(target: Path, *, allow_umask_mode: bool = False) -> None:
+ metadata = target.lstat()
+ if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISSOCK(metadata.st_mode):
+ raise OSError("control IPC socket is unsafe")
+ if hasattr(os, "getuid") and metadata.st_uid != os.getuid():
+ raise OSError("control IPC socket owner mismatch")
+ allowed_modes = (
+ {_SOCKET_MODE, _SOCKET_UMASK_MODE}
+ if allow_umask_mode
+ else {_SOCKET_MODE}
+ )
+ if stat.S_IMODE(metadata.st_mode) not in allowed_modes:
+ raise OSError("control IPC socket mode mismatch")
+
+
+class WindowsLoopbackHost(ControlIpcHost):
+ def __init__(
+ self,
+ descriptor_path: Optional[Path] = None,
+ *,
+ socket_factory: Callable[[int, int], socket.socket] = socket.socket,
+ max_bind_attempts: int = 3,
+ instance_id: Optional[str] = None,
+ bearer_token: Optional[str] = None,
+ ):
+ self.descriptor_path = _absolute_path(descriptor_path or default_descriptor_path())
+ self.socket_factory = socket_factory
+ self.max_bind_attempts = max(1, max_bind_attempts)
+ self.instance_id = instance_id or secrets.token_hex(16)
+ self.bearer_token = bearer_token or secrets.token_urlsafe(32)
+ _validate_instance_id(self.instance_id)
+ _validate_bearer_token(self.bearer_token)
+
+ def bind(self) -> BoundControlIpc:
+ for attempt in range(1, self.max_bind_attempts + 1):
+ listener = self.socket_factory(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ exclusive = getattr(socket, "SO_EXCLUSIVEADDRUSE", None)
+ if exclusive is not None:
+ listener.setsockopt(socket.SOL_SOCKET, exclusive, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(2048)
+ listener.setblocking(False)
+ host, port = listener.getsockname()[:2]
+ descriptor = ControlIpcDescriptor(
+ schema_version=CONTROL_IPC_SCHEMA_VERSION,
+ transport="tcp",
+ host=str(host),
+ port=int(port),
+ instance_id=self.instance_id,
+ bearer_token=self.bearer_token,
+ )
+ validate_descriptor(descriptor.to_dict())
+ return BoundControlIpc(
+ listener=listener,
+ transport="tcp",
+ descriptor=descriptor,
+ )
+ except OSError as exc:
+ listener.close()
+ if exc.errno == errno.EADDRINUSE and attempt < self.max_bind_attempts:
+ continue
+ raise
+ except Exception:
+ listener.close()
+ raise
+ raise AssertionError("unreachable")
+
+ def publish(self, bound: BoundControlIpc) -> None:
+ descriptor = bound.descriptor
+ if (
+ bound.transport != "tcp"
+ or descriptor is None
+ or descriptor.instance_id != self.instance_id
+ or not hmac.compare_digest(descriptor.bearer_token, self.bearer_token)
+ ):
+ raise ValueError("bound endpoint does not belong to this Windows host")
+ write_descriptor_atomic(self.descriptor_path, descriptor)
+
+ def cleanup(self, bound: BoundControlIpc) -> None:
+ try:
+ bound.listener.close()
+ except OSError:
+ pass
+ remove_descriptor_if_owned(
+ self.descriptor_path,
+ instance_id=self.instance_id,
+ bearer_token=self.bearer_token,
+ )
+
+
+def select_control_ipc_host(
+ *,
+ platform_name: Optional[str] = None,
+ socket_path: Optional[Path] = None,
+ descriptor_path: Optional[Path] = None,
+) -> ControlIpcHost:
+ platform_name = platform_name or os.name
+ if platform_name == "nt":
+ if socket_path is not None:
+ raise ValueError("Windows control IPC does not accept a Unix socket path")
+ return WindowsLoopbackHost(descriptor_path)
+ return PosixUnixSocketHost(socket_path)
+
+
+def resolve_client_endpoint(
+ *,
+ platform_name: Optional[str] = None,
+ socket_path: Optional[Path] = None,
+ descriptor_path: Optional[Path] = None,
+) -> ControlIpcClientEndpoint:
+ platform_name = platform_name or os.name
+ if socket_path is not None or platform_name != "nt":
+ target = (socket_path or default_unix_socket_path()).expanduser().resolve()
+ return ControlIpcClientEndpoint(transport="unix", socket_path=target)
+ descriptor = load_descriptor(descriptor_path or default_descriptor_path())
+ return ControlIpcClientEndpoint(transport="tcp", descriptor=descriptor)
+
+
+def validate_descriptor(payload: object) -> ControlIpcDescriptor:
+ if not isinstance(payload, dict):
+ raise ControlIpcDescriptorError("control IPC descriptor must be a JSON object")
+ if frozenset(payload) != _DESCRIPTOR_FIELDS:
+ raise ControlIpcDescriptorError("control IPC descriptor fields are invalid")
+
+ schema_version = payload.get("schema_version")
+ if type(schema_version) is not int or schema_version != CONTROL_IPC_SCHEMA_VERSION:
+ raise ControlIpcDescriptorError("control IPC descriptor schema is unsupported")
+ if payload.get("transport") != "tcp":
+ raise ControlIpcDescriptorError("control IPC descriptor transport is unsupported")
+ if payload.get("host") != "127.0.0.1":
+ raise ControlIpcDescriptorError("control IPC descriptor host is not loopback")
+
+ port = payload.get("port")
+ if type(port) is not int or not 1 <= port <= 65535:
+ raise ControlIpcDescriptorError("control IPC descriptor port is invalid")
+
+ instance_id = payload.get("instance_id")
+ bearer_token = payload.get("bearer_token")
+ _validate_instance_id(instance_id)
+ _validate_bearer_token(bearer_token)
+ return ControlIpcDescriptor(
+ schema_version=schema_version,
+ transport="tcp",
+ host="127.0.0.1",
+ port=port,
+ instance_id=instance_id,
+ bearer_token=bearer_token,
+ )
+
+
+def load_descriptor(descriptor_path: Path) -> ControlIpcDescriptor:
+ target = _absolute_path(descriptor_path)
+ try:
+ with _descriptor_lock(target, prepare_directory=False):
+ return _load_descriptor_unlocked(target)
+ except ControlIpcDescriptorError:
+ raise
+ except OSError as exc:
+ raise ControlIpcDescriptorError(f"control IPC descriptor is unavailable at {target}") from exc
+
+
+def _load_descriptor_unlocked(target: Path) -> ControlIpcDescriptor:
+ if target.is_symlink():
+ raise ControlIpcDescriptorError(f"control IPC descriptor is a symlink at {target}")
+
+ flags = os.O_RDONLY
+ flags |= getattr(os, "O_CLOEXEC", 0)
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(target, flags)
+ except OSError as exc:
+ raise ControlIpcDescriptorError(f"control IPC descriptor is unavailable at {target}") from exc
+
+ try:
+ metadata = os.fstat(fd)
+ if not stat.S_ISREG(metadata.st_mode):
+ raise ControlIpcDescriptorError(f"control IPC descriptor is not a regular file at {target}")
+ if os.name == "nt":
+ _windows_security().validate_file_descriptor(fd, target)
+ if metadata.st_size <= 0 or metadata.st_size > MAX_DESCRIPTOR_BYTES:
+ raise ControlIpcDescriptorError(f"control IPC descriptor size is invalid at {target}")
+ with os.fdopen(fd, "r", encoding="utf-8") as stream:
+ fd = -1
+ raw = stream.read(MAX_DESCRIPTOR_BYTES + 1)
+ except (OSError, UnicodeError) as exc:
+ raise ControlIpcDescriptorError(f"control IPC descriptor is unreadable at {target}") from exc
+ finally:
+ if fd >= 0:
+ os.close(fd)
+
+ if len(raw.encode("utf-8")) > MAX_DESCRIPTOR_BYTES:
+ raise ControlIpcDescriptorError(f"control IPC descriptor size is invalid at {target}")
+ try:
+ payload = json.loads(raw)
+ except (TypeError, json.JSONDecodeError) as exc:
+ raise ControlIpcDescriptorError(f"control IPC descriptor JSON is invalid at {target}") from exc
+ return validate_descriptor(payload)
+
+
+def write_descriptor_atomic(
+ descriptor_path: Path,
+ descriptor: ControlIpcDescriptor,
+) -> None:
+ descriptor = validate_descriptor(descriptor.to_dict())
+ target = _absolute_path(descriptor_path)
+ _ensure_private_directory(target.parent, allow_repair=True)
+ with _descriptor_lock(target, prepare_directory=True):
+ if os.name == "nt":
+ fd, temporary = _windows_security().create_private_temporary_file(target)
+ else:
+ fd, temporary_name = tempfile.mkstemp(
+ prefix=f".{target.name}.",
+ suffix=".tmp",
+ dir=target.parent,
+ )
+ temporary = Path(temporary_name)
+ try:
+ if os.name != "nt":
+ try:
+ os.chmod(temporary, 0o600)
+ except OSError:
+ pass
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
+ fd = -1
+ json.dump(
+ descriptor.to_dict(),
+ stream,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+ stream.write("\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ if os.name == "nt" and target.exists():
+ if target.is_symlink():
+ raise ControlIpcSecurityError(f"control IPC descriptor security is invalid at {target}")
+ _windows_security().secure_existing_owned_path(target)
+ os.replace(temporary, target)
+ if os.name == "nt":
+ _windows_security().validate_path(target)
+ finally:
+ if fd >= 0:
+ os.close(fd)
+ try:
+ temporary.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def remove_descriptor_if_owned(
+ descriptor_path: Path,
+ *,
+ instance_id: str,
+ bearer_token: str,
+) -> bool:
+ target = _absolute_path(descriptor_path)
+ try:
+ with _descriptor_lock(target, prepare_directory=False):
+ try:
+ descriptor = _load_descriptor_unlocked(target)
+ except ControlIpcDescriptorError:
+ return False
+ if descriptor.instance_id != instance_id or not hmac.compare_digest(
+ descriptor.bearer_token,
+ bearer_token,
+ ):
+ return False
+ try:
+ target.unlink()
+ except FileNotFoundError:
+ return False
+ return True
+ except OSError:
+ return False
+
+
+def response_instance_matches(
+ descriptor: ControlIpcDescriptor,
+ response_instance_id: Optional[str],
+) -> bool:
+ return bool(response_instance_id) and hmac.compare_digest(
+ descriptor.instance_id,
+ response_instance_id,
+ )
+
+
+def _validate_instance_id(value: object) -> None:
+ if not isinstance(value, str) or _INSTANCE_ID_RE.fullmatch(value) is None:
+ raise ControlIpcDescriptorError("control IPC descriptor instance is invalid")
+
+
+def _validate_bearer_token(value: object) -> None:
+ if not isinstance(value, str) or _BEARER_TOKEN_RE.fullmatch(value) is None:
+ raise ControlIpcDescriptorError("control IPC descriptor credential is invalid")
+
+
+def _ensure_private_directory(directory: Path, *, allow_repair: bool = False) -> None:
+ if os.name == "nt":
+ _windows_security().ensure_private_directory(directory, allow_repair=allow_repair)
+ return
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ try:
+ os.chmod(directory, 0o700)
+ except OSError:
+ pass
+
+
+def _absolute_path(path: Path) -> Path:
+ return Path(os.path.abspath(os.fspath(path.expanduser())))
+
+
+@contextmanager
+def _descriptor_lock(
+ descriptor_path: Path,
+ *,
+ prepare_directory: bool,
+) -> Iterator[None]:
+ lock_path = descriptor_path.with_name(f"{descriptor_path.name}.lock")
+ _ensure_private_directory(lock_path.parent, allow_repair=prepare_directory)
+ if os.name == "nt":
+ fd = _windows_security().open_private_lock_file(
+ lock_path,
+ allow_repair=prepare_directory,
+ )
+ else:
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
+ try:
+ if os.name != "nt":
+ try:
+ os.chmod(lock_path, 0o600)
+ except OSError:
+ pass
+ if os.fstat(fd).st_size == 0:
+ os.write(fd, b"\0")
+ os.fsync(fd)
+ os.lseek(fd, 0, os.SEEK_SET)
+ if os.name == "nt":
+ import msvcrt
+
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ os.lseek(fd, 0, os.SEEK_SET)
+ if os.name == "nt":
+ import msvcrt
+
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ finally:
+ os.close(fd)
+
+
+class _WindowsSecurity:
+ """Minimal Win32 owner/DACL operations for control IPC artifacts."""
+
+ _SDDL_REVISION_1 = 1
+ _SE_FILE_OBJECT = 1
+ _OWNER_SECURITY_INFORMATION = 0x00000001
+ _DACL_SECURITY_INFORMATION = 0x00000004
+ _PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
+ _SE_DACL_PRESENT = 0x0004
+ _SE_DACL_PROTECTED = 0x1000
+ _TOKEN_QUERY = 0x0008
+ _TOKEN_USER = 1
+ _TOKEN_OWNER = 4
+ _ERROR_INSUFFICIENT_BUFFER = 122
+ _ERROR_FILE_EXISTS = 80
+ _ERROR_ALREADY_EXISTS = 183
+ _GENERIC_READ = 0x80000000
+ _GENERIC_WRITE = 0x40000000
+ _FILE_SHARE_READ = 0x00000001
+ _FILE_SHARE_WRITE = 0x00000002
+ _FILE_SHARE_DELETE = 0x00000004
+ _CREATE_NEW = 1
+ _OPEN_ALWAYS = 4
+ _FILE_ATTRIBUTE_NORMAL = 0x00000080
+ _ACL_SIZE_INFORMATION_CLASS = 2
+
+ def __init__(self) -> None:
+ import ctypes
+ from ctypes import wintypes
+
+ self.ctypes = ctypes
+ self.wintypes = wintypes
+ self.advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+
+ class SecurityAttributes(ctypes.Structure):
+ _fields_ = [
+ ("nLength", wintypes.DWORD),
+ ("lpSecurityDescriptor", wintypes.LPVOID),
+ ("bInheritHandle", wintypes.BOOL),
+ ]
+
+ class SidAndAttributes(ctypes.Structure):
+ _fields_ = [
+ ("Sid", wintypes.LPVOID),
+ ("Attributes", wintypes.DWORD),
+ ]
+
+ class TokenUser(ctypes.Structure):
+ _fields_ = [("User", SidAndAttributes)]
+
+ class TokenOwner(ctypes.Structure):
+ _fields_ = [("Owner", wintypes.LPVOID)]
+
+ class AclSizeInformation(ctypes.Structure):
+ _fields_ = [
+ ("AceCount", wintypes.DWORD),
+ ("AclBytesInUse", wintypes.DWORD),
+ ("AclBytesFree", wintypes.DWORD),
+ ]
+
+ self.SecurityAttributes = SecurityAttributes
+ self.TokenUser = TokenUser
+ self.TokenOwner = TokenOwner
+ self.AclSizeInformation = AclSizeInformation
+ self._configure_functions()
+ self.current_user_sid = self._read_current_user_sid()
+ # Windows stamps newly created objects with the token's *default owner*,
+ # which is BUILTIN\Administrators for an elevated token rather than the
+ # token user. Both SIDs therefore name "an object this process made".
+ self.current_owner_sid = self._read_current_owner_sid()
+ # The ACEs carry no inheritance flags on purpose. Every object this
+ # module secures -- the endpoint directory, the descriptor and the lock
+ # -- is created here with this descriptor applied explicitly, so nothing
+ # depends on inheriting it. Adding OI/CI would not fix anything and
+ # would push this policy onto files control IPC does not own; the
+ # directory boundary in paths.get_runtime_control_ipc_endpoint_path is
+ # what keeps that set closed.
+ self.sddl = f"O:{self.current_user_sid}D:P(A;;FA;;;{self.current_user_sid})(A;;FA;;;SY)"
+
+ def _configure_functions(self) -> None:
+ ctypes = self.ctypes
+ wintypes = self.wintypes
+
+ self.advapi32.OpenProcessToken.argtypes = [
+ wintypes.HANDLE,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.HANDLE),
+ ]
+ self.advapi32.OpenProcessToken.restype = wintypes.BOOL
+ self.advapi32.GetTokenInformation.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ wintypes.LPVOID,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ self.advapi32.GetTokenInformation.restype = wintypes.BOOL
+ self.advapi32.ConvertSidToStringSidW.argtypes = [
+ wintypes.LPVOID,
+ ctypes.POINTER(wintypes.LPWSTR),
+ ]
+ self.advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
+ self.advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ self.advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
+ self.advapi32.GetSecurityDescriptorOwner.argtypes = [
+ wintypes.LPVOID,
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.BOOL),
+ ]
+ self.advapi32.GetSecurityDescriptorOwner.restype = wintypes.BOOL
+ self.advapi32.GetSecurityDescriptorDacl.argtypes = [
+ wintypes.LPVOID,
+ ctypes.POINTER(wintypes.BOOL),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.BOOL),
+ ]
+ self.advapi32.GetSecurityDescriptorDacl.restype = wintypes.BOOL
+ self.advapi32.GetSecurityDescriptorControl.argtypes = [
+ wintypes.LPVOID,
+ ctypes.POINTER(wintypes.WORD),
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ self.advapi32.GetSecurityDescriptorControl.restype = wintypes.BOOL
+ self.advapi32.GetSecurityInfo.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ]
+ self.advapi32.GetSecurityInfo.restype = wintypes.DWORD
+ self.advapi32.GetNamedSecurityInfoW.argtypes = [
+ wintypes.LPWSTR,
+ ctypes.c_int,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ctypes.POINTER(wintypes.LPVOID),
+ ]
+ self.advapi32.GetNamedSecurityInfoW.restype = wintypes.DWORD
+ self.advapi32.SetNamedSecurityInfoW.argtypes = [
+ wintypes.LPWSTR,
+ ctypes.c_int,
+ wintypes.DWORD,
+ wintypes.LPVOID,
+ wintypes.LPVOID,
+ wintypes.LPVOID,
+ wintypes.LPVOID,
+ ]
+ self.advapi32.SetNamedSecurityInfoW.restype = wintypes.DWORD
+ self.advapi32.EqualSid.argtypes = [wintypes.LPVOID, wintypes.LPVOID]
+ self.advapi32.EqualSid.restype = wintypes.BOOL
+ self.advapi32.GetAclInformation.argtypes = [
+ wintypes.LPVOID,
+ wintypes.LPVOID,
+ wintypes.DWORD,
+ ctypes.c_int,
+ ]
+ self.advapi32.GetAclInformation.restype = wintypes.BOOL
+ self.advapi32.GetAce.argtypes = [
+ wintypes.LPVOID,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.LPVOID),
+ ]
+ self.advapi32.GetAce.restype = wintypes.BOOL
+
+ self.kernel32.GetCurrentProcess.argtypes = []
+ self.kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ self.kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ self.kernel32.CloseHandle.restype = wintypes.BOOL
+ self.kernel32.LocalFree.argtypes = [wintypes.HLOCAL]
+ self.kernel32.LocalFree.restype = wintypes.HLOCAL
+ self.kernel32.CreateDirectoryW.argtypes = [
+ wintypes.LPCWSTR,
+ ctypes.POINTER(self.SecurityAttributes),
+ ]
+ self.kernel32.CreateDirectoryW.restype = wintypes.BOOL
+ self.kernel32.CreateFileW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ ctypes.POINTER(self.SecurityAttributes),
+ wintypes.DWORD,
+ wintypes.DWORD,
+ wintypes.HANDLE,
+ ]
+ self.kernel32.CreateFileW.restype = wintypes.HANDLE
+
+ def _read_current_user_sid(self) -> str:
+ return self._read_token_sid(self._TOKEN_USER, self.TokenUser, lambda info: info.User.Sid, "user")
+
+ def _read_current_owner_sid(self) -> str:
+ return self._read_token_sid(self._TOKEN_OWNER, self.TokenOwner, lambda info: info.Owner, "owner")
+
+ def _read_token_sid(self, information_class: int, structure: type, select, label: str) -> str:
+ ctypes = self.ctypes
+ wintypes = self.wintypes
+ token = wintypes.HANDLE()
+ if not self.advapi32.OpenProcessToken(
+ self.kernel32.GetCurrentProcess(),
+ self._TOKEN_QUERY,
+ ctypes.byref(token),
+ ):
+ self._raise_last_error("cannot open the current process token")
+ try:
+ required = wintypes.DWORD()
+ self.advapi32.GetTokenInformation(
+ token,
+ information_class,
+ None,
+ 0,
+ ctypes.byref(required),
+ )
+ if ctypes.get_last_error() != self._ERROR_INSUFFICIENT_BUFFER:
+ self._raise_last_error("cannot size the current process token")
+ buffer = ctypes.create_string_buffer(required.value)
+ if not self.advapi32.GetTokenInformation(
+ token,
+ information_class,
+ buffer,
+ required,
+ ctypes.byref(required),
+ ):
+ self._raise_last_error("cannot read the current process token")
+ information = ctypes.cast(buffer, ctypes.POINTER(structure)).contents
+ sid_text = wintypes.LPWSTR()
+ if not self.advapi32.ConvertSidToStringSidW(
+ select(information),
+ ctypes.byref(sid_text),
+ ):
+ self._raise_last_error(f"cannot encode the current {label} SID")
+ try:
+ value = sid_text.value
+ if not value:
+ raise ControlIpcSecurityError(f"the current process token has no {label} SID")
+ return value
+ finally:
+ self.kernel32.LocalFree(ctypes.cast(sid_text, wintypes.HLOCAL))
+ finally:
+ self.kernel32.CloseHandle(token)
+
+ @contextmanager
+ def _security_descriptor(self) -> Iterator[object]:
+ with self._descriptor_from_sddl(self.sddl) as descriptor:
+ yield descriptor
+
+ def _self_owner_sddls(self) -> tuple[str, ...]:
+ """Every SDDL owner this process can legitimately have created a path as.
+
+ An unelevated token owns what it creates as the token user. An elevated
+ token owns it as the token's default owner, normally
+ ``BUILTIN\\Administrators``. Both are "us"; anything else is not.
+ """
+
+ if self.current_owner_sid == self.current_user_sid:
+ return (self.sddl,)
+ return (self.sddl, f"O:{self.current_owner_sid}")
+
+ def _owner_is_self(self, owner: object) -> bool:
+ if not owner:
+ return False
+ for sddl in self._self_owner_sddls():
+ with self._descriptor_from_sddl(sddl) as expected:
+ if bool(self.advapi32.EqualSid(owner, self._descriptor_owner(expected))):
+ return True
+ return False
+
+ @contextmanager
+ def _descriptor_from_sddl(self, sddl: str) -> Iterator[object]:
+ ctypes = self.ctypes
+ wintypes = self.wintypes
+ descriptor = wintypes.LPVOID()
+ size = wintypes.DWORD()
+ if not self.advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ sddl,
+ self._SDDL_REVISION_1,
+ ctypes.byref(descriptor),
+ ctypes.byref(size),
+ ):
+ self._raise_last_error("cannot construct the private security descriptor")
+ try:
+ yield descriptor
+ finally:
+ self.kernel32.LocalFree(descriptor)
+
+ @contextmanager
+ def _security_attributes(self) -> Iterator[object]:
+ ctypes = self.ctypes
+ with self._security_descriptor() as descriptor:
+ attributes = self.SecurityAttributes(
+ nLength=ctypes.sizeof(self.SecurityAttributes),
+ lpSecurityDescriptor=descriptor,
+ bInheritHandle=False,
+ )
+ yield attributes
+
+ def ensure_private_directory(self, directory: Path, *, allow_repair: bool) -> None:
+ directory = _absolute_path(directory)
+ if directory.exists():
+ if not directory.is_dir() or directory.is_symlink():
+ raise ControlIpcSecurityError(f"control IPC runtime directory security is invalid at {directory}")
+ if allow_repair:
+ self.secure_existing_owned_path(directory)
+ else:
+ self.validate_path(directory)
+ return
+
+ directory.parent.mkdir(parents=True, exist_ok=True)
+ with self._security_attributes() as attributes:
+ if not self.kernel32.CreateDirectoryW(str(directory), self.ctypes.byref(attributes)):
+ error = self.ctypes.get_last_error()
+ if error != self._ERROR_ALREADY_EXISTS:
+ raise ControlIpcSecurityError(
+ f"cannot create the control IPC runtime directory at {directory}"
+ ) from self.ctypes.WinError(error)
+ self.validate_path(directory)
+
+ def open_private_lock_file(self, path: Path, *, allow_repair: bool) -> int:
+ if path.exists():
+ if path.is_symlink() or not path.is_file():
+ raise ControlIpcSecurityError(f"control IPC lock security is invalid at {path}")
+ if allow_repair:
+ self.secure_existing_owned_path(path)
+ fd = self._create_file(
+ path,
+ creation_disposition=self._OPEN_ALWAYS,
+ share_mode=(self._FILE_SHARE_READ | self._FILE_SHARE_WRITE | self._FILE_SHARE_DELETE),
+ )
+ try:
+ self.validate_file_descriptor(fd, path)
+ except Exception:
+ os.close(fd)
+ raise
+ return fd
+
+ def create_private_temporary_file(self, target: Path) -> tuple[int, Path]:
+ for _ in range(128):
+ temporary = target.with_name(f".{target.name}.{secrets.token_hex(16)}.tmp")
+ try:
+ fd = self._create_file(
+ temporary,
+ creation_disposition=self._CREATE_NEW,
+ share_mode=0,
+ )
+ except FileExistsError:
+ continue
+ try:
+ self.validate_file_descriptor(fd, temporary)
+ except Exception:
+ os.close(fd)
+ temporary.unlink(missing_ok=True)
+ raise
+ return fd, temporary
+ raise FileExistsError(f"cannot allocate a private descriptor beside {target}")
+
+ def _create_file(
+ self,
+ path: Path,
+ *,
+ creation_disposition: int,
+ share_mode: int,
+ ) -> int:
+ import msvcrt
+
+ with self._security_attributes() as attributes:
+ handle = self.kernel32.CreateFileW(
+ str(path),
+ self._GENERIC_READ | self._GENERIC_WRITE,
+ share_mode,
+ self.ctypes.byref(attributes),
+ creation_disposition,
+ self._FILE_ATTRIBUTE_NORMAL,
+ None,
+ )
+ invalid_handle = self.ctypes.c_void_p(-1).value
+ if handle == invalid_handle:
+ error = self.ctypes.get_last_error()
+ if error in {self._ERROR_FILE_EXISTS, self._ERROR_ALREADY_EXISTS}:
+ raise FileExistsError(error, os.strerror(error), str(path))
+ raise ControlIpcSecurityError(
+ f"cannot create the private control IPC file at {path}"
+ ) from self.ctypes.WinError(error)
+ try:
+ return msvcrt.open_osfhandle(
+ handle,
+ os.O_RDWR | getattr(os, "O_BINARY", 0),
+ )
+ except Exception:
+ self.kernel32.CloseHandle(handle)
+ raise
+
+ def secure_existing_owned_path(self, path: Path) -> None:
+ if not self._named_path_owner_matches(path):
+ raise ControlIpcSecurityError(f"control IPC path is not owned by the current user at {path}")
+ with self._security_descriptor() as expected:
+ expected_dacl = self._descriptor_dacl(expected)
+ result = self.advapi32.SetNamedSecurityInfoW(
+ str(path),
+ self._SE_FILE_OBJECT,
+ self._DACL_SECURITY_INFORMATION | self._PROTECTED_DACL_SECURITY_INFORMATION,
+ None,
+ None,
+ expected_dacl,
+ None,
+ )
+ if result:
+ raise ControlIpcSecurityError(
+ f"cannot secure the control IPC path at {path}"
+ ) from self.ctypes.WinError(result)
+ self.validate_path(path)
+
+ def validate_path(self, path: Path) -> None:
+ ctypes = self.ctypes
+ owner = self.wintypes.LPVOID()
+ dacl = self.wintypes.LPVOID()
+ descriptor = self.wintypes.LPVOID()
+ result = self.advapi32.GetNamedSecurityInfoW(
+ str(path),
+ self._SE_FILE_OBJECT,
+ self._OWNER_SECURITY_INFORMATION | self._DACL_SECURITY_INFORMATION,
+ ctypes.byref(owner),
+ None,
+ ctypes.byref(dacl),
+ None,
+ ctypes.byref(descriptor),
+ )
+ if result:
+ raise ControlIpcSecurityError(f"cannot inspect the control IPC path at {path}") from ctypes.WinError(result)
+ try:
+ self._validate_security_descriptor(owner, dacl, descriptor, path)
+ finally:
+ self.kernel32.LocalFree(descriptor)
+
+ def validate_file_descriptor(self, fd: int, path: Path) -> None:
+ import msvcrt
+
+ ctypes = self.ctypes
+ owner = self.wintypes.LPVOID()
+ dacl = self.wintypes.LPVOID()
+ descriptor = self.wintypes.LPVOID()
+ result = self.advapi32.GetSecurityInfo(
+ msvcrt.get_osfhandle(fd),
+ self._SE_FILE_OBJECT,
+ self._OWNER_SECURITY_INFORMATION | self._DACL_SECURITY_INFORMATION,
+ ctypes.byref(owner),
+ None,
+ ctypes.byref(dacl),
+ None,
+ ctypes.byref(descriptor),
+ )
+ if result:
+ raise ControlIpcSecurityError(f"cannot inspect the control IPC file at {path}") from ctypes.WinError(result)
+ try:
+ self._validate_security_descriptor(owner, dacl, descriptor, path)
+ finally:
+ self.kernel32.LocalFree(descriptor)
+
+ def _named_path_owner_matches(self, path: Path) -> bool:
+ ctypes = self.ctypes
+ owner = self.wintypes.LPVOID()
+ descriptor = self.wintypes.LPVOID()
+ result = self.advapi32.GetNamedSecurityInfoW(
+ str(path),
+ self._SE_FILE_OBJECT,
+ self._OWNER_SECURITY_INFORMATION,
+ ctypes.byref(owner),
+ None,
+ None,
+ None,
+ ctypes.byref(descriptor),
+ )
+ if result:
+ raise ControlIpcSecurityError(f"cannot inspect the control IPC path owner at {path}") from ctypes.WinError(
+ result
+ )
+ try:
+ return self._owner_is_self(owner)
+ finally:
+ self.kernel32.LocalFree(descriptor)
+
+ def _validate_security_descriptor(
+ self,
+ owner: object,
+ dacl: object,
+ descriptor: object,
+ path: Path,
+ ) -> None:
+ control = self._descriptor_control(descriptor)
+ owner_is_self = self._owner_is_self(owner)
+ with self._security_descriptor() as expected:
+ expected_dacl = self._descriptor_dacl(expected)
+ valid = (
+ owner_is_self
+ and bool(dacl)
+ and bool(control & self._SE_DACL_PRESENT)
+ and bool(control & self._SE_DACL_PROTECTED)
+ and self._acl_signature(dacl) == self._acl_signature(expected_dacl)
+ )
+ if not valid:
+ raise ControlIpcSecurityError(f"control IPC path owner or DACL is invalid at {path}")
+
+ def _descriptor_owner(self, descriptor: object) -> object:
+ owner = self.wintypes.LPVOID()
+ defaulted = self.wintypes.BOOL()
+ if not self.advapi32.GetSecurityDescriptorOwner(
+ descriptor,
+ self.ctypes.byref(owner),
+ self.ctypes.byref(defaulted),
+ ):
+ self._raise_last_error("cannot read the private descriptor owner")
+ if not owner:
+ raise ControlIpcSecurityError("private control IPC descriptor has no owner")
+ return owner
+
+ def _descriptor_dacl(self, descriptor: object) -> object:
+ present = self.wintypes.BOOL()
+ dacl = self.wintypes.LPVOID()
+ defaulted = self.wintypes.BOOL()
+ if not self.advapi32.GetSecurityDescriptorDacl(
+ descriptor,
+ self.ctypes.byref(present),
+ self.ctypes.byref(dacl),
+ self.ctypes.byref(defaulted),
+ ):
+ self._raise_last_error("cannot read the private descriptor DACL")
+ if not present or not dacl:
+ raise ControlIpcSecurityError("private control IPC descriptor has no DACL")
+ return dacl
+
+ def _descriptor_control(self, descriptor: object) -> int:
+ control = self.wintypes.WORD()
+ revision = self.wintypes.DWORD()
+ if not self.advapi32.GetSecurityDescriptorControl(
+ descriptor,
+ self.ctypes.byref(control),
+ self.ctypes.byref(revision),
+ ):
+ self._raise_last_error("cannot read control IPC DACL controls")
+ return control.value
+
+ def _acl_signature(self, acl: object) -> tuple[bytes, ...]:
+ info = self.AclSizeInformation()
+ if not self.advapi32.GetAclInformation(
+ acl,
+ self.ctypes.byref(info),
+ self.ctypes.sizeof(info),
+ self._ACL_SIZE_INFORMATION_CLASS,
+ ):
+ self._raise_last_error("cannot inspect a control IPC DACL")
+ ace_count = int(info.AceCount)
+ acl_bytes_in_use = int(info.AclBytesInUse)
+ entries: list[bytes] = []
+ for index in range(ace_count):
+ ace = self.wintypes.LPVOID()
+ if not self.advapi32.GetAce(acl, index, self.ctypes.byref(ace)):
+ self._raise_last_error("cannot inspect a control IPC DACL entry")
+ header = self.ctypes.string_at(ace, 4)
+ size = int.from_bytes(header[2:4], "little")
+ if size < 4 or size > acl_bytes_in_use:
+ raise ControlIpcSecurityError("control IPC DACL entry size is invalid")
+ entries.append(self.ctypes.string_at(ace, size))
+ return tuple(sorted(entries))
+
+ def _raise_last_error(self, message: str) -> None:
+ error = self.ctypes.get_last_error()
+ raise ControlIpcSecurityError(message) from self.ctypes.WinError(error)
+
+
+_WINDOWS_SECURITY: Optional[_WindowsSecurity] = None
+
+
+def _windows_security() -> _WindowsSecurity:
+ global _WINDOWS_SECURITY
+ if _WINDOWS_SECURITY is None:
+ if os.name != "nt":
+ raise RuntimeError("Windows control IPC security is unavailable")
+ _WINDOWS_SECURITY = _WindowsSecurity()
+ return _WINDOWS_SECURITY
diff --git a/core/controller.py b/core/controller.py
index 42d7edb38..1df1761e9 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1936,7 +1936,7 @@ class Controller:
asyncio.set_event_loop(self._loop)
self._schedule_model_hub_snapshot_reconcile()
self.show_git_checkpoint_service.start()
- # Internal Unix-socket ASGI server for the Web UI / future
+ # Internal control-IPC ASGI server for the Web UI / future
# ``vibe agent run --sync`` cross-process callers. Lives on
# the same loop as the IM dispatch path so they share one
# asyncio scheduler. See core/internal_server.py.
@@ -1972,18 +1972,19 @@ class Controller:
self.cleanup_sync()
if not getattr(self, "_shutdown_tainted", False):
self._service_lock_safe_to_release = True
- # Best-effort: remove the dispatch socket so the next controller
- # boot starts from a clean filesystem state. uvicorn unlinks
- # the path on exit when it bound the socket itself, but it
- # can be left behind on hard crashes.
+ # Let the transport owner close its listener and remove only the
+ # endpoint it published. This is required for the Windows descriptor:
+ # a stale Controller must not unlink a successor's endpoint.
try:
- from core import internal_server as _internal_server
-
- sock_path = _internal_server.default_socket_path()
- if sock_path.exists():
- sock_path.unlink()
- except Exception:
+ internal_task = getattr(self, "_internal_server_task", None)
+ if internal_task is not None and not internal_task.done():
+ internal_task.cancel()
+ self._loop.run_until_complete(internal_task)
+ except asyncio.CancelledError:
pass
+ except Exception as exc:
+ logger.debug("Internal control IPC cleanup skipped: %s", exc)
+ self._internal_server_task = None
if self._loop is not None:
try:
self._loop.stop()
diff --git a/core/inbox_events.py b/core/inbox_events.py
index 9205b7adb..61eba6e3c 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -156,6 +156,8 @@ def run_updated_payload(
session_id: str | None = None,
definition_id: str | None = None,
updated_at: str | None = None,
+ started_at: str | None = None,
+ completed_at: str | None = None,
cancel_requested: bool | None = None,
) -> dict[str, Any]:
"""Minimal run-lifecycle payload for browser refetch-on-event consumers."""
@@ -169,6 +171,10 @@ def run_updated_payload(
payload["definition_id"] = definition_id
if updated_at:
payload["updated_at"] = updated_at
+ if started_at:
+ payload["started_at"] = started_at
+ if completed_at:
+ payload["completed_at"] = completed_at
if cancel_requested is not None:
payload["cancel_requested"] = cancel_requested
return payload
diff --git a/core/internal_server.py b/core/internal_server.py
index e9662b479..c7ffdc41b 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1,11 +1,10 @@
-"""Controller-side ASGI server bound to a Unix Domain Socket.
+"""Controller-side ASGI server on the platform control IPC transport.
This is the C4 piece of Plan 2 from
``docs/plans/workbench-dispatch-architecture.md``: the controller process
-exposes a minimal FastAPI app on
-``~/.vibe_remote/state/dispatch.sock`` so cross-process callers (the
-separate UI server subprocess, future ``vibe agent run --sync`` flows)
-can submit turns to the controller-owned session turn manager.
+exposes a minimal FastAPI app over a POSIX UDS or authenticated Windows
+loopback listener so cross-process callers can invoke
+the controller-owned session turn manager.
Three properties matter:
@@ -13,12 +12,10 @@ Three properties matter:
background ``asyncio.Task`` on the loop that ``Controller.run()``
creates. IM adapters share that loop. No cross-loop futures, no
second uvicorn worker, no thread bridge.
-2. **Local-only.** Unix sockets are bind to a file path on the local
- filesystem; no TCP listen, so external network exposure is
- impossible.
-3. **Restrictive permissions.** The socket file is created under a
- restrictive umask and chmod'd to ``0o600`` when the filesystem supports
- it — defense in depth against shared hosts.
+2. **Local-only.** POSIX binds a Unix socket. Windows binds an authenticated
+ ephemeral listener on the literal IPv4 loopback address.
+3. **Restrictive discovery.** Unix sockets and Windows endpoint descriptors
+ use the narrowest practical current-user permissions.
The endpoint set is intentionally tiny; follow-ups can grow it without
changing the bind contract.
@@ -28,22 +25,22 @@ from __future__ import annotations
import asyncio
import contextlib
-import errno
+import hmac
import json
import logging
import os
import re
import socket
-import stat
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, TYPE_CHECKING
from fastapi import FastAPI, HTTPException, Request
-from fastapi.responses import JSONResponse, StreamingResponse
+from fastapi.responses import JSONResponse, PlainTextResponse, StreamingResponse
from config import paths
+from core import control_ipc
from config.atomic_io import write_atomic
from core.delivery_target import normalize_message_kind
from core.services.dispatch import SOURCE_SCHEDULED
@@ -56,18 +53,6 @@ if TYPE_CHECKING: # pragma: no cover - typing only
logger = logging.getLogger(__name__)
-_SOCKET_MODE = 0o600
-_SOCKET_UMASK_MODE = 0o700
-_CHECK_POSIX_SOCKET_MODE = os.name != "nt"
-_UNSUPPORTED_SOCKET_CHMOD_ERRNOS = frozenset(
- value
- for value in (
- errno.EINVAL,
- getattr(errno, "ENOTSUP", None),
- getattr(errno, "EOPNOTSUPP", None),
- )
- if value is not None
-)
_PROCESSING_RECORD_CURSOR_RE = re.compile(r"[A-Za-z0-9_-]{1,256}\Z")
_PROCESSING_RECORD_ENTRY_ID_RE = re.compile(r"[A-Za-z0-9_.:-]{1,256}\Z")
@@ -99,13 +84,15 @@ def default_socket_path() -> Path:
support Unix-socket permission operations.
"""
- override = os.environ.get("VIBE_INTERNAL_DISPATCH_SOCKET")
- if override:
- return Path(override).expanduser()
- return paths.get_state_dir() / "dispatch.sock"
+ return control_ipc.default_unix_socket_path()
-def create_app(controller: "Controller") -> FastAPI:
+def create_app(
+ controller: "Controller",
+ *,
+ instance_id: Optional[str] = None,
+ bearer_token: Optional[str] = None,
+) -> FastAPI:
"""Build the minimal FastAPI app the internal server exposes.
Factored out so tests can mount the same routes against a fake
@@ -120,6 +107,36 @@ def create_app(controller: "Controller") -> FastAPI:
redoc_url=None,
openapi_url=None,
)
+ if (instance_id is None) != (bearer_token is None):
+ raise ValueError("Windows control IPC requires both instance ID and bearer token")
+ if instance_id is not None and bearer_token is not None:
+
+ @app.exception_handler(Exception)
+ async def _windows_control_ipc_server_error(_request: Request, _exc: Exception):
+ return PlainTextResponse(
+ "Internal Server Error",
+ status_code=500,
+ headers={control_ipc.CONTROL_IPC_INSTANCE_HEADER: instance_id},
+ )
+
+ @app.middleware("http")
+ async def _authenticate_windows_control_ipc(request: Request, call_next):
+ scheme, separator, credential = request.headers.get("authorization", "").partition(" ")
+ authorized = (
+ separator == " "
+ and scheme.lower() == "bearer"
+ and bool(credential)
+ and hmac.compare_digest(credential, bearer_token)
+ )
+ if not authorized:
+ return JSONResponse(
+ status_code=401,
+ content={"detail": "unauthorized"},
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ response = await call_next(request)
+ response.headers[control_ipc.CONTROL_IPC_INSTANCE_HEADER] = instance_id
+ return response
from core.skill_observability import SkillObservationRecorder
skill_recorder = SkillObservationRecorder()
@@ -608,7 +625,13 @@ def create_app(controller: "Controller") -> FastAPI:
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
- return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+ from vibe.desktop_runtime import desktop_runtime_id
+
+ payload = {"ok": True, "service": "vibe-remote-internal", "version": 1}
+ runtime_id = desktop_runtime_id()
+ if runtime_id is not None:
+ payload["desktop_runtime_id"] = runtime_id
+ return payload
@app.post("/internal/show-access/settings-read")
async def _show_access_settings_read(request: Request) -> Any:
@@ -1248,26 +1271,35 @@ def create_app(controller: "Controller") -> FastAPI:
return app
-async def serve(controller: "Controller", *, socket_path: Optional[Path] = None) -> None:
+async def serve(
+ controller: "Controller",
+ *,
+ socket_path: Optional[Path] = None,
+ descriptor_path: Optional[Path] = None,
+ platform_name: Optional[str] = None,
+) -> None:
"""Run the internal server forever on the current event loop.
- Returns when the underlying uvicorn server exits (typically when the
- controller's loop is shut down). Each call binds a fresh socket
- file; pre-existing files at ``socket_path`` are removed first so
- restarts don't fail with "address already in use".
-
- Permissions: we tighten ``os.umask`` to ``0o077`` *before* uvicorn
- binds the socket so the file is created with mode ``0o700`` and is
- never readable / connectable by other local users — even briefly.
- A best-effort post-bind ``os.chmod`` then forces the final mode in
- case the platform's umask handling differs (some BSDs ignore umask
- for AF_UNIX bind). Without the umask wrap there is a TOCTOU window
- where the socket would be world-accessible between bind and chmod.
+ Returns when the underlying uvicorn server exits. POSIX pre-binds the
+ existing restrictive UDS endpoint. Windows pre-binds an authenticated
+ ephemeral loopback listener and atomically publishes its descriptor before
+ uvicorn starts accepting requests.
"""
import uvicorn
- app = create_app(controller)
+ host = control_ipc.select_control_ipc_host(
+ platform_name=platform_name,
+ socket_path=socket_path,
+ descriptor_path=descriptor_path,
+ )
+ app_kwargs: dict[str, str] = {}
+ if host.instance_id is not None and host.bearer_token is not None:
+ app_kwargs = {
+ "instance_id": host.instance_id,
+ "bearer_token": host.bearer_token,
+ }
+ app = create_app(controller, **app_kwargs)
skill_recorder = controller.skill_observability
try:
recovery_complete = getattr(controller, "_delivery_recovery_complete", None)
@@ -1281,20 +1313,14 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)
lifespan="off",
)
server = _create_controller_loop_server(config)
-
- listener, target = _bind_socket(socket_path)
+ bound = host.bind()
try:
+ host.publish(bound)
_write_internal_server_status("ready")
- await server.serve(sockets=[listener])
+ await server.serve(sockets=[bound.listener])
finally:
- try:
- listener.close()
- except OSError:
- pass
- _remove_owned_socket(target)
+ host.cleanup(bound)
finally:
- # Lifespan is disabled: this server task owns the recorder's cleanup,
- # including cancellation during controller recovery or socket setup.
await skill_recorder.close()
@@ -1307,81 +1333,11 @@ def _bind_socket(socket_path: Optional[Path] = None) -> tuple[socket.socket, Pat
uvicorn's path chmod while keeping the endpoint local-only.
"""
- # Bind and report the canonical path so platform aliases (for example
- # macOS ``/var`` -> ``/private/var``) do not produce a mismatched endpoint.
- target = (socket_path or default_socket_path()).expanduser().resolve()
- target.parent.mkdir(parents=True, exist_ok=True)
- _remove_stale_owned_socket(target)
-
- previous_umask = os.umask(0o077)
- listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- try:
- listener.bind(str(target))
- listener.listen(2048)
- listener.setblocking(False)
- try:
- os.chmod(target, _SOCKET_MODE)
- except OSError as error:
- if error.errno not in _UNSUPPORTED_SOCKET_CHMOD_ERRNOS:
- raise
- logger.debug("internal dispatch socket chmod is unsupported for %s", target)
- _verify_owned_socket(target, allow_umask_mode=True)
- else:
- _verify_owned_socket(target)
- return listener, target
- except Exception:
- listener.close()
- _remove_socket_after_bind_failure(target)
- raise
- finally:
- os.umask(previous_umask)
-
-
-def _remove_stale_owned_socket(target: Path) -> None:
- try:
- info = target.lstat()
- except FileNotFoundError:
- return
- if hasattr(os, "getuid") and info.st_uid != os.getuid():
- raise OSError("internal dispatch socket owner mismatch")
- # lstat + unlink removes the directory entry itself, including a symlink;
- # it never follows or mutates the path the stale entry may point at.
- target.unlink()
-
-
-def _remove_owned_socket(target: Path) -> None:
- try:
- _verify_owned_socket(target, allow_umask_mode=True)
- target.unlink()
- except FileNotFoundError:
- return
- except OSError:
- logger.debug("could not unlink internal dispatch socket %s", target, exc_info=True)
-
-
-def _remove_socket_after_bind_failure(target: Path) -> None:
- """Remove only a socket still owned by this user after a failed hardening step."""
-
- try:
- info = target.lstat()
- if stat.S_ISSOCK(info.st_mode) and (not hasattr(os, "getuid") or info.st_uid == os.getuid()):
- target.unlink()
- except FileNotFoundError:
- return
- except OSError:
- logger.debug("could not remove failed internal dispatch socket %s", target, exc_info=True)
-
-
-def _verify_owned_socket(target: Path, *, allow_umask_mode: bool = False) -> None:
- info = target.lstat()
- if stat.S_ISLNK(info.st_mode) or not stat.S_ISSOCK(info.st_mode):
- raise OSError("internal dispatch socket is unsafe")
- if hasattr(os, "getuid") and info.st_uid != os.getuid():
- raise OSError("internal dispatch socket owner mismatch")
- if _CHECK_POSIX_SOCKET_MODE:
- allowed_modes = {_SOCKET_MODE, _SOCKET_UMASK_MODE} if allow_umask_mode else {_SOCKET_MODE}
- if stat.S_IMODE(info.st_mode) not in allowed_modes:
- raise OSError("internal dispatch socket mode mismatch")
+ bound = control_ipc.PosixUnixSocketHost(socket_path).bind()
+ if bound.socket_path is None:
+ bound.listener.close()
+ raise RuntimeError("Unix control IPC bind returned no socket path")
+ return bound.listener, bound.socket_path
def _write_internal_server_status(
@@ -1412,7 +1368,13 @@ def _write_internal_server_status(
logger.warning("could not persist internal dispatch server status", exc_info=True)
-def start(controller: "Controller", *, socket_path: Optional[Path] = None) -> asyncio.Task:
+def start(
+ controller: "Controller",
+ *,
+ socket_path: Optional[Path] = None,
+ descriptor_path: Optional[Path] = None,
+ platform_name: Optional[str] = None,
+) -> asyncio.Task:
"""Schedule the internal server to run on the controller's loop.
Called from ``Controller.run`` once the loop is alive. Returns the
@@ -1422,7 +1384,15 @@ def start(controller: "Controller", *, socket_path: Optional[Path] = None) -> as
loop = asyncio.get_event_loop()
_write_internal_server_status("starting")
- task = loop.create_task(serve(controller, socket_path=socket_path), name="internal-dispatch-server")
+ task = loop.create_task(
+ serve(
+ controller,
+ socket_path=socket_path,
+ descriptor_path=descriptor_path,
+ platform_name=platform_name,
+ ),
+ name="internal-dispatch-server",
+ )
def _on_done(t: asyncio.Task) -> None:
if t.cancelled():
diff --git a/core/runtime_work.py b/core/runtime_work.py
index 47219d6d4..fdbbf4e4c 100644
--- a/core/runtime_work.py
+++ b/core/runtime_work.py
@@ -522,9 +522,15 @@ class RuntimeWorkSupervisor:
def _stop_for_lost_lease(self) -> None:
if self._quiescing or self._stopping or self._stop_task is not None:
return
+ # Says what was established, not what was inferred from it: the check
+ # re-opens the lock file and looks for a record naming this pid, so a
+ # false answer means either the lock went away or the record could not
+ # be read. Claiming a transition nobody observed sent three release
+ # candidates looking for a lock that was never lost.
logger.error(
- "Runtime work supervisor stopping because this process no longer "
- "owns the service lock"
+ "Runtime work supervisor stopping: re-reading the service lock did "
+ "not confirm this process as its holder -- either the lock was "
+ "released, or its holder record could not be read"
)
self.quiesce()
if self._on_lease_lost is not None:
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 86f841d6e..8def23223 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -4273,18 +4273,23 @@ class ShowRuntimeManager:
_manager: ShowRuntimeManager | None = None
+_manager_lock = threading.Lock()
def get_show_runtime_manager() -> ShowRuntimeManager:
global _manager
if _manager is None:
- _manager = ShowRuntimeManager()
+ with _manager_lock:
+ if _manager is None:
+ _manager = ShowRuntimeManager()
return _manager
def stop_show_runtime_manager() -> None:
- if _manager is not None:
- _manager.stop()
+ with _manager_lock:
+ manager = _manager
+ if manager is not None:
+ manager.stop()
def _is_runtime_server_cmdline(cmdline: list[str], workspace_root: str) -> bool:
@@ -4392,7 +4397,9 @@ def _show_runtime_app_session_part(path: str) -> str | None:
def set_show_runtime_manager_for_tests(manager: ShowRuntimeManager | None) -> None:
global _manager
- previous = _manager
+ with _manager_lock:
+ previous = _manager
+ _manager = manager
# Stop the manager we are replacing before dropping the reference. Serving-path
# tests that never install a fake cause get_show_runtime_manager() to lazily
# create the real manager, which spawns a Node cli.js + esbuild subprocess tree
@@ -4404,7 +4411,6 @@ def set_show_runtime_manager_for_tests(manager: ShowRuntimeManager | None) -> No
previous.stop()
except Exception: # pragma: no cover - defensive cleanup
logger.debug("failed to stop previous show runtime manager", exc_info=True)
- _manager = manager
def _show_runtime_prewarm_import_paths(
diff --git a/core/update_checker.py b/core/update_checker.py
index 6b52e5f00..de872ac2b 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -33,6 +33,7 @@ from vibe.upgrade import (
get_running_vibe_path,
get_update_metadata_url,
has_newer_version,
+ is_desktop_managed_runtime,
select_latest_update_version,
)
@@ -69,7 +70,7 @@ def _fetch_pypi_version_sync() -> Dict[str, Any]:
current = __version__
result = {"current": current, "latest": None, "has_update": False, "error": None}
- if get_build_identity().kind == "source":
+ if get_build_identity().kind == "source" or is_desktop_managed_runtime():
return result
try:
diff --git a/core/watches.py b/core/watches.py
index 2dc40f56a..c709d1f24 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -1854,7 +1854,16 @@ class ManagedWatchService:
return True
if runtime.current_process_owns_service_instance():
return True
- logger.error("Managed watch service stopping because this process no longer owns the service lock")
+ # Says what was established, not what was inferred from it: the check
+ # re-opens the lock file and looks for a record naming this pid, so a
+ # false answer means either the lock went away or the record could not
+ # be read. Claiming a transition nobody observed sent three release
+ # candidates looking for a lock that was never lost.
+ logger.error(
+ "Managed watch service stopping: re-reading the service lock did not "
+ "confirm this process as its holder -- either the lock was released, "
+ "or its holder record could not be read"
+ )
self._begin_stop()
return False
diff --git a/desktop/.gitignore b/desktop/.gitignore
new file mode 100644
index 000000000..e568fda92
--- /dev/null
+++ b/desktop/.gitignore
@@ -0,0 +1,13 @@
+# Bootstrap UI
+node_modules/
+dist/
+
+# Rust workspace
+target/
+
+# Target-specific private Runtime payloads are release build products.
+src-tauri/resources/runtime/*
+!src-tauri/resources/runtime/.keep
+
+# Generated by tauri-build from the installed plugin permissions.
+src-tauri/gen/schemas/
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
new file mode 100644
index 000000000..0b8d7b163
--- /dev/null
+++ b/desktop/Cargo.lock
@@ -0,0 +1,5495 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "alloc-no-stdlib"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
+
+[[package]]
+name = "alloc-stdlib"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
+dependencies = [
+ "alloc-no-stdlib",
+]
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+dependencies = [
+ "derive_arbitrary",
+]
+
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
+name = "async-trait"
+version = "0.1.91"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "atk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
+dependencies = [
+ "atk-sys",
+ "glib",
+ "libc",
+]
+
+[[package]]
+name = "atk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "auto-launch"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f012b8cc0c850f34117ec8252a44418f2e34a2cf501de89e29b241ae5f79471"
+dependencies = [
+ "dirs 4.0.0",
+ "thiserror 1.0.69",
+ "winreg 0.10.1",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "avibe-desktop"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "avibe-runtime-host",
+ "objc2",
+ "objc2-foundation",
+ "serde",
+ "serde_json",
+ "sys-locale",
+ "tauri",
+ "tauri-build",
+ "tauri-plugin-autostart",
+ "tauri-plugin-deep-link",
+ "tauri-plugin-dialog",
+ "tauri-plugin-notification",
+ "tauri-plugin-opener",
+ "tauri-plugin-single-instance",
+ "tauri-plugin-window-state",
+ "tokio",
+ "url",
+]
+
+[[package]]
+name = "avibe-runtime-host"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "chrono",
+ "reqwest 0.12.28",
+ "serde",
+ "serde_json",
+ "sha2",
+ "thiserror 2.0.19",
+ "tokio",
+ "url",
+ "zip",
+]
+
+[[package]]
+name = "base64"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
+dependencies = [
+ "objc2",
+]
+
+[[package]]
+name = "blocking"
+version = "1.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
+[[package]]
+name = "brotli"
+version = "8.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+ "brotli-decompressor",
+]
+
+[[package]]
+name = "brotli-decompressor"
+version = "5.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+]
+
+[[package]]
+name = "bs58"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "cairo-rs"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
+dependencies = [
+ "bitflags 2.13.1",
+ "cairo-sys-rs",
+ "glib",
+ "libc",
+ "once_cell",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "cairo-sys-rs"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
+dependencies = [
+ "glib-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "camino"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f2d30e4173c4026932d51d31d6b0613b1fd3014bf3f9f8943d4ba139c437ba0"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "cargo-platform"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"
+dependencies = [
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.19",
+]
+
+[[package]]
+name = "cargo_toml"
+version = "0.22.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
+dependencies = [
+ "serde",
+ "toml 0.9.12+spec-1.1.0",
+]
+
+[[package]]
+name = "cc"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cesu8"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+
+[[package]]
+name = "cfb"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"
+dependencies = [
+ "byteorder",
+ "fnv",
+ "uuid",
+]
+
+[[package]]
+name = "cfg-expr"
+version = "0.15.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
+dependencies = [
+ "smallvec",
+ "target-lexicon",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "num-traits",
+ "serde",
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "combine"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "const-random"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
+dependencies = [
+ "const-random-macro",
+]
+
+[[package]]
+name = "const-random-macro"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "tiny-keccak",
+]
+
+[[package]]
+name = "cookie"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
+dependencies = [
+ "time",
+ "version_check",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
+dependencies = [
+ "bitflags 2.13.1",
+ "core-foundation",
+ "core-graphics-types",
+ "foreign-types",
+ "libc",
+]
+
+[[package]]
+name = "core-graphics-types"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
+dependencies = [
+ "bitflags 2.13.1",
+ "core-foundation",
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "cssparser"
+version = "0.36.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
+dependencies = [
+ "cssparser-macros",
+ "dtoa-short",
+ "itoa",
+ "phf",
+ "smallvec",
+]
+
+[[package]]
+name = "cssparser-macros"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "ctor"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"
+dependencies = [
+ "ctor-proc-macro",
+ "dtor",
+]
+
+[[package]]
+name = "ctor-proc-macro"
+version = "0.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
+
+[[package]]
+name = "darling"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
+dependencies = [
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dbus"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "derive_arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "dirs"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
+dependencies = [
+ "dirs-sys 0.3.7",
+]
+
+[[package]]
+name = "dirs"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
+dependencies = [
+ "dirs-sys 0.5.0",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
+dependencies = [
+ "libc",
+ "redox_users 0.4.6",
+ "winapi",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users 0.5.2",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "libc",
+ "objc2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dlopen2"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4"
+dependencies = [
+ "dlopen2_derive",
+ "libc",
+ "once_cell",
+ "winapi",
+]
+
+[[package]]
+name = "dlopen2_derive"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dlv-list"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
+dependencies = [
+ "const-random",
+]
+
+[[package]]
+name = "dom_query"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
+dependencies = [
+ "bit-set",
+ "cssparser",
+ "foldhash",
+ "html5ever",
+ "precomputed-hash",
+ "selectors",
+ "tendril",
+]
+
+[[package]]
+name = "dpi"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "dtoa"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
+
+[[package]]
+name = "dtoa-short"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
+dependencies = [
+ "dtoa",
+]
+
+[[package]]
+name = "dtor"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"
+dependencies = [
+ "dtor-proc-macro",
+]
+
+[[package]]
+name = "dtor-proc-macro"
+version = "0.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"
+
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+[[package]]
+name = "dyn-clone"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+
+[[package]]
+name = "embed-resource"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"
+dependencies = [
+ "cc",
+ "memchr",
+ "rustc_version",
+ "toml 1.1.3+spec-1.1.0",
+ "vswhom",
+ "winreg 0.55.0",
+]
+
+[[package]]
+name = "embed_plist"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
+
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
+[[package]]
+name = "enumflags2"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
+dependencies = [
+ "enumflags2_derive",
+ "serde",
+]
+
+[[package]]
+name = "enumflags2_derive"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "erased-serde"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
+dependencies = [
+ "serde",
+ "serde_core",
+ "typeid",
+]
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "event-listener"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
+dependencies = [
+ "concurrent-queue",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "field-offset"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
+dependencies = [
+ "memoffset",
+ "rustc_version",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
+
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "futures-macro"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307"
+
+[[package]]
+name = "futures-task"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
+
+[[package]]
+name = "futures-util"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gdk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"
+dependencies = [
+ "cairo-rs",
+ "gdk-pixbuf",
+ "gdk-sys",
+ "gio",
+ "glib",
+ "libc",
+ "pango",
+]
+
+[[package]]
+name = "gdk-pixbuf"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
+dependencies = [
+ "gdk-pixbuf-sys",
+ "gio",
+ "glib",
+ "libc",
+ "once_cell",
+]
+
+[[package]]
+name = "gdk-pixbuf-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
+dependencies = [
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gdk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
+dependencies = [
+ "cairo-sys-rs",
+ "gdk-pixbuf-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pango-sys",
+ "pkg-config",
+ "system-deps",
+]
+
+[[package]]
+name = "gdkwayland-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
+dependencies = [
+ "gdk-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pkg-config",
+ "system-deps",
+]
+
+[[package]]
+name = "gdkx11"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"
+dependencies = [
+ "gdk",
+ "gdkx11-sys",
+ "gio",
+ "glib",
+ "libc",
+ "x11",
+]
+
+[[package]]
+name = "gdkx11-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
+dependencies = [
+ "gdk-sys",
+ "glib-sys",
+ "libc",
+ "system-deps",
+ "x11",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+]
+
+[[package]]
+name = "gio"
+version = "0.18.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-util",
+ "gio-sys",
+ "glib",
+ "libc",
+ "once_cell",
+ "pin-project-lite",
+ "smallvec",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "gio-sys"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+ "winapi",
+]
+
+[[package]]
+name = "glib"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
+dependencies = [
+ "bitflags 2.13.1",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-task",
+ "futures-util",
+ "gio-sys",
+ "glib-macros",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "memchr",
+ "once_cell",
+ "smallvec",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "glib-macros"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
+dependencies = [
+ "heck 0.4.1",
+ "proc-macro-crate 2.0.2",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "glib-sys"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"
+dependencies = [
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
+[[package]]
+name = "gobject-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
+dependencies = [
+ "glib-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gtk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"
+dependencies = [
+ "atk",
+ "cairo-rs",
+ "field-offset",
+ "futures-channel",
+ "gdk",
+ "gdk-pixbuf",
+ "gio",
+ "glib",
+ "gtk-sys",
+ "gtk3-macros",
+ "libc",
+ "pango",
+ "pkg-config",
+]
+
+[[package]]
+name = "gtk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"
+dependencies = [
+ "atk-sys",
+ "cairo-sys-rs",
+ "gdk-pixbuf-sys",
+ "gdk-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pango-sys",
+ "system-deps",
+]
+
+[[package]]
+name = "gtk3-macros"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"
+dependencies = [
+ "proc-macro-crate 1.3.1",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "html5ever"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"
+dependencies = [
+ "log",
+ "markup5ever",
+]
+
+[[package]]
+name = "http"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "hyper"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core 0.62.2",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "ico"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"
+dependencies = [
+ "byteorder",
+ "png 0.17.16",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
+
+[[package]]
+name = "icu_properties"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
+
+[[package]]
+name = "icu_provider"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "indexmap"
+version = "1.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
+dependencies = [
+ "autocfg",
+ "hashbrown 0.12.3",
+ "serde",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "infer"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"
+dependencies = [
+ "cfb",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
+
+[[package]]
+name = "is-docker"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "is-wsl"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
+dependencies = [
+ "is-docker",
+ "once_cell",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "javascriptcore-rs"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
+dependencies = [
+ "bitflags 1.3.2",
+ "glib",
+ "javascriptcore-rs-sys",
+]
+
+[[package]]
+name = "javascriptcore-rs-sys"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "jni"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
+dependencies = [
+ "cesu8",
+ "cfg-if",
+ "combine",
+ "jni-sys 0.3.1",
+ "log",
+ "thiserror 1.0.69",
+ "walkdir",
+ "windows-sys 0.45.0",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "json-patch"
+version = "3.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"
+dependencies = [
+ "jsonptr",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "jsonptr"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "keyboard-types"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"
+dependencies = [
+ "bitflags 2.13.1",
+ "serde",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "libappindicator"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
+dependencies = [
+ "glib",
+ "gtk",
+ "gtk-sys",
+ "libappindicator-sys",
+ "log",
+]
+
+[[package]]
+name = "libappindicator-sys"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"
+dependencies = [
+ "gtk-sys",
+ "libloading",
+ "once_cell",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "libloading"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
+dependencies = [
+ "cfg-if",
+ "winapi",
+]
+
+[[package]]
+name = "libredox"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litemap"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+
+[[package]]
+name = "mac-notification-sys"
+version = "0.6.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
+dependencies = [
+ "cc",
+ "log",
+ "objc2",
+ "objc2-foundation",
+ "time",
+ "uuid",
+]
+
+[[package]]
+name = "markup5ever"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"
+dependencies = [
+ "log",
+ "tendril",
+ "web_atoms",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "muda"
+version = "0.19.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"
+dependencies = [
+ "crossbeam-channel",
+ "dpi",
+ "gtk",
+ "keyboard-types",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "once_cell",
+ "png 0.18.1",
+ "serde",
+ "thiserror 2.0.19",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "ndk"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
+dependencies = [
+ "bitflags 2.13.1",
+ "jni-sys 0.3.1",
+ "log",
+ "ndk-sys",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ndk-sys"
+version = "0.6.0+11769913"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "notify-rust"
+version = "4.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5b4c1b4f2aa9f25f63a7a49d3dd0ed567b3670da15330a66b29434be899b891"
+dependencies = [
+ "futures-lite",
+ "log",
+ "mac-notification-sys",
+ "serde",
+ "tauri-winrt-notification",
+ "zbus",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
+dependencies = [
+ "objc2-encode",
+ "objc2-exception-helper",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.1",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
+dependencies = [
+ "bitflags 2.13.1",
+ "dispatch2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-text"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-exception-helper"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-surface"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "objc2",
+ "objc2-cloud-kit",
+ "objc2-core-data",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-core-image",
+ "objc2-core-location",
+ "objc2-core-text",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-web-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "open"
+version = "5.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0b3d059e795d52b8a72fef45658620edd4d9c359b338564aa14391ffa511ed5"
+dependencies = [
+ "dunce",
+ "is-wsl",
+ "libc",
+]
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "ordered-multimap"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
+dependencies = [
+ "dlv-list",
+ "hashbrown 0.14.5",
+]
+
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "pango"
+version = "0.18.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
+dependencies = [
+ "gio",
+ "glib",
+ "libc",
+ "once_cell",
+ "pango-sys",
+]
+
+[[package]]
+name = "pango-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "phf"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+ "serde",
+]
+
+[[package]]
+name = "phf_codegen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
+dependencies = [
+ "fastrand",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
+dependencies = [
+ "siphasher",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
+
+[[package]]
+name = "plist"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
+dependencies = [
+ "base64 0.22.1",
+ "indexmap 2.14.0",
+ "quick-xml",
+ "serde",
+ "time",
+]
+
+[[package]]
+name = "png"
+version = "0.17.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+dependencies = [
+ "bitflags 1.3.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.13.1",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "powerfmt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "precomputed-hash"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+
+[[package]]
+name = "proc-macro-crate"
+version = "1.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"
+dependencies = [
+ "once_cell",
+ "toml_edit 0.19.15",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
+dependencies = [
+ "toml_datetime 0.6.3",
+ "toml_edit 0.20.2",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.13+spec-1.1.0",
+]
+
+[[package]]
+name = "proc-macro-error"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
+dependencies = [
+ "proc-macro-error-attr",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro-error-attr"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.13.1",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
+dependencies = [
+ "getrandom 0.2.17",
+ "libredox",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
+dependencies = [
+ "getrandom 0.2.17",
+ "libredox",
+ "thiserror 2.0.19",
+]
+
+[[package]]
+name = "ref-cast"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "reqwest"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tokio-util",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams",
+ "web-sys",
+]
+
+[[package]]
+name = "rfd"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
+dependencies = [
+ "block2",
+ "dispatch2",
+ "glib-sys",
+ "gobject-sys",
+ "gtk-sys",
+ "js-sys",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "raw-window-handle",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "rust-ini"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
+dependencies = [
+ "cfg-if",
+ "ordered-multimap",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags 2.13.1",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schemars"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"
+dependencies = [
+ "dyn-clone",
+ "indexmap 1.9.3",
+ "schemars_derive",
+ "serde",
+ "serde_json",
+ "url",
+ "uuid",
+]
+
+[[package]]
+name = "schemars"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars_derive"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "selectors"
+version = "0.36.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
+dependencies = [
+ "bitflags 2.13.1",
+ "cssparser",
+ "derive_more",
+ "log",
+ "new_debug_unreachable",
+ "phf",
+ "phf_codegen",
+ "precomputed-hash",
+ "rustc-hash",
+ "servo_arc",
+ "smallvec",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde-untagged"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"
+dependencies = [
+ "erased-serde",
+ "serde",
+ "serde_core",
+ "typeid",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "serde_derive_internals"
+version = "0.29.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "serde_with"
+version = "3.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
+dependencies = [
+ "base64 0.22.1",
+ "bs58",
+ "chrono",
+ "hex",
+ "indexmap 1.9.3",
+ "indexmap 2.14.0",
+ "schemars 0.9.0",
+ "schemars 1.2.1",
+ "serde_core",
+ "serde_json",
+ "serde_with_macros",
+ "time",
+]
+
+[[package]]
+name = "serde_with_macros"
+version = "3.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "serialize-to-javascript"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"
+dependencies = [
+ "serde",
+ "serde_json",
+ "serialize-to-javascript-impl",
+]
+
+[[package]]
+name = "serialize-to-javascript-impl"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "servo_arc"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
+dependencies = [
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "siphasher"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "softbuffer"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"
+dependencies = [
+ "bytemuck",
+ "js-sys",
+ "ndk",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "raw-window-handle",
+ "redox_syscall",
+ "tracing",
+ "wasm-bindgen",
+ "web-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "soup3"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
+dependencies = [
+ "futures-channel",
+ "gio",
+ "glib",
+ "libc",
+ "soup3-sys",
+]
+
+[[package]]
+name = "soup3-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
+dependencies = [
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "string_cache"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
+dependencies = [
+ "new_debug_unreachable",
+ "parking_lot",
+ "phf_shared",
+ "precomputed-hash",
+]
+
+[[package]]
+name = "string_cache_codegen"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "swift-rs"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"
+dependencies = [
+ "base64 0.21.7",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "sys-locale"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "system-deps"
+version = "6.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
+dependencies = [
+ "cfg-expr",
+ "heck 0.5.0",
+ "pkg-config",
+ "toml 0.8.2",
+ "version-compare",
+]
+
+[[package]]
+name = "tao"
+version = "0.35.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2",
+ "core-foundation",
+ "core-graphics",
+ "crossbeam-channel",
+ "dbus",
+ "dispatch2",
+ "dlopen2",
+ "dpi",
+ "gdkwayland-sys",
+ "gdkx11-sys",
+ "gtk",
+ "jni",
+ "libc",
+ "log",
+ "ndk",
+ "ndk-sys",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "once_cell",
+ "parking_lot",
+ "percent-encoding",
+ "raw-window-handle",
+ "tao-macros",
+ "unicode-segmentation",
+ "url",
+ "windows",
+ "windows-core 0.61.2",
+ "windows-version",
+ "x11-dl",
+]
+
+[[package]]
+name = "tao-macros"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.12.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+
+[[package]]
+name = "tauri"
+version = "2.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "cookie",
+ "dirs 6.0.0",
+ "dunce",
+ "embed_plist",
+ "getrandom 0.3.4",
+ "glob",
+ "gtk",
+ "heck 0.5.0",
+ "http",
+ "jni",
+ "libc",
+ "log",
+ "mime",
+ "muda",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "percent-encoding",
+ "plist",
+ "raw-window-handle",
+ "reqwest 0.13.4",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "serialize-to-javascript",
+ "swift-rs",
+ "tauri-build",
+ "tauri-macros",
+ "tauri-runtime",
+ "tauri-runtime-wry",
+ "tauri-utils",
+ "thiserror 2.0.19",
+ "tokio",
+ "tray-icon",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "window-vibrancy",
+ "windows",
+]
+
+[[package]]
+name = "tauri-build"
+version = "2.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"
+dependencies = [
+ "anyhow",
+ "cargo_toml",
+ "dirs 6.0.0",
+ "glob",
+ "heck 0.5.0",
+ "json-patch",
+ "schemars 0.8.22",
+ "semver",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "tauri-winres",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-codegen"
+version = "2.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"
+dependencies = [
+ "base64 0.22.1",
+ "brotli",
+ "ico",
+ "json-patch",
+ "plist",
+ "png 0.17.16",
+ "proc-macro2",
+ "quote",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha2",
+ "syn 2.0.119",
+ "tauri-utils",
+ "thiserror 2.0.19",
+ "time",
+ "url",
+ "uuid",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-macros"
+version = "2.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"
+dependencies = [
+ "heck 0.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "tauri-codegen",
+ "tauri-utils",
+]
+
+[[package]]
+name = "tauri-plugin"
+version = "2.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"
+dependencies = [
+ "anyhow",
+ "glob",
+ "plist",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-plugin-autostart"
+version = "2.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"
+dependencies = [
+ "auto-launch",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.19",
+]
+
+[[package]]
+name = "tauri-plugin-deep-link"
+version = "2.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d489b8ecceae1cd09f6e1f7606f2095ac721cc8d54cf2f0e6bb377cc52cff6"
+dependencies = [
+ "dunce",
+ "plist",
+ "rust-ini",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.19",
+ "tracing",
+ "url",
+ "windows-registry",
+ "windows-result 0.3.4",
+]
+
+[[package]]
+name = "tauri-plugin-dialog"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
+dependencies = [
+ "log",
+ "raw-window-handle",
+ "rfd",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-plugin-fs",
+ "thiserror 2.0.19",
+ "url",
+]
+
+[[package]]
+name = "tauri-plugin-fs"
+version = "2.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
+dependencies = [
+ "anyhow",
+ "dunce",
+ "glob",
+ "log",
+ "objc2-foundation",
+ "percent-encoding",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.19",
+ "toml 1.1.3+spec-1.1.0",
+ "url",
+]
+
+[[package]]
+name = "tauri-plugin-notification"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad2fd40946aef810c4be9fd33a2d1b9b397cb79042b2d21c81a0a8f204354fd1"
+dependencies = [
+ "log",
+ "notify-rust",
+ "rand",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.19",
+ "time",
+ "url",
+]
+
+[[package]]
+name = "tauri-plugin-opener"
+version = "2.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17e1bea14edce6b793a04e2417e3fd924b9bc4faae83cdee7d714156cceeed29"
+dependencies = [
+ "dunce",
+ "glob",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "open",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.19",
+ "url",
+ "windows",
+ "zbus",
+]
+
+[[package]]
+name = "tauri-plugin-single-instance"
+version = "2.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3214becf9ef5783c0ae99a3bb25adf5353a7a16ebf53e74b909e29205735c6c"
+dependencies = [
+ "serde",
+ "serde_json",
+ "tauri",
+ "thiserror 2.0.19",
+ "tokio",
+ "tracing",
+ "windows-sys 0.60.2",
+ "zbus",
+]
+
+[[package]]
+name = "tauri-plugin-window-state"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73736611e14142408d15353e21e3cca2f12a3cfb523ad0ce85999b6d2ef1a704"
+dependencies = [
+ "bitflags 2.13.1",
+ "log",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.19",
+]
+
+[[package]]
+name = "tauri-runtime"
+version = "2.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"
+dependencies = [
+ "cookie",
+ "dpi",
+ "gtk",
+ "http",
+ "jni",
+ "objc2",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "raw-window-handle",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "thiserror 2.0.19",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "windows",
+]
+
+[[package]]
+name = "tauri-runtime-wry"
+version = "2.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
+dependencies = [
+ "gtk",
+ "http",
+ "jni",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "once_cell",
+ "percent-encoding",
+ "raw-window-handle",
+ "softbuffer",
+ "tao",
+ "tauri-runtime",
+ "tauri-utils",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "windows",
+ "wry",
+]
+
+[[package]]
+name = "tauri-utils"
+version = "2.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"
+dependencies = [
+ "anyhow",
+ "brotli",
+ "cargo_metadata",
+ "ctor",
+ "dom_query",
+ "dunce",
+ "glob",
+ "http",
+ "infer",
+ "json-patch",
+ "log",
+ "memchr",
+ "phf",
+ "plist",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "schemars 0.8.22",
+ "semver",
+ "serde",
+ "serde-untagged",
+ "serde_json",
+ "serde_with",
+ "swift-rs",
+ "thiserror 2.0.19",
+ "toml 1.1.3+spec-1.1.0",
+ "url",
+ "urlpattern",
+ "uuid",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-winres"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
+dependencies = [
+ "dunce",
+ "embed-resource",
+ "toml 1.1.3+spec-1.1.0",
+]
+
+[[package]]
+name = "tauri-winrt-notification"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
+dependencies = [
+ "thiserror 2.0.19",
+ "windows",
+ "windows-version",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tendril"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"
+dependencies = [
+ "new_debug_unreachable",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
+dependencies = [
+ "thiserror-impl 2.0.19",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
+[[package]]
+name = "time"
+version = "0.3.54"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e1d5e639ff6bab73cb6885cc7e7b1de96c3f32c68ec55f3952614bec1092244"
+dependencies = [
+ "deranged",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "tiny-keccak"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
+dependencies = [
+ "crunchy",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"
+dependencies = [
+ "serde",
+ "serde_spanned 0.6.9",
+ "toml_datetime 0.6.3",
+ "toml_edit 0.20.2",
+]
+
+[[package]]
+name = "toml"
+version = "0.9.12+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
+dependencies = [
+ "indexmap 2.14.0",
+ "serde_core",
+ "serde_spanned 1.1.1",
+ "toml_datetime 0.7.5+spec-1.1.0",
+ "toml_parser",
+ "toml_writer",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"
+dependencies = [
+ "indexmap 2.14.0",
+ "serde_core",
+ "serde_spanned 1.1.1",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "toml_writer",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.7.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.19.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
+dependencies = [
+ "indexmap 2.14.0",
+ "toml_datetime 0.6.3",
+ "winnow 0.5.40",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
+dependencies = [
+ "indexmap 2.14.0",
+ "serde",
+ "serde_spanned 0.6.9",
+ "toml_datetime 0.6.3",
+ "winnow 0.5.40",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.13+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
+dependencies = [
+ "indexmap 2.14.0",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
+dependencies = [
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags 2.13.1",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "tray-icon"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"
+dependencies = [
+ "crossbeam-channel",
+ "dirs 6.0.0",
+ "libappindicator",
+ "muda",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "once_cell",
+ "png 0.18.1",
+ "serde",
+ "thiserror 2.0.19",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typeid"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "unic-char-property"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"
+dependencies = [
+ "unic-char-range",
+]
+
+[[package]]
+name = "unic-char-range"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"
+
+[[package]]
+name = "unic-common"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"
+
+[[package]]
+name = "unic-ucd-ident"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"
+dependencies = [
+ "unic-char-property",
+ "unic-char-range",
+ "unic-ucd-version",
+]
+
+[[package]]
+name = "unic-ucd-version"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"
+dependencies = [
+ "unic-common",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "urlpattern"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"
+dependencies = [
+ "regex",
+ "serde",
+ "unic-ucd-ident",
+ "url",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "uuid"
+version = "1.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239"
+dependencies = [
+ "getrandom 0.4.3",
+ "js-sys",
+ "serde_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "version-compare"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "vswhom"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"
+dependencies = [
+ "libc",
+ "vswhom-sys",
+]
+
+[[package]]
+name = "vswhom-sys"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"
+dependencies = [
+ "cc",
+ "libc",
+]
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.126"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.76"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.126"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.126"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.126"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-streams"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web_atoms"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297"
+dependencies = [
+ "phf",
+ "phf_codegen",
+ "string_cache",
+ "string_cache_codegen",
+]
+
+[[package]]
+name = "webkit2gtk"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"
+dependencies = [
+ "bitflags 1.3.2",
+ "cairo-rs",
+ "gdk",
+ "gdk-sys",
+ "gio",
+ "gio-sys",
+ "glib",
+ "glib-sys",
+ "gobject-sys",
+ "gtk",
+ "gtk-sys",
+ "javascriptcore-rs",
+ "libc",
+ "once_cell",
+ "soup3",
+ "webkit2gtk-sys",
+]
+
+[[package]]
+name = "webkit2gtk-sys"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"
+dependencies = [
+ "bitflags 1.3.2",
+ "cairo-sys-rs",
+ "gdk-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "gtk-sys",
+ "javascriptcore-rs-sys",
+ "libc",
+ "pkg-config",
+ "soup3-sys",
+ "system-deps",
+]
+
+[[package]]
+name = "webview2-com"
+version = "0.38.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
+dependencies = [
+ "webview2-com-macros",
+ "webview2-com-sys",
+ "windows",
+ "windows-core 0.61.2",
+ "windows-implement",
+ "windows-interface",
+]
+
+[[package]]
+name = "webview2-com-macros"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "webview2-com-sys"
+version = "0.38.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
+dependencies = [
+ "thiserror 2.0.19",
+ "windows",
+ "windows-core 0.61.2",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "window-vibrancy"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"
+dependencies = [
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "raw-window-handle",
+ "windows-sys 0.59.0",
+ "windows-version",
+]
+
+[[package]]
+name = "windows"
+version = "0.61.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
+dependencies = [
+ "windows-collections",
+ "windows-core 0.61.2",
+ "windows-future",
+ "windows-link 0.1.3",
+ "windows-numerics",
+]
+
+[[package]]
+name = "windows-collections"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
+dependencies = [
+ "windows-core 0.61.2",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link 0.1.3",
+ "windows-result 0.3.4",
+ "windows-strings 0.4.2",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link 0.2.1",
+ "windows-result 0.4.1",
+ "windows-strings 0.5.1",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
+dependencies = [
+ "windows-core 0.61.2",
+ "windows-link 0.1.3",
+ "windows-threading",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-numerics"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
+dependencies = [
+ "windows-core 0.61.2",
+ "windows-link 0.1.3",
+]
+
+[[package]]
+name = "windows-registry"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"
+dependencies = [
+ "windows-link 0.1.3",
+ "windows-result 0.3.4",
+ "windows-strings 0.4.2",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
+dependencies = [
+ "windows-link 0.1.3",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
+dependencies = [
+ "windows-link 0.1.3",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
+dependencies = [
+ "windows-targets 0.42.2",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link 0.2.1",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows-threading"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
+dependencies = [
+ "windows-link 0.1.3",
+]
+
+[[package]]
+name = "windows-version"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "winnow"
+version = "0.5.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winreg"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "winreg"
+version = "0.55.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "writeable"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
+
+[[package]]
+name = "wry"
+version = "0.55.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514"
+dependencies = [
+ "base64 0.22.1",
+ "block2",
+ "cookie",
+ "crossbeam-channel",
+ "dirs 6.0.0",
+ "dom_query",
+ "dpi",
+ "dunce",
+ "gdkx11",
+ "gtk",
+ "http",
+ "javascriptcore-rs",
+ "jni",
+ "libc",
+ "ndk",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "once_cell",
+ "percent-encoding",
+ "raw-window-handle",
+ "sha2",
+ "soup3",
+ "tao-macros",
+ "thiserror 2.0.19",
+ "url",
+ "webkit2gtk",
+ "webkit2gtk-sys",
+ "webview2-com",
+ "windows",
+ "windows-core 0.61.2",
+ "windows-version",
+ "x11-dl",
+]
+
+[[package]]
+name = "x11"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
+dependencies = [
+ "libc",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure",
+]
+
+[[package]]
+name = "zbus"
+version = "5.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe18fb60dc696039e738717b76eaea21e7a4489bbb1885020b43c94236d7e98a"
+dependencies = [
+ "async-broadcast",
+ "async-executor",
+ "async-io",
+ "async-lock",
+ "async-process",
+ "async-recursion",
+ "async-task",
+ "async-trait",
+ "blocking",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-lite",
+ "hex",
+ "libc",
+ "ordered-stream",
+ "rustix",
+ "serde",
+ "serde_repr",
+ "tracing",
+ "uds_windows",
+ "uuid",
+ "windows-sys 0.61.2",
+ "winnow 1.0.4",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "5.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe96480bed92df2b442a1a30df364e12d08eed03aeb061f2b8dc6afb2be91119"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zbus_names",
+ "zvariant",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "4.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
+dependencies = [
+ "serde",
+ "winnow 1.0.4",
+ "zvariant",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zip"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "flate2",
+ "indexmap 2.14.0",
+ "memchr",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zvariant"
+version = "5.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bee2a0bcd2a907786a456fff45aaaaf54c9ba5f50b71ae9ec1a4edd200c94911"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "winnow 1.0.4",
+ "zvariant_derive",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "5.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38a708216a18780796770bfe3f4739c7c83a3e8f789b755534bbbc06e4e23e12"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 2.0.119",
+ "winnow 1.0.4",
+]
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
new file mode 100644
index 000000000..e5180986b
--- /dev/null
+++ b/desktop/Cargo.toml
@@ -0,0 +1,21 @@
+[workspace]
+resolver = "2"
+members = ["runtime-host", "src-tauri"]
+
+[workspace.package]
+version = "0.1.0"
+edition = "2021"
+license = "MIT"
+publish = false
+
+[workspace.dependencies]
+async-trait = "0.1"
+reqwest = { version = "0.12", default-features = false }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+sha2 = "0.10"
+sys-locale = "0.3.2"
+thiserror = "2"
+tokio = { version = "1", default-features = false, features = ["rt", "time"] }
+url = "2"
+zip = { version = "4.6.1", default-features = false, features = ["deflate-flate2-zlib-rs"] }
diff --git a/desktop/README.md b/desktop/README.md
new file mode 100644
index 000000000..87b7cc272
--- /dev/null
+++ b/desktop/README.md
@@ -0,0 +1,328 @@
+# Avibe desktop shell
+
+A Tauri v2 shell that opens one window, makes sure an Avibe Runtime is serving
+the local Workbench, and then hands the window to it. It is deliberately thin:
+it hosts no product UI of its own beyond a bootstrap screen, and it owns no
+product logic.
+
+## What it does
+
+1. A product build verifies and installs its embedded Runtime; an ordinary
+ development build resolves an installed `vibe` executable. Both invoke
+ `vibe desktop endpoint --json` through the selected interpreter. Python
+ derives that versioned descriptor from the effective V2 UI binding, so Rust
+ never duplicates config semantics.
+2. Validates the target origin. Only the literal addresses `127.0.0.1` and
+ `[::1]` over `http` are accepted, so the shell can never be pointed at a
+ remote host. The hostname `localhost` is refused too: it names both addresses,
+ and the shell navigates to exactly the one whose readiness probe answered. A
+ refused origin is reported without being quoted back — it is unvalidated
+ process output on its way to a WebView.
+3. Probes `GET /ready`. Only the exact versioned `product: "avibe"` affirmative
+ response means that the UI, service-lock owner, and Controller IPC are all
+ ready; that Runtime is **adopted as-is**.
+4. Otherwise runs the selected Runtime's `start --no-open-browser` command
+ once, detached, with no shell interpreter involved. The shell already owns a
+ window onto the Workbench; plain `vibe start` honours
+ `config.ui.open_browser` and would leave the user with a second,
+ browser-hosted view of the same Runtime.
+5. Polls until the Runtime is ready or the bound expires, then navigates. The
+ window never leaves the bootstrap page before combined readiness succeeds.
+ If the launcher it started exits non-zero, it gives up immediately instead of
+ waiting out the timeout: nothing is coming, and the user is asked to update
+ Avibe rather than watching a spinner for two minutes.
+6. After navigation, probes the same exact origin every two seconds. Three
+ consecutive failures return the WebView to the bundled bootstrap and rerun
+ adoption/startup; a transient miss does not replace the Workbench.
+
+The Runtime outlives the shell. Closing the window never stops a Runtime,
+whether the shell adopted it or started it.
+
+### Why the Workbench stays unprivileged
+
+The three bootstrap commands are declared in `src-tauri/build.rs`, which makes
+`tauri-build` generate `allow-bootstrap-status` / `allow-bootstrap-retry`
+permissions. Without that declaration a Tauri v2 app command is callable from
+any page in any window — including the Workbench and every Show Page inside it.
+
+`src-tauri/capabilities/bootstrap.json` then grants those two permissions to
+`local: true` pages in the `main` window and names **no** `remote` URL, so the
+grant stops matching the moment the window navigates to the Runtime's http
+origin. `ensure_shell_ui` in `src-tauri/src/lib.rs` rejects such a call a second
+time regardless.
+
+Tauri decides *local* versus *remote* with `is_local_url`, which counts any URL
+relative to the configured `devUrl` as local. Port `1420` is therefore refused
+as a Runtime origin outright — in release builds too, where the dev server does
+not exist — so no `AVIBE_DESKTOP_ORIGIN` value can produce a Workbench page that
+Tauri would classify as the shell's own.
+
+All three properties are asserted, in `src-tauri/tests/shell_boundaries.rs` and
+`runtime-host/src/origin.rs`. Widening any of them fails a test.
+
+## Product packages
+
+The consumer DMG/NSIS build is self-contained. It embeds target-specific
+CPython, the Avibe wheel and locked Python dependencies, Node, and npm. A new
+user does **not** install Python, `uv`, Node, or npm. Codex, Claude Code, and
+OpenCode are intentionally not part of the application payload: Avibe detects
+an existing installation first and otherwise installs the selected backend into
+its private application-data directory when the user clicks Install.
+
+The first launch verifies the embedded Runtime archive and installs it
+atomically below the operating system's application-data directory. Installs
+are versioned and content-addressed, so application updates never replace files
+used by a running Runtime. Later launches re-verify the extracted file tree and
+repair one corrupt slot from the immutable archive; a second integrity failure
+is rejected. The Controller owns the archive identity that the UI forwards
+through `/ready`; `vibe start` replaces a mismatched desktop-managed Controller
+before it can reuse the service. After a successor proves that identity, the
+shell removes superseded private Runtime trees; reopening an older app reinstalls
+its own immutable payload for rollback. User state stays under `~/.avibe` and
+is not part of the application or private Runtime.
+
+`desktop-self-contained-package` builds per-target artifacts for:
+
+- Apple silicon macOS (`aarch64-apple-darwin`);
+- Intel macOS (`x86_64-apple-darwin`);
+- Windows x64 (`x86_64-pc-windows-msvc`).
+
+The manual macOS path is credential-gated; whichever state it produces is recorded
+in a target-qualified `.SIGNATURE` metadata file next to the artifact hashes:
+
+- **With repository secrets configured** (`APPLE_CERTIFICATE` +
+ `APPLE_CERTIFICATE_PASSWORD`, `APPLE_API_KEY` + `APPLE_API_ISSUER` +
+ `APPLE_API_PRIVATE_KEY`, optional `APPLE_SIGNING_IDENTITY`) the workflow
+ Developer ID signs the .app, notarizes it through the App Store Connect
+ API key, staples the ticket, and verifies the produced signature
+ (`SIGNATURE: app-identity-signed`). The credential set must be complete —
+ a partially populated set fails the build rather than silently producing a
+ signed-but-unnotarized artifact.
+- **Without those secrets** the app inside the DMG is ad-hoc signed so macOS can
+ verify its complete app/resource structure; it has no trusted developer
+ identity. The outer DMG is unsigned and unnotarized.
+
+Two signing layers are deliberately NOT in this workflow yet and remain
+tracked release gates (see [#1976](https://github.com/avibe-bot/avibe/issues/1976)):
+signing/notarizing the outer DMG image itself, and signing the Mach-O
+binaries inside the embedded `runtime.zip` before archiving. Windows
+signing is likewise not yet implemented; NSIS artifacts remain unsigned
+acceptance builds. Windows ARM64 stays outside the current product gate.
+
+### Initial test distribution
+
+`Release (AI Notes)` calls the existing `desktop-self-contained-package` workflow
+for canonical `gh-vX.Y.ZrcN` tags. For example, `gh-v3.1.2rc1` builds the tag's
+exact commit, stamps desktop version `3.1.2-rc.1`, and bundles Avibe `3.1.2rc1`.
+All three native builds must succeed before the existing release job publishes
+the GitHub prerelease. Official `v*` releases and PyPI publication keep their
+existing workflow; they do not acquire desktop assets from this TEST path.
+
+TEST builds never receive Apple or Windows signing credentials, even when the
+repository has them configured. The macOS app is ad-hoc signed, its outer DMG
+is unsigned/unnotarized, and the Windows NSIS installer is unsigned. Each raw
+DMG/EXE download has a target-qualified `.SHA256SUMS`, `.SIGNATURE`,
+`.SOURCE.json`, and `.runtime-manifest.json` alongside it. `SIGNATURE` describes
+the verified layer; it is not a cryptographic signature. Hashes and source
+metadata are checked before upload and downloaded desktop bytes are checked
+again before publication. A failed build or check leaves the release unpublished.
+Existing asset bytes cannot be overwritten; a changed build requires a new rc.
+Already-published releases cannot be retrofitted with missing desktop assets.
+
+The manual workflow remains available for artifact-only builds: select a source
+ref and SemVer version in Actions. It retains optional Developer ID signing and
+notarization when its complete Apple secret set is configured. Actions artifacts
+are retained for 14 days; neither path enables a desktop auto-updater.
+
+See [Desktop TEST installation](../docs/desktop-test-installation.md) for
+architecture selection, hash checks, app-specific Gatekeeper/SmartScreen
+approval, manual replacement upgrades that preserve `~/.avibe`, and removal.
+Python, Avibe, Node, and npm are bundled; no separate installation is required.
+
+Release operators need the existing `OPENAI_API_KEY` for AI notes, Actions
+permissions to read runtime sources and write GitHub Releases, and all three
+hosted native runners. Apple/Windows signing credentials are not prerequisites
+for TEST publication. Do not create a tag or dispatch a release without owner
+authorization. Start with a new rc on the approved source; wait for all runtime,
+package, and desktop builds plus the sole `release_ai` finalizer. A rerun may
+reuse identical bytes in a draft, but native rebuilds are not guaranteed to be
+byte-reproducible: use a new rc if immutable asset comparison fails.
+
+### Uninstalling a product package
+
+Choose **Uninstall Avibe…** from the first application menu before removing the
+application. Avibe asks for confirmation, gracefully stops a private Runtime
+that it owns, deletes the private Runtime and Avibe-managed backend installs
+under the operating system's application-data directory, and then quits. It
+never deletes `~/.avibe`, so projects, sessions, credentials, and settings
+remain available to a later installation. External backend installations are
+also untouched. After the confirmation completes, delete the macOS application
+or continue with the Windows system uninstaller.
+
+## Development prerequisites
+
+- Rust stable (`rustup toolchain install stable`), with `rustfmt` and `clippy`
+- Node.js `^20.19.0 || >=22.12.0`
+- macOS: Xcode Command Line Tools. Windows: MSVC build tools + WebView2
+ (preinstalled on Windows 11). Both provide the system WebView; there is
+ nothing to install for the WebView itself.
+- An installed Avibe Runtime (`uv tool install avibe-os`) is needed only for
+ ordinary development builds that do not enable `bundled-runtime`. It must implement
+ `vibe desktop endpoint --json`, `GET /ready`, and
+ `vibe start --no-open-browser`; an older one produces a localized retryable
+ update failure.
+
+## Commands
+
+Run everything from `desktop/`.
+
+| Command | What it does |
+| --- | --- |
+| `npm ci` | Install the bootstrap UI dependencies |
+| `npm run tauri dev` | Run the shell against the Vite dev server on port 1420 |
+| `npm run build` | Type-check and build the bootstrap UI into `dist/` |
+| `npm run test:i18n` | Verify English/Chinese bootstrap key and placeholder parity |
+| `npm run dev` | Serve the bootstrap UI alone in a browser (no shell, no IPC) |
+| `cargo test --workspace` | Run every Rust test |
+| `cargo test -p avibe-runtime-host` | Run the runtime logic tests without compiling Tauri |
+| `cargo fmt --all` | Format |
+| `cargo clippy --workspace --all-targets -- -D warnings` | Lint |
+| `cargo build --workspace` | Compile the shell binary |
+| `npm run tauri build` | Produce a bundled application |
+| `python scripts/build-runtime-bundle.py --target aarch64-apple-darwin` | Stage a verified private Runtime for this target |
+| `npm run tauri -- build --bundles app --features bundled-runtime` | Produce a self-contained macOS application bundle |
+| `sh scripts/create-macos-dmg.sh target/release/bundle/macos/Avibe.app target/release/bundle/dmg/Avibe.dmg` | Wrap the app in a headless-safe DMG |
+
+`cargo` steps depend on `dist/` existing, because `tauri::generate_context!`
+embeds the frontend at compile time. Run `npm run build` first in a fresh
+checkout — `npm run tauri dev` and `npm run tauri build` handle this themselves.
+
+## Native links and window frame
+
+Packaged installations register `avibe://` for native, single-window navigation:
+
+| Link | Existing Workbench destination |
+| --- | --- |
+| `avibe://session/<id>` | `/chat/<id>` |
+| `avibe://show/<id>` | `/apps/show/<id>` |
+| `avibe://settings` | `/admin/settings/service` |
+| `avibe://vaults/request/<id>` | `/vaults?request_id=<id>` |
+
+IDs use literal ASCII letters, digits, `.`, `_`, and `-`, up to 128 bytes;
+complete `.` and `..` are not IDs. Other schemes, URL syntax, and extra segments
+are silently dropped. A link received during startup waits for readiness; a
+failed bootstrap discards it. Links never select a different Runtime origin or
+grant the Workbench native commands. IM/browser links remain HTTPS.
+
+The main window remembers its native position, size, and maximized state in the
+window-state plugin's app configuration store. Restore happens before showing
+the window; bootstrap and Runtime navigation only change its content. Open from
+the tray preserves the last shown frame, with off-screen recovery against the
+current display work areas. Fullscreen, Spaces, visibility, and routes are not
+restored. An absent or corrupt store uses the centered 1200×800 default.
+
+For manual acceptance, use a packaged test install with isolated app config and
+a fake loopback Runtime: set a non-default frame, quit/relaunch, hide/Open, and
+deliver a link both before and after readiness. Check the destination and frame,
+not just process startup. Development `tauri dev` does not register the scheme.
+
+## Environment overrides
+
+All optional; the defaults are what ships.
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `AVIBE_DESKTOP_ORIGIN` | Python descriptor | Development/test override for another local Runtime. Still validated as loopback, and port `1420` is reserved for the shell's own UI. The override is adopt-only: the shell re-probes it on retry but never starts the default `vibe` against a different origin. |
+| `AVIBE_DESKTOP_VIBE_PATH` | — | Absolute path to a `vibe` executable. Useful because a GUI process launched from Finder or Explorer inherits a minimal `PATH` that usually excludes `~/.local/bin`. |
+| `UV_TOOL_BIN_DIR` | uv default | Standard uv override for the directory containing installed tool executables. The shell checks it after inherited `PATH`. |
+| `AVIBE_DESKTOP_READY_TIMEOUT_SECONDS` | `120` | How long a starting Runtime has to answer. Accepted range 1–600; anything else is ignored. |
+
+The shell also sets `AVIBE_DESKTOP_SHELL=1` on the Runtime it starts. That is an
+output, not an input.
+
+Development Runtime discovery is ordered and shell-free: the explicit desktop override,
+inherited `PATH`, `UV_TOOL_BIN_DIR`, the uv default under `~/.local/bin`,
+then platform fallbacks (`~/bin`, `~/.cargo/bin`, `/opt/homebrew/bin`,
+`/usr/local/bin`, or `%APPDATA%\Python\Scripts`). The Windows executable name
+is `vibe.exe`.
+If no executable is found, the bootstrap offers the fixed Avibe installation
+guide in the system browser; the WebView cannot provide or alter that URL.
+Product packages do not use this resolver: they verify, install, and directly
+launch their embedded Runtime. That Runtime receives
+`AVIBE_DESKTOP_MANAGED_RUNTIME=1`, so package checks and in-place `uv`/`pip`
+upgrades are disabled; updates are delivered by replacing the signed desktop
+application while user data remains untouched.
+
+The packaged Runtime also receives immutable Node/npm paths and a separate
+app-private backend root. Backend installation invokes npm as
+`node <npm-cli.js>` without a shell or global prefix. Backend releases update
+independently from the desktop application and the selected executable is
+persisted as an absolute path.
+
+## Layout
+
+```
+desktop/
+├── index.html, src/ Bootstrap UI (vanilla TS + Vite)
+├── runtime-host/ Runtime discovery, launch, readiness — no Tauri dependency
+│ ├── src/origin.rs Loopback origin validation
+│ ├── src/health.rs Exact `/ready` probing
+│ ├── src/launcher.rs Descriptor query plus detached, shell-free startup
+│ ├── src/private_runtime.rs Verified, atomic private Runtime installation
+│ ├── src/bootstrap.rs The state machine
+│ └── src/status.rs The status contract shared with the UI
+└── src-tauri/ Window, IPC commands, capability boundary
+```
+
+The split is the reason the logic is testable: `avibe-runtime-host` depends on
+no Tauri crate, so its tests compile in seconds and run on any platform, and the
+`src-tauri` crate stays thin enough to be checked by inspection.
+
+`runtime-host/tests/bootstrap.rs` drives a real `RuntimeHost` through fake
+collaborators under `tokio`'s virtual clock, so the 120-second production wait
+is exercised in microseconds. Launcher tests execute a fake installed CLI and
+assert the descriptor schema, byte bound, direct argv, and literal-loopback
+validation.
+
+## Regenerating icons
+
+Icons derive from the product logo. Regenerate from `desktop/`:
+
+```sh
+npx tauri icon ../ui/public/logo.png
+```
+
+`tauri icon` writes a full set including Android, iOS, and Windows Store assets.
+Only the five files listed under `bundle.icon` in `src-tauri/tauri.conf.json`
+are used — delete the rest rather than committing them.
+
+The bootstrap screen shows `src-tauri/icons/128x128.png` directly, so the mark in
+the window and the mark in the Dock are the same file and cannot drift apart.
+Vite fingerprints it into `dist/assets/`; nothing depends on the icon path at
+runtime.
+
+## Notifications
+
+The native tray's Notifications toggle is on by default and persists across
+app restarts. While the main window is unfocused or hidden, the shell consumes
+the existing Workbench SSE stream for pending Vault approvals and qualifying
+terminal background runs. The connection belongs to the shell, not the WebView;
+SSE reconnection is independent of the readiness monitor. Copy comes only from
+the native locale catalog, and no notification capability is granted to web
+content. OS notification permissions and Do Not Disturb remain OS-managed.
+v1 uses OS-default notification activation; explicit cross-platform show/focus
+and session deep-link targets require follow-up work. See
+`../docs/plans/desktop-notifications-sse.md` for the frozen contract.
+
+## CI
+
+`.github/workflows/desktop-shell.yml` runs on macOS and Windows whenever
+`desktop/**` or the two central bootstrap locale sections change: `npm ci`,
+`npm run test:i18n`, `npm run build`, `cargo fmt --check`,
+`cargo clippy -D warnings`, `cargo test`, `cargo build`. It does not bundle or
+sign. `.github/workflows/desktop-package.yml` builds architecture-specific,
+self-contained DMG and NSIS artifacts, both manually and as the reusable TEST
+build unit for `.github/workflows/release_ai.yml`. The manual signing policy and
+the deterministic TEST policy are described above. Native packaging and a real
+installation on each supported architecture remain separate acceptance gates
+from unit/contract tests.
diff --git a/desktop/index.html b/desktop/index.html
new file mode 100644
index 000000000..323eb29db
--- /dev/null
+++ b/desktop/index.html
@@ -0,0 +1,34 @@
+<!doctype html>
+<html lang="en" data-phase="probing">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Avibe</title>
+ </head>
+ <body>
+ <main class="stage" role="main">
+ <section class="card" aria-labelledby="title">
+ <!--
+ The product mark, reused from the application icon set so the bootstrap
+ window and the Dock icon can never show two different logos.
+ -->
+ <img class="mark" src="/src-tauri/icons/128x128.png" alt="" width="56" height="56" />
+
+ <h1 class="title" id="title">Avibe</h1>
+
+ <p class="message" id="message" role="status" aria-live="polite"></p>
+
+ <div class="track" id="track" aria-hidden="true"><span class="bar"></span></div>
+
+ <p class="origin"><code id="origin"></code></p>
+
+ <div class="actions" id="actions" hidden>
+ <button class="retry" id="retry" type="button"></button>
+ <button class="help" id="help" type="button"></button>
+ </div>
+ </section>
+ </main>
+
+ <script type="module" src="/src/main.ts"></script>
+ </body>
+</html>
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
new file mode 100644
index 000000000..8dc4dedb0
--- /dev/null
+++ b/desktop/package-lock.json
@@ -0,0 +1,1124 @@
+{
+ "name": "avibe-desktop",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "avibe-desktop",
+ "version": "0.1.0",
+ "dependencies": {
+ "@tauri-apps/api": "^2.9.0"
+ },
+ "devDependencies": {
+ "@tauri-apps/cli": "^2.11.0",
+ "typescript": "~5.9.3",
+ "vite": "^8.0.16"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@emnapi/core": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
+ "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
+ "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
+ "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
+ "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.139.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz",
+ "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",
+ "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz",
+ "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz",
+ "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz",
+ "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz",
+ "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz",
+ "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz",
+ "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz",
+ "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz",
+ "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz",
+ "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz",
+ "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz",
+ "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-wasm32-wasi": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz",
+ "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "1.11.1",
+ "@emnapi/runtime": "1.11.1",
+ "@napi-rs/wasm-runtime": "^1.1.6"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz",
+ "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==",
+ "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.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz",
+ "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==",
+ "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/api": {
+ "version": "2.11.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.1.tgz",
+ "integrity": "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==",
+ "license": "Apache-2.0 OR MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/tauri"
+ }
+ },
+ "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/@tybys/wasm-util": {
+ "version": "0.10.3",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
+ "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "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.16",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
+ "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
+ "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.5",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.23",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
+ "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==",
+ "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.16",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
+ "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.139.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.1.5",
+ "@rolldown/binding-darwin-arm64": "1.1.5",
+ "@rolldown/binding-darwin-x64": "1.1.5",
+ "@rolldown/binding-freebsd-x64": "1.1.5",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.1.5",
+ "@rolldown/binding-linux-arm64-gnu": "1.1.5",
+ "@rolldown/binding-linux-arm64-musl": "1.1.5",
+ "@rolldown/binding-linux-ppc64-gnu": "1.1.5",
+ "@rolldown/binding-linux-s390x-gnu": "1.1.5",
+ "@rolldown/binding-linux-x64-gnu": "1.1.5",
+ "@rolldown/binding-linux-x64-musl": "1.1.5",
+ "@rolldown/binding-openharmony-arm64": "1.1.5",
+ "@rolldown/binding-wasm32-wasi": "1.1.5",
+ "@rolldown/binding-win32-arm64-msvc": "1.1.5",
+ "@rolldown/binding-win32-x64-msvc": "1.1.5"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "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/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.1.5",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.5.tgz",
+ "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.32.0",
+ "picomatch": "^4.0.5",
+ "postcss": "^8.5.17",
+ "rolldown": "~1.1.5",
+ "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.3.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/desktop/package.json b/desktop/package.json
new file mode 100644
index 000000000..a69f032b7
--- /dev/null
+++ b/desktop/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "avibe-desktop",
+ "description": "Bootstrap UI for the Avibe desktop shell",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "scripts": {
+ "dev": "vite",
+ "build": "tsc --noEmit && vite build",
+ "test:i18n": "node scripts/verify-i18n.mjs",
+ "preview": "vite preview",
+ "tauri": "tauri"
+ },
+ "dependencies": {
+ "@tauri-apps/api": "^2.9.0"
+ },
+ "devDependencies": {
+ "@tauri-apps/cli": "^2.11.0",
+ "typescript": "~5.9.3",
+ "vite": "^8.0.16"
+ }
+}
diff --git a/desktop/runtime-host/Cargo.toml b/desktop/runtime-host/Cargo.toml
new file mode 100644
index 000000000..121b0f86f
--- /dev/null
+++ b/desktop/runtime-host/Cargo.toml
@@ -0,0 +1,28 @@
+[package]
+name = "avibe-runtime-host"
+description = "Loopback Runtime discovery, launch, and readiness logic for the Avibe desktop shell"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[dependencies]
+async-trait.workspace = true
+chrono = { version = "0.4", default-features = false, features = ["std"] }
+reqwest.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+sha2.workspace = true
+thiserror.workspace = true
+tokio.workspace = true
+url.workspace = true
+zip.workspace = true
+
+[dev-dependencies]
+async-trait.workspace = true
+tokio = { version = "1", default-features = false, features = [
+ "macros",
+ "rt",
+ "test-util",
+ "time",
+] }
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
new file mode 100644
index 000000000..cb360ea64
--- /dev/null
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -0,0 +1,1084 @@
+//! The bootstrap state machine.
+//!
+//! One run answers a single question — "is there a Runtime at this origin, and
+//! if not, can we get one?" — and reports every step through a [`StatusSink`].
+//! The shell navigates only when a run ends in [`BootstrapPhase::Ready`].
+
+use std::env;
+use std::sync::{Arc, Mutex, MutexGuard};
+use std::time::Duration;
+
+use tokio::time::{sleep, Instant};
+
+use crate::health::{HealthProbe, RuntimeReadiness};
+use crate::launcher::{
+ LaunchError, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher, RuntimeRemovalState, StartupReceipt,
+};
+use crate::origin::LoopbackOrigin;
+use crate::status::{BootstrapNotice, BootstrapNoticeCode, BootstrapStatus};
+
+/// Overrides the origin the shell probes and navigates to. Still validated as a
+/// loopback origin — this is a development and regression convenience, not a way
+/// to point the shell at a remote host.
+pub const ORIGIN_ENV: &str = "AVIBE_DESKTOP_ORIGIN";
+
+/// Overrides how long the shell waits for a freshly started Runtime.
+pub const READY_TIMEOUT_ENV: &str = "AVIBE_DESKTOP_READY_TIMEOUT_SECONDS";
+
+/// Gap between readiness probes.
+pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
+
+/// How long a starting Runtime has to answer `/ready`.
+///
+/// Matches `SERVICE_SLOW_START_TIMEOUT_SECONDS` in the Python service so the
+/// shell does not give up before the Runtime itself would.
+pub const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(120);
+
+/// Per-request timeout for a single readiness probe.
+pub const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
+
+const READY_TIMEOUT_CEILING_SECONDS: u64 = 600;
+
+/// Where bootstrap progress goes. The Tauri layer implements this by storing the
+/// latest status and emitting it to the bootstrap window; tests record it.
+pub trait StatusSink: Send + Sync {
+ fn publish(&self, status: BootstrapStatus);
+}
+
+/// Drops every intermediate status. For callers that only need the terminal one.
+pub struct DiscardStatus;
+
+impl StatusSink for DiscardStatus {
+ fn publish(&self, _status: BootstrapStatus) {}
+}
+
+#[derive(Debug, Clone)]
+pub struct RuntimeHostSettings {
+ /// Explicit development/test override. Production discovers the endpoint
+ /// through the installed Python Runtime on every bootstrap run.
+ pub origin_override: Option<String>,
+ pub poll_interval: Duration,
+ pub ready_timeout: Duration,
+ pub probe_timeout: Duration,
+}
+
+impl Default for RuntimeHostSettings {
+ fn default() -> Self {
+ Self {
+ origin_override: None,
+ poll_interval: DEFAULT_POLL_INTERVAL,
+ ready_timeout: DEFAULT_READY_TIMEOUT,
+ probe_timeout: DEFAULT_PROBE_TIMEOUT,
+ }
+ }
+}
+
+impl RuntimeHostSettings {
+ /// Applies the documented environment overrides to the defaults.
+ pub fn from_env() -> Self {
+ let defaults = Self::default();
+ Self {
+ origin_override: env::var(ORIGIN_ENV).ok().filter(|value| !value.trim().is_empty()),
+ ready_timeout: env::var(READY_TIMEOUT_ENV)
+ .ok()
+ .and_then(|value| parse_timeout(&value))
+ .unwrap_or(defaults.ready_timeout),
+ ..defaults
+ }
+ }
+}
+
+/// Parses a ready-timeout override, ignoring values that would disable the bound.
+fn parse_timeout(raw: &str) -> Option<Duration> {
+ let seconds: u64 = raw.trim().parse().ok()?;
+ (1..=READY_TIMEOUT_CEILING_SECONDS)
+ .contains(&seconds)
+ .then(|| Duration::from_secs(seconds))
+}
+
+/// Owns one Runtime origin for the lifetime of the shell process.
+///
+/// A host may run `bootstrap` many times — once at startup and once per user
+/// retry. It never overlaps launch commands. Normal lifecycle never stops a
+/// Runtime; explicit replacement and uninstall use the Runtime's own graceful
+/// CLI. After a completed successful launch still fails the full readiness
+/// budget, a later retry may re-run the idempotent start command to repair
+/// missing components.
+pub struct RuntimeHost {
+ probe: Arc<dyn HealthProbe>,
+ launcher: Arc<dyn RuntimeLauncher>,
+ settings: RuntimeHostSettings,
+ launched_runtime: Mutex<LaunchState>,
+}
+
+struct LaunchAttempt {
+ runtime: LaunchedRuntime,
+ launcher: Arc<dyn ResolvedRuntimeLauncher>,
+}
+
+#[derive(Default)]
+struct LaunchState {
+ attempt: Option<LaunchAttempt>,
+ ownership: Option<(Arc<dyn ResolvedRuntimeLauncher>, StartupReceipt)>,
+ /// The shell has evidence that a Runtime may still be alive, without
+ /// necessarily having scoped stop authority for it.
+ runtime_may_be_running: bool,
+ stopping: bool,
+}
+
+impl LaunchState {
+ fn capture_ownership(&mut self) {
+ if let Some(attempt) = &self.attempt {
+ if let Some(receipt) = attempt.runtime.watch.owned_receipt() {
+ self.ownership = Some((attempt.launcher.clone(), receipt.clone()));
+ self.runtime_may_be_running = true;
+ }
+ }
+ }
+
+ fn retain_completed_attempt_liveness(&mut self) {
+ if self
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| attempt.runtime.watch.succeeded())
+ {
+ // A successful helper may have started a Runtime even when the
+ // receipt is reused or absent. Completion is not proof of process
+ // absence, so releasing the retry slot must retain this fence.
+ self.runtime_may_be_running = true;
+ }
+ }
+}
+
+impl RuntimeHost {
+ pub fn new(probe: Arc<dyn HealthProbe>, launcher: Arc<dyn RuntimeLauncher>, settings: RuntimeHostSettings) -> Self {
+ Self {
+ probe,
+ launcher,
+ settings,
+ launched_runtime: Mutex::new(LaunchState::default()),
+ }
+ }
+
+ pub fn settings(&self) -> &RuntimeHostSettings {
+ &self.settings
+ }
+
+ /// Whether this host retains a launch attempt for launch deduplication.
+ pub fn has_launched(&self) -> bool {
+ self.launched_runtime().attempt.is_some()
+ }
+
+ pub fn has_owned_runtime(&self) -> bool {
+ self.launched_runtime().ownership.is_some()
+ }
+
+ pub async fn stop_owned_runtime(&self) -> Result<(), LaunchError> {
+ let (launcher, receipt) = {
+ let mut state = self.launched_runtime();
+ let ownership = state.ownership.clone().ok_or(LaunchError::NotOwned)?;
+ if state.stopping
+ || state
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| !attempt.runtime.watch.succeeded() && !attempt.runtime.watch.failed())
+ {
+ return Err(LaunchError::RuntimeStop);
+ }
+ state.stopping = true;
+ ownership
+ };
+ let stopping = launcher.clone();
+ let result = tokio::task::spawn_blocking(move || stopping.stop(&receipt))
+ .await
+ .map_err(|_| LaunchError::RuntimeStop)
+ .and_then(|result| result);
+ let mut state = self.launched_runtime();
+ if state
+ .ownership
+ .as_ref()
+ .is_some_and(|(owner, _)| Arc::ptr_eq(owner, &launcher))
+ {
+ if result.is_ok() {
+ *state = LaunchState::default();
+ } else if matches!(result, Err(LaunchError::OwnershipLost)) {
+ // Refusal revokes the receipt, but does not prove that the
+ // replacement Runtime is gone. Retain the uninstall fence.
+ state.attempt = None;
+ state.ownership = None;
+ state.stopping = false;
+ } else {
+ state.stopping = false;
+ }
+ }
+ result
+ }
+
+ /// Probes the exact validated origin using the same readiness contract as bootstrap.
+ pub async fn is_ready(&self, origin: &LoopbackOrigin) -> bool {
+ self.probe.is_healthy(origin).await
+ }
+
+ /// Releases only completed helper retry state after readiness loss.
+ ///
+ /// Readiness loss is not process-loss evidence. A pending helper remains
+ /// retained so recovery cannot overlap it, and a valid started receipt
+ /// remains scoped stop authority. This transition never changes stopping
+ /// state or clears the liveness fence.
+ pub fn release_after_readiness_loss(&self) {
+ let mut state = self.launched_runtime();
+ if state.stopping {
+ return;
+ }
+ if state
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| attempt.runtime.watch.succeeded() || attempt.runtime.watch.failed())
+ {
+ state.retain_completed_attempt_liveness();
+ state.attempt = None;
+ }
+ }
+
+ /// Gracefully stops and removes an app-private Runtime owned by this host.
+ ///
+ /// Installed/user-managed launchers return `false` and are never modified.
+ pub async fn remove_private_runtime(&self, active_origin: Option<&LoopbackOrigin>) -> Result<bool, LaunchError> {
+ let liveness_uncertain = {
+ let state = self.launched_runtime();
+ state.runtime_may_be_running || state.attempt.is_some()
+ };
+ // A receipt authorizes only receipt-scoped stop, never the launcher's
+ // unscoped managed removal. Unavailable readiness remains unknown until
+ // a successful scoped stop clears local liveness evidence.
+ let state = match active_origin {
+ Some(origin) => match self.probe.readiness(origin).await {
+ Some(readiness) if readiness.desktop_ui_runtime_id.is_some() => RuntimeRemovalState::Unknown,
+ Some(readiness) if readiness.desktop_runtime_id.is_some() => RuntimeRemovalState::Managed,
+ Some(_) if liveness_uncertain => RuntimeRemovalState::Unknown,
+ Some(_) => RuntimeRemovalState::External,
+ None => RuntimeRemovalState::Unknown,
+ },
+ None if liveness_uncertain => RuntimeRemovalState::Unknown,
+ None => RuntimeRemovalState::Inactive,
+ };
+ let launcher = self.launcher.clone();
+ let removed = tokio::task::spawn_blocking(move || launcher.remove_private_runtime(state))
+ .await
+ .map_err(|_| LaunchError::RuntimeRemoval)??;
+ if removed {
+ *self.launched_runtime() = LaunchState::default();
+ }
+ Ok(removed)
+ }
+
+ /// Runs the state machine once and returns its terminal status.
+ pub async fn bootstrap(&self, sink: &dyn StatusSink) -> BootstrapStatus {
+ let (origin, resolved_launcher) = match self.resolve_origin().await {
+ Ok(resolved) => resolved,
+ Err(error) => {
+ return publish(
+ sink,
+ BootstrapStatus::rejected(error.notice_code(), error.is_retryable()),
+ )
+ }
+ };
+
+ let mut attempt = 1;
+ let mut handover_performed = false;
+ publish(sink, BootstrapStatus::probing(&origin, attempt));
+
+ // External Runtimes and the same desktop Runtime are adopted. A
+ // desktop-managed predecessor is stopped through its own graceful CLI
+ // before the successor starts.
+ if let Some(readiness) = self.probe.readiness(&origin).await {
+ let needs_handover = resolved_launcher
+ .as_ref()
+ .is_some_and(|launcher| launcher.requires_handover(&readiness));
+ if needs_handover {
+ if let Err(error) = handover(resolved_launcher.as_ref().expect("checked launcher").clone()).await {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(error.notice_code()),
+ error.is_retryable(),
+ ),
+ );
+ }
+ handover_performed = true;
+ } else {
+ cleanup_if_current(resolved_launcher.as_ref(), &readiness).await;
+ return publish(
+ sink,
+ BootstrapStatus::ready(&origin, attempt, BootstrapNoticeCode::Adopted),
+ );
+ }
+ }
+ // `/ready` rejects a UI/Controller pair with different private Runtime
+ // identities. That is intentionally not readiness, but the exact
+ // mismatch response still authorizes the bundled successor to stop the
+ // superseded desktop-managed service before launching.
+ if !handover_performed
+ && self
+ .probe
+ .mismatched_runtime_identity(&origin)
+ .await
+ .is_some_and(|identity| identity.desktop_runtime_id.is_some())
+ && resolved_launcher
+ .as_ref()
+ .is_some_and(|launcher| launcher.expected_runtime_id().is_some())
+ {
+ if let Err(error) = handover(resolved_launcher.as_ref().expect("checked launcher").clone()).await {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(error.notice_code()),
+ error.is_retryable(),
+ ),
+ );
+ }
+ handover_performed = true;
+ }
+
+ // A launcher may report its non-zero exit after an earlier bootstrap
+ // timed out. Re-check the retained watch before deciding this run is
+ // already waiting on a viable launch.
+ if self.clear_failed_launch() {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::LauncherExited),
+ true,
+ ),
+ );
+ }
+ // A development override points at another local Runtime and is treated
+ // as externally managed. The shell must not start a differently
+ // configured default Runtime and then wait on the override forever.
+ if resolved_launcher.is_none() {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::RuntimeNotFound),
+ true,
+ ),
+ );
+ }
+
+ // The lock makes the decision and launch atomic, so concurrent runs
+ // cannot both start the Runtime.
+ if let Err(error) = self.launch_if_needed(resolved_launcher.clone()) {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(error.notice_code()),
+ error.is_retryable(),
+ ),
+ );
+ }
+
+ publish(sink, BootstrapStatus::starting(&origin, attempt));
+
+ let mut deadline = Instant::now() + self.settings.ready_timeout;
+ while Instant::now() < deadline {
+ sleep(self.settings.poll_interval).await;
+ attempt += 1;
+ let readiness = self.probe.readiness(&origin).await;
+ let mut needs_polling_handover = false;
+ if let Some(readiness) = readiness {
+ if readiness_matches_launched_runtime(resolved_launcher.as_ref(), &readiness) {
+ cleanup_if_current(resolved_launcher.as_ref(), &readiness).await;
+ return publish(
+ sink,
+ BootstrapStatus::ready(
+ &origin,
+ attempt,
+ if self.has_owned_runtime() {
+ BootstrapNoticeCode::Ready
+ } else {
+ BootstrapNoticeCode::Adopted
+ },
+ ),
+ );
+ }
+ needs_polling_handover = !handover_performed
+ && resolved_launcher
+ .as_ref()
+ .is_some_and(|launcher| launcher.requires_handover(&readiness));
+ } else if !handover_performed {
+ needs_polling_handover = self
+ .probe
+ .mismatched_runtime_identity(&origin)
+ .await
+ .is_some_and(|identity| identity.desktop_runtime_id.is_some())
+ && resolved_launcher
+ .as_ref()
+ .is_some_and(|launcher| launcher.expected_runtime_id().is_some());
+ }
+ if needs_polling_handover {
+ let launcher = resolved_launcher
+ .as_ref()
+ .expect("handover requires a launcher")
+ .clone();
+ if let Err(error) = handover(launcher).await {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(error.notice_code()),
+ error.is_retryable(),
+ ),
+ );
+ }
+ handover_performed = true;
+ *self.launched_runtime() = LaunchState::default();
+ if let Err(error) = self.launch_if_needed(resolved_launcher.clone()) {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(error.notice_code()),
+ error.is_retryable(),
+ ),
+ );
+ }
+ // Handover may legitimately spend most of the original startup
+ // budget. The newly launched successor gets its own full window.
+ deadline = Instant::now() + self.settings.ready_timeout;
+ }
+ // A launcher that exited non-zero started nothing, so the remaining
+ // wait would be spent polling an address that will never answer.
+ if self.clear_failed_launch() {
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::LauncherExited),
+ true,
+ ),
+ );
+ }
+ publish(sink, BootstrapStatus::starting(&origin, attempt));
+ }
+
+ // Do not retain a completed zero-exit helper forever when the Runtime
+ // still failed the entire readiness budget. An unresolved launcher is
+ // retained so Retry cannot overlap a command that is still running.
+ self.clear_successful_launch();
+ publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::timeout(self.settings.ready_timeout.as_secs()),
+ true,
+ ),
+ )
+ }
+
+ async fn resolve_origin(&self) -> Result<(LoopbackOrigin, Option<Arc<dyn ResolvedRuntimeLauncher>>), LaunchError> {
+ if let Some(origin) = self.settings.origin_override.as_deref() {
+ return LoopbackOrigin::parse(origin)
+ .map(|origin| (origin, None))
+ .map_err(|_| LaunchError::InvalidOrigin);
+ }
+ let launcher = self.launcher.clone();
+ tokio::task::spawn_blocking(move || {
+ let resolved = launcher.resolve()?;
+ let origin = resolved.endpoint()?;
+ Ok((origin, Some(resolved)))
+ })
+ .await
+ .map_err(|_| LaunchError::EndpointOutput)?
+ }
+
+ fn launched_runtime(&self) -> MutexGuard<'_, LaunchState> {
+ let mut state = self
+ .launched_runtime
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ // A successful receipt can arrive between bootstrap attempts. Capture it
+ // before releasing a completed helper's retry slot.
+ state.capture_ownership();
+ state
+ }
+
+ fn launch_if_needed(&self, resolved_launcher: Option<Arc<dyn ResolvedRuntimeLauncher>>) -> Result<(), LaunchError> {
+ let mut state = self.launched_runtime();
+ if state.stopping {
+ return Err(LaunchError::RuntimeStop);
+ }
+ if state
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| attempt.runtime.watch.succeeded())
+ {
+ state.retain_completed_attempt_liveness();
+ state.attempt = None;
+ }
+ if state.attempt.is_none() {
+ let launcher = match resolved_launcher {
+ Some(resolved) => resolved,
+ None => self.launcher.resolve()?,
+ };
+ let runtime = launcher.launch()?;
+ // Spawning the helper is evidence that a Runtime may exist even
+ // when the helper later reports failure or no receipt. Keep that
+ // fact separate from retry deduplication and stop authority.
+ state.attempt = Some(LaunchAttempt { runtime, launcher });
+ state.runtime_may_be_running = true;
+ }
+ Ok(())
+ }
+
+ /// A failed helper releases its retry slot without erasing an earlier receipt.
+ fn clear_failed_launch(&self) -> bool {
+ let mut state = self.launched_runtime();
+ if state
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| attempt.runtime.watch.failed())
+ {
+ state.attempt = None;
+ return true;
+ }
+ false
+ }
+
+ /// Readiness timeout releases only a completed helper, never stop authority.
+ /// Pending helpers remain retained so Retry cannot overlap a live launch.
+ fn clear_successful_launch(&self) -> bool {
+ let mut state = self.launched_runtime();
+ if state
+ .attempt
+ .as_ref()
+ .is_some_and(|attempt| attempt.runtime.watch.succeeded())
+ {
+ state.retain_completed_attempt_liveness();
+ state.attempt = None;
+ return true;
+ }
+ false
+ }
+}
+
+async fn handover(launcher: Arc<dyn ResolvedRuntimeLauncher>) -> Result<(), LaunchError> {
+ tokio::task::spawn_blocking(move || launcher.handover())
+ .await
+ .map_err(|_| LaunchError::Handover)?
+}
+
+fn readiness_matches_launched_runtime(
+ launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>,
+ readiness: &RuntimeReadiness,
+) -> bool {
+ match launcher.and_then(|launcher| launcher.expected_runtime_id()) {
+ // A validated ready response without a desktop identity is an
+ // externally managed Controller. It may still be served by a UI that
+ // inherited the bundled launcher's identity, so polling must adopt it
+ // just as the initial probe does. A tagged response remains bound to
+ // the exact bundled identity.
+ Some(expected) => readiness
+ .desktop_runtime_id
+ .as_deref()
+ .is_none_or(|actual| actual == expected),
+ None => true,
+ }
+}
+
+async fn cleanup_if_current(launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>, readiness: &RuntimeReadiness) {
+ let Some(launcher) = launcher else {
+ return;
+ };
+ if launcher.expected_runtime_id() != readiness.desktop_runtime_id.as_deref() {
+ return;
+ }
+ let launcher = launcher.clone();
+ let _ = tokio::task::spawn_blocking(move || launcher.prune_superseded()).await;
+}
+
+fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
+ sink.publish(status.clone());
+ status
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::launcher::{LaunchWatch, StartupReceipt};
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+
+ struct ReadyProbe;
+
+ #[async_trait::async_trait]
+ impl HealthProbe for ReadyProbe {
+ async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ Some(RuntimeReadiness {
+ desktop_runtime_id: None,
+ desktop_ui_runtime_id: None,
+ })
+ }
+ }
+
+ fn receipt_watch(outcome: &str) -> LaunchWatch {
+ let receipt = StartupReceipt::from_json(
+ format!(
+ r#"{{"schema_version":1,"outcome":"{outcome}","service_pid":1234,"ui_pid":5678,"service_create_unix_ms":1789010100123.5,"ui_create_unix_ms":1789010100456.5}}"#
+ ).as_bytes(),
+ ).expect("valid receipt");
+ LaunchWatch::exited_with_receipt(true, receipt)
+ }
+
+ #[derive(Clone)]
+ struct RecordingLauncher {
+ resolutions: Arc<AtomicUsize>,
+ launches: Arc<AtomicUsize>,
+ stops: Arc<AtomicUsize>,
+ fail_stop: Arc<AtomicBool>,
+ ownership_lost: Arc<AtomicBool>,
+ removals: Arc<Mutex<Vec<RuntimeRemovalState>>>,
+ watch: LaunchWatch,
+ private_cleanup: Option<Arc<crate::BundledVibeLauncher>>,
+ }
+
+ impl Default for RecordingLauncher {
+ fn default() -> Self {
+ Self {
+ resolutions: Arc::default(),
+ launches: Arc::default(),
+ stops: Arc::default(),
+ fail_stop: Arc::default(),
+ ownership_lost: Arc::default(),
+ removals: Arc::default(),
+ watch: receipt_watch("started"),
+ private_cleanup: None,
+ }
+ }
+ }
+
+ impl RuntimeLauncher for RecordingLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ self.resolutions.fetch_add(1, Ordering::SeqCst);
+ Ok(Arc::new(self.clone()))
+ }
+
+ fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
+ self.removals.lock().expect("record removals").push(state);
+ match &self.private_cleanup {
+ Some(launcher) => launcher.remove_private_runtime(state),
+ None => Err(LaunchError::RuntimeRemoval),
+ }
+ }
+ }
+
+ impl ResolvedRuntimeLauncher for RecordingLauncher {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse("http://127.0.0.1:5123").expect("test origin"))
+ }
+
+ fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ self.launches.fetch_add(1, Ordering::SeqCst);
+ Ok(LaunchedRuntime {
+ pid: 9012,
+ watch: self.watch.clone(),
+ })
+ }
+
+ fn stop(&self, receipt: &StartupReceipt) -> Result<(), LaunchError> {
+ assert_eq!(Some(receipt), self.watch.owned_receipt());
+ self.stops.fetch_add(1, Ordering::SeqCst);
+ if self.ownership_lost.load(Ordering::SeqCst) {
+ Err(LaunchError::OwnershipLost)
+ } else if self.fail_stop.load(Ordering::SeqCst) {
+ Err(LaunchError::RuntimeStop)
+ } else {
+ Ok(())
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn an_adopted_runtime_can_never_be_stopped_by_the_host() {
+ let launcher = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
+ assert_eq!(
+ host.bootstrap(&DiscardStatus).await.notice.code,
+ BootstrapNoticeCode::Adopted
+ );
+ assert!(!host.has_launched());
+ assert!(!host.has_owned_runtime());
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(launcher.resolutions.load(Ordering::SeqCst), 1);
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
+ }
+
+ struct TransientProbe(AtomicBool);
+
+ #[async_trait::async_trait]
+ impl HealthProbe for TransientProbe {
+ async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ self.0.swap(true, Ordering::SeqCst).then_some(RuntimeReadiness {
+ desktop_runtime_id: None,
+ desktop_ui_runtime_id: None,
+ })
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn successful_reuse_after_a_transient_probe_miss_never_grants_stop_authority() {
+ let launcher = Arc::new(RecordingLauncher {
+ watch: receipt_watch("reused"),
+ ..RecordingLauncher::default()
+ });
+ let host = RuntimeHost::new(
+ Arc::new(TransientProbe(AtomicBool::new(false))),
+ launcher.clone(),
+ RuntimeHostSettings::default(),
+ );
+ let status = host.bootstrap(&DiscardStatus).await;
+ assert_eq!(status.phase, crate::BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
+ assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
+ assert!(host.has_launched());
+ assert!(!host.has_owned_runtime());
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn timeout_then_retry_then_uninstall_retains_unknown_liveness_fence() {
+ let launcher = Arc::new(RecordingLauncher {
+ watch: receipt_watch("reused"),
+ ..RecordingLauncher::default()
+ });
+ let host = RuntimeHost::new(
+ Arc::new(TransientProbe(AtomicBool::new(false))),
+ launcher.clone(),
+ RuntimeHostSettings {
+ ready_timeout: Duration::ZERO,
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ assert_eq!(
+ host.bootstrap(&DiscardStatus).await.notice.code,
+ BootstrapNoticeCode::ReadyTimeout
+ );
+ assert!(
+ !host.has_launched(),
+ "a completed helper must release retry deduplication"
+ );
+ assert!(
+ !host.has_owned_runtime(),
+ "a reused receipt never grants stop authority"
+ );
+
+ assert_eq!(host.bootstrap(&DiscardStatus).await.phase, crate::BootstrapPhase::Ready);
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ *launcher.removals.lock().expect("recorded removal"),
+ [RuntimeRemovalState::Unknown]
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn timeout_then_late_ready_retry_preserves_scoped_stop_authority() {
+ let launcher = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(
+ Arc::new(TransientProbe(AtomicBool::new(false))),
+ launcher.clone(),
+ RuntimeHostSettings {
+ ready_timeout: Duration::ZERO,
+ ..RuntimeHostSettings::default()
+ },
+ );
+ assert_eq!(
+ host.bootstrap(&DiscardStatus).await.notice.code,
+ BootstrapNoticeCode::ReadyTimeout
+ );
+ assert!(!host.has_launched(), "completed helper releases the retry slot");
+ assert!(host.has_owned_runtime(), "timeout is not evidence of ownership loss");
+ assert_eq!(host.bootstrap(&DiscardStatus).await.phase, crate::BootstrapPhase::Ready);
+ assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
+ host.stop_owned_runtime()
+ .await
+ .expect("retained receipt authorizes scoped stop");
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ assert!(!host.has_owned_runtime());
+ }
+
+ #[tokio::test]
+ async fn only_completed_successful_started_receipts_grant_stop_authority() {
+ for watch in [
+ LaunchWatch::default(),
+ LaunchWatch::exited(true),
+ LaunchWatch::exited(false),
+ receipt_watch("reused"),
+ ] {
+ let completed = watch.succeeded() || watch.failed();
+ let launcher = Arc::new(RecordingLauncher {
+ watch,
+ ..RecordingLauncher::default()
+ });
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
+ host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
+ assert!(host.has_launched());
+ assert!(!host.has_owned_runtime());
+ host.release_after_readiness_loss();
+ assert_eq!(
+ host.has_launched(),
+ !completed,
+ "only completed helpers release retry deduplication"
+ );
+ assert!(!host.has_owned_runtime(), "readiness loss never grants authority");
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ *launcher.removals.lock().expect("recorded removal"),
+ [RuntimeRemovalState::Unknown]
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn receipt_refusal_revokes_authority_without_retrying_or_stopping_a_replacement() {
+ let launcher = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
+ host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
+ assert!(host.has_owned_runtime());
+ launcher.ownership_lost.store(true, Ordering::SeqCst);
+ assert!(matches!(
+ host.stop_owned_runtime().await,
+ Err(LaunchError::OwnershipLost)
+ ));
+ assert!(!host.has_owned_runtime());
+ assert!(!host.has_launched());
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ host.bootstrap(&DiscardStatus).await.notice.code,
+ BootstrapNoticeCode::Adopted
+ );
+ assert!(!host.has_owned_runtime());
+ assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn receipt_refusal_retains_unknown_liveness_for_uninstall() {
+ let launcher = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
+ host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
+ launcher.ownership_lost.store(true, Ordering::SeqCst);
+
+ assert!(matches!(
+ host.stop_owned_runtime().await,
+ Err(LaunchError::OwnershipLost)
+ ));
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ *launcher.removals.lock().expect("recorded removal"),
+ [RuntimeRemovalState::Unknown]
+ );
+ }
+
+ #[tokio::test]
+ async fn stop_uses_the_retained_launcher_and_releases_only_successful_ownership() {
+ let resolver = Arc::new(RecordingLauncher::default());
+ let launched = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), resolver.clone(), RuntimeHostSettings::default());
+ host.launch_if_needed(Some(launched.clone())).expect("fake launch");
+ launched.fail_stop.store(true, Ordering::SeqCst);
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::RuntimeStop)));
+ assert!(host.has_launched());
+ assert!(host.has_owned_runtime());
+ launched.fail_stop.store(false, Ordering::SeqCst);
+ host.stop_owned_runtime().await.expect("explicit retry succeeds");
+ assert!(!host.has_launched());
+ assert!(!host.has_owned_runtime());
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(launched.stops.load(Ordering::SeqCst), 2);
+ assert_eq!(resolver.resolutions.load(Ordering::SeqCst), 0);
+ assert_eq!(resolver.stops.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn readiness_loss_releases_retry_slot_but_retains_scoped_stop_authority() {
+ let launcher = Arc::new(RecordingLauncher::default());
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
+ host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
+ host.release_after_readiness_loss();
+ assert!(!host.has_launched(), "completed helper retry slot is released");
+ assert!(
+ host.has_owned_runtime(),
+ "readiness loss does not revoke a valid receipt"
+ );
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ *launcher.removals.lock().expect("recorded removal"),
+ [RuntimeRemovalState::Unknown]
+ );
+ host.stop_owned_runtime()
+ .await
+ .expect("the retained receipt reaches explicit scoped stop");
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ assert!(
+ !host.has_owned_runtime(),
+ "successful stop clears the receipt and liveness fence"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_replacement_receipt_cannot_stop_the_previous_launcher() {
+ let previous = Arc::new(RecordingLauncher::default());
+ let mut replacement_receipt = serde_json::to_value(receipt_watch("started").owned_receipt().unwrap()).unwrap();
+ replacement_receipt["service_pid"] = serde_json::json!(4321);
+ let replacement = Arc::new(RecordingLauncher {
+ watch: LaunchWatch::exited_with_receipt(true, serde_json::from_value(replacement_receipt).unwrap()),
+ ..RecordingLauncher::default()
+ });
+ let host = RuntimeHost::new(Arc::new(ReadyProbe), previous.clone(), RuntimeHostSettings::default());
+
+ host.launch_if_needed(Some(previous.clone())).expect("previous launch");
+ host.release_after_readiness_loss();
+ let previous_receipt = previous
+ .watch
+ .owned_receipt()
+ .expect("previous started receipt")
+ .clone();
+ previous.ownership_lost.store(true, Ordering::SeqCst);
+
+ host.launch_if_needed(Some(replacement.clone()))
+ .expect("replacement launch");
+ assert!(
+ host.has_owned_runtime(),
+ "the newer receipt replaces old scoped authority"
+ );
+ assert!(matches!(
+ previous.stop(&previous_receipt),
+ Err(LaunchError::OwnershipLost)
+ ));
+ let previous_stop_attempts = previous.stops.load(Ordering::SeqCst);
+ host.stop_owned_runtime()
+ .await
+ .expect("the replacement receipt is stoppable");
+ assert_eq!(previous.stops.load(Ordering::SeqCst), previous_stop_attempts);
+ assert_eq!(replacement.stops.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn recovery_receipt_requires_scoped_stop_before_unknown_private_files_can_be_removed() {
+ // The real bundled remover must refuse before preparing a bundle or
+ // invoking unscoped handover. All paths below belong to this test.
+ for refused in [false, true] {
+ let root = std::env::temp_dir().join(format!("avibe-h4-removal-{}-{refused}", std::process::id()));
+ let installs = root.join("runtime");
+ let backends = root.join("backends");
+ std::fs::create_dir_all(&installs).unwrap();
+ std::fs::create_dir_all(&backends).unwrap();
+ std::fs::write(installs.join("active"), b"live runtime bytes").unwrap();
+ std::fs::write(backends.join("active"), b"live backend bytes").unwrap();
+ std::fs::write(root.join("unrelated"), b"unrelated state").unwrap();
+ let launcher = Arc::new(RecordingLauncher {
+ private_cleanup: Some(Arc::new(crate::BundledVibeLauncher::new(
+ root.join("missing-bundle"),
+ installs.clone(),
+ backends.clone(),
+ crate::BootstrapLog::disabled(),
+ ))),
+ ..RecordingLauncher::default()
+ });
+ let host = RuntimeHost::new(
+ Arc::new(TransientProbe(AtomicBool::new(false))),
+ launcher.clone(),
+ RuntimeHostSettings {
+ ready_timeout: Duration::ZERO,
+ ..RuntimeHostSettings::default()
+ },
+ );
+ host.launch_if_needed(Some(launcher.clone())).unwrap();
+ host.release_after_readiness_loss();
+ assert!(host.has_owned_runtime());
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap();
+ for active in [None, Some(&origin)] {
+ assert!(matches!(
+ host.remove_private_runtime(active).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ }
+ assert_eq!(*launcher.removals.lock().unwrap(), [RuntimeRemovalState::Unknown; 2]);
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
+ assert_eq!(std::fs::read(installs.join("active")).unwrap(), b"live runtime bytes");
+ assert_eq!(std::fs::read(backends.join("active")).unwrap(), b"live backend bytes");
+ launcher.ownership_lost.store(refused, Ordering::SeqCst);
+ let stopped = host.stop_owned_runtime().await;
+ if refused {
+ assert!(matches!(stopped, Err(LaunchError::OwnershipLost)));
+ assert!(!host.has_owned_runtime());
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert!(installs.join("active").exists() && backends.join("active").exists());
+ } else {
+ stopped.unwrap();
+ assert!(host.remove_private_runtime(None).await.unwrap());
+ assert!(!installs.exists() && !backends.exists());
+ assert_eq!(
+ launcher.removals.lock().unwrap().last(),
+ Some(&RuntimeRemovalState::Inactive)
+ );
+ }
+ assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ assert_eq!(std::fs::read(root.join("unrelated")).unwrap(), b"unrelated state");
+ std::fs::remove_dir_all(root).unwrap();
+ }
+ }
+
+ #[test]
+ fn production_discovers_the_origin_from_the_installed_runtime() {
+ let settings = RuntimeHostSettings::default();
+ assert!(settings.origin_override.is_none());
+ }
+
+ #[test]
+ fn the_default_wait_is_not_shorter_than_the_service_slow_start_budget() {
+ // `SERVICE_SLOW_START_TIMEOUT_SECONDS` in vibe/service_manager.py.
+ assert!(RuntimeHostSettings::default().ready_timeout >= Duration::from_secs(120));
+ }
+
+ #[test]
+ fn a_timeout_override_must_be_a_positive_bounded_number_of_seconds() {
+ assert_eq!(parse_timeout("30"), Some(Duration::from_secs(30)));
+ assert_eq!(parse_timeout(" 30 "), Some(Duration::from_secs(30)));
+ for rejected in ["", "0", "-1", "abc", "30s", "1e3", "601", "18446744073709551616"] {
+ assert_eq!(parse_timeout(rejected), None, "override {rejected:?}");
+ }
+ }
+}
diff --git a/desktop/runtime-host/src/bootstrap_log.rs b/desktop/runtime-host/src/bootstrap_log.rs
new file mode 100644
index 000000000..78dbaa943
--- /dev/null
+++ b/desktop/runtime-host/src/bootstrap_log.rs
@@ -0,0 +1,284 @@
+//! Why a bootstrap failed, in a file the user can send us.
+//!
+//! The shell's failure surface is a notice code. A code says that something
+//! went wrong; it cannot say what. Everything that would answer "what" is
+//! discarded today: the endpoint helper's stderr goes to the null device, and
+//! nothing records whether a launch reused the installed Runtime or paid to
+//! extract a fresh one. This module keeps those facts on disk, beside the
+//! Runtime the application installed for itself.
+//!
+//! Three rules hold it to that job:
+//!
+//! 1. **Diagnostics never change the outcome they describe.** Every I/O error
+//! here is dropped. A log that cannot be written must not turn a working
+//! launch into a failed one, nor one failure into a different one.
+//! 2. **The interesting attempt is usually the previous one**, so the file is
+//! appended to and trimmed from the front. Starting the application never
+//! truncates it.
+//! 3. **Only what a failure needs.** No environment, no configuration, no
+//! credentials.
+
+use std::fs::{self, OpenOptions};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+/// The file name the shell writes its bootstrap diagnostics to.
+///
+/// The shell joins it onto the application's local data directory, so on macOS
+/// the file is `~/Library/Application Support/bot.avibe.desktop/bootstrap.log`.
+/// Anything that later tells the user where to find it must derive the path
+/// from this name rather than restate it.
+pub const BOOTSTRAP_LOG_NAME: &str = "bootstrap.log";
+
+/// How much history the file keeps: enough for many attempts carrying a few KB
+/// of captured stderr each, small enough that a user can attach it to a message.
+const MAX_LOG_BYTES: usize = 64 * 1024;
+
+/// An append-only diagnostics file, or nothing at all.
+///
+/// `disabled()` is not an error case. A development shell drives an
+/// already-installed `vibe` and owns no application data directory, and the
+/// code that records must not have to know which of the two it is holding.
+#[derive(Clone, Debug, Default)]
+pub struct BootstrapLog {
+ sink: Option<Arc<Sink>>,
+}
+
+#[derive(Debug)]
+struct Sink {
+ path: PathBuf,
+ /// Appending and trimming is read-modify-write, and the bootstrap thread is
+ /// not the only thread that can reach a launcher.
+ gate: Mutex<()>,
+}
+
+impl BootstrapLog {
+ pub fn at(path: PathBuf) -> Self {
+ Self {
+ sink: Some(Arc::new(Sink {
+ path,
+ gate: Mutex::new(()),
+ })),
+ }
+ }
+
+ pub fn disabled() -> Self {
+ Self::default()
+ }
+
+ pub fn path(&self) -> Option<&Path> {
+ self.sink.as_ref().map(|sink| sink.path.as_path())
+ }
+
+ /// Appends one record: a timestamp, the application version, the event, and
+ /// the fields that event carries.
+ ///
+ /// Every value is written through `{:?}`, which quotes and escapes it. That
+ /// is what keeps the file's one structural promise — a record is a line —
+ /// true even though captured stderr is full of newlines and quotes.
+ pub fn record(&self, event: &str, fields: &[(&str, String)]) {
+ let Some(sink) = self.sink.as_ref() else {
+ return;
+ };
+ let mut line = format!("{} {event} app={:?}", timestamp(), env!("CARGO_PKG_VERSION"));
+ for (key, value) in fields {
+ line.push_str(&format!(" {key}={value:?}"));
+ }
+ line.push('\n');
+ let _ = sink.append(line.as_bytes());
+ }
+}
+
+impl Sink {
+ fn append(&self, record: &[u8]) -> std::io::Result<()> {
+ let _guard = self.gate.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ if let Some(parent) = self.path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let mut file = OpenOptions::new().create(true).append(true).open(&self.path)?;
+ file.write_all(record)?;
+ let length = file.metadata()?.len();
+ drop(file);
+ if length as usize > MAX_LOG_BYTES {
+ self.trim()?;
+ }
+ Ok(())
+ }
+
+ /// Keeps the newest `MAX_LOG_BYTES` and drops what precedes them.
+ ///
+ /// The cut lands on a line boundary so the file stays readable from its
+ /// first byte, and the rewrite goes through a sibling file so a crash mid-
+ /// trim cannot leave a half-written log where a whole one used to be.
+ fn trim(&self) -> std::io::Result<()> {
+ let data = fs::read(&self.path)?;
+ let cut = data.len().saturating_sub(MAX_LOG_BYTES);
+ let start = data[cut..]
+ .iter()
+ .position(|byte| *byte == b'\n')
+ .map(|offset| cut + offset + 1)
+ // A boundary at the very end would keep nothing at all; the newest
+ // record matters more than a clean first line.
+ .filter(|start| *start < data.len())
+ .unwrap_or(cut);
+ let temporary = self.path.with_extension("trim");
+ fs::write(&temporary, &data[start..])?;
+ fs::rename(&temporary, &self.path)
+ }
+}
+
+/// UTC, to the millisecond.
+///
+/// `chrono` is compiled here without its clock feature, so the moment comes
+/// from `SystemTime` and chrono only formats it. A log a user sends us is read
+/// against our own records, not against their wall clock, so UTC is the useful
+/// zone.
+fn timestamp() -> String {
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
+ chrono::DateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos())
+ .map(|moment| moment.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
+ .unwrap_or_else(|| "unknown".to_owned())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ fn scratch_dir(label: &str) -> PathBuf {
+ static COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+ let unique = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir = std::env::temp_dir().join(format!("avibe-bootstrap-log-{label}-{}-{unique}", std::process::id()));
+ fs::create_dir_all(&dir).expect("scratch directory is created");
+ dir
+ }
+
+ #[test]
+ fn a_disabled_log_has_no_path_and_writes_nothing() {
+ let log = BootstrapLog::disabled();
+ assert!(log.path().is_none());
+ // The record call still has to be safe to make; every caller makes it
+ // unconditionally so that the recording path is the same in both shells.
+ log.record("endpoint.query", &[("outcome", "ok".to_owned())]);
+ }
+
+ #[test]
+ fn captured_output_cannot_forge_a_record_of_its_own() {
+ let dir = scratch_dir("escaping");
+ let log = BootstrapLog::at(dir.join(BOOTSTRAP_LOG_NAME));
+
+ log.record(
+ "endpoint.query",
+ &[(
+ "stderr",
+ "Traceback:\n2000-01-01T00:00:00.000Z endpoint.query outcome=\"ok\"\n".to_owned(),
+ )],
+ );
+
+ let written = fs::read_to_string(dir.join(BOOTSTRAP_LOG_NAME)).expect("the log is written");
+ assert_eq!(
+ written.lines().count(),
+ 1,
+ "a captured newline must not become a second record: {written}"
+ );
+ assert!(written.contains("outcome=\\\"ok\\\""), "{written}");
+ assert!(written.contains("Traceback:\\n"), "{written}");
+
+ fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn every_record_carries_a_timestamp_and_the_application_version() {
+ let dir = scratch_dir("stamp");
+ let log = BootstrapLog::at(dir.join(BOOTSTRAP_LOG_NAME));
+
+ log.record("runtime.prepare", &[("outcome", "reused".to_owned())]);
+
+ let written = fs::read_to_string(dir.join(BOOTSTRAP_LOG_NAME)).expect("the log is written");
+ let (stamp, rest) = written.trim_end().split_once(' ').expect("a stamped record");
+ assert!(stamp.ends_with('Z') && stamp.len() >= 24, "{stamp}");
+ assert_eq!(
+ rest,
+ format!("runtime.prepare app={:?} outcome=\"reused\"", env!("CARGO_PKG_VERSION"))
+ );
+
+ fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn the_log_stays_bounded_across_many_attempts_and_keeps_the_newest() {
+ let dir = scratch_dir("bounded");
+ let path = dir.join(BOOTSTRAP_LOG_NAME);
+ let log = BootstrapLog::at(path.clone());
+
+ // Roughly 2MB of records through a 64KB file.
+ for attempt in 0..2_000 {
+ log.record(
+ "endpoint.query",
+ &[("attempt", attempt.to_string()), ("stderr", "x".repeat(1_000))],
+ );
+ }
+
+ let written = fs::read_to_string(&path).expect("the log is written");
+ assert!(
+ written.len() <= MAX_LOG_BYTES,
+ "the log grew to {} bytes",
+ written.len()
+ );
+ assert!(written.contains("attempt=\"1999\""), "the newest attempt is kept");
+ assert!(!written.contains("attempt=\"0\""), "the oldest attempt is dropped");
+ for line in written.lines() {
+ assert!(
+ line.contains(" endpoint.query app="),
+ "trimming cut inside a record: {line:.80}"
+ );
+ }
+
+ fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn nothing_is_written_outside_the_directory_the_log_was_given() {
+ let root = scratch_dir("contained");
+ let data_dir = root.join("application-data");
+ let log = BootstrapLog::at(data_dir.join(BOOTSTRAP_LOG_NAME));
+
+ for attempt in 0..200 {
+ log.record(
+ "endpoint.query",
+ &[("attempt", attempt.to_string()), ("stderr", "x".repeat(1_000))],
+ );
+ }
+
+ let mut entries: Vec<String> = fs::read_dir(&data_dir)
+ .expect("the log created its own directory")
+ .map(|entry| {
+ entry
+ .expect("a readable entry")
+ .file_name()
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect();
+ entries.sort();
+ // Including the trim's sibling file: it is renamed over the log, never
+ // left behind, and it never leaves this directory.
+ assert_eq!(entries, [BOOTSTRAP_LOG_NAME]);
+ let outside: Vec<String> = fs::read_dir(&root)
+ .expect("the scratch root is readable")
+ .map(|entry| {
+ entry
+ .expect("a readable entry")
+ .file_name()
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect();
+ assert_eq!(outside, ["application-data"]);
+
+ fs::remove_dir_all(&root).ok();
+ }
+}
diff --git a/desktop/runtime-host/src/deep_link.rs b/desktop/runtime-host/src/deep_link.rs
new file mode 100644
index 000000000..a203ccacf
--- /dev/null
+++ b/desktop/runtime-host/src/deep_link.rs
@@ -0,0 +1,314 @@
+use std::sync::Arc;
+
+use url::Url;
+
+use crate::{BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, LoopbackOrigin};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct DeepLinkTarget {
+ path: String,
+}
+
+impl DeepLinkTarget {
+ pub fn path(&self) -> &str {
+ &self.path
+ }
+
+ pub fn navigation_url(&self, origin: &LoopbackOrigin) -> Url {
+ origin
+ .navigation_url()
+ .join(&self.path)
+ .expect("a parsed deep link is a same-origin path")
+ }
+}
+
+pub fn parse_deep_link(raw: &str) -> Option<DeepLinkTarget> {
+ let parsed = Url::parse(raw).ok()?;
+ if parsed.scheme() != "avibe"
+ || !raw.starts_with("avibe://")
+ || parsed.as_str() != raw
+ || !parsed.username().is_empty()
+ || parsed.password().is_some()
+ || parsed.port().is_some()
+ || parsed.query().is_some()
+ || parsed.fragment().is_some()
+ {
+ return None;
+ }
+ let path = match (parsed.host_str()?, parsed.path()) {
+ ("session", path) | ("show", path) => {
+ let identifier = path.strip_prefix('/')?;
+ if !valid_identifier(identifier) {
+ return None;
+ }
+ let prefix = if parsed.host_str() == Some("session") {
+ "/chat"
+ } else {
+ "/apps/show"
+ };
+ format!("{prefix}/{identifier}")
+ }
+ ("settings", "") => "/admin/settings/service".to_owned(),
+ ("vaults", path) => {
+ let identifier = path.strip_prefix("/request/")?;
+ if !valid_identifier(identifier) {
+ return None;
+ }
+ format!("/vaults?request_id={identifier}")
+ }
+ _ => return None,
+ };
+ Some(DeepLinkTarget { path })
+}
+
+fn valid_identifier(identifier: &str) -> bool {
+ !identifier.is_empty()
+ && identifier.len() <= 128
+ && !matches!(identifier, "." | "..")
+ && identifier
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
+}
+
+pub struct DeepLinkNavigation {
+ destination: Url,
+ delivery: Option<Arc<DeepLinkTarget>>,
+}
+
+impl DeepLinkNavigation {
+ pub fn url(&self) -> &Url {
+ &self.destination
+ }
+}
+
+#[derive(Default)]
+pub struct DeepLinks {
+ pending: Option<Arc<DeepLinkTarget>>,
+ failed: bool,
+}
+
+impl DeepLinks {
+ pub fn receive(&mut self, arguments: impl IntoIterator<Item = impl AsRef<str>>) {
+ if self.failed {
+ return;
+ }
+ if let Some(target) = arguments
+ .into_iter()
+ .find_map(|argument| parse_deep_link(argument.as_ref()))
+ {
+ self.pending = Some(Arc::new(target));
+ }
+ }
+
+ pub fn observe_bootstrap(&mut self, status: &BootstrapStatus) {
+ self.failed = status.phase == BootstrapPhase::Failed
+ && status.notice.code != BootstrapNoticeCode::WorkbenchNavigationFailed;
+ if self.failed {
+ self.pending = None;
+ }
+ }
+
+ pub fn bootstrap_navigation(&mut self, status: &BootstrapStatus) -> Option<DeepLinkNavigation> {
+ self.observe_bootstrap(status);
+ if status.phase != BootstrapPhase::Ready {
+ return None;
+ }
+ let origin = LoopbackOrigin::parse(&status.origin).ok()?;
+ Some(self.prepare_navigation(&origin))
+ }
+
+ pub fn workbench_navigation(&self, origin: &LoopbackOrigin, current_url: &Url) -> Option<DeepLinkNavigation> {
+ if !origin.matches_url_origin(current_url) {
+ return None;
+ }
+ self.pending.as_ref()?;
+ Some(self.prepare_navigation(origin))
+ }
+
+ pub fn commit_navigation(
+ &mut self,
+ navigation: &DeepLinkNavigation,
+ navigation_succeeded: bool,
+ issuing_generation: u64,
+ current_generation: u64,
+ ) -> bool {
+ if !navigation_succeeded || issuing_generation != current_generation {
+ return false;
+ }
+ match (&self.pending, &navigation.delivery) {
+ (Some(pending), Some(delivery)) if Arc::ptr_eq(pending, delivery) => {
+ self.pending = None;
+ true
+ }
+ _ => false,
+ }
+ }
+
+ fn prepare_navigation(&self, origin: &LoopbackOrigin) -> DeepLinkNavigation {
+ DeepLinkNavigation {
+ destination: self
+ .pending
+ .as_ref()
+ .map_or_else(|| origin.navigation_url(), |target| target.navigation_url(origin)),
+ delivery: self.pending.clone(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const MAPPINGS: &[(&str, &str)] = &[
+ ("avibe://session/ses.A_b-9", "/chat/ses.A_b-9"),
+ ("avibe://show/ses.A_b-9", "/apps/show/ses.A_b-9"),
+ ("avibe://settings", "/admin/settings/service"),
+ ("avibe://vaults/request/req.A_b-9", "/vaults?request_id=req.A_b-9"),
+ ];
+
+ #[test]
+ fn every_contract_mapping_preserves_its_path_and_the_adopted_origin() {
+ for origin in ["http://127.0.0.1:35123", "http://[::1]:49152"] {
+ let origin = LoopbackOrigin::parse(origin).unwrap();
+ for (input, path) in MAPPINGS {
+ let target = parse_deep_link(input).unwrap();
+ assert_eq!(target.path(), *path);
+ let destination = target.navigation_url(&origin);
+ assert_eq!(destination.as_str(), format!("{}{path}", origin.as_str()));
+ assert!(origin.matches_url_origin(&destination));
+ assert!(!crate::is_shell_ui_url(&destination));
+ }
+ }
+ }
+
+ #[test]
+ fn identifiers_are_bounded_literal_path_segments_not_url_syntax() {
+ for prefix in ["avibe://session/", "avibe://show/", "avibe://vaults/request/"] {
+ for length in 1..=128 {
+ let identifier = "a".repeat(length);
+ assert!(parse_deep_link(&format!("{prefix}{identifier}")).is_some());
+ }
+ assert!(parse_deep_link(&format!("{prefix}{}", "a".repeat(129))).is_none());
+ for byte in 0..=127_u8 {
+ let identifier = format!("a{}b", char::from(byte));
+ let allowed = byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-');
+ assert_eq!(parse_deep_link(&format!("{prefix}{identifier}")).is_some(), allowed);
+ }
+ for identifier in ["", ".", "..", "%2E", "%2E%2E", "你好", "a/b", "a\\b", "a?x", "a#x"] {
+ assert!(parse_deep_link(&format!("{prefix}{identifier}")).is_none());
+ }
+ }
+ }
+
+ #[test]
+ fn only_the_literal_frozen_grammar_can_produce_a_navigation() {
+ for (input, _) in MAPPINGS {
+ for malformed in [
+ input.replacen("avibe:", "https:", 1),
+ input.replacen("avibe://", "avibe://host@", 1),
+ input.replacen("avibe://", "avibe:///", 1),
+ input.replacen("avibe://", "avibe://unknown/", 1),
+ input.replacen("avibe://", "avibe:", 1),
+ format!("{input}/"),
+ format!("{input}/extra"),
+ format!("{input}?unexpected"),
+ format!("{input}#fragment"),
+ format!(" {input}"),
+ format!("{input}\n"),
+ ] {
+ assert!(parse_deep_link(&malformed).is_none(), "{malformed:?}");
+ }
+ }
+ for malformed in [
+ "avibe://session:80/id",
+ "avibe://session@show/id",
+ "avibe://@session/id",
+ "avibe://session/id/../normalized",
+ "avibe://session/id/%2E%2E/normalized",
+ "avibe://session/id/./normalized",
+ ] {
+ assert!(parse_deep_link(malformed).is_none(), "{malformed:?}");
+ }
+ }
+
+ #[test]
+ fn hot_delivery_waits_for_the_adopted_workbench_and_applies_once() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:39567").unwrap();
+ let mut links = DeepLinks::default();
+ links.receive(["avibe", "--flag", "avibe://session/hot"]);
+ for current in ["tauri://localhost/", "http://localhost:1420/", "http://127.0.0.1:5123/"] {
+ assert!(links
+ .workbench_navigation(&origin, &Url::parse(current).unwrap())
+ .is_none());
+ }
+ let navigation = links.workbench_navigation(&origin, &origin.navigation_url()).unwrap();
+ assert_eq!(navigation.url().as_str(), "http://127.0.0.1:39567/chat/hot");
+ assert!(links.commit_navigation(&navigation, true, 1, 1));
+ assert!(links.workbench_navigation(&origin, &origin.navigation_url()).is_none());
+ }
+
+ #[test]
+ fn a_delivery_selects_one_valid_link_and_invalid_input_cannot_erase_it() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:39567").unwrap();
+ let mut links = DeepLinks::default();
+ links.receive(["avibe", "avibe://session/first", "avibe://session/second"]);
+ links.receive(["avibe://session/../settings"]);
+ assert_eq!(
+ links
+ .workbench_navigation(&origin, &origin.navigation_url())
+ .unwrap()
+ .url()
+ .path(),
+ "/chat/first"
+ );
+ }
+
+ #[test]
+ fn only_success_in_the_issuing_window_consumes_a_prepared_delivery() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:39567").unwrap();
+ let issuing_generation = 2;
+ for navigation_succeeded in [false, true] {
+ for current_generation in 1..=3 {
+ let mut links = DeepLinks::default();
+ links.receive(["avibe://session/pending"]);
+ let navigation = links.workbench_navigation(&origin, &origin.navigation_url()).unwrap();
+ assert!(links.workbench_navigation(&origin, &origin.navigation_url()).is_some());
+ let should_commit = navigation_succeeded && issuing_generation == current_generation;
+ assert_eq!(
+ links.commit_navigation(
+ &navigation,
+ navigation_succeeded,
+ issuing_generation,
+ current_generation
+ ),
+ should_commit
+ );
+ assert_eq!(
+ links.workbench_navigation(&origin, &origin.navigation_url()).is_none(),
+ should_commit
+ );
+ assert!(!links.commit_navigation(&navigation, false, issuing_generation, current_generation));
+ }
+ }
+ }
+
+ #[test]
+ fn an_older_commit_never_clears_a_newer_delivery_even_for_the_same_url() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:39567").unwrap();
+ let ready = BootstrapStatus::ready(&origin, 1, BootstrapNoticeCode::Ready);
+ for first in [None, Some("avibe://session/first")] {
+ for next in ["avibe://session/first", "avibe://show/newer"] {
+ let mut links = DeepLinks::default();
+ links.receive(first);
+ let older = links.bootstrap_navigation(&ready).unwrap();
+ links.receive([next]);
+ assert!(!links.commit_navigation(&older, true, 1, 1));
+ let newer = links.workbench_navigation(&origin, &origin.navigation_url()).unwrap();
+ assert_eq!(newer.url(), &parse_deep_link(next).unwrap().navigation_url(&origin));
+ assert!(links.commit_navigation(&newer, true, 1, 1));
+ assert!(!links.commit_navigation(&newer, true, 1, 1));
+ assert!(links.workbench_navigation(&origin, &origin.navigation_url()).is_none());
+ }
+ }
+ }
+}
diff --git a/desktop/runtime-host/src/health.rs b/desktop/runtime-host/src/health.rs
new file mode 100644
index 000000000..9c7fe0ff5
--- /dev/null
+++ b/desktop/runtime-host/src/health.rs
@@ -0,0 +1,499 @@
+//! Readiness probing against the Avibe Web UI server.
+
+use std::time::Duration;
+
+use async_trait::async_trait;
+
+use crate::origin::LoopbackOrigin;
+
+const MAX_READINESS_BYTES: usize = 1024;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RuntimeReadiness {
+ /// Identity of the Controller Runtime, when it is desktop-managed.
+ pub desktop_runtime_id: Option<String>,
+ /// Identity of the UI Runtime serving an external Controller, when the UI
+ /// is known to come from a bundled private tree.
+ pub desktop_ui_runtime_id: Option<String>,
+}
+
+/// Answers whether the Avibe UI and Controller serve this origin and, for an
+/// app-private Runtime, which immutable archive is running.
+///
+/// Transport errors and raw response bodies stay inside the probe so nothing
+/// from the network reaches the bootstrap UI.
+#[async_trait]
+pub trait HealthProbe: Send + Sync {
+ async fn readiness(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness>;
+
+ /// Returns the Controller identity from an explicit UI/Controller mismatch.
+ ///
+ /// This is not readiness: callers may use it only to hand a superseded
+ /// desktop-managed Runtime over to its bundled successor.
+ async fn mismatched_runtime_identity(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ None
+ }
+
+ async fn is_healthy(&self, origin: &LoopbackOrigin) -> bool {
+ self.readiness(origin).await.is_some()
+ }
+}
+
+/// `GET <origin>/ready`, requiring UI, service ownership, and Controller IPC.
+pub struct HttpHealthProbe {
+ client: reqwest::Client,
+}
+
+impl HttpHealthProbe {
+ pub fn new(timeout: Duration) -> Result<Self, reqwest::Error> {
+ let client = reqwest::Client::builder()
+ .timeout(timeout)
+ // Readiness must be proved by this exact loopback listener. Following
+ // a redirect would let an unrelated local service delegate trust to
+ // arbitrary remote content.
+ .redirect(reqwest::redirect::Policy::none())
+ // A proxy configured for the wider machine must never sit between the
+ // shell and a loopback Runtime.
+ .no_proxy()
+ .build()?;
+ Ok(Self { client })
+ }
+}
+
+#[async_trait]
+impl HealthProbe for HttpHealthProbe {
+ async fn readiness(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ let Ok(response) = self.client.get(origin.readiness_url()).send().await else {
+ return None;
+ };
+ if !response.status().is_success() {
+ return None;
+ }
+ let body = bounded_response_body(response).await?;
+ parse_avibe_readiness_body(&body)
+ }
+
+ async fn mismatched_runtime_identity(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ let Ok(response) = self.client.get(origin.readiness_url()).send().await else {
+ return None;
+ };
+ if response.status() != reqwest::StatusCode::SERVICE_UNAVAILABLE {
+ return None;
+ }
+ let body = bounded_response_body(response).await?;
+ parse_runtime_identity_mismatch_body(&body)
+ }
+}
+
+async fn bounded_response_body(mut response: reqwest::Response) -> Option<String> {
+ if response
+ .content_length()
+ .is_some_and(|length| length > MAX_READINESS_BYTES as u64)
+ {
+ return None;
+ }
+ let mut body = Vec::new();
+ loop {
+ let chunk = match response.chunk().await {
+ Ok(Some(chunk)) => chunk,
+ Ok(None) => break,
+ Err(_) => return None,
+ };
+ let length = body.len().checked_add(chunk.len())?;
+ if length > MAX_READINESS_BYTES {
+ return None;
+ }
+ body.extend_from_slice(&chunk);
+ }
+ String::from_utf8(body).ok()
+}
+
+/// Whether a `/ready` body proves both the UI and Controller are ready.
+///
+/// The Python endpoint performs the authoritative service-lock and internal IPC
+/// checks. Rust accepts only its exact affirmative payload.
+pub fn is_avibe_readiness_body(body: &str) -> bool {
+ parse_avibe_readiness_body(body).is_some()
+}
+
+pub fn parse_avibe_readiness_body(body: &str) -> Option<RuntimeReadiness> {
+ let Ok(payload) = serde_json::from_str::<serde_json::Value>(body) else {
+ return None;
+ };
+ let object = payload.as_object()?;
+ let controller_runtime_id = match object.get("desktop_runtime_id") {
+ Some(value) => Some(value.as_str()?),
+ None => None,
+ };
+ let ui_runtime_id = match object.get("desktop_ui_runtime_id") {
+ Some(value) => Some(value.as_str()?),
+ None => None,
+ };
+ let expected_len = 3 + usize::from(controller_runtime_id.is_some() || ui_runtime_id.is_some());
+ let keys_valid = object.keys().all(|key| {
+ matches!(
+ key.as_str(),
+ "schema_version" | "product" | "ready" | "desktop_runtime_id" | "desktop_ui_runtime_id"
+ )
+ });
+ if (controller_runtime_id.is_some() && ui_runtime_id.is_some())
+ || object.len() != expected_len
+ || !keys_valid
+ || object.get("schema_version").and_then(serde_json::Value::as_u64) != Some(1)
+ || object.get("product").and_then(serde_json::Value::as_str) != Some("avibe")
+ || object.get("ready").and_then(serde_json::Value::as_bool) != Some(true)
+ || controller_runtime_id.or(ui_runtime_id).is_some_and(|value| {
+ value.len() != 64
+ || !value
+ .bytes()
+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+ })
+ {
+ return None;
+ }
+ Some(RuntimeReadiness {
+ desktop_runtime_id: controller_runtime_id.map(str::to_owned),
+ desktop_ui_runtime_id: ui_runtime_id.map(str::to_owned),
+ })
+}
+
+fn parse_runtime_identity_mismatch_body(body: &str) -> Option<RuntimeReadiness> {
+ let Ok(payload) = serde_json::from_str::<serde_json::Value>(body) else {
+ return None;
+ };
+ let object = payload.as_object()?;
+ let runtime_id = object.get("desktop_runtime_id")?.as_str()?;
+ if object.len() != 5
+ || object.get("schema_version").and_then(serde_json::Value::as_u64) != Some(1)
+ || object.get("product").and_then(serde_json::Value::as_str) != Some("avibe")
+ || object.get("ready").and_then(serde_json::Value::as_bool) != Some(false)
+ || object.get("code").and_then(serde_json::Value::as_str) != Some("runtime_identity_mismatch")
+ || runtime_id.len() != 64
+ || !runtime_id
+ .bytes()
+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+ {
+ return None;
+ }
+ Some(RuntimeReadiness {
+ desktop_runtime_id: Some(runtime_id.to_owned()),
+ desktop_ui_runtime_id: None,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Read, Write};
+ use std::net::{Shutdown, TcpListener, TcpStream};
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Arc;
+
+ const READY_BODY: &str = r#"{"schema_version":1,"product":"avibe","ready":true}"#;
+ const EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY: &str =
+ include_str!("../../../tests/fixtures/desktop_ready_external_controller_bundled_ui.json");
+
+ struct TestServer {
+ origin: LoopbackOrigin,
+ contacted: Arc<AtomicBool>,
+ stop: Arc<AtomicBool>,
+ handle: Option<std::thread::JoinHandle<()>>,
+ }
+
+ impl TestServer {
+ fn start(response: Vec<u8>) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("test listener binds");
+ listener.set_nonblocking(true).expect("listener is nonblocking");
+ let address = listener.local_addr().expect("listener has an address");
+ let origin = LoopbackOrigin::parse(&format!("http://{address}")).expect("test origin is loopback");
+ let contacted = Arc::new(AtomicBool::new(false));
+ let stop = Arc::new(AtomicBool::new(false));
+ let thread_contacted = contacted.clone();
+ let thread_stop = stop.clone();
+ let handle = std::thread::spawn(move || {
+ while !thread_stop.load(Ordering::SeqCst) {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ thread_contacted.store(true, Ordering::SeqCst);
+ stream.set_nonblocking(false).expect("test request stream is blocking");
+ stream
+ .set_read_timeout(Some(Duration::from_secs(1)))
+ .expect("test request reads are bounded");
+ let mut request = Vec::new();
+ while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {
+ let mut chunk = [0_u8; 1024];
+ let read = stream.read(&mut chunk).expect("test request reads");
+ assert!(read > 0, "test request contains complete headers");
+ request.extend_from_slice(&chunk[..read]);
+ assert!(request.len() <= 16 * 1024, "test request headers are bounded");
+ }
+ stream.write_all(&response).expect("test response writes");
+ break;
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ Err(error) => panic!("test listener failed: {error}"),
+ }
+ }
+ });
+ Self {
+ origin,
+ contacted,
+ stop,
+ handle: Some(handle),
+ }
+ }
+
+ fn finish(mut self) -> bool {
+ self.stop.store(true, Ordering::SeqCst);
+ if let Some(handle) = self.handle.take() {
+ handle.join().expect("test server exits");
+ }
+ self.contacted.load(Ordering::SeqCst)
+ }
+ }
+
+ fn response(status: &str, headers: &[(&str, String)], body: &[u8]) -> Vec<u8> {
+ let mut bytes = format!("HTTP/1.1 {status}\r\nConnection: close\r\n").into_bytes();
+ for (name, value) in headers {
+ bytes.extend_from_slice(format!("{name}: {value}\r\n").as_bytes());
+ }
+ bytes.extend_from_slice(b"\r\n");
+ bytes.extend_from_slice(body);
+ bytes
+ }
+
+ #[test]
+ fn test_server_waits_for_complete_request_headers() {
+ let expected_response = response("200 OK", &[], READY_BODY.as_bytes());
+ let server = TestServer::start(expected_response.clone());
+ let mut client =
+ TcpStream::connect(server.origin.as_str().trim_start_matches("http://")).expect("test client connects");
+ client
+ .set_read_timeout(Some(Duration::from_millis(50)))
+ .expect("test client reads are bounded");
+
+ for fragment in [b"".as_slice(), b"GET /ready HTTP/1.1\r\nHost: localhost\r\n".as_slice()] {
+ client.write_all(fragment).expect("test request fragment writes");
+ let mut pending_response = [0_u8; 1];
+ let error = client
+ .read(&mut pending_response)
+ .expect_err("test server waits until the headers are complete");
+ assert!(matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ));
+ }
+
+ client.write_all(b"\r\n").expect("test request headers complete");
+ client
+ .set_read_timeout(Some(Duration::from_secs(2)))
+ .expect("test response reads are bounded");
+ let mut actual_response = Vec::new();
+ client.read_to_end(&mut actual_response).expect("test response reads");
+ assert_eq!(actual_response, expected_response);
+ assert!(server.finish());
+ }
+
+ #[test]
+ fn test_server_rejects_truncated_request_headers() {
+ let mut server = TestServer::start(Vec::new());
+ let mut client =
+ TcpStream::connect(server.origin.as_str().trim_start_matches("http://")).expect("test client connects");
+ client
+ .write_all(b"GET /ready HTTP/1.1\r\n")
+ .expect("test request writes");
+ client.shutdown(Shutdown::Write).expect("test request ends");
+ let failure = server
+ .handle
+ .take()
+ .expect("test server has a thread")
+ .join()
+ .expect_err("truncated headers fail the test server");
+ assert_eq!(
+ failure.downcast_ref::<&str>(),
+ Some(&"test request contains complete headers")
+ );
+ }
+
+ #[test]
+ fn test_server_rejects_oversized_request_headers() {
+ let mut server = TestServer::start(Vec::new());
+ let mut client =
+ TcpStream::connect(server.origin.as_str().trim_start_matches("http://")).expect("test client connects");
+ client
+ .write_all(&vec![b'x'; 16 * 1024 + 1])
+ .expect("test request writes");
+ let failure = server
+ .handle
+ .take()
+ .expect("test server has a thread")
+ .join()
+ .expect_err("oversized headers fail the test server");
+ assert_eq!(
+ failure.downcast_ref::<&str>(),
+ Some(&"test request headers are bounded")
+ );
+ }
+
+ #[test]
+ fn accepts_the_exact_runtime_readiness_payload() {
+ assert!(is_avibe_readiness_body(
+ r#"{"schema_version":1,"product":"avibe","ready":true}"#
+ ));
+ assert_eq!(
+ parse_avibe_readiness_body(EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY),
+ Some(RuntimeReadiness {
+ desktop_runtime_id: None,
+ desktop_ui_runtime_id: Some("a".repeat(64)),
+ })
+ );
+ assert_eq!(
+ parse_avibe_readiness_body(&format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":true,"desktop_runtime_id":"{}"}}"#,
+ "a".repeat(64)
+ )),
+ Some(RuntimeReadiness {
+ desktop_runtime_id: Some("a".repeat(64)),
+ desktop_ui_runtime_id: None,
+ })
+ );
+ assert_eq!(
+ parse_avibe_readiness_body(&format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":"{}"}}"#,
+ "b".repeat(64)
+ )),
+ Some(RuntimeReadiness {
+ desktop_runtime_id: None,
+ desktop_ui_runtime_id: Some("b".repeat(64)),
+ })
+ );
+ }
+
+ #[test]
+ fn accepts_only_the_exact_runtime_identity_mismatch_payload() {
+ let runtime_id = "a".repeat(64);
+ assert_eq!(
+ parse_runtime_identity_mismatch_body(&format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{runtime_id}"}}"#
+ )),
+ Some(RuntimeReadiness {
+ desktop_runtime_id: Some(runtime_id),
+ desktop_ui_runtime_id: None,
+ })
+ );
+ assert_eq!(
+ parse_runtime_identity_mismatch_body(
+ r#"{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch"}"#
+ ),
+ None
+ );
+ for invalid in ["", "bad", &"A".repeat(64)] {
+ assert!(parse_runtime_identity_mismatch_body(&format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{invalid}"}}"#
+ )).is_none());
+ }
+ assert!(parse_runtime_identity_mismatch_body(
+ r#"{"schema_version":1,"product":"avibe","ready":false,"code":"controller_unavailable"}"#
+ )
+ .is_none());
+ }
+
+ #[test]
+ fn rejects_ui_only_starting_stale_and_unrelated_bodies() {
+ let bodies = [
+ "",
+ "ok",
+ "<html><body>hello</body></html>",
+ "{}",
+ r#"{"status":"ok"}"#,
+ r#"{"ready":true}"#,
+ r#"{"schema_version":1,"product":"other","ready":true}"#,
+ r#"{"schema_version":2,"product":"avibe","ready":true}"#,
+ r#"{"ready":false,"code":"controller_unavailable"}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"extra":1}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_runtime_id":"short"}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":"short"}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":null}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","extra":1}"#,
+ r#"{"schema_version":1,"product":"avibe","ready":true,"desktop_runtime_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","desktop_ui_runtime_id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}"#,
+ r#"{"ready":"true"}"#,
+ "[]",
+ ];
+ for body in bodies {
+ assert!(!is_avibe_readiness_body(body), "body {body:?} must not be adopted");
+ }
+ }
+
+ #[test]
+ fn probe_construction_does_not_need_a_server() {
+ HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+ }
+
+ #[tokio::test]
+ async fn the_probe_accepts_the_exact_body_from_its_loopback_listener() {
+ let server = TestServer::start(response(
+ "200 OK",
+ &[("Content-Length", READY_BODY.len().to_string())],
+ READY_BODY.as_bytes(),
+ ));
+ let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+
+ assert!(probe.is_healthy(&server.origin).await);
+ assert!(server.finish());
+ }
+
+ #[tokio::test]
+ async fn the_probe_recovers_identity_from_an_explicit_mismatch() {
+ let runtime_id = "a".repeat(64);
+ let body = format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{runtime_id}"}}"#
+ );
+ let server = TestServer::start(response(
+ "503 Service Unavailable",
+ &[("Content-Length", body.len().to_string())],
+ body.as_bytes(),
+ ));
+ let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+
+ assert_eq!(
+ probe.mismatched_runtime_identity(&server.origin).await,
+ Some(RuntimeReadiness {
+ desktop_runtime_id: Some(runtime_id),
+ desktop_ui_runtime_id: None,
+ })
+ );
+ assert!(server.finish());
+ }
+
+ #[tokio::test]
+ async fn the_probe_does_not_follow_redirects() {
+ let target = TestServer::start(response(
+ "200 OK",
+ &[("Content-Length", READY_BODY.len().to_string())],
+ READY_BODY.as_bytes(),
+ ));
+ let redirect = TestServer::start(response(
+ "302 Found",
+ &[("Location", format!("{}/ready", target.origin.as_str()))],
+ &[],
+ ));
+ let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+
+ assert!(!probe.is_healthy(&redirect.origin).await);
+ assert!(redirect.finish());
+ assert!(!target.finish(), "the redirected listener must never be contacted");
+ }
+
+ #[tokio::test]
+ async fn the_probe_rejects_an_oversized_streamed_body() {
+ let body = vec![b'x'; MAX_READINESS_BYTES + 1];
+ let server = TestServer::start(response("200 OK", &[], &body));
+ let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+
+ assert!(!probe.is_healthy(&server.origin).await);
+ assert!(server.finish());
+ }
+}
diff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rs
new file mode 100644
index 000000000..cc45487ea
--- /dev/null
+++ b/desktop/runtime-host/src/launcher.rs
@@ -0,0 +1,2199 @@
+//! Starting the installed Avibe Runtime.
+//!
+//! Two rules shape this module:
+//!
+//! 1. The Runtime outlives normal shell lifecycle. Launched processes are
+//! detached and reaped; only explicit replacement or uninstall asks the
+//! Runtime's own CLI to stop it gracefully.
+//! 2. No shell interpreter is involved. The executable is resolved to a real
+//! path and spawned directly, so no user-controlled string is ever parsed as
+//! a command line.
+
+use std::env;
+use std::ffi::{OsStr, OsString};
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::sync::{mpsc, Arc, OnceLock};
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+
+use crate::bootstrap_log::BootstrapLog;
+use crate::health::RuntimeReadiness;
+use crate::origin::LoopbackOrigin;
+use crate::private_runtime::{InstalledPrivateRuntime, PrivateRuntimeBundle, PrivateRuntimeError};
+use crate::status::BootstrapNoticeCode;
+/// Environment variable that points the shell at a specific `vibe` executable.
+///
+/// Desktop applications inherit a minimal `PATH` when launched from Finder or
+/// the Windows shell, which usually does not contain `~/.local/bin`; this is the
+/// documented escape hatch when the search below cannot find an install.
+pub const VIBE_PATH_ENV: &str = "AVIBE_DESKTOP_VIBE_PATH";
+
+/// uv's supported override for the directory containing tool executables.
+pub const UV_TOOL_BIN_DIR_ENV: &str = "UV_TOOL_BIN_DIR";
+
+/// Marks the spawned Runtime as started by the desktop shell.
+pub const DESKTOP_SHELL_ENV: &str = "AVIBE_DESKTOP_SHELL";
+
+/// Prevents the embedded Python environment from trying to update itself.
+pub const DESKTOP_MANAGED_RUNTIME_ENV: &str = "AVIBE_DESKTOP_MANAGED_RUNTIME";
+
+/// Identifies the app-private Runtime root to the Python process.
+pub const DESKTOP_RUNTIME_ROOT_ENV: &str = "AVIBE_DESKTOP_RUNTIME_ROOT";
+
+/// Identifies the bundled npm CLI that must be invoked through private Node.js.
+pub const DESKTOP_NPM_CLI_ENV: &str = "AVIBE_DESKTOP_NPM_CLI";
+
+/// Identifies the mutable root for app-private agent backends.
+pub const DESKTOP_BACKENDS_ROOT_ENV: &str = "AVIBE_DESKTOP_BACKENDS_ROOT";
+
+/// How the shell starts a Runtime.
+///
+/// `start` is idempotent: it brings up what is missing without stopping what is
+/// running. `--no-open-browser` is what keeps a desktop launch from *also*
+/// opening a system browser at the Workbench — plain `vibe start` honours
+/// `config.ui.open_browser` and would leave the user with two windows onto the
+/// same Runtime. The shell owns a WebView for exactly this purpose, so it always
+/// opts out.
+const START_ARGS: [&str; 2] = ["start", "--no-open-browser"];
+const STOP_ARGS: [&str; 1] = ["stop"];
+const ENDPOINT_ARGS: [&str; 3] = ["desktop", "endpoint", "--json"];
+/// How long the shell waits for the Runtime to name its own address.
+///
+/// Sized for a *cold* first launch, not a warm one. The bundle has just been
+/// extracted, so nothing in the runtime tree has been paged in or evaluated by
+/// the system yet, and the interpreter pays for all of it on this first call.
+/// Measured on an M-series Mac with the exact environment `RuntimeCommand::private`
+/// builds: 15.8s and 18.4s on two independent cold extractions, 20.0s for the
+/// x86_64 build under Rosetta, against 2.3-4.1s once the binaries are warm. A 10s
+/// budget was therefore sized for the second launch and cut off the first one,
+/// which reached the user as `runtime_discovery_failed` on every fresh install.
+///
+/// This is the last step on the cold path that still held a warm number --
+/// readiness already allows 120s (`DEFAULT_READY_TIMEOUT`). Staying under that
+/// keeps discovery from dominating the launch, while 3x the worst measurement
+/// leaves room for slower hardware. The budget is only spent in full when the
+/// endpoint is genuinely broken, and that failure is already retryable.
+const ENDPOINT_TIMEOUT: Duration = Duration::from_secs(60);
+
+/// How much of the endpoint helper's stderr the bootstrap log keeps.
+const MAX_ENDPOINT_STDERR_BYTES: usize = 4 * 1024;
+
+/// How long the stderr reader is given to reach EOF once the query is over.
+///
+/// A grandchild that inherited the pipe can hold it open after the child is
+/// gone, and a diagnostic is worth waiting a moment for and nothing more.
+const ENDPOINT_STDERR_DRAIN: Duration = Duration::from_secs(2);
+const MAX_ENDPOINT_BYTES: u64 = 4096;
+const START_RECEIPT_PREFIX: &[u8] = b"@avibe-start-receipt:";
+const MAX_START_OUTPUT_BYTES: usize = 65_536;
+const START_OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(1);
+#[cfg(windows)]
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+
+#[derive(Debug, thiserror::Error)]
+pub enum LaunchError {
+ #[error("installed Avibe Runtime not found")]
+ ExecutableNotFound,
+ #[error("failed to prepare the app-private Avibe Runtime")]
+ RuntimeInstall,
+ #[error("failed to remove the app-private Avibe Runtime")]
+ RuntimeRemoval,
+ #[error("failed to execute the Avibe desktop endpoint command")]
+ EndpointSpawn(#[source] std::io::Error),
+ #[error("Avibe desktop endpoint command timed out")]
+ EndpointTimeout,
+ #[error("Avibe desktop endpoint command failed")]
+ EndpointExit,
+ #[error("Avibe desktop endpoint descriptor is invalid")]
+ EndpointOutput,
+ #[error("Avibe desktop endpoint origin is invalid")]
+ InvalidOrigin,
+ #[error("failed to start the installed Avibe Runtime")]
+ Spawn(#[source] std::io::Error),
+ #[error("failed to stop the superseded desktop-managed Runtime")]
+ Handover,
+ #[error("the Runtime was not launched by this host")]
+ NotOwned,
+ #[error("failed to stop the shell-started Runtime")]
+ RuntimeStop,
+ #[error("the Runtime ownership receipt no longer matches the service")]
+ OwnershipLost,
+}
+
+/// What the shell proved about a Runtime before removing app-private files.
+///
+/// Removal fails closed when an adopted origin stops answering: deleting its
+/// executable tree would strand a still-running Controller or UI process.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RuntimeRemovalState {
+ Inactive,
+ Managed,
+ External,
+ Unknown,
+}
+
+impl LaunchError {
+ /// Machine/install failures may be retried; an invalid origin must be fixed
+ /// before the shell is allowed to contact it.
+ pub fn is_retryable(&self) -> bool {
+ !matches!(self, Self::InvalidOrigin)
+ }
+
+ /// Stable localized notice code; raw errors never cross into the WebView.
+ pub fn notice_code(&self) -> BootstrapNoticeCode {
+ match self {
+ Self::ExecutableNotFound => BootstrapNoticeCode::RuntimeNotFound,
+ Self::RuntimeInstall | Self::RuntimeRemoval => BootstrapNoticeCode::RuntimeInstallFailed,
+ Self::EndpointSpawn(_) | Self::EndpointTimeout | Self::EndpointExit | Self::EndpointOutput => {
+ BootstrapNoticeCode::RuntimeDiscoveryFailed
+ }
+ Self::InvalidOrigin => BootstrapNoticeCode::InvalidOrigin,
+ Self::OwnershipLost => BootstrapNoticeCode::RuntimeOwnershipLost,
+ Self::Spawn(_) | Self::Handover | Self::NotOwned | Self::RuntimeStop => {
+ BootstrapNoticeCode::RuntimeSpawnFailed
+ }
+ }
+ }
+}
+
+/// Resolves one installed Avibe Runtime for a single bootstrap attempt.
+///
+/// Resolution is deliberately attempt-scoped. A retry after installation or
+/// repair must observe the current filesystem instead of a shell-lifetime cache.
+pub trait RuntimeLauncher: Send + Sync {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError>;
+
+ /// Gracefully stops and removes an app-private Runtime, if this launcher owns
+ /// one. Installed/user-managed launchers deliberately do nothing.
+ fn remove_private_runtime(&self, _state: RuntimeRemovalState) -> Result<bool, LaunchError> {
+ Ok(false)
+ }
+}
+
+/// One executable frozen for a single bootstrap attempt.
+///
+/// Both methods use this exact executable. `launch` returns as soon as it is
+/// spawned; readiness is decided by the readiness probe.
+pub trait ResolvedRuntimeLauncher: Send + Sync {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError>;
+ fn launch(&self) -> Result<LaunchedRuntime, LaunchError>;
+
+ fn stop(&self, _receipt: &StartupReceipt) -> Result<(), LaunchError> {
+ Err(LaunchError::RuntimeStop)
+ }
+
+ fn expected_runtime_id(&self) -> Option<&str> {
+ None
+ }
+
+ fn requires_handover(&self, readiness: &RuntimeReadiness) -> bool {
+ matches!(
+ (self.expected_runtime_id(), readiness.desktop_runtime_id.as_deref()),
+ (Some(expected), Some(actual)) if expected != actual
+ )
+ }
+
+ fn handover(&self) -> Result<(), LaunchError> {
+ Ok(())
+ }
+
+ fn prune_superseded(&self) {}
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
+#[serde(deny_unknown_fields)]
+pub struct StartupReceipt {
+ schema_version: u32,
+ outcome: StartupOutcome,
+ service_pid: u32,
+ ui_pid: u32,
+ service_create_unix_ms: f64,
+ ui_create_unix_ms: f64,
+}
+
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+enum StartupOutcome {
+ Started,
+ Reused,
+}
+
+impl StartupReceipt {
+ pub(crate) fn from_json(bytes: &[u8]) -> Option<Self> {
+ let receipt: Self = serde_json::from_slice(bytes).ok()?;
+ (receipt.schema_version == 1
+ && receipt.service_pid > 0
+ && receipt.ui_pid > 0
+ && receipt.service_create_unix_ms.is_finite()
+ && receipt.service_create_unix_ms > 0.0
+ && receipt.ui_create_unix_ms.is_finite()
+ && receipt.ui_create_unix_ms > 0.0)
+ .then_some(receipt)
+ }
+}
+
+#[derive(Debug)]
+struct LaunchOutcome {
+ succeeded: bool,
+ receipt: Option<StartupReceipt>,
+}
+
+/// Whether the launcher process itself survived long enough to do its job.
+///
+/// `vibe start` is short-lived by design: it brings the Runtime up and exits, so
+/// the shell cannot treat "it is gone" as failure. Its exit code distinguishes
+/// startup failure from completion; only the receipt proves stop authority.
+/// Empty means "still running, or not observable" and grants no authority.
+#[derive(Debug, Clone, Default)]
+pub struct LaunchWatch(Arc<OnceLock<LaunchOutcome>>);
+
+impl LaunchWatch {
+ /// A watch that has already seen the launcher exit. For launchers that learn
+ /// the outcome synchronously, and for tests.
+ pub fn exited(succeeded: bool) -> Self {
+ let watch = Self::default();
+ watch.record(succeeded, None);
+ watch
+ }
+
+ pub fn exited_with_receipt(succeeded: bool, receipt: StartupReceipt) -> Self {
+ let watch = Self::default();
+ watch.record(succeeded, Some(receipt));
+ watch
+ }
+
+ /// True only once the launcher has been *seen* to exit non-zero.
+ pub fn failed(&self) -> bool {
+ self.0.get().is_some_and(|outcome| !outcome.succeeded)
+ }
+
+ /// True only once the launcher has been *seen* to exit successfully.
+ pub fn succeeded(&self) -> bool {
+ self.0.get().is_some_and(|outcome| outcome.succeeded)
+ }
+
+ pub(crate) fn owned_receipt(&self) -> Option<&StartupReceipt> {
+ let outcome = self.0.get().filter(|outcome| outcome.succeeded)?;
+ outcome
+ .receipt
+ .as_ref()
+ .filter(|receipt| receipt.outcome == StartupOutcome::Started)
+ }
+
+ fn record(&self, succeeded: bool, receipt: Option<StartupReceipt>) {
+ let _ = self.0.set(LaunchOutcome { succeeded, receipt });
+ }
+}
+
+/// A Runtime the shell started. Held for diagnostics only — never for control.
+#[derive(Debug, Clone, Default)]
+pub struct LaunchedRuntime {
+ pub pid: u32,
+ /// Observes the launcher, not the Runtime: the Runtime's own daemons are
+ /// grandchildren and are unaffected by anything reported here.
+ pub watch: LaunchWatch,
+}
+
+/// Launches the `vibe` executable that is already installed on this machine.
+#[derive(Debug, Default)]
+pub struct InstalledVibeLauncher {
+ candidates: Vec<PathBuf>,
+}
+
+impl InstalledVibeLauncher {
+ /// Builds the search list from the current process environment.
+ pub fn from_env() -> Self {
+ Self {
+ candidates: vibe_executable_candidates(
+ env::var_os(VIBE_PATH_ENV).as_deref(),
+ env::var_os("PATH").as_deref(),
+ env::var_os(UV_TOOL_BIN_DIR_ENV).as_deref(),
+ home_dir().as_deref(),
+ env::var_os("APPDATA").as_deref().map(Path::new),
+ ),
+ }
+ }
+
+ /// The ordered locations this launcher will try.
+ pub fn candidates(&self) -> &[PathBuf] {
+ &self.candidates
+ }
+
+ fn resolve_executable(&self) -> Result<PathBuf, LaunchError> {
+ self.candidates
+ .iter()
+ .find(|candidate| is_executable_file(candidate))
+ .cloned()
+ .ok_or(LaunchError::ExecutableNotFound)
+ }
+}
+
+impl RuntimeLauncher for InstalledVibeLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(ResolvedVibeExecutable {
+ command: RuntimeCommand::installed(self.resolve_executable()?),
+ expected_runtime_id: None,
+ cleanup: None,
+ // A development shell drives an install it does not own and has no
+ // application data directory to write diagnostics into.
+ log: BootstrapLog::disabled(),
+ }))
+ }
+}
+
+/// Installs and launches the Runtime embedded in a product desktop package.
+#[derive(Debug, Clone)]
+pub struct BundledVibeLauncher {
+ bundle: PrivateRuntimeBundle,
+ backend_root: PathBuf,
+ log: BootstrapLog,
+}
+
+impl BundledVibeLauncher {
+ pub fn new(bundle_dir: PathBuf, install_root: PathBuf, backend_root: PathBuf, log: BootstrapLog) -> Self {
+ Self {
+ bundle: PrivateRuntimeBundle::new(bundle_dir, install_root),
+ backend_root,
+ log,
+ }
+ }
+}
+
+impl RuntimeLauncher for BundledVibeLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ let started = Instant::now();
+ let prepared = self.bundle.prepare();
+ record_runtime_prepare(&self.log, &prepared, started.elapsed());
+ let runtime = prepared.map_err(|_| LaunchError::RuntimeInstall)?;
+ let runtime_id = runtime.runtime_id.clone();
+ Ok(Arc::new(ResolvedVibeExecutable {
+ command: RuntimeCommand::private(
+ runtime.root.clone(),
+ runtime.python,
+ runtime.node,
+ runtime.npm_cli,
+ self.backend_root.clone(),
+ &runtime_id,
+ env::var_os("PATH").as_deref(),
+ ),
+ expected_runtime_id: Some(runtime_id),
+ cleanup: Some((self.bundle.clone(), runtime.root)),
+ log: self.log.clone(),
+ }))
+ }
+
+ fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
+ if state == RuntimeRemovalState::Unknown {
+ return Err(LaunchError::RuntimeRemoval);
+ }
+ validate_private_directory_root(&self.backend_root)?;
+ if state == RuntimeRemovalState::Managed {
+ let runtime = self.bundle.prepare().map_err(|_| LaunchError::RuntimeInstall)?;
+ let command = RuntimeCommand::private(
+ runtime.root,
+ runtime.python,
+ runtime.node,
+ runtime.npm_cli,
+ self.backend_root.clone(),
+ &runtime.runtime_id,
+ env::var_os("PATH").as_deref(),
+ );
+ run_handover(&command)?;
+ }
+ self.bundle.remove_all().map_err(|_| LaunchError::RuntimeRemoval)?;
+ remove_private_directory_root(&self.backend_root)?;
+ Ok(true)
+ }
+}
+
+fn validate_private_directory_root(path: &Path) -> Result<bool, LaunchError> {
+ let metadata = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(_) => return Err(LaunchError::RuntimeRemoval),
+ };
+ if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() {
+ Ok(true)
+ } else {
+ Err(LaunchError::RuntimeRemoval)
+ }
+}
+
+fn remove_private_directory_root(path: &Path) -> Result<(), LaunchError> {
+ if validate_private_directory_root(path)? {
+ std::fs::remove_dir_all(path).map_err(|_| LaunchError::RuntimeRemoval)?;
+ }
+ Ok(())
+}
+
+#[derive(Debug)]
+struct ResolvedVibeExecutable {
+ command: RuntimeCommand,
+ expected_runtime_id: Option<String>,
+ cleanup: Option<(PrivateRuntimeBundle, PathBuf)>,
+ log: BootstrapLog,
+}
+
+impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ query_endpoint(&self.command, &self.log)
+ }
+
+ fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ let mut child = spawn_detached(&self.command).map_err(LaunchError::Spawn)?;
+ let pid = child.id();
+ let watch = LaunchWatch::default();
+ let stdout = child.stdout.take().expect("startup stdout is piped");
+ let (sender, receiver) = mpsc::sync_channel(1);
+ std::thread::spawn(move || {
+ let receipt = read_startup_receipt(stdout);
+ let _ = sender.send(receipt);
+ });
+
+ // Reap the launcher process so it cannot linger as a zombie. `vibe start`
+ // returns once the Runtime daemons are up; those daemons are grandchildren
+ // and are entirely unaffected by this wait. `std::process::Child` never
+ // kills on drop, so the Runtime survives the shell exiting.
+ //
+ // The wait was already happening; recording its verdict costs nothing and
+ // is the only place the shell can learn that the launcher died.
+ let reaped = watch.clone();
+ std::thread::spawn(move || {
+ let mut child = child;
+ if let Ok(status) = child.wait() {
+ let receipt = receiver.recv_timeout(START_OUTPUT_DRAIN_TIMEOUT).ok().flatten();
+ reaped.record(status.success(), receipt);
+ }
+ });
+
+ Ok(LaunchedRuntime { pid, watch })
+ }
+
+ fn expected_runtime_id(&self) -> Option<&str> {
+ self.expected_runtime_id.as_deref()
+ }
+
+ fn handover(&self) -> Result<(), LaunchError> {
+ run_handover(&self.command)
+ }
+
+ fn stop(&self, receipt: &StartupReceipt) -> Result<(), LaunchError> {
+ let status = scoped_stop_command(&self.command, receipt)?
+ .spawn()
+ .and_then(|mut child| child.wait())
+ .map_err(|_| LaunchError::RuntimeStop)?;
+ match status.code() {
+ Some(0) => Ok(()),
+ Some(3) => Err(LaunchError::OwnershipLost),
+ _ => Err(LaunchError::RuntimeStop),
+ }
+ }
+
+ fn prune_superseded(&self) {
+ if let Some((bundle, active_root)) = &self.cleanup {
+ let _ = bundle.prune_superseded(active_root);
+ }
+ }
+}
+
+#[derive(Debug)]
+struct RuntimeCommand {
+ executable: PathBuf,
+ prefix_args: Vec<OsString>,
+ environment: Vec<(OsString, OsString)>,
+ /// Whether the shell's own `PYTHON*` variables are withheld from the child.
+ ///
+ /// Only the private Runtime sets this. `-I` protects just the interpreter
+ /// that receives the flag: `os.environ` still carries the inherited values,
+ /// and the Controller and UI interpreters that Runtime starts copy it and
+ /// run without `-I`. An inherited `PYTHONHOME` then aborts both before they
+ /// are ready, and a `PYTHONPATH` imports code from outside the verified
+ /// tree. A development shell drives an install it does not own, which runs
+ /// with the user's environment exactly as their terminal would.
+ withholds_inherited_python: bool,
+}
+
+impl RuntimeCommand {
+ fn installed(executable: PathBuf) -> Self {
+ Self {
+ executable,
+ prefix_args: Vec::new(),
+ environment: Vec::new(),
+ withholds_inherited_python: false,
+ }
+ }
+
+ fn private(
+ runtime_root: PathBuf,
+ python: PathBuf,
+ node: PathBuf,
+ npm_cli: PathBuf,
+ backends_root: PathBuf,
+ runtime_id: &str,
+ inherited_path: Option<&OsStr>,
+ ) -> Self {
+ let tools_dir = node.parent().expect("validated private Node has a parent");
+ let mut path_entries = vec![tools_dir.to_owned()];
+ if let Some(path) = inherited_path {
+ path_entries.extend(env::split_paths(path).filter(|entry| !entry.as_os_str().is_empty()));
+ }
+ let private_path = env::join_paths(path_entries).unwrap_or_else(|_| tools_dir.as_os_str().to_owned());
+ Self {
+ executable: python,
+ // Isolated mode excludes the user site and PYTHONPATH. The Avibe
+ // wheel lives in this interpreter's own site-packages.
+ //
+ // `-B` is not redundant with the PYTHONDONTWRITEBYTECODE below, and
+ // removing it reintroduces a bug that cost two days: `-I` implies
+ // `-E`, so this interpreter ignores every PYTHON* variable — including
+ // that one. Without the flag the Runtime writes `.pyc` files into its
+ // own install tree, `verify_installed_tree` then finds a tree the
+ // manifest no longer describes, and `prepare()` re-extracts 358MB on
+ // every single launch until both install slots are invalid.
+ prefix_args: vec![
+ OsString::from("-I"),
+ OsString::from("-B"),
+ OsString::from("-m"),
+ OsString::from("vibe"),
+ ],
+ environment: vec![
+ (OsString::from("PATH"), private_path),
+ (OsString::from("VIBE_SHOW_RUNTIME_NODE_BIN"), node.into_os_string()),
+ (OsString::from(DESKTOP_NPM_CLI_ENV), npm_cli.into_os_string()),
+ (
+ OsString::from(DESKTOP_BACKENDS_ROOT_ENV),
+ backends_root.into_os_string(),
+ ),
+ (OsString::from(DESKTOP_MANAGED_RUNTIME_ENV), OsString::from("1")),
+ (OsString::from(DESKTOP_RUNTIME_ROOT_ENV), runtime_root.into_os_string()),
+ (OsString::from("AVIBE_DESKTOP_RUNTIME_ID"), OsString::from(runtime_id)),
+ // For descendants: child interpreters the Runtime starts do not
+ // all run under `-I`, and those do honour this. The `-B` above is
+ // what covers this process itself.
+ (OsString::from("PYTHONDONTWRITEBYTECODE"), OsString::from("1")),
+ ],
+ withholds_inherited_python: true,
+ }
+ }
+
+ fn apply(&self, command: &mut Command) {
+ command.args(&self.prefix_args);
+ self.apply_environment(command, env::vars_os());
+ }
+
+ /// The environment half of `apply`, over an explicit inherited set.
+ ///
+ /// Production passes this process's own environment. A test passes one it
+ /// built, so that it never has to mutate a variable every other test thread
+ /// reads while it spawns.
+ fn apply_environment(&self, command: &mut Command, inherited: impl IntoIterator<Item = (OsString, OsString)>) {
+ if self.withholds_inherited_python {
+ for (name, _) in inherited {
+ if is_python_startup_variable(&name) {
+ command.env_remove(name);
+ }
+ }
+ }
+ // After the removal, so the one Python variable the Runtime does want
+ // is ours rather than whatever the shell was started with.
+ for (name, value) in &self.environment {
+ command.env(name, value);
+ }
+ }
+}
+
+/// Every variable CPython reads at startup is named `PYTHON*`. Windows looks
+/// environment names up without regard to case, so `PythonPath` counts there.
+fn is_python_startup_variable(name: &OsStr) -> bool {
+ let name = name.to_string_lossy();
+ if cfg!(windows) {
+ name.to_ascii_uppercase().starts_with("PYTHON")
+ } else {
+ name.starts_with("PYTHON")
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct EndpointDescriptor {
+ schema_version: u32,
+ origin: String,
+}
+
+/// One run of the endpoint helper, including everything a `LaunchError` cannot
+/// carry: how long it took, what it printed on stderr, and the exit status it
+/// actually had rather than the fact that it was not zero.
+struct EndpointAttempt {
+ result: Result<LoopbackOrigin, LaunchError>,
+ status: Option<std::process::ExitStatus>,
+ stderr: Option<Vec<u8>>,
+ elapsed: Duration,
+}
+
+fn query_endpoint(runtime: &RuntimeCommand, log: &BootstrapLog) -> Result<LoopbackOrigin, LaunchError> {
+ query_endpoint_within(runtime, log, ENDPOINT_TIMEOUT)
+}
+
+/// The timeout is a parameter so a test can drive the kill path in milliseconds
+/// instead of a minute. Production has exactly one caller and it passes
+/// `ENDPOINT_TIMEOUT`.
+fn query_endpoint_within(
+ runtime: &RuntimeCommand,
+ log: &BootstrapLog,
+ timeout: Duration,
+) -> Result<LoopbackOrigin, LaunchError> {
+ let started = Instant::now();
+ let mut status = None;
+ let mut stderr_reader = None;
+ let result = endpoint_descriptor(runtime, timeout, &mut status, &mut stderr_reader);
+ // Collected after the query returns, so a timeout that had to kill the child
+ // still reports what that child said before it was killed.
+ let stderr = stderr_reader.and_then(|reader| reader.recv_timeout(ENDPOINT_STDERR_DRAIN).ok());
+ let attempt = EndpointAttempt {
+ result,
+ status,
+ stderr,
+ elapsed: started.elapsed(),
+ };
+ record_endpoint_attempt(log, &attempt);
+ attempt.result
+}
+
+fn endpoint_descriptor(
+ runtime: &RuntimeCommand,
+ timeout: Duration,
+ status_slot: &mut Option<std::process::ExitStatus>,
+ stderr_slot: &mut Option<mpsc::Receiver<Vec<u8>>>,
+) -> Result<LoopbackOrigin, LaunchError> {
+ let mut command = Command::new(&runtime.executable);
+ runtime.apply(&mut command);
+ command
+ .args(ENDPOINT_ARGS)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ // Discarding this is what left us with a notice code and nothing else
+ // when discovery failed on a machine we could not reach.
+ .stderr(Stdio::piped())
+ .env(DESKTOP_SHELL_ENV, "1");
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ // The endpoint helper is a short-lived console executable. A GUI parent
+ // does not suppress its console automatically, so keep discovery silent.
+ command.creation_flags(CREATE_NO_WINDOW);
+ }
+ let mut child = command.spawn().map_err(LaunchError::EndpointSpawn)?;
+ if let Some(stderr) = child.stderr.take() {
+ *stderr_slot = Some(spawn_stderr_tail(stderr));
+ }
+ let stdout = child.stdout.take().ok_or(LaunchError::EndpointOutput)?;
+ let (sender, receiver) = mpsc::sync_channel(1);
+ std::thread::spawn(move || {
+ let mut bytes = Vec::new();
+ let result = stdout
+ .take(MAX_ENDPOINT_BYTES + 1)
+ .read_to_end(&mut bytes)
+ .map(|_| bytes);
+ let _ = sender.send(result);
+ });
+
+ let deadline = Instant::now() + timeout;
+ let status = loop {
+ match child.try_wait() {
+ Ok(Some(status)) => break status,
+ Ok(None) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ Ok(None) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(LaunchError::EndpointTimeout);
+ }
+ Err(error) => return Err(LaunchError::EndpointSpawn(error)),
+ }
+ };
+ *status_slot = Some(status);
+ if !status.success() {
+ return Err(LaunchError::EndpointExit);
+ }
+
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let bytes = receiver
+ .recv_timeout(remaining)
+ .map_err(|_| LaunchError::EndpointTimeout)?
+ .map_err(|_| LaunchError::EndpointOutput)?;
+ parse_endpoint_descriptor(&bytes)
+}
+
+/// Drains the child's stderr on its own thread, keeping only the tail.
+///
+/// The pipe must be read while the child is running. A child that fills it and
+/// is never drained blocks on writing its own diagnostics, which would make
+/// this log the cause of the timeout it exists to explain. Keeping the tail
+/// rather than the head is deliberate: a Python traceback puts the cause last.
+fn spawn_stderr_tail(mut stderr: std::process::ChildStderr) -> mpsc::Receiver<Vec<u8>> {
+ let (sender, receiver) = mpsc::channel();
+ std::thread::spawn(move || {
+ let mut tail: Vec<u8> = Vec::new();
+ let mut chunk = [0_u8; 4096];
+ loop {
+ match stderr.read(&mut chunk) {
+ Ok(0) | Err(_) => break,
+ Ok(read) => {
+ tail.extend_from_slice(&chunk[..read]);
+ if tail.len() > MAX_ENDPOINT_STDERR_BYTES {
+ tail.drain(..tail.len() - MAX_ENDPOINT_STDERR_BYTES);
+ }
+ }
+ }
+ }
+ let _ = sender.send(tail);
+ });
+ receiver
+}
+
+/// The one place a failed discovery becomes something a person can read.
+fn record_endpoint_attempt(log: &BootstrapLog, attempt: &EndpointAttempt) {
+ let mut fields = vec![
+ ("outcome", endpoint_outcome(&attempt.result).to_owned()),
+ ("ms", attempt.elapsed.as_millis().to_string()),
+ ];
+ if let Some(status) = attempt.status {
+ fields.push((
+ "exit",
+ match status.code() {
+ Some(code) => code.to_string(),
+ // A signalled child has no code, and on Unix the signal is the
+ // whole story.
+ None => status.to_string(),
+ },
+ ));
+ }
+ if let Err(LaunchError::EndpointSpawn(error)) = &attempt.result {
+ fields.push(("error", error.to_string()));
+ }
+ if let Some(stderr) = attempt.stderr.as_ref().filter(|bytes| !bytes.is_empty()) {
+ fields.push(("stderr", String::from_utf8_lossy(stderr).into_owned()));
+ }
+ log.record("endpoint.query", &fields);
+}
+
+fn endpoint_outcome(result: &Result<LoopbackOrigin, LaunchError>) -> &'static str {
+ match result {
+ Ok(_) => "ok",
+ Err(LaunchError::EndpointSpawn(_)) => "spawn_failed",
+ Err(LaunchError::EndpointTimeout) => "timeout",
+ Err(LaunchError::EndpointExit) => "exit_failed",
+ Err(LaunchError::EndpointOutput) => "unreadable_output",
+ Err(LaunchError::InvalidOrigin) => "invalid_origin",
+ Err(_) => "failed",
+ }
+}
+
+/// Records what `prepare()` did, which is the fact that separates a slow first
+/// launch from an install that silently re-extracts on every launch.
+fn record_runtime_prepare(
+ log: &BootstrapLog,
+ prepared: &Result<InstalledPrivateRuntime, PrivateRuntimeError>,
+ elapsed: Duration,
+) {
+ let (outcome, detail) = match prepared {
+ Ok(runtime) => (
+ if runtime.reused { "reused" } else { "extracted" },
+ ("root", runtime.root.display().to_string()),
+ ),
+ // The variant, with its inner I/O error: "could not be installed" alone
+ // does not distinguish a full disk from a permission denial.
+ Err(error) => ("failed", ("error", format!("{error:?}"))),
+ };
+ log.record(
+ "runtime.prepare",
+ &[
+ ("outcome", outcome.to_owned()),
+ ("ms", elapsed.as_millis().to_string()),
+ detail,
+ ],
+ );
+}
+
+fn parse_endpoint_descriptor(bytes: &[u8]) -> Result<LoopbackOrigin, LaunchError> {
+ if bytes.len() > MAX_ENDPOINT_BYTES as usize {
+ return Err(LaunchError::EndpointOutput);
+ }
+ let descriptor: EndpointDescriptor = serde_json::from_slice(bytes).map_err(|_| LaunchError::EndpointOutput)?;
+ if descriptor.schema_version != 1 {
+ return Err(LaunchError::EndpointOutput);
+ }
+ LoopbackOrigin::parse(&descriptor.origin).map_err(|_| LaunchError::InvalidOrigin)
+}
+
+/// Every location the shell is willing to look for an installed `vibe`, in order.
+///
+/// Kept pure and separate from the filesystem so the ordering is testable.
+/// The well-known directories mirror where `install.sh` and `install.ps1` place
+/// the executable.
+pub fn vibe_executable_candidates(
+ override_path: Option<&std::ffi::OsStr>,
+ path_var: Option<&std::ffi::OsStr>,
+ uv_tool_bin_dir: Option<&std::ffi::OsStr>,
+ home: Option<&Path>,
+ app_data: Option<&Path>,
+) -> Vec<PathBuf> {
+ let executable_name = OsString::from(format!("vibe{}", env::consts::EXE_SUFFIX));
+ let mut candidates: Vec<PathBuf> = Vec::new();
+
+ let mut push = |candidate: PathBuf| {
+ if !candidates.contains(&candidate) {
+ candidates.push(candidate);
+ }
+ };
+
+ // 1. An explicit override wins outright.
+ if let Some(raw) = override_path {
+ if !raw.is_empty() {
+ push(PathBuf::from(raw));
+ }
+ }
+
+ // 2. Whatever the inherited PATH can offer.
+ if let Some(raw) = path_var {
+ for directory in env::split_paths(raw) {
+ if directory.as_os_str().is_empty() {
+ continue;
+ }
+ push(directory.join(&executable_name));
+ }
+ }
+
+ // 3. uv's supported custom tool-bin location.
+ if let Some(raw) = uv_tool_bin_dir {
+ if !raw.is_empty() {
+ push(PathBuf::from(raw).join(&executable_name));
+ }
+ }
+
+ // 4. Install locations a GUI process usually cannot see through PATH.
+ for directory in well_known_bin_dirs(home, app_data) {
+ push(directory.join(&executable_name));
+ }
+
+ candidates
+}
+
+fn well_known_bin_dirs(home: Option<&Path>, app_data: Option<&Path>) -> Vec<PathBuf> {
+ let mut directories: Vec<PathBuf> = Vec::new();
+ if let Some(home) = home {
+ directories.push(home.join(".local").join("bin"));
+ if !cfg!(windows) {
+ directories.push(home.join("bin"));
+ directories.push(home.join(".cargo").join("bin"));
+ }
+ }
+ if !cfg!(windows) {
+ directories.push(PathBuf::from("/opt/homebrew/bin"));
+ directories.push(PathBuf::from("/usr/local/bin"));
+ } else if let Some(app_data) = app_data {
+ directories.push(app_data.join("Python").join("Scripts"));
+ }
+ directories
+}
+
+fn home_dir() -> Option<PathBuf> {
+ let key = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
+ env::var_os(key)
+ .map(PathBuf::from)
+ .filter(|path| !path.as_os_str().is_empty())
+}
+
+fn is_executable_file(path: &Path) -> bool {
+ let Ok(metadata) = std::fs::metadata(path) else {
+ return false;
+ };
+ metadata.is_file() && is_executable(&metadata)
+}
+
+#[cfg(unix)]
+fn is_executable(metadata: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::PermissionsExt;
+ metadata.permissions().mode() & 0o111 != 0
+}
+
+/// Windows derives executability from the extension, which every candidate
+/// already carries through `EXE_SUFFIX`.
+#[cfg(not(unix))]
+fn is_executable(_metadata: &std::fs::Metadata) -> bool {
+ true
+}
+
+fn spawn_detached(runtime: &RuntimeCommand) -> std::io::Result<std::process::Child> {
+ lifecycle_command(runtime, &START_ARGS).stdout(Stdio::piped()).spawn()
+}
+
+fn read_startup_receipt(mut stdout: impl Read) -> Option<StartupReceipt> {
+ let mut bytes = Vec::new();
+ let mut chunk = [0; 4096];
+ let mut oversized = false;
+ loop {
+ let count = stdout.read(&mut chunk).ok()?;
+ if count == 0 {
+ break;
+ }
+ if !oversized && bytes.len() + count <= MAX_START_OUTPUT_BYTES {
+ bytes.extend_from_slice(&chunk[..count]);
+ } else {
+ oversized = true;
+ bytes.clear();
+ }
+ }
+ if oversized {
+ return None;
+ }
+ let mut receipts = bytes
+ .split(|byte| *byte == b'\n')
+ .filter_map(|line| line.strip_prefix(START_RECEIPT_PREFIX));
+ let receipt = StartupReceipt::from_json(receipts.next()?)?;
+ receipts.next().is_none().then_some(receipt)
+}
+
+fn scoped_stop_command(runtime: &RuntimeCommand, receipt: &StartupReceipt) -> Result<Command, LaunchError> {
+ if receipt.outcome != StartupOutcome::Started {
+ return Err(LaunchError::NotOwned);
+ }
+ let json = serde_json::to_string(receipt).map_err(|_| LaunchError::RuntimeStop)?;
+ Ok(lifecycle_command(runtime, &["stop", "--receipt", &json]))
+}
+
+fn lifecycle_command(runtime: &RuntimeCommand, args: &[&str]) -> Command {
+ let mut command = Command::new(&runtime.executable);
+ runtime.apply(&mut command);
+ command
+ .args(args)
+ // Nothing the Runtime prints may reach the shell, and therefore the WebView.
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .env(DESKTOP_SHELL_ENV, "1");
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ // Its own process group: closing the shell, or a terminal signal sent to
+ // the shell's group, must not reach the Runtime.
+ command.process_group(0);
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ const DETACHED_PROCESS: u32 = 0x0000_0008;
+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
+ command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
+ }
+
+ command
+}
+
+fn run_handover(runtime: &RuntimeCommand) -> Result<(), LaunchError> {
+ // `vibe stop` owns the component-specific graceful and forced-stop budgets.
+ // A shorter outer deadline would kill this coordinator while its children
+ // are still shutting down and then start a successor against live services.
+ let status = lifecycle_command(runtime, &STOP_ARGS)
+ .spawn()
+ .and_then(|mut child| child.wait())
+ .map_err(|_| LaunchError::Handover)?;
+ if status.success() {
+ Ok(())
+ } else {
+ Err(LaunchError::Handover)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::ffi::OsStr;
+
+ fn receipt(outcome: &str) -> StartupReceipt {
+ StartupReceipt::from_json(
+ format!(
+ r#"{{"schema_version":1,"outcome":"{outcome}","service_pid":1234,"ui_pid":5678,"service_create_unix_ms":1789010100123.5,"ui_create_unix_ms":1789010100456.5}}"#
+ ).as_bytes(),
+ ).expect("valid fixture")
+ }
+
+ #[test]
+ fn startup_receipts_are_extracted_from_one_exact_prefixed_line_only() {
+ for outcome in ["started", "reused"] {
+ let expected = receipt(outcome);
+ let json = serde_json::to_string(&expected).expect("fixture JSON");
+ let output = format!("Starting 服务…\r\n@avibe-start-receipt:{json}\r\nReady\n");
+ assert_eq!(read_startup_receipt(output.as_bytes()), Some(expected));
+ for output in [
+ format!("{json}\n"),
+ format!("prefix @avibe-start-receipt:{json}\n"),
+ format!("@avibe-start-receipt:{json}\n@avibe-start-receipt:{json}\n"),
+ format!("@avibe-start-receipt:{json}\n@avibe-start-receipt:broken\n"),
+ ] {
+ assert!(read_startup_receipt(output.as_bytes()).is_none());
+ }
+ }
+ assert!(read_startup_receipt(b"legacy successful startup\n".as_slice()).is_none());
+ }
+
+ #[test]
+ fn startup_receipt_validation_fails_closed_for_every_required_field() {
+ let valid = serde_json::to_value(receipt("started")).expect("fixture JSON");
+ for field in valid.as_object().expect("receipt object").keys() {
+ let mut missing = valid.clone();
+ missing.as_object_mut().expect("receipt object").remove(field);
+ assert!(
+ StartupReceipt::from_json(&serde_json::to_vec(&missing).unwrap()).is_none(),
+ "{field}"
+ );
+ }
+ for (field, value) in [
+ ("schema_version", serde_json::json!(2)),
+ ("outcome", serde_json::json!("unknown")),
+ ("service_pid", serde_json::json!(0)),
+ ("ui_pid", serde_json::json!(-1)),
+ ("service_create_unix_ms", serde_json::json!(0)),
+ ("ui_create_unix_ms", serde_json::json!(-0.5)),
+ ("ui_create_unix_ms", serde_json::json!(null)),
+ ("unexpected", serde_json::json!(true)),
+ ] {
+ let mut invalid = valid.clone();
+ invalid[field] = value;
+ assert!(
+ StartupReceipt::from_json(&serde_json::to_vec(&invalid).unwrap()).is_none(),
+ "{field}"
+ );
+ }
+ }
+
+ #[test]
+ fn oversized_startup_output_is_drained_but_never_grants_authority() {
+ let json = serde_json::to_string(&receipt("started")).expect("fixture JSON");
+ let line = format!("\n@avibe-start-receipt:{json}\n");
+ let mut output = vec![b'x'; MAX_START_OUTPUT_BYTES - line.len()];
+ output.extend_from_slice(line.as_bytes());
+ assert!(read_startup_receipt(output.as_slice()).is_some());
+ output.extend(vec![b'x'; MAX_START_OUTPUT_BYTES * 2]);
+ let mut cursor = std::io::Cursor::new(output);
+ assert!(read_startup_receipt(&mut cursor).is_none());
+ assert_eq!(cursor.position(), cursor.get_ref().len() as u64);
+ }
+
+ #[test]
+ fn receipts_cannot_authorize_failed_pending_or_reused_launches() {
+ assert!(LaunchWatch::default().owned_receipt().is_none());
+ assert!(LaunchWatch::exited(true).owned_receipt().is_none());
+ assert!(LaunchWatch::exited_with_receipt(false, receipt("started"))
+ .owned_receipt()
+ .is_none());
+ assert!(LaunchWatch::exited_with_receipt(true, receipt("reused"))
+ .owned_receipt()
+ .is_none());
+ assert!(LaunchWatch::exited_with_receipt(true, receipt("started"))
+ .owned_receipt()
+ .is_some());
+ let runtime = RuntimeCommand::installed(PathBuf::from("/never-executed"));
+ assert!(matches!(
+ scoped_stop_command(&runtime, &receipt("reused")),
+ Err(LaunchError::NotOwned)
+ ));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_real_launcher_publishes_only_its_completed_receipt() {
+ for outcome in ["started", "reused"] {
+ let dir = scratch_dir("startup-receipt");
+ let json = serde_json::to_string(&receipt(outcome)).expect("fixture JSON");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!("#!/bin/sh\nprintf '%s\\n' 'Starting 服务…' '@avibe-start-receipt:{json}' 'Ready'\n"),
+ );
+ let resolved = InstalledVibeLauncher {
+ candidates: vec![executable],
+ }
+ .resolve()
+ .expect("fake resolve");
+ let launched = resolved.launch().expect("fake launch");
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while !launched.watch.succeeded() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(launched.watch.succeeded());
+ assert_eq!(launched.watch.owned_receipt().is_some(), outcome == "started");
+ std::fs::remove_dir_all(dir).expect("remove test-owned state");
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn scoped_stop_exit_three_never_falls_back_to_unscoped_stop() {
+ let dir = scratch_dir("receipt-refused");
+ let recording = dir.join("argv");
+ let executable = write_fake_runtime(&dir, &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"{}\"\nprintf '%s\\n' '{{\"reason\":\"service_pid_mismatch\"}}' >&2\nexit 3\n", recording.display()
+ ));
+ let resolved = InstalledVibeLauncher {
+ candidates: vec![executable],
+ }
+ .resolve()
+ .expect("fake resolve");
+ let receipt = receipt("started");
+ assert!(matches!(resolved.stop(&receipt), Err(LaunchError::OwnershipLost)));
+ assert_eq!(
+ std::fs::read_to_string(recording)
+ .expect("recorded argv")
+ .lines()
+ .collect::<Vec<_>>(),
+ [
+ "stop",
+ "--receipt",
+ &serde_json::to_string(&receipt).expect("fixture JSON")
+ ]
+ );
+ std::fs::remove_dir_all(dir).expect("remove test-owned state");
+ }
+
+ #[test]
+ fn stop_arguments_preserve_the_frozen_interpreter_and_private_environment() {
+ let runtime = RuntimeCommand {
+ executable: PathBuf::from("/test-owned/Runtime Root/python"),
+ prefix_args: vec![OsString::from("-m"), OsString::from("vibe")],
+ environment: vec![(OsString::from("AVIBE_DESKTOP_MANAGED_RUNTIME"), OsString::from("1"))],
+ withholds_inherited_python: true,
+ };
+ let receipt = receipt("started");
+ let json = serde_json::to_string(&receipt).expect("fixture JSON");
+ let command = scoped_stop_command(&runtime, &receipt).expect("scoped stop");
+ assert_eq!(command.get_program(), runtime.executable.as_os_str());
+ assert_eq!(
+ command.get_args().collect::<Vec<_>>(),
+ ["-m", "vibe", "stop", "--receipt", &json]
+ );
+ let environment: Vec<_> = command.get_envs().collect();
+ assert!(environment.contains(&(OsStr::new(DESKTOP_SHELL_ENV), Some(OsStr::new("1")))));
+ assert!(environment.contains(&(OsStr::new("AVIBE_DESKTOP_MANAGED_RUNTIME"), Some(OsStr::new("1")))));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn owned_stop_invokes_the_resolved_executable_without_rediscovery() {
+ let dir = scratch_dir("owned-stop");
+ let recording = dir.join("stop-argv");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
+ recording.display()
+ ),
+ );
+ let resolved = InstalledVibeLauncher {
+ candidates: vec![executable],
+ }
+ .resolve()
+ .expect("fake resolve");
+ let receipt = receipt("started");
+ let json = serde_json::to_string(&receipt).expect("fixture JSON");
+ resolved.stop(&receipt).expect("fake stop");
+ assert_eq!(
+ wait_for_file(&recording).lines().collect::<Vec<_>>(),
+ ["stop", "--receipt", &json, "shell=1"]
+ );
+ std::fs::remove_dir_all(dir).expect("remove test-owned state");
+ }
+
+ fn executable_name() -> String {
+ format!("vibe{}", env::consts::EXE_SUFFIX)
+ }
+
+ #[test]
+ fn an_explicit_override_is_tried_first() {
+ let override_path = PathBuf::from("/opt/custom/vibe-dev");
+ let candidates = vibe_executable_candidates(
+ Some(override_path.as_os_str()),
+ Some(OsStr::new("/usr/bin")),
+ None,
+ Some(Path::new("/home/tester")),
+ None,
+ );
+ assert_eq!(candidates.first(), Some(&override_path));
+ }
+
+ #[test]
+ fn an_empty_override_is_ignored() {
+ assert_eq!(
+ vibe_executable_candidates(Some(OsStr::new("")), None, None, Some(Path::new("/home/tester")), None,),
+ vibe_executable_candidates(None, None, None, Some(Path::new("/home/tester")), None),
+ );
+ }
+
+ #[test]
+ fn path_entries_come_before_well_known_directories() {
+ let path_var = env::join_paths([PathBuf::from("/custom/bin")]).expect("joins");
+ let candidates = vibe_executable_candidates(None, Some(&path_var), None, Some(Path::new("/home/tester")), None);
+
+ let from_path = PathBuf::from("/custom/bin").join(executable_name());
+ let from_home = PathBuf::from("/home/tester")
+ .join(".local")
+ .join("bin")
+ .join(executable_name());
+
+ let path_index = candidates.iter().position(|c| *c == from_path).expect("PATH candidate");
+ let home_index = candidates.iter().position(|c| *c == from_home).expect("home candidate");
+ assert!(path_index < home_index, "got {candidates:?}");
+ }
+
+ #[test]
+ fn the_gui_fallback_covers_the_documented_install_location() {
+ let candidates = vibe_executable_candidates(None, None, None, Some(Path::new("/home/tester")), None);
+ let expected = PathBuf::from("/home/tester")
+ .join(".local")
+ .join("bin")
+ .join(executable_name());
+ assert!(candidates.contains(&expected), "got {candidates:?}");
+ }
+
+ #[test]
+ fn candidates_are_deduplicated() {
+ let path_var = env::join_paths([PathBuf::from("/home/tester/.local/bin")]).expect("joins");
+ let candidates = vibe_executable_candidates(None, Some(&path_var), None, Some(Path::new("/home/tester")), None);
+ let duplicated = candidates
+ .iter()
+ .filter(|candidate| candidate.ends_with(executable_name()))
+ .filter(|candidate| candidate.starts_with("/home/tester/.local/bin"))
+ .count();
+ assert_eq!(duplicated, 1, "got {candidates:?}");
+ }
+
+ #[test]
+ fn every_candidate_targets_the_platform_executable_name() {
+ let path_var = env::join_paths([PathBuf::from("/custom/bin")]).expect("joins");
+ let candidates = vibe_executable_candidates(None, Some(&path_var), None, Some(Path::new("/home/tester")), None);
+ assert!(!candidates.is_empty());
+ for candidate in &candidates {
+ assert_eq!(
+ candidate.file_name().and_then(|name| name.to_str()),
+ Some(executable_name().as_str()),
+ "candidate {candidate:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn uv_tool_bin_dir_follows_path_and_precedes_default_locations() {
+ let path_var = env::join_paths([PathBuf::from("/custom/bin")]).expect("joins");
+ let uv_bin = PathBuf::from("/custom/uv-tools");
+ let candidates = vibe_executable_candidates(
+ None,
+ Some(&path_var),
+ Some(uv_bin.as_os_str()),
+ Some(Path::new("/home/tester")),
+ None,
+ );
+
+ let path_candidate = PathBuf::from("/custom/bin").join(executable_name());
+ let uv_candidate = uv_bin.join(executable_name());
+ let default_candidate = PathBuf::from("/home/tester")
+ .join(".local")
+ .join("bin")
+ .join(executable_name());
+ let path_index = candidates
+ .iter()
+ .position(|candidate| *candidate == path_candidate)
+ .unwrap();
+ let uv_index = candidates
+ .iter()
+ .position(|candidate| *candidate == uv_candidate)
+ .unwrap();
+ let default_index = candidates
+ .iter()
+ .position(|candidate| *candidate == default_candidate)
+ .unwrap();
+
+ assert!(path_index < uv_index && uv_index < default_index, "got {candidates:?}");
+ }
+
+ #[test]
+ fn an_empty_uv_tool_bin_dir_is_ignored() {
+ assert_eq!(
+ vibe_executable_candidates(None, None, Some(OsStr::new("")), Some(Path::new("/home/tester")), None,),
+ vibe_executable_candidates(None, None, None, Some(Path::new("/home/tester")), None),
+ );
+ }
+
+ #[test]
+ fn windows_app_data_scripts_are_platform_gated() {
+ let app_data = Path::new("C:/Users/tester/AppData/Roaming");
+ let candidates = vibe_executable_candidates(None, None, None, None, Some(app_data));
+ let expected = app_data.join("Python").join("Scripts").join(executable_name());
+
+ assert_eq!(candidates.contains(&expected), cfg!(windows), "got {candidates:?}");
+ }
+
+ #[cfg(not(windows))]
+ #[test]
+ fn native_homebrew_precedes_the_legacy_intel_prefix() {
+ let directories = well_known_bin_dirs(None, None);
+ let native = directories
+ .iter()
+ .position(|path| path == Path::new("/opt/homebrew/bin"))
+ .expect("native Homebrew fallback");
+ let legacy = directories
+ .iter()
+ .position(|path| path == Path::new("/usr/local/bin"))
+ .expect("legacy Homebrew fallback");
+
+ assert!(native < legacy, "got {directories:?}");
+ }
+
+ #[test]
+ fn a_missing_executable_reports_not_found_instead_of_spawning() {
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![PathBuf::from("/nonexistent/avibe-desktop-test/vibe")],
+ };
+ let error = match launcher.resolve() {
+ Ok(_) => panic!("nothing should resolve"),
+ Err(error) => error,
+ };
+ assert!(matches!(error, LaunchError::ExecutableNotFound));
+ assert!(error.is_retryable());
+ }
+
+ #[test]
+ fn a_directory_is_not_mistaken_for_an_executable() {
+ assert!(!is_executable_file(Path::new(env!("CARGO_MANIFEST_DIR"))));
+ }
+
+ #[test]
+ fn launch_failures_map_to_typed_notices_without_exposing_errors() {
+ assert_eq!(
+ LaunchError::ExecutableNotFound.notice_code(),
+ BootstrapNoticeCode::RuntimeNotFound
+ );
+ assert_eq!(
+ LaunchError::RuntimeInstall.notice_code(),
+ BootstrapNoticeCode::RuntimeInstallFailed
+ );
+ assert_eq!(
+ LaunchError::EndpointOutput.notice_code(),
+ BootstrapNoticeCode::RuntimeDiscoveryFailed
+ );
+ assert_eq!(
+ LaunchError::InvalidOrigin.notice_code(),
+ BootstrapNoticeCode::InvalidOrigin
+ );
+ assert_eq!(
+ LaunchError::Spawn(std::io::Error::other("secret path")).notice_code(),
+ BootstrapNoticeCode::RuntimeSpawnFailed
+ );
+ }
+
+ #[test]
+ fn descriptor_parser_accepts_only_the_frozen_schema_and_literal_loopback() {
+ let accepted = parse_endpoint_descriptor(br#"{"schema_version":1,"origin":"http://127.0.0.1:5123"}"#)
+ .expect("valid descriptor");
+ assert_eq!(accepted.as_str(), "http://127.0.0.1:5123");
+
+ for rejected in [
+ br#"{"schema_version":2,"origin":"http://127.0.0.1:5123"}"#.as_slice(),
+ br#"{"schema_version":1,"origin":"http://localhost:5123"}"#.as_slice(),
+ br#"{"schema_version":1,"origin":"http://192.168.1.2:5123"}"#.as_slice(),
+ br#"{"schema_version":1,"origin":"http://127.0.0.1:5123","extra":true}"#.as_slice(),
+ br#"{"schema_version":1}"#.as_slice(),
+ b"not json".as_slice(),
+ ] {
+ assert!(parse_endpoint_descriptor(rejected).is_err(), "{rejected:?}");
+ }
+ }
+
+ #[test]
+ fn descriptor_parser_rejects_oversized_output() {
+ let bytes = vec![b' '; MAX_ENDPOINT_BYTES as usize + 1];
+ assert!(matches!(
+ parse_endpoint_descriptor(&bytes),
+ Err(LaunchError::EndpointOutput)
+ ));
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn the_endpoint_helper_uses_the_no_console_creation_flag() {
+ assert_eq!(CREATE_NO_WINDOW, 0x0800_0000);
+ }
+
+ /// A private scratch directory. Nothing here may touch a real Avibe install,
+ /// so the "executable" launched below is a script this test wrote itself.
+ fn scratch_dir(label: &str) -> PathBuf {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ static COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+ let unique = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir = env::temp_dir().join(format!("avibe-desktop-{label}-{}-{unique}", std::process::id()));
+ std::fs::create_dir_all(&dir).expect("scratch directory is created");
+ dir
+ }
+
+ #[test]
+ fn inactive_broken_private_runtime_is_removed_without_preparing_the_bundle() {
+ let root = scratch_dir("remove-broken-inactive");
+ let install_root = root.join("application-data").join("runtime");
+ let backend_root = root.join("application-data").join("backends");
+ let user_state = root.join("user-state");
+ std::fs::create_dir_all(&install_root).expect("broken private Runtime root");
+ std::fs::create_dir_all(&backend_root).expect("private backend root");
+ std::fs::create_dir_all(&user_state).expect("user state root");
+ std::fs::write(install_root.join("corrupt"), b"not a valid Runtime").expect("broken private Runtime file");
+ std::fs::write(backend_root.join("codex"), b"private backend").expect("private backend file");
+ std::fs::write(user_state.join("config.json"), b"user state").expect("user state file");
+ let launcher = BundledVibeLauncher::new(
+ root.join("missing-bundle"),
+ install_root.clone(),
+ backend_root.clone(),
+ BootstrapLog::disabled(),
+ );
+
+ assert!(launcher
+ .remove_private_runtime(RuntimeRemovalState::Inactive)
+ .expect("inactive broken Runtime is removable"));
+ assert!(!install_root.exists());
+ assert!(!backend_root.exists());
+ assert_eq!(
+ std::fs::read(user_state.join("config.json")).expect("preserved user state"),
+ b"user state"
+ );
+
+ std::fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn unknown_runtime_ownership_blocks_private_file_removal() {
+ let root = scratch_dir("remove-unknown");
+ let install_root = root.join("application-data").join("runtime");
+ let backend_root = root.join("application-data").join("backends");
+ std::fs::create_dir_all(&install_root).expect("private Runtime root");
+ std::fs::create_dir_all(&backend_root).expect("private backend root");
+ std::fs::write(install_root.join("active"), b"potentially active").expect("private Runtime file");
+ std::fs::write(backend_root.join("active"), b"potentially active").expect("private backend file");
+ let launcher = BundledVibeLauncher::new(
+ root.join("missing-bundle"),
+ install_root.clone(),
+ backend_root.clone(),
+ BootstrapLog::disabled(),
+ );
+
+ assert!(matches!(
+ launcher.remove_private_runtime(RuntimeRemovalState::Unknown),
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert!(
+ install_root.is_dir(),
+ "uncertain ownership must preserve the executable tree"
+ );
+ assert!(
+ backend_root.is_dir(),
+ "uncertain ownership must preserve private backends"
+ );
+
+ std::fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn a_non_directory_backend_root_blocks_all_private_removal() {
+ let root = scratch_dir("remove-backend-file");
+ let install_root = root.join("application-data").join("runtime");
+ let backend_root = root.join("application-data").join("backends");
+ std::fs::create_dir_all(&install_root).expect("private Runtime root");
+ std::fs::write(install_root.join("runtime"), b"private Runtime").expect("private Runtime file");
+ std::fs::write(&backend_root, b"not a directory").expect("unsafe backend root");
+ let launcher = BundledVibeLauncher::new(
+ root.join("missing-bundle"),
+ install_root.clone(),
+ backend_root.clone(),
+ BootstrapLog::disabled(),
+ );
+
+ assert!(matches!(
+ launcher.remove_private_runtime(RuntimeRemovalState::Inactive),
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert!(install_root.is_dir());
+ assert!(backend_root.is_file());
+
+ std::fs::remove_dir_all(root).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_symlink_backend_root_blocks_all_private_removal() {
+ use std::os::unix::fs::symlink;
+
+ let root = scratch_dir("remove-backend-symlink");
+ let install_root = root.join("application-data").join("runtime");
+ let backend_root = root.join("application-data").join("backends");
+ let external = root.join("external-backends");
+ std::fs::create_dir_all(&install_root).expect("private Runtime root");
+ std::fs::write(install_root.join("runtime"), b"private Runtime").expect("private Runtime file");
+ std::fs::create_dir_all(&external).expect("external backend root");
+ std::fs::write(external.join("preserve"), b"external backend").expect("external backend file");
+ symlink(&external, &backend_root).expect("unsafe backend symlink");
+ let launcher = BundledVibeLauncher::new(
+ root.join("missing-bundle"),
+ install_root.clone(),
+ backend_root,
+ BootstrapLog::disabled(),
+ );
+
+ assert!(matches!(
+ launcher.remove_private_runtime(RuntimeRemovalState::Inactive),
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert!(install_root.is_dir());
+ assert_eq!(
+ std::fs::read(external.join("preserve")).expect("external backend preserved"),
+ b"external backend"
+ );
+
+ std::fs::remove_dir_all(root).ok();
+ }
+
+ /// Writes a runnable stand-in for `vibe` and returns its path.
+ #[cfg(unix)]
+ fn write_fake_runtime(dir: &Path, body: &str) -> PathBuf {
+ use std::os::unix::fs::PermissionsExt;
+
+ let executable = dir.join("vibe");
+ std::fs::write(&executable, body).expect("fake runtime is written");
+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755))
+ .expect("fake runtime is runnable");
+ executable
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_retry_discovers_a_runtime_installed_after_the_first_attempt() {
+ let dir = scratch_dir("installed-after-retry");
+ let executable = dir.join("vibe");
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![executable],
+ };
+
+ assert!(matches!(launcher.resolve(), Err(LaunchError::ExecutableNotFound)));
+ write_fake_runtime(&dir, "#!/bin/sh\nexit 0\n");
+ assert!(launcher.resolve().is_ok(), "the retry must see the new installation");
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn one_attempt_does_not_switch_executables_between_endpoint_and_launch() {
+ let first_dir = scratch_dir("attempt-first");
+ let second_dir = scratch_dir("attempt-second");
+ let first = write_fake_runtime(&first_dir, "#!/bin/sh\nexit 0\n");
+ let second = write_fake_runtime(&second_dir, "#!/bin/sh\nexit 0\n");
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![first.clone(), second],
+ };
+
+ let resolved = launcher.resolve().expect("the first executable resolves");
+ std::fs::remove_file(first).expect("the first executable is removed");
+ assert!(
+ matches!(resolved.launch(), Err(LaunchError::Spawn(_))),
+ "an in-flight attempt must not silently switch to the second candidate"
+ );
+ assert!(
+ launcher.resolve().is_ok(),
+ "the next attempt may resolve the remaining candidate"
+ );
+
+ std::fs::remove_dir_all(&first_dir).ok();
+ std::fs::remove_dir_all(&second_dir).ok();
+ }
+
+ /// The launch is detached, so the recording appears asynchronously.
+ #[cfg(unix)]
+ fn wait_for_file(path: &Path) -> String {
+ for _ in 0..200 {
+ if let Ok(contents) = std::fs::read_to_string(path) {
+ if !contents.is_empty() {
+ return contents;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+ panic!("{} was never written", path.display());
+ }
+
+ /// Asserts the launch contract against what the operating system actually
+ /// receives, rather than against the constant the code was built from.
+ #[cfg(unix)]
+ #[test]
+ fn the_runtime_is_started_headless_and_marked_as_shell_started() {
+ let dir = scratch_dir("launch");
+ let recording = dir.join("argv");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
+ recording.display()
+ ),
+ );
+
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![executable],
+ };
+ let launched = launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .launch()
+ .expect("the fake runtime starts");
+ assert!(launched.pid > 0);
+
+ let recorded = wait_for_file(&recording);
+ assert_eq!(
+ recorded.lines().collect::<Vec<_>>(),
+ // Without --no-open-browser the Runtime would open a second window
+ // onto the Workbench, in the system browser.
+ ["start", "--no-open-browser", "shell=1"],
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_desktop_endpoint_uses_the_machine_readable_cli_contract() {
+ let dir = scratch_dir("endpoint");
+ let recording = dir.join("endpoint-argv");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\nprintf '%s\\n' '{{\"schema_version\":1,\"origin\":\"http://127.0.0.1:6123\"}}'\n",
+ recording.display()
+ ),
+ );
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![executable],
+ };
+
+ let endpoint = launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .endpoint()
+ .expect("descriptor is accepted");
+
+ assert_eq!(endpoint.as_str(), "http://127.0.0.1:6123");
+ assert_eq!(
+ wait_for_file(&recording).lines().collect::<Vec<_>>(),
+ ["desktop", "endpoint", "--json", "shell=1"],
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// Longer than the 10s budget that cut off cold first launches, short enough
+ /// that the desktop-shell job barely notices. The number only has to sit
+ /// between the old budget and the new one; the assertion is that a slow
+ /// endpoint is waited for, not that it answers at any particular moment.
+ #[cfg(unix)]
+ const SLOW_ENDPOINT_SECONDS: u64 = 12;
+
+ /// A first launch extracts the runtime tree and then immediately asks it for
+ /// its address, so the interpreter pays for a whole cold tree on that one
+ /// call -- measured at 15.8s to 20.0s, against 2.3s once warm. The old budget
+ /// killed the child at 10s and the user met `runtime_discovery_failed` on
+ /// every fresh install, while a second launch worked and hid it from us.
+ ///
+ /// This drives the real `query_endpoint` deadline with a command that genuinely
+ /// outlives the old budget, so it fails on the constant rather than on a value
+ /// read back from it.
+ #[cfg(unix)]
+ #[test]
+ fn a_slow_cold_endpoint_is_waited_for_rather_than_killed() {
+ let dir = scratch_dir("endpoint-cold-start");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nsleep {}\nprintf '%s\\n' '{{\"schema_version\":1,\"origin\":\"http://127.0.0.1:6123\"}}'\n",
+ SLOW_ENDPOINT_SECONDS
+ ),
+ );
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![executable],
+ };
+
+ let endpoint = launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .endpoint()
+ .expect("an endpoint slower than the old budget still answers");
+
+ assert_eq!(endpoint.as_str(), "http://127.0.0.1:6123");
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// Every `.pyc` file and `__pycache__` directory under a tree.
+ #[cfg(unix)]
+ fn tree_bytecode(root: &Path) -> Vec<PathBuf> {
+ let mut found = Vec::new();
+ let mut pending = vec![root.to_owned()];
+ while let Some(directory) = pending.pop() {
+ let Ok(entries) = std::fs::read_dir(&directory) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ if path.file_name() == Some(OsStr::new("__pycache__")) {
+ found.push(path);
+ } else {
+ pending.push(path);
+ }
+ } else if path.extension() == Some(OsStr::new("pyc")) {
+ found.push(path);
+ }
+ }
+ }
+ found
+ }
+
+ /// The bug that invalidated an install on every launch, and the one test
+ /// that could have caught it.
+ ///
+ /// `RuntimeCommand::private` asks for no bytecode twice: once by flag and
+ /// once by environment variable. Only the flag works — `-I` implies `-E`,
+ /// which makes the interpreter ignore every PYTHON* variable, including the
+ /// one set right beside it. Nothing about that is visible in the code; it is
+ /// only visible in what a real interpreter leaves on disk. So this runs the
+ /// real interpreter with the real prefix arguments and the real environment,
+ /// substituting only the module to import, and counts the files written.
+ #[cfg(unix)]
+ #[test]
+ fn the_private_interpreter_writes_no_bytecode_into_its_own_install_tree() {
+ let python = env::split_paths(&env::var_os("PATH").unwrap_or_default())
+ .map(|entry| entry.join("python3"))
+ .find(|candidate| is_executable_file(candidate))
+ .expect("a python3 interpreter to run the private command against");
+ let dir = scratch_dir("no-bytecode");
+ let tree = dir.join("runtime");
+ let package = tree.join("avibe_bytecode_probe");
+ std::fs::create_dir_all(&package).expect("probe package directory");
+ std::fs::write(package.join("__init__.py"), "VALUE = 1\n").expect("probe package");
+ std::fs::write(package.join("module.py"), "from . import VALUE\n").expect("probe module");
+
+ let command = RuntimeCommand::private(
+ tree.clone(),
+ python,
+ tree.join("tools/bin/node"),
+ tree.join("tools/npm/bin/npm-cli.js"),
+ dir.join("backends"),
+ &"a".repeat(64),
+ env::var_os("PATH").as_deref(),
+ );
+ let mut process = Command::new(&command.executable);
+ for (name, value) in &command.environment {
+ process.env(name, value);
+ }
+ // Everything up to `-m vibe`, which is the part that cannot resolve here.
+ for argument in command.prefix_args.iter().take_while(|argument| *argument != "-m") {
+ process.arg(argument);
+ }
+ // `-I` also drops PYTHONPATH, so the probe package is put on the path
+ // the only way an isolated interpreter still accepts.
+ let status = process
+ .arg("-c")
+ .arg(format!(
+ "import sys; sys.path.insert(0, {:?}); import avibe_bytecode_probe.module",
+ tree.display().to_string()
+ ))
+ .status()
+ .expect("the private interpreter runs");
+ assert!(status.success(), "the probe import itself must succeed: {status}");
+
+ let bytecode = tree_bytecode(&tree);
+ assert!(
+ bytecode.is_empty(),
+ "the Runtime wrote bytecode into the tree `verify_installed_tree` checks: {bytecode:?}"
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// `-I` shields the one interpreter it is passed to, not the ones that
+ /// interpreter starts. The Controller and the UI copy `os.environ` and run
+ /// without it, so a `PYTHONHOME` the shell happened to be launched with
+ /// aborted both before readiness.
+ ///
+ /// The shell's own environment is modelled rather than mutated: the
+ /// variables are set on the child the way inheritance would deliver them,
+ /// and passed as the inherited set, so no other test thread sees a change to
+ /// this process's environment while it spawns.
+ #[cfg(unix)]
+ #[test]
+ fn the_private_runtime_does_not_hand_the_shells_python_variables_to_its_descendants() {
+ let python = env::split_paths(&env::var_os("PATH").unwrap_or_default())
+ .map(|entry| entry.join("python3"))
+ .find(|candidate| is_executable_file(candidate))
+ .expect("a python3 interpreter to run the private command against");
+ let dir = scratch_dir("python-environment");
+ let tree = dir.join("runtime");
+ std::fs::create_dir_all(&tree).expect("runtime directory");
+ let command = RuntimeCommand::private(
+ tree.clone(),
+ python,
+ tree.join("tools/bin/node"),
+ tree.join("tools/npm/bin/npm-cli.js"),
+ dir.join("backends"),
+ &"a".repeat(64),
+ env::var_os("PATH").as_deref(),
+ );
+ let inherited = [
+ (
+ OsString::from("PYTHONHOME"),
+ dir.join("no-such-python-home").into_os_string(),
+ ),
+ (
+ OsString::from("PYTHONPATH"),
+ dir.join("outside-the-verified-tree").into_os_string(),
+ ),
+ (OsString::from("AVIBE_UNRELATED_INHERITED"), OsString::from("kept")),
+ ];
+
+ let mut process = Command::new(&command.executable);
+ for (name, value) in &inherited {
+ process.env(name, value);
+ }
+ command.apply_environment(&mut process, env::vars_os().chain(inherited.iter().cloned()));
+ for argument in command.prefix_args.iter().take_while(|argument| *argument != "-m") {
+ process.arg(argument);
+ }
+ // What the Runtime would see, and whether a descendant started the way
+ // `cmd_start` starts the Controller -- no `-I`, `os.environ` copied --
+ // gets as far as running a statement.
+ let output = process
+ .arg("-c")
+ .arg(concat!(
+ "import json, os, subprocess, sys; ",
+ "child = subprocess.run([sys.executable, '-c', 'pass'], env=dict(os.environ)); ",
+ "print(json.dumps({'python': {k: v for k, v in os.environ.items() if k.startswith('PYTHON')}, ",
+ "'unrelated': os.environ.get('AVIBE_UNRELATED_INHERITED'), 'descendant': child.returncode}))",
+ ))
+ .stderr(Stdio::null())
+ .output()
+ .expect("the private interpreter runs");
+ assert!(
+ output.status.success(),
+ "the private interpreter itself must run: {output:?}"
+ );
+ let report: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("the child reports its environment");
+
+ assert_eq!(
+ report["python"],
+ serde_json::json!({"PYTHONDONTWRITEBYTECODE": "1"}),
+ "only the Runtime's own Python variable may reach it"
+ );
+ assert_eq!(
+ report["unrelated"], "kept",
+ "only Python startup variables are withheld"
+ );
+ assert_eq!(
+ report["descendant"], 0,
+ "a descendant interpreter without -I must start"
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn python_startup_variables_are_recognised_by_prefix() {
+ assert!(is_python_startup_variable(OsStr::new("PYTHONHOME")));
+ assert!(is_python_startup_variable(OsStr::new("PYTHONSTARTUP")));
+ assert!(!is_python_startup_variable(OsStr::new("PATH")));
+ assert!(!is_python_startup_variable(OsStr::new("VIRTUAL_ENV")));
+ assert_eq!(is_python_startup_variable(OsStr::new("PythonPath")), cfg!(windows));
+ }
+
+ /// The stderr this used to send to the null device is where the cause lives.
+ #[cfg(unix)]
+ #[test]
+ fn a_failed_endpoint_query_records_its_stderr_and_exit_status() {
+ let dir = scratch_dir("endpoint-stderr");
+ let executable = write_fake_runtime(
+ &dir,
+ "#!/bin/sh\nprintf '%s\\n' 'Traceback (most recent call last):' 'ModuleNotFoundError: vibe' >&2\nexit 3\n",
+ );
+ let log = BootstrapLog::at(dir.join("bootstrap.log"));
+
+ let failure = query_endpoint(&RuntimeCommand::installed(executable), &log);
+
+ assert!(matches!(failure, Err(LaunchError::EndpointExit)));
+ let written = std::fs::read_to_string(dir.join("bootstrap.log")).expect("the attempt is recorded");
+ assert_eq!(written.lines().count(), 1, "one attempt is one record: {written}");
+ assert!(written.contains("endpoint.query"), "{written}");
+ assert!(written.contains("outcome=\"exit_failed\""), "{written}");
+ assert!(written.contains("exit=\"3\""), "{written}");
+ assert!(
+ written.contains("ModuleNotFoundError: vibe"),
+ "the discarded stderr is the whole point: {written}"
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// A timeout is the failure we could least explain, so it must not be the
+ /// one that records nothing: the child is killed, and what it said before
+ /// that is still collected.
+ #[cfg(unix)]
+ #[test]
+ fn an_endpoint_that_never_answers_records_the_timeout_rather_than_nothing() {
+ let dir = scratch_dir("endpoint-timeout");
+ // The fixture runs twice. The first run takes the `exit 0` branch and
+ // only leaves the flag behind; the second finds it and blocks forever,
+ // which is the child this test is about.
+ //
+ // The warm-up is not decoration. Measured under a full `cargo test`, the
+ // FIRST execution of a just-written executable takes ~4.8s to reach its
+ // own first line -- macOS evaluates a new binary before it runs -- while
+ // every later one takes ~10-25ms. Inside a sub-second deadline that cost
+ // lands on the wrong side of the kill, and the test then proves nothing
+ // while looking like a timing flake. Paying it through a run that exits
+ // on its own moves it outside the window by construction rather than by
+ // choosing a budget large enough to hide it.
+ //
+ // `exec` so the sleep replaces the shell: one process to kill, and the
+ // stderr pipe closes with it rather than being held open by a survivor.
+ // The message goes through the external `echo` because `exec` replaces
+ // the image without flushing whatever the shell still holds in its own
+ // stdio buffers.
+ let warmed = dir.join("warmed");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\n/bin/echo 'still importing' >&2\nif [ -e {flag} ]; then exec sleep 30; fi\n: > {flag}\nexit 0\n",
+ flag = warmed.display()
+ ),
+ );
+ let warm_up = Command::new(&executable)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .expect("the fixture runs");
+ assert!(
+ warm_up.success() && warmed.exists(),
+ "the warm-up run must complete: {warm_up}"
+ );
+ let log = BootstrapLog::at(dir.join("bootstrap.log"));
+
+ let failure = query_endpoint_within(
+ &RuntimeCommand::installed(executable),
+ &log,
+ Duration::from_millis(1_500),
+ );
+
+ assert!(matches!(failure, Err(LaunchError::EndpointTimeout)));
+ let written = std::fs::read_to_string(dir.join("bootstrap.log")).expect("the attempt is recorded");
+ assert!(written.contains("outcome=\"timeout\""), "{written}");
+ assert!(
+ !written.contains(" exit="),
+ "a child that was killed has no exit status to report: {written}"
+ );
+ assert!(
+ written.contains("still importing"),
+ "output from before the kill is still worth having: {written}"
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// Reused against extracted is the line that settles whether an install is
+ /// quietly reinstalling itself on every launch.
+ #[test]
+ fn a_prepare_records_whether_it_reused_an_install_or_extracted_one() {
+ let dir = scratch_dir("prepare-record");
+ let log = BootstrapLog::at(dir.join("bootstrap.log"));
+ let installed = |reused: bool| InstalledPrivateRuntime {
+ root: PathBuf::from("/installs/3.1.1/20aa5822aa3595e1"),
+ python: PathBuf::from("/installs/3.1.1/20aa5822aa3595e1/python/bin/python3"),
+ node: PathBuf::from("/installs/3.1.1/20aa5822aa3595e1/tools/bin/node"),
+ npm_cli: PathBuf::from("/installs/3.1.1/20aa5822aa3595e1/tools/npm/bin/npm-cli.js"),
+ runtime_id: "a".repeat(64),
+ reused,
+ };
+
+ record_runtime_prepare(&log, &Ok(installed(true)), Duration::from_millis(5_123));
+ record_runtime_prepare(&log, &Ok(installed(false)), Duration::from_millis(41_000));
+ record_runtime_prepare(
+ &log,
+ &Err(PrivateRuntimeError::ArchiveVerification),
+ Duration::from_millis(12),
+ );
+
+ let written = std::fs::read_to_string(dir.join("bootstrap.log")).expect("the attempts are recorded");
+ let records: Vec<&str> = written.lines().collect();
+ assert_eq!(records.len(), 3, "{written}");
+ assert!(
+ records[0].contains("outcome=\"reused\"")
+ && records[0].contains("ms=\"5123\"")
+ // The install directory is named for the payload digest, which is
+ // what makes a user-sent log identify its own build.
+ && records[0].contains("20aa5822aa3595e1"),
+ "{}",
+ records[0]
+ );
+ assert!(records[1].contains("outcome=\"extracted\""), "{}", records[1]);
+ assert!(
+ records[2].contains("outcome=\"failed\"") && records[2].contains("ArchiveVerification"),
+ "{}",
+ records[2]
+ );
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_superseded_runtime_is_stopped_through_the_cli_contract() {
+ let dir = scratch_dir("handover");
+ let recording = dir.join("stop-argv");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
+ recording.display()
+ ),
+ );
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![executable],
+ };
+
+ launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .handover()
+ .expect("the fake runtime stops");
+
+ assert_eq!(
+ wait_for_file(&recording).lines().collect::<Vec<_>>(),
+ ["stop", "shell=1"],
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// The bootstrap loop aborts a doomed wait on this verdict, so it has to be
+ /// right in both directions: a launcher that refused its arguments must be
+ /// visible, and the ordinary `vibe start` — which exits 0 once the Runtime is
+ /// up — must never be mistaken for one.
+ #[cfg(unix)]
+ #[test]
+ fn only_a_non_zero_launcher_exit_is_reported_as_a_failure() {
+ let refused = scratch_dir("exit-nonzero");
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![write_fake_runtime(&refused, "#!/bin/sh\nexit 3\n")],
+ };
+ let launched = launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .launch()
+ .expect("the fake runtime starts");
+ // The wait runs on a detached thread, so the verdict arrives late.
+ for _ in 0..200 {
+ if launched.watch.failed() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+ assert!(launched.watch.failed(), "a launcher that exited non-zero is invisible");
+
+ let succeeded = scratch_dir("exit-zero");
+ let launcher = InstalledVibeLauncher {
+ candidates: vec![write_fake_runtime(&succeeded, "#!/bin/sh\nexit 0\n")],
+ };
+ let launched = launcher
+ .resolve()
+ .expect("the fake runtime resolves")
+ .launch()
+ .expect("the fake runtime starts");
+ std::thread::sleep(std::time::Duration::from_millis(250));
+ assert!(
+ !launched.watch.failed(),
+ "a normal start would be aborted as if it had failed"
+ );
+
+ std::fs::remove_dir_all(&refused).ok();
+ std::fs::remove_dir_all(&succeeded).ok();
+ }
+
+ #[test]
+ fn private_runtime_commands_ignore_user_python_and_prepend_managed_tools() {
+ let runtime_root = PathBuf::from("/private/runtime");
+ let python = PathBuf::from("/private/runtime/python/bin/python3");
+ let node = PathBuf::from("/private/runtime/tools/bin/node");
+ let npm_cli = PathBuf::from("/private/runtime/tools/npm/bin/npm-cli.js");
+ let backends_root = PathBuf::from("/private/backends");
+ let inherited = env::join_paths([PathBuf::from("/usr/bin")]).expect("PATH");
+ let expected_node = node.clone().into_os_string();
+ let expected_npm_cli = npm_cli.clone().into_os_string();
+ let expected_backends_root = backends_root.clone().into_os_string();
+
+ let command = RuntimeCommand::private(
+ runtime_root.clone(),
+ python.clone(),
+ node.clone(),
+ npm_cli,
+ backends_root,
+ &"a".repeat(64),
+ Some(&inherited),
+ );
+
+ assert_eq!(command.executable, python);
+ assert_eq!(
+ command.prefix_args,
+ [
+ OsString::from("-I"),
+ OsString::from("-B"),
+ OsString::from("-m"),
+ OsString::from("vibe")
+ ]
+ );
+ let environment: std::collections::HashMap<_, _> = command.environment.into_iter().collect();
+ let path_entries: Vec<_> =
+ env::split_paths(environment.get(OsStr::new("PATH")).expect("private PATH")).collect();
+ assert_eq!(path_entries.first().map(PathBuf::as_path), node.parent());
+ assert_eq!(path_entries.get(1).map(PathBuf::as_path), Some(Path::new("/usr/bin")));
+ assert_eq!(
+ environment.get(OsStr::new("VIBE_SHOW_RUNTIME_NODE_BIN")),
+ Some(&expected_node)
+ );
+ assert_eq!(
+ environment.get(OsStr::new(DESKTOP_NPM_CLI_ENV)),
+ Some(&expected_npm_cli)
+ );
+ assert_eq!(
+ environment.get(OsStr::new(DESKTOP_BACKENDS_ROOT_ENV)),
+ Some(&expected_backends_root)
+ );
+ assert_eq!(
+ environment.get(OsStr::new(DESKTOP_MANAGED_RUNTIME_ENV)),
+ Some(&OsString::from("1"))
+ );
+ assert_eq!(
+ environment.get(OsStr::new(DESKTOP_RUNTIME_ROOT_ENV)),
+ Some(&runtime_root.into_os_string())
+ );
+ assert_eq!(
+ environment.get(OsStr::new("AVIBE_DESKTOP_RUNTIME_ID")),
+ Some(&OsString::from("a".repeat(64)))
+ );
+ assert_eq!(
+ environment.get(OsStr::new("PYTHONDONTWRITEBYTECODE")),
+ Some(&OsString::from("1"))
+ );
+ }
+}
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
new file mode 100644
index 000000000..4126dbb00
--- /dev/null
+++ b/desktop/runtime-host/src/lib.rs
@@ -0,0 +1,80 @@
+//! Runtime discovery, launch, and readiness logic for the Avibe desktop shell.
+//!
+//! The crate deliberately knows nothing about Tauri. Everything the desktop
+//! shell decides — which origin is acceptable, whether a Runtime is already
+//! serving it, whether to start one, when the WebView may navigate — is decided
+//! here, behind traits that tests can substitute.
+//!
+//! ```no_run
+//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
+//! use avibe_runtime_host::{default_runtime_host, BootstrapPhase, DiscardStatus};
+//!
+//! let host = default_runtime_host()?;
+//! let status = host.bootstrap(&DiscardStatus).await;
+//! if status.phase == BootstrapPhase::Ready {
+//! // Only now may the WebView leave the bootstrap page.
+//! }
+//! # Ok(())
+//! # }
+//! ```
+
+#![forbid(unsafe_code)]
+
+pub mod bootstrap;
+pub mod bootstrap_log;
+pub mod deep_link;
+pub mod health;
+pub mod launcher;
+pub mod notifications;
+pub mod origin;
+pub mod private_runtime;
+pub mod status;
+pub mod window_frame;
+
+use std::sync::Arc;
+
+pub use bootstrap::{
+ DiscardStatus, RuntimeHost, RuntimeHostSettings, StatusSink, DEFAULT_POLL_INTERVAL, DEFAULT_PROBE_TIMEOUT,
+ DEFAULT_READY_TIMEOUT, ORIGIN_ENV, READY_TIMEOUT_ENV,
+};
+pub use bootstrap_log::{BootstrapLog, BOOTSTRAP_LOG_NAME};
+pub use health::{is_avibe_readiness_body, parse_avibe_readiness_body, HealthProbe, HttpHealthProbe, RuntimeReadiness};
+pub use launcher::{
+ vibe_executable_candidates, BundledVibeLauncher, InstalledVibeLauncher, LaunchError, LaunchWatch, LaunchedRuntime,
+ ResolvedRuntimeLauncher, RuntimeLauncher, RuntimeRemovalState, DESKTOP_BACKENDS_ROOT_ENV, DESKTOP_NPM_CLI_ENV,
+ DESKTOP_RUNTIME_ROOT_ENV, UV_TOOL_BIN_DIR_ENV, VIBE_PATH_ENV,
+};
+pub use origin::{is_shell_ui_url, LoopbackOrigin, OriginError, DEV_SERVER_PORT};
+pub use private_runtime::{PrivateRuntimeBundle, PrivateRuntimeError, RuntimeBundleManifest};
+pub use status::{BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus};
+
+/// The host the shipped desktop shell uses: real HTTP probing, the installed
+/// `vibe` executable, and settings from the process environment.
+pub fn default_runtime_host() -> Result<RuntimeHost, reqwest::Error> {
+ let settings = RuntimeHostSettings::from_env();
+ let probe = HttpHealthProbe::new(settings.probe_timeout)?;
+ Ok(RuntimeHost::new(
+ Arc::new(probe),
+ Arc::new(InstalledVibeLauncher::from_env()),
+ settings,
+ ))
+}
+
+/// The host used by a product package containing its own Runtime.
+///
+/// The bundle is installed lazily by the blocking launcher resolver, so Tauri's
+/// setup hook never extracts a large archive on the UI thread.
+pub fn bundled_runtime_host(
+ bundle_dir: std::path::PathBuf,
+ install_root: std::path::PathBuf,
+ backend_root: std::path::PathBuf,
+ log: BootstrapLog,
+) -> Result<RuntimeHost, reqwest::Error> {
+ let settings = RuntimeHostSettings::from_env();
+ let probe = HttpHealthProbe::new(settings.probe_timeout)?;
+ Ok(RuntimeHost::new(
+ Arc::new(probe),
+ Arc::new(BundledVibeLauncher::new(bundle_dir, install_root, backend_root, log)),
+ settings,
+ ))
+}
diff --git a/desktop/runtime-host/src/notifications.rs b/desktop/runtime-host/src/notifications.rs
new file mode 100644
index 000000000..b55d9578a
--- /dev/null
+++ b/desktop/runtime-host/src/notifications.rs
@@ -0,0 +1,489 @@
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use chrono::DateTime;
+use serde::Deserialize;
+use tokio::time::Instant;
+use url::Url;
+
+use crate::LoopbackOrigin;
+
+pub const RETAINED_KEYS: usize = 512;
+pub const RETENTION: Duration = Duration::from_secs(24 * 60 * 60);
+const MAX_EVENT_BYTES: usize = 64 * 1024;
+const MAX_DETAIL_BYTES: usize = 256 * 1024;
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
+const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(45);
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct SseFrame {
+ pub event: String,
+ pub data: String,
+}
+
+#[derive(Default)]
+pub struct SseDecoder {
+ line: Vec<u8>,
+ event: String,
+ data: String,
+ skip_lf: bool,
+ started: bool,
+ bytes: usize,
+ discarded: bool,
+ line_has_bytes: bool,
+}
+
+impl SseDecoder {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn push(&mut self, chunk: &[u8]) -> Vec<SseFrame> {
+ let mut frames = Vec::new();
+ for byte in chunk {
+ if self.skip_lf && *byte == b'\n' {
+ self.skip_lf = false;
+ continue;
+ }
+ self.skip_lf = *byte == b'\r';
+ if matches!(byte, b'\r' | b'\n') {
+ self.finish_line(&mut frames);
+ } else {
+ self.line_has_bytes = true;
+ if self.bytes < MAX_EVENT_BYTES {
+ self.line.push(*byte);
+ self.bytes += 1;
+ } else {
+ self.discarded = true;
+ }
+ }
+ }
+ frames
+ }
+
+ fn finish_line(&mut self, frames: &mut Vec<SseFrame>) {
+ if !std::mem::replace(&mut self.line_has_bytes, false) {
+ if !self.discarded && !self.data.is_empty() {
+ self.data.pop();
+ frames.push(SseFrame {
+ event: std::mem::take(&mut self.event),
+ data: std::mem::take(&mut self.data),
+ });
+ }
+ self.event.clear();
+ self.data.clear();
+ self.bytes = 0;
+ self.discarded = false;
+ return;
+ }
+ let line = std::mem::take(&mut self.line);
+ let Ok(line) = std::str::from_utf8(&line) else {
+ self.discarded = true;
+ return;
+ };
+ let line = if !std::mem::replace(&mut self.started, true) {
+ line.strip_prefix('\u{feff}').unwrap_or(line)
+ } else {
+ line
+ };
+ if self.discarded || line.starts_with(':') {
+ return;
+ }
+ let (field, value) = line.split_once(':').unwrap_or((line, ""));
+ let value = value.strip_prefix(' ').unwrap_or(value);
+ match field {
+ "event" => self.event = value.to_owned(),
+ "data" => {
+ self.data.push_str(value);
+ self.data.push('\n');
+ }
+ _ => {}
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NotificationIntent {
+ ApprovalRequested,
+ RunSucceeded,
+ RunFailed,
+ RunCanceled,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct NotificationGate {
+ pub enabled: bool,
+ pub focused: bool,
+ pub visible: bool,
+}
+
+impl NotificationGate {
+ pub fn allows(self) -> bool {
+ self.enabled && !(self.focused && self.visible)
+ }
+}
+
+pub trait NotificationSink: Send + Sync {
+ fn gate(&self) -> NotificationGate;
+ fn deliver(&self, intent: NotificationIntent);
+}
+
+#[derive(Default)]
+struct RetainedKeys(VecDeque<(String, Instant)>);
+
+impl RetainedKeys {
+ fn insert(&mut self, key: &str, now: Instant) -> bool {
+ self.0.retain(|(_, inserted)| now.duration_since(*inserted) < RETENTION);
+ if let Some(index) = self.0.iter().position(|(retained, _)| retained == key) {
+ let retained = self.0.remove(index).expect("the retained key exists");
+ self.0.push_back(retained);
+ return false;
+ }
+ if self.0.len() == RETAINED_KEYS {
+ self.0.pop_front();
+ }
+ self.0.push_back((key.to_owned(), now));
+ true
+ }
+
+ fn remove(&mut self, key: &str) {
+ self.0.retain(|(retained, _)| retained != key);
+ }
+}
+
+#[derive(Default)]
+pub struct NotificationFilter {
+ approvals: RetainedKeys,
+ runs: RetainedKeys,
+}
+
+#[derive(Deserialize)]
+struct Envelope {
+ #[serde(rename = "type")]
+ event: String,
+ data: serde_json::Value,
+}
+
+#[derive(Deserialize)]
+struct Approval {
+ request_id: String,
+ request_status: String,
+}
+
+#[derive(Clone, Default, Deserialize)]
+pub struct RunTimestamps {
+ pub started_at: Option<String>,
+ pub completed_at: Option<String>,
+ pub updated_at: Option<String>,
+}
+
+impl RunTimestamps {
+ fn completion(&self) -> Option<&str> {
+ self.completed_at.as_deref().or(self.updated_at.as_deref())
+ }
+
+ fn missing(&self) -> bool {
+ self.started_at.is_none() || self.completion().is_none()
+ }
+
+ fn is_long_running(&self) -> bool {
+ let duration = self
+ .started_at
+ .as_deref()
+ .zip(self.completion())
+ .and_then(|(start, end)| {
+ let start = DateTime::parse_from_rfc3339(start).ok()?;
+ let end = DateTime::parse_from_rfc3339(end).ok()?;
+ Some(end.signed_duration_since(start))
+ });
+ duration.is_some_and(|duration| duration >= chrono::Duration::seconds(30))
+ }
+
+ fn fill_missing(&mut self, other: Self) {
+ if self.started_at.is_none() {
+ self.started_at = other.started_at;
+ }
+ if self.completion().is_none() {
+ self.completed_at = other.completed_at;
+ self.updated_at = other.updated_at;
+ }
+ }
+}
+
+#[derive(Deserialize)]
+struct RunEvent {
+ run_id: String,
+ status: String,
+ run_type: Option<String>,
+ #[serde(flatten)]
+ stamps: RunTimestamps,
+}
+
+enum Candidate {
+ Ready(NotificationIntent),
+ Refetch {
+ run_id: String,
+ stamps: RunTimestamps,
+ intent: NotificationIntent,
+ },
+}
+
+impl NotificationFilter {
+ fn consider(&mut self, frame: SseFrame, now: Instant) -> Option<Candidate> {
+ if !matches!(frame.event.as_str(), "vaults.updated" | "runs.updated") {
+ return None;
+ }
+ let envelope: Envelope = serde_json::from_str(&frame.data).ok()?;
+ if envelope.event != frame.event {
+ return None;
+ }
+ if frame.event == "vaults.updated" {
+ let approval: Approval = serde_json::from_value(envelope.data).ok()?;
+ if approval.request_id.is_empty() {
+ return None;
+ }
+ if approval.request_status != "pending" {
+ self.approvals.remove(&approval.request_id);
+ return None;
+ }
+ return self
+ .approvals
+ .insert(&approval.request_id, now)
+ .then_some(Candidate::Ready(NotificationIntent::ApprovalRequested));
+ }
+ let run: RunEvent = serde_json::from_value(envelope.data).ok()?;
+ if run.run_id.is_empty() {
+ return None;
+ }
+ let intent = match run.status.as_str() {
+ "succeeded" => NotificationIntent::RunSucceeded,
+ "failed" => NotificationIntent::RunFailed,
+ "canceled" => NotificationIntent::RunCanceled,
+ _ => return None,
+ };
+ if !self.runs.insert(&run.run_id, now) {
+ return None;
+ }
+ if matches!(run.run_type.as_deref(), Some("scheduled" | "watch")) || run.stamps.is_long_running() {
+ return Some(Candidate::Ready(intent));
+ }
+ run.stamps.missing().then_some(Candidate::Refetch {
+ run_id: run.run_id,
+ stamps: run.stamps,
+ intent,
+ })
+ }
+}
+
+#[async_trait]
+pub trait EventStream: Send {
+ async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, StreamError>;
+}
+
+#[derive(Debug)]
+pub struct StreamError;
+
+#[async_trait]
+pub trait NotificationTransport: Send + Sync {
+ async fn connect(&self) -> Result<Box<dyn EventStream>, StreamError>;
+ async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps>;
+}
+
+pub struct HttpNotificationTransport {
+ client: reqwest::Client,
+ origin: LoopbackOrigin,
+}
+
+impl HttpNotificationTransport {
+ pub fn new(origin: LoopbackOrigin) -> Result<Self, reqwest::Error> {
+ Ok(Self {
+ client: reqwest::Client::builder()
+ .connect_timeout(REQUEST_TIMEOUT)
+ .redirect(reqwest::redirect::Policy::none())
+ .no_proxy()
+ .build()?,
+ origin,
+ })
+ }
+
+ fn url(&self, path: &str) -> Url {
+ Url::parse(&format!("{}{path}", self.origin.as_str())).expect("the Runtime origin is validated")
+ }
+}
+
+struct HttpEventStream(reqwest::Response);
+
+#[async_trait]
+impl EventStream for HttpEventStream {
+ async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, StreamError> {
+ self.0
+ .chunk()
+ .await
+ .map(|chunk| chunk.map(|chunk| chunk.to_vec()))
+ .map_err(|_| StreamError)
+ }
+}
+
+#[async_trait]
+impl NotificationTransport for HttpNotificationTransport {
+ async fn connect(&self) -> Result<Box<dyn EventStream>, StreamError> {
+ let response = tokio::time::timeout(
+ REQUEST_TIMEOUT,
+ self.client
+ .get(self.url("/api/events"))
+ .header("Accept", "text/event-stream")
+ .send(),
+ )
+ .await
+ .map_err(|_| StreamError)?
+ .map_err(|_| StreamError)?;
+ let content_type = response
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok());
+ if response.status() != reqwest::StatusCode::OK
+ || !content_type.is_some_and(|value| {
+ value
+ .split(';')
+ .next()
+ .is_some_and(|mime| mime.trim() == "text/event-stream")
+ })
+ {
+ return Err(StreamError);
+ }
+ Ok(Box::new(HttpEventStream(response)))
+ }
+
+ async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps> {
+ if matches!(run_id, "" | "." | "..") {
+ return None;
+ }
+ let mut url = self.url("/api/harness/runs/");
+ url.path_segments_mut().ok()?.pop_if_empty().push(run_id);
+ let response = self.client.get(url).timeout(REQUEST_TIMEOUT).send().await.ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ let bytes = bounded_detail_body(response).await?;
+ let detail: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
+ if !detail.get("ok")?.as_bool()? || detail.get("run")?.get("id")?.as_str()? != run_id {
+ return None;
+ }
+ serde_json::from_value(detail.get("run")?.clone()).ok()
+ }
+}
+
+async fn bounded_detail_body(mut response: reqwest::Response) -> Option<Vec<u8>> {
+ if response
+ .content_length()
+ .is_some_and(|size| size > MAX_DETAIL_BYTES as u64)
+ {
+ return None;
+ }
+ let mut body = Vec::new();
+ while let Some(chunk) = response.chunk().await.ok()? {
+ if chunk.len() > MAX_DETAIL_BYTES.saturating_sub(body.len()) {
+ return None;
+ }
+ body.extend_from_slice(&chunk);
+ }
+ Some(body)
+}
+
+#[derive(Default)]
+pub struct ReconnectBackoff {
+ failures: u32,
+}
+
+impl ReconnectBackoff {
+ pub fn next_delay(&mut self) -> Duration {
+ let delay = Duration::from_secs(1u64 << self.failures.min(5)).min(Duration::from_secs(30));
+ self.failures = self.failures.saturating_add(1);
+ delay
+ }
+
+ pub fn reset(&mut self) {
+ self.failures = 0;
+ }
+}
+
+pub async fn run_notifications(
+ transport: &dyn NotificationTransport,
+ filter: Arc<Mutex<NotificationFilter>>,
+ sink: &dyn NotificationSink,
+) {
+ let mut backoff = ReconnectBackoff::default();
+ loop {
+ let connected_at = Instant::now();
+ if let Ok(mut stream) = transport.connect().await {
+ let mut decoder = SseDecoder::new();
+ while let Ok(Ok(Some(chunk))) = tokio::time::timeout(STREAM_IDLE_TIMEOUT, stream.next_chunk()).await {
+ if Instant::now().duration_since(connected_at) >= STREAM_IDLE_TIMEOUT {
+ backoff.reset();
+ }
+ let allowed_at_receipt = sink.gate().allows();
+ let candidates = decoder
+ .push(&chunk)
+ .into_iter()
+ .filter_map(|frame| {
+ filter
+ .lock()
+ .ok()
+ .and_then(|mut filter| filter.consider(frame, Instant::now()))
+ })
+ .collect::<Vec<_>>();
+ for candidate in candidates.into_iter().filter(|_| allowed_at_receipt) {
+ let intent = match candidate {
+ Candidate::Ready(intent) => Some(intent),
+ Candidate::Refetch {
+ run_id,
+ mut stamps,
+ intent,
+ } => {
+ if !sink.gate().allows() {
+ continue;
+ }
+ if let Ok(Some(detail)) =
+ tokio::time::timeout(REQUEST_TIMEOUT, transport.run_timestamps(&run_id)).await
+ {
+ stamps.fill_missing(detail);
+ }
+ stamps.is_long_running().then_some(intent)
+ }
+ };
+ if let Some(intent) = intent.filter(|_| sink.gate().allows()) {
+ sink.deliver(intent);
+ }
+ }
+ }
+ }
+ tokio::time::sleep(backoff.next_delay()).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test(start_paused = true)]
+ async fn both_retained_sets_are_bounded_by_size_and_age_even_without_transition_events() {
+ for keys in [
+ &mut NotificationFilter::default().approvals,
+ &mut NotificationFilter::default().runs,
+ ] {
+ let created = Instant::now();
+ for index in 0..RETAINED_KEYS * 3 {
+ assert!(keys.insert(&index.to_string(), created));
+ assert!(keys.0.len() <= RETAINED_KEYS);
+ }
+ assert_eq!(keys.0.len(), RETAINED_KEYS);
+ assert!(keys.insert("0", created));
+ assert!(!keys.insert("0", created));
+ tokio::time::advance(RETENTION).await;
+ assert!(keys.insert("0", Instant::now()));
+ assert_eq!(keys.0.len(), 1);
+ }
+ }
+}
diff --git a/desktop/runtime-host/src/origin.rs b/desktop/runtime-host/src/origin.rs
new file mode 100644
index 000000000..cae3c67ea
--- /dev/null
+++ b/desktop/runtime-host/src/origin.rs
@@ -0,0 +1,358 @@
+//! Loopback origin resolution and validation.
+//!
+//! The shell navigates its only WebView to whatever this module accepts, so the
+//! accepted set is deliberately tiny: plain `http` on the literal addresses
+//! `127.0.0.1` or `[::1]`, with no credentials, path, query, or fragment.
+//!
+//! The hostname `localhost` is refused even though it is loopback. It resolves
+//! to both `127.0.0.1` and `[::1]` on a normal machine, and the readiness probe and
+//! the WebView resolve it independently — so a probe that succeeded over IPv4
+//! could be followed by a navigation over IPv6 to nothing, since the Runtime
+//! binds one literal address. The shell navigates to exactly the address it
+//! proved healthy.
+
+use std::fmt;
+use std::net::{Ipv4Addr, Ipv6Addr};
+
+use url::{Host, Url};
+
+/// Port of the Vite dev server that serves the bootstrap UI during `npm run tauri dev`.
+/// Must match `desktop/vite.config.ts` and `build.devUrl` in `tauri.conf.json`.
+pub const DEV_SERVER_PORT: u16 = 1420;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum OriginError {
+ #[error("The desktop origin is empty.")]
+ Empty,
+ #[error("The desktop origin is not a valid absolute URL.")]
+ Malformed,
+ #[error("The desktop origin must use http://; https and custom schemes are not accepted.")]
+ UnsupportedScheme,
+ #[error("The desktop origin must be a literal loopback address: 127.0.0.1 or [::1].")]
+ NonLoopbackHost,
+ #[error("The desktop origin must not carry a username or password.")]
+ CredentialsPresent,
+ #[error("The desktop origin must be a bare origin, without a path, query, or fragment.")]
+ NotBareOrigin,
+ #[error("The desktop origin must not be the port reserved for the shell's own UI.")]
+ ShellUiOrigin,
+}
+
+/// A validated loopback origin. Constructing one is the only way to get a URL
+/// the shell is willing to navigate to.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LoopbackOrigin {
+ url: Url,
+ origin: String,
+}
+
+impl LoopbackOrigin {
+ pub fn parse(raw: &str) -> Result<Self, OriginError> {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return Err(OriginError::Empty);
+ }
+
+ let url = Url::parse(trimmed).map_err(|_| OriginError::Malformed)?;
+
+ if url.scheme() != "http" {
+ return Err(OriginError::UnsupportedScheme);
+ }
+ if !url.username().is_empty() || url.password().is_some() {
+ return Err(OriginError::CredentialsPresent);
+ }
+ if !matches!(url.path(), "" | "/") || url.query().is_some() || url.fragment().is_some() {
+ return Err(OriginError::NotBareOrigin);
+ }
+ // `url` follows the WHATWG parser and canonicalizes legacy IPv4 forms:
+ // `127.1`, `2130706433`, and `0x7f000001` all become `127.0.0.1`.
+ // The desktop contract is deliberately narrower, so validate the raw
+ // authority as well as the parsed address.
+ if !has_literal_loopback_authority(trimmed) || !is_loopback_host(&url) {
+ return Err(OriginError::NonLoopbackHost);
+ }
+ // Tauri decides a WebView's ACL origin with `is_local_url`, which counts
+ // any URL relative to `devUrl` as *local*. A Workbench served on the dev
+ // server's port would therefore keep matching the shell's `local: true`
+ // capability after navigation, and the page would keep the bootstrap
+ // commands. Nothing legitimate listens there — Vite owns the port under
+ // `strictPort` — so the whole port is refused, in every build profile,
+ // rather than only in the one where the hazard is reachable.
+ if url.port() == Some(DEV_SERVER_PORT) {
+ return Err(OriginError::ShellUiOrigin);
+ }
+
+ let origin = url.origin().ascii_serialization();
+ Ok(Self { url, origin })
+ }
+
+ /// The canonical origin string handed to the bootstrap UI, e.g. `http://127.0.0.1:5123`.
+ pub fn as_str(&self) -> &str {
+ &self.origin
+ }
+
+ /// Where the shell navigates the WebView once the Runtime is ready.
+ pub fn navigation_url(&self) -> Url {
+ self.url.clone()
+ }
+
+ /// Whether a navigation stays on this exact validated origin.
+ ///
+ /// Paths, queries, and fragments may vary because the Workbench and Show
+ /// Pages route below the same listener. Scheme, address, and port may not.
+ pub fn matches_url_origin(&self, url: &Url) -> bool {
+ url.origin().ascii_serialization() == self.origin
+ }
+
+ /// The combined UI + Controller readiness endpoint.
+ pub fn readiness_url(&self) -> Url {
+ self.url
+ .join("/ready")
+ .expect("/ready is a valid path on a validated origin")
+ }
+}
+
+impl fmt::Display for LoopbackOrigin {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.origin)
+ }
+}
+
+fn is_loopback_host(url: &Url) -> bool {
+ match url.host() {
+ Some(Host::Ipv4(address)) => address == Ipv4Addr::LOCALHOST,
+ Some(Host::Ipv6(address)) => address == Ipv6Addr::LOCALHOST,
+ // Including `localhost`: see the module comment.
+ Some(Host::Domain(_)) | None => false,
+ }
+}
+
+fn has_literal_loopback_authority(raw: &str) -> bool {
+ let Some((_, remainder)) = raw.split_once("://") else {
+ return false;
+ };
+ // A path, query, or fragment has already been rejected. Removing the one
+ // permitted trailing slash leaves only the raw authority.
+ let authority = remainder.strip_suffix('/').unwrap_or(remainder);
+ authority_matches(authority, "127.0.0.1") || authority_matches(authority, "[::1]")
+}
+
+fn authority_matches(authority: &str, host: &str) -> bool {
+ if authority == host {
+ return true;
+ }
+ authority
+ .strip_prefix(host)
+ .and_then(|remainder| remainder.strip_prefix(':'))
+ .is_some_and(|port| !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()))
+}
+
+/// Whether a WebView URL belongs to the shell's own bootstrap page.
+///
+/// Tauri's capability files are the enforcing boundary; this is the second
+/// layer, applied inside every command so that a page loaded from the Workbench
+/// origin cannot reach shell commands even if a capability is later widened by
+/// mistake.
+pub fn is_shell_ui_url(url: &Url) -> bool {
+ let host = url.host();
+ match url.scheme() {
+ // macOS and Linux serve bundled app assets from tauri://localhost.
+ "tauri" => matches!(host, Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost")),
+ "http" => match host {
+ // Windows (WebView2) serves the same assets from http://tauri.localhost.
+ Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("tauri.localhost") => true,
+ // The Vite dev server, in development builds only.
+ Some(Host::Domain(domain)) if cfg!(debug_assertions) && domain.eq_ignore_ascii_case("localhost") => {
+ url.port() == Some(DEV_SERVER_PORT)
+ }
+ _ => false,
+ },
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse(raw: &str) -> Result<LoopbackOrigin, OriginError> {
+ LoopbackOrigin::parse(raw)
+ }
+
+ #[test]
+ fn builds_navigation_and_readiness_urls_from_a_valid_origin() {
+ let origin = parse("http://127.0.0.1:5123").expect("the origin is accepted");
+ assert_eq!(origin.as_str(), "http://127.0.0.1:5123");
+ assert_eq!(origin.readiness_url().as_str(), "http://127.0.0.1:5123/ready");
+ assert_eq!(origin.navigation_url().as_str(), "http://127.0.0.1:5123/");
+ }
+
+ #[test]
+ fn navigation_matching_keeps_every_path_on_the_exact_listener() {
+ let origin = parse("http://127.0.0.1:5123").expect("the origin is accepted");
+ for raw in [
+ "http://127.0.0.1:5123/",
+ "http://127.0.0.1:5123/show/session/",
+ "http://127.0.0.1:5123/?view=chat#latest",
+ ] {
+ let url = Url::parse(raw).expect("test URL parses");
+ assert!(origin.matches_url_origin(&url), "{raw} stays on the listener");
+ }
+ for raw in [
+ "http://127.0.0.1:5124/",
+ "http://127.0.0.2:5123/",
+ "http://192.168.1.10:5123/",
+ "http://[::1]:5123/",
+ "https://127.0.0.1:5123/",
+ "https://avibe.bot/",
+ ] {
+ let url = Url::parse(raw).expect("test URL parses");
+ assert!(!origin.matches_url_origin(&url), "{raw} leaves the listener");
+ }
+ }
+
+ #[test]
+ fn accepts_every_loopback_spelling_in_the_contract() {
+ let cases = [
+ ("http://127.0.0.1:5123", "http://127.0.0.1:5123"),
+ ("http://[::1]:5123", "http://[::1]:5123"),
+ ("http://127.0.0.1", "http://127.0.0.1"),
+ ("http://127.0.0.1:5123/", "http://127.0.0.1:5123"),
+ (" http://127.0.0.1:5123 ", "http://127.0.0.1:5123"),
+ ];
+ for (raw, expected) in cases {
+ let origin = parse(raw).unwrap_or_else(|error| panic!("{raw} should be accepted, got {error}"));
+ assert_eq!(origin.as_str(), expected, "origin string for {raw}");
+ }
+ }
+
+ /// `localhost` is loopback, and is still refused: it names two addresses, and
+ /// the probe and the WebView would each pick one on their own. The shell
+ /// navigates to the address it proved healthy, so it only ever handles
+ /// literal ones.
+ #[test]
+ fn the_hostname_localhost_is_refused_however_it_is_spelled() {
+ for raw in [
+ "http://localhost:5123",
+ "http://localhost",
+ "http://LOCALHOST:5123",
+ "http://localhost.:5123",
+ "http://ip6-localhost:5123",
+ ] {
+ assert_eq!(parse(raw), Err(OriginError::NonLoopbackHost), "origin {raw:?}");
+ }
+ }
+
+ #[test]
+ fn canonicalized_loopback_spellings_are_not_literal_addresses() {
+ for raw in [
+ "http://127.1:5123",
+ "http://2130706433:5123",
+ "http://0x7f000001:5123",
+ "http://017700000001:5123",
+ "http://127.000.000.001:5123",
+ "http://[0:0:0:0:0:0:0:1]:5123",
+ "http://[::0001]:5123",
+ ] {
+ assert_eq!(parse(raw), Err(OriginError::NonLoopbackHost), "origin {raw:?}");
+ }
+ }
+
+ #[test]
+ fn rejects_everything_that_is_not_a_bare_loopback_http_origin() {
+ let cases = [
+ ("", OriginError::Empty),
+ (" ", OriginError::Empty),
+ ("127.0.0.1:5123", OriginError::Malformed),
+ ("not a url", OriginError::Malformed),
+ ("https://127.0.0.1:5123", OriginError::UnsupportedScheme),
+ ("file:///etc/passwd", OriginError::UnsupportedScheme),
+ ("tauri://localhost", OriginError::UnsupportedScheme),
+ ("ws://127.0.0.1:5123", OriginError::UnsupportedScheme),
+ ("http://192.168.1.10:5123", OriginError::NonLoopbackHost),
+ ("http://127.0.0.2:5123", OriginError::NonLoopbackHost),
+ ("http://0.0.0.0:5123", OriginError::NonLoopbackHost),
+ ("http://example.com", OriginError::NonLoopbackHost),
+ ("http://localhost.example.com", OriginError::NonLoopbackHost),
+ ("http://[::2]:5123", OriginError::NonLoopbackHost),
+ ("http://[email protected]:5123", OriginError::CredentialsPresent),
+ ("http://user:[email protected]:5123", OriginError::CredentialsPresent),
+ ("http://127.0.0.1:5123/admin", OriginError::NotBareOrigin),
+ ("http://127.0.0.1:5123/?next=/x", OriginError::NotBareOrigin),
+ ("http://127.0.0.1:5123/#/chat", OriginError::NotBareOrigin),
+ ("http://127.0.0.1:1420", OriginError::ShellUiOrigin),
+ ("http://[::1]:1420", OriginError::ShellUiOrigin),
+ ];
+ for (raw, expected) in cases {
+ assert_eq!(parse(raw), Err(expected), "origin {raw:?}");
+ }
+ }
+
+ #[test]
+ fn rejected_origins_explain_themselves_without_leaking_the_value() {
+ let error = parse("https://example.com").expect_err("https is rejected");
+ let message = error.to_string();
+ assert!(message.contains("http://"), "message should name the accepted scheme");
+ assert!(
+ !message.contains("example.com"),
+ "message must not echo the rejected value"
+ );
+ }
+
+ #[test]
+ fn shell_ui_urls_are_the_bundled_app_and_dev_server_only() {
+ let shell = [
+ "tauri://localhost/index.html",
+ "tauri://localhost",
+ "http://tauri.localhost/index.html",
+ ];
+ for raw in shell {
+ let url = Url::parse(raw).expect("test url parses");
+ assert!(is_shell_ui_url(&url), "{raw} is the shell's own page");
+ }
+
+ let not_shell = [
+ // The Workbench origin: reachable in the same WebView after navigation.
+ "http://127.0.0.1:5123/",
+ "http://127.0.0.1:5123/show/abc/",
+ "https://tauri.localhost/",
+ "http://tauri.localhost.example.com/",
+ "https://avibe.bot/",
+ "file:///index.html",
+ ];
+ for raw in not_shell {
+ let url = Url::parse(raw).expect("test url parses");
+ assert!(!is_shell_ui_url(&url), "{raw} must not reach shell commands");
+ }
+ }
+
+ #[test]
+ fn the_vite_dev_server_is_shell_ui_only_in_development_builds() {
+ let url = Url::parse(&format!("http://localhost:{DEV_SERVER_PORT}/")).expect("dev url parses");
+ assert_eq!(is_shell_ui_url(&url), cfg!(debug_assertions));
+
+ // A different loopback port is never the shell, in either build profile.
+ let other = Url::parse("http://localhost:5123/").expect("test url parses");
+ assert!(!is_shell_ui_url(&other));
+ }
+
+ /// The port the shell's own UI is served from is the one loopback port a
+ /// Runtime must never be reached at: a page there would be classified as
+ /// *local* by Tauri and would keep the bootstrap commands after navigation.
+ /// The refusal is unconditional, so a release build cannot be the only thing
+ /// standing between a misconfigured origin and a privileged Workbench.
+ #[test]
+ fn the_shells_own_port_is_refused_in_every_build_profile() {
+ for host in ["127.0.0.1", "[::1]"] {
+ let raw = format!("http://{host}:{DEV_SERVER_PORT}");
+ assert_eq!(parse(&raw), Err(OriginError::ShellUiOrigin), "origin {raw:?}");
+
+ // Neighbouring ports stay perfectly acceptable: it is one reserved
+ // port, not a range.
+ for port in [DEV_SERVER_PORT - 1, DEV_SERVER_PORT + 1] {
+ let neighbour = format!("http://{host}:{port}");
+ assert!(parse(&neighbour).is_ok(), "origin {neighbour:?} should be accepted");
+ }
+ }
+ }
+}
diff --git a/desktop/runtime-host/src/private_runtime.rs b/desktop/runtime-host/src/private_runtime.rs
new file mode 100644
index 000000000..a045c3ad7
--- /dev/null
+++ b/desktop/runtime-host/src/private_runtime.rs
@@ -0,0 +1,987 @@
+//! Verification and atomic installation of the app-private Avibe Runtime.
+//!
+//! Product packages carry one target-specific ZIP plus an embedded manifest.
+//! Production trust comes from the desktop application's code signature; the
+//! first launch then verifies the archive before extracting it into a versioned
+//! user-data directory. The application bundle is never mutated, and an update
+//! can install a successor without replacing files used by a running daemon.
+
+use std::fs::{self, File, OpenOptions};
+use std::io::{self, Read, Write};
+use std::path::{Component, Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use zip::ZipArchive;
+
+const MANIFEST_NAME: &str = "runtime-manifest.json";
+const INSTALL_MARKER_NAME: &str = ".avibe-runtime.json";
+const MAX_MANIFEST_BYTES: u64 = 32 * 1024;
+const MAX_ARCHIVE_BYTES: u64 = 1024 * 1024 * 1024;
+const MAX_UNPACKED_BYTES: u64 = 2 * 1024 * 1024 * 1024;
+const MAX_ARCHIVE_ENTRIES: u64 = 200_000;
+const TREE_HASH_DOMAIN: &[u8] = b"avibe-runtime-tree-v1\0";
+static INSTALL_SEQUENCE: AtomicU64 = AtomicU64::new(0);
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RuntimeBundleManifest {
+ pub schema_version: u32,
+ pub runtime_version: String,
+ pub os: String,
+ pub arch: String,
+ pub archive: String,
+ pub archive_sha256: String,
+ pub archive_size: u64,
+ pub unpacked_size: u64,
+ pub entry_count: u64,
+ pub tree_sha256: String,
+ pub python_entrypoint: String,
+ pub node_entrypoint: String,
+ pub npm_entrypoint: String,
+ pub python_distribution: RuntimeSource,
+ pub node_distribution: RuntimeSource,
+ pub npm_version: String,
+ pub avibe_wheel: RuntimeArtifact,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RuntimeSource {
+ pub url: String,
+ pub sha256: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RuntimeArtifact {
+ pub name: String,
+ pub sha256: String,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PrivateRuntimeError {
+ #[error("the bundled Runtime manifest is unavailable")]
+ ManifestUnavailable(#[source] io::Error),
+ #[error("the bundled Runtime manifest is invalid")]
+ ManifestInvalid,
+ #[error("the bundled Runtime targets another platform")]
+ TargetMismatch,
+ #[error("the bundled Runtime archive is unavailable")]
+ ArchiveUnavailable(#[source] io::Error),
+ #[error("the bundled Runtime archive failed verification")]
+ ArchiveVerification,
+ #[error("the bundled Runtime archive is invalid")]
+ ArchiveInvalid,
+ #[error("the private Runtime could not be installed")]
+ Install(#[source] io::Error),
+}
+
+#[derive(Debug, Clone)]
+pub struct InstalledPrivateRuntime {
+ pub root: PathBuf,
+ pub python: PathBuf,
+ pub node: PathBuf,
+ pub npm_cli: PathBuf,
+ pub runtime_id: String,
+ /// True when `prepare()` found this tree already installed and valid.
+ ///
+ /// False means this launch paid to extract it. The distinction is invisible
+ /// to the user and decides how long the first Runtime call will take, so it
+ /// is the fact the bootstrap log exists to record: an install that reports
+ /// `extracted` on every launch is invalidating itself between launches.
+ pub reused: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct PrivateRuntimeBundle {
+ bundle_dir: PathBuf,
+ install_root: PathBuf,
+}
+
+impl PrivateRuntimeBundle {
+ pub fn new(bundle_dir: PathBuf, install_root: PathBuf) -> Self {
+ Self {
+ bundle_dir,
+ install_root,
+ }
+ }
+
+ pub fn prepare(&self) -> Result<InstalledPrivateRuntime, PrivateRuntimeError> {
+ let manifest = self.read_manifest()?;
+ validate_manifest(&manifest)?;
+
+ let digest_prefix = manifest
+ .archive_sha256
+ .get(..16)
+ .ok_or(PrivateRuntimeError::ManifestInvalid)?;
+ let version_dir = self.install_root.join(&manifest.runtime_version);
+ let primary_dir = version_dir.join(digest_prefix);
+ let repair_dir = version_dir.join(format!("{digest_prefix}-repair"));
+ for candidate in [&primary_dir, &repair_dir] {
+ if path_present(candidate) {
+ if let Ok(runtime) = installed_runtime(candidate, &manifest) {
+ return Ok(InstalledPrivateRuntime {
+ reused: true,
+ ..runtime
+ });
+ }
+ }
+ }
+
+ let archive_path = self.bundle_dir.join(&manifest.archive);
+ verify_archive(&archive_path, &manifest)?;
+ fs::create_dir_all(&self.install_root).map_err(PrivateRuntimeError::Install)?;
+ let install_dir = if !path_present(&primary_dir) {
+ primary_dir
+ } else if !path_present(&repair_dir) {
+ repair_dir
+ } else {
+ // Both independently installed copies failed integrity validation.
+ // Never execute either one — but refusing here is a dead end with no
+ // way out except deleting a directory by hand, and two copies is not
+ // a large enough margin to strand an install on.
+ //
+ // The reason the old code refused still holds: a daemon started from
+ // a copy that was valid at launch may have its files open, and a tree
+ // partially replaced underneath a running process is worse than the
+ // failure that got us here. Renaming is what satisfies both. It frees
+ // the name atomically without touching a single file the daemon
+ // holds, so the reinstall below lands on a name nothing can be
+ // reading, and the count of installed copies stays at two.
+ discard_install_path(&self.install_root, &primary_dir)?;
+ primary_dir
+ };
+
+ let sequence = INSTALL_SEQUENCE.fetch_add(1, Ordering::SeqCst);
+ let staging = self
+ .install_root
+ .join(format!(".install-{}-{sequence}", std::process::id()));
+ if staging.exists() {
+ fs::remove_dir_all(&staging).map_err(PrivateRuntimeError::Install)?;
+ }
+ fs::create_dir(&staging).map_err(PrivateRuntimeError::Install)?;
+
+ let install_result = (|| {
+ extract_archive(&archive_path, &staging, &manifest)?;
+ validate_runtime_files(&staging, &manifest)?;
+ verify_installed_tree(&staging, &manifest)?;
+ write_marker(&staging, &manifest)?;
+ if let Some(parent) = install_dir.parent() {
+ fs::create_dir_all(parent).map_err(PrivateRuntimeError::Install)?;
+ }
+ match fs::rename(&staging, &install_dir) {
+ Ok(()) => {}
+ Err(error) => {
+ // Windows and Unix report different error kinds when
+ // another process wins this content-addressed install.
+ // Accept the race only after validating the winner.
+ if installed_runtime(&install_dir, &manifest).is_ok() {
+ fs::remove_dir_all(&staging).map_err(PrivateRuntimeError::Install)?;
+ } else {
+ return Err(PrivateRuntimeError::Install(error));
+ }
+ }
+ }
+ installed_runtime(&install_dir, &manifest)
+ })();
+
+ if staging.exists() {
+ let _ = fs::remove_dir_all(&staging);
+ }
+ install_result
+ }
+
+ /// Removes private Runtime trees that are no longer used by the active
+ /// desktop-managed daemon.
+ ///
+ /// The caller invokes this only after `/ready` proves that `active_root` is
+ /// the Runtime currently serving the desktop shell. Cleanup is deliberately
+ /// outside `prepare`: an older daemon may still have its executable tree
+ /// open while the successor is being installed.
+ pub fn prune_superseded(&self, active_root: &Path) -> Result<(), PrivateRuntimeError> {
+ let active_version = active_root
+ .parent()
+ .filter(|parent| parent.parent() == Some(self.install_root.as_path()))
+ .ok_or(PrivateRuntimeError::Install(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "active Runtime is outside the private install root",
+ )))?;
+
+ let entries = match fs::read_dir(&self.install_root) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(PrivateRuntimeError::Install(error)),
+ };
+ for entry in entries {
+ let path = entry.map_err(PrivateRuntimeError::Install)?.path();
+ if path == active_version {
+ for candidate in fs::read_dir(&path).map_err(PrivateRuntimeError::Install)? {
+ let candidate = candidate.map_err(PrivateRuntimeError::Install)?.path();
+ if candidate != active_root {
+ remove_install_path(&candidate)?;
+ }
+ }
+ } else {
+ remove_install_path(&path)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Removes every app-private Runtime install while leaving Avibe user state
+ /// untouched. The caller must first complete a graceful `vibe stop`.
+ pub fn remove_all(&self) -> Result<(), PrivateRuntimeError> {
+ let metadata = match fs::symlink_metadata(&self.install_root) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(PrivateRuntimeError::Install(error)),
+ };
+ if !metadata.file_type().is_dir() || metadata.file_type().is_symlink() {
+ return Err(PrivateRuntimeError::Install(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "private Runtime install root is not a directory",
+ )));
+ }
+ fs::remove_dir_all(&self.install_root).map_err(PrivateRuntimeError::Install)
+ }
+
+ fn read_manifest(&self) -> Result<RuntimeBundleManifest, PrivateRuntimeError> {
+ let path = self.bundle_dir.join(MANIFEST_NAME);
+ let file = File::open(path).map_err(PrivateRuntimeError::ManifestUnavailable)?;
+ let mut bytes = Vec::new();
+ file.take(MAX_MANIFEST_BYTES + 1)
+ .read_to_end(&mut bytes)
+ .map_err(PrivateRuntimeError::ManifestUnavailable)?;
+ if bytes.len() > MAX_MANIFEST_BYTES as usize {
+ return Err(PrivateRuntimeError::ManifestInvalid);
+ }
+ serde_json::from_slice(&bytes).map_err(|_| PrivateRuntimeError::ManifestInvalid)
+ }
+}
+
+fn validate_manifest(manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {
+ if manifest.schema_version != 2
+ || !safe_segment(&manifest.runtime_version)
+ || !safe_file_name(&manifest.archive)
+ || !valid_sha256(&manifest.archive_sha256)
+ || manifest.archive_size == 0
+ || manifest.archive_size > MAX_ARCHIVE_BYTES
+ || manifest.unpacked_size == 0
+ || manifest.unpacked_size > MAX_UNPACKED_BYTES
+ || manifest.entry_count == 0
+ || manifest.entry_count > MAX_ARCHIVE_ENTRIES
+ || !valid_sha256(&manifest.tree_sha256)
+ || !valid_relative_path(&manifest.python_entrypoint)
+ || !valid_relative_path(&manifest.node_entrypoint)
+ || !valid_relative_path(&manifest.npm_entrypoint)
+ || !valid_sha256(&manifest.python_distribution.sha256)
+ || !valid_sha256(&manifest.node_distribution.sha256)
+ || !valid_sha256(&manifest.avibe_wheel.sha256)
+ || manifest.python_distribution.url.is_empty()
+ || manifest.node_distribution.url.is_empty()
+ || manifest.npm_version.is_empty()
+ || !safe_file_name(&manifest.avibe_wheel.name)
+ {
+ return Err(PrivateRuntimeError::ManifestInvalid);
+ }
+ if manifest.os != current_os() || manifest.arch != current_arch() {
+ return Err(PrivateRuntimeError::TargetMismatch);
+ }
+ Ok(())
+}
+
+fn current_os() -> &'static str {
+ std::env::consts::OS
+}
+
+fn current_arch() -> &'static str {
+ std::env::consts::ARCH
+}
+
+fn safe_segment(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 128
+ && value
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-'))
+}
+
+fn safe_file_name(value: &str) -> bool {
+ safe_segment(value) && Path::new(value).file_name().is_some_and(|name| name == value)
+}
+
+fn valid_sha256(value: &str) -> bool {
+ value.len() == 64
+ && value
+ .bytes()
+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+}
+
+fn valid_relative_path(value: &str) -> bool {
+ let path = Path::new(value);
+ !value.is_empty()
+ && !path.is_absolute()
+ && path
+ .components()
+ .all(|component| matches!(component, Component::Normal(_)))
+}
+
+fn path_present(path: &Path) -> bool {
+ fs::symlink_metadata(path).is_ok()
+}
+
+/// Moves an installed copy aside so its name can be reused.
+///
+/// Deleting in place is what this avoids. `remove_dir_all` on a tree a running
+/// Runtime is executing from succeeds on Unix and fails partway through on
+/// Windows, where a mapped executable cannot be unlinked — and a half-deleted
+/// tree under a live process is a worse state than the invalid one it replaced.
+/// A rename either moves the whole thing or moves none of it, and the open
+/// handles a daemon holds keep working across it.
+///
+/// The discarded copy is then removed on a best-effort basis: it is already
+/// unreachable by name, and `prune_superseded` sweeps whatever is left after
+/// the next successful launch.
+fn discard_install_path(install_root: &Path, path: &Path) -> Result<(), PrivateRuntimeError> {
+ let sequence = INSTALL_SEQUENCE.fetch_add(1, Ordering::SeqCst);
+ let discarded = install_root.join(format!(".discard-{}-{sequence}", std::process::id()));
+ // A machine that cannot even rename the directory reports what it reported
+ // before this became recoverable, rather than pretending it installed.
+ fs::rename(path, &discarded).map_err(|_| PrivateRuntimeError::ArchiveVerification)?;
+ let _ = fs::remove_dir_all(&discarded);
+ Ok(())
+}
+
+fn remove_install_path(path: &Path) -> Result<(), PrivateRuntimeError> {
+ let metadata = fs::symlink_metadata(path).map_err(PrivateRuntimeError::Install)?;
+ if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() {
+ fs::remove_dir_all(path).map_err(PrivateRuntimeError::Install)
+ } else {
+ fs::remove_file(path).map_err(PrivateRuntimeError::Install)
+ }
+}
+
+fn verify_archive(path: &Path, manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {
+ let metadata = fs::metadata(path).map_err(PrivateRuntimeError::ArchiveUnavailable)?;
+ if !metadata.is_file() || metadata.len() != manifest.archive_size {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+
+ let mut file = File::open(path).map_err(PrivateRuntimeError::ArchiveUnavailable)?;
+ let mut hasher = Sha256::new();
+ io::copy(&mut file, &mut hasher).map_err(PrivateRuntimeError::ArchiveUnavailable)?;
+ let actual = format!("{:x}", hasher.finalize());
+ if actual != manifest.archive_sha256 {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+ Ok(())
+}
+
+fn extract_archive(
+ archive_path: &Path,
+ destination: &Path,
+ manifest: &RuntimeBundleManifest,
+) -> Result<(), PrivateRuntimeError> {
+ let file = File::open(archive_path).map_err(PrivateRuntimeError::ArchiveUnavailable)?;
+ let mut archive = ZipArchive::new(file).map_err(|_| PrivateRuntimeError::ArchiveInvalid)?;
+ if archive.len() as u64 != manifest.entry_count {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+
+ let mut unpacked = 0_u64;
+ for index in 0..archive.len() {
+ let mut entry = archive
+ .by_index(index)
+ .map_err(|_| PrivateRuntimeError::ArchiveInvalid)?;
+ unpacked = unpacked
+ .checked_add(entry.size())
+ .filter(|value| *value <= manifest.unpacked_size)
+ .ok_or(PrivateRuntimeError::ArchiveInvalid)?;
+ let relative = entry
+ .enclosed_name()
+ .filter(|path| path.components().all(|part| matches!(part, Component::Normal(_))))
+ .ok_or(PrivateRuntimeError::ArchiveInvalid)?;
+ if entry.unix_mode().is_some_and(|mode| mode & 0o170_000 == 0o120_000) {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+
+ let output = destination.join(relative);
+ if entry.is_dir() {
+ fs::create_dir_all(&output).map_err(PrivateRuntimeError::Install)?;
+ continue;
+ }
+ if let Some(parent) = output.parent() {
+ fs::create_dir_all(parent).map_err(PrivateRuntimeError::Install)?;
+ }
+ let mut target = OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&output)
+ .map_err(PrivateRuntimeError::Install)?;
+ io::copy(&mut entry, &mut target).map_err(PrivateRuntimeError::Install)?;
+ target.flush().map_err(PrivateRuntimeError::Install)?;
+ set_entry_permissions(&output, entry.unix_mode())?;
+ }
+ if unpacked != manifest.unpacked_size {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+ Ok(())
+}
+
+#[cfg(unix)]
+fn set_entry_permissions(path: &Path, mode: Option<u32>) -> Result<(), PrivateRuntimeError> {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = mode.ok_or(PrivateRuntimeError::ArchiveInvalid)? & 0o777;
+ fs::set_permissions(path, fs::Permissions::from_mode(mode)).map_err(PrivateRuntimeError::Install)
+}
+
+#[cfg(not(unix))]
+fn set_entry_permissions(_path: &Path, _mode: Option<u32>) -> Result<(), PrivateRuntimeError> {
+ Ok(())
+}
+
+fn validate_runtime_files(root: &Path, manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {
+ for (relative, must_be_executable) in required_runtime_files(manifest) {
+ let path = root.join(relative);
+ let metadata = fs::symlink_metadata(path).map_err(PrivateRuntimeError::Install)?;
+ if !metadata.file_type().is_file() {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+ #[cfg(not(unix))]
+ let _ = must_be_executable;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if must_be_executable && metadata.permissions().mode() & 0o111 == 0 {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+ }
+ }
+ Ok(())
+}
+
+fn required_runtime_files(manifest: &RuntimeBundleManifest) -> [(PathBuf, bool); 3] {
+ [
+ (PathBuf::from(&manifest.python_entrypoint), true),
+ (PathBuf::from(&manifest.node_entrypoint), true),
+ (PathBuf::from(&manifest.npm_entrypoint), false),
+ ]
+}
+
+fn verify_installed_tree(root: &Path, manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {
+ let root_metadata = fs::symlink_metadata(root).map_err(PrivateRuntimeError::Install)?;
+ if !root_metadata.file_type().is_dir() {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+
+ let mut files = Vec::new();
+ collect_tree_files(root, root, &mut files)?;
+ files.sort_by(|left, right| left.0.cmp(&right.0));
+
+ let mut hasher = Sha256::new();
+ hasher.update(TREE_HASH_DOMAIN);
+ let mut unpacked_size = 0_u64;
+ for (relative, path, size) in &files {
+ unpacked_size = unpacked_size
+ .checked_add(*size)
+ .filter(|value| *value <= manifest.unpacked_size)
+ .ok_or(PrivateRuntimeError::ArchiveVerification)?;
+ update_tree_header(&mut hasher, relative, *size);
+ let mut file = File::open(path).map_err(PrivateRuntimeError::Install)?;
+ io::copy(&mut file, &mut hasher).map_err(PrivateRuntimeError::Install)?;
+ }
+ if files.len() as u64 != manifest.entry_count || unpacked_size != manifest.unpacked_size {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+ let actual = format!("{:x}", hasher.finalize());
+ if actual != manifest.tree_sha256 {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+ Ok(())
+}
+
+fn collect_tree_files(
+ root: &Path,
+ directory: &Path,
+ files: &mut Vec<(String, PathBuf, u64)>,
+) -> Result<(), PrivateRuntimeError> {
+ for entry in fs::read_dir(directory).map_err(PrivateRuntimeError::Install)? {
+ let entry = entry.map_err(PrivateRuntimeError::Install)?;
+ let path = entry.path();
+ let metadata = fs::symlink_metadata(&path).map_err(PrivateRuntimeError::Install)?;
+ let file_type = metadata.file_type();
+ if file_type.is_symlink() {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+ if file_type.is_dir() {
+ collect_tree_files(root, &path, files)?;
+ continue;
+ }
+ if !file_type.is_file() {
+ return Err(PrivateRuntimeError::ArchiveVerification);
+ }
+ let relative_path = path
+ .strip_prefix(root)
+ .map_err(|_| PrivateRuntimeError::ArchiveVerification)?;
+ if relative_path == Path::new(INSTALL_MARKER_NAME) {
+ continue;
+ }
+ let relative = portable_relative_path(relative_path)?;
+ files.push((relative, path, metadata.len()));
+ }
+ Ok(())
+}
+
+fn portable_relative_path(path: &Path) -> Result<String, PrivateRuntimeError> {
+ path.components()
+ .map(|component| match component {
+ Component::Normal(value) => value.to_str().ok_or(PrivateRuntimeError::ArchiveVerification),
+ _ => Err(PrivateRuntimeError::ArchiveVerification),
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .map(|parts| parts.join("/"))
+}
+
+fn update_tree_header(hasher: &mut Sha256, relative: &str, size: u64) {
+ let relative = relative.as_bytes();
+ hasher.update((relative.len() as u64).to_be_bytes());
+ hasher.update(relative);
+ hasher.update(size.to_be_bytes());
+}
+
+fn write_marker(root: &Path, manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {
+ let bytes = serde_json::to_vec(manifest).map_err(|_| PrivateRuntimeError::ManifestInvalid)?;
+ let marker = root.join(INSTALL_MARKER_NAME);
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(marker)
+ .map_err(PrivateRuntimeError::Install)?;
+ file.write_all(&bytes).map_err(PrivateRuntimeError::Install)?;
+ file.sync_all().map_err(PrivateRuntimeError::Install)
+}
+
+fn installed_runtime(
+ root: &Path,
+ manifest: &RuntimeBundleManifest,
+) -> Result<InstalledPrivateRuntime, PrivateRuntimeError> {
+ let marker = fs::read(root.join(INSTALL_MARKER_NAME)).map_err(PrivateRuntimeError::Install)?;
+ let installed: RuntimeBundleManifest =
+ serde_json::from_slice(&marker).map_err(|_| PrivateRuntimeError::ArchiveInvalid)?;
+ if &installed != manifest {
+ return Err(PrivateRuntimeError::ArchiveInvalid);
+ }
+ validate_runtime_files(root, manifest)?;
+ verify_installed_tree(root, manifest)?;
+ Ok(InstalledPrivateRuntime {
+ root: root.to_owned(),
+ python: root.join(&manifest.python_entrypoint),
+ node: root.join(&manifest.node_entrypoint),
+ npm_cli: root.join(&manifest.npm_entrypoint),
+ runtime_id: manifest.archive_sha256.clone(),
+ // Validating a tree says nothing about who put it there. Only the reuse
+ // scan in `prepare()` knows it did not extract this one.
+ reused: false,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+ use zip::write::SimpleFileOptions;
+ use zip::{CompressionMethod, ZipWriter};
+
+ fn scratch(label: &str) -> PathBuf {
+ let sequence = INSTALL_SEQUENCE.fetch_add(1, Ordering::SeqCst);
+ let path = std::env::temp_dir().join(format!(
+ "avibe-private-runtime-{label}-{}-{sequence}",
+ std::process::id()
+ ));
+ fs::create_dir_all(&path).expect("scratch directory");
+ path
+ }
+
+ fn entrypoints() -> (&'static str, &'static str, &'static str) {
+ if cfg!(windows) {
+ ("python/python.exe", "tools/bin/node.exe", "tools/npm/bin/npm-cli.js")
+ } else {
+ ("python/bin/python3", "tools/bin/node", "tools/npm/bin/npm-cli.js")
+ }
+ }
+
+ fn write_bundle(root: &Path, extra_entry: Option<&str>) -> RuntimeBundleManifest {
+ let bundle = root.join("bundle");
+ fs::create_dir_all(&bundle).expect("bundle directory");
+ let archive_path = bundle.join("runtime.zip");
+ let archive_file = File::create(&archive_path).expect("archive");
+ let mut zip = ZipWriter::new(archive_file);
+ let executable_options = SimpleFileOptions::default()
+ .compression_method(CompressionMethod::Deflated)
+ .unix_permissions(0o755);
+ let data_options = SimpleFileOptions::default()
+ .compression_method(CompressionMethod::Deflated)
+ .unix_permissions(0o644);
+ let (python, node, npm_cli) = entrypoints();
+ let mut unpacked_size = 0_u64;
+ let mut entry_count = 0_u64;
+ let entries: Vec<_> = [python, node, npm_cli].into_iter().chain(extra_entry).collect();
+ for name in &entries {
+ let options = if *name == npm_cli {
+ data_options
+ } else {
+ executable_options
+ };
+ zip.start_file(name, options).expect("zip entry");
+ zip.write_all(b"runtime").expect("zip bytes");
+ unpacked_size += 7;
+ entry_count += 1;
+ }
+ zip.finish().expect("zip finished");
+
+ let mut tree_entries = entries;
+ tree_entries.sort_unstable();
+ let mut tree_hasher = Sha256::new();
+ tree_hasher.update(TREE_HASH_DOMAIN);
+ for name in tree_entries {
+ update_tree_header(&mut tree_hasher, name, 7);
+ tree_hasher.update(b"runtime");
+ }
+ let bytes = fs::read(&archive_path).expect("archive bytes");
+ let manifest = RuntimeBundleManifest {
+ schema_version: 2,
+ runtime_version: "3.0.0-test".to_owned(),
+ os: current_os().to_owned(),
+ arch: current_arch().to_owned(),
+ archive: "runtime.zip".to_owned(),
+ archive_sha256: format!("{:x}", Sha256::digest(&bytes)),
+ archive_size: bytes.len() as u64,
+ unpacked_size,
+ entry_count,
+ tree_sha256: format!("{:x}", tree_hasher.finalize()),
+ python_entrypoint: python.to_owned(),
+ node_entrypoint: node.to_owned(),
+ npm_entrypoint: npm_cli.to_owned(),
+ python_distribution: RuntimeSource {
+ url: "https://example.invalid/python".to_owned(),
+ sha256: "a".repeat(64),
+ },
+ node_distribution: RuntimeSource {
+ url: "https://example.invalid/node".to_owned(),
+ sha256: "b".repeat(64),
+ },
+ npm_version: "10.9.8".to_owned(),
+ avibe_wheel: RuntimeArtifact {
+ name: "avibe_os-3.0.0-py3-none-any.whl".to_owned(),
+ sha256: "c".repeat(64),
+ },
+ };
+ fs::write(
+ bundle.join(MANIFEST_NAME),
+ serde_json::to_vec(&manifest).expect("manifest JSON"),
+ )
+ .expect("manifest");
+ manifest
+ }
+
+ #[test]
+ fn installs_once_into_a_versioned_content_addressed_directory() {
+ let root = scratch("install");
+ let manifest = write_bundle(&root, None);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+
+ let first = bundle.prepare().expect("first install");
+ let second = bundle.prepare().expect("existing install");
+
+ assert_eq!(first.root, second.root);
+ // The distinction the bootstrap log is built to record. An install that
+ // keeps reporting `extracted` is invalidating itself between launches,
+ // and every launch then pays a cold tree's start-up cost.
+ assert!(!first.reused, "the first launch extracted this tree");
+ assert!(second.reused, "the second launch must not extract it again");
+ assert!(first.root.ends_with(&manifest.archive_sha256[..16]));
+ assert!(first.python.is_file());
+ assert!(first.node.is_file());
+ assert!(first.npm_cli.is_file());
+ assert_eq!(
+ fs::read_dir(root.join("installs").join(&manifest.runtime_version))
+ .expect("version directory")
+ .count(),
+ 1
+ );
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn rejects_an_archive_that_does_not_match_the_signed_manifest() {
+ let root = scratch("digest");
+ write_bundle(&root, None);
+ let archive = root.join("bundle/runtime.zip");
+ fs::OpenOptions::new()
+ .append(true)
+ .open(&archive)
+ .expect("archive")
+ .write_all(b"tampered")
+ .expect("tamper");
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+
+ assert!(matches!(
+ bundle.prepare(),
+ Err(PrivateRuntimeError::ArchiveVerification)
+ ));
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn a_tampered_install_is_never_reused_and_repairs_once() {
+ let root = scratch("installed-tamper");
+ let manifest = write_bundle(&root, None);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+ let first = bundle.prepare().expect("first install");
+ fs::write(&first.python, b"tampered").expect("tamper installed interpreter");
+
+ let repaired = bundle.prepare().expect("repair install");
+
+ assert_ne!(repaired.root, first.root);
+ assert!(repaired
+ .root
+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])));
+ assert_eq!(fs::read(&repaired.python).expect("repaired interpreter"), b"runtime");
+ assert_eq!(bundle.prepare().expect("reuse repair").root, repaired.root);
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_runtime_with_a_non_executable_entrypoint_is_repaired() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let root = scratch("installed-mode-tamper");
+ let manifest = write_bundle(&root, None);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+ let first = bundle.prepare().expect("first install");
+ fs::set_permissions(&first.python, fs::Permissions::from_mode(0o644)).expect("remove execute bits");
+
+ let repaired = bundle.prepare().expect("repair install");
+
+ assert_ne!(repaired.root, first.root);
+ assert!(repaired
+ .root
+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])));
+ assert_ne!(
+ fs::metadata(&repaired.python)
+ .expect("repaired metadata")
+ .permissions()
+ .mode()
+ & 0o111,
+ 0
+ );
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn npm_cli_does_not_need_an_executable_mode() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let root = scratch("npm-cli-mode");
+ write_bundle(&root, None);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+ let installed = bundle.prepare().expect("Runtime with npm CLI installs");
+
+ assert_eq!(
+ fs::metadata(&installed.npm_cli)
+ .expect("npm CLI metadata")
+ .permissions()
+ .mode()
+ & 0o111,
+ 0
+ );
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn a_tampered_npm_cli_is_never_reused() {
+ let root = scratch("installed-npm-tamper");
+ let manifest = write_bundle(&root, None);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+ let first = bundle.prepare().expect("first install");
+ fs::write(&first.npm_cli, b"tampered").expect("tamper installed npm CLI");
+
+ let repaired = bundle.prepare().expect("repair install");
+
+ assert_ne!(repaired.root, first.root);
+ assert!(repaired
+ .root
+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])));
+ assert_eq!(fs::read(&repaired.npm_cli).expect("repaired npm CLI"), b"runtime");
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn superseded_installs_are_pruned_only_after_an_active_runtime_is_selected() {
+ let root = scratch("prune");
+ let manifest = write_bundle(&root, None);
+ let install_root = root.join("installs");
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), install_root.clone());
+ let active = bundle.prepare().expect("active install");
+ let sibling = active
+ .root
+ .with_file_name(format!("{}-repair", &manifest.archive_sha256[..16]));
+ fs::create_dir_all(&sibling).expect("sibling install");
+ fs::write(sibling.join("unused"), b"unused").expect("sibling file");
+ let old = install_root.join("2.9.0").join("old-digest");
+ fs::create_dir_all(&old).expect("old install");
+ fs::write(old.join("unused"), b"unused").expect("old file");
+ let staging = install_root.join(".install-abandoned");
+ fs::create_dir_all(&staging).expect("staging install");
+
+ bundle.prune_superseded(&active.root).expect("prune succeeds");
+
+ assert!(active.root.is_dir());
+ assert!(!sibling.exists());
+ assert!(!old.exists());
+ assert!(!staging.exists());
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn explicit_removal_deletes_only_the_private_runtime_root() {
+ let root = scratch("remove-all");
+ let install_root = root.join("application-data").join("runtime");
+ let user_state = root.join(".avibe");
+ fs::create_dir_all(&install_root).expect("install root");
+ fs::create_dir_all(&user_state).expect("user state");
+ fs::write(install_root.join("private"), b"runtime").expect("private Runtime file");
+ fs::write(user_state.join("config.json"), b"user state").expect("user state file");
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), install_root.clone());
+
+ bundle.remove_all().expect("private Runtime removal");
+
+ assert!(!install_root.exists());
+ assert_eq!(
+ fs::read(user_state.join("config.json")).expect("preserved user state"),
+ b"user state"
+ );
+ fs::remove_dir_all(root).ok();
+ }
+
+ /// Both slots invalid used to be terminal: the user's only way out was
+ /// deleting a directory by hand. Nothing here relaxes verification — a
+ /// tampered tree is still never executed — but the recovery is a reinstall
+ /// from the verified archive rather than a refusal, and it repeats.
+ #[test]
+ fn two_tampered_install_slots_are_reinstalled_rather_than_stranded() {
+ let root = scratch("installed-double-tamper");
+ let manifest = write_bundle(&root, None);
+ let install_root = root.join("installs");
+ let version_dir = install_root.join(&manifest.runtime_version);
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), install_root.clone());
+
+ let primary = bundle.prepare().expect("primary install");
+ fs::write(&primary.python, b"tampered").expect("tamper primary");
+ let repair = bundle.prepare().expect("repair install");
+ fs::write(&repair.node, b"tampered").expect("tamper repair");
+ assert_ne!(primary.root, repair.root, "the two slots are distinct copies");
+
+ // Three rounds, because a single escape hatch that only works once is
+ // still a dead end for the second mutation.
+ for round in 0..3 {
+ let recovered = bundle.prepare().expect("both slots invalid still recovers");
+ assert!(!recovered.reused, "round {round} reused a tampered tree");
+ assert_eq!(
+ recovered.root, primary.root,
+ "the reinstall takes the freed primary name"
+ );
+ assert_eq!(
+ fs::read(&recovered.python).expect("reinstalled interpreter"),
+ b"runtime"
+ );
+ assert!(
+ bundle.prepare().expect("the recovered install is reusable").reused,
+ "round {round} could not reuse what it had just installed"
+ );
+
+ // Recovery must not grow the install by a copy per failure: the
+ // displaced tree is discarded, not accumulated.
+ let mut installed: Vec<String> = fs::read_dir(&version_dir)
+ .expect("version directory")
+ .map(|entry| entry.expect("entry").file_name().to_string_lossy().into_owned())
+ .collect();
+ installed.sort();
+ assert_eq!(
+ installed,
+ [
+ manifest.archive_sha256[..16].to_owned(),
+ format!("{}-repair", &manifest.archive_sha256[..16]),
+ ],
+ "round {round} left more than the two install slots"
+ );
+ assert_eq!(
+ fs::read_dir(&install_root)
+ .expect("install root")
+ .filter(|entry| {
+ let name = entry.as_ref().expect("entry").file_name();
+ name.to_string_lossy().starts_with(".discard-")
+ })
+ .count(),
+ 0,
+ "round {round} left a discarded copy behind"
+ );
+
+ // Set up the next round from the state this one produced: the repair
+ // slot is still tampered, so only the primary has to be re-broken.
+ fs::write(&recovered.python, b"tampered").expect("tamper for the next round");
+ }
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn rejects_path_traversal_before_any_file_can_escape() {
+ let root = scratch("traversal");
+ write_bundle(&root, Some("../escape"));
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+
+ assert!(matches!(bundle.prepare(), Err(PrivateRuntimeError::ArchiveInvalid)));
+ assert!(!root.join("escape").exists());
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn rejects_a_manifest_for_another_architecture() {
+ let root = scratch("target");
+ let mut manifest = write_bundle(&root, None);
+ manifest.arch = if current_arch() == "aarch64" {
+ "x86_64".to_owned()
+ } else {
+ "aarch64".to_owned()
+ };
+ fs::write(
+ root.join("bundle").join(MANIFEST_NAME),
+ serde_json::to_vec(&manifest).expect("manifest JSON"),
+ )
+ .expect("manifest");
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+
+ assert!(matches!(bundle.prepare(), Err(PrivateRuntimeError::TargetMismatch)));
+ fs::remove_dir_all(root).ok();
+ }
+
+ #[test]
+ fn rejects_the_legacy_runtime_manifest_schema() {
+ let root = scratch("schema-one");
+ let mut manifest = write_bundle(&root, None);
+ manifest.schema_version = 1;
+ fs::write(
+ root.join("bundle").join(MANIFEST_NAME),
+ serde_json::to_vec(&manifest).expect("manifest JSON"),
+ )
+ .expect("manifest");
+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));
+
+ assert!(matches!(bundle.prepare(), Err(PrivateRuntimeError::ManifestInvalid)));
+ fs::remove_dir_all(root).ok();
+ }
+}
diff --git a/desktop/runtime-host/src/status.rs b/desktop/runtime-host/src/status.rs
new file mode 100644
index 000000000..70416abfe
--- /dev/null
+++ b/desktop/runtime-host/src/status.rs
@@ -0,0 +1,234 @@
+//! The frozen desktop bootstrap contract.
+//!
+//! Every field here is produced by this crate and consumed by the bootstrap UI.
+//! The desktop vertical-slice plan freezes this shape; changing a field name or
+//! phase value is a contract change.
+
+use serde::{Deserialize, Serialize};
+
+use crate::origin::LoopbackOrigin;
+
+/// `probing -> ready`, `probing -> starting -> ready | failed`, `probing -> failed`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum BootstrapPhase {
+ Probing,
+ Starting,
+ Ready,
+ Failed,
+}
+
+impl BootstrapPhase {
+ /// Terminal phases end a bootstrap run; the shell only navigates on `Ready`.
+ pub fn is_terminal(self) -> bool {
+ matches!(self, Self::Ready | Self::Failed)
+ }
+}
+
+/// Stable bootstrap copy identifiers understood by the bundled UI.
+///
+/// Rust emits codes, never display prose. The offline desktop bundle maps every
+/// value to the central English and Chinese catalogs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BootstrapNoticeCode {
+ Probing,
+ Adopted,
+ Starting,
+ Ready,
+ InvalidOrigin,
+ RuntimeNotFound,
+ RuntimeInstallFailed,
+ RuntimeDiscoveryFailed,
+ RuntimeSpawnFailed,
+ RuntimeStopped,
+ RuntimeOwnershipLost,
+ LauncherExited,
+ ReadyTimeout,
+ WorkbenchNavigationFailed,
+}
+
+/// Typed, bounded arguments for one localized bootstrap notice.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct BootstrapNotice {
+ pub code: BootstrapNoticeCode,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub seconds: Option<u64>,
+}
+
+impl BootstrapNotice {
+ pub const fn new(code: BootstrapNoticeCode) -> Self {
+ Self { code, seconds: None }
+ }
+
+ pub const fn timeout(seconds: u64) -> Self {
+ Self {
+ code: BootstrapNoticeCode::ReadyTimeout,
+ seconds: Some(seconds),
+ }
+ }
+}
+
+/// One observation of the bootstrap state machine.
+///
+/// `notice` contains no display prose, command string, environment variable,
+/// path, or Runtime process output.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct BootstrapStatus {
+ pub phase: BootstrapPhase,
+ /// A validated loopback origin, or empty. Never unvalidated input — see
+ /// [`BootstrapStatus::rejected`].
+ pub origin: String,
+ /// Current readiness probe attempt; `0` before the first probe is possible.
+ pub attempt: u32,
+ pub notice: BootstrapNotice,
+ /// Whether the user may safely ask the shell to try again.
+ pub retryable: bool,
+}
+
+impl BootstrapStatus {
+ pub fn probing(origin: &LoopbackOrigin, attempt: u32) -> Self {
+ Self {
+ phase: BootstrapPhase::Probing,
+ origin: origin.as_str().to_owned(),
+ attempt,
+ notice: BootstrapNotice::new(BootstrapNoticeCode::Probing),
+ retryable: false,
+ }
+ }
+
+ pub fn starting(origin: &LoopbackOrigin, attempt: u32) -> Self {
+ Self {
+ phase: BootstrapPhase::Starting,
+ origin: origin.as_str().to_owned(),
+ attempt,
+ notice: BootstrapNotice::new(BootstrapNoticeCode::Starting),
+ retryable: false,
+ }
+ }
+
+ pub fn ready(origin: &LoopbackOrigin, attempt: u32, code: BootstrapNoticeCode) -> Self {
+ debug_assert!(matches!(
+ code,
+ BootstrapNoticeCode::Adopted | BootstrapNoticeCode::Ready
+ ));
+ Self {
+ phase: BootstrapPhase::Ready,
+ origin: origin.as_str().to_owned(),
+ attempt,
+ notice: BootstrapNotice::new(code),
+ retryable: false,
+ }
+ }
+
+ pub fn failed(origin: &LoopbackOrigin, attempt: u32, notice: BootstrapNotice, retryable: bool) -> Self {
+ Self {
+ phase: BootstrapPhase::Failed,
+ origin: origin.as_str().to_owned(),
+ attempt,
+ notice,
+ retryable,
+ }
+ }
+
+ /// A run that failed before it had an origin at all.
+ ///
+ /// The rejected value is dropped rather than echoed. It is unvalidated
+ /// configuration input, it would reach the WebView as rendered text, and the
+ /// error already describes what an acceptable origin looks like without
+ /// quoting the bad one. Taking `&LoopbackOrigin` everywhere else is what
+ /// makes this the only way to report the failure.
+ pub fn rejected(code: BootstrapNoticeCode, retryable: bool) -> Self {
+ Self {
+ phase: BootstrapPhase::Failed,
+ origin: String::new(),
+ attempt: 0,
+ notice: BootstrapNotice::new(code),
+ retryable,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn phases_serialize_as_the_contract_spells_them() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").expect("a loopback origin");
+ let status = BootstrapStatus::failed(&origin, 3, BootstrapNotice::timeout(120), true);
+ let json = serde_json::to_value(&status).expect("status serializes");
+
+ assert_eq!(json["phase"], "failed");
+ assert_eq!(json["origin"], "http://127.0.0.1:5123");
+ assert_eq!(json["attempt"], 3);
+ assert_eq!(json["notice"]["code"], "ready_timeout");
+ assert_eq!(json["notice"]["seconds"], 120);
+ assert_eq!(json["retryable"], true);
+
+ let object = json.as_object().expect("status is a JSON object");
+ let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ // The contract has exactly five fields; extra fields are a contract change.
+ assert_eq!(keys, ["attempt", "notice", "origin", "phase", "retryable"]);
+ }
+
+ #[test]
+ fn every_phase_uses_its_contract_spelling() {
+ let cases = [
+ (BootstrapPhase::Probing, "probing"),
+ (BootstrapPhase::Starting, "starting"),
+ (BootstrapPhase::Ready, "ready"),
+ (BootstrapPhase::Failed, "failed"),
+ ];
+ for (phase, expected) in cases {
+ assert_eq!(serde_json::to_value(phase).expect("phase serializes"), expected);
+ }
+ }
+
+ /// The one status produced from a value that was never validated.
+ #[test]
+ fn a_rejected_origin_is_not_carried_into_the_status() {
+ let status = BootstrapStatus::rejected(BootstrapNoticeCode::InvalidOrigin, false);
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(status.origin.is_empty(), "got {:?}", status.origin);
+ assert!(!status.retryable);
+ assert_eq!(status.attempt, 0);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::InvalidOrigin);
+ }
+
+ #[test]
+ fn every_notice_code_uses_its_contract_spelling() {
+ let cases = [
+ (BootstrapNoticeCode::Probing, "probing"),
+ (BootstrapNoticeCode::Adopted, "adopted"),
+ (BootstrapNoticeCode::Starting, "starting"),
+ (BootstrapNoticeCode::Ready, "ready"),
+ (BootstrapNoticeCode::InvalidOrigin, "invalid_origin"),
+ (BootstrapNoticeCode::RuntimeNotFound, "runtime_not_found"),
+ (BootstrapNoticeCode::RuntimeInstallFailed, "runtime_install_failed"),
+ (BootstrapNoticeCode::RuntimeDiscoveryFailed, "runtime_discovery_failed"),
+ (BootstrapNoticeCode::RuntimeSpawnFailed, "runtime_spawn_failed"),
+ (BootstrapNoticeCode::RuntimeStopped, "runtime_stopped"),
+ (BootstrapNoticeCode::RuntimeOwnershipLost, "runtime_ownership_lost"),
+ (BootstrapNoticeCode::LauncherExited, "launcher_exited"),
+ (BootstrapNoticeCode::ReadyTimeout, "ready_timeout"),
+ (
+ BootstrapNoticeCode::WorkbenchNavigationFailed,
+ "workbench_navigation_failed",
+ ),
+ ];
+ for (code, expected) in cases {
+ assert_eq!(serde_json::to_value(code).expect("code serializes"), expected);
+ }
+ }
+
+ #[test]
+ fn only_ready_and_failed_end_a_run() {
+ assert!(!BootstrapPhase::Probing.is_terminal());
+ assert!(!BootstrapPhase::Starting.is_terminal());
+ assert!(BootstrapPhase::Ready.is_terminal());
+ assert!(BootstrapPhase::Failed.is_terminal());
+ }
+}
diff --git a/desktop/runtime-host/src/window_frame.rs b/desktop/runtime-host/src/window_frame.rs
new file mode 100644
index 000000000..4d7d924a0
--- /dev/null
+++ b/desktop/runtime-host/src/window_frame.rs
@@ -0,0 +1,122 @@
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct WindowFrame {
+ pub x: i32,
+ pub y: i32,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct MonitorArea {
+ pub frame: WindowFrame,
+ pub scale_factor: f64,
+}
+
+pub fn clamp_window_frame(frame: WindowFrame, monitors: &[MonitorArea], minimum: (f64, f64)) -> WindowFrame {
+ let Some(monitor) = monitors
+ .iter()
+ .filter(|monitor| monitor.frame.width > 0 && monitor.frame.height > 0)
+ .max_by_key(|monitor| overlap_area(frame, monitor.frame))
+ else {
+ return frame;
+ };
+ let bounds = monitor.frame;
+ let width = frame.width.max((minimum.0 * monitor.scale_factor).ceil() as u32);
+ let height = frame.height.max((minimum.1 * monitor.scale_factor).ceil() as u32);
+ let title_bar = ((32.0 * monitor.scale_factor).ceil() as u32).min(bounds.height);
+ let clamp_position = |position: i32, start: i32, extent: u32, visible: u32| {
+ let start = i64::from(start);
+ let end = start + i64::from(extent.saturating_sub(visible));
+ i64::from(position)
+ .clamp(start, end)
+ .clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
+ };
+ WindowFrame {
+ x: clamp_position(frame.x, bounds.x, bounds.width, width),
+ y: clamp_position(frame.y, bounds.y, bounds.height, title_bar),
+ width,
+ height,
+ }
+}
+
+fn overlap_area(frame: WindowFrame, bounds: WindowFrame) -> u64 {
+ let overlap = |start: i32, extent: u32, other_start: i32, other_extent: u32| {
+ let right = (i64::from(start) + i64::from(extent)).min(i64::from(other_start) + i64::from(other_extent));
+ (right - i64::from(start.max(other_start))).max(0) as u64
+ };
+ overlap(frame.x, frame.width, bounds.x, bounds.width) * overlap(frame.y, frame.height, bounds.y, bounds.height)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn clamping_makes_the_title_bar_visible_and_preserves_the_scaled_minimum() {
+ let minimum = (880.0, 600.0);
+ for seed in 1..200_u32 {
+ let monitor = MonitorArea {
+ frame: WindowFrame {
+ x: -(seed as i32) * 37,
+ y: seed as i32 * 13,
+ width: 480 + seed * 17,
+ height: 320 + seed * 11,
+ },
+ scale_factor: 1.0 + f64::from(seed % 5) * 0.5,
+ };
+ for position in [i32::MIN, -10_000, 0, 10_000, i32::MAX] {
+ let saved = WindowFrame {
+ x: position,
+ y: position,
+ width: seed * 21,
+ height: seed * 15,
+ };
+ let restored = clamp_window_frame(saved, &[monitor], minimum);
+ assert!(restored.width >= (minimum.0 * monitor.scale_factor).ceil() as u32);
+ assert!(restored.height >= (minimum.1 * monitor.scale_factor).ceil() as u32);
+ assert!(restored.width >= saved.width && restored.height >= saved.height);
+ assert!(restored.x >= monitor.frame.x);
+ assert!(i64::from(restored.x) < i64::from(monitor.frame.x) + i64::from(monitor.frame.width));
+ assert!(restored.y >= monitor.frame.y);
+ let title_bar = ((32.0 * monitor.scale_factor).ceil() as u32).min(monitor.frame.height);
+ assert!(
+ i64::from(restored.y) + i64::from(title_bar)
+ <= i64::from(monitor.frame.y) + i64::from(monitor.frame.height)
+ );
+ assert_eq!(clamp_window_frame(restored, &[monitor], minimum), restored);
+ }
+ }
+ }
+
+ #[test]
+ fn an_accessible_frame_is_unchanged_across_restore_and_show() {
+ let monitors = [
+ MonitorArea {
+ frame: WindowFrame {
+ x: -2000,
+ y: 40,
+ width: 2000,
+ height: 1400,
+ },
+ scale_factor: 1.0,
+ },
+ MonitorArea {
+ frame: WindowFrame {
+ x: 0,
+ y: 40,
+ width: 2000,
+ height: 1400,
+ },
+ scale_factor: 1.0,
+ },
+ ];
+ let frame = WindowFrame {
+ x: -1800,
+ y: 200,
+ width: 1000,
+ height: 700,
+ };
+ assert_eq!(clamp_window_frame(frame, &monitors, (880.0, 600.0)), frame);
+ assert!(clamp_window_frame(frame, &monitors[1..], (880.0, 600.0)).x >= 0);
+ }
+}
diff --git a/desktop/runtime-host/tests/bootstrap.rs b/desktop/runtime-host/tests/bootstrap.rs
new file mode 100644
index 000000000..8e330295f
--- /dev/null
+++ b/desktop/runtime-host/tests/bootstrap.rs
@@ -0,0 +1,969 @@
+//! Behavioural coverage for the bootstrap state machine.
+//!
+//! Every test drives a real `RuntimeHost` through fake collaborators, so the
+//! guarantees under test are the ones the shell actually relies on: adopt what
+//! is already running, start what is not, never start twice, never navigate
+//! before the Runtime answers.
+//!
+//! Time is virtual (`start_paused`), so the 120-second production wait is
+//! exercised in microseconds.
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use avibe_runtime_host::deep_link::DeepLinks;
+use avibe_runtime_host::{
+ parse_avibe_readiness_body, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, HealthProbe, LaunchError,
+ LaunchWatch, LaunchedRuntime, LoopbackOrigin, ResolvedRuntimeLauncher, RuntimeHost, RuntimeHostSettings,
+ RuntimeLauncher, RuntimeReadiness, RuntimeRemovalState, StatusSink,
+};
+
+const TEST_ORIGIN: &str = "http://127.0.0.1:5123";
+const EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY: &str =
+ include_str!("../../../tests/fixtures/desktop_ready_external_controller_bundled_ui.json");
+type RemovalRecord = RuntimeRemovalState;
+
+/// Answers "not yet" until the given probe call, then "ready" forever.
+struct FakeProbe {
+ healthy_from: usize,
+ runtime_id: Option<String>,
+ ui_runtime_id: Option<String>,
+ identity_mismatch_at: Option<usize>,
+ calls: AtomicUsize,
+}
+
+impl FakeProbe {
+ fn healthy_from(call: usize) -> Arc<Self> {
+ Arc::new(Self {
+ healthy_from: call,
+ runtime_id: None,
+ ui_runtime_id: None,
+ identity_mismatch_at: None,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn healthy_from_readiness(call: usize, readiness: &RuntimeReadiness) -> Arc<Self> {
+ Arc::new(Self {
+ healthy_from: call,
+ runtime_id: readiness.desktop_runtime_id.clone(),
+ ui_runtime_id: readiness.desktop_ui_runtime_id.clone(),
+ identity_mismatch_at: None,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn healthy_managed(runtime_id: &str) -> Arc<Self> {
+ Arc::new(Self {
+ healthy_from: 1,
+ runtime_id: Some(runtime_id.to_owned()),
+ ui_runtime_id: None,
+ identity_mismatch_at: None,
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn mismatched_managed(runtime_id: &str) -> Arc<Self> {
+ Arc::new(Self {
+ healthy_from: usize::MAX,
+ runtime_id: Some(runtime_id.to_owned()),
+ ui_runtime_id: None,
+ identity_mismatch_at: Some(1),
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn mismatch_after_launch_then_healthy(runtime_id: &str) -> Arc<Self> {
+ Arc::new(Self {
+ healthy_from: 3,
+ runtime_id: Some(runtime_id.to_owned()),
+ ui_runtime_id: None,
+ identity_mismatch_at: Some(2),
+ calls: AtomicUsize::new(0),
+ })
+ }
+
+ fn never_healthy() -> Arc<Self> {
+ Self::healthy_from(usize::MAX)
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+}
+
+#[async_trait]
+impl HealthProbe for FakeProbe {
+ async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ (call >= self.healthy_from).then(|| RuntimeReadiness {
+ desktop_runtime_id: self.runtime_id.clone(),
+ desktop_ui_runtime_id: self.ui_runtime_id.clone(),
+ })
+ }
+
+ async fn mismatched_runtime_identity(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
+ (self.identity_mismatch_at == Some(self.calls())).then(|| RuntimeReadiness {
+ desktop_runtime_id: self.runtime_id.clone(),
+ desktop_ui_runtime_id: None,
+ })
+ }
+}
+
+/// Records launch attempts; the first `failures` of them report no executable.
+struct FakeLauncher {
+ calls: Arc<AtomicUsize>,
+ failures: usize,
+ dies_immediately: bool,
+ succeeds_immediately: bool,
+ runtime_id: Option<String>,
+ handovers: Arc<AtomicUsize>,
+ cleanups: Arc<AtomicUsize>,
+ removals: Arc<Mutex<Vec<RemovalRecord>>>,
+}
+
+impl FakeLauncher {
+ fn working() -> Arc<Self> {
+ Arc::new(Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ failures: 0,
+ dies_immediately: false,
+ succeeds_immediately: false,
+ runtime_id: None,
+ handovers: Arc::new(AtomicUsize::new(0)),
+ cleanups: Arc::new(AtomicUsize::new(0)),
+ removals: Arc::new(Mutex::new(Vec::new())),
+ })
+ }
+
+ fn managed(runtime_id: &str) -> Arc<Self> {
+ Arc::new(Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ failures: 0,
+ dies_immediately: false,
+ succeeds_immediately: false,
+ runtime_id: Some(runtime_id.to_owned()),
+ handovers: Arc::new(AtomicUsize::new(0)),
+ cleanups: Arc::new(AtomicUsize::new(0)),
+ removals: Arc::new(Mutex::new(Vec::new())),
+ })
+ }
+
+ fn failing_first(failures: usize) -> Arc<Self> {
+ Arc::new(Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ failures,
+ dies_immediately: false,
+ succeeds_immediately: false,
+ runtime_id: None,
+ handovers: Arc::new(AtomicUsize::new(0)),
+ cleanups: Arc::new(AtomicUsize::new(0)),
+ removals: Arc::new(Mutex::new(Vec::new())),
+ })
+ }
+
+ /// Spawns successfully, then exits non-zero without starting a Runtime —
+ /// what an installed `vibe` too old for the shell's arguments does.
+ fn dying() -> Arc<Self> {
+ Arc::new(Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ failures: 0,
+ dies_immediately: true,
+ succeeds_immediately: false,
+ runtime_id: None,
+ handovers: Arc::new(AtomicUsize::new(0)),
+ cleanups: Arc::new(AtomicUsize::new(0)),
+ removals: Arc::new(Mutex::new(Vec::new())),
+ })
+ }
+
+ /// The start helper exits zero, but no Runtime ever answers `/ready`.
+ fn zero_exit_without_runtime() -> Arc<Self> {
+ Arc::new(Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ failures: 0,
+ dies_immediately: false,
+ succeeds_immediately: true,
+ runtime_id: None,
+ handovers: Arc::new(AtomicUsize::new(0)),
+ cleanups: Arc::new(AtomicUsize::new(0)),
+ removals: Arc::new(Mutex::new(Vec::new())),
+ })
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+}
+
+impl RuntimeLauncher for FakeLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(Self {
+ calls: self.calls.clone(),
+ failures: self.failures,
+ dies_immediately: self.dies_immediately,
+ succeeds_immediately: self.succeeds_immediately,
+ runtime_id: self.runtime_id.clone(),
+ handovers: self.handovers.clone(),
+ cleanups: self.cleanups.clone(),
+ removals: self.removals.clone(),
+ }))
+ }
+
+ fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
+ self.removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .push(state);
+ if state == RuntimeRemovalState::Unknown {
+ return Err(LaunchError::RuntimeRemoval);
+ }
+ Ok(true)
+ }
+}
+
+impl ResolvedRuntimeLauncher for FakeLauncher {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse(TEST_ORIGIN).expect("the test endpoint is valid"))
+ }
+
+ fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ if call <= self.failures {
+ return Err(LaunchError::ExecutableNotFound);
+ }
+ Ok(LaunchedRuntime {
+ pid: 4242,
+ watch: if self.dies_immediately {
+ LaunchWatch::exited(false)
+ } else if self.succeeds_immediately {
+ LaunchWatch::exited(true)
+ } else {
+ LaunchWatch::default()
+ },
+ })
+ }
+
+ fn expected_runtime_id(&self) -> Option<&str> {
+ self.runtime_id.as_deref()
+ }
+
+ fn handover(&self) -> Result<(), LaunchError> {
+ self.handovers.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+
+ fn prune_superseded(&self) {
+ self.cleanups.fetch_add(1, Ordering::SeqCst);
+ }
+}
+
+#[derive(Default)]
+struct Recorder {
+ statuses: Mutex<Vec<BootstrapStatus>>,
+}
+
+impl Recorder {
+ fn statuses(&self) -> Vec<BootstrapStatus> {
+ self.statuses.lock().expect("recorder is not poisoned").clone()
+ }
+
+ fn phases(&self) -> Vec<BootstrapPhase> {
+ self.statuses().iter().map(|status| status.phase).collect()
+ }
+}
+
+impl StatusSink for Recorder {
+ fn publish(&self, status: BootstrapStatus) {
+ self.statuses.lock().expect("recorder is not poisoned").push(status);
+ }
+}
+
+/// Production defaults, minus the wall-clock wait: the shell polls every 500ms
+/// for two seconds, which under virtual time is five probes.
+fn fast_settings() -> RuntimeHostSettings {
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ ..RuntimeHostSettings::default()
+ }
+}
+
+fn immediate_timeout_settings() -> RuntimeHostSettings {
+ RuntimeHostSettings {
+ ready_timeout: Duration::ZERO,
+ ..RuntimeHostSettings::default()
+ }
+}
+
+fn host(probe: Arc<FakeProbe>, launcher: Arc<FakeLauncher>, settings: RuntimeHostSettings) -> RuntimeHost {
+ RuntimeHost::new(probe, launcher, settings)
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_cold_link_is_consumed_only_after_ready_navigation_commits_and_never_replayed() {
+ let launcher = FakeLauncher::working();
+ let host = host(FakeProbe::healthy_from(3), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+ let mut links = DeepLinks::default();
+ links.receive(["avibe", "avibe://show/cold.session"]);
+ let ready = host.bootstrap(&recorder).await;
+ for status in recorder
+ .statuses
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|status| status.phase != BootstrapPhase::Ready)
+ {
+ assert!(links.bootstrap_navigation(status).is_none());
+ }
+ assert_eq!(ready.phase, BootstrapPhase::Ready);
+ let destination = links.bootstrap_navigation(&ready).unwrap();
+ assert_eq!(
+ destination.url().as_str(),
+ format!("{}/apps/show/cold.session", ready.origin)
+ );
+ assert_eq!(links.bootstrap_navigation(&ready).unwrap().url(), destination.url());
+ assert!(links.commit_navigation(&destination, true, 1, 1));
+ assert_eq!(links.bootstrap_navigation(&ready).unwrap().url().path(), "/");
+ assert_eq!(launcher.calls(), 1);
+}
+
+#[tokio::test(start_paused = true)]
+async fn bootstrap_failure_discards_the_link_without_navigating_or_replaying_on_retry() {
+ let host = host(FakeProbe::never_healthy(), FakeLauncher::working(), fast_settings());
+ let recorder = Recorder::default();
+ let mut links = DeepLinks::default();
+ links.receive(["avibe://session/failed"]);
+ let failed = host.bootstrap(&recorder).await;
+ assert_eq!(failed.phase, BootstrapPhase::Failed);
+ assert!(links.bootstrap_navigation(&failed).is_none());
+ links.receive(["avibe://session/arrived-after-failure"]);
+ let healthy = RuntimeHost::new(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
+ let ready = healthy.bootstrap(&recorder).await;
+ assert_eq!(links.bootstrap_navigation(&ready).unwrap().url().path(), "/");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_ready_link_survives_failed_handoffs_until_the_current_window_accepts_it() {
+ let host = host(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
+ let mut links = DeepLinks::default();
+ links.receive(["avibe://session/retry"]);
+ let ready = host.bootstrap(&Recorder::default()).await;
+ let origin = LoopbackOrigin::parse(&ready.origin).unwrap();
+ let first = links.bootstrap_navigation(&ready).unwrap();
+ assert!(!links.commit_navigation(&first, false, 1, 1));
+ let handoff_failed = BootstrapStatus::failed(
+ &origin,
+ ready.attempt,
+ avibe_runtime_host::BootstrapNotice::new(BootstrapNoticeCode::WorkbenchNavigationFailed),
+ true,
+ );
+ assert!(links.bootstrap_navigation(&handoff_failed).is_none());
+ let retried = host.bootstrap(&Recorder::default()).await;
+ let replacement = links.bootstrap_navigation(&retried).unwrap();
+ assert_eq!(replacement.url(), first.url());
+ assert!(!links.commit_navigation(&replacement, true, 1, 2));
+ let current = links.bootstrap_navigation(&retried).unwrap();
+ assert_eq!(current.url(), first.url());
+ assert!(links.commit_navigation(&current, true, 2, 2));
+ assert_eq!(links.bootstrap_navigation(&retried).unwrap().url().path(), "/");
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_already_running_runtime_is_adopted_without_starting_anything() {
+ let probe = FakeProbe::healthy_from(1);
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.origin, TEST_ORIGIN);
+ assert_eq!(status.attempt, 1);
+ assert_eq!(launcher.calls(), 0, "an adopted Runtime must never be re-started");
+ assert_eq!(probe.calls(), 1);
+ assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Ready]);
+ assert!(!host.has_launched());
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_matching_desktop_runtime_is_adopted_and_superseded_installs_are_pruned() {
+ let runtime_id = "a".repeat(64);
+ let probe = FakeProbe::healthy_managed(&runtime_id);
+ let launcher = FakeLauncher::managed(&runtime_id);
+ let host = host(probe, launcher.clone(), fast_settings());
+
+ let status = host.bootstrap(&Recorder::default()).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(launcher.calls(), 0);
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
+ assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn uninstall_marks_an_adopted_private_runtime_as_managed() {
+ let runtime_id = "a".repeat(64);
+ let probe = FakeProbe::healthy_managed(&runtime_id);
+ let launcher = FakeLauncher::managed(&runtime_id);
+ let host = host(probe, launcher.clone(), fast_settings());
+ let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+
+ assert!(host
+ .remove_private_runtime(Some(&origin))
+ .await
+ .expect("private Runtime removal"));
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Managed]
+ );
+}
+
+#[tokio::test]
+async fn uninstall_refuses_to_remove_files_when_an_adopted_runtime_stops_answering() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::managed(&"a".repeat(64));
+ let host = host(probe, launcher.clone(), fast_settings());
+ let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+
+ assert!(matches!(
+ host.remove_private_runtime(Some(&origin)).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Unknown]
+ );
+}
+
+#[tokio::test]
+async fn uninstall_can_remove_an_inactive_private_runtime_without_probing_or_launching() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::managed(&"a".repeat(64));
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+
+ assert!(host
+ .remove_private_runtime(None)
+ .await
+ .expect("inactive private Runtime removal"));
+ assert_eq!(probe.calls(), 0);
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Inactive]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_superseded_desktop_runtime_is_stopped_before_the_successor_starts() {
+ let expected = "b".repeat(64);
+ let probe = FakeProbe::mismatched_managed(&"a".repeat(64));
+ let launcher = FakeLauncher::managed(&expected);
+ let host = host(probe, launcher.clone(), immediate_timeout_settings());
+
+ let status = host.bootstrap(&Recorder::default()).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 1);
+ assert_eq!(launcher.calls(), 1);
+ assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_unknown_predecessor_never_authorizes_initial_or_polling_handover() {
+ for mismatch_at in [1, 2] {
+ let probe = Arc::new(FakeProbe {
+ healthy_from: usize::MAX,
+ runtime_id: None,
+ ui_runtime_id: None,
+ identity_mismatch_at: Some(mismatch_at),
+ calls: AtomicUsize::new(0),
+ });
+ let launcher = FakeLauncher::managed(&"b".repeat(64));
+ let host = host(probe, launcher.clone(), fast_settings());
+ assert_eq!(host.bootstrap(&Recorder::default()).await.phase, BootstrapPhase::Failed);
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
+ assert_eq!(launcher.calls(), 1);
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_identity_mismatch_discovered_while_polling_hands_over_and_relaunches_immediately() {
+ let expected = "b".repeat(64);
+ let probe = FakeProbe::mismatch_after_launch_then_healthy(&expected);
+ let launcher = FakeLauncher::managed(&expected);
+ let host = host(probe, launcher.clone(), fast_settings());
+
+ let status = host.bootstrap(&Recorder::default()).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ launcher.calls(),
+ 2,
+ "the post-handover successor must launch in the same run"
+ );
+ assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_absent_runtime_is_started_and_adopted_once_it_answers() {
+ let probe = FakeProbe::healthy_from(3);
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(launcher.calls(), 1, "exactly one Runtime is started");
+ assert!(host.has_launched());
+ assert_eq!(
+ recorder.phases(),
+ vec![
+ BootstrapPhase::Probing,
+ BootstrapPhase::Starting,
+ BootstrapPhase::Starting,
+ BootstrapPhase::Ready,
+ ]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_helper_adopts_untagged_readiness_after_launch_without_handover_or_pruning() {
+ // The first probe misses, so the bundled helper is started. The next
+ // probe is the real external-adoption shape produced by `/ready`: the
+ // Controller is healthy but has no desktop identity.
+ let readiness = parse_avibe_readiness_body(r#"{"schema_version":1,"product":"avibe","ready":true}"#)
+ .expect("the Python /ready payload is accepted by the Rust parser");
+ assert_eq!(readiness.desktop_runtime_id, None);
+ let probe = FakeProbe::healthy_from_readiness(2, &readiness);
+ let launcher = FakeLauncher::managed(&"b".repeat(64));
+ let host = host(probe, launcher.clone(), fast_settings());
+
+ let status = host.bootstrap(&Recorder::default()).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
+ assert_eq!(launcher.calls(), 1);
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
+ assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
+ assert!(!host.has_owned_runtime());
+
+ // The helper may have created the UI from the private tree even though the
+ // adopted Controller is external. Do not delete that tree on a no-ID
+ // readiness response while launch liveness is still uncertain.
+ let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+ assert!(matches!(
+ host.remove_private_runtime(Some(&origin)).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Unknown]
+ );
+}
+
+#[tokio::test]
+async fn uninstall_keeps_a_preexisting_untagged_external_runtime_external() {
+ let readiness = parse_avibe_readiness_body(r#"{"schema_version":1,"product":"avibe","ready":true}"#)
+ .expect("the Python /ready payload is accepted by the Rust parser");
+ let probe = FakeProbe::healthy_from_readiness(1, &readiness);
+ let launcher = FakeLauncher::working();
+ let host = host(probe, launcher.clone(), fast_settings());
+ let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+
+ assert!(host
+ .remove_private_runtime(Some(&origin))
+ .await
+ .expect("external private-runtime cleanup"));
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::External]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_external_controller_with_a_bundled_ui_stays_unknown_after_shell_reopen() {
+ let readiness = parse_avibe_readiness_body(EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY)
+ .expect("the tagged UI readiness payload is accepted by the Rust parser");
+ let probe = FakeProbe::healthy_from_readiness(2, &readiness);
+ let launcher = FakeLauncher::managed(&"b".repeat(64));
+ let first = host(probe.clone(), launcher.clone(), fast_settings());
+ let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+
+ assert_eq!(
+ first.bootstrap(&Recorder::default()).await.notice.code,
+ BootstrapNoticeCode::Adopted
+ );
+ assert!(matches!(
+ first.remove_private_runtime(Some(&origin)).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+
+ // Closing the shell drops in-memory state, but the same UI identity in
+ // /ready still proves that private UI files may be serving the Controller.
+ drop(first);
+ let reopened = host(probe, launcher.clone(), fast_settings());
+ assert_eq!(
+ reopened.bootstrap(&Recorder::default()).await.notice.code,
+ BootstrapNoticeCode::Adopted
+ );
+ assert!(matches!(
+ reopened.remove_private_runtime(Some(&origin)).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ launcher.calls(),
+ 1,
+ "reopening adopts the surviving UI without relaunching it"
+ );
+ assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
+ assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Unknown, RuntimeRemovalState::Unknown]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_shell_learns_of_readiness_only_after_the_runtime_answers() {
+ let probe = FakeProbe::healthy_from(4);
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+ let statuses = recorder.statuses();
+
+ // Ready is emitted once, last, and only on the probe call that succeeded.
+ assert_eq!(statuses.iter().filter(|s| s.phase == BootstrapPhase::Ready).count(), 1);
+ assert_eq!(statuses.last().map(|s| s.phase), Some(BootstrapPhase::Ready));
+ assert_eq!(status.attempt as usize, probe.calls());
+ assert!(status.phase.is_terminal());
+ assert_eq!(
+ Some(&status),
+ statuses.last(),
+ "the returned status is the published one"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_runtime_that_never_answers_fails_with_a_retryable_timeout() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(status.retryable, "a slow machine deserves another try");
+ assert_eq!(status.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(status.notice.seconds, Some(2));
+ assert!(status.attempt > 1, "the wait is polled, not a single shot");
+ assert_eq!(launcher.calls(), 1);
+ assert!(
+ !recorder.phases().contains(&BootstrapPhase::Ready),
+ "a timed-out run must never report readiness"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn retrying_after_a_timeout_never_starts_a_second_runtime() {
+ // Call 6 is the retry's first probe; the Runtime answers on call 7, after the
+ // first run has already given up.
+ let probe = FakeProbe::healthy_from(7);
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+
+ let first = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(first.phase, BootstrapPhase::Failed);
+ assert_eq!(launcher.calls(), 1);
+
+ let recorder = Recorder::default();
+ let second = host.bootstrap(&recorder).await;
+
+ assert_eq!(second.phase, BootstrapPhase::Ready);
+ assert_eq!(
+ launcher.calls(),
+ 1,
+ "the retry must adopt the Runtime it already started"
+ );
+ assert!(
+ recorder.phases().contains(&BootstrapPhase::Starting),
+ "the retry still waits on the Runtime it started earlier"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_launcher_failure_observed_after_timeout_is_rechecked_on_retry() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::dying();
+ let host = host(probe, launcher.clone(), immediate_timeout_settings());
+
+ // The zero-length budget expires before the polling loop can inspect the
+ // watch, matching a real launcher whose non-zero exit lands just after a
+ // normal timeout.
+ let first = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(first.phase, BootstrapPhase::Failed);
+ assert_eq!(first.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(first.notice.seconds, Some(0));
+ assert!(host.has_launched(), "the timed-out launch watch must be retained");
+ assert_eq!(launcher.calls(), 1);
+
+ let second = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(second.phase, BootstrapPhase::Failed);
+ assert_eq!(second.notice.code, BootstrapNoticeCode::LauncherExited);
+ assert!(
+ !host.has_launched(),
+ "a retained non-zero exit must release the launch slot"
+ );
+ assert_eq!(
+ launcher.calls(),
+ 1,
+ "observing the failed launch must not start a replacement in the same retry"
+ );
+ assert!(matches!(
+ host.remove_private_runtime(None).await,
+ Err(LaunchError::RuntimeRemoval)
+ ));
+ assert_eq!(
+ launcher
+ .removals
+ .lock()
+ .expect("removal recorder is not poisoned")
+ .as_slice(),
+ [RuntimeRemovalState::Unknown],
+ "a failed helper does not prove that a previously launched Runtime is absent"
+ );
+
+ let third = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(third.phase, BootstrapPhase::Failed);
+ assert_eq!(launcher.calls(), 2, "the next retry may start the Runtime again");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_long_running_launcher_is_retained_across_repeated_timeouts() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::working();
+ let host = host(probe, launcher.clone(), immediate_timeout_settings());
+
+ let first = host.bootstrap(&Recorder::default()).await;
+ let second = host.bootstrap(&Recorder::default()).await;
+
+ assert_eq!(first.phase, BootstrapPhase::Failed);
+ assert_eq!(second.phase, BootstrapPhase::Failed);
+ assert!(first.retryable && second.retryable);
+ assert!(host.has_launched());
+ assert_eq!(
+ launcher.calls(),
+ 1,
+ "an unresolved launcher watch remains the same launch across retries"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_zero_exit_launch_without_readiness_can_be_retried() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::zero_exit_without_runtime();
+ let host = host(probe, launcher.clone(), immediate_timeout_settings());
+
+ let first = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(first.phase, BootstrapPhase::Failed);
+ assert_eq!(first.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert!(
+ !host.has_launched(),
+ "a completed zero-exit helper must not block a retry after readiness timed out"
+ );
+ assert_eq!(launcher.calls(), 1);
+
+ let second = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(second.phase, BootstrapPhase::Failed);
+ assert_eq!(
+ launcher.calls(),
+ 2,
+ "Retry may re-run the idempotent start command once the prior helper completed"
+ );
+}
+
+#[tokio::test]
+async fn readiness_loss_keeps_a_pending_helper_deduplicated() {
+ let launcher = FakeLauncher::working();
+ let host = host(
+ FakeProbe::never_healthy(),
+ launcher.clone(),
+ immediate_timeout_settings(),
+ );
+
+ assert_eq!(
+ host.bootstrap(&Recorder::default()).await.notice.code,
+ BootstrapNoticeCode::ReadyTimeout
+ );
+ assert!(host.has_launched(), "the timeout retains the pending helper");
+ host.release_after_readiness_loss();
+
+ assert!(
+ host.has_launched(),
+ "a pending helper remains the single recovery owner"
+ );
+ assert_eq!(launcher.calls(), 1);
+}
+
+#[tokio::test(start_paused = true)]
+async fn concurrent_bootstraps_start_at_most_one_runtime() {
+ let probe = FakeProbe::healthy_from(3);
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+
+ let (left, right) = (Recorder::default(), Recorder::default());
+ let (first, second) = tokio::join!(host.bootstrap(&left), host.bootstrap(&right));
+
+ assert_eq!(first.phase, BootstrapPhase::Ready);
+ assert_eq!(second.phase, BootstrapPhase::Ready);
+ assert_eq!(launcher.calls(), 1, "two racing runs must not start two Runtimes");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_missing_executable_fails_retryably_and_the_next_attempt_may_start_one() {
+ let probe = FakeProbe::healthy_from(3);
+ let launcher = FakeLauncher::failing_first(1);
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+
+ let first = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(first.phase, BootstrapPhase::Failed);
+ assert!(first.retryable);
+ assert_eq!(launcher.calls(), 1);
+ assert!(
+ !host.has_launched(),
+ "a launch that failed did not start anything, so it must not block the retry"
+ );
+
+ let second = host.bootstrap(&Recorder::default()).await;
+ assert_eq!(second.phase, BootstrapPhase::Ready);
+ assert_eq!(launcher.calls(), 2, "the retry is allowed to start the Runtime");
+ assert!(host.has_launched());
+}
+
+/// An installed `vibe` too old for the shell's arguments spawns fine, rejects an
+/// argument, and exits without starting anything. The rest of the ready timeout
+/// would then be spent polling an address that will never answer.
+#[tokio::test(start_paused = true)]
+async fn a_launcher_that_exits_without_starting_anything_gives_up_early() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::dying();
+ let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let recorder = Recorder::default();
+
+ let started = tokio::time::Instant::now();
+ let status = host.bootstrap(&recorder).await;
+ let waited = started.elapsed();
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(status.retryable, "updating the Runtime makes the next attempt viable");
+ assert_eq!(status.notice.code, BootstrapNoticeCode::LauncherExited);
+ assert!(
+ waited < fast_settings().ready_timeout,
+ "waited {waited:?}, which is the full timeout this abort exists to avoid"
+ );
+ assert!(!recorder.phases().contains(&BootstrapPhase::Ready));
+
+ // Nothing is running, so the retry has to be allowed to start one.
+ assert!(!host.has_launched());
+ assert_eq!(host.bootstrap(&Recorder::default()).await.phase, BootstrapPhase::Failed);
+ assert_eq!(launcher.calls(), 2, "the retry starts a Runtime again");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_non_loopback_origin_fails_immediately_and_is_not_retryable() {
+ let probe = FakeProbe::healthy_from(1);
+ let launcher = FakeLauncher::working();
+ let settings = RuntimeHostSettings {
+ origin_override: Some("http://avibe.example.com:5123".to_owned()),
+ ..fast_settings()
+ };
+ let host = host(probe.clone(), launcher.clone(), settings);
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(!status.retryable, "retrying cannot make a remote origin acceptable");
+ assert_eq!(status.attempt, 0);
+ assert_eq!(probe.calls(), 0, "a rejected origin is never contacted");
+ assert_eq!(launcher.calls(), 0);
+ assert_eq!(recorder.phases(), vec![BootstrapPhase::Failed]);
+ // The rejected value is unvalidated input on its way to a WebView, so it is
+ // dropped and represented only by a typed notice.
+ assert!(status.origin.is_empty(), "got {:?}", status.origin);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::InvalidOrigin);
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_override_origin_is_adopted_only_and_never_starts_the_default_runtime() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::working();
+ let settings = RuntimeHostSettings {
+ origin_override: Some(TEST_ORIGIN.to_owned()),
+ ..fast_settings()
+ };
+ let host = host(probe.clone(), launcher.clone(), settings);
+ let recorder = Recorder::default();
+
+ let status = host.bootstrap(&recorder).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(status.retryable);
+ assert_eq!(status.origin, TEST_ORIGIN);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeNotFound);
+ assert_eq!(probe.calls(), 1, "the override origin is probed directly");
+ assert_eq!(launcher.calls(), 0, "override mode must not launch the default Runtime");
+ assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Failed]);
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_production_wait_is_bounded() {
+ let probe = FakeProbe::never_healthy();
+ let launcher = FakeLauncher::working();
+ let host = host(probe.clone(), launcher.clone(), RuntimeHostSettings::default());
+
+ let started = tokio::time::Instant::now();
+ let status = host.bootstrap(&Recorder::default()).await;
+ let waited = started.elapsed();
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert!(status.retryable);
+ let budget = RuntimeHostSettings::default().ready_timeout;
+ assert!(waited >= budget, "waited {waited:?}, expected at least {budget:?}");
+ assert!(
+ waited < budget + Duration::from_secs(5),
+ "waited {waited:?}, which overruns the bound"
+ );
+}
diff --git a/desktop/runtime-host/tests/notification_http.rs b/desktop/runtime-host/tests/notification_http.rs
new file mode 100644
index 000000000..677545299
--- /dev/null
+++ b/desktop/runtime-host/tests/notification_http.rs
@@ -0,0 +1,213 @@
+use std::collections::VecDeque;
+use std::io::{Read, Write};
+use std::net::TcpListener;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use avibe_runtime_host::notifications::{HttpNotificationTransport, NotificationTransport, SseDecoder};
+use avibe_runtime_host::LoopbackOrigin;
+use serde_json::json;
+
+struct FakeServer {
+ origin: LoopbackOrigin,
+ requests: Arc<Mutex<Vec<String>>>,
+ stopped: Arc<AtomicBool>,
+ thread: Option<std::thread::JoinHandle<()>>,
+}
+
+impl FakeServer {
+ fn start(responses: impl IntoIterator<Item = Vec<u8>>) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let origin = LoopbackOrigin::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let received = requests.clone();
+ let stopped = Arc::new(AtomicBool::new(false));
+ let stop = stopped.clone();
+ let mut responses = responses.into_iter().collect::<VecDeque<_>>();
+ let thread = std::thread::spawn(move || {
+ while !stop.load(Ordering::SeqCst) {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ stream.set_nonblocking(false).unwrap();
+ stream.set_read_timeout(Some(Duration::from_millis(50))).unwrap();
+ stream.set_write_timeout(Some(Duration::from_secs(1))).unwrap();
+ let mut request = Vec::new();
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while !request.windows(4).any(|chunk| chunk == b"\r\n\r\n") {
+ if stop.load(Ordering::SeqCst) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "request headers must arrive before the deadline"
+ );
+ let mut buffer = [0; 1024];
+ match stream.read(&mut buffer) {
+ Ok(0) => panic!("request headers were truncated"),
+ Ok(length) => request.extend_from_slice(&buffer[..length]),
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ) =>
+ {
+ continue
+ }
+ Err(error) => panic!("fake request failed: {error}"),
+ }
+ assert!(request.len() <= 16 * 1024);
+ }
+ received.lock().unwrap().push(String::from_utf8(request).unwrap());
+ let response = responses.pop_front().expect("only the expected requests are allowed");
+ let _ = stream.write_all(&response);
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ Err(error) => panic!("fake listener failed: {error}"),
+ }
+ }
+ });
+ Self {
+ origin,
+ requests,
+ stopped,
+ thread: Some(thread),
+ }
+ }
+
+ fn transport(&self) -> HttpNotificationTransport {
+ HttpNotificationTransport::new(self.origin.clone()).unwrap()
+ }
+}
+
+impl Drop for FakeServer {
+ fn drop(&mut self) {
+ self.stopped.store(true, Ordering::SeqCst);
+ if let Some(thread) = self.thread.take() {
+ let result = thread.join();
+ if !std::thread::panicking() {
+ result.expect("fake server exited cleanly");
+ }
+ }
+ }
+}
+
+fn response(status: &str, content_type: &str, body: &[u8]) -> Vec<u8> {
+ let mut response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ )
+ .into_bytes();
+ response.extend_from_slice(body);
+ response
+}
+
+#[tokio::test]
+async fn production_framing_uses_only_the_adopted_origin_and_reconnect_never_sends_a_replay_cursor() {
+ let event = b": stream connected\n\nevent: connected\ndata: {}\n\n: ping\n\nid: never-replay\nevent: vaults.updated\ndata: {\"type\":\"vaults.updated\",\"data\":{\"request_id\":\"request\",\"request_status\":\"pending\"}}\n\n";
+ let server = FakeServer::start([
+ response("200 OK", "text/event-stream; charset=utf-8", event),
+ response("200 OK", "text/event-stream", b": stream connected\n\n"),
+ ]);
+ let transport = server.transport();
+ let mut first = transport.connect().await.unwrap();
+ let mut decoder = SseDecoder::new();
+ let mut frames = Vec::new();
+ while let Some(chunk) = first.next_chunk().await.unwrap() {
+ frames.extend(decoder.push(&chunk));
+ }
+ assert_eq!(frames.len(), 2);
+ assert_eq!(frames[1].event, "vaults.updated");
+ let mut second = transport.connect().await.unwrap();
+ while second.next_chunk().await.unwrap().is_some() {}
+ let requests = server.requests.lock().unwrap();
+ assert_eq!(requests.len(), 2);
+ for request in requests.iter() {
+ let normalized = request.to_ascii_lowercase();
+ assert!(request.starts_with("GET /api/events HTTP/1.1\r\n"));
+ assert!(normalized.contains("accept: text/event-stream\r\n"));
+ for forbidden in ["last-event-id:", "authorization:", "cookie:"] {
+ assert!(!normalized.contains(forbidden));
+ }
+ }
+}
+
+#[tokio::test]
+async fn stream_and_detail_redirects_never_delegate_trust_to_another_origin() {
+ let target = FakeServer::start([]);
+ let redirect = format!(
+ "HTTP/1.1 302 Found\r\nLocation: {}/api/events\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ target.origin.as_str()
+ )
+ .into_bytes();
+ let server = FakeServer::start([redirect.clone(), redirect]);
+ let transport = server.transport();
+ assert!(transport.connect().await.is_err());
+ assert!(transport.run_timestamps("run").await.is_none());
+ assert!(target.requests.lock().unwrap().is_empty());
+ assert_eq!(server.requests.lock().unwrap().len(), 2);
+}
+
+#[tokio::test]
+async fn stream_requires_a_successful_sse_response_not_an_arbitrary_live_http_endpoint() {
+ let server = FakeServer::start([
+ response("200 OK", "text/html", b"<html>not SSE</html>"),
+ response("503 Unavailable", "text/event-stream", b": unavailable\n\n"),
+ response("204 No Content", "text/event-stream", b""),
+ ]);
+ for _ in 0..3 {
+ assert!(server.transport().connect().await.is_err());
+ }
+}
+
+#[tokio::test]
+async fn refetch_requires_the_requested_run_and_bounds_untrusted_detail_bodies() {
+ let valid = json!({"ok": true, "run": {
+ "id": "run", "started_at": "2026-09-10T12:00:00Z", "updated_at": "2026-09-10T12:00:30Z",
+ }});
+ let server = FakeServer::start([
+ response("200 OK", "application/json", valid.to_string().as_bytes()),
+ response(
+ "200 OK",
+ "application/json",
+ json!({"ok": true, "run": {"id": "another"}}).to_string().as_bytes(),
+ ),
+ response("404 Not Found", "application/json", b"{}"),
+ response("200 OK", "application/json", b"not-json"),
+ response("200 OK", "application/json", &vec![b'x'; 256 * 1024 + 1]),
+ b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 999999999\r\nConnection: close\r\n\r\n"
+ .to_vec(),
+ ]);
+ let transport = server.transport();
+ let detail = transport.run_timestamps("run").await.unwrap();
+ assert_eq!(detail.started_at, Some("2026-09-10T12:00:00Z".into()));
+ assert_eq!(detail.updated_at, Some("2026-09-10T12:00:30Z".into()));
+ for _ in 0..5 {
+ assert!(transport.run_timestamps("run").await.is_none());
+ }
+ for request in server.requests.lock().unwrap().iter() {
+ assert!(request.starts_with("GET /api/harness/runs/run HTTP/1.1\r\n"));
+ }
+}
+
+#[tokio::test]
+async fn identifiers_are_encoded_as_one_path_segment_not_runtime_selected_routes() {
+ let server = FakeServer::start([response("404 Not Found", "application/json", b"{}")]);
+ let transport = server.transport();
+ for key in ["", ".", ".."] {
+ assert!(transport.run_timestamps(key).await.is_none());
+ }
+ assert!(server.requests.lock().unwrap().is_empty());
+ assert!(transport
+ .run_timestamps("../settings?token=secret#片段")
+ .await
+ .is_none());
+ let requests = server.requests.lock().unwrap();
+ assert_eq!(requests.len(), 1);
+ assert!(
+ requests[0].starts_with("GET /api/harness/runs/..%2Fsettings%3Ftoken=secret%23%E7%89%87%E6%AE%B5 HTTP/1.1\r\n")
+ );
+}
diff --git a/desktop/runtime-host/tests/notifications.rs b/desktop/runtime-host/tests/notifications.rs
new file mode 100644
index 000000000..364d527f0
--- /dev/null
+++ b/desktop/runtime-host/tests/notifications.rs
@@ -0,0 +1,580 @@
+use std::collections::{HashMap, VecDeque};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use avibe_runtime_host::notifications::{
+ run_notifications, EventStream, NotificationFilter, NotificationGate, NotificationIntent, NotificationSink,
+ NotificationTransport, ReconnectBackoff, RunTimestamps, SseDecoder, StreamError, RETAINED_KEYS, RETENTION,
+};
+use serde_json::{json, Value};
+use tokio::time::Instant;
+
+struct FakeStream {
+ chunks: VecDeque<Vec<u8>>,
+ drop_after: bool,
+}
+
+#[async_trait]
+impl EventStream for FakeStream {
+ async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, StreamError> {
+ if let Some(chunk) = self.chunks.pop_front() {
+ return Ok(Some(chunk));
+ }
+ if self.drop_after {
+ Ok(None)
+ } else {
+ std::future::pending().await
+ }
+ }
+}
+
+#[derive(Default)]
+struct FakeTransport {
+ streams: Mutex<VecDeque<FakeStream>>,
+ connected_at: Mutex<Vec<Instant>>,
+ details: Mutex<HashMap<String, RunTimestamps>>,
+ refetched: Mutex<Vec<String>>,
+ detail_delay: Duration,
+}
+
+#[async_trait]
+impl NotificationTransport for FakeTransport {
+ async fn connect(&self) -> Result<Box<dyn EventStream>, StreamError> {
+ self.connected_at.lock().unwrap().push(Instant::now());
+ self.streams
+ .lock()
+ .unwrap()
+ .pop_front()
+ .map(|stream| Box::new(stream) as Box<dyn EventStream>)
+ .ok_or(StreamError)
+ }
+
+ async fn run_timestamps(&self, run_id: &str) -> Option<RunTimestamps> {
+ self.refetched.lock().unwrap().push(run_id.to_owned());
+ tokio::time::sleep(self.detail_delay).await;
+ self.details.lock().unwrap().get(run_id).cloned()
+ }
+}
+
+impl FakeTransport {
+ fn stream(&self, frames: impl IntoIterator<Item = Vec<u8>>, drop_after: bool) {
+ self.streams.lock().unwrap().push_back(FakeStream {
+ chunks: frames.into_iter().collect(),
+ drop_after,
+ });
+ }
+}
+
+struct FakeSink {
+ enabled: AtomicBool,
+ focused: AtomicBool,
+ visible: AtomicBool,
+ delivered: Mutex<Vec<NotificationIntent>>,
+}
+
+impl Default for FakeSink {
+ fn default() -> Self {
+ Self {
+ enabled: AtomicBool::new(true),
+ focused: AtomicBool::new(false),
+ visible: AtomicBool::new(true),
+ delivered: Mutex::new(Vec::new()),
+ }
+ }
+}
+
+impl NotificationSink for FakeSink {
+ fn gate(&self) -> NotificationGate {
+ NotificationGate {
+ enabled: self.enabled.load(Ordering::SeqCst),
+ focused: self.focused.load(Ordering::SeqCst),
+ visible: self.visible.load(Ordering::SeqCst),
+ }
+ }
+
+ fn deliver(&self, intent: NotificationIntent) {
+ self.delivered.lock().unwrap().push(intent);
+ }
+}
+
+fn frame(event: &str, data: Value) -> Vec<u8> {
+ format!(
+ "event: {event}\r\ndata: {}\r\n\r\n",
+ json!({"type": event, "data": data})
+ )
+ .into_bytes()
+}
+
+fn approval(request_id: impl ToString, status: &str) -> Vec<u8> {
+ frame(
+ "vaults.updated",
+ json!({"request_id": request_id.to_string(), "request_status": status}),
+ )
+}
+
+fn run(run_id: impl ToString, run_type: &str, seconds: u64) -> Vec<u8> {
+ frame(
+ "runs.updated",
+ json!({
+ "run_id": run_id.to_string(), "run_type": run_type, "status": "succeeded",
+ "started_at": "2026-09-10T12:00:00+00:00",
+ "completed_at": format!("2026-09-10T12:{:02}:{:02}+00:00", seconds / 60, seconds % 60),
+ }),
+ )
+}
+
+fn spawn(transport: Arc<FakeTransport>, sink: Arc<FakeSink>) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(async move {
+ run_notifications(&*transport, Arc::new(Mutex::new(NotificationFilter::default())), &*sink).await;
+ })
+}
+
+async fn settle() {
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn global_sse_is_an_allow_list_not_a_second_event_bus() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ let mut chunks = vec![b": stream connected\n\nevent: connected\ndata: {}\n\n: ping\n\n".to_vec()];
+ for event in [
+ "message.new",
+ "session.activity",
+ "queue.updated",
+ "inbox.unread.changed",
+ "show.event",
+ "invented.event",
+ ] {
+ chunks.push(frame(event, json!({
+ "request_id": "approval", "request_status": "pending", "run_id": "run", "status": "succeeded", "run_type": "scheduled",
+ })));
+ }
+ chunks.extend([approval("approval", "pending"), run("run", "watch", 2)]);
+ transport.stream(chunks, false);
+ let task = spawn(transport, sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ [NotificationIntent::ApprovalRequested, NotificationIntent::RunSucceeded]
+ );
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn approvals_reset_only_on_observed_non_pending_transitions() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport.stream(
+ [
+ approval("request", "pending"),
+ approval("request", "pending"),
+ approval("request", "approved"),
+ approval("request", "pending"),
+ approval("request", "pending"),
+ ],
+ false,
+ );
+ let task = spawn(transport, sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ vec![NotificationIntent::ApprovalRequested; 2]
+ );
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn malformed_or_mismatched_envelopes_cannot_become_attention_and_runtime_copy_is_never_forwarded() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ let pending = json!({"request_id": "request", "request_status": "pending"});
+ transport.stream(
+ [
+ b"event: vaults.updated\ndata: not-json\n\n".to_vec(),
+ b"event: vaults.updated\ndata: {\"type\":\"runs.updated\",\"data\":{}}\n\n".to_vec(),
+ frame("vaults.updated", json!({"request_status": "pending"})),
+ frame("vaults.updated", json!({"request_id": "", "request_status": "pending"})),
+ frame(
+ "runs.updated",
+ json!({"run_id": "run", "status": "running", "run_type": "scheduled"}),
+ ),
+ frame(
+ "runs.updated",
+ json!({"run_id": "", "status": "failed", "run_type": "scheduled"}),
+ ),
+ frame("vaults.updated", pending),
+ frame(
+ "runs.updated",
+ json!({
+ "run_id": "run", "status": "failed", "run_type": "scheduled", "session_id": "untrusted\ntext",
+ "title": "untrusted title", "body": "untrusted body", "error": "untrusted error",
+ }),
+ ),
+ ],
+ false,
+ );
+ let task = spawn(transport, sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ [NotificationIntent::ApprovalRequested, NotificationIntent::RunFailed]
+ );
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn refetch_timeout_is_bounded_and_cannot_block_later_attention_forever() {
+ let transport = Arc::new(FakeTransport {
+ detail_delay: Duration::from_secs(60),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ transport.stream(
+ [
+ frame("runs.updated", json!({"run_id": "run", "status": "failed"})),
+ approval("request", "pending"),
+ ],
+ false,
+ );
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ tokio::time::advance(Duration::from_secs(5)).await;
+ settle().await;
+ assert_eq!(*transport.refetched.lock().unwrap(), ["run"]);
+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn idle_streams_reconnect_and_rejected_connections_back_off_without_bootstrap_recovery() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport.stream([b": stream connected\n\n".to_vec()], false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ tokio::time::advance(Duration::from_secs(45)).await;
+ settle().await;
+ for seconds in [1, 2, 4, 8, 16, 30, 30] {
+ let before = transport.connected_at.lock().unwrap().len();
+ tokio::time::advance(Duration::from_secs(seconds)).await;
+ settle().await;
+ assert_eq!(transport.connected_at.lock().unwrap().len(), before + 1);
+ }
+ transport.stream([approval("recovered", "pending")], false);
+ tokio::time::advance(Duration::from_secs(30)).await;
+ settle().await;
+ assert_eq!(*sink.delivered.lock().unwrap(), [NotificationIntent::ApprovalRequested]);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn durable_duration_not_arrival_or_attach_time_controls_all_other_run_kinds() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ tokio::time::advance(Duration::from_secs(60)).await;
+ let mut chunks = Vec::new();
+ let mut expected = 0;
+ for kind in ["agent_run", "scheduled", "watch", "task", "foreground", "new_kind"] {
+ for seconds in [0, 2, 29, 30, 31, 90] {
+ chunks.push(run(format!("{kind}-{seconds}"), kind, seconds));
+ expected += usize::from(seconds >= 30 || matches!(kind, "scheduled" | "watch"));
+ }
+ }
+ transport.stream(chunks, false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ vec![NotificationIntent::RunSucceeded; expected]
+ );
+ assert!(transport.refetched.lock().unwrap().is_empty());
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn terminal_stamps_cover_offsets_updated_at_precision_and_fail_closed_values() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ let cases = [
+ ("2026-09-10T20:00:00+08:00", "2026-09-10T12:00:30Z", true),
+ ("2026-09-10T12:00:00.000001Z", "2026-09-10T12:00:30Z", false),
+ ("2026-09-10T12:00:00Z", "2026-09-10T12:00:29.999999Z", false),
+ ("2026-09-10T12:00:00Z", "2026-09-10T11:59:00Z", false),
+ ("invalid", "2026-09-10T12:00:30Z", false),
+ ("2026-09-10T12:00:00Z", "invalid", false),
+ ];
+ let mut chunks = Vec::new();
+ let mut expected = 0;
+ for (index, (started, completed, long)) in cases.iter().enumerate() {
+ for stamp in ["completed_at", "updated_at"] {
+ let mut data = json!({"run_id": format!("{index}-{stamp}"), "status": "failed", "started_at": started});
+ data[stamp] = json!(completed);
+ chunks.push(frame("runs.updated", data));
+ expected += usize::from(*long);
+ }
+ }
+ chunks.push(frame(
+ "runs.updated",
+ json!({
+ "run_id": "completed-wins", "status": "succeeded", "started_at": "2026-09-10T12:00:00Z",
+ "completed_at": "2026-09-10T12:00:02Z", "updated_at": "2026-09-10T12:01:00Z",
+ }),
+ ));
+ transport.stream(chunks, false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ vec![NotificationIntent::RunFailed; expected]
+ );
+ assert!(transport.refetched.lock().unwrap().is_empty());
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn missing_stamps_refetch_once_per_retained_terminal_and_then_fail_closed() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ let complete = RunTimestamps {
+ started_at: Some("2026-09-10T12:00:00Z".into()),
+ completed_at: Some("2026-09-10T12:00:30Z".into()),
+ ..RunTimestamps::default()
+ };
+ let mut chunks = Vec::new();
+ for (index, stamps) in [
+ complete.clone(),
+ RunTimestamps {
+ started_at: None,
+ ..complete.clone()
+ },
+ RunTimestamps {
+ completed_at: None,
+ ..complete.clone()
+ },
+ RunTimestamps::default(),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let key = index.to_string();
+ transport.details.lock().unwrap().insert(key.clone(), stamps);
+ let event = frame(
+ "runs.updated",
+ json!({"run_id": key, "status": "canceled", "run_type": "agent_run"}),
+ );
+ chunks.extend([event.clone(), event]);
+ }
+ let event = frame("runs.updated", json!({"run_id": "404", "status": "canceled"}));
+ chunks.extend([event.clone(), event]);
+ for (key, data) in [
+ ("fill-start", json!({"completed_at": "2026-09-10T12:00:30Z"})),
+ ("fill-end", json!({"started_at": "2026-09-10T12:00:00Z"})),
+ ] {
+ transport.details.lock().unwrap().insert(key.into(), complete.clone());
+ let mut data = data;
+ data["run_id"] = json!(key);
+ data["status"] = json!("canceled");
+ chunks.push(frame("runs.updated", data));
+ }
+ transport.stream(chunks, false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(
+ *sink.delivered.lock().unwrap(),
+ vec![NotificationIntent::RunCanceled; 3]
+ );
+ assert_eq!(transport.refetched.lock().unwrap().len(), 7);
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn both_key_classes_evict_the_oldest_and_allow_it_to_notify_again() {
+ for approval_class in [true, false] {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ let event = |index| {
+ if approval_class {
+ approval(index, "pending")
+ } else {
+ run(index, "watch", 0)
+ }
+ };
+ let mut chunks = (0..=RETAINED_KEYS).map(event).collect::<Vec<_>>();
+ chunks.push(event(RETAINED_KEYS));
+ chunks.push(event(0));
+ transport.stream(chunks, false);
+ let task = spawn(transport, sink.clone());
+ settle().await;
+ assert_eq!(sink.delivered.lock().unwrap().len(), RETAINED_KEYS + 2);
+ task.abort();
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn both_key_classes_expire_after_24_hours_despite_missing_transitions() {
+ let filter = Arc::new(Mutex::new(NotificationFilter::default()));
+ let sink = Arc::new(FakeSink::default());
+ for (elapsed, expected) in [
+ (Duration::ZERO, 2),
+ (RETENTION - Duration::from_secs(1), 2),
+ (Duration::from_secs(1), 4),
+ ] {
+ tokio::time::advance(elapsed).await;
+ let transport = Arc::new(FakeTransport::default());
+ transport.stream([approval("same", "pending"), run("same", "watch", 0)], false);
+ let retained = filter.clone();
+ let output = sink.clone();
+ let task = tokio::spawn(async move { run_notifications(&*transport, retained, &*output).await });
+ settle().await;
+ assert_eq!(sink.delivered.lock().unwrap().len(), expected);
+ task.abort();
+ assert!(task.await.unwrap_err().is_cancelled());
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn gate_suppression_is_not_a_queue_or_a_disconnect() {
+ for enabled in [false, true] {
+ for focused in [false, true] {
+ for visible in [false, true] {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ sink.enabled.store(enabled, Ordering::SeqCst);
+ sink.focused.store(focused, Ordering::SeqCst);
+ sink.visible.store(visible, Ordering::SeqCst);
+ transport.stream([approval("same", "pending")], true);
+ transport.stream([approval("same", "pending"), approval("new", "pending")], false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ let expected = usize::from(enabled && !(focused && visible));
+ assert_eq!(sink.delivered.lock().unwrap().len(), expected);
+ sink.enabled.store(true, Ordering::SeqCst);
+ sink.focused.store(false, Ordering::SeqCst);
+ tokio::time::advance(Duration::from_secs(1)).await;
+ settle().await;
+ assert_eq!(sink.delivered.lock().unwrap().len(), expected + 1);
+ assert_eq!(transport.connected_at.lock().unwrap().len(), 2);
+ task.abort();
+ }
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn focus_is_rechecked_after_refetch_without_deferring_the_notification() {
+ let transport = Arc::new(FakeTransport {
+ detail_delay: Duration::from_secs(2),
+ ..FakeTransport::default()
+ });
+ let sink = Arc::new(FakeSink::default());
+ transport.details.lock().unwrap().insert(
+ "run".into(),
+ RunTimestamps {
+ started_at: Some("2026-09-10T12:00:00Z".into()),
+ completed_at: Some("2026-09-10T12:01:00Z".into()),
+ ..RunTimestamps::default()
+ },
+ );
+ transport.stream(
+ [frame("runs.updated", json!({"run_id": "run", "status": "succeeded"}))],
+ false,
+ );
+ let task = spawn(transport, sink.clone());
+ settle().await;
+ sink.focused.store(true, Ordering::SeqCst);
+ tokio::time::advance(Duration::from_secs(2)).await;
+ settle().await;
+ assert!(sink.delivered.lock().unwrap().is_empty());
+ sink.focused.store(false, Ordering::SeqCst);
+ settle().await;
+ assert!(sink.delivered.lock().unwrap().is_empty());
+ task.abort();
+}
+
+#[tokio::test(start_paused = true)]
+async fn reconnect_discards_partial_frames_keeps_dedup_and_has_no_bootstrap_dependency() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport.stream(
+ [approval("first", "pending"), b"event: vaults.updated\ndata: {".to_vec()],
+ true,
+ );
+ transport.stream([approval("first", "pending"), approval("second", "pending")], false);
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+ assert_eq!(sink.delivered.lock().unwrap().len(), 1);
+ tokio::time::advance(Duration::from_millis(999)).await;
+ settle().await;
+ assert_eq!(transport.connected_at.lock().unwrap().len(), 1);
+ tokio::time::advance(Duration::from_millis(1)).await;
+ settle().await;
+ assert_eq!(transport.connected_at.lock().unwrap().len(), 2);
+ assert_eq!(sink.delivered.lock().unwrap().len(), 2);
+ task.abort();
+ assert!(task.await.unwrap_err().is_cancelled());
+ tokio::time::advance(Duration::from_secs(120)).await;
+ assert_eq!(transport.connected_at.lock().unwrap().len(), 2);
+}
+
+#[test]
+fn framing_is_invariant_under_byte_chunking_and_line_endings() {
+ for ending in ["\n", "\r\n", "\r"] {
+ let source = [
+ "\u{feff}: stream connected",
+ "",
+ "event: vaults.updated",
+ "id: ignored",
+ "retry: 0",
+ "data: {",
+ "data: \"type\":\"vaults.updated\",\"data\":{\"request_id\":\"请求\",\"request_status\":\"pending\"}}",
+ "",
+ "",
+ ]
+ .join(ending);
+ for chunk_size in 1..=source.len() {
+ let mut decoder = SseDecoder::new();
+ let frames = source
+ .as_bytes()
+ .chunks(chunk_size)
+ .flat_map(|chunk| decoder.push(chunk))
+ .collect::<Vec<_>>();
+ assert_eq!(frames.len(), 1);
+ assert_eq!(frames[0].event, "vaults.updated");
+ assert_eq!(
+ serde_json::from_str::<Value>(&frames[0].data).unwrap()["data"]["request_id"],
+ "请求"
+ );
+ }
+ }
+}
+
+#[test]
+fn oversized_or_invalid_frames_are_discarded_until_the_next_real_blank_line() {
+ let mut source = b"event: vaults.updated\ndata: ".to_vec();
+ source.extend(vec![b'x'; 128 * 1024]);
+ source.extend(b"\nevent: vaults.updated\ndata: hidden\n\n");
+ source.extend(b"event: vaults.updated\ndata: \xff\n\n");
+ source.extend(approval("valid", "pending"));
+ let mut decoder = SseDecoder::new();
+ let frames = source
+ .chunks(71)
+ .flat_map(|chunk| decoder.push(chunk))
+ .collect::<Vec<_>>();
+ assert_eq!(frames.len(), 1);
+ assert!(frames[0].data.contains("valid"));
+}
+
+#[test]
+fn reconnect_backoff_is_positive_capped_and_resettable() {
+ let mut backoff = ReconnectBackoff::default();
+ for expected in [1, 2, 4, 8, 16, 30, 30, 30, 30] {
+ assert_eq!(backoff.next_delay(), Duration::from_secs(expected));
+ }
+ backoff.reset();
+ assert_eq!(backoff.next_delay(), Duration::from_secs(1));
+}
diff --git a/desktop/runtime-sources.json b/desktop/runtime-sources.json
new file mode 100644
index 000000000..dfa6e6e04
--- /dev/null
+++ b/desktop/runtime-sources.json
@@ -0,0 +1,65 @@
+{
+ "schema_version": 2,
+ "npm_version": "10.9.8",
+ "sdist_build_allowlist": [
+ "claude-agent-sdk",
+ "http-ece"
+ ],
+ "show_runtime_manifest": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/v3.0.7/show-runtime-manifest.json",
+ "sha256": "e9ca5bc2106ec59f23394e164fb30ed41135240d6fdff8054535ea7cdd80f8e2"
+ },
+ "targets": {
+ "aarch64-apple-darwin": {
+ "os": "macos",
+ "arch": "aarch64",
+ "python": {
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260510/cpython-3.12.13%2B20260510-aarch64-apple-darwin-install_only_stripped.tar.gz",
+ "sha256": "55bc1a5edbc8ac4da0081f4f5731ed2d1ed10c57cb37a820b2a0dbc7cad742e9"
+ },
+ "node": {
+ "url": "https://nodejs.org/dist/v22.23.1/node-v22.23.1-darwin-arm64.tar.gz",
+ "sha256": "ef28d8fab2c0e4314522d4bb1b7173270aa3937e93b92cb7de79c112ac1fa953"
+ },
+ "python_entrypoint": "python/bin/python3",
+ "node_source": "bin/node",
+ "node_entrypoint": "tools/bin/node",
+ "npm_source": "lib/node_modules/npm",
+ "npm_entrypoint": "tools/npm/bin/npm-cli.js"
+ },
+ "x86_64-apple-darwin": {
+ "os": "macos",
+ "arch": "x86_64",
+ "python": {
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260510/cpython-3.12.13%2B20260510-x86_64-apple-darwin-install_only_stripped.tar.gz",
+ "sha256": "6bab7fa97d4f2ddba86da0e05acff66c53b5edaca1df8edcf00ddca785a9c59b"
+ },
+ "node": {
+ "url": "https://nodejs.org/dist/v22.23.1/node-v22.23.1-darwin-x64.tar.gz",
+ "sha256": "b8da981b8a0b1241b70249204916da76c63573ddf5814dbd2d1e41069105cb81"
+ },
+ "python_entrypoint": "python/bin/python3",
+ "node_source": "bin/node",
+ "node_entrypoint": "tools/bin/node",
+ "npm_source": "lib/node_modules/npm",
+ "npm_entrypoint": "tools/npm/bin/npm-cli.js"
+ },
+ "x86_64-pc-windows-msvc": {
+ "os": "windows",
+ "arch": "x86_64",
+ "python": {
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260510/cpython-3.12.13%2B20260510-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
+ "sha256": "24168aff2e7d93784c6a436124c4ebb79b076a4e289bde4902c08333507b71d0"
+ },
+ "node": {
+ "url": "https://nodejs.org/dist/v22.23.1/node-v22.23.1-win-x64.zip",
+ "sha256": "7df0bc9375723f4a86b3aa1b7cc73342423d9677a8df4538aca31a049e309c29"
+ },
+ "python_entrypoint": "python/python.exe",
+ "node_source": "node.exe",
+ "node_entrypoint": "tools/bin/node.exe",
+ "npm_source": "node_modules/npm",
+ "npm_entrypoint": "tools/npm/bin/npm-cli.js"
+ }
+ }
+}
diff --git a/desktop/rustfmt.toml b/desktop/rustfmt.toml
new file mode 100644
index 000000000..b76f01ee6
--- /dev/null
+++ b/desktop/rustfmt.toml
@@ -0,0 +1,3 @@
+# Wide enough that the shell's descriptive names and doc comments do not force
+# awkward wrapping; everything else stays at rustfmt defaults.
+max_width = 120
diff --git a/desktop/scripts/build-runtime-bundle.py b/desktop/scripts/build-runtime-bundle.py
new file mode 100755
index 000000000..97ebb2c39
--- /dev/null
+++ b/desktop/scripts/build-runtime-bundle.py
@@ -0,0 +1,791 @@
+#!/usr/bin/env python3
+"""Build one target-specific, offline Avibe desktop Runtime payload."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import shutil
+import signal
+import socket
+import stat
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.parse
+import urllib.request
+import zipfile
+from pathlib import Path
+from typing import Any
+
+
+DESKTOP_DIR = Path(__file__).resolve().parents[1]
+REPO_ROOT = DESKTOP_DIR.parent
+SOURCES_PATH = DESKTOP_DIR / "runtime-sources.json"
+DEFAULT_OUTPUT = DESKTOP_DIR / "src-tauri" / "resources" / "runtime"
+COPY_CHUNK = 1024 * 1024
+FIXED_ZIP_TIME = (2020, 1, 1, 0, 0, 0)
+TREE_HASH_DOMAIN = b"avibe-runtime-tree-v1\0"
+
+# Everything the probe Runtime records about its own startup, relative to the
+# probe HOME. The process logs are the runtime directory's sink files; the
+# application log is the service's own structured output.
+PROBE_DIAGNOSTIC_FILES = (
+ "runtime/service_stderr.log",
+ "runtime/service_stdout.log",
+ "runtime/ui_stderr.log",
+ "runtime/ui_stdout.log",
+ "runtime/status.json",
+ "logs/vibe_remote.log",
+)
+PROBE_PID_FILES = (
+ "runtime/vibe.pid",
+ "runtime/vibe-ui.pid",
+ "runtime/remote-access-cloudflared.pid",
+)
+PROBE_DIAGNOSTIC_TAIL_BYTES = 64 * 1024
+
+
+def sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as file:
+ for chunk in iter(lambda: file.read(COPY_CHUNK), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def run(command: list[str], *, cwd: Path = REPO_ROOT, env: dict[str, str] | None = None) -> None:
+ subprocess.run(command, cwd=cwd, env=env, check=True)
+
+
+def download(source: dict[str, str], cache_dir: Path) -> Path:
+ url = source["url"]
+ expected = source["sha256"]
+ name = Path(urllib.parse.urlparse(url).path).name
+ destination = cache_dir / name
+ if destination.is_file() and sha256(destination) == expected:
+ return destination
+
+ partial = destination.with_suffix(destination.suffix + ".partial")
+ partial.unlink(missing_ok=True)
+ request = urllib.request.Request(url, headers={"User-Agent": "Avibe-Desktop-Builder/1"})
+ with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as output:
+ shutil.copyfileobj(response, output, COPY_CHUNK)
+ if sha256(partial) != expected:
+ partial.unlink(missing_ok=True)
+ raise SystemExit(f"Downloaded asset failed SHA-256 verification: {url}")
+ os.replace(partial, destination)
+ return destination
+
+
+def extract_source(archive: Path, destination: Path) -> Path:
+ before = set(destination.iterdir()) if destination.exists() else set()
+ destination.mkdir(parents=True, exist_ok=True)
+ if archive.name.endswith(".zip"):
+ with zipfile.ZipFile(archive) as source:
+ for member in source.infolist():
+ target = (destination / member.filename).resolve()
+ if destination.resolve() not in target.parents and target != destination.resolve():
+ raise SystemExit(f"Unsafe source archive entry: {member.filename}")
+ source.extractall(destination)
+ else:
+ with tarfile.open(archive, "r:gz") as source:
+ source.extractall(destination, filter="data")
+ created = [path for path in destination.iterdir() if path not in before]
+ if len(created) != 1 or not created[0].is_dir():
+ raise SystemExit(f"Expected one top-level directory in {archive.name}")
+ return created[0]
+
+
+def ensure_show_runtime_manifest(sources: dict[str, Any], cache_dir: Path) -> tuple[Path, bool]:
+ destination = REPO_ROOT / "vibe" / "show_runtime_manifest.json"
+ expected = sources["show_runtime_manifest"]["sha256"]
+ if destination.is_file():
+ if sha256(destination) != expected:
+ raise SystemExit(
+ "Existing vibe/show_runtime_manifest.json does not match "
+ "desktop/runtime-sources.json"
+ )
+ return destination, False
+ source = download(sources["show_runtime_manifest"], cache_dir)
+ destination.write_bytes(source.read_bytes())
+ return destination, True
+
+
+def build_wheel(work_dir: Path, private_python: Path, sources: dict[str, Any], cache_dir: Path) -> Path:
+ if not (REPO_ROOT / "ui" / "dist" / "index.html").is_file():
+ raise SystemExit("ui/dist is missing; build the Workbench before the private Runtime")
+
+ generated_manifest, remove_manifest = ensure_show_runtime_manifest(sources, cache_dir)
+ wheel_dir = work_dir / "wheel"
+ wheel_dir.mkdir()
+ try:
+ run(
+ [
+ "uv",
+ "build",
+ "--wheel",
+ "--out-dir",
+ str(wheel_dir),
+ "--no-create-gitignore",
+ "--python",
+ str(private_python),
+ ]
+ )
+ finally:
+ if remove_manifest:
+ generated_manifest.unlink(missing_ok=True)
+ wheels = list(wheel_dir.glob("*.whl"))
+ if len(wheels) != 1:
+ raise SystemExit(f"Expected one Avibe wheel, found {len(wheels)}")
+ return wheels[0]
+
+
+def install_python_environment(
+ private_python: Path,
+ wheel: Path,
+ work_dir: Path,
+ sdist_build_allowlist: list[str],
+) -> str:
+ requirements = work_dir / "requirements.txt"
+ run(
+ [
+ "uv",
+ "export",
+ "--frozen",
+ "--no-dev",
+ "--no-emit-project",
+ "--output-file",
+ str(requirements),
+ "--python",
+ str(private_python),
+ "--quiet",
+ ]
+ )
+ install_command = [
+ "uv",
+ "pip",
+ "install",
+ "--python",
+ str(private_python),
+ "--require-hashes",
+ "--only-binary=:all:",
+ "--no-cache",
+ "--requirements",
+ str(requirements),
+ ]
+ for package in sdist_build_allowlist:
+ install_command.extend(["--no-binary", package])
+ run(install_command)
+ run(
+ [
+ "uv",
+ "pip",
+ "install",
+ "--python",
+ str(private_python),
+ "--no-deps",
+ "--no-cache",
+ str(wheel),
+ ]
+ )
+ completed = subprocess.run(
+ [
+ str(private_python),
+ "-I",
+ "-c",
+ "from importlib.metadata import version; print(version('avibe-os'))",
+ ],
+ cwd=work_dir,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return completed.stdout.strip()
+
+
+def verify_python_runtime_excludes_agent_backends(private_python: Path, work_dir: Path) -> None:
+ """Reject Python dependencies that smuggle an Agent backend into the Runtime."""
+
+ probe = """
+from pathlib import Path
+import claude_agent_sdk
+
+bundled = Path(claude_agent_sdk.__file__).resolve().parent / "_bundled"
+for name in ("claude", "claude.exe"):
+ candidate = bundled / name
+ if candidate.is_file() or candidate.is_symlink():
+ raise SystemExit(f"Runtime contains bundled Agent backend: {candidate}")
+""".strip()
+ subprocess.run(
+ [str(private_python), "-I", "-c", probe],
+ cwd=work_dir,
+ check=True,
+ )
+
+
+def install_node_toolchain(
+ target_config: dict[str, Any],
+ node_archive: Path,
+ payload: Path,
+ work_dir: Path,
+ expected_npm_version: str,
+) -> None:
+ node_root = extract_source(node_archive, work_dir / "node-source")
+ node_source = node_root / target_config["node_source"]
+ node_destination = payload / target_config["node_entrypoint"]
+ if not node_source.is_file():
+ raise SystemExit(f"Node distribution is missing {target_config['node_source']}")
+ node_destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(node_source, node_destination)
+
+ npm_source = node_root / target_config["npm_source"]
+ npm_destination = payload / "tools" / "npm"
+ if not npm_source.is_dir():
+ raise SystemExit(f"Node distribution is missing npm at {target_config['npm_source']}")
+ _validate_npm_links(npm_source)
+ shutil.copytree(npm_source, npm_destination)
+ if any(path.is_symlink() for path in npm_destination.rglob("*")):
+ raise SystemExit("Private Runtime npm must not contain symlinks")
+
+ npm_entrypoint = payload / target_config["npm_entrypoint"]
+ npm_package = npm_destination / "package.json"
+ npm_license = npm_destination / "LICENSE"
+ if not npm_entrypoint.is_file() or not npm_package.is_file() or not npm_license.is_file():
+ raise SystemExit("Node distribution contains an incomplete npm package")
+ npm_metadata = json.loads(npm_package.read_text(encoding="utf-8"))
+ if npm_metadata.get("version") != expected_npm_version:
+ raise SystemExit(
+ f"Node distribution contains npm {npm_metadata.get('version')}, expected {expected_npm_version}"
+ )
+ tools_root = payload / "tools"
+ if {path.name for path in tools_root.iterdir()} != {"bin", "npm"}:
+ raise SystemExit("Private Runtime tools must contain only Node.js and npm")
+ if {path.name for path in node_destination.parent.iterdir()} != {node_destination.name}:
+ raise SystemExit("Private Runtime tools/bin must contain only the Node.js executable")
+
+ licenses = payload / "licenses"
+ licenses.mkdir()
+ for source, name in [
+ (node_root / "LICENSE", "node-LICENSE"),
+ (REPO_ROOT / "LICENSE", "avibe-LICENSE"),
+ (npm_license, "npm-LICENSE"),
+ ]:
+ if not source.is_file():
+ raise SystemExit(f"Required Runtime license is missing: {source}")
+ shutil.copy2(source, licenses / name)
+
+ if target_config["os"] != "windows":
+ node_destination.chmod(node_destination.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+ completed = subprocess.run(
+ [str(node_destination), str(npm_entrypoint), "--version"],
+ cwd=work_dir,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ if completed.stdout.strip() != expected_npm_version:
+ raise SystemExit("Private npm entrypoint returned an unexpected version")
+
+
+def _validate_npm_links(npm_source: Path) -> None:
+ """Allow only npm's contained file links, which copytree dereferences."""
+
+ root = npm_source.resolve(strict=True)
+ for link in npm_source.rglob("*"):
+ if not link.is_symlink():
+ continue
+ try:
+ target = link.resolve(strict=True)
+ target.relative_to(root)
+ except (OSError, ValueError) as exc:
+ raise SystemExit(f"Bundled npm link escapes its package: {link}") from exc
+ if not target.is_file():
+ raise SystemExit(f"Bundled npm link must target a regular file: {link}")
+
+
+def write_inventory(private_python: Path, payload: Path) -> None:
+ program = """
+import importlib.metadata
+import json
+items = sorted(
+ ({"name": item.metadata["Name"], "version": item.version} for item in importlib.metadata.distributions()),
+ key=lambda item: (item["name"].lower(), item["version"]),
+)
+print(json.dumps({"schema_version": 1, "python_packages": items}, indent=2, sort_keys=True))
+"""
+ completed = subprocess.run(
+ [str(private_python), "-I", "-c", program],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ (payload / "runtime-packages.json").write_text(completed.stdout, encoding="utf-8")
+
+
+def create_runtime_zip(payload: Path, archive: Path) -> tuple[int, int, str]:
+ unpacked_size = 0
+ entry_count = 0
+ tree_hasher = hashlib.sha256(TREE_HASH_DOMAIN)
+ files = [
+ (path.relative_to(payload).as_posix(), path)
+ for path in payload.rglob("*")
+ if path.is_file()
+ ]
+ files.sort(key=lambda item: item[0])
+ with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9, allowZip64=True) as output:
+ for relative, path in files:
+ relative_bytes = relative.encode("utf-8")
+ file_size = path.stat().st_size
+ tree_hasher.update(len(relative_bytes).to_bytes(8, "big"))
+ tree_hasher.update(relative_bytes)
+ tree_hasher.update(file_size.to_bytes(8, "big"))
+ mode = 0o755 if os.access(path, os.X_OK) else 0o644
+ info = zipfile.ZipInfo(relative, FIXED_ZIP_TIME)
+ info.compress_type = zipfile.ZIP_DEFLATED
+ info.external_attr = (stat.S_IFREG | mode) << 16
+ with path.open("rb") as source, output.open(info, "w", force_zip64=True) as destination:
+ for chunk in iter(lambda: source.read(COPY_CHUNK), b""):
+ tree_hasher.update(chunk)
+ destination.write(chunk)
+ unpacked_size += file_size
+ entry_count += 1
+ return unpacked_size, entry_count, tree_hasher.hexdigest()
+
+
+def reserve_loopback_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
+ listener.bind(("127.0.0.1", 0))
+ return int(listener.getsockname()[1])
+
+
+def collect_probe_diagnostics(
+ probe_home: Path,
+ *,
+ tail_bytes: int = PROBE_DIAGNOSTIC_TAIL_BYTES,
+) -> str:
+ """Render what the probe Runtime recorded about itself, for the job log.
+
+ The probe runs with its whole HOME inside a temporary directory, so the
+ service and UI logs that explain a startup failure are written and then
+ deleted without ever reaching the job output. Whoever reads the job is left
+ holding an exception about the probe rather than about the process that
+ died. Every file is optional: the point is to report whatever exists.
+ """
+ sections = [f"--- Private Runtime probe diagnostics: {probe_home} ---"]
+ for relative in PROBE_DIAGNOSTIC_FILES:
+ path = probe_home.joinpath(*relative.split("/"))
+ try:
+ raw = path.read_bytes()
+ except FileNotFoundError:
+ sections.append(f"--- {relative}: absent ---")
+ continue
+ except OSError as error:
+ sections.append(f"--- {relative}: unreadable: {error} ---")
+ continue
+ kept = f"last {tail_bytes} of {len(raw)} bytes" if len(raw) > tail_bytes else f"{len(raw)} bytes"
+ sections.append(f"--- {relative} ({kept}) ---")
+ sections.append(raw[-tail_bytes:].decode("utf-8", "replace").strip() or "(empty)")
+ return "\n".join(sections)
+
+
+def terminate_probe_processes(probe_home: Path) -> None:
+ """Take down whatever the probe's pid files still name.
+
+ `vibe stop` is the supported path and has already run; this covers only what
+ it could not. A UI process that failed its health checks is still recorded
+ and left running, and the log handles it holds make the temporary
+ directory's removal fail on Windows, so a cleanup error ends up replacing
+ the real one. A survivor would also still hold the reserved port.
+ """
+ for relative in PROBE_PID_FILES:
+ path = probe_home.joinpath(*relative.split("/"))
+ try:
+ pid = int(path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ continue
+ if pid <= 0:
+ continue
+ print(f"--- terminating leftover probe process {relative} pid={pid} ---", file=sys.stderr, flush=True)
+ if os.name == "nt":
+ # /T carries the inherited log sinks with it, and without /F a
+ # process already wedged enough to reach here will not go.
+ subprocess.run(
+ ["taskkill", "/F", "/T", "/PID", str(pid)],
+ check=False,
+ capture_output=True,
+ timeout=30,
+ )
+ continue
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except OSError:
+ continue
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ try:
+ os.kill(pid, 0)
+ except OSError:
+ break
+ time.sleep(0.1)
+ else:
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+
+
+def verify_payload(
+ target_config: dict[str, Any],
+ payload: Path,
+ work_dir: Path,
+ expected_npm_version: str,
+) -> None:
+ # Keep AVIBE_HOME short on macOS: its absolute state path is embedded in the
+ # AF_UNIX dispatch address, whose platform limit is much smaller than a
+ # typical CI checkout path.
+ #
+ # Cleanup errors are ignored because a process that outlived the failure
+ # path holds handles here on Windows, and the resulting PermissionError
+ # would be the exception the job reports instead of the one that matters.
+ with tempfile.TemporaryDirectory(prefix="avibe-probe-", ignore_cleanup_errors=True) as probe_home:
+ home = Path(probe_home)
+ try:
+ _verify_payload_with_home(
+ target_config,
+ payload,
+ work_dir,
+ home,
+ expected_npm_version,
+ )
+ except BaseException:
+ # SystemExit is how this script reports verification failures, so
+ # this has to catch BaseException to see them at all. The probe HOME
+ # is about to be removed and takes the only account of the failure
+ # with it, so report it here, and leave nothing running.
+ terminate_probe_processes(home)
+ # The log sinks are separate processes that exit once the pipe they
+ # hold closes; give them a moment to drain before reading.
+ time.sleep(1.0)
+ sys.stdout.flush()
+ print(collect_probe_diagnostics(home), file=sys.stderr, flush=True)
+ raise
+
+
+def private_probe_environment(probe_home: Path, node: Path, npm_cli: Path) -> dict[str, str]:
+ inherited_path = os.environ.get("PATH", "")
+ retained_env = {
+ name: value
+ for name, value in os.environ.items()
+ if name
+ in {
+ "COMSPEC",
+ "LANG",
+ "LC_ALL",
+ "PATHEXT",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "WINDIR",
+ }
+ }
+ return {
+ **retained_env,
+ "HOME": str(probe_home),
+ "USERPROFILE": str(probe_home),
+ "APPDATA": str(probe_home / "appdata"),
+ "LOCALAPPDATA": str(probe_home / "local-appdata"),
+ "XDG_CACHE_HOME": str(probe_home / "cache"),
+ "XDG_CONFIG_HOME": str(probe_home / "config"),
+ "XDG_DATA_HOME": str(probe_home / "data"),
+ "XDG_STATE_HOME": str(probe_home / "state"),
+ "CODEX_HOME": str(probe_home / "codex"),
+ "AVIBE_HOME": str(probe_home),
+ "PATH": os.pathsep.join(
+ part
+ for part in (
+ str(node.parent),
+ inherited_path,
+ )
+ if part
+ ),
+ "VIBE_SHOW_RUNTIME_NODE_BIN": str(node),
+ "AVIBE_DESKTOP_NPM_CLI": str(npm_cli),
+ "AVIBE_DESKTOP_BACKENDS_ROOT": str(probe_home / "backends"),
+ "AVIBE_DESKTOP_MANAGED_RUNTIME": "1",
+ "VIBE_INSTALL_SKIP_SHOW_RUNTIME": "1",
+ "VIBE_INSTALL_SKIP_ASKILL": "1",
+ "VIBE_ASKILL_AUTO_UPDATE": "0",
+ "VIBE_MODEL_HUB_ENABLED": "0",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ }
+
+
+def _decode_stop_stream(stream: Any) -> str | None:
+ """Normalize a captured stream that may have skipped `text=True` decoding.
+
+ `subprocess.run` decodes its streams on the completion path, which a timeout
+ never reaches: `TimeoutExpired` carries whatever was captured before the
+ deadline as raw bytes even when the call asked for text, and an unwritten
+ stream as `None`. Formatting those bytes would raise a `TypeError` out of
+ the `finally` that calls this, masking the probe failure this whole path
+ exists to report. Decode the way the probe diagnostics do, so an undecodable
+ byte is reported rather than raised.
+ """
+ if isinstance(stream, bytes):
+ return stream.decode("utf-8", "replace")
+ return stream
+
+
+def _stop_report(outcome: str, stdout: str | None, stderr: str | None) -> str:
+ lines = [f"--- vibe stop ({outcome}) ---"]
+ for name, stream in (("stdout", stdout), ("stderr", stderr)):
+ text = (stream or "").strip()
+ if text:
+ lines.append(f"--- vibe stop {name} ---")
+ lines.append(text)
+ return "\n".join(lines)
+
+
+def stop_private_runtime(command: list[str], work_dir: Path, env: dict[str, str]) -> tuple[bool, str]:
+ """Stop the probe Runtime, reporting the outcome instead of raising it.
+
+ This is called from a `finally`, where a timeout raised here would replace
+ the exception that explains why the probe failed; sending the streams to
+ DEVNULL would discard the stop's own account of what it found, which is the
+ other half of the same problem. Both are captured and handed back.
+ """
+ try:
+ result = subprocess.run(
+ [*command, "stop"],
+ cwd=work_dir,
+ env=env,
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ except subprocess.TimeoutExpired as error:
+ return False, _stop_report(
+ "timed out after 60s",
+ _decode_stop_stream(error.stdout),
+ _decode_stop_stream(error.stderr),
+ )
+ except OSError as error:
+ return False, _stop_report(f"could not run: {error}", None, None)
+ return result.returncode == 0, _stop_report(f"exit {result.returncode}", result.stdout, result.stderr)
+
+
+def _verify_payload_with_home(
+ target_config: dict[str, Any],
+ payload: Path,
+ work_dir: Path,
+ probe_home: Path,
+ expected_npm_version: str,
+) -> None:
+ python = payload / target_config["python_entrypoint"]
+ node = payload / target_config["node_entrypoint"]
+ npm_cli = payload / target_config["npm_entrypoint"]
+ config_dir = probe_home / "config"
+ config_dir.mkdir(parents=True)
+ port = reserve_loopback_port()
+ config_path = config_dir / "config.json"
+ env = private_probe_environment(probe_home, node, npm_cli)
+ command = [str(python), "-I", "-m", "vibe"]
+ endpoint = subprocess.run(
+ [*command, "desktop", "endpoint", "--json"],
+ cwd=work_dir,
+ env=env,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ descriptor = json.loads(endpoint.stdout)
+ seeded = json.loads(config_path.read_text(encoding="utf-8"))
+ if (
+ descriptor.get("schema_version") != 1
+ or seeded.get("setup_completed") is not False
+ or (seeded.get("platforms") or {}).get("enabled") != []
+ or (seeded.get("platforms") or {}).get("primary") != "avibe"
+ ):
+ raise SystemExit("Private Runtime did not seed a fresh Workbench onboarding config")
+
+ # Keep the seeded first-run shape intact; only move this isolated probe off
+ # the product's default port so a developer build cannot collide with an
+ # Avibe Runtime already running on the host.
+ seeded["ui"]["setup_host"] = "127.0.0.1"
+ seeded["ui"]["setup_port"] = port
+ seeded["ui"]["open_browser"] = False
+ config_path.write_text(json.dumps(seeded), encoding="utf-8")
+ endpoint = subprocess.run(
+ [*command, "desktop", "endpoint", "--json"],
+ cwd=work_dir,
+ env=env,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ descriptor = json.loads(endpoint.stdout)
+ if descriptor != {"schema_version": 1, "origin": f"http://127.0.0.1:{port}"}:
+ raise SystemExit("Private Runtime did not honor the isolated desktop endpoint")
+
+ run([str(node), "--version"], cwd=work_dir, env=env)
+ npm_version = subprocess.run(
+ [str(node), str(npm_cli), "--version"],
+ cwd=work_dir,
+ env=env,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ if npm_version != expected_npm_version:
+ raise SystemExit("Private Runtime npm version does not match runtime-sources.json")
+
+ ready_url = f"http://127.0.0.1:{port}/ready"
+ try:
+ run([*command, "start", "--no-open-browser"], cwd=work_dir, env=env)
+ deadline = time.monotonic() + 90
+ last_error: Exception | None = None
+ while time.monotonic() < deadline:
+ try:
+ request = urllib.request.Request(ready_url, headers={"Host": f"127.0.0.1:{port}"})
+ with urllib.request.urlopen(request, timeout=2) as response:
+ readiness = json.loads(response.read(4097))
+ if (
+ readiness.get("schema_version") == 1
+ and readiness.get("product") == "avibe"
+ and readiness.get("ready") is True
+ ):
+ break
+ except Exception as error:
+ last_error = error
+ time.sleep(0.25)
+ else:
+ raise SystemExit(f"Private Runtime did not become ready: {last_error}")
+ finally:
+ stopped, stop_report = stop_private_runtime(command, work_dir, env)
+ print(stop_report, file=sys.stderr, flush=True)
+ if not stopped:
+ raise SystemExit("Private Runtime failed to stop cleanly")
+
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ try:
+ urllib.request.urlopen(ready_url, timeout=1).close()
+ except Exception:
+ break
+ time.sleep(0.25)
+ else:
+ raise SystemExit("Private Runtime remained reachable after stop")
+
+
+def prune_payload(payload: Path) -> None:
+ for directory in sorted(payload.rglob("__pycache__"), reverse=True):
+ shutil.rmtree(directory)
+ for file in payload.rglob("*.pyc"):
+ file.unlink()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--target", required=True)
+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
+ parser.add_argument("--cache", type=Path, default=DESKTOP_DIR / "target" / "runtime-cache")
+ args = parser.parse_args()
+
+ sources = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))
+ if sources.get("schema_version") != 2:
+ raise SystemExit("Unsupported runtime-sources.json schema")
+ try:
+ target_config = sources["targets"][args.target]
+ except KeyError:
+ raise SystemExit(f"Unsupported target: {args.target}") from None
+
+ args.cache.mkdir(parents=True, exist_ok=True)
+ python_archive = download(target_config["python"], args.cache)
+ node_archive = download(target_config["node"], args.cache)
+
+ work_parent = DESKTOP_DIR / "target"
+ work_parent.mkdir(exist_ok=True)
+ # Same reason as the probe HOME: a leftover Windows handle on the payload's
+ # own DLLs must not turn into the exception the job reports. The stale
+ # directory under desktop/target/ is the cheaper of the two outcomes.
+ with tempfile.TemporaryDirectory(
+ prefix=f"runtime-{args.target}-",
+ dir=work_parent,
+ ignore_cleanup_errors=True,
+ ) as temporary:
+ work_dir = Path(temporary)
+ payload = work_dir / "payload"
+ python_root = extract_source(python_archive, payload)
+ if python_root.name != "python":
+ raise SystemExit(f"Unexpected Python archive root: {python_root.name}")
+ private_python = payload / target_config["python_entrypoint"]
+ wheel = build_wheel(work_dir, private_python, sources, args.cache)
+ runtime_version = install_python_environment(
+ private_python,
+ wheel,
+ work_dir,
+ sources.get("sdist_build_allowlist", []),
+ )
+ verify_python_runtime_excludes_agent_backends(private_python, work_dir)
+ install_node_toolchain(
+ target_config,
+ node_archive,
+ payload,
+ work_dir,
+ sources["npm_version"],
+ )
+ write_inventory(private_python, payload)
+ verify_payload(target_config, payload, work_dir, sources["npm_version"])
+ prune_payload(payload)
+
+ output_parent = args.output.parent
+ output_parent.mkdir(parents=True, exist_ok=True)
+ staged_output = Path(tempfile.mkdtemp(prefix=".runtime-output-", dir=output_parent))
+ try:
+ archive = staged_output / "runtime.zip"
+ unpacked_size, entry_count, tree_sha256 = create_runtime_zip(payload, archive)
+ wheel_digest = sha256(wheel)
+ manifest = {
+ "schema_version": 2,
+ "runtime_version": runtime_version,
+ "os": target_config["os"],
+ "arch": target_config["arch"],
+ "archive": archive.name,
+ "archive_sha256": sha256(archive),
+ "archive_size": archive.stat().st_size,
+ "unpacked_size": unpacked_size,
+ "entry_count": entry_count,
+ "tree_sha256": tree_sha256,
+ "python_entrypoint": target_config["python_entrypoint"],
+ "node_entrypoint": target_config["node_entrypoint"],
+ "npm_entrypoint": target_config["npm_entrypoint"],
+ "python_distribution": target_config["python"],
+ "node_distribution": target_config["node"],
+ "npm_version": sources["npm_version"],
+ "avibe_wheel": {"name": wheel.name, "sha256": wheel_digest},
+ }
+ (staged_output / "runtime-manifest.json").write_text(
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n",
+ encoding="utf-8",
+ )
+ args.output.mkdir(parents=True, exist_ok=True)
+ for name in ["runtime.zip", "runtime-manifest.json"]:
+ os.replace(staged_output / name, args.output / name)
+ finally:
+ if staged_output.exists():
+ shutil.rmtree(staged_output)
+
+ print(json.dumps({"ok": True, "target": args.target, "output": str(args.output)}, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/desktop/scripts/create-macos-dmg.sh b/desktop/scripts/create-macos-dmg.sh
new file mode 100755
index 000000000..fd8e83667
--- /dev/null
+++ b/desktop/scripts/create-macos-dmg.sh
@@ -0,0 +1,82 @@
+#!/bin/sh
+set -eu
+
+if [ "$#" -ne 2 ]; then
+ echo "usage: create-macos-dmg.sh <Avibe.app> <output.dmg>" >&2
+ exit 2
+fi
+
+app=$1
+output=$2
+
+if [ ! -d "$app/Contents/MacOS" ]; then
+ echo "input is not a macOS application bundle: $app" >&2
+ exit 2
+fi
+
+# Signature-aware staging. A Developer ID (or any identity-bearing) signature
+# is copied as-is: re-signing with an ad-hoc identity here would strip it and
+# the DMG would ship unsigned. An ad-hoc or absent signature means the bundle
+# is an acceptance artifact, and the disposable copy is ad-hoc signed so macOS
+# can still verify its structure.
+#
+# Detection: `codesign -dv` prints `Signature=adhoc` ONLY for ad-hoc
+# signatures — identity signatures print `Signature size=...` and one or more
+# `Authority=...` lines instead, so `Signature=` alone never matches them.
+# Authority lines are the identity-bearing signal; `TeamIdentifier=not set`
+# covers self-signed identities without a team. verbose=4 is required for
+# Authority output.
+identity=$(codesign -dv --verbose=4 "$app" 2>&1 | sed -n 's/^Authority=//p' | head -1 || true)
+adhoc=$(codesign -dv "$app" 2>&1 | sed -n '/^Signature=adhoc$/p' || true)
+
+staging=$(mktemp -d "${TMPDIR:-/tmp}/avibe-dmg.XXXXXX")
+trap 'rm -rf "$staging"' EXIT HUP INT TERM
+
+cp -R "$app" "$staging/Avibe.app"
+ln -s /Applications "$staging/Applications"
+mkdir -p "$(dirname "$output")"
+rm -f "$output"
+
+if [ -n "$adhoc" ] || [ -z "$identity" ]; then
+ # A linker-signed executable does not seal the resources copied into the app
+ # bundle. Ad-hoc sign the disposable DMG copy so macOS can verify its
+ # structure. This is not Developer ID signing and does not bypass
+ # Gatekeeper/notarization.
+ codesign --force --deep --sign - "$staging/Avibe.app"
+ codesign --verify --deep --strict "$staging/Avibe.app"
+else
+ # Sealing the copy must not invalidate the identity signature: verify the
+ # staging copy still validates against the same team before imaging it.
+ codesign --verify --deep --strict "$staging/Avibe.app"
+fi
+
+# Tauri's decorated DMG helper drives Finder through AppleScript, which is
+# brittle on headless CI and hardened developer machines. A plain compressed
+# image has the same install semantics and no GUI dependency.
+#
+# `hdiutil create` intermittently fails with "Resource busy" on CI while the
+# identical call succeeds on another runner in the same job matrix: the imaging
+# helper contends with whatever still holds the freshly written staging tree.
+# Retry a bounded number of times with a pause, and let the last attempt's
+# failure through unchanged so a real defect is still a build failure.
+attempt=1
+while :; do
+ if hdiutil create \
+ -volname Avibe \
+ -srcfolder "$staging" \
+ -format UDZO \
+ -imagekey zlib-level=9 \
+ -ov \
+ "$output"; then
+ break
+ fi
+ if [ "$attempt" -ge 3 ]; then
+ echo "hdiutil create failed after $attempt attempts" >&2
+ exit 1
+ fi
+ echo "hdiutil create failed (attempt $attempt); retrying" >&2
+ attempt=$((attempt + 1))
+ sleep 5
+done
+
+hdiutil verify "$output"
diff --git a/desktop/scripts/verify-i18n.mjs b/desktop/scripts/verify-i18n.mjs
new file mode 100644
index 000000000..57e8fa059
--- /dev/null
+++ b/desktop/scripts/verify-i18n.mjs
@@ -0,0 +1,82 @@
+import assert from 'node:assert/strict'
+import { readFile } from 'node:fs/promises'
+
+const expectedNoticeCodes = [
+ 'adopted',
+ 'invalid_origin',
+ 'launcher_exited',
+ 'probing',
+ 'ready',
+ 'ready_timeout',
+ 'runtime_discovery_failed',
+ 'runtime_install_failed',
+ 'runtime_not_found',
+ 'runtime_ownership_lost',
+ 'runtime_spawn_failed',
+ 'runtime_stopped',
+ 'starting',
+ 'workbench_navigation_failed',
+]
+
+async function catalog(locale) {
+ const source = await readFile(
+ new URL(`../../ui/src/i18n/${locale}.json`, import.meta.url),
+ 'utf8',
+ )
+ return JSON.parse(source).desktopBootstrap
+}
+
+function leafShape(value, prefix = '') {
+ return Object.entries(value)
+ .flatMap(([key, child]) => {
+ const path = prefix ? `${prefix}.${key}` : key
+ return child && typeof child === 'object'
+ ? leafShape(child, path)
+ : [path]
+ })
+ .sort()
+}
+
+function placeholders(value) {
+ return [...value.matchAll(/\{\{([a-zA-Z0-9_]+)\}\}/g)]
+ .map((match) => match[1])
+ .sort()
+}
+
+const [en, zh] = await Promise.all([catalog('en'), catalog('zh')])
+
+assert.deepEqual(leafShape(zh), leafShape(en), 'desktop locale keys must match')
+assert.deepEqual(
+ Object.keys(en.notices).sort(),
+ expectedNoticeCodes,
+ 'notice catalog must exactly match the frozen Rust contract',
+)
+assert.deepEqual(Object.keys(zh.notices).sort(), expectedNoticeCodes)
+
+const notificationKeys = [
+ 'approvalRequested.body',
+ 'approvalRequested.title',
+ 'runCanceled.body',
+ 'runCanceled.title',
+ 'runFailed.body',
+ 'runFailed.title',
+ 'runSucceeded.body',
+ 'runSucceeded.title',
+ 'toggle',
+]
+assert.deepEqual(leafShape(en.notifications), notificationKeys)
+assert.deepEqual(leafShape(zh.notifications), notificationKeys)
+for (const key of notificationKeys) {
+ const english = key.split('.').reduce((value, segment) => value[segment], en.notifications)
+ const chinese = key.split('.').reduce((value, segment) => value[segment], zh.notifications)
+ assert.ok(english.length > 0 && chinese.length > 0)
+ assert.deepEqual(placeholders(chinese), placeholders(english), `placeholder mismatch for notifications.${key}`)
+}
+
+for (const code of expectedNoticeCodes) {
+ assert.deepEqual(
+ placeholders(zh.notices[code]),
+ placeholders(en.notices[code]),
+ `placeholder mismatch for ${code}`,
+ )
+}
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
new file mode 100644
index 000000000..3fbfa43e6
--- /dev/null
+++ b/desktop/src-tauri/Cargo.toml
@@ -0,0 +1,46 @@
+[package]
+name = "avibe-desktop"
+description = "Avibe desktop shell: bootstraps a local Runtime and hands its Workbench to a native window"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[lib]
+# `_lib` keeps the library name distinct from the binary on Windows, as the
+# Tauri v2 scaffold requires.
+name = "avibe_desktop_lib"
+crate-type = ["staticlib", "cdylib", "rlib"]
+
+[features]
+default = []
+bundled-runtime = []
+
+[build-dependencies]
+tauri-build = { version = "2", features = [] }
+
+[dependencies]
+avibe-runtime-host = { path = "../runtime-host" }
+serde.workspace = true
+serde_json.workspace = true
+sys-locale.workspace = true
+tauri = { version = "2", features = ["tray-icon"] }
+tauri-plugin-autostart = "2"
+tauri-plugin-deep-link = "2"
+tauri-plugin-dialog = "2"
+tauri-plugin-notification = "2"
+tauri-plugin-opener = "2"
+tauri-plugin-single-instance = "2"
+tauri-plugin-window-state = "2"
+tokio.workspace = true
+url.workspace = true
+
+[dev-dependencies]
+async-trait.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+objc2 = "0.6.4"
+objc2-foundation = { version = "0.3.2", default-features = false, features = [
+ "NSAppleEventDescriptor",
+ "NSAppleEventManager",
+] }
diff --git a/desktop/src-tauri/Entitlements.plist b/desktop/src-tauri/Entitlements.plist
new file mode 100644
index 000000000..9aaca5486
--- /dev/null
+++ b/desktop/src-tauri/Entitlements.plist
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- Deliberately empty. WKWebView's JavaScript engine JITs in
+ WebKit-owned helper processes, so the embedding Tauri process needs
+ no executable-memory exception, and the notary does not require one.
+ Granting com.apple.security.cs.allow-unsigned-executable-memory here
+ would weaken the hardened runtime for the whole process. Re-adding
+ any entitlement must carry evidence that the app process itself
+ needs it. -->
+</dict>
+</plist>
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
new file mode 100644
index 000000000..0e30259f1
--- /dev/null
+++ b/desktop/src-tauri/build.rs
@@ -0,0 +1,10 @@
+fn main() {
+ // Application commands are ungated by default in Tauri v2: any page loaded in
+ // any window could invoke them. Declaring them here makes `tauri-build`
+ // generate per-command permissions, so `capabilities/bootstrap.json`
+ // becomes the only thing that can hand them out — and it hands them only to
+ // the shell's own local page.
+ let manifest =
+ tauri_build::AppManifest::new().commands(&["bootstrap_status", "bootstrap_retry", "open_install_docs"]);
+ tauri_build::try_build(tauri_build::Attributes::new().app_manifest(manifest)).expect("failed to run tauri-build");
+}
diff --git a/desktop/src-tauri/capabilities/bootstrap.json b/desktop/src-tauri/capabilities/bootstrap.json
new file mode 100644
index 000000000..f98e649cd
--- /dev/null
+++ b/desktop/src-tauri/capabilities/bootstrap.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "bootstrap",
+ "description": "Lets the shell's own bootstrap page read bootstrap status, ask for a retry, and open the fixed Avibe installation guide. This capability has no `remote` field, so it applies only while the window shows the bundled bootstrap page: once the window navigates to the Workbench origin, these commands are no longer reachable. Show Pages, which load inside the Workbench, never receive them either.",
+ "local": true,
+ "windows": ["main"],
+ "permissions": [
+ "core:event:default",
+ "allow-bootstrap-status",
+ "allow-bootstrap-retry",
+ "allow-open-install-docs"
+ ]
+}
diff --git a/desktop/src-tauri/icons/128x128.png b/desktop/src-tauri/icons/128x128.png
new file mode 100644
index 000000000..a4d2b2d31
Binary files /dev/null and b/desktop/src-tauri/icons/128x128.png differ
diff --git a/desktop/src-tauri/icons/[email protected] b/desktop/src-tauri/icons/[email protected]
new file mode 100644
index 000000000..35c0266eb
Binary files /dev/null and b/desktop/src-tauri/icons/[email protected] differ
diff --git a/desktop/src-tauri/icons/32x32.png b/desktop/src-tauri/icons/32x32.png
new file mode 100644
index 000000000..0d4a3dad1
Binary files /dev/null and b/desktop/src-tauri/icons/32x32.png differ
diff --git a/desktop/src-tauri/icons/icon.icns b/desktop/src-tauri/icons/icon.icns
new file mode 100644
index 000000000..e648ccb5c
Binary files /dev/null and b/desktop/src-tauri/icons/icon.icns differ
diff --git a/desktop/src-tauri/icons/icon.ico b/desktop/src-tauri/icons/icon.ico
new file mode 100644
index 000000000..783d6eec4
Binary files /dev/null and b/desktop/src-tauri/icons/icon.ico differ
diff --git a/desktop/src-tauri/permissions/autogenerated/bootstrap_retry.toml b/desktop/src-tauri/permissions/autogenerated/bootstrap_retry.toml
new file mode 100644
index 000000000..82f9eeff2
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/bootstrap_retry.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-bootstrap-retry"
+description = "Enables the bootstrap_retry command without any pre-configured scope."
+commands.allow = ["bootstrap_retry"]
+
+[[permission]]
+identifier = "deny-bootstrap-retry"
+description = "Denies the bootstrap_retry command without any pre-configured scope."
+commands.deny = ["bootstrap_retry"]
diff --git a/desktop/src-tauri/permissions/autogenerated/bootstrap_status.toml b/desktop/src-tauri/permissions/autogenerated/bootstrap_status.toml
new file mode 100644
index 000000000..5cfc08f6e
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/bootstrap_status.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-bootstrap-status"
+description = "Enables the bootstrap_status command without any pre-configured scope."
+commands.allow = ["bootstrap_status"]
+
+[[permission]]
+identifier = "deny-bootstrap-status"
+description = "Denies the bootstrap_status command without any pre-configured scope."
+commands.deny = ["bootstrap_status"]
diff --git a/desktop/src-tauri/permissions/autogenerated/open_install_docs.toml b/desktop/src-tauri/permissions/autogenerated/open_install_docs.toml
new file mode 100644
index 000000000..60238755c
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/open_install_docs.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-open-install-docs"
+description = "Enables the open_install_docs command without any pre-configured scope."
+commands.allow = ["open_install_docs"]
+
+[[permission]]
+identifier = "deny-open-install-docs"
+description = "Denies the open_install_docs command without any pre-configured scope."
+commands.deny = ["open_install_docs"]
diff --git a/desktop/src-tauri/resources/runtime/.keep b/desktop/src-tauri/resources/runtime/.keep
new file mode 100644
index 000000000..9a90ea5f4
--- /dev/null
+++ b/desktop/src-tauri/resources/runtime/.keep
@@ -0,0 +1 @@
+Release builds stage runtime-manifest.json and runtime.zip here.
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
new file mode 100644
index 000000000..da64299fd
--- /dev/null
+++ b/desktop/src-tauri/src/lib.rs
@@ -0,0 +1,2457 @@
+//! The Avibe desktop shell.
+//!
+//! The shell is deliberately thin. It owns one window, runs the bootstrap state
+//! machine from [`avibe_runtime_host`], and navigates that window to the
+//! Workbench once the Runtime answers the combined readiness endpoint.
+//!
+//! Two boundaries are load-bearing:
+//!
+//! * **Normal lifecycle does not stop the Runtime.** Closing or recreating a
+//! window leaves it running. Only confirmed lifecycle actions invoke
+//! the Runtime's own graceful stop command.
+//! * **The Workbench is not privileged.** `capabilities/bootstrap.json` grants
+//! the two bootstrap commands to the shell's own local page only. Once the
+//! window navigates to the Workbench origin the capability no longer matches,
+//! and [`ensure_shell_ui`] rejects the call a second time regardless.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+mod native_frame;
+mod notifications;
+
+#[cfg(target_os = "macos")]
+mod macos_deep_link;
+
+use avibe_runtime_host::deep_link::{DeepLinkNavigation, DeepLinks};
+#[cfg(not(feature = "bundled-runtime"))]
+use avibe_runtime_host::default_runtime_host;
+#[cfg(feature = "bundled-runtime")]
+use avibe_runtime_host::{bundled_runtime_host, BootstrapLog, BOOTSTRAP_LOG_NAME};
+use avibe_runtime_host::{
+ is_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, LaunchError,
+ LoopbackOrigin, RuntimeHost, StatusSink,
+};
+use serde::Deserialize;
+use tauri::menu::{CheckMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
+use tauri::plugin::Builder as PluginBuilder;
+use tauri::tray::TrayIconBuilder;
+use tauri::{AppHandle, Emitter, Manager, WebviewWindow, WebviewWindowBuilder};
+use tauri::{RunEvent, WindowEvent};
+use tauri_plugin_autostart::ManagerExt;
+use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};
+use url::Url;
+
+/// The shell's only window. Matches `app.windows[0].label` in `tauri.conf.json`
+/// and the `windows` list in `capabilities/bootstrap.json`.
+const MAIN_WINDOW: &str = "main";
+
+/// Event carrying a [`BootstrapStatus`] to the bootstrap page.
+const STATUS_EVENT: &str = "bootstrap-status";
+
+/// Fixed destination for the bootstrap's missing-Runtime help action.
+const INSTALL_DOCS_URL: &str = "https://docs.avibe.bot/get-started/install";
+
+/// How often the shell checks a Runtime after handing the window to it.
+const MONITOR_INTERVAL: Duration = Duration::from_secs(2);
+
+/// A single missed probe may be a reload or a short scheduler pause. Requiring
+/// three misses avoids replacing a healthy Workbench on transient failure.
+const READINESS_FAILURE_THRESHOLD: u8 = 3;
+
+const ACTIVITY_IDLE: u8 = 0;
+const ACTIVITY_BOOTSTRAP: u8 = 1;
+const ACTIVITY_MONITOR: u8 = 2;
+const ACTIVITY_STOP: u8 = 4;
+
+const TRAY_ID: &str = "avibe-runtime";
+const OPEN_MENU_ID: &str = "open-avibe";
+const STOP_MENU_ID: &str = "stop-runtime";
+const QUIT_MENU_ID: &str = "quit-avibe";
+const LOGIN_MENU_ID: &str = "start-at-login";
+const SETTINGS_MENU_ID: &str = "open-settings";
+/// What Settings opens: the Workbench deep link, whose destination
+/// `parse_deep_link` owns, delivered the way an external link is.
+const SETTINGS_DEEP_LINK: &str = "avibe://settings";
+#[cfg(feature = "bundled-runtime")]
+const ACTIVITY_UNINSTALL: u8 = 3;
+
+#[cfg(feature = "bundled-runtime")]
+const UNINSTALL_MENU_ID: &str = "uninstall-private-runtime";
+
+const EN_PRODUCT_CATALOG: &str = include_str!("../../../ui/src/i18n/en.json");
+const ZH_PRODUCT_CATALOG: &str = include_str!("../../../ui/src/i18n/zh.json");
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ProductCatalog {
+ desktop_bootstrap: DesktopBootstrapCatalog,
+}
+
+#[derive(Deserialize)]
+struct DesktopBootstrapCatalog {
+ tray: NativeTrayCatalog,
+ notifications: notifications::NativeNotificationCatalog,
+ #[cfg(feature = "bundled-runtime")]
+ uninstall: NativeUninstallCatalog,
+}
+
+#[derive(Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct NativeTrayCatalog {
+ open: String,
+ starting: String,
+ serving: String,
+ unreachable: String,
+ stopped: String,
+ stopping: String,
+ stop: String,
+ quit: String,
+ login: String,
+ settings: String,
+ stop_title: String,
+ stop_message: String,
+ stop_action: String,
+ quit_title: String,
+ quit_message: String,
+ quit_stop: String,
+ quit_keep: String,
+ cancel: String,
+ busy_title: String,
+ busy_message: String,
+ failure_title: String,
+ stop_failure: String,
+ login_failure: String,
+}
+
+#[cfg(feature = "bundled-runtime")]
+#[derive(Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct NativeUninstallCatalog {
+ menu_label: String,
+ confirm_title: String,
+ confirm_message: String,
+ confirm_action: String,
+ cancel_action: String,
+ busy_title: String,
+ busy_message: String,
+ success_title: String,
+ success_message: String,
+ failure_title: String,
+ failure_message: String,
+}
+
+fn native_catalog_for_locales(locales: impl IntoIterator<Item = String>) -> DesktopBootstrapCatalog {
+ let use_chinese = locales
+ .into_iter()
+ .find_map(|locale| {
+ let normalized = locale.to_lowercase();
+ if normalized.starts_with("zh") {
+ Some(true)
+ } else if normalized.starts_with("en") {
+ Some(false)
+ } else {
+ None
+ }
+ })
+ .unwrap_or(false);
+ let source = if use_chinese {
+ ZH_PRODUCT_CATALOG
+ } else {
+ EN_PRODUCT_CATALOG
+ };
+ serde_json::from_str::<ProductCatalog>(source)
+ .expect("the checked product locale catalog must be valid")
+ .desktop_bootstrap
+}
+
+fn native_tray_catalog() -> NativeTrayCatalog {
+ native_catalog_for_locales(sys_locale::get_locales()).tray
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn native_uninstall_catalog_for_locales(locales: impl IntoIterator<Item = String>) -> NativeUninstallCatalog {
+ native_catalog_for_locales(locales).uninstall
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn native_uninstall_catalog() -> NativeUninstallCatalog {
+ native_uninstall_catalog_for_locales(sys_locale::get_locales())
+}
+
+/// Shared shell state. Everything is an `Arc` so a bootstrap run can hold what it
+/// needs without borrowing from the managed state across an await point.
+struct Shell {
+ host: Arc<RuntimeHost>,
+ latest: Arc<Mutex<Option<BootstrapStatus>>>,
+ activity: Arc<AtomicU8>,
+ active_origin: Arc<Mutex<Option<LoopbackOrigin>>>,
+ window_generation: Arc<AtomicU64>,
+ monitor_generation: Arc<AtomicU64>,
+ dialog_pending: AtomicBool,
+ exit_authorized: AtomicBool,
+ bootstrap_url: Url,
+}
+
+impl Shell {
+ fn new(host: RuntimeHost, bootstrap_url: Url) -> Self {
+ Self {
+ host: Arc::new(host),
+ latest: Arc::new(Mutex::new(None)),
+ activity: Arc::new(AtomicU8::new(ACTIVITY_IDLE)),
+ active_origin: Arc::new(Mutex::new(None)),
+ window_generation: Arc::new(AtomicU64::new(0)),
+ monitor_generation: Arc::new(AtomicU64::new(0)),
+ dialog_pending: AtomicBool::new(false),
+ exit_authorized: AtomicBool::new(false),
+ bootstrap_url,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum TrayRuntimeState {
+ Starting,
+ Serving(LoopbackOrigin),
+ Unreachable,
+ Stopped,
+ Stopping,
+}
+
+impl TrayRuntimeState {
+ fn from_status(status: &BootstrapStatus) -> Self {
+ match status.phase {
+ BootstrapPhase::Probing | BootstrapPhase::Starting => Self::Starting,
+ BootstrapPhase::Ready => LoopbackOrigin::parse(&status.origin)
+ .map(Self::Serving)
+ .unwrap_or(Self::Unreachable),
+ BootstrapPhase::Failed if status.notice.code == BootstrapNoticeCode::RuntimeStopped => Self::Stopped,
+ BootstrapPhase::Failed => Self::Unreachable,
+ }
+ }
+
+ fn label(&self, catalog: &NativeTrayCatalog) -> String {
+ match self {
+ Self::Starting => catalog.starting.clone(),
+ Self::Serving(origin) => catalog
+ .serving
+ .replace("{{address}}", origin.as_str().trim_start_matches("http://")),
+ Self::Unreachable => catalog.unreachable.clone(),
+ Self::Stopped => catalog.stopped.clone(),
+ Self::Stopping => catalog.stopping.clone(),
+ }
+ }
+
+ fn icon(&self) -> tauri::image::Image<'static> {
+ let color = match self {
+ Self::Starting | Self::Stopping => [210, 135, 10, 255],
+ Self::Serving(_) => [28, 160, 90, 255],
+ Self::Unreachable => [216, 64, 64, 255],
+ Self::Stopped => [125, 125, 125, 255],
+ };
+ let mut pixels = vec![0; 32 * 32 * 4];
+ for row in 0..32_i32 {
+ for column in 0..32_i32 {
+ let distance = (row - 16).pow(2) + (column - 16).pow(2);
+ let ring = (110..=210).contains(&distance);
+ let mark = match self {
+ Self::Serving(_) => distance < 38,
+ Self::Starting | Self::Stopping => (14..=17).contains(&column) && (7..=17).contains(&row),
+ Self::Unreachable => (column - row).abs() <= 2 && (9..=23).contains(&row),
+ Self::Stopped => (12..=20).contains(&row) && (12..=20).contains(&column),
+ };
+ if ring || mark {
+ let offset = ((row * 32 + column) * 4) as usize;
+ pixels[offset..offset + 4].copy_from_slice(&color);
+ }
+ }
+ }
+ tauri::image::Image::new_owned(pixels, 32, 32)
+ }
+}
+
+struct NativeMenus {
+ tray: Menu<tauri::Wry>,
+ application: Option<Submenu<tauri::Wry>>,
+ status: MenuItem<tauri::Wry>,
+ stop: MenuItem<tauri::Wry>,
+ settings: MenuItem<tauri::Wry>,
+ login: CheckMenuItem<tauri::Wry>,
+ notifications: CheckMenuItem<tauri::Wry>,
+ stop_present: AtomicBool,
+ displayed: Mutex<Option<(TrayRuntimeState, bool, bool)>>,
+}
+
+fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
+ let catalog = native_tray_catalog();
+ let open = MenuItem::with_id(app, OPEN_MENU_ID, &catalog.open, true, None::<&str>)?;
+ let status = MenuItem::with_id(app, "runtime-status", &catalog.starting, false, None::<&str>)?;
+ let stop = MenuItem::with_id(app, STOP_MENU_ID, &catalog.stop, true, None::<&str>)?;
+ // Enabled by `refresh_runtime_tray` once the window shows a Workbench.
+ let settings = MenuItem::with_id(app, SETTINGS_MENU_ID, &catalog.settings, false, Some("CmdOrCtrl+,"))?;
+ let login_state = app.autolaunch().is_enabled();
+ let login_unavailable = login_state.is_err();
+ let login = CheckMenuItem::with_id(
+ app,
+ LOGIN_MENU_ID,
+ &catalog.login,
+ true,
+ login_state.unwrap_or(false),
+ None::<&str>,
+ )?;
+ let quit = MenuItem::with_id(app, QUIT_MENU_ID, &catalog.quit, true, None::<&str>)?;
+ let notifications = CheckMenuItem::with_id(
+ app,
+ notifications::MENU_ID,
+ native_catalog_for_locales(sys_locale::get_locales())
+ .notifications
+ .toggle,
+ true,
+ app.state::<notifications::Notifications>().enabled(),
+ None::<&str>,
+ )?;
+ let tray = Menu::with_items(
+ app,
+ &[
+ &open,
+ &status,
+ &PredefinedMenuItem::separator(app)?,
+ &settings,
+ &login,
+ &notifications,
+ &PredefinedMenuItem::separator(app)?,
+ &quit,
+ ],
+ )?;
+ let application_menu = application_menu(app)?;
+ let application = application_menu.items()?.into_iter().find_map(|item| match item {
+ MenuItemKind::Submenu(submenu) => Some(submenu),
+ _ => None,
+ });
+ if let Some(submenu) = &application {
+ // `Menu::default` opens the macOS app submenu with About and a separator;
+ // Settings takes its own group right below, where the platform puts it.
+ // Elsewhere the first submenu is File, and Settings leads it.
+ let settings_position = if cfg!(target_os = "macos") { 2 } else { 0 };
+ submenu.insert_items(&[&settings, &PredefinedMenuItem::separator(app)?], settings_position)?;
+ submenu.insert_items(&[&open, &status, &login, &PredefinedMenuItem::separator(app)?], 0)?;
+ }
+ app.set_menu(application_menu)?;
+ TrayIconBuilder::with_id(TRAY_ID)
+ .icon(TrayRuntimeState::Starting.icon())
+ .tooltip(&catalog.starting)
+ .menu(&tray)
+ .build(app)?;
+ app.manage(NativeMenus {
+ tray,
+ application,
+ status,
+ stop,
+ settings,
+ login,
+ notifications,
+ stop_present: AtomicBool::new(false),
+ displayed: Mutex::new(None),
+ });
+ if login_unavailable {
+ app.dialog()
+ .message(catalog.login_failure)
+ .title(catalog.failure_title)
+ .kind(MessageDialogKind::Error)
+ .show(|_| {});
+ }
+ Ok(())
+}
+
+fn stop_is_available(owned: bool, activity: u8) -> bool {
+ owned && matches!(activity, ACTIVITY_IDLE | ACTIVITY_MONITOR)
+}
+
+/// Settings live in the Workbench, so they open only while the window shows one:
+/// the shell is monitoring the listener it navigated to. During bootstrap, stop,
+/// or removal there is nothing to open, and a queued request would land later.
+fn settings_is_available(activity: u8, workbench_origin: bool) -> bool {
+ activity == ACTIVITY_MONITOR && workbench_origin
+}
+
+fn open_workbench_settings(app: &AppHandle) {
+ let Some(shell) = app.try_state::<Shell>() else {
+ return;
+ };
+ let workbench_origin = shell.active_origin.lock().is_ok_and(|origin| origin.is_some());
+ if !settings_is_available(shell.activity.load(Ordering::SeqCst), workbench_origin) {
+ return;
+ }
+ receive_native_deep_link(app, [SETTINGS_DEEP_LINK]);
+}
+
+fn refresh_runtime_tray(app: &AppHandle, state: TrayRuntimeState) {
+ refresh_native_controls(app, Some(state));
+}
+
+/// The Runtime status the native controls show next. `None` keeps the status
+/// already shown: a page load says what the window shows, not whether the
+/// Runtime is healthy. With nothing shown yet there is nothing to keep, and the
+/// first status refresh sets every control.
+fn next_tray_state(
+ requested: Option<TrayRuntimeState>,
+ shown: Option<&TrayRuntimeState>,
+ activity: u8,
+) -> Option<TrayRuntimeState> {
+ let state = requested.or_else(|| shown.cloned())?;
+ Some(if activity == ACTIVITY_STOP {
+ TrayRuntimeState::Stopping
+ } else {
+ state
+ })
+}
+
+/// Brings every native control in line with the shell's current activity and
+/// window, so availability is decided in one place whoever asks.
+fn refresh_native_controls(app: &AppHandle, requested: Option<TrayRuntimeState>) {
+ let handle = app.clone();
+ let _ = app.run_on_main_thread(move || {
+ let Some(menus) = handle.try_state::<NativeMenus>() else {
+ return;
+ };
+ let shell = handle.state::<Shell>();
+ let activity = shell.activity.load(Ordering::SeqCst);
+ let owned = stop_is_available(shell.host.has_owned_runtime(), activity);
+ let workbench_origin = shell.active_origin.lock().is_ok_and(|origin| origin.is_some());
+ let settings = settings_is_available(activity, workbench_origin);
+ let mut displayed = menus.displayed.lock().expect("native tray state lock");
+ let Some(state) = next_tray_state(requested, displayed.as_ref().map(|(shown, _, _)| shown), activity) else {
+ return;
+ };
+ if displayed.as_ref() == Some(&(state.clone(), owned, settings)) {
+ return;
+ }
+ let update = || -> tauri::Result<()> {
+ let label = state.label(&native_tray_catalog());
+ menus.status.set_text(&label)?;
+ menus.settings.set_enabled(settings)?;
+ if owned != menus.stop_present.load(Ordering::SeqCst) {
+ if owned {
+ menus.tray.insert(&menus.stop, 2)?;
+ if let Some(submenu) = &menus.application {
+ submenu.insert(&menus.stop, 2)?;
+ }
+ } else {
+ menus.tray.remove(&menus.stop)?;
+ if let Some(submenu) = &menus.application {
+ submenu.remove(&menus.stop)?;
+ }
+ }
+ menus.stop_present.store(owned, Ordering::SeqCst);
+ }
+ if let Some(tray) = handle.tray_by_id(TRAY_ID) {
+ tray.set_tooltip(Some(&label))?;
+ tray.set_icon(Some(state.icon()))?;
+ }
+ Ok(())
+ };
+ if update().is_ok() {
+ *displayed = Some((state, owned, settings));
+ } else {
+ eprintln!("failed to refresh native Runtime controls");
+ }
+ });
+}
+
+fn refresh_latest_tray(app: &AppHandle) {
+ let state = app
+ .state::<Shell>()
+ .latest
+ .lock()
+ .ok()
+ .and_then(|latest| latest.as_ref().map(TrayRuntimeState::from_status))
+ .unwrap_or(TrayRuntimeState::Starting);
+ refresh_runtime_tray(app, state);
+}
+
+fn show_lifecycle_busy(app: &AppHandle) {
+ let catalog = native_tray_catalog();
+ app.dialog()
+ .message(catalog.busy_message)
+ .title(catalog.busy_title)
+ .show(|_| {});
+}
+
+fn claim_runtime_stop(activity: &AtomicU8) -> bool {
+ loop {
+ let current = activity.load(Ordering::SeqCst);
+ if !matches!(current, ACTIVITY_IDLE | ACTIVITY_MONITOR) {
+ return false;
+ }
+ if activity
+ .compare_exchange(current, ACTIVITY_STOP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ return true;
+ }
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum QuitChoice {
+ Stop,
+ Keep,
+ Cancel,
+}
+
+fn quit_choice(result: MessageDialogResult, catalog: &NativeTrayCatalog) -> QuitChoice {
+ match result {
+ MessageDialogResult::Yes => QuitChoice::Stop,
+ MessageDialogResult::No => QuitChoice::Keep,
+ MessageDialogResult::Custom(label) if label == catalog.quit_stop => QuitChoice::Stop,
+ MessageDialogResult::Custom(label) if label == catalog.quit_keep => QuitChoice::Keep,
+ _ => QuitChoice::Cancel,
+ }
+}
+
+fn exit_shell(app: &AppHandle) {
+ notifications::stop(app);
+ app.state::<Shell>().exit_authorized.store(true, Ordering::SeqCst);
+ app.exit(0);
+}
+
+fn request_runtime_lifecycle(app: AppHandle, quit: bool) {
+ let shell = app.state::<Shell>();
+ if !matches!(shell.activity.load(Ordering::SeqCst), ACTIVITY_IDLE | ACTIVITY_MONITOR) {
+ show_lifecycle_busy(&app);
+ return;
+ }
+ if shell.dialog_pending.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ if quit && !shell.host.has_owned_runtime() {
+ if claim_runtime_stop(&shell.activity) {
+ exit_shell(&app);
+ } else {
+ shell.dialog_pending.store(false, Ordering::SeqCst);
+ show_lifecycle_busy(&app);
+ }
+ return;
+ }
+ if !shell.host.has_owned_runtime() {
+ shell.dialog_pending.store(false, Ordering::SeqCst);
+ return;
+ }
+ let catalog = native_tray_catalog();
+ if quit {
+ let callback_app = app.clone();
+ app.dialog()
+ .message(catalog.quit_message.clone())
+ .title(catalog.quit_title.clone())
+ .buttons(MessageDialogButtons::YesNoCancelCustom(
+ catalog.quit_stop.clone(),
+ catalog.quit_keep.clone(),
+ catalog.cancel.clone(),
+ ))
+ .show_with_result(move |result| {
+ match quit_choice(result, &catalog) {
+ QuitChoice::Stop => stop_runtime(callback_app.clone(), true),
+ QuitChoice::Keep => {
+ if claim_runtime_stop(&callback_app.state::<Shell>().activity) {
+ exit_shell(&callback_app);
+ } else {
+ show_lifecycle_busy(&callback_app);
+ }
+ }
+ QuitChoice::Cancel => {}
+ }
+ callback_app
+ .state::<Shell>()
+ .dialog_pending
+ .store(false, Ordering::SeqCst);
+ });
+ } else {
+ let callback_app = app.clone();
+ app.dialog()
+ .message(catalog.stop_message)
+ .title(catalog.stop_title)
+ .kind(MessageDialogKind::Warning)
+ .buttons(MessageDialogButtons::OkCancelCustom(
+ catalog.stop_action,
+ catalog.cancel,
+ ))
+ .show(move |confirmed| {
+ if confirmed {
+ stop_runtime(callback_app.clone(), false);
+ }
+ callback_app
+ .state::<Shell>()
+ .dialog_pending
+ .store(false, Ordering::SeqCst);
+ });
+ }
+}
+
+fn stop_runtime(app: AppHandle, quit: bool) {
+ let (host, activity, origin, previous_status) = {
+ let shell = app.state::<Shell>();
+ (
+ shell.host.clone(),
+ shell.activity.clone(),
+ shell.active_origin.lock().ok().and_then(|origin| origin.clone()),
+ shell.latest.lock().ok().and_then(|latest| latest.clone()),
+ )
+ };
+ if !claim_runtime_stop(&activity) {
+ show_lifecycle_busy(&app);
+ return;
+ }
+ refresh_runtime_tray(&app, TrayRuntimeState::Stopping);
+ notifications::stop(&app);
+ tauri::async_runtime::spawn(async move {
+ match host.stop_owned_runtime().await {
+ Ok(()) if quit => exit_shell(&app),
+ Ok(()) => {
+ let _ = return_to_bootstrap(&app);
+ let mut stopped = BootstrapStatus::rejected(BootstrapNoticeCode::RuntimeStopped, true);
+ if let Some(previous) = previous_status {
+ stopped.origin = previous.origin;
+ }
+ activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
+ WindowSink {
+ app: app.clone(),
+ latest: app.state::<Shell>().latest.clone(),
+ }
+ .publish(stopped);
+ }
+ Err(LaunchError::OwnershipLost | LaunchError::NotOwned) => {
+ let _ = return_to_bootstrap(&app);
+ let mut lost = BootstrapStatus::rejected(BootstrapNoticeCode::RuntimeOwnershipLost, true);
+ if let Some(previous) = previous_status {
+ lost.origin = previous.origin;
+ }
+ activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
+ WindowSink {
+ app: app.clone(),
+ latest: app.state::<Shell>().latest.clone(),
+ }
+ .publish(lost);
+ focus_or_restore_main_window(&app);
+ }
+ Err(_) => {
+ if let Some(origin) = origin {
+ activity.store(ACTIVITY_MONITOR, Ordering::SeqCst);
+ start_runtime_monitor(app.clone(), origin, activity);
+ } else {
+ activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
+ }
+ refresh_latest_tray(&app);
+ let catalog = native_tray_catalog();
+ app.dialog()
+ .message(catalog.stop_failure)
+ .title(catalog.failure_title)
+ .kind(MessageDialogKind::Error)
+ .show(|_| {});
+ }
+ }
+ });
+}
+
+fn toggle_start_at_login(app: &AppHandle) {
+ let requested = app
+ .autolaunch()
+ .is_enabled()
+ .map(|enabled| !enabled)
+ .map_err(|error| error.to_string());
+ set_start_at_login(app, requested);
+}
+
+/// Writes Start at Login under the policy below. The menu toggle and an
+/// uninstall putting back the registration it cleared both come here; the
+/// uninstall's own disable does not, because its failure already fails that
+/// uninstall closed. Returns whether the requested state now holds.
+fn set_start_at_login(app: &AppHandle, requested: Result<bool, String>) -> bool {
+ let manager = app.autolaunch();
+ settle_start_at_login(
+ requested,
+ |enabled| {
+ let written = if enabled { manager.enable() } else { manager.disable() };
+ written.map_err(|error| error.to_string())
+ },
+ || manager.is_enabled().map_err(|error| error.to_string()),
+ |checked| {
+ if let Some(menus) = app.try_state::<NativeMenus>() {
+ let _ = menus.login.set_checked(checked);
+ }
+ },
+ || {
+ let catalog = native_tray_catalog();
+ app.dialog()
+ .message(catalog.login_failure)
+ .title(catalog.failure_title)
+ .kind(MessageDialogKind::Error)
+ .show(|_| {});
+ },
+ )
+}
+
+/// Start at Login's terminal policy. The requested state is written once and
+/// read back, and the checkbox is drawn from what was read, so the menu shows
+/// the registration the OS actually holds. A failed write, a failed read, or a
+/// read that disagrees with the request is reported with the one login failure
+/// message. Nothing is retried: the checkbox already shows what the OS holds,
+/// so the user can act on it.
+fn settle_start_at_login(
+ requested: Result<bool, String>,
+ write: impl FnOnce(bool) -> Result<(), String>,
+ observe: impl FnOnce() -> Result<bool, String>,
+ render: impl FnOnce(bool),
+ report_failure: impl FnOnce(),
+) -> bool {
+ let written = requested.and_then(|enabled| write(enabled).map(|()| enabled));
+ let observed = observe();
+ render(observed.as_ref().copied().unwrap_or(false));
+ let settled = matches!((&written, &observed), (Ok(requested), Ok(observed)) if requested == observed);
+ if !settled {
+ report_failure();
+ }
+ settled
+}
+
+#[derive(Default)]
+struct ReadinessLoss {
+ consecutive_failures: u8,
+}
+
+impl ReadinessLoss {
+ fn observe(&mut self, ready: bool) -> bool {
+ if ready {
+ self.consecutive_failures = 0;
+ return false;
+ }
+ self.consecutive_failures = self.consecutive_failures.saturating_add(1);
+ self.consecutive_failures >= READINESS_FAILURE_THRESHOLD
+ }
+
+ fn begin_recovery(
+ &mut self,
+ ready: bool,
+ host: &RuntimeHost,
+ activity: &AtomicU8,
+ generation: &AtomicU64,
+ observed_generation: u64,
+ ) -> bool {
+ if generation.load(Ordering::SeqCst) != observed_generation
+ || activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR
+ || !self.observe(ready)
+ || activity
+ .compare_exchange(ACTIVITY_MONITOR, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return false;
+ }
+ // A window recreation can advance the generation between the initial
+ // fence and the activity claim. Leave recovery ownership with the new
+ // bootstrap instead of mutating the host for the stale monitor.
+ if generation.load(Ordering::SeqCst) != observed_generation {
+ return false;
+ }
+ // Three readiness misses do not prove process exit or revoke a receipt.
+ host.release_after_readiness_loss();
+ true
+ }
+}
+
+/// Publishes bootstrap progress to the bootstrap page, and keeps the latest value
+/// so a page that loads mid-run can catch up.
+struct WindowSink {
+ app: AppHandle,
+ latest: Arc<Mutex<Option<BootstrapStatus>>>,
+}
+
+impl StatusSink for WindowSink {
+ fn publish(&self, status: BootstrapStatus) {
+ if let Ok(mut links) = self.app.state::<Mutex<DeepLinks>>().lock() {
+ links.observe_bootstrap(&status);
+ }
+ if let Ok(mut latest) = self.latest.lock() {
+ *latest = Some(status.clone());
+ }
+ refresh_runtime_tray(&self.app, TrayRuntimeState::from_status(&status));
+ // Addressed to the shell's window specifically: a broadcast would also
+ // reach the Workbench after navigation.
+ let _ = self.app.emit_to(MAIN_WINDOW, STATUS_EVENT, status);
+ }
+}
+
+/// Rejects any caller that is not the shell's own bootstrap page.
+///
+/// The capability file is the enforcing boundary. This is the second layer, so
+/// that widening a capability by mistake cannot alone expose the shell to a page
+/// served by the Runtime.
+fn ensure_shell_ui(window: &WebviewWindow) -> Result<(), String> {
+ match window.url() {
+ Ok(url) if is_shell_ui_url(&url) => Ok(()),
+ _ => Err("This command is only available to the Avibe desktop shell.".to_owned()),
+ }
+}
+
+/// The bundled bootstrap may always navigate within its own origin. Once the
+/// Runtime is ready, unprivileged pages may route only below the exact listener
+/// that proved readiness; a settings rebind or hostile link cannot move the
+/// shell onto another local or remote service.
+fn navigation_is_allowed(url: &Url, active_origin: Option<&LoopbackOrigin>) -> bool {
+ is_shell_ui_url(url) || active_origin.is_some_and(|origin| origin.matches_url_origin(url))
+}
+
+/// The Console settings page expresses a UI rebind as a navigation to a bare
+/// HTTP origin. The desktop shell must rediscover the Python-owned companion
+/// listener instead of following that configured LAN address.
+fn is_runtime_rebind_target(url: &Url) -> bool {
+ url.scheme() == "http"
+ && url.host().is_some()
+ && url.port().is_some()
+ && url.username().is_empty()
+ && url.password().is_none()
+ && matches!(url.path(), "" | "/")
+ && url.query().is_none()
+ && url.fragment().is_none()
+}
+
+fn set_active_origin(app: &AppHandle, origin: Option<LoopbackOrigin>) -> bool {
+ app.state::<Shell>()
+ .active_origin
+ .lock()
+ .map(|mut active| *active = origin)
+ .is_ok()
+}
+
+/// The current bootstrap status, or `null` before the first one is published.
+#[tauri::command]
+fn bootstrap_status(window: WebviewWindow, app: AppHandle) -> Result<Option<BootstrapStatus>, String> {
+ ensure_shell_ui(&window)?;
+ let latest = app.state::<Shell>().latest.clone();
+ let status = latest
+ .lock()
+ .map_err(|_| "Bootstrap state is unavailable.".to_owned())?;
+ Ok(status.clone())
+}
+
+/// Starts another bootstrap run after a failure. Returns as soon as the run is
+/// scheduled; progress arrives through [`STATUS_EVENT`].
+#[tauri::command]
+fn bootstrap_retry(window: WebviewWindow, app: AppHandle) -> Result<bool, String> {
+ ensure_shell_ui(&window)?;
+ Ok(spawn_bootstrap(app))
+}
+
+/// Opens installation guidance in the system browser.
+///
+/// The URL is deliberately not an argument: even the privileged bootstrap page
+/// cannot turn this into an arbitrary protocol or URL opener.
+#[tauri::command]
+fn open_install_docs(window: WebviewWindow) -> Result<(), String> {
+ ensure_shell_ui(&window)?;
+ tauri_plugin_opener::open_url(INSTALL_DOCS_URL, None::<&str>)
+ .map_err(|_| "Installation help could not be opened.".to_owned())
+}
+
+/// Runs the bootstrap state machine once, unless one is already running.
+///
+/// The return value is part of the retry contract: the bootstrap page must not
+/// hide its Retry action when another run still owns the activity.
+fn spawn_bootstrap(app: AppHandle) -> bool {
+ let activity = app.state::<Shell>().activity.clone();
+ if activity
+ .compare_exchange(ACTIVITY_IDLE, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return false;
+ }
+ spawn_owned_bootstrap(app);
+ true
+}
+
+/// Runs bootstrap after the caller has atomically acquired bootstrap activity.
+fn spawn_owned_bootstrap(app: AppHandle) {
+ let (host, latest, activity) = {
+ let shell = app.state::<Shell>();
+ (shell.host.clone(), shell.latest.clone(), shell.activity.clone())
+ };
+
+ tauri::async_runtime::spawn(async move {
+ let sink = WindowSink {
+ app: app.clone(),
+ latest,
+ };
+ let status = host.bootstrap(&sink).await;
+
+ if status.phase == BootstrapPhase::Ready {
+ open_workbench(&app, &status, activity);
+ } else {
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ }
+ refresh_latest_tray(&app);
+ });
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum WorkbenchHandoff {
+ Monitor,
+ RetryCurrentWindow,
+ LostOwnership,
+}
+
+/// Promotes a ready bootstrap to monitoring only if the window it navigated is
+/// still the current generation. A recreation that happened during the handoff
+/// returns ownership to bootstrap so the caller can navigate the replacement.
+fn complete_workbench_handoff(
+ activity: &AtomicU8,
+ window_generation: &AtomicU64,
+ observed_generation: u64,
+) -> WorkbenchHandoff {
+ if activity
+ .compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return WorkbenchHandoff::LostOwnership;
+ }
+ if window_generation.load(Ordering::SeqCst) == observed_generation {
+ return WorkbenchHandoff::Monitor;
+ }
+ if activity
+ .compare_exchange(ACTIVITY_MONITOR, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ WorkbenchHandoff::RetryCurrentWindow
+ } else {
+ WorkbenchHandoff::LostOwnership
+ }
+}
+
+/// Hands the window to the Workbench. Reached only from a `Ready` status, so the
+/// Runtime has already proved both UI and Controller readiness at this origin.
+fn open_workbench(app: &AppHandle, ready: &BootstrapStatus, activity: Arc<AtomicU8>) {
+ // Validated once more at the point of use: navigation is the one irreversible
+ // step, and it must never be reachable with an unvalidated string.
+ let Ok(origin) = LoopbackOrigin::parse(&ready.origin) else {
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ return;
+ };
+ let window_generation = app.state::<Shell>().window_generation.clone();
+ loop {
+ let observed_generation = window_generation.load(Ordering::SeqCst);
+ let Some(window) = app.get_webview_window(MAIN_WINDOW) else {
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ if app.get_webview_window(MAIN_WINDOW).is_some() {
+ let _ = spawn_bootstrap(app.clone());
+ }
+ return;
+ };
+ if window_generation.load(Ordering::SeqCst) != observed_generation {
+ continue;
+ }
+ let Some(navigation) = app
+ .state::<Mutex<DeepLinks>>()
+ .lock()
+ .ok()
+ .and_then(|mut links| links.bootstrap_navigation(ready))
+ else {
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ return;
+ };
+ // A recreated window clears the previous navigation grant. Restore the
+ // exact ready origin for each generation immediately before navigating
+ // that generation's window.
+ if !set_active_origin(app, Some(origin.clone())) {
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ return;
+ }
+ if window.navigate(navigation.url().clone()).is_err() {
+ if window_generation.load(Ordering::SeqCst) != observed_generation {
+ continue;
+ }
+ let _ = set_active_origin(app, None);
+ let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ WindowSink {
+ app: app.clone(),
+ latest: app.state::<Shell>().latest.clone(),
+ }
+ .publish(workbench_navigation_failure_status(ready, &origin));
+ return;
+ }
+ match complete_workbench_handoff(&activity, &window_generation, observed_generation) {
+ WorkbenchHandoff::Monitor => {
+ commit_deep_link_navigation(app, &navigation, true, observed_generation);
+ apply_pending_deep_link(app);
+ start_runtime_monitor(app.clone(), origin, activity);
+ return;
+ }
+ WorkbenchHandoff::RetryCurrentWindow => continue,
+ WorkbenchHandoff::LostOwnership => return,
+ }
+ }
+}
+
+fn workbench_navigation_failure_status(ready: &BootstrapStatus, origin: &LoopbackOrigin) -> BootstrapStatus {
+ BootstrapStatus::failed(
+ origin,
+ ready.attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::WorkbenchNavigationFailed),
+ true,
+ )
+}
+
+/// Watches the exact origin that bootstrap proved ready. The caller owns the
+/// shell's single monitor activity until this task exits or begins recovery.
+///
+/// This is also the notification connection's only opener, and it is the rule
+/// the whole lifetime hangs off: every caller arrives holding monitor ownership
+/// of a navigation that actually happened, and the stop sites give the
+/// connection up only where a hand-off away actually happened. Opening it
+/// anywhere earlier — before a navigation is known to have succeeded — leaves a
+/// live connection behind on every path that then fails.
+fn start_runtime_monitor(app: AppHandle, origin: LoopbackOrigin, activity: Arc<AtomicU8>) {
+ notifications::start(&app, origin.clone());
+ let host = app.state::<Shell>().host.clone();
+ let generation = app.state::<Shell>().monitor_generation.clone();
+ let observed_generation = generation.fetch_add(1, Ordering::SeqCst) + 1;
+
+ tauri::async_runtime::spawn(async move {
+ let mut readiness_loss = ReadinessLoss::default();
+
+ loop {
+ tokio::time::sleep(MONITOR_INTERVAL).await;
+ if activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR
+ || generation.load(Ordering::SeqCst) != observed_generation
+ {
+ break;
+ }
+ let ready = host.is_ready(&origin).await;
+ // Window recreation can transfer ownership while the network probe
+ // is pending. The superseded monitor must not mutate the new
+ // bootstrap run's launch ownership after the await point.
+ if activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR
+ || generation.load(Ordering::SeqCst) != observed_generation
+ {
+ break;
+ }
+ refresh_runtime_tray(
+ &app,
+ if ready {
+ TrayRuntimeState::Serving(origin.clone())
+ } else {
+ TrayRuntimeState::Unreachable
+ },
+ );
+ if readiness_loss.begin_recovery(ready, &host, &activity, &generation, observed_generation)
+ && recover_after_readiness_loss(
+ || restore_bootstrap_view(&app),
+ || notifications::stop(&app),
+ || spawn_owned_bootstrap(app.clone()),
+ || {
+ activity
+ .compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ },
+ )
+ {
+ break;
+ }
+ }
+ });
+}
+
+/// Readiness loss has one decision: the notification connection is given up
+/// only on the branch where the hand-off back to bootstrap actually happened. A
+/// native navigation failure keeps the connection, so the monitor that retains
+/// ownership still has one to recover with instead of running mute for the rest
+/// of the session. Answers whether the monitor should stop.
+fn recover_after_readiness_loss(
+ hand_off: impl FnOnce() -> bool,
+ stop_notifications: impl FnOnce(),
+ spawn_bootstrap: impl FnOnce(),
+ retain_ownership: impl FnOnce() -> bool,
+) -> bool {
+ if hand_off() {
+ stop_notifications();
+ spawn_bootstrap();
+ return true;
+ }
+ // A transient native navigation failure must not silently abandon
+ // recovery. Keep the monitor ownership and try again.
+ !retain_ownership()
+}
+
+/// Hands the shell back to bootstrap and, only once that succeeded, gives up
+/// the notification connection the abandoned origin owned.
+fn return_to_bootstrap(app: &AppHandle) -> bool {
+ if !restore_bootstrap_view(app) {
+ return false;
+ }
+ notifications::stop(app);
+ true
+}
+
+/// Restores the exact bootstrap URL captured before the first navigation. It is
+/// a bundled Tauri page in production and the fixed Vite dev URL in development.
+fn restore_bootstrap_view(app: &AppHandle) -> bool {
+ let (bootstrap_url, latest) = {
+ let shell = app.state::<Shell>();
+ (shell.bootstrap_url.clone(), shell.latest.clone())
+ };
+ if !is_shell_ui_url(&bootstrap_url) {
+ return false;
+ }
+ let Some(window) = app.get_webview_window(MAIN_WINDOW) else {
+ return false;
+ };
+ if let Ok(mut latest) = latest.lock() {
+ *latest = None;
+ }
+ if window.navigate(bootstrap_url).is_err() {
+ return false;
+ }
+ let _ = set_active_origin(app, None);
+ true
+}
+
+/// Re-enters endpoint discovery after the Workbench asks to move to a newly
+/// configured UI origin. The requested URL itself is never loaded.
+fn rediscover_after_runtime_rebind(app: AppHandle, origin: LoopbackOrigin) {
+ let activity = app.state::<Shell>().activity.clone();
+ if activity
+ .compare_exchange(ACTIVITY_MONITOR, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return;
+ }
+
+ tauri::async_runtime::spawn(async move {
+ if return_to_bootstrap(&app) {
+ spawn_owned_bootstrap(app);
+ return;
+ }
+ if activity
+ .compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ start_runtime_monitor(app, origin, activity);
+ }
+ });
+}
+
+/// Returns the shell's window, building it when there is none. This is the only
+/// place the window is built: its `tauri.conf.json` entry is `create: false`, so
+/// the window at startup and every recreated one carry the same new-window rule.
+fn ensure_main_window(app: &AppHandle) -> Option<WebviewWindow> {
+ if let Some(window) = app.get_webview_window(MAIN_WINDOW) {
+ return Some(window);
+ }
+ let config = app
+ .config()
+ .app
+ .windows
+ .iter()
+ .find(|config| config.label == MAIN_WINDOW)?
+ .clone();
+ WebviewWindowBuilder::from_config(app, &config)
+ .ok()?
+ .initialization_script(DESKTOP_SHELL_MARKER)
+ .on_new_window(|url, _features| handle_new_window_request(url))
+ .build()
+ .ok()
+}
+
+/// Tells the Workbench, before any of its scripts run, that it is rendered by
+/// this shell rather than a browser tab or a PWA: it hides what the shell cannot
+/// do (a pre-opened `about:blank` tab never exists here). Top-level document only;
+/// WebView2 runs initialization scripts in subframes too, hence the frame check.
+const DESKTOP_SHELL_MARKER: &str =
+ "if (window.self === window.top) Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true });";
+
+/// What happens to a browsing context the page asks for.
+#[derive(Debug, PartialEq, Eq)]
+enum NewWindowDecision {
+ OpenInSystemBrowser,
+ Deny,
+}
+
+/// A web destination the page wanted in a new context (a `target="_blank"` link
+/// or `window.open(url)`) is read in the user's own browser. Anything else,
+/// `about:blank` included, has no destination the shell can hand over and is
+/// dropped, which is also what the platform does when no handler is registered.
+fn new_window_decision(url: &Url) -> NewWindowDecision {
+ match url.scheme() {
+ "http" | "https" => NewWindowDecision::OpenInSystemBrowser,
+ _ => NewWindowDecision::Deny,
+ }
+}
+
+/// The page never gets a second webview. On macOS a returned webview must share
+/// the opener's `WKWebViewConfiguration`, and wry registers each webview's init
+/// scripts and IPC handler on that shared content controller: every such window
+/// would add a copy of the scripts to this one and, when dropped, remove this
+/// window's IPC handler, leaving the bootstrap page unable to reach the shell.
+fn handle_new_window_request(url: Url) -> tauri::webview::NewWindowResponse<tauri::Wry> {
+ if new_window_decision(&url) == NewWindowDecision::OpenInSystemBrowser {
+ // Off the main thread: this runs inside the webview's own delegate callback.
+ tauri::async_runtime::spawn_blocking(move || {
+ if tauri_plugin_opener::open_url(url.as_str(), None::<&str>).is_err() {
+ eprintln!("failed to open a Workbench link in the system browser");
+ }
+ });
+ }
+ tauri::webview::NewWindowResponse::Deny
+}
+
+/// Transfers a recreated window from an idle or stale monitor owner to a fresh
+/// bootstrap run. An already-running bootstrap will publish into the new page.
+fn claim_recreated_window_bootstrap(activity: &AtomicU8) -> bool {
+ loop {
+ let current = activity.load(Ordering::SeqCst);
+ match current {
+ ACTIVITY_BOOTSTRAP => return false,
+ ACTIVITY_IDLE | ACTIVITY_MONITOR => {
+ if activity
+ .compare_exchange(current, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ return true;
+ }
+ }
+ _ => return false,
+ }
+ }
+}
+
+/// Brings the existing window forward, or recreates it and re-enters bootstrap.
+fn focus_or_restore_main_window(app: &AppHandle) {
+ let created = app.get_webview_window(MAIN_WINDOW).is_none();
+ let Some(window) = ensure_main_window(app) else {
+ return;
+ };
+ let _ = window.unminimize();
+ let _ = native_frame::clamp(&window.as_ref().window());
+ let _ = window.show();
+ let _ = window.set_focus();
+ let stopped = app
+ .state::<Shell>()
+ .latest
+ .lock()
+ .ok()
+ .and_then(|latest| latest.clone())
+ .filter(|status| {
+ matches!(
+ status.notice.code,
+ BootstrapNoticeCode::RuntimeStopped | BootstrapNoticeCode::RuntimeOwnershipLost
+ )
+ });
+ if let Some(status) = stopped {
+ if window.url().is_ok_and(|url| !is_shell_ui_url(&url)) {
+ let _ = return_to_bootstrap(app);
+ }
+ WindowSink {
+ app: app.clone(),
+ latest: app.state::<Shell>().latest.clone(),
+ }
+ .publish(status);
+ return;
+ }
+ if created {
+ let (activity, latest, window_generation) = {
+ let shell = app.state::<Shell>();
+ (
+ shell.activity.clone(),
+ shell.latest.clone(),
+ shell.window_generation.clone(),
+ )
+ };
+ // Increment before inspecting activity. A bootstrap-to-monitor handoff
+ // that races this recreation will observe the generation change and
+ // navigate this replacement window before it starts monitoring.
+ window_generation.fetch_add(1, Ordering::SeqCst);
+ let _ = set_active_origin(app, None);
+ if claim_recreated_window_bootstrap(&activity) {
+ if let Ok(mut latest) = latest.lock() {
+ *latest = None;
+ }
+ spawn_owned_bootstrap(app.clone());
+ }
+ }
+}
+
+fn receive_native_deep_link(app: &AppHandle, arguments: impl IntoIterator<Item = impl AsRef<str>>) {
+ if let Ok(mut links) = app.state::<Mutex<DeepLinks>>().lock() {
+ links.receive(arguments);
+ }
+ if app.try_state::<Shell>().is_none() {
+ return;
+ }
+ focus_or_restore_main_window(app);
+ apply_pending_deep_link(app);
+}
+
+fn apply_pending_deep_link(app: &AppHandle) {
+ let Some(shell) = app.try_state::<Shell>() else {
+ return;
+ };
+ if shell.activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR {
+ return;
+ }
+ let observed_generation = shell.window_generation.load(Ordering::SeqCst);
+ let Some(window) = app.get_webview_window(MAIN_WINDOW) else {
+ return;
+ };
+ let Some(origin) = shell.active_origin.lock().ok().and_then(|origin| origin.clone()) else {
+ return;
+ };
+ let Ok(current_url) = window.url() else {
+ return;
+ };
+ let navigation = app
+ .state::<Mutex<DeepLinks>>()
+ .lock()
+ .ok()
+ .and_then(|links| links.workbench_navigation(&origin, &current_url));
+ if let Some(navigation) = navigation {
+ if shell.window_generation.load(Ordering::SeqCst) != observed_generation {
+ return;
+ }
+ let succeeded = window.navigate(navigation.url().clone()).is_ok();
+ commit_deep_link_navigation(app, &navigation, succeeded, observed_generation);
+ }
+}
+
+fn commit_deep_link_navigation(
+ app: &AppHandle,
+ navigation: &DeepLinkNavigation,
+ navigation_succeeded: bool,
+ issuing_generation: u64,
+) {
+ let shell = app.state::<Shell>();
+ if let Ok(mut links) = app.state::<Mutex<DeepLinks>>().lock() {
+ links.commit_navigation(
+ navigation,
+ navigation_succeeded,
+ issuing_generation,
+ shell.window_generation.load(Ordering::SeqCst),
+ );
+ }
+}
+
+fn application_menu(app: &AppHandle) -> tauri::Result<Menu<tauri::Wry>> {
+ let menu = Menu::default(app)?;
+ #[cfg(feature = "bundled-runtime")]
+ {
+ use tauri::menu::{MenuItem, PredefinedMenuItem};
+
+ let first_submenu = menu.items()?.into_iter().find_map(|item| match item {
+ MenuItemKind::Submenu(submenu) => Some(submenu),
+ _ => None,
+ });
+ if let Some(submenu) = first_submenu {
+ let catalog = native_uninstall_catalog();
+ let separator = PredefinedMenuItem::separator(app)?;
+ let uninstall = MenuItem::with_id(app, UNINSTALL_MENU_ID, catalog.menu_label, true, None::<&str>)?;
+ let position = submenu.items()?.len().saturating_sub(1);
+ submenu.insert_items(&[&separator, &uninstall], position)?;
+ }
+ }
+ Ok(menu)
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn claim_runtime_removal(activity: &AtomicU8) -> bool {
+ loop {
+ let current = activity.load(Ordering::SeqCst);
+ match current {
+ ACTIVITY_IDLE | ACTIVITY_MONITOR => {
+ if activity
+ .compare_exchange(current, ACTIVITY_UNINSTALL, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ return true;
+ }
+ }
+ ACTIVITY_BOOTSTRAP | ACTIVITY_UNINSTALL => return false,
+ _ => return false,
+ }
+ }
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn recover_after_runtime_removal_failure(app: &AppHandle, activity: Arc<AtomicU8>) {
+ let _ = activity.compare_exchange(ACTIVITY_UNINSTALL, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
+ if return_to_bootstrap(app) {
+ let _ = spawn_bootstrap(app.clone());
+ }
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn report_runtime_removal_failure(app: &AppHandle, activity: Arc<AtomicU8>, catalog: &NativeUninstallCatalog) {
+ recover_after_runtime_removal_failure(app, activity);
+ app.dialog()
+ .message(catalog.failure_message.clone())
+ .title(catalog.failure_title.clone())
+ .kind(MessageDialogKind::Error)
+ .show(|_| {});
+}
+
+/// The confirmed uninstall's one decision: an opt-in login registration is
+/// cleared before the private Runtime is deleted, so the OS never keeps
+/// launching an application the user just removed. Failing to inspect or to
+/// clear that registration is an uninstall failure — the Runtime stays and the
+/// caller reports it — rather than a silently stale entry. Clearing it is also
+/// undone when the removal it authorized does not happen: the application is
+/// still installed, so it must keep launching the way the user configured it.
+/// That restore goes through Start at Login's one write policy; when it fails,
+/// the outcome says so and both failures are reported, never an uninstall that
+/// quietly finished with the registration gone.
+#[cfg(feature = "bundled-runtime")]
+async fn remove_runtime_after_login_cleanup<Removal>(
+ login_enabled: Result<bool, String>,
+ disable_login: impl FnOnce() -> Result<(), String>,
+ remove_runtime: impl FnOnce() -> Removal,
+ restore_login: impl FnOnce() -> bool,
+ report_failure: impl FnOnce(),
+) -> UninstallOutcome
+where
+ Removal: std::future::Future<Output = bool>,
+{
+ let cleared = match login_enabled {
+ Ok(true) => disable_login().map(|()| true),
+ Ok(false) => Ok(false),
+ Err(error) => Err(error),
+ };
+ let Ok(cleared) = cleared else {
+ report_failure();
+ return UninstallOutcome::Kept;
+ };
+ if remove_runtime().await {
+ return UninstallOutcome::Removed;
+ }
+ let outcome = if cleared && !restore_login() {
+ UninstallOutcome::KeptWithoutLogin
+ } else {
+ UninstallOutcome::Kept
+ };
+ report_failure();
+ outcome
+}
+
+/// How a confirmed uninstall ended. Only `Removed` reached the success dialog
+/// and the shell exit; the other two left the installation in place and
+/// reported the failure.
+#[cfg(feature = "bundled-runtime")]
+#[derive(Debug, PartialEq, Eq)]
+enum UninstallOutcome {
+ Removed,
+ Kept,
+ /// The login registration this uninstall cleared could not be put back.
+ KeptWithoutLogin,
+}
+
+#[cfg(feature = "bundled-runtime")]
+fn request_private_runtime_removal(app: AppHandle) {
+ if app.state::<Shell>().dialog_pending.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ let catalog = native_uninstall_catalog();
+ let confirmation_app = app.clone();
+ app.dialog()
+ .message(catalog.confirm_message.clone())
+ .title(catalog.confirm_title.clone())
+ .kind(MessageDialogKind::Warning)
+ .buttons(MessageDialogButtons::OkCancelCustom(
+ catalog.confirm_action.clone(),
+ catalog.cancel_action.clone(),
+ ))
+ .show(move |confirmed| {
+ confirmation_app
+ .state::<Shell>()
+ .dialog_pending
+ .store(false, Ordering::SeqCst);
+ if !confirmed {
+ return;
+ }
+ let (host, activity, active_origin) = {
+ let shell = confirmation_app.state::<Shell>();
+ (
+ shell.host.clone(),
+ shell.activity.clone(),
+ shell.active_origin.lock().ok().and_then(|origin| origin.clone()),
+ )
+ };
+ if !claim_runtime_removal(&activity) {
+ confirmation_app
+ .dialog()
+ .message(catalog.busy_message.clone())
+ .title(catalog.busy_title.clone())
+ .kind(MessageDialogKind::Info)
+ .show(|_| {});
+ return;
+ }
+
+ let removal_catalog = catalog.clone();
+ let login_app = confirmation_app.clone();
+ let restore_app = confirmation_app.clone();
+ let failure_app = confirmation_app.clone();
+ tauri::async_runtime::spawn(async move {
+ remove_runtime_after_login_cleanup(
+ login_app.autolaunch().is_enabled().map_err(|error| error.to_string()),
+ || login_app.autolaunch().disable().map_err(|error| error.to_string()),
+ || async move {
+ notifications::stop(&confirmation_app);
+ match host.remove_private_runtime(active_origin.as_ref()).await {
+ Ok(true) => {
+ let exit_app = confirmation_app.clone();
+ confirmation_app
+ .dialog()
+ .message(removal_catalog.success_message.clone())
+ .title(removal_catalog.success_title.clone())
+ .kind(MessageDialogKind::Info)
+ .show(move |_| exit_shell(&exit_app));
+ true
+ }
+ Ok(false) | Err(_) => false,
+ }
+ },
+ || set_start_at_login(&restore_app, Ok(true)),
+ || report_runtime_removal_failure(&failure_app, activity, &catalog),
+ )
+ .await;
+ });
+ });
+}
+
+pub fn run() {
+ let builder = tauri::Builder::default()
+ .manage(Mutex::new(DeepLinks::default()))
+ // Registered first, as the plugin documents: a second launch is handed to
+ // the running shell instead of starting a competing Runtime.
+ .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
+ receive_native_deep_link(app, argv.iter().skip(1));
+ }))
+ .plugin(tauri_plugin_deep_link::init());
+ #[cfg(target_os = "macos")]
+ let builder = builder.plugin(macos_deep_link::init());
+ builder
+ .plugin(
+ tauri_plugin_window_state::Builder::new()
+ .with_state_flags(native_frame::state_flags())
+ .with_filter(|label| label == MAIN_WINDOW)
+ .build(),
+ )
+ .plugin(native_frame::init())
+ .plugin(tauri_plugin_dialog::init())
+ .plugin(tauri_plugin_autostart::Builder::new().build())
+ .plugin(tauri_plugin_notification::init())
+ .on_menu_event(|app, event| {
+ match event.id().as_ref() {
+ OPEN_MENU_ID => focus_or_restore_main_window(app),
+ SETTINGS_MENU_ID => open_workbench_settings(app),
+ STOP_MENU_ID => request_runtime_lifecycle(app.clone(), false),
+ QUIT_MENU_ID => request_runtime_lifecycle(app.clone(), true),
+ LOGIN_MENU_ID => toggle_start_at_login(app),
+ notifications::MENU_ID => {
+ let notifications = app.state::<notifications::Notifications>();
+ notifications.toggle();
+ if let Some(menus) = app.try_state::<NativeMenus>() {
+ let _ = menus.notifications.set_checked(notifications.enabled());
+ }
+ }
+ _ => {}
+ }
+ #[cfg(feature = "bundled-runtime")]
+ if event.id() == UNINSTALL_MENU_ID {
+ request_private_runtime_removal(app.clone());
+ }
+ })
+ .plugin(
+ PluginBuilder::<_, ()>::new("shell-run-events")
+ .on_page_load(|webview, payload| {
+ if webview.label() == MAIN_WINDOW && payload.event() == tauri::webview::PageLoadEvent::Finished {
+ apply_pending_deep_link(webview.app_handle());
+ // Settings become available the moment a Workbench is on
+ // screen, not at the monitor's first tick. The shared
+ // rule still decides, so a bootstrap page enables nothing.
+ refresh_native_controls(webview.app_handle(), None);
+ }
+ })
+ .on_navigation(|webview, url| {
+ let active_origin = webview
+ .try_state::<Shell>()
+ .and_then(|shell| shell.active_origin.lock().ok().and_then(|active| active.clone()));
+ if navigation_is_allowed(url, active_origin.as_ref()) {
+ return true;
+ }
+ if is_runtime_rebind_target(url) {
+ if let Some(origin) = active_origin {
+ rediscover_after_runtime_rebind(webview.app_handle().clone(), origin);
+ }
+ }
+ false
+ })
+ .on_event(|app, event| {
+ if let RunEvent::WindowEvent {
+ label,
+ event: WindowEvent::CloseRequested { api, .. },
+ ..
+ } = event
+ {
+ if label == MAIN_WINDOW {
+ api.prevent_close();
+ if let Some(window) = app.get_webview_window(MAIN_WINDOW) {
+ let _ = window.hide();
+ }
+ }
+ }
+ if let RunEvent::ExitRequested { api, .. } = event {
+ if let Some(shell) = app.try_state::<Shell>() {
+ if !shell.exit_authorized.load(Ordering::SeqCst) {
+ api.prevent_exit();
+ request_runtime_lifecycle(app.clone(), true);
+ }
+ }
+ }
+ #[cfg(target_os = "macos")]
+ if let RunEvent::Reopen {
+ has_visible_windows: false,
+ ..
+ } = event
+ {
+ focus_or_restore_main_window(app);
+ }
+ })
+ .build(),
+ )
+ .invoke_handler(tauri::generate_handler![
+ bootstrap_status,
+ bootstrap_retry,
+ open_install_docs
+ ])
+ .setup(|app| {
+ let window = ensure_main_window(app.handle()).ok_or_else(|| {
+ std::io::Error::new(std::io::ErrorKind::NotFound, "the Avibe desktop window is missing")
+ })?;
+ let bootstrap_url = window.url()?;
+ if !is_shell_ui_url(&bootstrap_url) {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::PermissionDenied,
+ "the Avibe desktop window did not load its bundled bootstrap page",
+ )
+ .into());
+ }
+ let host = {
+ #[cfg(feature = "bundled-runtime")]
+ {
+ bundled_runtime_host(
+ app.path().resource_dir()?.join("runtime"),
+ app.path().app_local_data_dir()?.join("runtime"),
+ app.path().app_local_data_dir()?.join("backends"),
+ // Beside the Runtime it describes, so a user asked for
+ // "the log next to your Avibe runtime folder" finds it.
+ BootstrapLog::at(app.path().app_local_data_dir()?.join(BOOTSTRAP_LOG_NAME)),
+ )?
+ }
+ #[cfg(not(feature = "bundled-runtime"))]
+ {
+ default_runtime_host()?
+ }
+ };
+ app.manage(Shell::new(host, bootstrap_url));
+ app.manage(notifications::Notifications::new(
+ app.path().app_local_data_dir()?.join("notifications.json"),
+ ));
+ if let Ok(mut links) = app.state::<Mutex<DeepLinks>>().lock() {
+ links.receive(
+ std::env::args_os()
+ .skip(1)
+ .filter_map(|argument| argument.into_string().ok()),
+ );
+ }
+ install_native_tray(app.handle())?;
+ let _ = spawn_bootstrap(app.handle().clone());
+ Ok(())
+ })
+ .run(tauri::generate_context!())
+ .expect("failed to start the Avibe desktop shell");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use async_trait::async_trait;
+ use avibe_runtime_host::{HealthProbe, LaunchWatch, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher};
+ use std::sync::atomic::AtomicUsize;
+
+ #[test]
+ fn settings_open_only_while_the_window_shows_a_workbench() {
+ for activity in 0..=u8::MAX {
+ assert!(!settings_is_available(activity, false));
+ assert_eq!(settings_is_available(activity, true), activity == ACTIVITY_MONITOR);
+ }
+ assert!(avibe_runtime_host::deep_link::parse_deep_link(SETTINGS_DEEP_LINK).is_some());
+ }
+
+ #[test]
+ fn a_control_refresh_without_a_status_keeps_the_status_already_shown() {
+ let unreachable = TrayRuntimeState::Unreachable;
+ // A page load must not turn an unreachable Runtime back into a serving one.
+ assert_eq!(
+ next_tray_state(None, Some(&unreachable), ACTIVITY_MONITOR),
+ Some(TrayRuntimeState::Unreachable)
+ );
+ assert_eq!(next_tray_state(None, None, ACTIVITY_MONITOR), None);
+ assert_eq!(
+ next_tray_state(Some(TrayRuntimeState::Starting), Some(&unreachable), ACTIVITY_BOOTSTRAP),
+ Some(TrayRuntimeState::Starting)
+ );
+ for requested in [None, Some(TrayRuntimeState::Starting)] {
+ assert_eq!(
+ next_tray_state(requested, Some(&unreachable), ACTIVITY_STOP),
+ Some(TrayRuntimeState::Stopping)
+ );
+ }
+ }
+
+ #[test]
+ fn stop_authority_requires_ownership_and_exclusive_idle_or_monitor_activity() {
+ for activity in 0..=u8::MAX {
+ assert!(!stop_is_available(false, activity));
+ let expected = matches!(activity, ACTIVITY_IDLE | ACTIVITY_MONITOR);
+ assert_eq!(stop_is_available(true, activity), expected);
+ let state = AtomicU8::new(activity);
+ assert_eq!(claim_runtime_stop(&state), expected);
+ assert_eq!(
+ state.load(Ordering::SeqCst),
+ if expected { ACTIVITY_STOP } else { activity }
+ );
+ assert!(!claim_runtime_stop(&state));
+ assert!(!claim_recreated_window_bootstrap(&AtomicU8::new(ACTIVITY_STOP)));
+ }
+ }
+
+ #[test]
+ fn quit_results_require_an_explicit_stop_or_keep_choice_in_each_locale() {
+ for locale in ["en-US", "zh-CN"] {
+ let catalog = native_catalog_for_locales([locale.to_owned()]).tray;
+ assert_eq!(
+ quit_choice(MessageDialogResult::Custom(catalog.quit_stop.clone()), &catalog),
+ QuitChoice::Stop
+ );
+ assert_eq!(
+ quit_choice(MessageDialogResult::Custom(catalog.quit_keep.clone()), &catalog),
+ QuitChoice::Keep
+ );
+ for result in [
+ MessageDialogResult::Cancel,
+ MessageDialogResult::Ok,
+ MessageDialogResult::Custom(catalog.cancel.clone()),
+ MessageDialogResult::Custom("unknown".to_owned()),
+ ] {
+ assert_eq!(quit_choice(result, &catalog), QuitChoice::Cancel);
+ }
+ }
+ }
+
+ #[test]
+ fn tray_status_is_a_projection_of_bootstrap_and_the_proved_listener() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:6123").expect("test listener");
+ let catalog = native_catalog_for_locales(["en".to_owned()]).tray;
+ for code in [BootstrapNoticeCode::Ready, BootstrapNoticeCode::Adopted] {
+ let status = BootstrapStatus::ready(&origin, 1, code);
+ let state = TrayRuntimeState::from_status(&status);
+ assert_eq!(state, TrayRuntimeState::Serving(origin.clone()));
+ assert_eq!(state.label(&catalog), "Runtime: serving on 127.0.0.1:6123");
+ }
+ assert_eq!(
+ TrayRuntimeState::from_status(&BootstrapStatus::probing(&origin, 1)),
+ TrayRuntimeState::Starting
+ );
+ assert_eq!(
+ TrayRuntimeState::from_status(&BootstrapStatus::rejected(BootstrapNoticeCode::RuntimeStopped, true)),
+ TrayRuntimeState::Stopped
+ );
+ assert_eq!(
+ TrayRuntimeState::from_status(&BootstrapStatus::rejected(BootstrapNoticeCode::ReadyTimeout, true)),
+ TrayRuntimeState::Unreachable
+ );
+ assert_ne!(
+ TrayRuntimeState::Unreachable.icon().rgba(),
+ TrayRuntimeState::Stopped.icon().rgba()
+ );
+ }
+
+ #[test]
+ fn readiness_recovers_only_after_consecutive_failures() {
+ let mut loss = ReadinessLoss::default();
+ assert!(!loss.observe(false));
+ assert!(!loss.observe(false));
+ assert!(loss.observe(false));
+ }
+
+ struct RecoveryProbe(Mutex<std::collections::VecDeque<bool>>);
+
+ #[async_trait]
+ impl HealthProbe for RecoveryProbe {
+ async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<avibe_runtime_host::RuntimeReadiness> {
+ self.0
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or(false)
+ .then_some(avibe_runtime_host::RuntimeReadiness {
+ desktop_runtime_id: None,
+ desktop_ui_runtime_id: None,
+ })
+ }
+ }
+
+ struct RecoveryLauncher {
+ watches: Mutex<std::collections::VecDeque<LaunchWatch>>,
+ launches: Arc<AtomicUsize>,
+ stops: Arc<Mutex<Vec<avibe_runtime_host::launcher::StartupReceipt>>>,
+ }
+
+ struct RecoveryExecutable {
+ watch: LaunchWatch,
+ launches: Arc<AtomicUsize>,
+ stops: Arc<Mutex<Vec<avibe_runtime_host::launcher::StartupReceipt>>>,
+ }
+
+ impl RuntimeLauncher for RecoveryLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(RecoveryExecutable {
+ watch: self.watches.lock().unwrap().pop_front().expect("expected resolution"),
+ launches: self.launches.clone(),
+ stops: self.stops.clone(),
+ }))
+ }
+ }
+
+ impl ResolvedRuntimeLauncher for RecoveryExecutable {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap())
+ }
+
+ fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ self.launches.fetch_add(1, Ordering::SeqCst);
+ Ok(LaunchedRuntime {
+ pid: 1,
+ watch: self.watch.clone(),
+ })
+ }
+
+ fn stop(&self, receipt: &avibe_runtime_host::launcher::StartupReceipt) -> Result<(), LaunchError> {
+ self.stops.lock().unwrap().push(receipt.clone());
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn monitor_recovery_preserves_started_authority_and_pending_helper_exclusion() {
+ use avibe_runtime_host::launcher::StartupReceipt;
+ use avibe_runtime_host::{DiscardStatus, RuntimeHostSettings};
+
+ let receipt: StartupReceipt = serde_json::from_value(serde_json::json!({
+ "schema_version": 1, "outcome": "started", "service_pid": 1234, "ui_pid": 5678,
+ "service_create_unix_ms": 1789010100123.5, "ui_create_unix_ms": 1789010100456.5,
+ }))
+ .unwrap();
+ let mut reused_json = serde_json::to_value(&receipt).unwrap();
+ reused_json["outcome"] = serde_json::json!("reused");
+ let reused: StartupReceipt = serde_json::from_value(reused_json).unwrap();
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_time()
+ .build()
+ .unwrap();
+
+ for pending in [false, true] {
+ // Start -> ready -> three monitor misses -> recovery helper -> ready.
+ let probe = Arc::new(RecoveryProbe(Mutex::new(
+ [false, true, false, false, false, false, true].into(),
+ )));
+ let launcher = Arc::new(RecoveryLauncher {
+ watches: Mutex::new(
+ [
+ if pending {
+ LaunchWatch::default()
+ } else {
+ LaunchWatch::exited_with_receipt(true, receipt.clone())
+ },
+ LaunchWatch::exited_with_receipt(true, reused.clone()),
+ ]
+ .into(),
+ ),
+ launches: Arc::default(),
+ stops: Arc::default(),
+ });
+ let host = RuntimeHost::new(
+ probe,
+ launcher.clone(),
+ RuntimeHostSettings {
+ poll_interval: Duration::from_millis(1),
+ ready_timeout: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+ runtime.block_on(async {
+ let ready = host.bootstrap(&DiscardStatus).await;
+ assert_eq!(ready.phase, BootstrapPhase::Ready);
+ let origin = LoopbackOrigin::parse(&ready.origin).unwrap();
+ let activity = AtomicU8::new(ACTIVITY_MONITOR);
+ let generation = AtomicU64::new(7);
+ let mut loss = ReadinessLoss::default();
+ // A stale monitor or a stop activity cannot release this helper.
+ for current in [ACTIVITY_MONITOR, ACTIVITY_STOP] {
+ activity.store(current, Ordering::SeqCst);
+ for _ in 0..3 {
+ assert!(!loss.begin_recovery(
+ false,
+ &host,
+ &activity,
+ &generation,
+ if current == ACTIVITY_MONITOR { 6 } else { 7 }
+ ));
+ }
+ assert!(host.has_launched());
+ }
+ activity.store(ACTIVITY_MONITOR, Ordering::SeqCst);
+ let mut loss = ReadinessLoss::default();
+ for miss in 1..=3 {
+ let ready = host.is_ready(&origin).await;
+ assert!(!ready);
+ assert_eq!(loss.begin_recovery(ready, &host, &activity, &generation, 7), miss == 3);
+ }
+ assert_eq!(host.has_launched(), pending);
+ assert_eq!(host.has_owned_runtime(), !pending);
+ assert!(!stop_is_available(
+ host.has_owned_runtime(),
+ activity.load(Ordering::SeqCst)
+ ));
+ let recovered = host.bootstrap(&DiscardStatus).await;
+ assert_eq!(recovered.phase, BootstrapPhase::Ready);
+ let window_generation = AtomicU64::new(1);
+ assert_eq!(
+ complete_workbench_handoff(&activity, &window_generation, 1),
+ WorkbenchHandoff::Monitor
+ );
+ assert_eq!(
+ stop_is_available(host.has_owned_runtime(), activity.load(Ordering::SeqCst)),
+ !pending
+ );
+ assert_eq!(launcher.launches.load(Ordering::SeqCst), if pending { 1 } else { 2 });
+ if pending {
+ assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert!(launcher.stops.lock().unwrap().is_empty());
+ } else {
+ host.stop_owned_runtime()
+ .await
+ .expect("original receipt survives reused recovery");
+ assert_eq!(
+ launcher.stops.lock().unwrap().as_slice(),
+ std::slice::from_ref(&receipt)
+ );
+ assert!(!host.has_owned_runtime());
+ }
+ });
+ }
+ }
+
+ #[test]
+ fn a_successful_probe_resets_the_failure_streak() {
+ let mut loss = ReadinessLoss::default();
+ assert!(!loss.observe(false));
+ assert!(!loss.observe(false));
+ assert!(!loss.observe(true));
+ assert!(!loss.observe(false));
+ assert!(!loss.observe(false));
+ assert!(loss.observe(false));
+ }
+
+ #[test]
+ fn a_recreated_window_transfers_monitor_ownership_to_bootstrap() {
+ let activity = AtomicU8::new(ACTIVITY_MONITOR);
+
+ assert!(claim_recreated_window_bootstrap(&activity));
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_BOOTSTRAP);
+ }
+
+ #[test]
+ fn a_recreated_window_does_not_duplicate_an_active_bootstrap() {
+ let activity = AtomicU8::new(ACTIVITY_BOOTSTRAP);
+
+ assert!(!claim_recreated_window_bootstrap(&activity));
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_BOOTSTRAP);
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_claims_idle_or_monitor_activity_exclusively() {
+ for current in [ACTIVITY_IDLE, ACTIVITY_MONITOR] {
+ let activity = AtomicU8::new(current);
+ assert!(claim_runtime_removal(&activity));
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_UNINSTALL);
+ assert!(!claim_runtime_removal(&activity));
+ }
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_waits_for_an_active_bootstrap() {
+ let activity = AtomicU8::new(ACTIVITY_BOOTSTRAP);
+
+ assert!(!claim_runtime_removal(&activity));
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_BOOTSTRAP);
+ }
+
+ /// Every effect the confirmed uninstall can produce. `RemoveRuntime` stands
+ /// for the whole success branch the shell wires into it — stopping
+ /// notifications, deleting the private Runtime, the success dialog and the
+ /// shell exit — so a run without it is a run that reported failure and left
+ /// the installation intact. `RestoreLogin`, `RenderLogin` and
+ /// `ReportLoginFailure` are the restore's write, checkbox and login failure
+ /// message, produced by the real `settle_start_at_login` policy.
+ #[cfg(feature = "bundled-runtime")]
+ #[derive(Debug, PartialEq, Eq)]
+ enum UninstallEffect {
+ DisableLogin,
+ RemoveRuntime,
+ RestoreLogin,
+ RenderLogin(bool),
+ ReportLoginFailure,
+ ReportFailure,
+ }
+
+ /// A confirmed uninstall whose restore, when it runs, writes `restore_write`
+ /// and then reads `restore_observed` back.
+ #[cfg(feature = "bundled-runtime")]
+ fn uninstall_run(
+ login_enabled: Result<bool, String>,
+ disable_login: Result<(), String>,
+ removed: bool,
+ restore_write: Result<(), String>,
+ restore_observed: Result<bool, String>,
+ ) -> (UninstallOutcome, Vec<UninstallEffect>) {
+ let effects = std::cell::RefCell::new(Vec::new());
+ let outcome = tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(
+ remove_runtime_after_login_cleanup(
+ login_enabled,
+ || {
+ effects.borrow_mut().push(UninstallEffect::DisableLogin);
+ disable_login
+ },
+ || async {
+ effects.borrow_mut().push(UninstallEffect::RemoveRuntime);
+ removed
+ },
+ || {
+ settle_start_at_login(
+ Ok(true),
+ |enabled| {
+ assert!(enabled, "a restore only ever puts the registration back");
+ effects.borrow_mut().push(UninstallEffect::RestoreLogin);
+ restore_write
+ },
+ || restore_observed,
+ |checked| effects.borrow_mut().push(UninstallEffect::RenderLogin(checked)),
+ || effects.borrow_mut().push(UninstallEffect::ReportLoginFailure),
+ )
+ },
+ || effects.borrow_mut().push(UninstallEffect::ReportFailure),
+ ),
+ );
+ (outcome, effects.into_inner())
+ }
+
+ /// The same uninstall with a restore that succeeds.
+ #[cfg(feature = "bundled-runtime")]
+ fn uninstall_effects(
+ login_enabled: Result<bool, String>,
+ disable_login: Result<(), String>,
+ removed: bool,
+ ) -> Vec<UninstallEffect> {
+ uninstall_run(login_enabled, disable_login, removed, Ok(()), Ok(true)).1
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_clears_an_enabled_login_item_before_removing_the_private_runtime() {
+ assert_eq!(
+ uninstall_run(Ok(true), Ok(()), true, Ok(()), Ok(true)),
+ (
+ UninstallOutcome::Removed,
+ vec![UninstallEffect::DisableLogin, UninstallEffect::RemoveRuntime],
+ ),
+ );
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_leaves_an_already_disabled_login_item_alone() {
+ assert_eq!(
+ uninstall_effects(Ok(false), Ok(()), true),
+ vec![UninstallEffect::RemoveRuntime]
+ );
+ // The removal failed, but this uninstall never disabled anything, so
+ // there is no registration of its own to put back.
+ assert_eq!(
+ uninstall_effects(Ok(false), Ok(()), false),
+ vec![UninstallEffect::RemoveRuntime, UninstallEffect::ReportFailure],
+ );
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_restores_the_login_item_it_cleared_when_the_removal_does_not_happen() {
+ // The application is still installed, so the login registration this
+ // uninstall cleared has to come back before the failure is reported.
+ assert_eq!(
+ uninstall_run(Ok(true), Ok(()), false, Ok(()), Ok(true)),
+ (
+ UninstallOutcome::Kept,
+ vec![
+ UninstallEffect::DisableLogin,
+ UninstallEffect::RemoveRuntime,
+ UninstallEffect::RestoreLogin,
+ UninstallEffect::RenderLogin(true),
+ UninstallEffect::ReportFailure,
+ ],
+ ),
+ );
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_reports_a_login_item_it_could_not_restore() {
+ // Clearing succeeded, the removal did not happen, and putting the
+ // registration back failed too. The checkbox shows what the OS now
+ // holds, the login failure is reported, the uninstall failure is still
+ // reported, and nothing reaches the success dialog or the exit.
+ let lost = vec![
+ UninstallEffect::DisableLogin,
+ UninstallEffect::RemoveRuntime,
+ UninstallEffect::RestoreLogin,
+ UninstallEffect::RenderLogin(false),
+ UninstallEffect::ReportLoginFailure,
+ UninstallEffect::ReportFailure,
+ ];
+ assert_eq!(
+ uninstall_run(Ok(true), Ok(()), false, Err("enable failed".to_owned()), Ok(false)),
+ (UninstallOutcome::KeptWithoutLogin, lost),
+ );
+ // A write that claims success but reads back disabled is the same loss.
+ assert_eq!(
+ uninstall_run(Ok(true), Ok(()), false, Ok(()), Ok(false)).0,
+ UninstallOutcome::KeptWithoutLogin,
+ );
+ // So is a write whose result cannot be read back; the checkbox then
+ // falls back to unchecked.
+ let (outcome, effects) = uninstall_run(Ok(true), Ok(()), false, Ok(()), Err("state unavailable".to_owned()));
+ assert_eq!(outcome, UninstallOutcome::KeptWithoutLogin);
+ assert!(effects.contains(&UninstallEffect::RenderLogin(false)));
+ assert!(effects.ends_with(&[UninstallEffect::ReportLoginFailure, UninstallEffect::ReportFailure]));
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn uninstall_fails_closed_when_the_login_item_cannot_be_cleared() {
+ // Clearing failed, so the Runtime is never touched: no success dialog,
+ // no exit, and the user is told the uninstall failed. Nothing was
+ // disabled, so nothing is restored either.
+ assert_eq!(
+ uninstall_effects(Ok(true), Err("disable failed".to_owned()), true),
+ vec![UninstallEffect::DisableLogin, UninstallEffect::ReportFailure],
+ );
+ // The registration could not even be inspected — same answer, and
+ // nothing is disabled on a state the shell could not read.
+ assert_eq!(
+ uninstall_effects(Err("state unavailable".to_owned()), Ok(()), true),
+ vec![UninstallEffect::ReportFailure],
+ );
+ assert_eq!(
+ uninstall_run(Ok(true), Err("disable failed".to_owned()), true, Ok(()), Ok(true)).0,
+ UninstallOutcome::Kept,
+ );
+ }
+
+ #[derive(Debug, PartialEq, Eq)]
+ enum LoginEffect {
+ Write(bool),
+ Render(bool),
+ ReportFailure,
+ }
+
+ fn settle_login(
+ requested: Result<bool, String>,
+ write: Result<(), String>,
+ observed: Result<bool, String>,
+ ) -> (bool, Vec<LoginEffect>) {
+ let effects = std::cell::RefCell::new(Vec::new());
+ let settled = settle_start_at_login(
+ requested,
+ |enabled| {
+ effects.borrow_mut().push(LoginEffect::Write(enabled));
+ write
+ },
+ || observed,
+ |checked| effects.borrow_mut().push(LoginEffect::Render(checked)),
+ || effects.borrow_mut().push(LoginEffect::ReportFailure),
+ );
+ (settled, effects.into_inner())
+ }
+
+ #[test]
+ fn start_at_login_writes_once_and_draws_the_state_it_reads_back() {
+ for enabled in [true, false] {
+ assert_eq!(
+ settle_login(Ok(enabled), Ok(()), Ok(enabled)),
+ (true, vec![LoginEffect::Write(enabled), LoginEffect::Render(enabled)]),
+ );
+ }
+ }
+
+ #[test]
+ fn start_at_login_reports_every_unsettled_write_once_without_retrying() {
+ // The write failed: the checkbox shows the registration that remains.
+ assert_eq!(
+ settle_login(Ok(true), Err("enable failed".to_owned()), Ok(false)),
+ (
+ false,
+ vec![
+ LoginEffect::Write(true),
+ LoginEffect::Render(false),
+ LoginEffect::ReportFailure,
+ ],
+ ),
+ );
+ // The write claimed success but the OS reads back the other state.
+ assert_eq!(
+ settle_login(Ok(false), Ok(()), Ok(true)),
+ (
+ false,
+ vec![
+ LoginEffect::Write(false),
+ LoginEffect::Render(true),
+ LoginEffect::ReportFailure,
+ ],
+ ),
+ );
+ // The state cannot be read back, so the checkbox falls back to unchecked.
+ assert_eq!(
+ settle_login(Ok(true), Ok(()), Err("state unavailable".to_owned())),
+ (
+ false,
+ vec![
+ LoginEffect::Write(true),
+ LoginEffect::Render(false),
+ LoginEffect::ReportFailure,
+ ],
+ ),
+ );
+ // The toggle could not learn what to request: nothing is written, and
+ // the checkbox is still redrawn from a fresh read.
+ assert_eq!(
+ settle_login(Err("state unavailable".to_owned()), Ok(()), Ok(true)),
+ (false, vec![LoginEffect::Render(true), LoginEffect::ReportFailure]),
+ );
+ }
+
+ #[derive(Debug, PartialEq, Eq)]
+ enum RecoveryEffect {
+ HandOff,
+ StopNotifications,
+ SpawnBootstrap,
+ RetainOwnership,
+ }
+
+ fn readiness_recovery_effects(handed_off: bool, retained: bool) -> (bool, Vec<RecoveryEffect>) {
+ let effects = std::cell::RefCell::new(Vec::new());
+ let stop = recover_after_readiness_loss(
+ || {
+ effects.borrow_mut().push(RecoveryEffect::HandOff);
+ handed_off
+ },
+ || effects.borrow_mut().push(RecoveryEffect::StopNotifications),
+ || effects.borrow_mut().push(RecoveryEffect::SpawnBootstrap),
+ || {
+ effects.borrow_mut().push(RecoveryEffect::RetainOwnership);
+ retained
+ },
+ );
+ (stop, effects.into_inner())
+ }
+
+ #[test]
+ fn readiness_recovery_gives_up_notifications_only_after_the_hand_off_succeeds() {
+ assert_eq!(
+ readiness_recovery_effects(true, false),
+ (
+ true,
+ vec![
+ RecoveryEffect::HandOff,
+ RecoveryEffect::StopNotifications,
+ RecoveryEffect::SpawnBootstrap,
+ ]
+ ),
+ );
+ }
+
+ #[test]
+ fn a_failed_hand_off_keeps_the_notification_connection_and_the_monitor() {
+ // Navigation failed, so the shell is still on the abandoned origin. The
+ // monitor takes its ownership back and keeps watching with a live
+ // connection instead of running mute for the rest of the session.
+ let (stop, effects) = readiness_recovery_effects(false, true);
+ assert!(!stop);
+ assert_eq!(effects, vec![RecoveryEffect::HandOff, RecoveryEffect::RetainOwnership]);
+ // Ownership that cannot be retaken belongs to another run, so this
+ // monitor exits — still without tearing down that run's connection.
+ let (stop, effects) = readiness_recovery_effects(false, false);
+ assert!(stop);
+ assert_eq!(effects, vec![RecoveryEffect::HandOff, RecoveryEffect::RetainOwnership]);
+ }
+
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn native_uninstall_copy_uses_the_first_supported_system_locale() {
+ let chinese =
+ native_uninstall_catalog_for_locales(["fr-FR", "zh-Hant-TW", "en-US"].into_iter().map(str::to_owned));
+ let english =
+ native_uninstall_catalog_for_locales(["fr-FR", "en-US", "zh-Hans-CN"].into_iter().map(str::to_owned));
+
+ assert_ne!(chinese.menu_label, english.menu_label);
+ assert_ne!(chinese.confirm_message, english.confirm_message);
+ assert!(!chinese.failure_message.is_empty());
+ assert!(!english.failure_message.is_empty());
+ }
+
+ #[test]
+ fn a_navigation_failure_is_retryable_without_losing_the_ready_origin() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").expect("a loopback origin");
+ let ready = BootstrapStatus::ready(&origin, 4, BootstrapNoticeCode::Ready);
+ let mut links = DeepLinks::default();
+ links.receive(["avibe://session/retry"]);
+ let navigation = links.bootstrap_navigation(&ready).unwrap();
+
+ let failed = workbench_navigation_failure_status(&ready, &origin);
+ links.observe_bootstrap(&failed);
+
+ assert_eq!(failed.phase, BootstrapPhase::Failed);
+ assert_eq!(failed.origin, origin.as_str());
+ assert_eq!(failed.attempt, ready.attempt);
+ assert_eq!(failed.notice.code, BootstrapNoticeCode::WorkbenchNavigationFailed);
+ assert!(failed.retryable);
+ assert_eq!(links.bootstrap_navigation(&ready).unwrap().url(), navigation.url());
+ }
+
+ #[test]
+ fn a_recreated_window_keeps_bootstrap_ownership_during_handoff() {
+ let activity = AtomicU8::new(ACTIVITY_BOOTSTRAP);
+ let generation = AtomicU64::new(2);
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap();
+ let ready = BootstrapStatus::ready(&origin, 1, BootstrapNoticeCode::Ready);
+ let mut links = DeepLinks::default();
+ links.receive(["avibe://session/recreated"]);
+ let navigation = links.bootstrap_navigation(&ready).unwrap();
+
+ assert_eq!(
+ complete_workbench_handoff(&activity, &generation, 1),
+ WorkbenchHandoff::RetryCurrentWindow
+ );
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_BOOTSTRAP);
+ assert!(!links.commit_navigation(&navigation, true, 1, generation.load(Ordering::SeqCst)));
+ let replacement = links.bootstrap_navigation(&ready).unwrap();
+ assert_eq!(replacement.url(), navigation.url());
+ assert_eq!(
+ complete_workbench_handoff(&activity, &generation, 2),
+ WorkbenchHandoff::Monitor
+ );
+ assert!(links.commit_navigation(&replacement, true, 2, generation.load(Ordering::SeqCst)));
+ assert_eq!(links.bootstrap_navigation(&ready).unwrap().url().path(), "/");
+ }
+
+ #[test]
+ fn an_unchanged_window_enters_monitoring_after_handoff() {
+ let activity = AtomicU8::new(ACTIVITY_BOOTSTRAP);
+ let generation = AtomicU64::new(2);
+
+ assert_eq!(
+ complete_workbench_handoff(&activity, &generation, 2),
+ WorkbenchHandoff::Monitor
+ );
+ assert_eq!(activity.load(Ordering::SeqCst), ACTIVITY_MONITOR);
+ }
+
+ #[test]
+ fn navigation_is_confined_to_the_shell_or_the_active_runtime_listener() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").expect("a loopback origin");
+
+ assert!(navigation_is_allowed(
+ &Url::parse("tauri://localhost/index.html").expect("shell URL"),
+ None
+ ));
+ assert!(navigation_is_allowed(
+ &Url::parse("http://127.0.0.1:5123/show/session/").expect("Workbench URL"),
+ Some(&origin)
+ ));
+ for raw in [
+ "http://127.0.0.1:5124/",
+ "http://192.168.1.10:5123/",
+ "https://avibe.bot/",
+ ] {
+ assert!(
+ !navigation_is_allowed(&Url::parse(raw).expect("test URL"), Some(&origin)),
+ "{raw} must not leave the active listener"
+ );
+ }
+ }
+
+ #[test]
+ fn only_bare_http_origins_are_treated_as_runtime_rebinds() {
+ for raw in [
+ "http://192.168.1.10:5123/",
+ "http://localhost:5123",
+ "http://[2001:db8::1]:5123/",
+ ] {
+ assert!(is_runtime_rebind_target(&Url::parse(raw).expect("test URL")), "{raw}");
+ }
+ for raw in [
+ "https://192.168.1.10:5123/",
+ "http://192.168.1.10/",
+ "http://192.168.1.10:5123/settings",
+ "http://[email protected]:5123/",
+ "http://192.168.1.10:5123/?next=remote",
+ ] {
+ assert!(!is_runtime_rebind_target(&Url::parse(raw).expect("test URL")), "{raw}");
+ }
+ }
+
+ #[test]
+ fn only_web_destinations_leave_for_the_system_browser() {
+ for raw in [
+ "https://auth.openai.com/oauth/authorize?client_id=avibe&state=s",
+ "http://127.0.0.1:5123/show/page",
+ ] {
+ assert_eq!(
+ new_window_decision(&Url::parse(raw).expect("test URL")),
+ NewWindowDecision::OpenInSystemBrowser,
+ "{raw}"
+ );
+ }
+ for raw in [
+ "about:blank",
+ "javascript:alert(1)",
+ "data:text/html,<p>hi</p>",
+ "blob:http://127.0.0.1:5123/7f1c",
+ "file:///etc/hosts",
+ "mailto:[email protected]",
+ "avibe://open",
+ "tauri://localhost/index.html",
+ ] {
+ assert_eq!(
+ new_window_decision(&Url::parse(raw).expect("test URL")),
+ NewWindowDecision::Deny,
+ "{raw}"
+ );
+ }
+ }
+}
diff --git a/desktop/src-tauri/src/macos_deep_link.rs b/desktop/src-tauri/src/macos_deep_link.rs
new file mode 100644
index 000000000..85169191f
--- /dev/null
+++ b/desktop/src-tauri/src/macos_deep_link.rs
@@ -0,0 +1,179 @@
+use std::cell::RefCell;
+
+use objc2::rc::Retained;
+use objc2::{define_class, msg_send, sel, AnyThread, DefinedClass};
+use objc2_foundation::{NSAppleEventDescriptor, NSAppleEventManager, NSObject, NSObjectProtocol};
+use tauri::plugin::{Builder, TauriPlugin};
+use tauri::RunEvent;
+
+const GET_URL_EVENT: u32 = u32::from_be_bytes(*b"GURL");
+const DIRECT_OBJECT: u32 = u32::from_be_bytes(*b"----");
+
+struct HandlerState {
+ receive: Box<dyn Fn(String)>,
+}
+
+define_class!(
+ #[unsafe(super = NSObject)]
+ #[name = "AvibeRawDeepLinkHandler"]
+ #[ivars = HandlerState]
+ struct RawDeepLinkHandler;
+
+ unsafe impl NSObjectProtocol for RawDeepLinkHandler {}
+
+ impl RawDeepLinkHandler {
+ #[unsafe(method(handleGetURLEvent:withReplyEvent:))]
+ fn handle_get_url(&self, event: &NSAppleEventDescriptor, _reply: &NSAppleEventDescriptor) {
+ if let Some(raw) = raw_url(event) {
+ (self.ivars().receive)(raw);
+ }
+ }
+ }
+);
+
+impl RawDeepLinkHandler {
+ fn new(receive: impl Fn(String) + 'static) -> Retained<Self> {
+ let allocated = Self::alloc().set_ivars(HandlerState {
+ receive: Box::new(receive),
+ });
+ unsafe { msg_send![super(allocated), init] }
+ }
+}
+
+thread_local! {
+ static HANDLER: RefCell<Option<Retained<RawDeepLinkHandler>>> = const { RefCell::new(None) };
+}
+
+fn raw_url(event: &NSAppleEventDescriptor) -> Option<String> {
+ let descriptor: Option<Retained<NSAppleEventDescriptor>> =
+ unsafe { msg_send![event, paramDescriptorForKeyword: DIRECT_OBJECT] };
+ descriptor?.stringValue().map(|text| text.to_string())
+}
+
+fn install(receive: impl Fn(String) + 'static) {
+ let handler = RawDeepLinkHandler::new(receive);
+ let manager = NSAppleEventManager::sharedAppleEventManager();
+ unsafe {
+ let _: () = msg_send![
+ &*manager,
+ setEventHandler: &*handler,
+ andSelector: sel!(handleGetURLEvent:withReplyEvent:),
+ forEventClass: GET_URL_EVENT,
+ andEventID: GET_URL_EVENT,
+ ];
+ }
+ HANDLER.with(|current| *current.borrow_mut() = Some(handler));
+}
+
+fn remove() {
+ HANDLER.with(|current| {
+ let Some(handler) = current.borrow_mut().take() else {
+ return;
+ };
+ let manager = NSAppleEventManager::sharedAppleEventManager();
+ unsafe {
+ let _: () = msg_send![
+ &*manager,
+ removeEventHandlerForEventClass: GET_URL_EVENT,
+ andEventID: GET_URL_EVENT,
+ ];
+ }
+ drop(handler);
+ });
+}
+
+pub fn init() -> TauriPlugin<tauri::Wry> {
+ Builder::new("macos-deep-link")
+ .setup(|app, _| {
+ let app = app.clone();
+ install(move |raw| crate::receive_native_deep_link(&app, [raw]));
+ Ok(())
+ })
+ .on_event(|_, event| {
+ if matches!(event, RunEvent::Exit) {
+ remove();
+ }
+ })
+ .build()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::{Arc, Mutex};
+
+ use avibe_runtime_host::deep_link::{parse_deep_link, DeepLinks};
+ use avibe_runtime_host::LoopbackOrigin;
+ use objc2::ClassType;
+ use objc2_foundation::NSString;
+
+ use super::*;
+
+ fn native_event(raw: Option<&str>) -> Retained<NSAppleEventDescriptor> {
+ let event: Retained<NSAppleEventDescriptor> = unsafe {
+ msg_send![
+ NSAppleEventDescriptor::class(),
+ appleEventWithEventClass: GET_URL_EVENT,
+ eventID: GET_URL_EVENT,
+ targetDescriptor: None::<&NSAppleEventDescriptor>,
+ returnID: -1_i16,
+ transactionID: 0_i32,
+ ]
+ };
+ if let Some(raw) = raw {
+ let parameter = NSAppleEventDescriptor::descriptorWithString(&NSString::from_str(raw));
+ unsafe {
+ let _: () = msg_send![&*event, setParamDescriptor: &*parameter, forKeyword: DIRECT_OBJECT];
+ }
+ }
+ event
+ }
+
+ #[test]
+ fn native_descriptor_text_keeps_the_literal_grammar_visible_to_the_parser() {
+ let valid = "avibe://session/target";
+ assert!(parse_deep_link(valid).is_some());
+ for raw in [
+ valid,
+ "avibe://session/ignored/../target",
+ "avibe://session/ignored/%2E%2E/target",
+ "avibe://session/target\0ignored",
+ "avibe://session/你好",
+ ] {
+ let event = native_event(Some(raw));
+ let received = raw_url(&event).unwrap();
+ assert_eq!(received, raw);
+ assert_eq!(parse_deep_link(&received).is_some(), raw == valid);
+ }
+ assert!(raw_url(&native_event(None)).is_none());
+ }
+
+ #[test]
+ fn the_native_selector_feeds_literal_input_to_the_shared_stash_without_an_appkit_loop() {
+ let origin = LoopbackOrigin::parse("http://127.0.0.1:39567").unwrap();
+ let links = Arc::new(Mutex::new(DeepLinks::default()));
+ let receiver = links.clone();
+ let handler = RawDeepLinkHandler::new(move |raw| receiver.lock().unwrap().receive([raw]));
+ let reply = NSAppleEventDescriptor::nullDescriptor();
+ for (raw, expected_path) in [
+ ("avibe://session/target", Some("/chat/target")),
+ ("avibe://session/ignored/../target", None),
+ ("avibe://session/ignored/%2E%2E/target", None),
+ ] {
+ let event = native_event(Some(raw));
+ unsafe {
+ let _: () = msg_send![&*handler, handleGetURLEvent: &*event, withReplyEvent: &*reply];
+ }
+ let navigation = links
+ .lock()
+ .unwrap()
+ .workbench_navigation(&origin, &origin.navigation_url());
+ assert_eq!(
+ navigation.as_ref().map(|navigation| navigation.url().path()),
+ expected_path
+ );
+ if let Some(navigation) = navigation {
+ assert!(links.lock().unwrap().commit_navigation(&navigation, true, 1, 1));
+ }
+ }
+ }
+}
diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs
new file mode 100644
index 000000000..c1a0b22f3
--- /dev/null
+++ b/desktop/src-tauri/src/main.rs
@@ -0,0 +1,7 @@
+// The shell is a GUI application; a release build must not open a console window
+// alongside it on Windows.
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+
+fn main() {
+ avibe_desktop_lib::run()
+}
diff --git a/desktop/src-tauri/src/native_frame.rs b/desktop/src-tauri/src/native_frame.rs
new file mode 100644
index 000000000..0e0506cff
--- /dev/null
+++ b/desktop/src-tauri/src/native_frame.rs
@@ -0,0 +1,99 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use avibe_runtime_host::window_frame::{clamp_window_frame, MonitorArea, WindowFrame};
+use tauri::plugin::{Builder, TauriPlugin};
+use tauri::{Manager, PhysicalPosition, PhysicalSize, Runtime, Window, WindowEvent};
+use tauri_plugin_window_state::{AppHandleExt, StateFlags};
+
+use crate::MAIN_WINDOW;
+
+pub fn state_flags() -> StateFlags {
+ StateFlags::POSITION | StateFlags::SIZE | StateFlags::MAXIMIZED
+}
+
+pub fn clamp<R: Runtime>(window: &Window<R>) -> tauri::Result<()> {
+ if window.is_maximized()? || window.is_fullscreen()? || window.is_minimized()? {
+ return Ok(());
+ }
+ let position = window.outer_position()?;
+ let size = window.inner_size()?;
+ let frame = WindowFrame {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ };
+ let monitors: Vec<_> = window
+ .available_monitors()?
+ .into_iter()
+ .map(|monitor| {
+ let area = monitor.work_area();
+ MonitorArea {
+ frame: WindowFrame {
+ x: area.position.x,
+ y: area.position.y,
+ width: area.size.width,
+ height: area.size.height,
+ },
+ scale_factor: monitor.scale_factor(),
+ }
+ })
+ .collect();
+ let Some(config) = window
+ .config()
+ .app
+ .windows
+ .iter()
+ .find(|config| config.label == MAIN_WINDOW)
+ else {
+ return Ok(());
+ };
+ let restored = clamp_window_frame(
+ frame,
+ &monitors,
+ (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0)),
+ );
+ if restored.width != frame.width || restored.height != frame.height {
+ window.set_size(PhysicalSize::new(restored.width, restored.height))?;
+ }
+ if restored.x != frame.x || restored.y != frame.y {
+ window.set_position(PhysicalPosition::new(restored.x, restored.y))?;
+ }
+ Ok(())
+}
+
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ Builder::new("native-frame")
+ .on_window_ready(|window| {
+ if window.label() != MAIN_WINDOW {
+ return;
+ }
+ let _ = clamp(&window);
+ let _ = window.show();
+ let generation = Arc::new(AtomicU64::new(0));
+ let app = window.app_handle().clone();
+ window.on_window_event(move |event| {
+ if !matches!(event, WindowEvent::Moved(_) | WindowEvent::Resized(_)) {
+ return;
+ }
+ let observed = generation.fetch_add(1, Ordering::SeqCst) + 1;
+ let generation = generation.clone();
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ if generation.load(Ordering::SeqCst) != observed {
+ return;
+ }
+ let save_app = app.clone();
+ let _ = app.run_on_main_thread(move || {
+ if generation.load(Ordering::SeqCst) == observed {
+ let _ = save_app.save_window_state(state_flags());
+ }
+ });
+ });
+ });
+ })
+ .build()
+}
diff --git a/desktop/src-tauri/src/notifications.rs b/desktop/src-tauri/src/notifications.rs
new file mode 100644
index 000000000..1c604b78b
--- /dev/null
+++ b/desktop/src-tauri/src/notifications.rs
@@ -0,0 +1,295 @@
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+
+use avibe_runtime_host::notifications::{
+ run_notifications, HttpNotificationTransport, NotificationFilter, NotificationGate, NotificationIntent,
+ NotificationSink,
+};
+use avibe_runtime_host::LoopbackOrigin;
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Manager};
+use tauri_plugin_notification::NotificationExt;
+
+use crate::{native_catalog_for_locales, MAIN_WINDOW};
+
+pub const MENU_ID: &str = "notifications";
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NativeNotificationCatalog {
+ pub toggle: String,
+ approval_requested: NotificationCopy,
+ run_succeeded: NotificationCopy,
+ run_failed: NotificationCopy,
+ run_canceled: NotificationCopy,
+}
+
+#[derive(Clone, Deserialize)]
+struct NotificationCopy {
+ title: String,
+ body: String,
+}
+
+impl NativeNotificationCatalog {
+ fn copy(&self, intent: NotificationIntent) -> NotificationCopy {
+ match intent {
+ NotificationIntent::ApprovalRequested => &self.approval_requested,
+ NotificationIntent::RunSucceeded => &self.run_succeeded,
+ NotificationIntent::RunFailed => &self.run_failed,
+ NotificationIntent::RunCanceled => &self.run_canceled,
+ }
+ .clone()
+ }
+}
+
+#[derive(Deserialize, Serialize)]
+struct Preference {
+ enabled: bool,
+}
+
+fn read_preference(path: &Path) -> std::io::Result<bool> {
+ match std::fs::read(path) {
+ Ok(bytes) => serde_json::from_slice::<Preference>(&bytes)
+ .map(|preference| preference.enabled)
+ .map_err(std::io::Error::other),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
+ Err(error) => Err(error),
+ }
+}
+
+fn write_preference(path: &Path, enabled: bool) -> std::io::Result<()> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let bytes = serde_json::to_vec(&Preference { enabled })?;
+ let temporary = path.with_extension("tmp");
+ let result = std::fs::write(&temporary, bytes).and_then(|()| std::fs::rename(&temporary, path));
+ if result.is_err() {
+ let _ = std::fs::remove_file(&temporary);
+ }
+ result
+}
+
+struct Connection {
+ origin: LoopbackOrigin,
+ task: tauri::async_runtime::JoinHandle<()>,
+}
+
+pub struct Notifications {
+ preference_path: PathBuf,
+ enabled: Arc<AtomicBool>,
+ generation: Arc<AtomicU64>,
+ connection: Mutex<Option<Connection>>,
+ filter: Arc<Mutex<NotificationFilter>>,
+}
+
+impl Notifications {
+ pub fn new(preference_path: PathBuf) -> Self {
+ let enabled = read_preference(&preference_path).unwrap_or_else(|_| {
+ eprintln!("Desktop notifications disabled: the notification preference could not be read.");
+ false
+ });
+ Self {
+ preference_path,
+ enabled: Arc::new(AtomicBool::new(enabled)),
+ generation: Arc::new(AtomicU64::new(0)),
+ connection: Mutex::new(None),
+ filter: Arc::new(Mutex::new(NotificationFilter::default())),
+ }
+ }
+
+ pub fn enabled(&self) -> bool {
+ self.enabled.load(Ordering::SeqCst)
+ }
+
+ pub fn toggle(&self) {
+ let enabled = !self.enabled();
+ if write_preference(&self.preference_path, enabled).is_ok() {
+ self.enabled.store(enabled, Ordering::SeqCst);
+ } else {
+ eprintln!("The desktop notification preference could not be saved.");
+ }
+ }
+
+ pub fn start(&self, app: &AppHandle, origin: LoopbackOrigin) {
+ let mut connection = self.connection.lock().expect("notification connection lock");
+ if connection.as_ref().is_some_and(|current| current.origin == origin) {
+ return;
+ }
+ let observed_generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
+ if let Some(previous) = connection.take() {
+ previous.task.abort();
+ }
+ let Ok(transport) = HttpNotificationTransport::new(origin.clone()) else {
+ eprintln!("The desktop notification connection could not be initialized.");
+ return;
+ };
+ let sink = NativeSink {
+ app: app.clone(),
+ enabled: self.enabled.clone(),
+ generation: self.generation.clone(),
+ observed_generation,
+ };
+ let filter = self.filter.clone();
+ *connection = Some(Connection {
+ origin,
+ task: tauri::async_runtime::spawn(async move {
+ run_notifications(&transport, filter, &sink).await;
+ }),
+ });
+ }
+
+ pub fn stop(&self) {
+ let mut connection = self.connection.lock().expect("notification connection lock");
+ self.generation.fetch_add(1, Ordering::SeqCst);
+ if let Some(connection) = connection.take() {
+ connection.task.abort();
+ }
+ }
+}
+
+#[derive(Clone)]
+struct NativeSink {
+ app: AppHandle,
+ enabled: Arc<AtomicBool>,
+ generation: Arc<AtomicU64>,
+ observed_generation: u64,
+}
+
+impl NotificationSink for NativeSink {
+ fn gate(&self) -> NotificationGate {
+ let window = self.app.get_webview_window(MAIN_WINDOW);
+ NotificationGate {
+ enabled: self.enabled.load(Ordering::SeqCst)
+ && self.generation.load(Ordering::SeqCst) == self.observed_generation,
+ focused: window
+ .as_ref()
+ .is_some_and(|window| window.is_focused().unwrap_or(true)),
+ visible: window
+ .as_ref()
+ .is_some_and(|window| window.is_visible().unwrap_or(true)),
+ }
+ }
+
+ fn deliver(&self, intent: NotificationIntent) {
+ let sink = self.clone();
+ let _ = self.app.run_on_main_thread(move || {
+ if !sink.gate().allows() {
+ return;
+ }
+ let copy = native_catalog_for_locales(sys_locale::get_locales())
+ .notifications
+ .copy(intent);
+ if sink
+ .app
+ .notification()
+ .builder()
+ .title(copy.title)
+ .body(copy.body)
+ .show()
+ .is_err()
+ {
+ eprintln!("The desktop notification could not be submitted to the operating system.");
+ }
+ });
+ }
+}
+
+pub fn start(app: &AppHandle, origin: LoopbackOrigin) {
+ app.state::<Notifications>().start(app, origin);
+}
+
+pub fn stop(app: &AppHandle) {
+ app.state::<Notifications>().stop();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct TestDirectory(PathBuf);
+
+ impl TestDirectory {
+ fn new() -> Self {
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+ let directory = std::env::temp_dir().join(format!(
+ "avibe-notification-preference-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::SeqCst)
+ ));
+ std::fs::create_dir(&directory).unwrap();
+ Self(directory)
+ }
+ }
+
+ impl Drop for TestDirectory {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+
+ #[test]
+ fn preference_defaults_on_and_persists_the_tray_choice_across_restarts() {
+ let directory = TestDirectory::new();
+ let path = directory.0.join("notifications.json");
+ let state = Notifications::new(path.clone());
+ assert!(state.enabled());
+ state.toggle();
+ assert!(!state.enabled());
+ let restarted = Notifications::new(path.clone());
+ assert!(!restarted.enabled());
+ restarted.toggle();
+ assert!(Notifications::new(path).enabled());
+ }
+
+ #[test]
+ fn unreadable_preferences_fail_closed_and_failed_writes_preserve_the_choice() {
+ let directory = TestDirectory::new();
+ let path = directory.0.join("notifications.json");
+ std::fs::write(&path, "invalid").unwrap();
+ assert!(!Notifications::new(path.clone()).enabled());
+ std::fs::remove_file(&path).unwrap();
+ let state = Notifications::new(path.clone());
+ std::fs::create_dir(&path).unwrap();
+ state.toggle();
+ assert!(state.enabled());
+ assert!(!path.with_extension("tmp").exists());
+ }
+
+ #[test]
+ fn every_intent_uses_only_native_catalog_copy_in_both_locales() {
+ for locale in ["en-US", "zh-CN"] {
+ let catalog = native_catalog_for_locales([locale.to_owned()]).notifications;
+ assert!(!catalog.toggle.is_empty());
+ for intent in [
+ NotificationIntent::ApprovalRequested,
+ NotificationIntent::RunSucceeded,
+ NotificationIntent::RunFailed,
+ NotificationIntent::RunCanceled,
+ ] {
+ let copy = catalog.copy(intent);
+ assert!(!copy.title.is_empty() && !copy.body.is_empty());
+ assert!(!copy.body.contains("{{"));
+ }
+ }
+ }
+
+ #[test]
+ fn stopping_invalidates_dispatched_intents_and_aborts_the_connection_task() {
+ let directory = TestDirectory::new();
+ let state = Notifications::new(directory.0.join("notifications.json"));
+ let task = tauri::async_runtime::spawn(std::future::pending());
+ *state.connection.lock().unwrap() = Some(Connection {
+ origin: LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap(),
+ task,
+ });
+ let previous = state.generation.load(Ordering::SeqCst);
+ state.stop();
+ assert!(state.connection.lock().unwrap().is_none());
+ assert_ne!(state.generation.load(Ordering::SeqCst), previous);
+ assert!(state.enabled());
+ state.stop();
+ assert!(state.connection.lock().unwrap().is_none());
+ }
+}
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
new file mode 100644
index 000000000..f71bd0c0e
--- /dev/null
+++ b/desktop/src-tauri/tauri.conf.json
@@ -0,0 +1,60 @@
+{
+ "$schema": "https://schema.tauri.app/config/2",
+ "productName": "Avibe",
+ "version": "0.1.0",
+ "identifier": "bot.avibe.desktop",
+ "build": {
+ "beforeDevCommand": "npm run dev",
+ "beforeBuildCommand": "npm run build",
+ "devUrl": "http://localhost:1420",
+ "frontendDist": "../dist"
+ },
+ "app": {
+ "windows": [
+ {
+ "label": "main",
+ "create": false,
+ "title": "Avibe",
+ "width": 1200,
+ "height": 800,
+ "minWidth": 880,
+ "minHeight": 600,
+ "visible": false,
+ "center": true,
+ "resizable": true
+ }
+ ],
+ "security": {
+ "capabilities": ["bootstrap"],
+ "csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost"
+ }
+ },
+ "plugins": {
+ "deep-link": {
+ "desktop": {
+ "schemes": ["avibe"]
+ }
+ }
+ },
+ "bundle": {
+ "active": true,
+ "targets": "all",
+ "category": "Productivity",
+ "shortDescription": "The local-first Agent OS",
+ "longDescription": "Avibe turns this machine into the runtime an agent lives in. The desktop shell starts the local Avibe Runtime and opens its Workbench in a native window.",
+ "resources": {
+ "resources/runtime/": "runtime/"
+ },
+ "macOS": {
+ "hardenedRuntime": true,
+ "entitlements": "Entitlements.plist"
+ },
+ "icon": [
+ "icons/32x32.png",
+ "icons/128x128.png",
+ "icons/icon.icns",
+ "icons/icon.ico"
+ ]
+ }
+}
diff --git a/desktop/src-tauri/tests/notarization_preflight.rs b/desktop/src-tauri/tests/notarization_preflight.rs
new file mode 100644
index 000000000..6032d9e00
--- /dev/null
+++ b/desktop/src-tauri/tests/notarization_preflight.rs
@@ -0,0 +1,101 @@
+//! Guards for the macOS notarization preflight contract.
+//!
+//! The bundle is accepted by Apple's notary service only when it is signed
+//! with Developer ID, the hardened runtime is enabled, and the entitlements
+//! cover what WKWebView needs. These facts live in configuration files that
+//! compile-time tooling does not fully validate, so each is asserted here as
+//! an invariant rather than left to review vigilance.
+
+use std::path::{Path, PathBuf};
+
+use serde_json::Value;
+
+fn crate_dir() -> &'static Path {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn read_to_string(path: &Path) -> String {
+ std::fs::read_to_string(path).unwrap_or_else(|error| panic!("{} is readable: {error}", path.display()))
+}
+
+fn config() -> Value {
+ serde_json::from_str(&read_to_string(&crate_dir().join("tauri.conf.json")))
+ .unwrap_or_else(|error| panic!("tauri.conf.json is valid JSON: {error}"))
+}
+
+fn entitlements_path() -> PathBuf {
+ let path = crate_dir().join("Entitlements.plist");
+ assert!(path.is_file(), "Entitlements.plist exists next to tauri.conf.json");
+ path
+}
+
+#[test]
+fn the_macos_bundle_declares_the_hardened_runtime_and_entitlements() {
+ let binding = config();
+ let macos = binding["bundle"]["macOS"]
+ .as_object()
+ .expect("bundle.macOS is configured");
+ // Explicit, not inherited from tooling defaults: a future Tauri default
+ // flip must be a deliberate decision, not a silent behavior change.
+ assert_eq!(
+ macos["hardenedRuntime"],
+ Value::Bool(true),
+ "hardened runtime must be explicitly enabled for notarization"
+ );
+ assert_eq!(
+ macos["entitlements"],
+ Value::String("Entitlements.plist".into()),
+ "the bundle must sign with the checked-in entitlements"
+ );
+}
+
+#[test]
+fn entitlements_grant_no_executable_memory_exception() {
+ let entitlements = read_to_string(&entitlements_path());
+ // WKWebView's JavaScript engine JITs inside WebKit-owned helper
+ // processes; the embedding Tauri process itself needs no
+ // executable-memory exception, and the notary does not require one.
+ // Granting it would weaken the hardened runtime for the whole process,
+ // so its absence is the invariant: any re-add must come with evidence
+ // that the app process itself needs it.
+ assert!(
+ !entitlements.contains("<key>"),
+ "entitlements must stay empty; in particular no executable-memory exception for the embedding process"
+ );
+}
+
+#[test]
+fn the_dmg_script_never_re_signs_an_identity_signed_app() {
+ let script = read_to_string(&crate_dir().join("..").join("scripts").join("create-macos-dmg.sh"));
+ // The guard must bind to executable logic, not comment prose. The
+ // ad-hoc re-sign may only run inside the branch whose `if` condition
+ // tests the ad-hoc/absent signature markers; stripping that condition
+ // to re-sign unconditionally must fail this test even with every
+ // comment left intact.
+ let if_line = script
+ .lines()
+ .find(|line| {
+ let trimmed = line.trim_start();
+ trimmed.starts_with("if ") && (trimmed.contains("adhoc") || trimmed.contains("signature"))
+ })
+ .expect("the script branches on signature state before re-signing");
+ assert!(
+ if_line.contains("adhoc") && if_line.contains("identity"),
+ "the branch condition must test the ad-hoc/absent markers: {if_line}"
+ );
+ let if_offset = script.find(if_line.trim()).expect("if line offset");
+ let resign = script
+ .find("--sign -")
+ .expect("the script re-signs disposable ad-hoc copies");
+ assert!(
+ if_offset < resign,
+ "the ad-hoc re-sign must appear after (inside) the signature-state branch"
+ );
+ // The re-sign appears exactly once and no second signing site exists
+ // outside the branch.
+ assert_eq!(
+ script.matches("--sign ").count(),
+ 1,
+ "exactly one re-sign site: an identity-signed app is never re-signed"
+ );
+}
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
new file mode 100644
index 000000000..0693476ec
--- /dev/null
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -0,0 +1,912 @@
+//! Guards on the shell's two load-bearing boundaries.
+//!
+//! Both are enforced by configuration and narrow ownership — a capability that
+//! names no remote URL, and code that never sends raw process signals. Explicit
+//! uninstall may invoke the Runtime's own graceful CLI, so the source boundary
+//! is asserted directly alongside the capability contract.
+
+use std::path::{Path, PathBuf};
+
+use serde_json::Value;
+
+const MAIN_WINDOW: &str = "main";
+
+fn crate_dir() -> &'static Path {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn read_to_string(path: &Path) -> String {
+ std::fs::read_to_string(path).unwrap_or_else(|error| panic!("{} is readable: {error}", path.display()))
+}
+
+fn read_json(path: PathBuf) -> Value {
+ serde_json::from_str(&read_to_string(&path))
+ .unwrap_or_else(|error| panic!("{} is valid JSON: {error}", path.display()))
+}
+
+fn capability() -> Value {
+ read_json(crate_dir().join("capabilities").join("bootstrap.json"))
+}
+
+fn config() -> Value {
+ read_json(crate_dir().join("tauri.conf.json"))
+}
+
+/// Source with its test module removed, so a test's own vocabulary cannot
+/// satisfy a check about the shipping code.
+fn shipping_source(relative: &str) -> String {
+ shipping_text(&read_to_string(&crate_dir().join(relative)))
+}
+
+/// Line endings are normalized to LF first. A Windows checkout has CRLF, and
+/// every check here must read the same text on every platform.
+fn shipping_text(source: &str) -> String {
+ let source = source.replace("\r\n", "\n");
+ match source.find("#[cfg(test)]") {
+ Some(offset) => source[..offset].to_owned(),
+ None => source,
+ }
+}
+
+#[test]
+fn source_checks_read_a_windows_checkout_as_the_same_text() {
+ let checkout = read_to_string(&crate_dir().join("src/lib.rs")).replace("\r\n", "\n");
+ let windows = checkout.replace('\n', "\r\n");
+ assert_eq!(shipping_text(&windows), shipping_text(&checkout));
+ assert!(!shipping_source("src/lib.rs").contains('\r'));
+}
+
+#[test]
+fn the_bootstrap_capability_is_never_granted_to_remotely_loaded_pages() {
+ let capability = capability();
+ // A `remote` entry is the only way a Tauri capability reaches a page loaded
+ // over http. The Workbench, and every Show Page inside it, is such a page.
+ assert!(
+ capability.get("remote").is_none(),
+ "the bootstrap capability must not name remote URLs"
+ );
+ assert_eq!(capability["local"], Value::Bool(true));
+}
+
+#[test]
+fn the_bootstrap_capability_is_scoped_to_the_shell_window() {
+ assert_eq!(
+ capability()["windows"],
+ serde_json::json!([MAIN_WINDOW]),
+ "the capability must name exactly the shell's own window"
+ );
+}
+
+#[test]
+fn the_bootstrap_capability_grants_only_the_three_shell_commands() {
+ let capability = capability();
+ let permissions: Vec<&str> = capability["permissions"]
+ .as_array()
+ .expect("permissions is a list")
+ .iter()
+ .map(|value| value.as_str().expect("permissions are strings"))
+ .collect();
+
+ assert_eq!(
+ permissions,
+ [
+ "core:event:default",
+ "allow-bootstrap-status",
+ "allow-bootstrap-retry",
+ "allow-open-install-docs",
+ ],
+ "widening this list widens what a WebView can ask the shell to do"
+ );
+}
+
+#[test]
+fn the_shell_enables_no_capability_beyond_bootstrap() {
+ assert_eq!(
+ config()["app"]["security"]["capabilities"],
+ serde_json::json!(["bootstrap"])
+ );
+}
+
+#[test]
+fn notifications_are_native_only_without_remote_capabilities_or_workbench_callable_commands() {
+ let source = shipping_source("src/lib.rs");
+ let native = shipping_source("src/notifications.rs");
+ let build = shipping_source("build.rs");
+ assert!(source.contains(".plugin(tauri_plugin_notification::init())"));
+ assert!(native.contains("NotificationExt"));
+ assert!(native.contains(".notification()"));
+ assert!(native.contains("sink.gate().allows()"));
+ assert!(!build.contains("notification"));
+ let commands = source
+ .split(".invoke_handler(tauri::generate_handler![")
+ .nth(1)
+ .unwrap()
+ .split("])")
+ .next()
+ .unwrap();
+ assert!(!commands.contains("notification"));
+ for forbidden in ["#[tauri::command]", "invoke_handler", ".listen(", ".emit(", ".eval("] {
+ assert!(
+ !native.contains(forbidden),
+ "notification path must not use {forbidden}"
+ );
+ }
+ for entry in std::fs::read_dir(crate_dir().join("capabilities")).unwrap() {
+ let path = entry.unwrap().path();
+ if path.extension().is_some_and(|extension| extension == "json") {
+ let capability = read_json(path);
+ assert!(capability.get("remote").is_none());
+ assert!(!capability["permissions"].to_string().contains("notification:"));
+ }
+ }
+}
+
+#[test]
+fn notification_lifecycle_follows_runtime_ownership_not_webview_visibility_or_sse_health() {
+ let source = shipping_source("src/lib.rs");
+ for (function, next_function, required) in [
+ (
+ "fn start_runtime_monitor(",
+ "fn recover_after_readiness_loss",
+ "notifications::start(&app, origin.clone())",
+ ),
+ (
+ "fn start_runtime_monitor(",
+ "fn return_to_bootstrap",
+ "notifications::stop(&app)",
+ ),
+ (
+ "fn stop_runtime(",
+ "fn toggle_start_at_login",
+ "notifications::stop(&app)",
+ ),
+ (
+ "fn exit_shell(",
+ "fn request_runtime_lifecycle",
+ "notifications::stop(app)",
+ ),
+ (
+ "fn request_private_runtime_removal(",
+ "pub fn run()",
+ "notifications::stop(&confirmation_app)",
+ ),
+ ] {
+ let body = source
+ .split(function)
+ .nth(1)
+ .unwrap()
+ .split(next_function)
+ .next()
+ .unwrap();
+ assert!(body.contains(required), "{function} must retain {required}");
+ }
+ // The connection has exactly one opener, and it is the monitor a completed
+ // handoff created. `open_workbench` used to open it before attempting the
+ // navigation, which left it running on every failure exit from that loop —
+ // ownership the shell no longer had, which is the property this test is named
+ // for.
+ let workbench = source
+ .split("fn open_workbench(")
+ .nth(1)
+ .unwrap()
+ .split("fn workbench_navigation_failure_status")
+ .next()
+ .unwrap();
+ assert!(!workbench.contains("notifications::"));
+ assert_eq!(source.matches("notifications::start(").count(), 1);
+ let close = source
+ .split("event: WindowEvent::CloseRequested")
+ .nth(1)
+ .unwrap()
+ .split("if let RunEvent::ExitRequested")
+ .next()
+ .unwrap();
+ assert!(!close.contains("notifications::stop"));
+ let native = shipping_source("src/notifications.rs");
+ assert!(native.contains("previous.task.abort()"));
+ assert!(native.contains("current.origin == origin"));
+ assert!(native.contains("observed_generation"));
+ assert!(!native.contains("/ready") && !native.contains("bootstrap"));
+}
+
+#[test]
+fn deep_links_have_native_entry_points_without_a_workbench_callable_command() {
+ let source = shipping_source("src/lib.rs");
+ let build = shipping_source("build.rs");
+ for required in [
+ "tauri_plugin_deep_link::init()",
+ "receive_native_deep_link(app, argv.iter().skip(1))",
+ "builder.plugin(macos_deep_link::init())",
+ "std::env::args_os()",
+ "links.bootstrap_navigation(ready)",
+ "links.workbench_navigation(&origin, &current_url)",
+ "links.observe_bootstrap(&status)",
+ "PageLoadEvent::Finished",
+ ] {
+ assert!(source.contains(required), "native deep-link path is missing {required}");
+ }
+ assert!(!build.contains("deep_link") && !build.contains("window_state"));
+ assert!(!source.contains("on_open_url") && !source.contains(".eval("));
+ assert!(!source.contains("RunEvent::Opened"));
+ let receiver = source
+ .split("fn receive_native_deep_link(")
+ .nth(1)
+ .unwrap()
+ .split("fn apply_pending_deep_link")
+ .next()
+ .unwrap();
+ assert!(receiver.contains("focus_or_restore_main_window(app)"));
+ assert_eq!(
+ config()["plugins"]["deep-link"]["desktop"]["schemes"],
+ serde_json::json!(["avibe"])
+ );
+ assert_eq!(config()["identifier"], "bot.avibe.desktop");
+}
+
+#[test]
+fn macos_receives_original_event_text_before_any_url_parser_can_normalize_it() {
+ let native = shipping_source("src/macos_deep_link.rs");
+ for required in [
+ ".setup(|app, _|",
+ "install(move |raw| crate::receive_native_deep_link(&app, [raw]))",
+ "paramDescriptorForKeyword: DIRECT_OBJECT",
+ "descriptor?.stringValue()",
+ "setEventHandler: &*handler",
+ "forEventClass: GET_URL_EVENT",
+ "andEventID: GET_URL_EVENT",
+ "RunEvent::Exit",
+ "removeEventHandlerForEventClass: GET_URL_EVENT",
+ ] {
+ assert!(native.contains(required), "raw native delivery must retain {required}");
+ }
+ for forbidden in [
+ "Url::",
+ "currentAppleEvent",
+ "invoke_handler",
+ "#[tauri::command]",
+ ".emit(",
+ ] {
+ assert!(!native.contains(forbidden), "raw delivery must not use {forbidden}");
+ }
+ let cargo = read_to_string(&crate_dir().join("Cargo.toml"));
+ let (_, macos_dependencies) = cargo
+ .split_once("[target.'cfg(target_os = \"macos\")'.dependencies]")
+ .unwrap();
+ assert!(macos_dependencies.contains("objc2 = \"0.6.4\""));
+ assert!(macos_dependencies.contains("objc2-foundation = { version = \"0.3.2\""));
+ assert!(!cargo.contains("objc2-core-services"));
+}
+
+#[test]
+fn native_link_consumption_uses_one_success_and_window_generation_commit_boundary() {
+ let source = shipping_source("src/lib.rs");
+ for line_ending in ["\n", "\r\n"] {
+ let source = source.lines().collect::<Vec<_>>().join(line_ending);
+ assert_native_link_consumption_boundary(&source);
+ }
+}
+
+fn assert_native_link_consumption_boundary(source: &str) {
+ let cold = source
+ .split("fn open_workbench(")
+ .nth(1)
+ .unwrap()
+ .split("fn workbench_navigation_failure_status")
+ .next()
+ .unwrap();
+ assert!(cold.find("let Some(window)").unwrap() < cold.find("links.bootstrap_navigation(ready)").unwrap());
+ assert!(
+ cold.find("window.navigate(navigation.url().clone())").unwrap()
+ < cold.find("commit_deep_link_navigation(").unwrap()
+ );
+ let (_, monitoring) = cold.split_once("WorkbenchHandoff::Monitor => {").unwrap();
+ assert!(monitoring.trim_start().starts_with("commit_deep_link_navigation("));
+ let hot = source
+ .split("fn apply_pending_deep_link(")
+ .nth(1)
+ .unwrap()
+ .split("fn commit_deep_link_navigation")
+ .next()
+ .unwrap();
+ assert!(hot.contains("let succeeded = window.navigate(navigation.url().clone()).is_ok()"));
+ assert!(hot.contains("commit_deep_link_navigation(app, &navigation, succeeded, observed_generation)"));
+ let commit = source
+ .split("fn commit_deep_link_navigation(")
+ .nth(1)
+ .unwrap()
+ .split("fn application_menu")
+ .next()
+ .unwrap();
+ assert!(commit.contains("links.commit_navigation("));
+ assert!(commit.contains("shell.window_generation.load(Ordering::SeqCst)"));
+ assert!(!commit.contains(".navigate("));
+}
+
+#[test]
+fn window_frames_are_restored_before_show_without_document_or_remote_authority() {
+ let source = shipping_source("src/lib.rs");
+ let native_frame = shipping_source("src/native_frame.rs");
+ let window = &config()["app"]["windows"][0];
+ assert_eq!(window["visible"], false);
+ assert_eq!(window["width"], 1200);
+ assert_eq!(window["height"], 800);
+ assert_eq!(window["minWidth"], 880);
+ assert_eq!(window["minHeight"], 600);
+ assert_eq!(window["center"], true);
+ assert!(
+ source.find("tauri_plugin_window_state::Builder::new()").unwrap()
+ < source.find("native_frame::init()").unwrap()
+ );
+ assert!(source.contains(".with_filter(|label| label == MAIN_WINDOW)"));
+ assert!(source.contains(".with_state_flags(native_frame::state_flags())"));
+ assert!(native_frame.contains("StateFlags::POSITION | StateFlags::SIZE | StateFlags::MAXIMIZED"));
+ assert_eq!(native_frame.matches("StateFlags::").count(), 3);
+ assert!(native_frame.contains(".on_window_ready("));
+ assert!(native_frame.find("clamp(&window)").unwrap() < native_frame.find("window.show()").unwrap());
+ assert!(native_frame.contains("tokio::time::sleep("));
+ assert!(native_frame.contains("save_app.save_window_state(state_flags())"));
+ assert!(!native_frame.contains("#[tauri::command]") && !native_frame.contains("invoke_handler"));
+ assert!(!native_frame.contains("on_page_load") && !native_frame.contains("std::fs"));
+ let handoff = source
+ .split("fn open_workbench(")
+ .nth(1)
+ .unwrap()
+ .split("fn workbench_navigation_failure_status")
+ .next()
+ .unwrap();
+ for mutation in ["set_size", "set_position", ".center(", "restore_state"] {
+ assert!(
+ !handoff.contains(mutation),
+ "content handoff must not alter the restored frame"
+ );
+ }
+}
+
+#[test]
+fn product_bundles_have_an_explicit_private_runtime_gate() {
+ let cargo = read_to_string(&crate_dir().join("Cargo.toml"));
+ let source = shipping_source("src/lib.rs");
+ assert!(
+ cargo.contains("bundled-runtime = []"),
+ "consumer packaging must select the private Runtime explicitly"
+ );
+ for required in [
+ "#[cfg(feature = \"bundled-runtime\")]",
+ "bundled_runtime_host(",
+ "app.path().resource_dir()?.join(\"runtime\")",
+ "app.path().app_local_data_dir()?.join(\"runtime\")",
+ ] {
+ assert!(
+ source.contains(required),
+ "the product package must install its own Runtime, missing {required:?}"
+ );
+ }
+ assert_eq!(
+ config()["bundle"]["resources"]["resources/runtime/"],
+ Value::String("runtime/".to_owned())
+ );
+}
+
+#[test]
+fn every_shell_command_is_declared_so_its_permission_exists() {
+ // Application commands are ungated in Tauri v2 unless declared here; an
+ // undeclared command has no `allow-*` permission and so no capability can
+ // scope it.
+ let build_rs = shipping_source("build.rs");
+ let lib_rs = shipping_source("src/lib.rs");
+
+ let declared: Vec<&str> = ["bootstrap_status", "bootstrap_retry", "open_install_docs"]
+ .into_iter()
+ .filter(|command| build_rs.contains(command))
+ .collect();
+ assert_eq!(declared, ["bootstrap_status", "bootstrap_retry", "open_install_docs"]);
+
+ let defined = lib_rs.matches("#[tauri::command]").count();
+ assert_eq!(
+ defined,
+ declared.len(),
+ "every #[tauri::command] must be declared in build.rs and allowed by a capability"
+ );
+}
+
+#[test]
+fn installation_help_is_a_fixed_bootstrap_only_destination() {
+ let source = shipping_source("src/lib.rs");
+ assert!(
+ source.contains("https://docs.avibe.bot/get-started/install"),
+ "the install action must use the product installation guide"
+ );
+ assert!(
+ source.contains("fn open_install_docs(window: WebviewWindow)"),
+ "the command must accept no URL or protocol argument from the WebView"
+ );
+}
+
+#[test]
+fn the_window_label_is_consistent_across_config_and_code() {
+ let config = config();
+ let windows = config["app"]["windows"].as_array().expect("windows is a list");
+ assert_eq!(windows.len(), 1, "the shell owns exactly one window");
+ assert_eq!(windows[0]["label"], MAIN_WINDOW);
+ assert!(
+ shipping_source("src/lib.rs").contains(&format!("MAIN_WINDOW: &str = {MAIN_WINDOW:?}")),
+ "the window label in tauri.conf.json and lib.rs must agree"
+ );
+}
+
+#[test]
+fn the_dev_server_url_matches_the_port_the_host_trusts() {
+ let expected = format!("http://localhost:{}", avibe_runtime_host::DEV_SERVER_PORT);
+ assert_eq!(config()["build"]["devUrl"], Value::String(expected));
+}
+
+#[test]
+fn normal_shell_lifecycle_has_no_raw_process_termination_path() {
+ for file in ["src/lib.rs", "src/main.rs"] {
+ let source = shipping_source(file);
+ for forbidden in [".kill(", "libc::kill", "taskkill", "SIGTERM", "SIGKILL"] {
+ assert!(
+ !source.contains(forbidden),
+ "{file} must not bypass the Runtime's graceful lifecycle, found {forbidden:?}"
+ );
+ }
+ }
+}
+
+#[test]
+fn product_packages_expose_an_explicit_private_runtime_uninstall_path() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "UNINSTALL_MENU_ID",
+ "fn request_private_runtime_removal",
+ "host.remove_private_runtime(active_origin.as_ref()).await",
+ "native_uninstall_catalog()",
+ "sys_locale::get_locales()",
+ "../../../ui/src/i18n/en.json",
+ "../../../ui/src/i18n/zh.json",
+ ] {
+ assert!(
+ source.contains(required),
+ "the desktop uninstall path must retain {required:?}"
+ );
+ }
+ for locale in ["en", "zh"] {
+ let catalog = read_json(
+ crate_dir()
+ .join("..")
+ .join("..")
+ .join("ui")
+ .join("src")
+ .join("i18n")
+ .join(format!("{locale}.json")),
+ );
+ assert!(
+ catalog["desktopBootstrap"]["uninstall"]["confirmMessage"]
+ .as_str()
+ .is_some_and(|message| message.contains("~/.avibe")),
+ "{locale} uninstall copy must promise to preserve user state"
+ );
+ }
+}
+
+#[test]
+fn post_navigation_recovery_stays_in_the_unprivileged_rust_shell() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "host.is_ready(&origin).await",
+ "release_after_readiness_loss",
+ "return_to_bootstrap(&app)",
+ "spawn_owned_bootstrap(app)",
+ ] {
+ assert!(
+ source.contains(required),
+ "the post-navigation recovery path must retain {required:?}"
+ );
+ }
+ assert!(
+ source.contains("compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR")
+ && source.contains("compare_exchange(ACTIVITY_MONITOR, ACTIVITY_BOOTSTRAP"),
+ "bootstrap and monitoring must exchange one exclusive shell activity"
+ );
+}
+
+#[test]
+fn macos_reopen_recreates_or_refocuses_the_main_window() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "fn ensure_main_window",
+ "fn focus_or_restore_main_window",
+ "RunEvent::Reopen",
+ "claim_recreated_window_bootstrap(&activity)",
+ "spawn_owned_bootstrap(app.clone())",
+ "WebviewWindowBuilder::from_config",
+ ] {
+ assert!(
+ source.contains(required),
+ "the shell must keep a path to recreate or refocus the main window, missing {required:?}"
+ );
+ }
+}
+
+#[test]
+fn recreated_windows_transfer_monitor_ownership_before_bootstrapping() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "compare_exchange(current, ACTIVITY_BOOTSTRAP",
+ "activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR",
+ "claim_recreated_window_bootstrap(&activity)",
+ ] {
+ assert!(
+ source.contains(required),
+ "window recreation must retire a stale monitor before bootstrapping, missing {required:?}"
+ );
+ }
+ let awaited_probe = source
+ .find("let ready = host.is_ready(&origin).await;")
+ .expect("the monitor awaits readiness");
+ let ownership_recheck = source[awaited_probe..]
+ .find("activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR")
+ .map(|offset| awaited_probe + offset)
+ .expect("the monitor rechecks ownership after readiness");
+ let state_mutation = source[ownership_recheck..]
+ .find("if readiness_loss.begin_recovery(ready,")
+ .map(|offset| ownership_recheck + offset)
+ .expect("the monitor mutates state only after the ownership recheck");
+ assert!(
+ awaited_probe < ownership_recheck && ownership_recheck < state_mutation,
+ "the superseded monitor must retire after its await before mutating recovery state"
+ );
+ for required in [
+ "window_generation.fetch_add(1, Ordering::SeqCst)",
+ "complete_workbench_handoff(&activity, &window_generation, observed_generation)",
+ "WorkbenchHandoff::RetryCurrentWindow => continue",
+ ] {
+ assert!(
+ source.contains(required),
+ "window recreation during the bootstrap handoff must retain {required:?}"
+ );
+ }
+}
+
+#[test]
+fn every_navigation_stays_on_the_shell_or_the_proved_runtime_listener() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ ".on_navigation(|webview, url|",
+ "fn navigation_is_allowed",
+ "origin.matches_url_origin(url)",
+ "active_origin",
+ "set_active_origin(app, Some(origin.clone()))",
+ "is_runtime_rebind_target(url)",
+ "rediscover_after_runtime_rebind(webview.app_handle().clone(), origin)",
+ ] {
+ assert!(
+ source.contains(required),
+ "native navigation confinement is missing {required:?}"
+ );
+ }
+}
+
+#[test]
+fn every_main_window_sends_new_browsing_contexts_to_the_system_browser() {
+ // Built only by the shell, never implicitly from config, so no instance of
+ // the window can exist without the handler.
+ assert_eq!(
+ config()["app"]["windows"][0]["create"],
+ Value::Bool(false),
+ "the main window must be built by ensure_main_window, not auto-created"
+ );
+ let source = shipping_source("src/lib.rs");
+ let builder = source
+ .split("fn ensure_main_window(")
+ .nth(1)
+ .expect("main window builder")
+ .split("\n}\n")
+ .next()
+ .expect("builder body");
+ assert!(
+ builder.contains(".on_new_window(|url, _features| handle_new_window_request(url))"),
+ "the main window must register the new-window handler"
+ );
+ let setup = &source[source.find(".setup(|app|").expect("shell setup")..];
+ assert!(setup.contains("ensure_main_window(app.handle())"));
+ let handler = source
+ .split("fn handle_new_window_request(")
+ .nth(1)
+ .expect("new-window handler")
+ .split("\n}\n")
+ .next()
+ .expect("handler body");
+ assert!(handler.contains("new_window_decision(&url)"));
+ assert!(handler.contains("tauri_plugin_opener::open_url(url.as_str(), None::<&str>)"));
+ for forbidden in ["NewWindowResponse::Allow", "NewWindowResponse::Create"] {
+ assert!(
+ !source.contains(forbidden),
+ "the page must never get a second webview, found {forbidden:?}"
+ );
+ }
+}
+
+#[test]
+fn the_workbench_learns_it_runs_in_the_shell_from_one_top_level_marker() {
+ let source = shipping_source("src/lib.rs");
+ let builder = source
+ .split("fn ensure_main_window(")
+ .nth(1)
+ .expect("main window builder")
+ .split("\n}\n")
+ .next()
+ .expect("builder body");
+ assert!(
+ builder.contains(".initialization_script(DESKTOP_SHELL_MARKER)"),
+ "every main window must define the marker before Workbench scripts run"
+ );
+ assert!(!source.contains("initialization_script_for_all_frames"));
+ let marker = source
+ .split("const DESKTOP_SHELL_MARKER: &str =")
+ .nth(1)
+ .expect("marker script")
+ .split("\";\n")
+ .next()
+ .expect("marker literal");
+ // Show Page content runs in subframes, and WebView2 injects there regardless.
+ assert!(marker.contains("if (window.self === window.top)"));
+ assert!(marker.contains("Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true })"));
+ let reader = read_to_string(&crate_dir().join("../../ui/src/lib/desktopShell.ts"));
+ assert!(
+ reader.contains("window.__AVIBE_DESKTOP_SHELL__ === true"),
+ "the Workbench must read the same marker the shell defines"
+ );
+}
+
+#[test]
+fn native_navigation_failures_return_to_a_retryable_bootstrap_state() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "window.navigate(navigation.url().clone()).is_err()",
+ "workbench_navigation_failure_status(ready, &origin)",
+ "BootstrapNoticeCode::WorkbenchNavigationFailed",
+ ] {
+ assert!(
+ source.contains(required),
+ "native navigation failures must remain recoverable, missing {required:?}"
+ );
+ }
+}
+
+#[test]
+fn a_dropped_retry_is_reported_to_the_bootstrap_page() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "fn bootstrap_retry(window: WebviewWindow, app: AppHandle) -> Result<bool, String>",
+ "Ok(spawn_bootstrap(app))",
+ "fn spawn_bootstrap(app: AppHandle) -> bool",
+ "return false",
+ ] {
+ assert!(
+ source.contains(required),
+ "a retry command must report whether it acquired bootstrap ownership, missing {required:?}"
+ );
+ }
+
+ let frontend = shipping_source("../src/main.ts");
+ for required in [
+ "invoke<boolean>('bootstrap_retry')",
+ "if (!scheduled)",
+ "retryEl.disabled = false",
+ ] {
+ assert!(
+ frontend.contains(required),
+ "the bootstrap page must preserve a retry the shell did not schedule, missing {required:?}"
+ );
+ }
+ assert!(
+ !frontend.contains("retryEl.hidden = scheduled"),
+ "the invoke response must not overwrite a newer terminal status event"
+ );
+}
+
+#[test]
+fn native_lifecycle_controls_never_add_a_webview_permission() {
+ let source = shipping_source("src/lib.rs");
+ for required in [
+ "TrayIconBuilder::with_id(TRAY_ID)",
+ "tauri_plugin_autostart::Builder::new().build()",
+ "host.stop_owned_runtime().await",
+ "api.prevent_close()",
+ "window.hide()",
+ "api.prevent_exit()",
+ "request_runtime_lifecycle(app.clone(), true)",
+ "fn exit_shell",
+ ] {
+ assert!(source.contains(required), "native lifecycle wiring missing {required}");
+ }
+ assert_eq!(source.matches("#[tauri::command]").count(), 3);
+ for permission in capability()["permissions"].as_array().expect("capability permissions") {
+ let permission = permission.as_str().expect("string permission");
+ assert!(!permission.contains("autostart") && !permission.contains("tray") && !permission.contains("dialog"));
+ }
+ let setup = &source[source.find(".setup(|app|").expect("shell setup")..];
+ assert!(
+ !setup.contains(".enable()"),
+ "login registration is never a startup side effect"
+ );
+}
+
+#[test]
+fn native_lifecycle_authority_requires_a_receipt_not_a_launch_attempt() {
+ let source = shipping_source("src/lib.rs");
+ assert!(source.contains("shell.host.has_owned_runtime()"));
+ assert!(!source.contains("host.has_launched()"));
+ let stop = source
+ .split("fn stop_runtime(")
+ .nth(1)
+ .expect("native stop")
+ .split("fn toggle_start_at_login")
+ .next()
+ .expect("stop body");
+ let refusal = stop
+ .split("Err(LaunchError::OwnershipLost | LaunchError::NotOwned)")
+ .nth(1)
+ .expect("receipt refusal")
+ .split("Err(_)")
+ .next()
+ .expect("refusal handling");
+ assert!(refusal.contains("BootstrapNoticeCode::RuntimeOwnershipLost"));
+ assert!(refusal.contains("ACTIVITY_IDLE"));
+ assert!(refusal.contains("focus_or_restore_main_window(&app)"));
+ assert!(!refusal.contains("start_runtime_monitor("));
+ assert!(!stop.contains("spawn_bootstrap("));
+}
+
+#[test]
+fn native_tray_copy_has_locale_and_placeholder_parity() {
+ let root = crate_dir().join("../../ui/src/i18n");
+ let english = read_json(root.join("en.json"));
+ let chinese = read_json(root.join("zh.json"));
+ let english = english["desktopBootstrap"]["tray"]
+ .as_object()
+ .expect("English tray catalog");
+ let chinese = chinese["desktopBootstrap"]["tray"]
+ .as_object()
+ .expect("Chinese tray catalog");
+ assert_eq!(english.keys().collect::<Vec<_>>(), chinese.keys().collect::<Vec<_>>());
+ for (key, value) in english {
+ let source = value.as_str().expect("English string");
+ let translated = chinese[key].as_str().expect("Chinese string");
+ assert!(!source.is_empty() && !translated.is_empty());
+ let placeholders = |text: &str| -> Vec<String> {
+ text.split("{{")
+ .skip(1)
+ .map(|part| part.split("}}").next().expect("placeholder").to_owned())
+ .collect()
+ };
+ assert_eq!(
+ placeholders(source),
+ placeholders(translated),
+ "placeholder parity for {key}"
+ );
+ }
+}
+
+#[test]
+fn settings_open_through_the_deep_link_path_only_while_a_workbench_is_shown() {
+ let source = shipping_source("src/lib.rs");
+ let body = |name: &str| -> String {
+ source
+ .split(&format!("fn {name}("))
+ .nth(1)
+ .unwrap_or_else(|| panic!("{name} exists"))
+ .split("\n}\n")
+ .next()
+ .expect("function body")
+ .to_owned()
+ };
+ // One item, created disabled, in both native menus.
+ assert!(
+ source.contains("MenuItem::with_id(app, SETTINGS_MENU_ID, &catalog.settings, false, Some(\"CmdOrCtrl+,\"))")
+ );
+ let tray = body("install_native_tray");
+ assert!(tray.contains("&settings,\n &login,"));
+ assert!(
+ tray.contains("submenu.insert_items(&[&settings, &PredefinedMenuItem::separator(app)?], settings_position)")
+ );
+ assert!(source.contains("SETTINGS_MENU_ID => open_workbench_settings(app),"));
+ // The item's enabled state and the handler share one rule, read live.
+ assert!(body("refresh_runtime_tray").contains("refresh_native_controls(app, Some(state));"));
+ let refresh = body("refresh_native_controls");
+ assert!(refresh.contains("let activity = shell.activity.load(Ordering::SeqCst);"));
+ assert!(refresh.contains("let settings = settings_is_available(activity, workbench_origin);"));
+ assert!(refresh.contains("menus.settings.set_enabled(settings)?;"));
+ // The item is created disabled, so it must be re-evaluated the moment a
+ // Workbench finishes loading rather than at the monitor's first tick.
+ let page_load = source
+ .split(".on_page_load(|webview, payload| {")
+ .nth(1)
+ .expect("the shell observes main-window page loads")
+ .split(".on_navigation(")
+ .next()
+ .expect("page-load hook body");
+ assert!(page_load
+ .contains("webview.label() == MAIN_WINDOW && payload.event() == tauri::webview::PageLoadEvent::Finished"));
+ assert!(
+ page_load.contains("refresh_native_controls(webview.app_handle(), None);"),
+ "a finished Workbench load must refresh the native controls"
+ );
+ let handler = body("open_workbench_settings");
+ let gate = handler
+ .find("if !settings_is_available(")
+ .expect("the handler refuses without a Workbench");
+ let delivery = handler
+ .find("receive_native_deep_link(app, [SETTINGS_DEEP_LINK]);")
+ .expect("Settings is delivered as a deep link");
+ assert!(gate < delivery, "the handler must refuse before delivering");
+ assert!(!handler.contains(".navigate("), "the deep-link path owns navigation");
+ assert!(source.contains("const SETTINGS_DEEP_LINK: &str = \"avibe://settings\";"));
+}
+
+#[test]
+fn start_at_login_is_restored_through_the_toggle_write_policy() {
+ let source = shipping_source("src/lib.rs");
+ let body = |name: &str| -> String {
+ source
+ .split(&format!("fn {name}("))
+ .nth(1)
+ .unwrap_or_else(|| panic!("{name} exists"))
+ .split("\n}\n")
+ .next()
+ .expect("function body")
+ .to_owned()
+ };
+ // The menu toggle and the uninstall's restore reach one adapter, which
+ // hands the write, the read-back, the checkbox and the failure message to
+ // the policy the unit tests exercise.
+ assert!(body("toggle_start_at_login").contains("set_start_at_login(app, requested);"));
+ assert!(body("request_private_runtime_removal").contains("|| set_start_at_login(&restore_app, Ok(true)),"));
+ let adapter = body("set_start_at_login");
+ for required in [
+ "settle_start_at_login(",
+ "manager.enable()",
+ "manager.is_enabled()",
+ "menus.login.set_checked(checked)",
+ ".message(catalog.login_failure)",
+ ] {
+ assert!(
+ adapter.contains(required),
+ "the Start at Login adapter must keep {required:?}"
+ );
+ }
+ // The policy takes its write as `FnOnce` and the adapter runs it once, so a
+ // failure is reported, never retried. Nothing else enables the registration
+ // or draws its checkbox, so no caller can discard a write's result again.
+ assert_eq!(source.matches("settle_start_at_login(").count(), 2);
+ assert_eq!(source.matches(".enable()").count(), 1);
+ assert_eq!(source.matches("login.set_checked(").count(), 1);
+}
+
+#[test]
+fn explicit_stop_does_not_schedule_automatic_recovery() {
+ let source = shipping_source("src/lib.rs");
+ let stop = source
+ .split("fn stop_runtime(")
+ .nth(1)
+ .expect("native stop")
+ .split("fn toggle_start_at_login")
+ .next()
+ .expect("stop body");
+ assert!(stop.contains("BootstrapNoticeCode::RuntimeStopped"));
+ assert!(!stop.contains("spawn_bootstrap("));
+ assert!(!stop.contains("spawn_owned_bootstrap("));
+ let monitor = source
+ .split("fn start_runtime_monitor(")
+ .nth(1)
+ .expect("monitor")
+ .split("fn return_to_bootstrap")
+ .next()
+ .expect("monitor body");
+ assert!(
+ !monitor.contains("get_webview_window"),
+ "status monitoring survives window closure"
+ );
+ assert!(monitor.contains("generation.load(Ordering::SeqCst) != observed_generation"));
+}
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
new file mode 100644
index 000000000..164a5fa40
--- /dev/null
+++ b/desktop/src/main.ts
@@ -0,0 +1,205 @@
+import { invoke } from '@tauri-apps/api/core'
+import { listen } from '@tauri-apps/api/event'
+
+import './styles.css'
+
+/**
+ * The frozen desktop bootstrap contract.
+ *
+ * Mirrors `BootstrapStatus` in `runtime-host/src/status.rs`. The Rust side owns
+ * every value here — this page renders it and never decides anything itself,
+ * least of all when to navigate.
+ */
+type BootstrapPhase = 'probing' | 'starting' | 'ready' | 'failed'
+type NoticeCode =
+ | 'probing'
+ | 'adopted'
+ | 'starting'
+ | 'ready'
+ | 'invalid_origin'
+ | 'runtime_not_found'
+ | 'runtime_install_failed'
+ | 'runtime_discovery_failed'
+ | 'runtime_spawn_failed'
+ | 'runtime_stopped'
+ | 'runtime_ownership_lost'
+ | 'launcher_exited'
+ | 'ready_timeout'
+ | 'workbench_navigation_failed'
+
+interface BootstrapNotice {
+ code: string
+ seconds?: number
+}
+
+interface BootstrapStatus {
+ phase: BootstrapPhase
+ origin: string
+ attempt: number
+ notice: BootstrapNotice
+ retryable: boolean
+}
+
+interface BootstrapCatalog {
+ retry: string
+ installationHelp: string
+ notRunningTitle: string
+ shellUnavailable: string
+ genericFailure: string
+ notices: Record<NoticeCode, string>
+}
+
+declare const __DESKTOP_BOOTSTRAP_CATALOGS__: Record<'en' | 'zh', BootstrapCatalog>
+
+const STATUS_EVENT = 'bootstrap-status'
+const NOTICE_CODES: ReadonlySet<string> = new Set<NoticeCode>([
+ 'probing',
+ 'adopted',
+ 'starting',
+ 'ready',
+ 'invalid_origin',
+ 'runtime_not_found',
+ 'runtime_install_failed',
+ 'runtime_discovery_failed',
+ 'runtime_spawn_failed',
+ 'runtime_stopped',
+ 'runtime_ownership_lost',
+ 'launcher_exited',
+ 'ready_timeout',
+ 'workbench_navigation_failed',
+])
+
+const root = document.documentElement
+const messageEl = requireElement('message')
+const originEl = requireElement('origin')
+const trackEl = requireElement('track')
+const actionsEl = requireElement('actions')
+const retryEl = requireElement<HTMLButtonElement>('retry')
+const helpEl = requireElement<HTMLButtonElement>('help')
+const locale = selectLocale(navigator.languages)
+const catalog = __DESKTOP_BOOTSTRAP_CATALOGS__[locale]
+
+root.lang = locale
+messageEl.textContent = catalog.notices.probing
+retryEl.textContent = catalog.retry
+helpEl.textContent = catalog.installationHelp
+
+function requireElement<T extends HTMLElement = HTMLElement>(id: string): T {
+ const element = document.getElementById(id)
+ if (!element) {
+ throw new Error(`bootstrap markup is missing #${id}`)
+ }
+ return element as T
+}
+
+function render(status: BootstrapStatus): void {
+ root.dataset.phase = status.phase
+ messageEl.textContent = localizeNotice(status.notice)
+ originEl.textContent = status.origin
+
+ // The Runtime is either coming up or it is not; a determinate bar would be a
+ // lie, and a bar after failure would suggest work is still happening.
+ trackEl.hidden = status.phase === 'failed'
+
+ const showRetry = status.phase === 'failed' && status.retryable
+ const showHelp = status.phase === 'failed' && showInstallHelp(status.notice)
+ retryEl.disabled = false
+ retryEl.hidden = !showRetry
+ helpEl.hidden = !showHelp
+ actionsEl.hidden = !showRetry && !showHelp
+ document.title = status.phase === 'failed' ? catalog.notRunningTitle : 'Avibe'
+}
+
+function selectLocale(languages: readonly string[]): 'en' | 'zh' {
+ for (const language of languages) {
+ const normalized = language.toLowerCase()
+ if (normalized.startsWith('zh')) {
+ return 'zh'
+ }
+ if (normalized.startsWith('en')) {
+ return 'en'
+ }
+ }
+ return 'en'
+}
+
+function localizeNotice(notice: BootstrapNotice): string {
+ if (!NOTICE_CODES.has(notice.code)) {
+ return catalog.genericFailure
+ }
+ const code = notice.code as NoticeCode
+ const template = catalog.notices[code]
+ if (code !== 'ready_timeout') {
+ return template
+ }
+ if (!Number.isSafeInteger(notice.seconds) || (notice.seconds ?? -1) < 0) {
+ return catalog.genericFailure
+ }
+ return template.replace('{{seconds}}', String(notice.seconds))
+}
+
+function showInstallHelp(notice: BootstrapNotice): boolean {
+ return (
+ notice.code === 'runtime_not_found' ||
+ notice.code === 'runtime_discovery_failed' ||
+ notice.code === 'launcher_exited'
+ )
+}
+
+retryEl.addEventListener('click', () => {
+ // Disable synchronously so a double click cannot queue two runs. The native
+ // command reports whether it acquired bootstrap ownership; a rejected retry
+ // stays visible instead of waiting forever for an event that will not arrive.
+ retryEl.disabled = true
+ void invoke<boolean>('bootstrap_retry')
+ .then((scheduled) => {
+ // Once scheduled, status events own both visibility and enabled state.
+ // A fast terminal event may already have rendered Retry again before this
+ // promise resolves, so the response must not overwrite that newer state.
+ if (!scheduled) {
+ retryEl.disabled = false
+ }
+ })
+ .catch((error: unknown) => {
+ retryEl.disabled = false
+ reportUnavailable(error)
+ })
+})
+
+helpEl.addEventListener('click', () => {
+ void invoke('open_install_docs').catch((error: unknown) => {
+ console.error('installation docs could not be opened', error)
+ })
+})
+
+async function start(): Promise<void> {
+ let sawEvent = false
+ // Subscribe before asking for the current value, so a status published while
+ // this page was still loading cannot be missed.
+ await listen<BootstrapStatus>(STATUS_EVENT, (event) => {
+ sawEvent = true
+ render(event.payload)
+ })
+
+ const current = await invoke<BootstrapStatus | null>('bootstrap_status')
+ // If a newer event arrived before the snapshot resolved, keep that newer
+ // state. The snapshot exists only to populate a page that loaded mid-run.
+ if (current && !sawEvent) {
+ render(current)
+ }
+}
+
+/**
+ * The shell is the only thing that can answer these calls. If it cannot, the
+ * page says so plainly instead of sitting on a spinner forever.
+ */
+function reportUnavailable(error: unknown): void {
+ console.error('bootstrap command failed', error)
+ root.dataset.phase = 'failed'
+ messageEl.textContent = catalog.shellUnavailable
+ trackEl.hidden = true
+ actionsEl.hidden = true
+ document.title = catalog.notRunningTitle
+}
+
+void start().catch(reportUnavailable)
diff --git a/desktop/src/styles.css b/desktop/src/styles.css
new file mode 100644
index 000000000..18f86cb27
--- /dev/null
+++ b/desktop/src/styles.css
@@ -0,0 +1,249 @@
+/*
+ * Bootstrap window styling.
+ *
+ * The tokens below are the Avibe Web UI tokens from `ui/src/index.css`, copied
+ * rather than imported: this page must render before anything is fetched over
+ * the network, and it is the one surface a user sees when the Runtime is down.
+ * Dark is the product default; light follows the OS.
+ */
+
+:root {
+ color-scheme: dark;
+
+ --background: #080812;
+ --foreground: #f5f1e8;
+ --card: #11111c;
+ --muted: #9ba3b8;
+ --primary: #5bffa0;
+ --primary-foreground: #080812;
+ --border: rgba(255, 255, 255, 0.08);
+ --ring: rgba(91, 255, 160, 0.6);
+ --track: rgba(255, 255, 255, 0.06);
+ --shadow-card: 0 32px 64px -12px rgba(91, 255, 160, 0.078);
+
+ --font-sans: Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
+ --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace;
+
+ --radius: 8px;
+}
+
+@media (prefers-color-scheme: light) {
+ :root {
+ color-scheme: light;
+
+ --background: #f4f6fb;
+ --foreground: #0a0a14;
+ --card: #ffffff;
+ --muted: #5c6079;
+ --primary: #10b981;
+ --primary-foreground: #ffffff;
+ --border: rgba(8, 8, 18, 0.08);
+ --ring: rgba(16, 185, 129, 0.5);
+ --track: rgba(8, 8, 18, 0.06);
+ --shadow-card: 0 24px 48px -12px rgba(8, 8, 18, 0.1);
+ }
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ height: 100%;
+}
+
+body {
+ margin: 0;
+ display: flex;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: var(--font-sans);
+ font-size: 14px;
+ line-height: 1.5;
+ -webkit-font-smoothing: antialiased;
+ /* Nothing on this page is selectable content; it is chrome. */
+ -webkit-user-select: none;
+ user-select: none;
+ cursor: default;
+}
+
+.stage {
+ flex: 1;
+ display: grid;
+ place-items: center;
+ padding: 32px;
+}
+
+.card {
+ width: min(420px, 100%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 16px;
+ padding: 40px 32px 32px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--card);
+ box-shadow: var(--shadow-card);
+ text-align: center;
+}
+
+/* The product mark, shown as shipped: the icon carries its own corners and
+ * background, so nothing here restyles it. */
+.mark {
+ display: block;
+ width: 56px;
+ height: 56px;
+}
+
+/* --- Copy ---------------------------------------------------------------- */
+
+.title {
+ margin: 0;
+ font-size: 20px;
+ font-weight: 600;
+}
+
+.message {
+ margin: 0;
+ min-height: 42px;
+ max-width: 32ch;
+ color: var(--muted);
+}
+
+[data-phase='failed'] .message {
+ color: var(--foreground);
+}
+
+.origin {
+ margin: 0;
+ min-height: 18px;
+}
+
+.origin code {
+ font-family: var(--font-mono);
+ font-size: 12px;
+ color: var(--muted);
+ -webkit-user-select: text;
+ user-select: text;
+}
+
+/* --- Progress ------------------------------------------------------------ */
+
+.track {
+ width: 100%;
+ height: 3px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: var(--track);
+}
+
+.track[hidden] {
+ display: none;
+}
+
+.bar {
+ display: block;
+ width: 40%;
+ height: 100%;
+ border-radius: inherit;
+ background: var(--primary);
+ animation: slide 1.6s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+}
+
+@keyframes slide {
+ 0% {
+ transform: translateX(-100%);
+ }
+ 100% {
+ transform: translateX(250%);
+ }
+}
+
+[data-phase='ready'] .bar {
+ width: 100%;
+ animation: none;
+ transform: none;
+}
+
+/* --- Actions ------------------------------------------------------------- */
+
+.actions {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ min-height: 38px;
+}
+
+.actions[hidden] {
+ display: none;
+}
+
+.retry,
+.help {
+ appearance: none;
+ margin-top: 4px;
+ padding: 0 20px;
+ height: 38px;
+ border-radius: var(--radius);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ transition:
+ filter 120ms ease,
+ transform 120ms ease;
+}
+
+.retry {
+ border: 0;
+ background: var(--primary);
+ color: var(--primary-foreground);
+}
+
+.help {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--foreground);
+}
+
+.retry:hover,
+.help:hover {
+ filter: brightness(1.08);
+}
+
+.retry:active,
+.help:active {
+ transform: translateY(1px);
+}
+
+.retry:focus-visible,
+.help:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+}
+
+.retry[hidden] {
+ display: none;
+}
+
+@media (max-width: 420px) {
+ .actions {
+ width: 100%;
+ flex-direction: column;
+ }
+
+ .retry,
+ .help {
+ width: 100%;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .bar {
+ width: 100%;
+ animation: none;
+ transform: none;
+ }
+}
diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json
new file mode 100644
index 000000000..1c647579b
--- /dev/null
+++ b/desktop/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "types": ["vite/client"],
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedIndexedAccess": true,
+ "isolatedModules": true,
+ "verbatimModuleSyntax": true,
+ "skipLibCheck": true,
+ "noEmit": true
+ },
+ "include": ["src", "vite.config.ts"]
+}
diff --git a/desktop/vite.config.ts b/desktop/vite.config.ts
new file mode 100644
index 000000000..cb40caabf
--- /dev/null
+++ b/desktop/vite.config.ts
@@ -0,0 +1,35 @@
+import { defineConfig } from 'vite'
+
+import en from '../ui/src/i18n/en.json'
+import zh from '../ui/src/i18n/zh.json'
+
+// The dev server port is part of the shell's trust boundary: `is_shell_ui_url`
+// in `runtime-host` accepts `http://localhost:1420` as the shell's own page, and
+// only in debug builds. Keep this in sync with `DEV_SERVER_PORT` and with
+// `build.devUrl` in `src-tauri/tauri.conf.json`.
+const DEV_SERVER_PORT = 1420
+
+export default defineConfig({
+ // The bootstrap must render while the Runtime is down. Inject only its small
+ // section from the central catalogs instead of bundling the whole Workbench
+ // translation payload or fetching it from loopback.
+ define: {
+ __DESKTOP_BOOTSTRAP_CATALOGS__: JSON.stringify({
+ en: en.desktopBootstrap,
+ zh: zh.desktopBootstrap,
+ }),
+ },
+ // Tauri prints its own diagnostics; do not wipe them.
+ clearScreen: false,
+ server: {
+ host: '127.0.0.1',
+ port: DEV_SERVER_PORT,
+ strictPort: true,
+ },
+ build: {
+ // The bootstrap page only ever runs in the bundled WebView (WKWebView on
+ // macOS, WebView2 on Windows), so it does not need legacy output.
+ target: ['es2022', 'safari15', 'chrome110'],
+ emptyOutDir: true,
+ },
+})
diff --git a/docs/CLI.md b/docs/CLI.md
index 9daf90c34..1c19fefb1 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -5,6 +5,7 @@
```bash
vibe # Alias for vibe start
vibe start # Start Avibe if needed (opens web UI)
+vibe start --no-open-browser # Start/reuse Avibe without opening a browser
vibe status # Check service status
vibe restart # Restart all services (use --delay-seconds when agent-triggered)
vibe remote # Guided Avibe Cloud remote-access setup
@@ -52,15 +53,17 @@ vibe
### `vibe start`
-Start Avibe if needed. Opens the web UI in your browser.
+Start Avibe if needed. Opens the web UI in your browser unless you suppress it.
```bash
vibe start
+vibe start --no-open-browser
```
**Behavior:**
- Reuses the main service and Web UI if they are already running
- Opens the setup wizard at `http://127.0.0.1:5123`
+- With `--no-open-browser`, keeps the service/UI lifecycle the same but does not launch a system browser window
- **Preserves running processes** — Use `vibe restart` when you need an explicit restart
### `vibe stop`
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index bbda0c466..24d8bda83 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -5,6 +5,7 @@
```bash
vibe # vibe start 的别名
vibe start # 按需启动 Avibe(打开 Web UI)
+vibe start --no-open-browser # 启动/复用 Avibe,但不打开浏览器
vibe status # 查看服务状态
vibe remote # 引导式配置 Avibe Cloud 远程访问
vibe screenshot # 截取本机桌面截图
@@ -50,15 +51,17 @@ vibe
### `vibe start`
-按需启动 Avibe。会在浏览器中打开 Web UI。
+按需启动 Avibe。默认会在浏览器中打开 Web UI;也可以显式抑制。
```bash
vibe start
+vibe start --no-open-browser
```
**行为:**
- 如果主服务与 Web UI 已在运行,则复用现有进程
- 打开设置向导 `http://127.0.0.1:5123`
+- 使用 `--no-open-browser` 时,服务和 Web UI 的启动/复用逻辑不变,但不会额外拉起系统浏览器窗口
- **保留已运行的进程** — 需要明确重启时请使用 `vibe restart`
### `vibe stop`
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index a86b880a7..5519bd8e6 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -523,7 +523,7 @@ mode. Continue with `pagination.next_command`; inspect one record with its
| Command | Purpose |
| --- | --- |
| `vibe` | Alias for `vibe start` |
-| `vibe start` | Start the service and Web UI if needed; reuse already-running processes |
+| `vibe start` | Start the service and Web UI if needed; reuse already-running processes; `--no-open-browser` suppresses the browser launch |
| `vibe stop` | Stop the service and UI; also terminates OpenCode server |
| `vibe restart` | Stop then start again |
| `vibe status` | Print runtime status JSON |
@@ -552,8 +552,11 @@ vibe
```bash
vibe start
+vibe start --no-open-browser
```
+- `--no-open-browser` keeps the same start/reuse semantics but suppresses the browser launch. This is the supported contract for desktop shells that own their own WebView.
+
- starts the main service if it is not already running
- opens the Web UI
- preserves already-running service, Web UI, and OpenCode processes; use `vibe restart` for an explicit restart
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index f7c6b4a97..ee9115ea9 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -501,7 +501,7 @@ bind vr-a3x9k2
| 命令 | 作用 |
| --- | --- |
| `vibe` | `vibe start` 的别名 |
-| `vibe start` | 按需启动服务与 Web UI;已运行时复用现有进程 |
+| `vibe start` | 按需启动服务与 Web UI;已运行时复用现有进程;`--no-open-browser` 可禁止自动打开浏览器 |
| `vibe stop` | 停止服务与 UI,同时终止 OpenCode server |
| `vibe restart` | 停止后重新启动 |
| `vibe status` | 输出运行状态 JSON |
@@ -530,8 +530,11 @@ vibe
```bash
vibe start
+vibe start --no-open-browser
```
+- `--no-open-browser` 会保留相同的启动/复用语义,但不会自动打开浏览器;桌面壳这类自带 WebView 的调用方应使用这个契约。
+
- 如果主服务尚未运行,则启动主服务
- 打开 Web UI
- 保留已运行的服务、Web UI 与 OpenCode server;需要明确重启时使用 `vibe restart`
diff --git a/docs/desktop-test-installation.md b/docs/desktop-test-installation.md
new file mode 100644
index 000000000..1ed4740e1
--- /dev/null
+++ b/docs/desktop-test-installation.md
@@ -0,0 +1,43 @@
+
+
+## Desktop TEST installation
+
+This GitHub prerelease is for desktop testing. Download the installer matching
+your machine: `aarch64-apple-darwin.dmg` for Apple silicon,
+`x86_64-apple-darwin.dmg` for Intel Macs, or `x86_64-pc-windows-msvc.exe` for
+Windows x64. Each filename starts with `Avibe_<version>_`.
+
+Download the matching `.SHA256SUMS`, `.SIGNATURE`, `.SOURCE.json`, and
+`.runtime-manifest.json` files too. On macOS, run `shasum -a 256 -c` with the
+downloaded `.SHA256SUMS` filename in the directory containing all five files.
+On Windows, use `Get-FileHash -Algorithm SHA256 <installer.exe>` and compare it
+with the installer entry in `.SHA256SUMS`. The source record identifies the tag,
+commit, desktop version, and bundled Avibe package version; the Runtime manifest
+records the embedded archive and toolchain hashes. `SIGNATURE` is descriptive
+metadata, **not a cryptographic signature file**. Hashes detect changed downloads;
+they do not establish a trusted developer identity.
+
+The macOS **app inside the DMG is ad-hoc signed**. The outer DMG is unsigned and
+unnotarized; this is not Developer ID distribution. Open the DMG, drag Avibe to
+Applications, and launch it. If macOS blocks this verified test app, use System
+Settings → Privacy & Security → Open Anyway for this app and confirm the prompt.
+The Windows NSIS installer is unsigned and may show SmartScreen or an unknown
+publisher prompt. After checking the download, use More info → Run anyway only
+if your machine's policy permits it. Keep Gatekeeper, SmartScreen, and antivirus
+enabled; managed machines may require administrator approval.
+
+Python, Avibe, Node, and npm are bundled; no separate installation is required.
+Agent backends are detected or installed when selected in Avibe. There is no
+desktop auto-updater. Quit the shell and manually replace the app (macOS) or run
+the replacement installer (Windows) to upgrade. User data under `~/.avibe` is
+retained; reopening the replacement app verifies and activates its private Runtime.
+
+To remove the private Runtime and Avibe-managed backend installations, choose
+**Uninstall Avibe…** in the application's first menu and confirm, then remove
+the macOS app or use the Windows system uninstaller. Removing only the app does
+not perform that cleanup. Sessions, settings, credentials, and projects under
+`~/.avibe` remain available for reinstall; external backend installations are
+untouched. Closing the window alone does not stop the Runtime.
+
+Trusted distribution, including the remaining signing layers, is tracked in
+[#1976](https://github.com/avibe-bot/avibe/issues/1976).
diff --git a/docs/plans/desktop-backend-lazy-install.md b/docs/plans/desktop-backend-lazy-install.md
new file mode 100644
index 000000000..30a5a38a3
--- /dev/null
+++ b/docs/plans/desktop-backend-lazy-install.md
@@ -0,0 +1,127 @@
+# Desktop Backend Lazy Installation
+
+## Status
+
+Frozen implementation contract for the first self-contained desktop release.
+
+## Product Outcome
+
+The desktop package remains usable on a clean macOS or Windows machine without
+system Python, Node.js, npm, or `uv`. It embeds the Avibe Runtime, Python,
+Node.js, and npm, but does not embed Codex, Claude Code, or OpenCode. Agent
+backends are installed only after the user requests one.
+
+## Resolution Contract
+
+1. An explicitly configured executable path is authoritative while it remains
+ valid. Avibe never silently replaces it.
+2. With no configured path, existing external installations are discovered
+ first through the current platform resolver.
+3. Only when external discovery fails may Avibe resolve an app-private backend
+ recorded under the desktop backend root.
+4. A desktop Runtime projects every configured backend selector through the
+ same resolver used by Settings before constructing Claude, Codex, or
+ OpenCode runtime configuration. GUI-process `PATH` inheritance is never a
+ second source of truth for whether an installed backend can launch.
+ Historical snapshots remain unresolved when deciding whether a saved
+ selector change requires live reconciliation.
+5. Installing a missing backend in a desktop-managed Runtime uses the bundled
+ Node.js and npm. It never requires or mutates system Node.js, npm, or global
+ package state. An invalid private toolchain fails closed instead of falling
+ through to a global installer.
+6. Non-desktop installations retain the existing global one-click installer
+ behavior.
+
+## Private Install Contract
+
+- The package allowlist is fixed in code:
+ - Codex: `@openai/codex`
+ - Claude Code: `@anthropic-ai/claude-code`
+ - OpenCode: `opencode-ai`
+- npm is invoked directly as `node <npm-cli.js>` without a shell.
+- Lifecycle scripts are disabled. Avibe selects the target-specific optional
+ package and verifies its native executable instead of delegating publication
+ to an upstream postinstall script.
+- npm installs into a fresh staging prefix below the app-private backend root.
+- Avibe validates the installed package version, target-native executable, and
+ every native support executable required by that backend before publishing
+ the release. For Codex this includes its code-mode host, packaged ripgrep,
+ shell/sandbox helpers, and package metadata.
+- Publication is an atomic, bounded `current.json` descriptor. Every descriptor
+ path is relative and must remain below the backend root.
+- The exact published executable path is persisted in backend configuration.
+- Updates use the same staged install and atomic publication path. A running
+ backend may continue using its previous release; old releases are not deleted
+ during installation.
+- Failed staging directories and unpublished releases are removed. Previously
+ published releases and configuration remain unchanged.
+
+## Runtime Bundle Contract
+
+Runtime manifest schema 2 contains Python, Node.js, npm, and Avibe metadata.
+It contains no agent backend version, executable, helper, or license. The
+desktop launcher supplies these immutable paths to Python:
+
+- `AVIBE_DESKTOP_RUNTIME_ROOT`
+- `VIBE_SHOW_RUNTIME_NODE_BIN`
+- `AVIBE_DESKTOP_NPM_CLI`
+- `AVIBE_DESKTOP_BACKENDS_ROOT`
+
+The backend root is mutable app data and is separate from the content-addressed
+Runtime root. The Runtime integrity verifier therefore never treats lazy-loaded
+backends as bundled files.
+
+Mutable backend helper directories are derived from the exact configured
+executable and added at that backend's subprocess boundary. They are not added
+to the desktop launcher's process-wide `PATH`, because the launcher starts
+before a backend may be installed or updated. Codex uses the same derived
+environment for its app-server and per-thread shell policy, including Model Hub
+launches, so the packaged ripgrep remains available without a Runtime restart.
+
+The desktop builder installs `claude-agent-sdk` from its pure-Python source
+distribution. Its platform wheels embed Claude Code, so accepting those wheels
+would violate the same boundary even though the executable lives inside a
+Python dependency rather than under `tools/`. The builder verifies that the
+installed SDK contains no bundled Claude executable before packaging.
+
+## Lifecycle And Updates
+
+- A private backend reports `managed_by: "desktop"`, but remains independently
+ updateable from the Settings UI.
+- A successful install path is already persisted and hot-reconciled. Settings
+ adopts it as both the displayed and saved value, so it never offers a second
+ Save action for the same activation.
+- Install completion and failure messages use the configured Avibe language.
+- The install-job response publishes a polling budget that exceeds the full
+ bounded lock, npm, verification, process-drain, and reconciliation budget;
+ the Workbench uses that server-owned budget.
+- Backend update checks continue to compare the installed version with the
+ package registry version.
+- Desktop application updates replace the signed Runtime bundle but do not
+ silently replace private backends.
+- Explicit desktop uninstall removes both the app-private Runtime and the
+ app-private backend root after the managed Runtime has stopped. Avibe user
+ state under `AVIBE_HOME` remains untouched.
+
+## Acceptance
+
+- A clean desktop install can install and launch each backend without system
+ Node.js or npm.
+- An existing external backend is selected before an app-private one.
+- An explicit configured path remains selected across desktop and backend
+ updates.
+- Private install and update publish only verified direct native executables;
+ command shims such as `.cmd` are never persisted.
+- A freshly installed Codex can resolve its packaged ripgrep in both the
+ app-server and command environment without system ripgrep or a Runtime
+ restart.
+- A failed install cannot replace the active descriptor or configured path.
+- The product Runtime archive contains no Codex, Claude Code, OpenCode, or
+ backend-specific ripgrep payload.
+- macOS and Windows package CI verify Runtime schema 2 and the bundled npm CLI.
+
+## Residual Follow-up
+
+Release pruning needs a backend-process drain boundary. Until that exists,
+superseded private backend releases are retained to avoid deleting files used by
+active sessions.
diff --git a/docs/plans/desktop-deep-links.md b/docs/plans/desktop-deep-links.md
new file mode 100644
index 000000000..1ecc458ac
--- /dev/null
+++ b/docs/plans/desktop-deep-links.md
@@ -0,0 +1,206 @@
+# Desktop deep links (`avibe://`)
+
+## Status
+
+Frozen implementation contract for gap G5. Companion to
+`desktop-product-gaps.md` (G5), `desktop-notifications-sse.md` (G4 click
+upgrades to a locate, not a redesign), and
+`tauri-desktop-vertical-slice.md` (thin shell, Workbench stays the
+product UI).
+
+Owner: Avibe core
+Date: 2026-09-10
+Baseline: `desktop` branch after #1975 (single-instance plugin already
+focuses the running window and ignores argv).
+
+## Product outcome
+
+A click on `avibe://session/<id>` (from IM, mail, or a future G4
+notification) brings Avibe to the front and shows that session. If the
+app was not running, it starts, finishes bootstrap, then shows the
+session. Unknown or malformed links are dropped, never echoed back
+into a WebView.
+
+v1 is **locate-in-the-existing-window**. Opening a second native
+window for a Show Page is G8 and is not this contract.
+
+## Frozen grammar
+
+Scheme: `avibe` (no `+` / no vendor prefix). Registered for the
+packaged app identifier `bot.avibe.desktop`.
+
+v1 URLs use the `avibe://` form users type and OS scheme handlers
+deliver. A WHATWG parser therefore treats `<kind>` as the **authority
+(host)**, not as a path segment. That is the frozen grammar: kind **is**
+the allow-listed authority. Do not also accept a second, host-less
+spelling (`avibe:session/...`); one form only.
+
+| Link (kind = authority) | Workbench navigation |
+| --------------------------------- | -------------------------------------------- |
+| `avibe://session/<session_id>` | `/chat/<session_id>` |
+| `avibe://show/<session_id>` | `/apps/show/<session_id>` |
+| `avibe://settings` | `/admin/settings/service` |
+| `avibe://vaults/request/<request_id>` | `/vaults?request_id=<request_id>` |
+
+Parse as a URL. Accept only when `scheme == avibe`, `host` is one of
+`session`, `show`, `settings`, `vaults`, **and `port` is absent**
+(`avibe://session:443/<id>` is malformed even though `host_str()`
+would look allow-listed). Userinfo is rejected. Path/id rules:
+
+- `session` / `show`: path is exactly one segment, the id.
+- `settings`: path empty.
+- `vaults`: path is exactly `request/<request_id>`.
+
+`<session_id>` and `<request_id>` are the product's existing identifiers
+(Workbench session ids, vault request ids). They are accepted only when
+they match `^[A-Za-z0-9._-]+$`, are at most 128 bytes, and are **not**
+the complete path segments `.` or `..`. Ordinary dots inside an id
+(`ses.abc`) remain valid.
+
+Rejected complete `.` / `..` because WHATWG URL path normalization
+would turn `/chat/.` into `/chat/` and `/chat/..` into `/`, so the
+in-window navigation could not land on the mapped session route. Percent-encoded `%2E` / `%2E%2E` **do** normalize as dot-segments under
+WHATWG (`/chat/%2E` → `/chat/`, `/chat/%2E%2E` → `/`). They are still
+rejected, but by the character-class rule (`%` is not in
+`[A-Za-z0-9._-]`), not by a special encoded-dot exception. Do not
+document them as surviving the parser.
+
+Rejected (no navigation, no quoted echo into the WebView):
+
+- any scheme other than `avibe`;
+- host/authority not in `{session, show, settings, vaults}`
+ (this is what "reject unknown authority" means — userinfo,
+ non-allow-listed hosts, `avibe://session@…`);
+- extra path segments, query, or fragment other than the table;
+- an id that fails the character/length rule or is complete `.` / `..`.
+
+The mapping table is the contract. A new kind is a contract revision,
+not a silent addition in the parser.
+
+## Delivery: the shell never talks IPC to the Workbench
+
+Two launch shapes, one Workbench mechanism.
+
+1. **Hot path** (app already running). Every OS delivery of an
+ `avibe://` URL is parsed by the **same** function and applied to
+ the live window. On Windows a second launch typically arrives as
+ single-instance argv (already wired to focus the main window in
+ `desktop/src-tauri/src/lib.rs`). On macOS, Launch Services delivers
+ custom-scheme activations as a native open-URL event
+ (`RunEvent::Opened` / the deep-link plugin's current-URL /
+ `on_open_url` **Rust** callback) — **not** as a second-process
+ argv. Feed that native event into the same parser/stash as argv.
+ Never handle it in WebView JavaScript, never add an IPC command.
+ After the window is showing the Workbench origin, navigate
+ **in-window** to `{origin}{path}{query}` from the table. Same
+ origin as the currently adopted Runtime; never `devUrl` / port 1420.
+2. **Cold path** (app was not running). OS starts the packaged app
+ with the URL in argv **or** (macOS) as the first open-URL event.
+ The shell stashes the parsed target, runs
+ the existing bootstrap/adopt flow unchanged, and on the first
+ successful Workbench navigation includes the target path so the
+ SPA lands on it instead of the default session list.
+
+Both paths resolve to "the Workbench SPA navigates to a same-origin
+URL it already implements". There is **no new Tauri command, no new
+capability, no `remote` grant**. A Workbench page still cannot invoke
+bootstrap IPC; the shell pushing a same-origin path into its own
+WebView is not an IPC grant.
+
+If the Runtime is not yet ready (bootstrap screen still up), the
+stashed target waits. Bootstrap failure discards it and stays on the
+bootstrap screen — a deep link must not override a failed Runtime
+with a half-navigated Workbench.
+
+## Why not an IPC command
+
+An IPC `open_target` callable from the WebView would have to be
+granted to the navigated Workbench to be useful on the hot path,
+which is exactly the capability boundary `shell_boundaries.rs`
+forbids. Same-origin in-window navigation keeps the privilege in
+the shell: only the process that owns the window decides to move it.
+
+## Producer side (Python, separate from the shell PR if needed)
+
+Today `vault_request_url` / IM formatters emit public `https://`
+Workbench URLs via `workbench_url` (`core/avibe_cloud.py`). That
+remains the right link for browsers and for users without the
+desktop app.
+
+v1 desktop does **not** require those producers to switch. The
+shell's job is to honour `avibe://` when the OS delivers one.
+Producers may start emitting `avibe://` **in addition to** https
+(for example in a native-notification payload once G4 lands) under
+their own PR; that is a link-grammar consumer, not a scheme-parser
+change. Until they do, G5 is still testable: open
+`avibe://session/<known-id>` from Terminal / a test page.
+
+Do not replace https links in IM with `avibe://` in v1: IM clients
+are not the desktop OS and cannot route the scheme.
+
+## Plugin and packaging
+
+- `tauri-plugin-deep-link` registers the scheme at build/install
+ time for the packaged app. Development `tauri dev` may not receive
+ OS-level `avibe://` clicks (scheme registration is an installed-app
+ concern); argv injection and the single-instance callback remain
+ the testable path.
+- macOS: the scheme lands in `Info.plist` via the plugin. That file
+ is generated; do not hand-edit it in source.
+- Windows: the scheme lands in the NSIS file association. Unsigned
+ acceptance builds still register it for that install; signing (G1)
+ does not change the grammar.
+
+## Tests (invariants)
+
+- Parser: every row in the mapping table produces the exact
+ Workbench path; every rejected shape (wrong scheme, extra
+ segment, bad id, complete `.` / `..` path id, authority, explicit
+ port) produces `None` and never includes the raw input in a UI
+ string. An id that merely contains a dot still maps.
+- Hot path: a valid link focuses the main window and requests
+ in-window navigation to the mapped path on the **currently adopted
+ origin**, not on `devUrl` / port 1420 — whether the link arrived as
+ second-instance argv **or** as a macOS native open-URL / GURL
+ Apple Event (raw string into the same parser/stash). An
+ implementation that only wires argv does not satisfy this.
+- Cold path: a stashed valid target (from argv **or** the first
+ macOS open-URL event) is applied on the first successful Workbench
+ navigation and then cleared; a failed bootstrap leaves the stash
+ dropped and the window on bootstrap.
+- Boundary: no new command appears in `src-tauri/build.rs`;
+ `shell_boundaries.rs` still forbids `remote` grants. Deep-link
+ handling lives in argv, the single-instance callback, and the
+ macOS native open-URL adapter — none of which are
+ WebView-callable. The adapter must feed the shared parser/stash;
+ it must not reintroduce a `Url::as_str()` path after Tao has
+ normalized the URL.
+- Capability: a Workbench origin (remote after navigation) still
+ cannot invoke bootstrap commands after a deep link is consumed.
+
+Drive parser tests without Tauri (pure function in `runtime-host` or
+an equivalent Tauri-free module). Drive the stash/apply state
+machine with the existing fake-Runtime bootstrap tests.
+
+## Explicit non-goals (v1)
+
+- Native multi-window as the link's destination (G8).
+ `avibe://show/<id>` in v1 locates inside the main window.
+- Replacing https Workbench URLs in IM / mail.
+- Authenticating the link (ids are capabilities-by-guess of a
+ local-only app; loopback Workbench already assumes the user on
+ the machine).
+- Query parameters other than `request_id` on `/vaults`.
+- Custom URL scheme beyond `avibe`.
+
+## Sequencing
+
+- Independent of G1 signing. Scheme registration works on unsigned
+ acceptance builds.
+- G4 may adopt these URLs as notification click targets in a
+ follow-up; G4 v1 remains "focus the window".
+- G6 (window state) is independent; a restored frame still receives
+ the in-window navigation.
+- G8, when it exists, may reinterpret `avibe://show/<id>` as "tear
+ out that Show Page"; the grammar stays, the destination policy
+ is a G8 revision of this table's third column.
diff --git a/docs/plans/desktop-g5-g6-implementation.md b/docs/plans/desktop-g5-g6-implementation.md
new file mode 100644
index 000000000..68d0f1ae7
--- /dev/null
+++ b/docs/plans/desktop-g5-g6-implementation.md
@@ -0,0 +1,86 @@
+# Desktop deep-link and window-frame implementation
+
+## Change contract
+
+Implements the authoritative `desktop-deep-links.md` and
+`desktop-window-state.md` contracts from PR #1979, including the 4bd96455c
+amendment. Requires #1979 merged first; its branch is not stacked into this lane.
+
+- Native argv, single-instance delivery, and a macOS raw GURL Apple Event handler share a
+ Tauri-free parser and one pending target. The first valid link in one delivery
+ wins; a later valid delivery replaces an unconsumed target.
+- Only a ready, adopted Runtime supplies the origin. Navigation prepares a
+ target and consumes it only on native success in the issuing window generation.
+ True Runtime bootstrap failure drops it. A hot delivery waits until
+ the WebView has reached that origin before applying the same route mapping.
+- Raw links never become JavaScript or error copy. Complete dot segments are
+ rejected; ordinary identifier dots remain valid. Percent escapes fail the
+ literal identifier character rule. The kind is the allow-listed URL authority;
+ userinfo, ports, host-less spellings, and normalized nonliteral input are rejected.
+- The window-state plugin is the only frame store. It restores native geometry
+ before showing `main`; a native frame hook clamps against monitor work areas
+ with DPI-aware minimum dimensions. Content navigation never reapplies defaults.
+- Native move/resize events debounce the plugin's existing save operation. Only
+ position, size, and maximized state are enabled; visibility and fullscreen are
+ excluded. Hide/Open keeps the same window and frame.
+
+## Boundaries and non-goals
+
+No new application command, capability, remote grant, React route, Python link
+producer, notification, or second native window. The local-first data-location
+and bootstrap-only IPC boundaries remain unchanged. G8 and producer adoption are
+explicitly deferred; malformed links are silently dropped.
+
+## Verification
+
+- Parser properties cover exact mappings, literal identifiers, origin stability,
+ malformed grammar, and one-shot hot delivery without Tauri.
+- Existing fake-Runtime bootstrap tests exercise cold staging, failure discard,
+ and retry without replay. Native source-boundary tests check OS-only entry
+ points, unchanged commands/capabilities, and frame-only plugin lifecycle hooks.
+- Clamp properties check title-bar visibility, DPI-aware minimum dimensions,
+ idempotence, and preservation of accessible frames.
+- macOS descriptor and Objective-C selector tests retain literal strings through
+ the native adapter into the same stash, including rejected dot segments,
+ percent-encoded dot segments, embedded NUL, and Unicode. No AppKit event loop,
+ installed application, or external Apple Event delivery is required.
+- Local gates: bootstrap npm install/build/i18n, Rust formatting, all-target
+ all-feature clippy, and all-feature workspace tests. CI repeats on macOS and
+ Windows. Packaged OS scheme registration and native frame round-trip remain
+ manual acceptance checks when an isolated graphical environment is unavailable.
+
+## Review correction: native input fidelity
+
+Review 5165620370 on head 722e04e143 identified one input-fidelity class: Tao
+0.35.3 parses NSURL text before Tauri exposes `RunEvent::Opened`, so stringifying
+that event cannot enforce the literal grammar. The orchestrator approved a raw
+GURL handler in plugin setup and removal on Exit, with no normalized fallback.
+The grammar and other OS/G6 behavior are unchanged.
+
+Only macOS directly depends on the already-locked objc2 0.6.4 and Foundation
+0.3.2, adding the descriptor/manager features. The adapter uses Foundation's
+documented selectors with 32-bit FourCC values, not Core Services bindings or a
+new framework. The Objective-C handler owns its Rust callback, is retained on
+the installing thread until Exit removes the registration, and never writes a
+reply descriptor. No delegate replacement, swizzle, or current-event lookup is
+used. Plugin setup runs before Tauri's event loop, while the process-level stash
+already exists, so an early event does not depend on window or Runtime readiness.
+
+## Review correction: navigation commit ownership
+
+Review 5167442411 on head 12f5b5855f identified a distinct second class:
+preparing a cold or hot navigation consumed its target before the native window
+accepted it. The September 10 orchestrator ruling freezes two-phase delivery:
+
+- Missing windows, generation changes, native navigation errors, and
+ `WorkbenchNavigationFailed` retain the target for a ready Runtime.
+- True Runtime bootstrap failure discards the target.
+- Only successful navigation in the issuing window generation may commit.
+- An old attempt cannot clear a newer delivery, even when both URLs are equal.
+
+The existing `DeepLinks` owner retains an immutable delivery identity and returns
+a prepared URL plus that identity. Both native paths share one commit boundary;
+neither holds the stash mutex during native navigation. No new persistent store,
+IPC, capability, dependency, or G6 behavior is introduced. Fake-Runtime tests and
+pure owner tests cover handoff retry, generation changes, failure distinction,
+newer delivery preservation, and one-shot successful consumption.
diff --git a/docs/plans/desktop-master-integration-20260920.md b/docs/plans/desktop-master-integration-20260920.md
new file mode 100644
index 000000000..609b2f575
--- /dev/null
+++ b/docs/plans/desktop-master-integration-20260920.md
@@ -0,0 +1,561 @@
+# Desktop / master integration contract
+
+## Goal and authorization
+
+The owner requested resolving the merge conflicts in avibe-bot/avibe PR #2062 (`desktop` into `master`) on 2026-09-20. Integrate the current mainline into the existing desktop lineage, preserve both sets of intended behavior, and update that PR. Merge into master, production operations, signing setup, and desktop publication are not authorized by this task.
+
+The orchestrator is Avibe Session `sessjyd34p9rp`. One implementation lane owns the integration; do not split shared Runtime contracts across concurrent writers.
+
+## Source snapshots and workspace
+
+- Initial desktop head: `92c600aa78f51e3b9ec48f185e5150a4f2ef3163`.
+- Initial master head: `4de519cce2f7254325a88f652b31f510a7a8ff70`.
+- Branch: `chore/desktop-master-integration-20260920`, based on origin/desktop.
+- Worktree: `/Users/max/workspace/ai/avibe/.worktrees/avibe/desktop-master-integration-20260920`.
+- Existing PR: https://github.com/avibe-bot/avibe/pull/2062.
+- The primary checkout and other desktop worktrees belong to other tasks and must remain untouched.
+
+Use a real merge of origin/master into this desktop-based integration branch. Preserve the desktop ancestry and push the resulting descendant to origin/desktop with a normal non-force push. Do not cherry-pick desktop onto a new mainline branch or replace the assigned PR. Recheck the remote desktop head before pushing; reconcile unexpected movement instead of overwriting it.
+
+## Behavior invariants
+
+1. Mainline Web/IM orchestration, async UI/API handling, authorization, persistent state compatibility, and current backend/Model Hub behavior remain effective after integration.
+2. Desktop retains its local native shell, self-contained Runtime installation, lazy backend installation, startup/ownership receipts, Windows IPC, tray lifecycle, native links, window restoration, and native notifications.
+3. The shell remains the native capability owner; remote/Workbench pages gain no native privilege. User state stays separate from immutable packaged Runtime contents.
+4. Shared behavior has one owner. Adapt desktop-specific callers to current shared interfaces when possible; do not restore obsolete mainline paths solely to satisfy stale desktop tests.
+5. Successful backend config persistence uses the mainline rolling refresh path; UI request paths stay async and do not add per-request event-loop bridges.
+6. On-disk released shapes retain migration or safe-degradation behavior. No destructive state changes, speculative architecture rewrite, or removal of a capability to make the merge clean.
+7. Conflict resolution is semantic: automatically merged files and tests must be checked for interface drift too. No blanket ours/theirs strategy.
+
+## Initial conflict inventory
+
+The initial non-checkout merge probe reported 27 paths:
+
+- AGENTS.md
+- core/internal_server.py
+- core/show_runtime.py
+- modules/agents/codex/agent.py
+- tests/test_claude_cli_path.py
+- tests/test_cli_setup_status.py
+- tests/test_internal_server.py
+- tests/test_local_deps.py
+- tests/test_restart_supervisor.py
+- tests/test_ui_api.py
+- tests/test_ui_server_install.py
+- tests/test_ui_show_pages.py
+- tests/test_upgrade_flow.py
+- tests/test_vibe_cli.py
+- ui/src/components/VersionBadge.tsx
+- ui/src/components/settings/SettingsDependenciesPage.logic.ts
+- ui/src/components/settings/SettingsDependenciesPage.test.ts
+- ui/src/components/settings/SettingsDependenciesPage.tsx
+- ui/src/components/settings/shared/useBackendRuntime.ts
+- ui/src/context/ApiContext.tsx
+- vibe/api.py
+- vibe/cli.py
+- vibe/internal_client.py
+- vibe/model_hub_client.py
+- vibe/restart_supervisor.py
+- vibe/runtime.py
+- vibe/ui_server.py
+
+The lane may edit these files, existing desktop-delta paths, and directly consuming callers/tests required to preserve the invariants. It may update this plan and the PR description. Any broader architecture change or unrelated feature is outside scope and goes to the orchestrator with evidence.
+
+## Validation and safety
+
+Read the current master AGENTS.md, the workspace AGENTS.md, and the canonical pr-delivery-loop skill; the desktop copy may be old. The owner's current acceptance target is the designated cloud test instance per workspace conventions, but this task does not authorize deploying to it. Use hermetic local tests by default. Do not restart the installed local service, touch real user config/token stores, create the retired local Incus environment, or run write-capable production tests.
+
+- Compare desktop and mainline contracts before choosing each conflict resolution; record the significant choices below.
+- Run focused Python tests for Runtime, desktop lifecycle/backends, IPC, readiness, API/config reconciliation, and any changed shared subsystem; adapt existing scenario coverage where its contract is affected.
+- Run focused frontend tests for merged backend settings/API context/version behavior and `npm run build` in ui/.
+- Run desktop bootstrap localization/build and relevant Rust Runtime/shell checks as supported locally. Let GitHub desktop-shell cover its macOS and Windows matrix; report any local limitation accurately.
+- Run Ruff on changed Python files before each push and inspect the full diff for conflict markers, accidental mainline reversions, debug files, or obsolete paths.
+- Required PR workflow families: lint and desktop-shell. Verify expected individual checks, current-head Codex pass, and zero unresolved threads before handing back.
+
+## Review and delivery
+
+Load pr-delivery-loop and background-watch-hook. One durable lane-owned combined PR/CI Watch must cover PR #2062 using a separate cursor from the orchestrator's existing Watch. Seed only once before the first pushed head or explicit review trigger, use --forever and --timeout 0 at both layers, and do not reseed between rounds.
+
+A bot review of the original head was pending when this task began. Do not push while a prior-head review is still in flight. Resolve/reconcile its findings against the integrated candidate. Follow the circuit breaker: repeated root-cause class on two reviewed heads, or three findings-bearing heads after a model rewrite, pauses editing for orchestrator diagnosis. Fetch all paginated threads and report the full inventory. Existing review authority is not replaced by a local reviewer.
+
+Read back every PR-body/comment change. Hand back PR/head, source parent SHAs, significant resolution decisions, test evidence, CI/review status, residual acceptance checks, and any active Watch ID. Do not merge into master or publish.
+
+## Decisions and evidence
+
+- 2026-09-20: Use one implementation lane and one merge commit lineage because the conflicts cross shared Runtime/UI boundaries. Preserve current master architecture and adapt desktop contracts within it.
+- 2026-09-20: Resolve shared Python/API/UI conflicts by keeping the current
+ `master` async FastAPI, rolling backend refresh, dependency reconciliation,
+ Model Hub/Memory projections, CLI authority, and Show Runtime provider/file
+ lock contracts. Adapt desktop callers and fixtures to those interfaces rather
+ than restoring retired Flask, per-request event-loop, GitHub Show Runtime, or
+ in-process install-lock paths.
+- 2026-09-20: Preserve desktop Runtime-host ownership as two facts: launch
+ attempts continue to deduplicate retries, while a completed startup receipt
+ remains scoped stop authority until receipt refusal or confirmed Runtime loss.
+ Readiness timeout releases only the completed helper retry slot. Handover is
+ authorized only by the exact five-field identity-mismatch payload containing a
+ valid 64-character lowercase hexadecimal desktop predecessor identity; both
+ initial and polling consumers enforce the same boundary.
+- 2026-09-20: Keep the master's `doctor` validation and bare `doctor` behavior
+ by validating individual repair targets with a custom argparse type. This
+ avoids argparse's empty-list `choices` failure without accepting unknown
+ targets. The live-service receipt fixture now supplies controlled process
+ identities and creation times rather than reading local PIDs or state.
+
+### Validation evidence before the integration commit
+
+- Python integration boundary and desktop/runtime/API/UI tests:
+ `2123 passed, 5 skipped` across the focused Runtime, desktop, IPC, API,
+ backend, CLI, upgrade, internal-server, dependency, restart, and Show Runtime
+ suites.
+- Rust Runtime-host: `cargo test --lib` (`92 passed`), bootstrap integration
+ (`25 passed`), notification HTTP (`5 passed`), and `cargo fmt --check` passed.
+ The desktop workspace `cargo fmt --all -- --check` and
+ `cargo clippy --workspace --all-targets -- -D warnings` also passed.
+- Frontend: merged settings/API-context focused tests `81 passed`,
+ `npm run typecheck:tests`, and `npm run build` passed. Desktop bootstrap
+ `npm run test:i18n` and `npm run build` passed.
+- Changed Python Ruff check passed with `uvx ruff check`; Python compile and
+ whitespace checks were run during reconciliation. The repository's existing
+ `patches/cliproxyapi/native-intent.patch` carries intentional patch-format
+ whitespace diagnostics under a full `git diff --check`; no conflict markers
+ remain in source files.
+- The original-head Codex review inventory remains two distinct findings on
+ `92c600aa78`: predecessor identity authorization and receipt ownership across
+ readiness timeout. Both have consuming regression tests and no repeated class
+ or circuit-breaker trigger at this point. The exact-head review and required
+ GitHub CI remain post-push gates.
+
+### Post-push mainline synchronization note
+
+- 2026-09-20: After pushing `007f631613be43b3d00918c9e1e3cde58235099d`, the
+ latest remote `master` was independently verified with `git ls-remote` as
+ `162fda5942461941942536355130477372739c36`. It includes the native
+ credential takeover integration from PR #2060, which intersects the shared
+ Model Hub/auth/backend lifecycle boundaries in this merge.
+- The repository's `remote.origin.fetch` contains only unrelated branch-specific
+ refspecs. A plain `git fetch origin master desktop` updates `FETCH_HEAD` but
+ does not refresh `origin/master` or `origin/desktop`. Subsequent source refresh
+ must use explicit refspecs such as
+ `refs/heads/master:refs/remotes/origin/master` and
+ `refs/heads/desktop:refs/remotes/origin/desktop`, or pin the SHA returned by
+ `git ls-remote`. The shared fetch configuration must remain unchanged.
+- A non-checkout merge-tree probe of `162fda5942` with the current candidate
+ returned a clean tree, but textual cleanliness does not establish semantic
+ compatibility. After the current-head review is terminal, merge this exact
+ master SHA normally, inspect native credential takeover against desktop IPC,
+ API, auth, and backend rolling-refresh ownership, and rerun focused consumers,
+ frontend build, and changed-Python Ruff before the one subsequent push.
+
+### Circuit-breaker ruling and bounded follow-up
+
+- 2026-09-20: The Codex review inventory contains two findings-bearing heads:
+ `92c600aa78` (review `5259095413`) and `007f631613` (review `5259460941`).
+ The predecessor-identity finding was fixed on the first candidate. The
+ launch-provenance class repeated on the second candidate as
+ `4056057500`/`PRRT_kwDOPbFPYs6kG0NV`, so the review-loop circuit breaker
+ paused edits until the orchestrator diagnosed the complete class.
+- The diagnosis is that retry deduplication, scoped stop authority, and
+ evidence that a Runtime may still be alive have different lifetimes. The
+ bounded fix keeps one `LaunchState` owner and adds only minimal in-memory
+ liveness evidence. A helper timeout, successful reused outcome, missing
+ receipt, helper failure, receipt refusal, or recovery reset is not proof that
+ a previously launched or reused Runtime is absent. Receipt refusal revokes
+ stop authority; it does not turn uncertain liveness into `Inactive` removal.
+ Unknown liveness must continue to reach `RuntimeRemovalState::Unknown`, where
+ the bundled launcher refuses destructive deletion. A definitive safe stop or
+ completed removal may clear the evidence.
+- The lifecycle contract to preserve is:
+
+ | Launch/watch outcome | Readiness/retry state | Stop authority | Removal decision |
+ | --- | --- | --- | --- |
+ | pending | retain attempt; no overlapping helper | none | `Unknown` if no external readiness proves otherwise |
+ | started receipt | timeout releases only completed retry slot; late readiness may be adopted | scoped stop remains valid until refusal or confirmed loss | `Managed` while the owned Runtime is active; unknown liveness remains fail-closed |
+ | reused receipt | retry may proceed after a completed helper; no ownership | none | `Unknown` until liveness is disproved or removal completes |
+ | successful without receipt | retry may proceed after a completed helper; no ownership | none | `Unknown` rather than `Inactive` |
+ | failed helper | release failed attempt; do not infer prior Runtime absence | none | `Unknown` when prior liveness evidence remains; fresh never-launched state may be `Inactive` |
+
+ Readiness timeout alone releases retry eligibility, not liveness evidence.
+ Receipt refusal removes scoped stop authority but preserves uncertainty.
+ `reset_after_confirmed_runtime_loss` is called by the readiness-only recovery
+ monitor. It releases retry and stop ownership after the monitor's recovery
+ threshold, but does not itself prove process absence or clear the removal
+ fence. Tests cover timeout -> retry eligibility -> uninstall,
+ late-ready scoped stop, refusal, no-overlap, valid handover, fresh inactive
+ removal, and safe successful cleanup.
+- The Windows notification review finding `4056057501` is a verified false
+ positive and remains a deliberate non-change. `std::fs::rename` replaces an
+ existing destination on Windows according to the Rust standard-library
+ documentation; desktop-shell job `106015889235` in run `35487284891` passed
+ `preference_defaults_on_and_persists_the_tray_choice_across_restarts` and the
+ failure-preservation test on the reviewed head. No notification code or
+ dependency change is warranted. This evidence will be linked in the thread
+ reply before the thread is resolved.
+
+### Latest-master candidate evidence
+
+- 2026-09-20: Explicit refspec refresh confirmed `origin/master` at
+ `162fda5942461941942536355130477372739c36` and `origin/desktop` at
+ `007f631613be43b3d00918c9e1e3cde58235099d`. The local candidate is a real
+ merge commit with parents `a323abc0fb300baca829a3df0d986cabc49445cf` and
+ `162fda5942461941942536355130477372739c36`; the first parent preserves the
+ desktop integration candidate and the second is the native credential
+ takeover mainline. The restricted fetch configuration was not changed.
+- The three exact CI compatibility classes from the synthetic latest-master
+ merge ref were fixed at their current contracts: the Codex Hub transport
+ test supplies a hermetic catalog-preparation result; dependency selective
+ checks assert `reconciling` and `reconciling_dependencies` metadata while
+ retaining row/probe ownership assertions; internal-server observability
+ tests use the current cross-platform `ControlIpcHost` bind/publish/cleanup
+ owner and retain all five recorder-close paths.
+- Focused evidence on the candidate: the three CI classes plus local dependency
+ coverage passed (`483 passed`); the native auth/Model Hub/backend consumer
+ set passed (`1303 passed, 33 warnings, 125 subtests`); Runtime-host passed
+ `94` library tests, `25` bootstrap integration tests, and `5` notification
+ HTTP tests, with `cargo fmt --check`; changed-Python Ruff passed; desktop
+ localization and bootstrap build passed; UI test typechecks and production
+ build passed.
+- The first native consumer run reported 17 Claude direct-observation failures
+ only because this agent process exports `ANTHROPIC_*` and `OPENAI_*` launch
+ credentials. The new-master direct projection intentionally honors those
+ launch sources. The connection-test safety fixture now removes those five
+ variables before each test, and the same consumer set passes with hermetic
+ source selection. Production credential precedence is unchanged.
+
+### Final mainline synchronization candidate
+
+- 2026-09-20: The restricted tracking refs were refreshed with explicit
+ refspecs, and `origin/master` was verified at
+ `a32cd9df9be96ae9b86e1cdf81c86e9fd6bdbfc3`; `origin/desktop` remained
+ `007f631613be43b3d00918c9e1e3cde58235099d`. A real normal merge produced
+ candidate `f07634ac61ba41d6f05e26c1a1f6b6feff2175a1`, with parents
+ `e2c92afc19c9f95b2581ea8bc46b8ad40ce98896` and
+ `a32cd9df9be96ae9b86e1cdf81c86e9fd6bdbfc3`. The expected merged tree was
+ independently checked as `5dea0c52f75b6eedb5c952bd9f7f4ca56f462ebf` before
+ this plan append. The only overlapping files are the i18n catalogs; the
+ upstream Workbench/AppShell/ChatPage/Composer/Sidebar behavior and the two
+ migration test fixtures are retained.
+- Independent pre-push spot-checks covered the three CI compatibility classes
+ and exhaustive dependency selection (`270` tests), 13 RuntimeHost/bootstrap
+ consumers, and the native credential fixture boundary. On the merged tree,
+ the focused Python CI compatibility, dependency, and observability command
+ passed `314` tests; Runtime-host passed `94` library, `25` bootstrap, and `5`
+ notification HTTP tests; the merged Workbench queue tests passed `106` UI
+ tests. Rust formatting and workspace Clippy passed. The opt-in hermetic
+ mock-upstream Model Hub suite passed `69` tests with `20` expected skips.
+ The migration E2E command requires the separately supplied offline engine
+ manifest; this workspace did not have that fixture. Its local attempt failed
+ closed at `engine_down`/`migration_native_busy`, before credential mutation,
+ confirming the fixture prerequisite rather than a production catalog or
+ native-auth bypass. The command was not retried against a network asset or
+ installed service.
+
+### Original-head review inventory and scope decision
+
+Review 5259095413 reviewed `92c600aa78f51e3b9ec48f185e5150a4f2ef3163`.
+The lane and orchestrator independently paginated all threads: two findings on
+one reviewed head, with no repeated class and no circuit breaker.
+
+- `PRRT_kwDOPbFPYs6kGKft` / 4055803241: handover authority accepted without a
+ validated desktop predecessor identity. Require that identity at the response
+ parser and test the bootstrap consumer; preserve valid desktop replacement.
+- `PRRT_kwDOPbFPYs6kGKfv` / 4055803243: readiness timeout discards successful
+ launch provenance. Keep receipt ownership independent of retry deduplication;
+ test timeout, late readiness, retry and scoped stop together.
+
+The orchestrator ratified both bounded fixes within the existing desktop delta.
+Neither requires a new lane, product direction, or lifecycle rewrite. A repeated
+class on the next reviewed head requires another orchestrator diagnosis before
+editing or pushing.
+
+### H3 circuit-breaker ruling: untagged Controller adoption
+
+Review `5259674396` reviewed `c7b749838181d443b19af4faa270f829f13c04fc` and
+added `PRRT_kwDOPbFPYs6kHQt4` / 4056230990 at `vibe/ui_server.py:3304`.
+The finding repeats the original predecessor-identity scenario on a later
+head: `vibe start` correctly reuses a healthy user-managed Controller without a
+desktop identity, but the newly started UI inherits the bundled identity and
+`/ready` reports a mismatch forever. The predecessor-ID boundary remains a
+hard authority boundary; the missing behavior is positive external adoption.
+
+The bounded closure keeps `/ready` as the authoritative service-lock and IPC
+chokepoint. After those checks pass, a healthy Controller with no
+`desktop_runtime_id` is an affirmative versioned external readiness response,
+even if the serving UI inherited a bundled tag. When that UI tag is valid, the
+response carries it separately as optional `desktop_ui_runtime_id`; this field
+records which UI artifact is serving and never identifies or authorizes the
+Controller. A truly external Controller/UI pair with no UI tag keeps the
+existing three-field response. A tagged Controller whose ID differs from the
+UI remains a five-field mismatch and can never authorize handover without a
+validated predecessor identity. Invalid identity, owner change, unavailable
+Controller, and not-ready responses remain rejected. No spawn-time environment
+rewrite, persistent adoption model, or new receipt protocol is introduced.
+
+The desktop consumers apply the same rule in both adoption paths. A bundled
+launcher receiving affirmative readiness without a Controller ID adopts it
+without handover, pruning, or scoped stop authority. Polling after the helper
+starts also accepts that external readiness; a tagged different Controller ID
+still follows the existing handover path. During uninstall, affirmative
+readiness with `desktop_ui_runtime_id` is always `Unknown`, including in a new
+host after the shell has been reopened, because the private UI may still be
+serving beside the external Controller. Older three-field no-ID peers remain
+`Unknown` whenever the host has local helper attempt/liveness evidence. A
+truly external three-field Controller/UI pair with no helper evidence retains
+`External` cleanup behavior.
+
+The required consuming transitions are:
+
+| Scenario | `/ready` identity | Bootstrap result | Handover/prune/stop | Uninstall decision |
+| --- | --- | --- | --- | --- |
+| Existing external Controller/UI | no IDs | adopt | none | `External` when the host did not launch it |
+| Bundled UI beside an untagged Controller | `desktop_ui_runtime_id` | adopt | none | `Unknown`; preserve private trees, including after reopen |
+| Bundled helper starts an older no-field peer | no IDs after launch | adopt during polling | none | `Unknown` while local liveness evidence remains |
+| Bundled helper and Controller share the expected ID | expected ID | adopt | prune superseded installs only | `Managed` |
+| Tagged Controller has a different ID | other valid ID | mismatch/handover through validated predecessor path | no authority from the body itself | existing managed/external rules |
+| Missing/invalid/not-ready identity | unavailable or invalid | reject or keep polling | no handover authority | fail closed when liveness is uncertain |
+
+Tests must cover the real Python reused-service/missing-UI path and its
+untagged `/ready` response, the Rust parser's exact three-field and
+`desktop_ui_runtime_id` payloads, polling adoption after a helper launch, and
+uninstall reaching `Unknown` while preserving private Runtime/backend trees,
+including after a fresh RuntimeHost reopen. Existing valid handover, no-ID
+mismatch rejection, receipt lifetime/refusal, fresh inactive cleanup, and
+safe successful cleanup remain part of this contract.
+
+The first H3 candidate exposed a boundary the initial ruling missed: the
+in-memory liveness fence disappears when the shell closes, so a later host
+cannot know that its bundled UI may still be using private files. The smallest
+stateless correction is to let the already authoritative `/ready` response
+carry the live UI identity separately. `desktop_ui_runtime_id` is optional in
+schema version 1, accepts the same validated lowercase hexadecimal identity as
+the Controller field, and is never used for handover, stop authority, managed
+classification, or pruning. Old valid payloads remain accepted; malformed or
+ambiguous new shapes fail closed. The orchestrator reproduced the failure as
+`adopt -> Unknown removal -> reopen -> External removal`, and authorized this
+producer/parser/consumer correction before commit or push.
+
+### Revised H3 candidate evidence before commit
+
+- The revised candidate remains limited to the producer, readiness parser and
+ direct RuntimeHost consumers, plus the shared contract fixture
+ `tests/fixtures/desktop_ready_external_controller_bundled_ui.json`. Python's
+ `/ready` producer test and `runtime.ui_server_healthy` read that same
+ affirmative external-Controller/bundled-UI shape; the Rust parser and
+ bootstrap test include it directly. The fixture therefore exercises the
+ actual cross-language field names and values rather than two independently
+ invented payloads.
+- `uv run pytest -q tests/test_desktop_runtime.py tests/test_internal_client.py`
+ passed `133` tests. This includes the real reused-service `cmd_start` path,
+ the single missing-UI spawn and reused receipt, valid and malformed optional
+ identity payloads, producer output, and `ui_server_healthy` acceptance of the
+ new shape. The Python tests reject null, uppercase, short, ambiguous and
+ extra-field identities.
+- RuntimeHost bootstrap consumers passed `cargo test --test bootstrap` with
+ `28` tests. `a_helper_adopts_untagged_readiness_after_launch_without_handover_or_pruning`
+ proves polling adoption after helper launch and the no-authority/Unknown
+ uninstall fence. `an_external_controller_with_a_bundled_ui_stays_unknown_after_shell_reopen`
+ starts the helper on the first host, drops that host, adopts the same
+ producer fixture in a fresh host, asserts one launch total, no handover or
+ prune, and `Unknown` on both removal attempts. The pre-existing
+ `unknown_runtime_ownership_blocks_private_file_removal` consumer still
+ proves that Unknown refuses deletion of private Runtime and backend roots.
+- Rust readiness unit tests passed `11` tests, full RuntimeHost library tests
+ passed earlier with `94` tests, and RuntimeHost Clippy with `-D warnings`
+ passed. `cargo fmt --all -- --check`, changed-Python Ruff, and
+ `git diff --check` passed. Cargo emitted only its existing permission warning
+ while attempting to clean a shared global cache; compilation, tests and
+ lint completed successfully. No notification, process-stop, spawn-environment,
+ persistence or predecessor-authority behavior was widened.
+- The earlier opt-in mock-upstream Model Hub suite passed `69` tests with `20`
+ expected skips. The migration E2E attempt remains accurately recorded as
+ `3 failed, 71 passed, 20 skipped` in the earlier evidence: the workspace
+ lacked the separately supplied offline engine manifest, and the run closed
+ at `engine_down` / `migration_native_busy` before credential mutation. This
+ observes the fixture limitation; it does not prove a causal production
+ authentication failure and was not retried against a network asset or the
+ installed service.
+
+The orchestrator independently reviewed all eight candidate paths at the
+`c7b749838181d443b19af4faa270f829f13c04fc` base and approved this bounded fix
+for commit and push. Its consuming spot-check passed `133` Python tests, `28`
+bootstrap tests, `11` readiness-parser tests, and the existing
+`unknown_runtime_ownership_blocks_private_file_removal` consumer (`40` Rust
+checks in total). The prior destructive transition `[Unknown, External]` is
+now covered by the fresh-host regression and expects `[Unknown, Unknown]`.
+The remote desktop was still `c7b749838181d443b19af4faa270f829f13c04fc`,
+and the three findings-bearing review heads remain H1 `92c600aa78`, H2
+`007f631613`, and H3 `c7b749838`, with the H3 thread still open until the
+pushed fix is evidenced.
+
+### Resumption for the 2026-09-22 integration cycle
+
+- 2026-09-22: The owner reopened PR #2062 for conflict resolution. The clean
+ desktop head is `8440cf81737be5db46a16992ecce41fe29beb866`; the actual remote
+ `master` source is `16bf1be3f93cd3cb855da2dd1b7133932acc0363`. GitHub's PR
+ base ref remains stale at the earlier `3994d18d`, so this cycle uses explicit
+ remote refspecs and the SHA returned by `git ls-remote`.
+- The new cycle has one lane-owned combined PR/lint/desktop-shell Watch,
+ `54efbc6d5cec`, with cursor
+ `pr-2062-sesy9cb4ht9nq-20260922.json`. Both the supervisor and bundled waiter
+ use `timeout 0`; the cursor is new for this cycle and will not be reseeded.
+ The prior 2026-09-20 cursor and retired Watch remain untouched.
+- The merge probe reports one textual conflict in
+ `tests/test_ui_server_install.py`. Resolution must retain the desktop
+ three-backend parameterization of
+ `test_install_job_fails_when_runtime_refresh_fails`, master's hermetic
+ `_agent_runtime_fingerprint -> None` fixture stub, and all newer measured
+ runtime refresh tests. Automatically merged changes at the shared controller,
+ Codex agent, API/CLI/UI server, UI API context/backend lifecycle, i18n, and
+ related test boundaries require semantic audit; no redesign or unrelated
+ behavior change is authorized.
+- This cycle remains a real merge into the existing desktop ancestry. The first
+ push is held until the orchestrator independently spot-checks a concrete
+ candidate SHA/diff and a consuming test. Required evidence is focused
+ hermetic Python installation/runtime/IPC/backend coverage, relevant UI tests
+ and build, desktop Rust lifecycle tests/format/lint, and changed-Python Ruff.
+- 2026-09-22: The owner approved the initial test distribution path: use the
+ existing manually triggered package workflow with a selected SemVer and
+ source ref, macOS ad-hoc app signing inside an unsigned/unnotarized DMG, and
+ unsigned Windows NSIS installers. The README records Gatekeeper/SmartScreen
+ prompts, `SHA256SUMS`/`SIGNATURE` evidence, 14-day artifact retention, the
+ self-contained runtime/no Python or Node prerequisite, and manual replacement
+ upgrades. The optional trusted-signing path remains unchanged; this decision
+ does not authorize public Release publishing, updater work, new certificates,
+ or OS-protection bypasses.
+
+### Resumed merge candidate evidence
+
+- 2026-09-22: A real non-fast-forward merge of
+ `16bf1be3f93cd3cb855da2dd1b7133932acc0363` completed as
+ `5589edc71292921281f95d072916628a9790fa6a`, with parents
+ `45aa0208e8acda3a7d51e1e5b2052e90a824743e` and
+ `16bf1be3f93cd3cb855da2dd1b7133932acc0363`. The one conflict in
+ `tests/test_ui_server_install.py` keeps the desktop three-backend refresh
+ failure parameterization, master's `_agent_runtime_fingerprint -> None`
+ hermetic stub, and all measured-runtime refresh cases. No conflict markers or
+ unresolved paths remain.
+- The automatically merged shared boundaries were audited. Master changes to
+ Model Hub credential migration/persistence, Codex steering reconciliation,
+ caller authorization, queued delivery projections, Workbench/sidebar/API
+ context, and i18n remain present. Desktop `vibe.desktop_backends`,
+ `vibe.desktop_runtime`, FastAPI UI server behavior, rolling backend refresh,
+ and native Runtime ownership/readiness paths remain present. No migration or
+ allocated-ID namespace collision was introduced.
+- Candidate validation passed: Python desktop/runtime, installation/upgrade,
+ IPC, FastAPI/API, backend rolling-refresh, and observability consumers passed
+ `1389` tests with `5` skips; Model Hub/native-auth/Codex consumers passed
+ `1610` tests, `68` warnings, and `47` subtests. The merged UI focused suite
+ passed `125` tests; UI test typechecks and `npm run build` passed. Desktop
+ i18n validation and bootstrap `npm run build` passed. Runtime-host passed
+ `94` library, `28` bootstrap, and `5` notification HTTP tests; `cargo fmt
+ --all -- --check` and workspace Clippy with `-D warnings` passed. Changed
+ Python Ruff passed. The only native warning was the existing inability to
+ clean one shared global Cargo cache entry due to permissions; it did not
+ affect compilation, tests, or lint.
+- This candidate is ready for the orchestrator's independent diff and consuming
+ test spot-check. It has not been pushed; the first push remains held. The
+ latest remote desktop still needs an immediate explicit-refspec check before
+ any authorized push.
+
+### H4 readiness-loss transition correction
+
+- 2026-09-22: The exact-head Codex review identified a real monitor boundary
+ defect: three consecutive `/ready` misses discarded a valid startup receipt,
+ even though readiness loss supplied no process-exit or ownership-loss
+ evidence. The repeated receipt/provenance class was diagnosed at the
+ orchestrator level before this bounded edit; no receipt schema, persistence,
+ parser, launcher signaling policy, or lifecycle redesign was introduced.
+- The shared RuntimeHost transition is now named
+ `release_after_readiness_loss`. It releases only a completed helper's retry
+ slot. A pending helper remains the single deduplicated launch, a valid
+ `started` receipt remains paired with its original resolved launcher, and
+ `runtime_may_be_running` remains set. Scoped `OwnershipLost` still revokes
+ only that receipt and preserves the unknown-liveness fence; a successful
+ scoped stop clears the state.
+- Private removal now fails closed whenever local launch/liveness evidence is
+ present but readiness is unavailable. A retained receipt therefore cannot
+ make `BundledVibeLauncher::remove_private_runtime(Managed)` invoke unscoped
+ handover. Affirmative managed readiness remains sufficient for managed
+ cleanup, while external/UI-only readiness and unknown readiness retain their
+ existing boundaries.
+- The production shell monitor uses the shared transition after its existing
+ generation and activity checks. RuntimeHost tests cover retained receipt,
+ explicit scoped stop, pending-helper deduplication, replacement receipt
+ authority, reused/receipt-less/failed no-authority outcomes, unknown removal,
+ and successful cleanup. The shell crate test drives the same recovery
+ transition after three misses with a real RuntimeHost and confirms that a
+ pending helper is not overlapped. The former
+ `confirmed_runtime_loss` expectation was corrected to distinguish readiness
+ loss from confirmed process loss.
+
+### Latest master refresh: #2118 lint-gate test-only delta
+
+- 2026-09-22: Explicit refspec refresh moved `origin/master` from
+ `335f62e6c15987d0ab72f6139c16fe49eea706e8` to
+ `4b964fef223862c2cf7d5cec852ac0d3aa64e323` (#2118). The delta is one
+ test-only path, `ui/scripts/lintBaseline.test.mjs`: its temporary integrity
+ probe now explains its ownership and asserts that the diagnostic contains one
+ inline-policy finding. It changes no desktop runtime, shell, release, or
+ product behavior.
+- The real merge into the desktop candidate is conflict-free and has parents
+ `deedb50b4bb814b180953ebdbf14b64350e51ff3` and
+ `4b964fef223862c2cf7d5cec852ac0d3aa64e323`. The existing release and H4
+ implementation paths remain unchanged. Focused Vitest coverage for the
+ incoming file passed with 33 tests; GitHub lint and desktop-shell remain the
+ authoritative pushed-head checks.
+
+### H5 review round: reconciling marker, identity reuse, login-item cleanup
+
+- 2026-09-22/23: The exact-head Codex review on `d65847228` opened three
+ threads. All three were diagnosed as independent local defects, not one
+ repeated root-cause class, so the circuit breaker did not trip: one missing
+ status marker, one parser verdict, and one uninstall ordering gap.
+- **Model Hub reconciling flag.** `reconcile_startup_dependencies` installed
+ the Model Hub engine without ever marking that dependency as reconciling, so
+ the dependency surface showed a settled state during a live install. The
+ marker is now set before the install and cleared in a `finally`, matching the
+ other dependencies in the same function. The consuming test observes
+ `dependencies_status(...)["reconciling_dependencies"]` from inside the
+ installer callback and asserts it is `["model-hub-engine"]` while the install
+ runs and empty afterwards, so a missing set or a missing clear each fail.
+- **`runtime_identity_invalid` reuse.** `_ui_ready_identity_state` mapped every
+ well-formed 503 to "incompatible but adoptable", which let the launcher adopt
+ a UI process that had already declared its runtime identity invalid. That one
+ code now returns `None`, and because `_ui_server_compatible` is
+ `readiness is not None`, the process is treated as incompatible and replaced.
+ Evidence is two layers: the predicate test, and a `start_ui` test that drives
+ the real replacement path and asserts the stale PID was stopped and a new one
+ spawned.
+- **Uninstall login item.** Confirmed uninstall deleted the private Runtime and
+ exited without clearing an opt-in **Start at Login** registration, leaving the
+ OS launching an application that no longer exists. The confirmed uninstall now
+ clears an enabled registration first and fails closed: a failure to inspect or
+ to clear it returns through the existing uninstall failure/recovery path
+ instead of deleting the Runtime behind a stale entry.
+- That decision is the single function `remove_runtime_after_login_cleanup`,
+ which owns both outcomes — it calls the removal effect or the failure effect,
+ never both. The duplicated recovery-plus-failure-dialog pair became one
+ `report_runtime_removal_failure` helper, so the login-cleanup failure returns
+ through literally the same path as an async removal failure rather than a
+ parallel copy. No second uninstall lifecycle, no RuntimeHost receipt change,
+ and no process-stop policy change was introduced.
+- The consuming test drives that production function with recorded effects and
+ asserts the exact effect sequence for each of the four inputs: enabled clears
+ then removes; already disabled removes without any disable call; a disable
+ failure and an unreadable registration each report failure with no removal.
+ Because the shell wires notification stop, `remove_private_runtime`, the
+ success dialog and `exit_shell` entirely inside the removal effect, a run that
+ never produces `RemoveRuntime` is a run with no success dialog and no exit.
+ The earlier draft's source-substring ordering assertion was removed: it
+ asserted the order of two identifiers in a file, which cannot distinguish the
+ fail-closed path from a silently continuing one.
+- The extracted boundary is bound to production by the build, not by a string
+ match: CI runs `cargo clippy --workspace --all-targets --all-features -D
+ warnings`, so a version of the shell that stopped calling the function would
+ fail on dead code rather than keep a green test.
+- The draft also renamed the removal handle and the host/origin bindings, which
+ silently broke two pre-existing `shell_boundaries.rs` invariants — the
+ uninstall path must retain `notifications::stop(&confirmation_app)` and
+ `host.remove_private_runtime(active_origin.as_ref()).await`. Both original
+ names are restored; the notification stop now happens at the point the shell
+ commits to removal, and the async handle is cloned there.
diff --git a/docs/plans/desktop-notifications-implementation.md b/docs/plans/desktop-notifications-implementation.md
new file mode 100644
index 000000000..ff8645419
--- /dev/null
+++ b/docs/plans/desktop-notifications-implementation.md
@@ -0,0 +1,55 @@
+# Desktop notification consumer implementation
+
+## Change contract
+
+Implement `desktop-notifications-sse.md` on the shell side without changing
+Python, HTTP routes, loopback authentication, WebView IPC, or capabilities.
+The orchestrator approved OS-default activation for v1 on 2026-09-11;
+cross-platform explicit activation requires a separate native adapter.
+The orchestrator also approved the existing locked chrono 0.4 dependency
+for durable timestamp parsing (std only, no clock).
+
+## Data flow and ownership
+
+After readiness succeeds, the shell owns one cancellable SSE task for the
+validated Runtime origin. Transport loss retries only that task with capped
+backoff. Three readiness failures, Stop, Uninstall, and Quit cancel it.
+Window visibility and the stored notification preference only suppress
+delivery; they neither disconnect the stream nor queue events for later.
+The shell retains bounded filter state across stream reconnections.
+
+The Tauri-free runtime-host parses production SSE framing, allows only the
+two frozen event classes, deduplicates each class at 512 keys/24h, and
+computes duration from durable timestamps. Missing stamps trigger one
+bounded detail GET; missing/invalid stamps then fail closed. Scheduled
+and watch runs are the only duration-independent kinds. Generic localized
+copy carries no untrusted Runtime text.
+
+## Verification plan
+
+- Fake SSE collaborators under a virtual clock prove allow-list filtering,
+ suppression without replay, duration independent of arrival/attachment,
+ refetch-once/fail-closed, bounded approval/run retention, and reconnect.
+- A loopback fake HTTP server proves framing, bounded reads, redirect refusal,
+ exact routes, and no replay cursor on reconnection.
+- Shell tests prove lifecycle ownership, preference persistence against
+ test-owned paths, and notification intentions without calling the OS.
+- Boundary tests keep all notification privileges away from WebViews.
+- Both native catalogs use the frozen keys and matching placeholders.
+- Run desktop npm install/build/i18n, UI build, and Rust fmt/clippy/tests
+ across the workspace/all features before PR handoff.
+
+## Integration acceptance
+
+Real OS permission, delivery, OS-default activation, hidden-to-tray behavior,
+and menu interaction remain packaged macOS/Windows acceptance. The producer
+PR #1982 adds terminal timestamp fields independently and must merge first.
+
+## Local evidence
+
+Desktop npm install/build/i18n, UI npm install/build, workspace all-features
+Rust tests, and all-target/all-feature clippy with warnings denied pass.
+The notification suites exercise the production HTTP adapter against an
+isolated loopback server and drive filter/reconnect behavior with a virtual
+clock. No test submits an OS notification or starts the user's Runtime.
+Packaged OS acceptance is deliberately not claimed by these checks.
diff --git a/docs/plans/desktop-notifications-sse.md b/docs/plans/desktop-notifications-sse.md
new file mode 100644
index 000000000..16d093362
--- /dev/null
+++ b/docs/plans/desktop-notifications-sse.md
@@ -0,0 +1,289 @@
+# Desktop notifications over Workbench SSE
+
+## Status
+
+Frozen implementation contract for gap G4. Companion to
+`desktop-product-gaps.md` (G4) and `desktop-start-receipt.md` (ownership of
+the Runtime is already settled; this contract does not reopen it).
+
+Owner: Avibe core
+Date: 2026-09-10
+Baseline: `desktop` branch after #1975 / #1977 (tray + start-receipt).
+
+## Product outcome
+
+When the Avibe window is unfocused or closed (tray still alive), the user
+gets a native OS notification for the two classes of event that actually
+need them to look:
+
+1. A Vault request that is waiting on them (`approval.requested`).
+2. A background agent run that has reached a terminal state
+ (`run.terminal`), only if the run was clearly backgrounded or ran
+ longer than ~30 seconds.
+
+Default on. The tray has a checkable "Notifications" item that persists
+the preference. System Focus / Do Not Disturb is left to the OS; Avibe
+does not reimplement it.
+
+Notification activation follows the OS-default behavior described in
+**Click** below. Deep-link navigation into a specific session
+(`avibe://session/<id>`) is G5 and is **not** in this slice.
+
+## Why SSE, not polling
+
+The shell already probes `GET /ready` every two seconds after navigation;
+that loop is the liveness signal ("is the Runtime still there?").
+Attention ("something needs you") is a different job. Polling it off
+`/ready` would:
+
+- bound notification latency to the probe period (bad for blocking
+ Vault approvals);
+- tax a tray-resident Agent OS with permanent empty-cycle HTTP;
+- fork the product's event model: Workbench already consumes SSE,
+ desktop notifications would pull.
+
+v1 therefore **reuses the existing event source** (`GET /api/events`)
+and leaves `/ready` as liveness-only.
+
+## Frozen transport
+
+### Endpoint
+
+`GET {origin}/api/events` on the adopted Runtime origin (the same
+loopback origin the shell already validated and navigated to).
+
+No new HTTP route. The Workbench EventSource client at
+`ui/src/context/ApiContext.tsx` already opens this path with no extra
+auth on loopback; the shell does the same. Adding a cookie or token
+requirement to `/api/events` is a breaking change for both clients and
+is out of scope.
+
+SSE framing already in production (`vibe/ui_server.py::workbench_events`):
+
+- handshake: `: stream connected` comment, then `event: connected`;
+- 15-second keep-alive comment (`: ping`) so proxies do not idle-kill;
+- each application event: `event: <type>` + `data: <json>` where the
+ JSON is `{"type": <type>, "data": <payload>}` (see `sse_broker.py`).
+
+The shell parses this framing; it does not invent a second protocol.
+
+### Connection ownership
+
+The **shell** owns the SSE connection, not the WebView.
+
+- Opened once the Runtime is adopted/started and `/ready` has succeeded.
+- Survives window close (the tray is the user's handle on a living
+ Runtime; notifications must still arrive).
+- Torn down when the shell gives up on the Runtime: three consecutive
+ `/ready` failures (existing bootstrap recovery), explicit Stop of an
+ owned Runtime, Uninstall, or Quit-and-stop. Adopted Runtimes that
+ outlive the shell keep running; the SSE dies with the shell, which
+ is the same visibility the user already accepted by quitting.
+- Reconnect with bounded backoff on stream drop, independently of the
+ `/ready` probe. A reconnect does not replay history (the broker has
+ no replay); the shell must tolerate missed events. Vault pending
+ state is recoverable on click by opening the Workbench.
+
+`/ready` probing and the SSE are two loops with one shared origin.
+Neither substitutes for the other: a live SSE with a failing `/ready`
+still triggers bootstrap recovery; a live `/ready` with a down SSE
+retries the stream and does not take the window back to bootstrap.
+
+### Filtering, not a second bus
+
+The broker is a global fan-out. The shell **subscribes to the existing
+stream and filters**. It does not ask Python for a dedicated attention
+channel in v1. Adding `GET /api/desktop/attention` would be a contract
+v2 if the filter ever becomes a product-logic burden the shell should
+not carry.
+
+v1 filter (exact event type strings, already published):
+
+| SSE `event` | Payload fields used | Notification class | When it fires |
+| ------------------ | ------------------------------------------- | --------------------- | -------------------------------------- |
+| `vaults.updated` | `request_id`, `request_status` | `approval.requested` | `request_status == "pending"` and `request_id` present |
+| `runs.updated` | `run_id`, `status`, `session_id`, `run_type`| `run.terminal` | `status` in `{succeeded, failed, canceled}` AND the run is "background" (see below) |
+
+Every other event (`message.new`, `session.activity`, `queue.updated`,
+`inbox.unread.changed`, `show.event`, keep-alives, unknown types) is
+ignored by the notification path. The filter is an allow-list: a new
+event type never becomes a notification by accident.
+
+### "Background" for `run.terminal`
+
+A terminal `runs.updated` notifies iff **at least one** of the two
+properties below holds. This is not an allow-list of product verbs
+and is not extended in v1 (a new always-background kind is a contract
+revision). `run_type=agent_run` — including default async
+`vibe agent run` — is not a special case: it follows the duration
+rule only. v1 does not add `visibility` to the SSE payload.
+
+A terminal `runs.updated` notifies if **either**:
+
+1. **Duration ≥ 30s**, measured as
+ `completed_at − started_at` (both durable, ISO-8601 on the
+ terminal event). `completed_at` is the event's `completed_at` if
+ present, otherwise the terminal `updated_at`. Never "receipt time
+ minus started_at" — a two-second run delivered a minute later
+ (sleep, stall, reconnect) must not cross the threshold. If the
+ terminal event omits `started_at` or the completion timestamp, the
+ shell refetches `GET /api/harness/runs/<run_id>` once. Still
+ missing either stamp → fail closed (no notify).
+ or
+2. **`run_type` ∈ `{scheduled, watch}`** even under 30s (stored
+ values from `core/scheduled_tasks.py` / `core/watches.py`; `task`
+ is a definition kind, not a run_type).
+
+Python adds `started_at` and `completed_at` (or always-populated
+terminal `updated_at`) on terminal `runs.updated`. No "please
+notify" flag, no `visibility` field in v1.
+
+### Dedup
+
+- `approval.requested`: key = `request_id`. Same pending request is
+ never notified twice **while the key is retained**. Non-pending
+ transitions drop the key when observed. Because the broker has no
+ replay, a reconnect can miss that transition — so this set is
+ **bounded the same way as run keys** (LRU or TTL; default 512 or
+ 24h). Do not rely on seeing a later status to bound memory. A
+ dropped key may notify again if the same request is still pending;
+ that is acceptable (at-least-once), not a leak.
+- `run.terminal`: key = `run_id`. Terminal is once per key while the
+ key is retained. Retention is **bounded** (LRU or TTL, frozen
+ default: 512 entries or 24 hours, whichever hits first). The bound
+ only needs to cover repeated terminal publications of the same run
+ (SSE bursts / reconnect duplicates), not process lifetime. A
+ tray-resident shell must not grow this set without bound.
+
+A notification is suppressed (not queued) when:
+
+- the Avibe window is focused and visible; or
+- the tray "Notifications" item is unchecked.
+
+System DND / Focus is the OS's problem.
+
+## Frozen presentation
+
+### Copy lives in the shell, keyed by class + locale
+
+Existing SSE payloads are refetch hints (`run_id` / `request_id`), not
+finished user copy. The shell therefore owns notification title/body,
+using the same locale catalog pattern as the tray (`sys-locale` →
+`desktopBootstrap` keys in `ui/src/i18n/{en,zh}.json`, verified by
+`npm run test:i18n`).
+
+v1 keys (names frozen; wording is i18n content, not contract):
+
+- `desktopBootstrap.notifications.approvalRequested.title`
+- `desktopBootstrap.notifications.approvalRequested.body`
+- `desktopBootstrap.notifications.runSucceeded.title`
+- `desktopBootstrap.notifications.runSucceeded.body`
+- `desktopBootstrap.notifications.runFailed.title`
+- `desktopBootstrap.notifications.runFailed.body`
+- `desktopBootstrap.notifications.runCanceled.title`
+- `desktopBootstrap.notifications.runCanceled.body`
+- `desktopBootstrap.notifications.toggle` (tray menu label)
+
+Bodies may include the `session_id` / `run_id` as a short suffix when
+present; they must not interpolate unsanitized Runtime strings into
+the OS notification (the payload is untrusted process output on its
+way to a privileged surface, same rule as refused origins).
+
+### Plugin and permission
+
+`tauri-plugin-notification` on the shell. Permission prompts are the
+OS's (macOS notification permission on first fire). The plugin is
+invoked from Rust, never from the WebView.
+
+**No new IPC command, no capability widening.** Notifications are
+shell-privileged the same way the tray is: the Workbench page cannot
+trigger them. `shell_boundaries.rs` gains an assertion that the
+notification path does not grant any `remote` capability.
+
+### Click
+
+v1 ships **OS-default activation**, not a shell click callback: on macOS,
+clicking a banner activates the sending app by default (approximately
+show + focus); on Windows, unpackaged-toast click behavior is OS/backend
+dependent and may only dismiss. The notification plugin's desktop API
+does not expose an action callback. Explicit cross-platform click =
+`show` + `unminimize` + `set_focus` is **v2 with native activation adapter
+(macOS UNUserNotificationCenter delegate + Windows toast activation)**.
+No Workbench navigation or simulated click wiring is included in v1.
+
+## Frozen architecture split
+
+```
+Python Runtime Shell (Rust)
+────────────── ────────────
+SSEBroker ──GET /api/events──► attention filter
+ vaults.updated (allow-list)
+ runs.updated + 30s / run_type rule
+ (everything else ignored) + dedup
+ + focus/pref gate
+ └── tauri-plugin-notification
+/ready probe (existing, 2s) liveness only, never attention
+```
+
+Python changes in v1: include `started_at` and `completed_at` (or
+guarantee terminal `updated_at`) on terminal `runs.updated` payloads
+(`run_updated_payload` / `publish_run_updated`). Additive fields on
+the existing payload, not a new route. Workbench refetch consumers
+ignore unknown fields.
+
+Rust changes live in `desktop/runtime-host` (filter, dedup, reconnect
+— Tauri-free, testable) and a thin `src-tauri` adapter that fires the
+plugin and reads window-focus / tray-pref state.
+
+## Tests (invariants, not enumerations)
+
+- Filter allow-list: given a stream that mixes ignored types with one
+ `vaults.updated {request_status: pending, request_id}` and one
+ terminal `runs.updated`, only those two classes produce a
+ notification intent. A newly invented event type in the same
+ fixture must not.
+- Dedup: two identical `request_id` pendings → one intent; a
+ non-pending transition then a new pending with the same id → a
+ second intent.
+- Duration property: `completed_at − started_at` (or terminal
+ `updated_at − started_at`) ≥ 30s → intent for a non-scheduled run;
+ a 2s run whose event arrives 60s later does **not**. Missing either
+ stamp after one refetch → no intent. `run_type=scheduled`/`watch`
+ → intent even under 30s. A new run_type in the fixture must not
+ notify unless it is those two or the duration property hits.
+- Dedup bound: both approval and run key sets stay within 512
+ entries / 24h; inserting past the bound drops the oldest, and a
+ later duplicate of a dropped key may notify again.
+- Focus gate: window focused + visible → no intent even on a matching
+ event.
+- Reconnect: stream drop then restore does not panic, does not
+ replay, does not take bootstrap recovery by itself.
+- Boundary: `shell_boundaries` still forbids remote capabilities;
+ notification code is not reachable from a navigated Workbench page.
+- i18n: the new keys exist in both catalogs with matching
+ placeholders (`npm run test:i18n`).
+
+Drive the filter with a fake SSE collaborator under tokio's virtual
+clock (same pattern as `runtime-host/tests/bootstrap.rs`) so the 30s
+threshold is exercised in microseconds.
+
+## Explicit non-goals (v1)
+
+- A new HTTP route or a Python "please notify" flag.
+- Deep-link click targets (G5).
+- Notifying on every chat message, every `session.activity`, or
+ foreground turns that finish quickly.
+- Replaying missed events after reconnect.
+- Changing `/api/events` auth.
+- Windows-vs-macOS copy differences beyond the shared catalog.
+
+## Sequencing
+
+Depends on the tray (#1975, merged): the Notifications toggle lives
+on the same menu as "Start at Login", and window-hidden-to-tray is
+the state in which notifications matter.
+
+Does not depend on G1 signing or G2 auto-update.
+
+Does not block G5. A notification-specific deep-link target follows the
+native activation adapter rather than assuming a v1 click callback exists.
diff --git a/docs/plans/desktop-product-gaps.md b/docs/plans/desktop-product-gaps.md
new file mode 100644
index 000000000..19523ef93
--- /dev/null
+++ b/docs/plans/desktop-product-gaps.md
@@ -0,0 +1,197 @@
+# Desktop Product Gaps
+
+## Status
+
+- Owner: Avibe core
+- Date: 2026-09-10
+- Baseline: `desktop` branch after #1975 / #1977 / #1971 / #1972
+ (tray + start-receipt + notarization preflight; local docs head
+ tracks origin/desktop @ `937d23e35` plus this planning slice)
+- Scope: what the desktop product still lacks to read as a first-class desktop
+ application, not a windowed browser. The shell engineering base (loopback
+ adoption, capability boundary, private Runtime, lazy backends) is sound and
+ is **not** re-litigated here.
+- Companion docs: `tauri-desktop-vertical-slice.md` (original slice),
+ `desktop-backend-lazy-install.md` (frozen backend-install contract),
+ `desktop-notifications-sse.md` (G4), `desktop-deep-links.md` (G5),
+ `desktop-window-state.md` (G6)
+
+## Baseline: what already exists
+
+A Tauri v2 thin shell (window + bootstrap screen) that adopts or starts one
+local Avibe Runtime, hands the window to the Workbench, and verifies integrity
+of the installed private Runtime on every launch. Self-contained packages
+embed CPython, the Avibe wheel, locked Python dependencies, Node, and npm.
+CI produces unsigned acceptance artifacts for macOS arm/x64 and Windows x64.
+
+What the baseline deliberately does **not** have: production distribution
+signing (G1 remaining layers), auto-update, notifications, deep links,
+native multi-window, or persisted window state. Tray / Runtime lifecycle
+visibility and launch-at-login **shipped** in #1975.
+
+## P0 — distribution and trust (the release gate)
+
+### G1. Code signing and notarization
+
+- Problem: unsigned artifacts are stopped by Gatekeeper (macOS) and flagged by
+ SmartScreen (Windows). There is currently no way to ship to a real user.
+- Work: introduce a `desktop-package-sign.yml`-style manual workflow or extend
+ `desktop-package.yml`: macOS Developer ID signing + notarytool notarization +
+ stapling; Windows EV/OV certificate signing of the NSIS installer. Secrets
+ via GitHub Environments; artifacts published as Draft releases only.
+- Acceptance: a DMG and an NSIS installer, both signed, open on a clean
+ machine with no security warning and no right-click override.
+- Estimate: M. The Rust/Tauri side is configuration; the cost is certificate
+ procurement and Apple/Windows account plumbing.
+- Risk: certificate processes (Apple Developer ID, EV certs) have lead time;
+ start procurement first.
+
+### G2. Auto-update
+
+- Problem: today an update means "download and replace the app". No security
+ fix can reach an installed base.
+- Work: integrate `tauri-plugin-updater` against a JSON endpoint (GitHub
+ Releases draft flow or a dedicated channel). Decide the signing story for
+ update artifacts (updater signature key, independent of G1 codesigning).
+ Respect the version identity already stamped by `desktop-package.yml` input.
+ The private Runtime install path is already content-addressed and versioned,
+ so app replacement composes with it by design.
+- Acceptance: an installed app detects a newer published artifact, downloads,
+ verifies, and applies it; user state (`~/.avibe`) and private Runtime slots
+ survive; rollback path is the previous app bundle reinstalling its payload.
+- Estimate: M. Endpoint + key management + first signed release is the bulk.
+- Depends: G1 (signed artifacts worth updating to).
+
+### G3. Tray / Runtime lifecycle visibility
+
+- **Shipped** in #1975 (`install_native_tray`: live Runtime state, Open /
+ Stop / Quit with receipt-gated stop, Start at Login default off).
+ Remaining work is real-OS verification on a signed build, not a new
+ feature. G4's Notifications toggle lands on this same menu.
+
+## P1 — system integration (the native feel)
+
+### G4. Desktop notifications
+
+- Problem: task completion, approval requests, and errors are the core
+ feedback loop of an agent OS and are invisible when the window is not
+ focused (which is most of the time for long-running work).
+- Work: frozen in `desktop-notifications-sse.md`. The shell owns an SSE
+ connection to the existing `GET /api/events` (not a new route, not polling
+ `/ready`); filters an allow-list (`vaults.updated` pending →
+ `approval.requested`; terminal `runs.updated` that ran ≥30s or has
+ `run_type` in `{scheduled, watch}` → `run.terminal`); fires
+ `tauri-plugin-notification`. Connection survives window-close-to-tray.
+ Default on, tray toggle, OS DND untouched. Click focuses the window (deep
+ links are G5).
+- Acceptance: with the window unfocused or hidden to tray, a pending Vault
+ request and a long/background run completion each produce one native
+ notification; duplicates of the same `request_id`/`run_id` do not; a
+ focused visible window produces none; toggling the tray item off produces
+ none. No new IPC / no remote capability.
+- Estimate: M. Event source exists; the work is the shell-owned stream,
+ filter/dedup, reconnect, and the plugin/permission prompt.
+- Depends: tray (#1975, merged). Does not depend on G1/G2.
+
+### G5. Deep links (`avibe://`)
+
+- Problem: no path back into a specific session, Show Page, or approval from
+ outside the app (IM messages, emails, notifications). The Workbench is only
+ reachable as a single entry URL.
+- Work: frozen in `desktop-deep-links.md`. Scheme `avibe`, four kinds
+ (`session`, `show`, `settings`, `vaults/request`) mapping onto existing
+ Workbench routes. Hot path extends the existing single-instance callback;
+ cold path stashes the target until bootstrap navigates. Delivery is
+ same-origin in-window navigation — no new IPC, no capability widening.
+ Malformed links are dropped and never quoted into the WebView. IM/https
+ producers are not switched in v1.
+- Acceptance: `avibe://session/<id>` focuses the running app and opens that
+ chat; a cold start finishes bootstrap then lands on it; unknown or
+ malformed URLs do nothing visible in the Workbench. Click-on-notification
+ locating is a G4 follow-up, not this slice.
+- Estimate: M. Parser + stash/apply + scheme registration; security review
+ of untrusted argv.
+- Independent of G1/G6. G8 may later reinterpret `show` as a torn-out
+ window; the grammar stays.
+
+### G6. Window state persistence
+
+- Problem: the window always opens 1200×800 centered. Every desktop user
+ notices within a week.
+- Work: frozen in `desktop-window-state.md`. `tauri-plugin-window-state`
+ on the native frame (`x/y/width/height/maximized` per window label).
+ Full-screen/Spaces are not restored. Off-screen frames clamp so the
+ title bar is visible and size ≥ 880×600. Bootstrap and Runtime
+ navigation must not reset the restored frame.
+- Acceptance: move and resize, quit, relaunch → same frame; unplug the
+ display the window was on → window still visible, not smaller than
+ minimum. Hide-to-tray then Open restores the last shown frame.
+- Estimate: S.
+- No dependencies. Do this before G8 so new windows inherit the store.
+
+### G7. Launch at login (optional, off by default)
+
+- **Shipped** in #1975 (tray checkable "Start at Login", default off).
+ Remaining work is real-OS verification on a signed build, not a new
+ feature.
+
+## P2 — polish and reach
+
+### G8. Multi-window — deferred
+
+- **Decision (2026-09-10):** do not implement native multi-window. Keep the
+ current single-WebView shell wrapping the Workbench SPA. Session switching,
+ Show Pages, and Settings stay in-SPA.
+- Why: every frozen v1 contract (tray, start-receipt, G4 SSE, G5 deep
+ links, G6 window state) already holds at N=1. Native multi-window is not
+ "browser tabs"; it requires a singleton-Runtime + multi-WebView
+ lifecycle (only the main window bootstraps; extra windows are remote
+ from frame one and must never gain bootstrap IPC; closing them must not
+ stop the Runtime). That lifecycle is unverifiable without a second
+ window, so it ships in the same slice as the first extra window — not
+ ahead of it.
+- Trigger to reopen: a demonstrated need to pin a Show Page on another
+ display. First slice then is "settings window + torn-out Show Page",
+ not per-session windows. Until that trigger, Workbench split-pane (web
+ + desktop) is the cheaper way to sit two sessions side by side.
+- Estimate when reopened: M–L, lifecycle invariants + two window kinds.
+
+### G9. macOS Universal Binary
+
+- One DMG for both architectures instead of two (lipo the app binaries;
+ runtime payloads are per-arch and can stay separate resources or be
+ universal-merged).
+- Estimate: S–M, mostly packaging automation. Low priority while dual-DMG
+ works.
+
+### G10. Accessibility and shortcuts
+
+- Keyboard access to the full Workbench under WKWebView/WebView2, global
+ hotkey to summon the window, standard cut/copy/paste menu wiring on macOS.
+- Estimate: M, spread thin. Audit first, fix by surface.
+
+### G11. Diagnostics surface
+
+- `vibe doctor` and logs exist; the desktop has no "open logs / run
+ diagnostics" affordance in-app. Pairs naturally with the tray menu (G3).
+- Estimate: S (tray menu already exists).
+
+## Explicit non-goals for this phase
+
+- Mobile (per the original slice doc).
+- Auto-updating agent backends from the app (frozen contract in
+ `desktop-backend-lazy-install.md` keeps backends independent).
+- Rewriting Workbench behavior for desktop: everything above is shell-layer
+ and composes with the replaceable-shell constraint.
+
+## Suggested sequencing
+
+1. G1 remaining signing layers + certificate procurement (longest lead)
+2. G2 auto-update (needs G1; ship with the first signed release)
+3. G6 window state + G5 deep links (in flight; no G1 dependency)
+4. G4 notifications (depends on shipped tray)
+5. P2 items by demand; G8 stays deferred until a Show Page needs another display
+
+The deliberate observation from the review: every gap is shell-layer. The
+thin-shell bet held — the missing work is breadth on one boundary, not
+rework under it.
diff --git a/docs/plans/desktop-run-terminal-timestamps.md b/docs/plans/desktop-run-terminal-timestamps.md
new file mode 100644
index 000000000..0193ac5c2
--- /dev/null
+++ b/docs/plans/desktop-run-terminal-timestamps.md
@@ -0,0 +1,55 @@
+# G4 terminal run timestamp producer
+
+## Contract and scope
+
+The authoritative contract is `desktop-notifications-sse.md`, specifically
+`"Background" for run.terminal` and `Python changes in v1`. The desktop consumer
+needs durable duration, not elapsed time since event receipt. Terminal row events
+carry the stored `started_at` and `completed_at` when available; missing stamps
+remain missing. Non-terminal payloads do not change.
+
+No desktop, transport, event-name, visibility, timestamp-storage, or notification
+policy changes belong to this lane. The detail endpoint already exposes both
+timestamps through `SQLiteBackgroundTaskStore._run_from_row`.
+
+## Publisher inventory and design
+
+At base `395d7c2c75980cb154bce3aa83abda7a92ff9450`, every row publisher converges on
+`storage/background.py::_publish_run_rows_updated`:
+
+- Direct callers: `cancel_run`, `claim_pending_run`, `mark_run_execution_started`,
+ `update_run_status`, `mark_run_queued_from_running`,
+ `recover_claimed_pre_execution_run`, `record_run_message`, `record_run_output`,
+ `settle_run_terminal`, `defer_run_terminal`, and `settle_deferred_run` (including
+ participant rows).
+- Deferred callers use `run_update_event_transaction`; snapshots are full rows
+ or fetched with `_run_rows_for_ids`, including session teardown writes.
+- `core/inbox_events.py::publish_run_updated` delegates to `run_updated_payload`;
+ there are no other direct callers. Add optional timestamp passthrough here.
+- `core/internal_server.py` relays the supplied event without projecting it.
+ `vibe/ui_server.py::_archive_publish_run_updates` sends a session invalidation,
+ not a terminal run status. `core/runtime_work.py` consumes the event.
+
+Normalize status once in the shared row publisher, then pass each stored timestamp
+only when that status belongs to `TERMINAL_RUN_STATUSES`. Keep existing local bus
+and controller bridge behavior unchanged, with no new reads or fabricated dates.
+
+## Verification
+
+- [x] Optional payload timestamps are preserved independently or omitted.
+- [x] Every existing status alias preserves the non-terminal payload or adds only
+ available terminal timestamps; the local bus and controller bridge agree.
+- [x] Real persisted lifecycle events carry durable stamps across execution run
+ types, watch-runtime rows, and an unknown future type. Completion differs from
+ update time so the contract cannot silently regress to receipt/update timing.
+- [x] List/detail projection and the HTTP detail endpoint expose stored timestamps,
+ including nulls for incomplete history.
+- [x] Focused Python tests and changed-file Ruff pass (190 tests across inbox
+ events, Harness run projection, and the FastAPI UI server).
+
+Delivery gates: exact-head Codex review, zero unresolved threads, and green CI.
+Track those changing remote gates on the PR rather than in this source snapshot.
+
+Native notification behavior remains for the Rust consumer lane and the
+orchestrator's integration verification. The consumer declares `requires #<PR>`
+for this producer PR; neither lane merges itself.
diff --git a/docs/plans/desktop-start-receipt.md b/docs/plans/desktop-start-receipt.md
new file mode 100644
index 000000000..b3b52642e
--- /dev/null
+++ b/docs/plans/desktop-start-receipt.md
@@ -0,0 +1,90 @@
+# Desktop startup receipt and service-owner stop gate
+
+## Outcome and boundaries
+
+The desktop shell needs to distinguish a Runtime it started from one it adopted.
+Python produces launch provenance at the actual spawn/reuse branch; the shell
+retains stop authority only for a `started` receipt. A pre-launch process snapshot
+is not provenance: another launcher can start the service before `start_service`
+reads the pidfile. Service and UI startup both capture their actual process
+identity and reuse decision without changing their existing integer return value.
+
+This change does not modify desktop Rust code, deployment, routing, data location,
+or the existing unscoped shutdown behavior.
+
+## Frozen schema-v1 startup line
+
+Every successful `vibe start`, including `vibe start --no-open-browser`, writes
+exactly one additional stdout line with this exact prefix and compact JSON:
+
+```text
+@avibe-start-receipt:{"schema_version":1,"outcome":"started","service_pid":1234,"ui_pid":5678,"service_create_unix_ms":1789010100123.5,"ui_create_unix_ms":1789010100456.5}
+```
+
+- `schema_version`: integer `1`.
+- `outcome`: provenance from the spawn-vs-return-existing branch inside
+ `start_service`, never a caller's pre-launch snapshot. `started` means its
+ spawn branch, including a scoped launch resolving its authoritative PID;
+ `reused` means its return-existing branch. UI reuse does not change it.
+- `service_pid`, `ui_pid`: positive integer process IDs.
+- `service_create_unix_ms`, `ui_create_unix_ms`: finite positive epoch
+ milliseconds from `psutil.Process(pid).create_time() * 1000`, captured during
+ startup, not wall-clock sampling or the human-readable status file. Fractional
+ milliseconds are allowed. If a scoped launcher resolves to another service
+ PID, its identity is updated to the authoritative service process.
+
+Consumers match the prefix at the beginning of a line and parse only its JSON
+suffix; other stdout remains human-readable. Failed startup must not emit a
+success receipt. Unreadable process identity must not be fabricated.
+The desktop consumer treats a `reused` receipt as adoption regardless of which
+process invoked start.
+
+## Frozen scoped-stop interface
+
+```text
+vibe stop --receipt '<the receipt JSON, without the stdout prefix>'
+```
+
+Before any shutdown side effect, the service pidfile must contain the receipt's
+`service_pid`, and that live process's psutil create-time must match
+`service_create_unix_ms` with an inclusive absolute tolerance of **2 ms**.
+Malformed/unsupported receipts, missing identity, replacement PIDs, and recycled
+PIDs fail closed: **exit 3**, one JSON object on stderr with a `reason` string,
+no fallback to unscoped stop, no status/pidfile edits, and no shutdown calls.
+
+Reason codes are `invalid_receipt`, `service_pid_mismatch`,
+`service_identity_unavailable`, and `service_create_time_mismatch`.
+
+A match runs today's full graceful stop, including the service sweep, UI,
+OpenCode server, and tunnel. Its normal success/stop-failure exit codes remain
+`0`/`2`. Without `--receipt`, output, exit codes, and behavior are unchanged.
+Python validates identity, not ownership policy: `outcome=reused` is valid input;
+the desktop consumer must not offer or invoke stop for adopted runtimes.
+
+## Security rationale and known limits
+
+A PID alone can refer to an unrelated process after recycling; checking the
+recorded PID and the live kernel-backed create-time prevents a stale desktop
+receipt from authorizing shutdown of a replacement Runtime at gate time.
+
+This is a **service-owner gate**, not a per-process capability or an
+authentication token. It preserves today's full-stop semantics after the gate
+passes. It does not prevent same-install concurrent replacement after the gate,
+nor independently authorize each UI, OpenCode, or tunnel process. A future
+per-process guarantee requires a new contract version. Receipts contain no
+secrets, and a same-user caller can still invoke the existing unscoped stop.
+
+## Validation contract
+
+- Startup output preserves human prose and emits one exact-prefix receipt with
+ launch-captured identities, regardless of browser-opening configuration.
+- Provenance reflects the startup function's branch even when the caller's
+ earlier view of the service differs; service and UI reuse are observed at
+ their owning layer.
+- Every rejected scoped stop leaves shutdown collaborators and state untouched.
+- Matching identities preserve full-stop behavior, including exit `2` failures;
+ omitting the receipt preserves the legacy path.
+- Parser and dispatch tests exercise the documented command shape.
+- Fake-process tests remain hermetic. Real desktop-to-Python acceptance is
+ deferred to the orchestrator's integration pass; never restart the local
+ agent-hosting Runtime for verification.
diff --git a/docs/plans/desktop-test-release-20260922.md b/docs/plans/desktop-test-release-20260922.md
new file mode 100644
index 000000000..073ce26c5
--- /dev/null
+++ b/docs/plans/desktop-test-release-20260922.md
@@ -0,0 +1,1552 @@
+# Desktop test prerelease delivery
+
+## Goal and ownership
+
+Owner request (2026-09-22): complete the desktop test release workflow with macOS ad-hoc app signing in DMGs and unsigned Windows EXE installers. Deliver the implementation through PR #2062; executing a release, creating/pushing tags, merging into master, and deployment are not authorized.
+
+Orchestrator: sessjyd34p9rp. Release implementation uses its own isolated worktree on feat/desktop-test-release-20260922, based on merge candidate 5589edc71292921281f95d072916628a9790fa6a. The existing integration Session sesy9cb4ht9nq retains its worktree and conflict validation. That Session's codex Agent was disabled at 07:58Z, so new release work is dispatched to the enabled backend-codex Agent. Do not edit the integration worktree or push either branch during implementation. Final integration into desktop is gated by independent review of the exact candidate and consuming tests.
+
+## Contract and acceptance
+
+Chosen minimal design: reuse .github/workflows/desktop-package.yml as a workflow_call build unit while keeping its manual artifact-only workflow_dispatch. Connect it to the EXISTING .github/workflows/release_ai.yml GitHub-only gh-vX.Y.ZrcN path. release_ai remains the ONLY publisher for that tag. Do not introduce a competing release workflow or another tag namespace. Official v* / PyPI behavior must remain unchanged, including draft-only AI notes and the existing finalizer. Do not retrofit desktop assets into immutable already-published tags.
+
+Contract:
+- Resolve and validate the gh-v rc tag and its exact source SHA; pass exact ref and a valid Tauri SemVer (e.g. gh-v3.1.2rc1 -> 3.1.2-rc.1) into reusable packaging. Ensure bundled Avibe version corresponds to that tag too, not a stale desktop manifest/default or caller branch. Check existing scripts/release_package_version.py first. Unknown/malformed tag fails before publication.
+- Test channel uses macOS ad-hoc and unsigned Windows deterministically without Apple/Windows credentials, even if optional repository signing secrets exist. Preserve the old optional identity-signing MANUAL path. Clearly record actual layer: app ad-hoc, outer DMG unsigned/unnotarized; Windows installer unsigned. SIGNATURE is metadata, not a cryptographic signature file. No updater.
+- Three required native targets: aarch64-apple-darwin + x86_64-apple-darwin DMG, x86_64-pc-windows-msvc NSIS EXE. Reuse existing build/runtime scripts. Verify existing action pins (desktop upload-artifact appears to differ from repository's v6 pin).
+- All 3 target builds and runtime/hash metadata must succeed before GitHub prerelease finalize. Use unique target-qualified installer/metadata filenames or equivalent unambiguous packaging to avoid three runtime-manifest.json/SIGNATURE/SHA256SUMS collisions; raw DMG/EXE should be convenient release downloads. Validate expected asset set and hashes before upload/finalize, prove provenance matches exact tag/source. Failed/missing/mismatched assets leave draft/unpublished. Do not clobber changed desktop bytes under an existing tag: same bytes can be idempotent, different bytes require a new rc.
+- Existing wheel/sdist, Show/Memory runtime assets and publication ordering remain intact. Correctly handle skipped desktop job for official tags in release job needs/if. Existing AI notes secret requirements are not Apple signing requirements; document real prerequisites without adding another notes service.
+- Append stable test-installation guidance to gh-only notes and desktop README: platform/architecture downloads, hashes + metadata, macOS local app approval / Windows prompts as applicable, no blanket security disable, bundled Python/Node, manual app replacement upgrade retaining user data, removal behavior, links to #1976 for trusted distribution. Revise current artifact-only README claim.
+
+Authorized files: .github/workflows/desktop-package.yml; .github/workflows/release_ai.yml; narrowly necessary desktop/scripts or scripts release helpers; existing/new focused release/package tests; desktop/README.md; docs/plans/desktop-test-release-20260922.md and a concise release runbook under docs if useful. No product UI, lifecycle redesign, auth, notifications, updater, or production changes.
+
+Validation: existing release tests plus meaningful hermetic producer/consumer tests for tag/version/ref mapping, real assembled release assets/hash verification, all-target completeness, skipped official behavior, idempotent/same vs changed bytes, and preservation of manual packaging. Use mocked gh where publication logic requires calls; never hit a real Release write. Parse/lint workflow YAML and shell with existing tooling, verify referenced action revisions read-only. Run changed Python Ruff and focused runtime/merge tests already required. No demand for local full 3-OS packaging: clearly separate contract evidence from actual packaging/install acceptance.
+
+
+## Evidence
+
+Implementation, independent review, exact-head Codex/CI, and packaged/manual acceptance must be reported separately. No actual packaging or publishing result has been established by this design document.
+
+## Implemented data flow and decisions
+
+1. `release_ai.yml` resolves a canonical `gh-vX.Y.ZrcN` tag once to its peeled
+ commit, a Tauri SemVer, and the existing helper's Python package version.
+ Preview package/Memory builds and all three desktop targets check out that
+ exact commit. The desktop producer also checks its HEAD against the tag.
+2. The existing desktop workflow accepts `workflow_call` without receiving
+ secrets. Before building the private Runtime it writes the tag-derived SCM
+ environment overrides and Tauri config. The test override uses the ad-hoc
+ macOS identity and clears Windows signing configuration. Manual dispatch
+ keeps its optional complete Apple credential path and its SemVer input.
+3. The existing Runtime builder remains unchanged. Its installed Avibe version,
+ target, archive size/hash and tree hash are validated when recording assets.
+ The app is ad-hoc signed and verified before the existing headless DMG wrapper;
+ Windows checks Authenticode reports `NotSigned`.
+4. Each target produces five uniquely named files: installer, Runtime manifest,
+ source record, signature-state metadata, and checksums. The release consumer
+ admits exactly 15 files, checks every checksum and semantic field, and appends
+ the stable installation guide to the generated GitHub-only notes.
+5. The existing GitHub-only upload shell compares all existing package, runtime,
+ and desktop bytes before uploading anything. Published releases missing any
+ desktop file are refused. Identical assets are reused; different bytes require
+ a new rc. Runtime uploads still precede package/desktop uploads. All uploaded
+ desktop assets are downloaded and compared again before the existing sole
+ finalizer publishes the prerelease. Finalization is serialized per tag.
+6. The release job explicitly permits skipped preview/desktop dependencies for
+ official tags while requiring successful desktop/source jobs for TEST tags.
+ The official notes step remains draft-only; `publish.yml` is unchanged.
+
+No product lifecycle, UI, authorization, runtime protocol, updater, dependency,
+or production configuration changes were made. Native outputs are not assumed
+byte-reproducible; immutable comparison can require a new rc after a rebuild.
+
+## Local verification, 2026-09-22
+
+- 527 focused tests passed across desktop release, desktop Runtime bundle builder,
+ release verification, package-version mapping, GitHub release state, and Show
+ Runtime release tests. After adding actual producer-shell coverage for all
+ three targets and renaming the version helper, all 39 desktop release tests
+ passed (three additional cases; the other focused tests were unchanged).
+- 207 existing Memory Runtime release, desktop Runtime/backend, Workbench-only
+ Runtime, runtime ownership, and UI install tests passed. The 35 SQLAlchemy
+ expression-index reflection warnings are existing warnings, with no failures.
+- Consuming tests use the real Runtime ZIP writer, real desktop metadata producer,
+ real assembled files, and the actual workflow upload shell. Only GitHub is
+ simulated. They cover tag/annotated-tag/HEAD binding, invalid tags, stale package
+ versions, archive tampering, target completeness, checksum and provenance
+ mismatches, preserved manual signing export, identical/changed remote bytes,
+ missing published assets, and corrupted uploads that must remain drafts.
+- Ruff and `git diff --check` passed. YAML parsing and `bash -n` passed for both
+ workflows. Cached actionlint v1.7.7 passed with a temporary configuration naming
+ the repository's existing `macos-15-intel` and `windows-11-arm` runner labels
+ (these postdate its built-in label list); no lint configuration was committed.
+- Read-only public checks returned HTTP 200 for `action.yml` at all seven unique
+ Action revisions referenced by these workflows. The previous desktop upload
+ revision returned 404; it now matches the repository's working v6 pin.
+
+## H4 and latest-master integration candidate
+
+The implementation candidate now includes the real merge of upstream master
+`335f62e6c15987d0ab72f6139c16fe49eea706e8` into the desktop release lineage,
+preserving the six upstream Model Hub route-picker paths. It also contains the
+bounded H4 readiness-loss correction recorded in the integration plan. Release
+workflow, producer, consumer, and package files remain byte-identical to the
+reviewed release implementation; the only release-plan changes are evidence
+updates.
+
+The shared RuntimeHost transition retains a valid started receipt and its
+original launcher through three readiness misses, releases only completed
+helper retry state, keeps pending helper deduplication, and classifies
+unavailable readiness as `Unknown` while local liveness evidence remains. The
+shell monitor invokes that transition after its existing generation/activity
+fences. The candidate evidence is 96 RuntimeHost library tests, 28 bootstrap
+consumer tests, 19 desktop shell unit tests, 27 shell boundary tests, and
+`cargo fmt --all -- --check`; the focused shell test drives the same transition
+used by production and proves started/reused recovery plus pending-helper
+exclusion. Cargo emitted its existing shared-cache cleanup permission warning;
+compilation and tests completed successfully.
+
+## Remaining gates and handoff
+
+- This lane delivers one local candidate commit on
+ `feat/desktop-test-release-20260922`, descended from the release merge
+ `5589edc71292921281f95d072916628a9790fa6a` and the latest-master merge
+ above. No push, PR, tag, dispatch, Release mutation, merge into master,
+ deployment, or Watch changes were performed.
+- The orchestrator independently accepted integration evidence commit
+ `33eeb3eefbeecf0a479f4f70b922f900466102fb`; its code is identical to this lane's
+ base and its additional plan evidence will be integrated by the orchestrator.
+ This lane did not modify that integration worktree or contact its Session.
+- Independent candidate review, final integration, exact-head Codex review, zero
+ unresolved PR threads, and CI remain the orchestrator's delivery gates. Local
+ checks do not substitute for those gates.
+- Actual three-target packaging and installation remain unexecuted: build an
+ owner-authorized fresh rc; verify each downloaded DMG/EXE and signature layer;
+ launch on machines without Python/Node; verify readiness/onboarding, manual
+ replacement upgrade preserving user data, and uninstall cleanup/preservation.
+ The existing AI notes secret and Actions/repository permissions are still
+ prerequisites. Apple and Windows signing credentials are not TEST prerequisites.
+
+### Pre-push master refresh
+
+At 08:31Z the explicit remote fetch found `master` advanced from `16bf1be3` to
+`a582c87f0156082f87548be2912e063f09fc2bb1` (#2112), while remote `desktop`
+remained `8440cf81737be5db46a16992ecce41fe29beb866`. Push authorization for
+`da11a508bcb4f9602b8a368a2a1fc4f46fbd9ed9` was therefore held. The new master
+changes only pytest configuration comments, the advisory async-plugin guard,
+its consuming tests, and the bounded atomic-IO test reader. These four files
+merged without conflicts; all eight release implementation files were unchanged
+before this evidence update. The merged tree passed 750 tests (seven existing
+SQLAlchemy reflection warnings) across those new tests, six release suites,
+desktop bundle builder, desktop Runtime, IPC, and UI installation consumers.
+The parent process HOME/XDG/backend state paths were redirected into a temporary
+test directory as well as the repository's per-test isolation. Ruff passed for
+the release changes and incoming Python files. The updated local candidate is
+returned for independent inspection before any push. All five historical PR
+threads remain resolved, no review is pending, and the original lane Watch
+`54efbc6d5cec` remains live with its cursor unchanged under Session
+`sesu7hnukugyr`; orchestrator Watch `25111cdab6a3` remains separate.
+
+## Owner authorization and next TEST release
+
+At 2026-09-22 08:34:44Z the owner explicitly authorized publishing the desktop
+TEST prerelease after review passes. This supersedes the earlier no-publication
+boundary for this conditional GitHub-only TEST release; merging into master is
+still not authorized. The exact final desktop commit must have Codex PASS, zero
+unresolved threads, all expected `lint` and `desktop-shell` checks green, clean
+mergeability, and latest-master ancestry. The orchestrator independently verifies
+that gate before executing or delegating the release tag push. No further owner
+confirmation is required for that authorized sequence.
+
+The intended next tag is `gh-v3.1.1rc4` (desktop `3.1.1-rc.4`, bundled Avibe
+`3.1.1rc4`), subject to a fresh remote tag/Release lookup immediately before
+allocation. If another publisher uses it first, choose the next unused rc in the
+same sequence. Do not reserve or overwrite a tag or existing asset. Create an
+annotated tag on the exact reviewed desktop commit with the following annotation:
+
+```text
+Desktop TEST prerelease: macOS ad-hoc app in unsigned/unnotarized DMG; unsigned Windows x64 installer.
+
+<!-- avibe:update-notification=none -->
+```
+
+Publication runs only through the tag-triggered `Release (AI Notes)` workflow as
+a GitHub prerelease with `latest=false`; no manually created competing Release,
+official `v*` tag, PyPI publish, production service change, or local service
+restart is authorized. Apple/Windows signing credentials are not required. The
+orchestrator confirmed the existing `OPENAI_API_KEY` secret name is present,
+without reading its value.
+
+Before any tag push, arm a separate exact-source/tag Actions Watch through
+`background-watch-hook` for `Release (AI Notes)`, with independent state and both
+timeout layers disabled. Confirm liveness and explicitly diagnose a missing or
+failed workflow. Preserve the two existing PR Watches/cursors until the PR gate
+report; establish durable release observation before retiring the lane PR loop.
+
+Completion requires a successful workflow for the exact source/tag and all three
+public native installers plus matched provenance, hashes and signature metadata,
+verified by download/readback. Report direct URLs for Apple silicon and Intel
+DMGs and the Windows x64 EXE. Contract tests are not native packaging evidence.
+Actual install, manual replacement upgrade and uninstall remain separate manual
+acceptance; never install over the owner's live Avibe to claim those passed.
+Any packaging defect requires a bounded fix, new exact-head review, and a fresh
+rc when immutable bytes would change, rather than blind reruns or asset replacement.
+
+### Latest master ancestry refresh
+
+The explicit remote refresh on 2026-09-22 found `origin/master` at
+`4b964fef223862c2cf7d5cec852ac0d3aa64e323` (#2118), ahead of the previously
+integrated `335f62e6c15987d0ab72f6139c16fe49eea706e8`. That upstream change is
+limited to `ui/scripts/lintBaseline.test.mjs`, where the temporary integrity
+probe now carries cleanup guidance and verifies exactly one inline-policy
+diagnostic. It has no release, RuntimeHost, shell, or product behavior delta.
+The change was merged as a real conflict-free second parent into the desktop
+candidate. Focused Vitest evidence passed 33 tests; the new exact-head GitHub
+lint and desktop-shell gates remain required before push and TEST publication.
+
+### H5 candidate: lane handover, master refresh, local evidence
+
+- 2026-09-23: The previous implementation lane (Session `sesu7hnukugyr`, codex
+ backend) is dead — every run failed with `model_hub_recovery_exhausted` and a
+ resume failed again immediately. A replacement lane inherited its worktree and
+ its uncommitted H5 draft rather than resetting the branch; the draft's two
+ Python fixes were kept and its Rust test was replaced with a real consuming
+ test. Root-cause detail for all three H5 threads lives in
+ `docs/plans/desktop-master-integration-20260920.md`.
+- **Latest master.** An explicit refspec fetch put `origin/master` at
+ `c400da2df4eb09feab84678c8f3d5c76d3af1b12`, ahead of the previously integrated
+ `4b964fef223862c2cf7d5cec852ac0d3aa64e323`. The incoming delta is Model Hub UI
+ and Claude model catalog work across 37 files; it touches no desktop shell,
+ RuntimeHost, or release path. It was merged as a real conflict-free second
+ parent, and `origin/master` is now an ancestor of the candidate. The PR's
+ `baseRefOid` was not used for this: it was stale.
+- **TEST release surface unchanged.** The seven release implementation files
+ from `13082a8501ce5d1e771f56395a72fc062859cf8b` — the two workflows,
+ `desktop/README.md`, `docs/desktop-test-installation.md`,
+ `scripts/desktop_release.py`, `tests/test_desktop_release.py`, and
+ `tests/test_release_verification.py` — were re-verified byte-identical by
+ object hash after the merge. No UI or workflow file is touched by this
+ candidate's own commit.
+- **Local validation on the candidate tree.** 107 focused Python tests pass
+ (`tests/test_desktop_runtime.py` in full, plus the reconcile/model-hub
+ selection from `tests/test_local_deps.py`), all under the repository's
+ per-test `HOME`/XDG isolation. `ruff check` is clean on the four changed
+ Python files. The Rust workspace passes `cargo fmt --all --check`, 201 tests
+ under `cargo test --workspace --all-features` — including the shell unit tests
+ and the `shell_boundaries.rs` integration guards — and `cargo clippy
+ --workspace --all-targets --all-features -- -D warnings`. GitHub `lint` and
+ `desktop-shell` at the pushed head remain the authoritative gates.
+- Push is held pending explicit orchestrator candidate clearance. Replies to the
+ three H5 threads follow the pushed head, not this commit.
+
+### H6: the Windows-only path-separator defect the first TEST release exposed
+
+The first real prerelease attempt found a defect no existing gate could have
+caught. Tag `gh-v3.1.1rc5` at the reviewed head started `Release (AI Notes)` run
+`35776410677`, and `desktop-packages / x86_64-pc-windows-msvc` failed at **Build
+Workbench**, so no Windows installer could be produced and the release could not
+complete.
+
+- **Cause.** `ui/scripts/validate-out-of-tree-imports.mjs` guards the Docker
+ `ui-builder` stage: every import that escapes `ui/` must be placed at the
+ repository-relative path the import expects, or `npm run build` cannot resolve
+ it in that image. The guard produced its targets with
+ `path.relative(REPO_ROOT, resolved)`, which answers in the *host* separator.
+ Everything the target is then compared against is POSIX: the Dockerfile's
+ `COPY` sources, the ``target.startsWith(`${source}/`)`` prefix test, and the
+ `path.posix` joins. On Windows the target became
+ `vibe\data\api_key_vendors.json`, which equals no `COPY` source and prefixes
+ none, so `imagePathOf` returned nothing and the guard reported that the file is
+ put "at no path at all" — against a Dockerfile that is correct.
+- **Why every other job was green.** The guard only runs inside `npm run build`,
+ and `ui-checks` runs on Linux only. The desktop Windows package job is the one
+ place in the pipeline where `npm run build` executes on Windows, so the first
+ Windows packaging attempt was the first execution that could fail.
+- **Fix.** The repository-relative path is normalized to POSIX at the single
+ place it is produced, so the whole comparison chain stays POSIX.
+ `repoRelativePosix` lives in `ui/scripts/repoRelativePosix.mjs` and takes the
+ path flavour as a defaulted argument; `escapingImports` calls it instead of
+ `path.relative`. The validator is not restructured, the check is not weakened
+ or skipped on Windows, and the Dockerfile is untouched.
+- **Why a separate module rather than an export from the validator.** The
+ validator runs its validation at import time and calls `process.exit(0)` when
+ no Dockerfile is present — a state its own comment anticipates inside the
+ `ui-builder` stage. Importing it from a test would make that a silent
+ green-exit hazard for the whole suite. The repository's dominant script idiom
+ is already a pure module beside its entry point, as `scenarioCatalog.mjs` is to
+ `validate-scenario-catalog.mjs`. A `main`-module guard was rejected for the
+ opposite reason: a guard that compares `process.argv[1]` to
+ `import.meta.url` can disagree on Windows drive-letter casing, which would
+ silently stop running the guard on the one platform it now has to protect.
+- **Consuming test.** `ui/scripts/repoRelativePosix.test.mjs` drives
+ `path.win32` explicitly, which is the only way to reach Windows' separator from
+ Linux CI, where the test actually runs. Six cases pin the normalization, the
+ POSIX no-op, the host default, and the failure itself: for each of the two real
+ catalogs the Dockerfile copies, the un-normalized Windows target matches its
+ `COPY` source by neither equality nor prefix while the normalized one matches,
+ and the expected image path is `/app/vibe\data\api_key_vendors.json` before the
+ fix against `/app/vibe/data/api_key_vendors.json` after. Removing the
+ normalization fails four of the six, with exactly the string the Windows job
+ reported.
+- **Local validation.** The full UI suite passes at 348 files and 5295 tests, up
+ by one file and six tests. `npm run build` succeeds, which runs the repaired
+ guard as its first step. `npm run lint` reports no drift in any (file, rule)
+ pair, and ESLint is clean on all three changed files. No Python changed, so
+ Ruff does not apply. The seven release implementation files from
+ `13082a8501ce5d1e771f56395a72fc062859cf8b` were re-verified identical.
+- **Release state.** Tag `gh-v3.1.1rc5` stays as it is and is never reused; the
+ orchestrator cuts a new rc after this fix passes review and CI. Push is held
+ pending explicit candidate clearance.
+
+## H7 — the failure-path review round
+
+The exact-head Codex review of `b85261e41` returned five P2 findings. Four of
+them are one root-cause class: a multi-step operation commits an irreversible or
+externally visible step before the step it depends on is known to have
+succeeded, and the failure path neither aborts nor undoes it. That class had
+already appeared at the H5 head, so the review-loop circuit breaker was tripped
+and the inventory went to the orchestrator, which issued the scope ruling this
+round implements. Each fix is expressed as one decision function that owns every
+outcome and emits explicit effects, so the failure path is a branch of the same
+unit and a test can assert the effect sequence.
+
+- **Stale UI replacement now honours the stop result.** `start_ui` discarded
+ `stop_pid`'s answer, unlinked the pid file and spawned a replacement anyway. If
+ the stop failed, the old process still owned the listener, the replacement
+ could only die on bind, and the pid record had stopped naming the process that
+ actually had to be killed. It now fails through the module's existing idiom —
+ an error log and a falsy return — before the unlink, so the record keeps
+ naming the live process. H5 is what made this branch busier: reclassifying
+ `runtime_identity_invalid` as incompatible routes more restarts through it.
+- **Uninstall restores the login item it cleared when the removal does not
+ happen.** Clearing **Start at Login** still comes first, so the OS never keeps
+ launching an application the user just removed. But a removal that reports
+ `Ok(false)` or errors leaves the application installed, and the user's login
+ preference was silently gone. The decision function is now async and owns the
+ removal outcome, so the restore is a branch of the same unit rather than a
+ guard bolted onto the caller.
+- **Readiness recovery stops notifications only after the hand-off succeeds.**
+ The monitor tore the connection down before `return_to_bootstrap` was known to
+ have navigated. A failed navigation plus a recovered Runtime left native
+ notifications dead for the rest of the session with nothing to restart them.
+ The navigation is now `restore_bootstrap_view` and the recovery decision owns
+ the ordering; `return_to_bootstrap` keeps its previous behaviour for its five
+ other callers.
+- **Release tooling runs from the released source.** Both the
+ `resolve-desktop-release` and `release` checkouts passed only `fetch-depth`,
+ so a `workflow_dispatch` resolved and published a tag using whatever branch
+ the dispatch selected. Both are pinned now. The release job needs a fallback
+ because `resolve-desktop-release` is gated on `gh-v` and is skipped on the
+ official `v*` path, where its output would be the empty string. `Checkout
+ release verification` keeps `github.sha` deliberately: it is workflow-owned
+ verification applied to the tagged build, and pinning it to the resolved
+ source would defeat that.
+- **Deferred.** Uninstall deletes the private Runtime root without fencing an
+ in-flight backend install. The install lock is Python-only, so the Rust
+ launcher has none to take; the fix is a cross-language ownership change
+ outside this PR. Tracked in issue 2131 and in the PR's Known-by-design ledger.
+
+- **Local validation.** The new checkout-pinning guard is mutation-checked
+ against both an unpinned checkout and a pin that loses its official-path
+ fallback. The `start_ui` consumer fails with its own message when the fix is
+ reverted, and the two Rust effect-sequence tests fail when the stop is moved
+ back before the hand-off or the restore is dropped. Full Rust workspace: 204
+ tests including all 27 `shell_boundaries.rs` guards, `cargo fmt --all --check`,
+ and `cargo clippy --workspace --all-targets --all-features -- -D warnings`
+ clean. 303 Python release and desktop-runtime tests, Ruff clean on the changed
+ files, and actionlint on both release workflows with only the three
+ pre-existing newer-runner-label notices.
+- **Release state.** The freeze lifted for `.github/workflows/release_ai.yml`
+ only; its delta against `13082a8501ce5d1e771f56395a72fc062859cf8b` is the two
+ pins and their rationale. The other six release implementation files are still
+ byte-identical, which is why the guard test lives in its own file rather than
+ in `tests/test_desktop_release.py`. Tag `gh-v3.1.1rc5` stays spent. Push is
+ held pending explicit candidate clearance.
+
+## H8 — packaging observability after the second TEST prerelease
+
+`gh-v3.1.1rc6` ran the desktop packaging matrix from `902c447141df` and failed on
+two of three targets, so nothing was published. Desktop packaging has never run
+outside this PR — neither `.github/workflows/desktop-package.yml` nor
+`desktop/scripts/build-runtime-bundle.py` exists on master — so these are first
+exposures rather than regressions, and more should be expected.
+
+### What the Windows job showed, and what it did not
+
+The private-Runtime probe failed because the service process exited before
+acquiring the service lock, about 28 seconds after `vibe start` spawned it. Why
+it exited is **not** in the job log, and cannot be: the probe runs with its
+entire HOME inside a `TemporaryDirectory`, so `runtime/service_stderr.log` and
+`logs/vibe_remote.log` are written and deleted without ever being read. The job
+instead reported a `PermissionError` on a payload DLL — the last of four stacked
+exceptions and the least informative.
+
+Four separate defects turned one failure into an unreadable one, and each is
+fixed here:
+
+- **The probe's own logs were discarded.** `verify_payload` now reports every
+ diagnostic file under the probe HOME to stderr before the directory is
+ removed, naming the files that are absent as well as the ones that exist.
+- **The failure path orphaned processes.** Nothing killed the spawned service or
+ UI. `vibe/runtime.py` returns the UI pid even when its health checks fail —
+ pre-existing behaviour, deliberately left alone in a release round — so a live
+ UI kept holding the log handles that made the temporary directory's removal
+ fail. The probe now terminates whatever its pid files still name.
+- **The `finally` replaced the real exception.** `vibe stop` ran with a 60s
+ timeout raised straight out of `finally`, superseding the `CalledProcessError`
+ that carried the actual failure, with both streams at DEVNULL so the stop's own
+ account was discarded too. `stop_private_runtime` now reports its outcome
+ instead of raising it, and prints what it captured.
+- **Cleanup noise masked the result.** Both `TemporaryDirectory` uses now pass
+ `ignore_cleanup_errors=True`, so a leftover Windows handle leaves a stale
+ directory rather than becoming the exception the job reports.
+
+The authoritative proof is the next CI run. That is the point: this round buys
+legibility for an unknown number of remaining first-exposure failures rather
+than guessing at this one. The one added test covers the real seam —
+`collect_probe_diagnostics` — and is mutation-checked against dropping the tail
+slice and against skipping absent files silently. The subprocess orchestration
+is deliberately not harnessed.
+
+### macOS DMG
+
+`hdiutil create` failed with "Resource busy" on `aarch64-apple-darwin` while the
+identical script succeeded on `x86_64-apple-darwin` in the same run, so this is
+imaging flake, not a code defect. It now retries up to three times with a pause,
+and the final failure is still a build failure.
+
+The signature detection beside it was broken: `sed -n 's/^Signature=adhoc$/p'`
+has no replacement field, so sed errored on every invocation and `adhoc` was
+always empty, leaving the branch to be decided by `-z "$identity"` alone. The
+expression is now `sed -n '/^Signature=adhoc$/p'`.
+
+**No case changes behaviour.** `Signature=adhoc` and `Authority=` are mutually
+exclusive in `codesign` output — an ad-hoc signature has no certificate chain and
+prints no Authority line — so a correctly detected ad-hoc bundle was already
+taking the ad-hoc branch through the empty-identity test. Checked against all
+three real output shapes: ad-hoc, Developer ID, and unsigned each select the same
+branch before and after. It is a correctness and noise fix that finally makes the
+code do what the comment above it has always claimed.
+
+The same broken expression also appears in `.github/workflows/desktop-package.yml`
+at the "Verify macOS app signature matches the signing path" step. That file is
+in the frozen release-implementation set and is **not** touched here. The same
+analysis applies — its `adhoc` is always empty, the identity branch still turns
+on `-z "$authority"`, and the TEST branch uses `grep -q` directly rather than the
+sed — so it is noise with no behavioural consequence, reported to the
+orchestrator rather than fixed under the freeze. **Deferred by orchestrator
+decision, to be fixed in a later round**: touching a frozen release-implementation
+file to correct cosmetic noise is not worth the re-verification it would cost
+this close to a TEST prerelease.
+
+### The stop report's own timeout branch
+
+Review of the change above caught the one place where the fix reproduced the
+defect it was written to remove. `subprocess.run` decodes its streams on the
+completion path, which a timeout never reaches: `TimeoutExpired` carries what it
+captured before the deadline as raw bytes even when the call passed `text=True`,
+and an unwritten stream as `None`. `_stop_report` would have joined bytes into a
+string and raised `TypeError` — from inside the `finally`, over the probe failure
+the report exists to explain.
+
+This is not hypothetical for the next run. The Windows job that motivated the
+whole round took exactly this branch: `vibe stop` ran the full sixty seconds and
+timed out. `stop_private_runtime` now normalizes both streams before formatting
+them, decoding the same way `collect_probe_diagnostics` does so an undecodable
+byte is reported rather than raised.
+
+Only two subprocess calls in the file carry a timeout at all, and the other one
+— `taskkill` in `terminate_probe_processes` — never reads its streams, so it does
+not share this defect. It does carry a related one: it has no `TimeoutExpired`
+handler and runs inside an `except BaseException:` block, so a thirty-second hang
+there would replace the original exception and mask the failure the same way.
+Different root cause, same consequence. **Deferred by orchestrator decision, to
+be fixed in a later round** alongside the `desktop-package.yml` expression above.
+
+### One opener for the notification connection
+
+The notification connection's lifetime was not paired with the outcome of the
+navigation it belongs to. `open_workbench` opened it before attempting the
+navigation, and every failure exit from that loop — no window, no bootstrap
+navigation, `set_active_origin` refusing, `window.navigate` erroring — returned
+without closing it, leaving it consuming Runtime events and able to raise native
+notifications while the shell sat on bootstrap.
+
+The fix is an ownership statement expressed as a deletion rather than a guard.
+`Notifications::start` returns early when a connection for the same origin
+already exists, so the monitor's own start was a no-op after it and the early one
+was redundant on the success path and a leak everywhere else. Removing it leaves
+exactly one opener, `start_runtime_monitor`, which is reached only once a handoff
+has actually completed; the stop sites already give the connection up only where
+a hand-off away actually happened. Start and stop now both hang off a navigation
+that really occurred instead of one that was merely attempted, and the rule is
+written at the monitor's start site for the next reader.
+
+The shell's boundary test already owned this invariant and had recorded the old
+shape: it required `open_workbench` to contain the early start. Both starts
+arrived in the same commit, so what it captured was the code as first written
+rather than a decision that the connection must open early — and its own name
+says the lifecycle follows runtime ownership, which is exactly what the early
+start broke. It now requires the start inside `start_runtime_monitor`, requires
+`open_workbench` to touch the lifecycle not at all, and holds the opener count at
+one, so reintroducing a premature start anywhere fails it.
+
+The line predates this PR — it arrived with #1983 — and the other lifecycle sites
+(`exit_shell`, `stop_runtime`, the readiness-loss recovery, `return_to_bootstrap`
+and the removal flow) were audited against that one sentence and do not
+contradict it. None of them is changed here.
+
+## H9 — the lease check that could not pass on Windows
+
+The third TEST prerelease, `gh-v3.1.1rc7`, failed its Windows desktop package in
+the private-Runtime probe. The packaging observability added in H8 is what made
+it readable: the probe printed the service's own log, which said `Failed to
+start: Unsafe native lease file`, and the `RuntimeError` about the service lock
+that the job surfaced first was only the symptom of that.
+
+`NativeCredentialLease.acquire` verified the lease file with a POSIX permission
+mask, `info.st_mode & 0o077`. Windows synthesizes `st_mode` from file attributes,
+so any writable regular file reports `0o100666` there and the mask always yields
+`0o066`; the `0o600` passed to `os.open` cannot change it, because Windows honors
+only the read-only bit from that argument. The check therefore rejected every
+lease on Windows, deterministically, and the service could not finish starting.
+The clause is now POSIX-only, in the idiom the same expression already used twice
+within five lines — `hasattr(os, "getuid")` for the owner check and
+`getattr(os, "O_NOFOLLOW", 0)` for the open flag. The equivalent guarantee on
+Windows is an ACL check, not a mode mask, and is not attempted here.
+
+**This arrived from master, not from us.** The check came in with #2060
+(`162fda594`, 20 September); this PR does not touch `core/backend_restart.py` in
+any other respect. It stayed invisible because nothing had ever executed that
+line on Windows: unit tests run on Linux, the lease tests needed no platform
+skip, `desktop/scripts/build-runtime-bundle.py` does not exist on master, and no
+prior prerelease shipped a desktop installer at all. The Windows private-Runtime
+probe this PR introduces is the first caller to reach it on that platform, which
+is why a pre-existing defect surfaced as a release-path blocker here. It was
+fixed in this PR rather than deferred for exactly that reason: no number of
+re-runs produces a Windows installer while it stands.
+
+Whether an ordinary Windows service start also reaches `acquire()` — and has
+therefore been broken on master since 20 September — is deliberately not claimed
+here. It is tracked in issue #2132 with this evidence. The coverage added with
+the fix asserts both directions, so neither dropping the mask nor restoring it
+unguarded can pass: POSIX still refuses a group-accessible lease file, and the
+identical file acquires once `os.name` is not `posix`.
+
+## H10 — Known-by-design: runtime identity across lifecycle boundaries
+
+- **Deferred.** The Codex review at `4458203f1a` returned three P2 findings —
+ an unscoped handover stop in `launcher.rs`, monitored readiness collapsing a
+ changed `desktop_runtime_id` to `true` in `bootstrap.rs`, and an uninstall
+ recovery in `lib.rs` that can leave no monitor owner when its navigation
+ fails. All three are one cause: the desktop lifecycle re-derives which
+ Runtime it has authority over at every boundary instead of carrying one
+ verified identity through launch, probe, monitor, stop and removal. The same
+ class was patched per-boundary on roughly seven earlier heads of this PR, so
+ a bounded patch at a seventh boundary was explicitly rejected under the
+ review-loop circuit breaker in `AGENTS.md`; the fix is a coordinated
+ ownership change spanning the Rust shell, `runtime-host` and the Python
+ runtime. None of the three is on the packaging path, none risks data loss or
+ user-state corruption, and each requires a second desktop instance replacing
+ the Runtime mid-flight — a race a TEST prerelease installer does not need to
+ survive. They do block a master merge, which this PR is not authorized to do.
+ Tracked in issue 2135.
+
+## H11 — the control IPC owner check under an elevated token
+
+`gh-v3.1.1rc8` proved the H9 lease fix: Windows got past `Unsafe native lease
+file` and reached `IM runtime ready`, then failed one layer deeper with
+`control IPC path is not owned by the current user`, which stopped the runtime
+through the lost-lease path.
+
+The cause is Windows object ownership, not a path problem and not another POSIX
+assumption. `_WindowsSecurity` builds its expected descriptor from the token
+**user** SID — `self.sddl = f"O:{self.current_user_sid}..."`, fed by
+`_read_current_user_sid()` reading `TokenUser` — and then requires the existing
+directory's owner to equal that SID. But Windows stamps a newly created object
+with the token's **default owner**, and for an elevated token that default is
+`BUILTIN\Administrators`, not the user. An elevated Avibe therefore creates a
+runtime directory it then refuses to recognise as its own.
+
+Two independent owner checks had to move together, which the first reading of
+this bug missed. `secure_existing_owned_path` gates on
+`_named_path_owner_matches`, and then finishes with `validate_path` →
+`_validate_security_descriptor`, which re-checks the owner itself. Because
+`SetNamedSecurityInfoW` is called with `None` for the owner argument — repair
+rewrites the DACL and never the owner — relaxing only the first check would have
+left the second one failing on exactly the same directory. Both now route
+through one predicate, `_owner_is_self`, so there is a single answer to "did
+this process create this path".
+
+Acceptance is derived from the running token, not from a hardcoded well-known
+SID: an unelevated process still accepts only its user SID, and
+`BUILTIN\Administrators` is accepted only when it is genuinely this token's
+default owner.
+
+**Tradeoff, stated rather than slipped in.** An elevated Avibe now trusts an IPC
+runtime directory owned by `BUILTIN\Administrators`, which means any
+administrator on the machine could have created it. The DACL contract is
+deliberately unchanged — still present, still protected, still exactly
+`(A;;FA;;;<user>)(A;;FA;;;SY)` — so an Administrators-owned path is still
+rejected unless its access control list grants nobody but this user and SYSTEM.
+For an elevated Windows service that matches normal practice, where
+administrator-equivalence is already assumed; without it an elevated Avibe
+cannot use control IPC at all.
+
+The Linux-executable tests pin the acceptance rule by driving `_owner_is_self`
+and `_validate_security_descriptor` through a bypassed constructor with fake
+`advapi32` bindings. They prove the decision logic, including that an unrelated
+SID and a non-protected DACL are still rejected. They cannot prove the Win32
+behavior underneath; as with H9, only the next prerelease's Windows leg settles
+that.
+
+## H12 — CLI discovery must not run on an async request path
+
+The runtime path projection added in this PR made `to_app_config` call
+`resolve_cli_path`, whose last-resort branch runs `npm config get prefix` with a
+five-second timeout and no caching. `to_app_config` is reached from async
+handlers — `_reconcile_platforms` on the controller loop, `opencode_options_async`
+and `_opencode_get_server` on the UI server loop — so a missing backend CLI would
+stall an event loop for up to five seconds, once per missing backend.
+
+Fixed by passing `include_npm_global=False`: that branch is the only one in the
+resolver that spawns a process, and the cheap candidates it keeps —
+`~/.local/bin`, `~/.bun/bin`, Homebrew, `/usr/local/bin` and every NVM version —
+already cover what a GUI-launched Runtime needs. The cost is narrow and stated:
+a CLI installed via `npm -g` into a non-default prefix that is *also* absent from
+`PATH` will no longer be discovered by the Runtime. A GUI-launched process is
+exactly the context where such a prefix is unreliable anyway.
+
+Memoizing the npm prefix was the alternative and is worse: it still blocks the
+loop once and buys a staleness question that the keyword does not.
+
+## H13 — Banked: why the Windows service lock self-check fails
+
+Not fixed. Windows is shelved; this is recorded so the next attempt starts from
+a cause rather than from the logs again. Tracked in issue 2141, which is the
+layer underneath issue 2132: both are code that is correct on POSIX because
+POSIX file locks are advisory, and wrong on Windows because Windows byte-range
+locks are not.
+
+The rc8 Windows leg reported two symptoms that look separate and are one bug:
+the probe said pid 3176 had not acquired the service lock after 5s, and 47
+seconds later the service stopped itself through `_stop_for_lost_lease`. The
+control IPC owner error in that window is on the shutdown path, i.e. downstream.
+
+The cause is that the lock byte sits on top of the data it guards.
+`_try_lock_file` seeks to 0 and calls `msvcrt.locking(fd, LK_NBLCK, 1)`, so it
+locks byte 0. `_lock_file_pid` then seeks to 0 and reads — the same byte. On
+POSIX this is harmless because `fcntl.flock` is advisory and never blocks a
+read. On Windows byte-range locks are **mandatory and per-handle**: Microsoft's
+documentation states that if the locking process attempts to access a locked
+byte range through a second file handle, the attempt fails, and that an
+exclusive lock denies all other processes both read and write access to the
+range. Every read of that byte through any other handle therefore fails with
+`ERROR_LOCK_VIOLATION`.
+
+Both symptoms follow directly:
+
+- The external probe calls `read_service_instance_lock_record()`, which opens
+ the file fresh and reads byte 0. The read raises, the `except OSError` returns
+ `None`, and the probe concludes the lock was never acquired — while the
+ service is in fact holding it.
+- `current_process_owns_service_instance()` calls `service_lock_held_by`, which
+ opens a **second handle in the same process**. Its `_try_lock_file` correctly
+ fails, and then `_lock_file_pid` reads the locked byte through that second
+ handle and also fails, yielding `None`. `None == os.getpid()` is false, so a
+ process that genuinely owns the lock reports that it does not, and
+ `_stop_for_lost_lease` shuts the service down.
+
+The smallest fix is to stop overlapping the two: on Windows, lock a sentinel
+byte at a fixed offset past any plausible record instead of byte 0, leaving the
+JSON payload readable by every handle while the lock is held. POSIX keeps
+`flock`, which is whole-file and unaffected. The compatibility caveat to decide
+before shipping it: a process locking byte 0 and one locking the sentinel byte
+do not exclude each other, so a mixed-version transition needs the old service
+stopped first.
+
+This is reproducible on `windows-latest` without any packaged Runtime — it needs
+one lock file, two handles and a read — so an existing Windows CI job could hold
+the regression test whenever this is picked up. Two related notes found while
+diagnosing and deliberately left alone: `storage/lock.py::_try_lock` has the
+same overlap shape for the migration lock, and the `_stop_for_lost_lease` log
+line claims the service "no longer owns" the lock, which asserts a transition
+nobody observed — it should say the ownership check failed.
+
+## H14 — fixing the Windows service-lock blackout, red first
+
+Windows was reopened by owner decision to fix H13. The evidence was built before
+the fix, as a test that fails on Windows and passes on POSIX, wired into the
+existing `windows-control-ipc` job in `.github/workflows/lint.yml` — one lock
+file and two handles, no packaged Runtime, no installer, no new workflow. That
+job runs `tests/test_service_lock_record.py`, whose cases go through the real
+`vibe.runtime` entry points rather than a synthetic `msvcrt` demonstration, so a
+red there is the product defect and not a restatement of the platform fact.
+
+### The premise, verified rather than assumed
+
+The fix is Windows-only, which is safe exactly to the extent that no Windows
+service can be running today. That was checked against the code rather than
+inferred from the rc8 log:
+
+- `main.py` acquires the service lock unconditionally at startup, so every
+ Windows service takes it.
+- `RuntimeWorkSupervisor`, the watch service and the scheduled-task service each
+ capture `service_instance_lock_attached_to_process()` at construction, which is
+ true in a real service, and then poll `current_process_owns_service_instance()`.
+- That call re-opens the lock file, so on Windows it reads the record through a
+ handle that is not the one holding the lock, gets `None`, and answers `False`.
+- `RuntimeWorkSupervisor` is constructed with
+ `on_lease_lost=lambda: self.request_shutdown("service lease lost")`, so the
+ first such answer shuts the whole service down.
+
+There is no branch that skips the lease check for a real service, and no path by
+which the record becomes readable while the lock is held. A Windows service
+therefore cannot stay up on any released version, which is why moving the locked
+byte cannot break a working installed base: on Windows there is none, and POSIX
+is not touched.
+
+### The fix
+
+`vibe/runtime.py` now locks `_WINDOWS_LOCK_BYTE_OFFSET = 1 << 30` instead of byte
+0, applied to the raw descriptor through `_windows_lock_byte` because a text
+handle cannot seek to an arbitrary byte, and restoring position 0 afterwards so
+the buffered handle stays coherent for the record write and read around it.
+Locking past end-of-file is legal on Windows, costs no disk and does not extend
+the file. The record itself is untouched: it stays a plain JSON document from
+byte 0, which is what keeps `read_service_instance_lock_record` and a human
+running `type service.lock` working. The alternative — keeping the lock on byte 0
+and starting the record at byte 1 — was rejected for exactly that reason and is
+pinned against by a test.
+
+The POSIX branch is unchanged, and a test asserts it: the advisory whole-file
+`flock` is taken with the descriptor at offset 0, so the platform that does have
+an installed base keeps excluding today's releases byte for byte.
+
+### `storage/lock.py::_try_lock` — reachable, different consequence, left alone
+
+The same overlap shape is there, and it is reachable on Windows, but the
+consequence is not the same and fixing it the same way would be a net loss:
+
+- The migration lock's exclusion works correctly on Windows today. A waiter's
+ `_try_lock` fails, which is the right answer, and it waits and retries. Only
+ `_recorded_holder` reads the locked byte, and it feeds one log line —
+ "held by pid unknown" instead of a pid. Its own docstring already says nothing
+ decides on that value.
+- Unlike the service lock, this path **works** on Windows, so it does have an
+ installed base. It is taken during startup before any lease check, and by plain
+ `vibe` CLI commands that never become a service.
+- Moving its byte would therefore create a real old-versus-new window in which two
+ processes both hold "the" migration lock and migrate the same SQLite database
+ concurrently. Trading a corrupt-database risk for a log line that already reads
+ as an honest "we do not know" is the wrong trade.
+
+Recorded here rather than fixed. The two other Windows `msvcrt` lock sites,
+`core/managed_runtime.py` and `core/show_runtime.py`, were checked and do not
+have the defect: they use the lock file purely as an exclusion token and identify
+it with `fstat`/`lstat`, never by reading its bytes.
+
+### The log lines that cost three release candidates
+
+`_stop_for_lost_lease` said the process "no longer owns the service lock", a
+transition nobody observed, and `core/watches.py` said the same thing in its own
+words. Both now say what was actually established — re-reading the lock did not
+confirm this process as its holder, either because the lock went away or because
+the record could not be read. The watch-service copy was corrected in the same
+round on the same reasoning that keeps `storage/lock.py` and its twin together:
+fixing one instance of a defect and leaving its duplicate is how the duplicate
+survives.
+
+### What the tests prove, and what they do not
+
+They prove that while the lock is held, its record is readable, the holder is
+named, the holder recognises itself through a second handle, a launcher can see
+the service it spawned, and the started phase is visible to a watcher — on
+Windows and POSIX alike. They prove the lock still excludes, and that POSIX still
+locks the whole file advisorily at offset 0.
+
+They do not prove that a Windows service now starts end to end: that needs the
+packaging probe, which is a separate decision. They do not cover a mixed-version
+Windows transition, because the premise above says there is nothing to transition
+from. They say nothing about the migration lock, deliberately.
+
+## H15 — control IPC hardening orphaned the runtime directory
+
+`gh-v3.1.1rc9` failed on `desktop-packages / x86_64-pc-windows-msvc` in "Build
+verified private Runtime". The whole private runtime tree went unreadable to the
+process tree that created it: the service lock, both captured stdio logs and the
+model-hub tree, the last of these with an explicit `[WinError 5]`. `release` was
+skipped, so no rc9 release object exists.
+
+### Mechanism
+
+`core/control_ipc.py` hardens the directory containing the endpoint descriptor,
+and that directory was the runtime directory itself — `write_descriptor_atomic`
+passed `target.parent` to `_ensure_private_directory(..., allow_repair=True)`,
+where `target` was `get_runtime_dir() / "control-ipc.json"`.
+
+`SetNamedSecurityInfoW` with `PROTECTED_DACL_SECURITY_INFORMATION` propagates.
+The DACL it applies carries no inheritable ACE, so the propagation strips the
+inherited ACEs from every child that already exists. Children created purely by
+inheritance hold no explicit ACE of their own and are left with an effectively
+empty DACL — unreadable even to their owner's later `open()`.
+
+The discriminating observation is what stayed readable. `runtime/status.json`
+survived and was the newest file in the directory, because `write_json` goes
+through `write_atomic`, which creates a fresh `mkstemp` file and `os.replace`s
+it: a child created *after* the stamp takes the creating token's default DACL
+rather than parent inheritance. `logs/vibe_remote.log` survived because it is in
+a different directory. Timing agrees: uvicorn started at 04:40:55,077 and the
+first `PermissionError` landed at 04:40:55,097.
+
+This never fired before `03662baa7`, which taught the owner check to accept an
+elevated token's default owner. Until then the check raised before reaching
+`SetNamedSecurityInfoW`. The fix was correct; it made a latent defect reachable.
+
+### The boundary decision, and why the inheritance flags are not the fix
+
+The obvious repair is `(A;OICI;FA;;;{sid})` so children inherit the grant. It was
+rejected. Control IPC's legitimate concern is one descriptor and one lock;
+making its ACEs inheritable would hand it the ACL of the entire runtime tree
+recursively — logs, model-hub, and every model file the Runtime ever downloads —
+stripped to user and SYSTEM. It also carries a Windows-only hazard:
+`_acl_signature` compares raw ACE bytes including the flags byte, and
+`_validate_security_descriptor` demands an exact match, so putting `OICI` in the
+shared SDDL risks failing validation on the files created with it, which would
+break service startup on Windows only.
+
+The descriptor moved to `runtime/control-ipc/endpoint.json` instead. The stamped
+directory now contains only objects control IPC created, each with its own
+explicit protected security descriptor, so stripping inherited ACEs from them is
+a no-op. The lock follows automatically: `_descriptor_lock` derives it with
+`descriptor_path.with_name(...)`, and the only `_ensure_private_directory` calls
+take that same parent.
+
+**The non-inheritable ACE is now correct by construction, not merely tolerated.**
+Nothing inside that directory relies on inheriting anything, so adding `OI`/`CI`
+would fix nothing and would only push control IPC's policy onto files it does not
+own. Both `config/paths.py` and the SDDL itself carry that note, because the next
+reader would otherwise "repair" it.
+
+Cost of the move was one path expression. No Rust, TypeScript, workflow or
+manifest computes that path, and there is no persisted-shape risk:
+`core/control_ipc.py` is not an ancestor of master and appears in no `v*` tag,
+only `gh-v3.1.1rc5`..`rc9`, this PR's own pre-releases. The descriptor is also
+ephemeral state rewritten at every service start. On POSIX nothing changes at
+all: `write_descriptor_atomic` is reached only from `WindowsLoopbackHost.publish`.
+
+### The test, and the assertion that would have passed on the defect
+
+The reproduction asserts that a file which exists **before** the securing call is
+still readable **after** it. The natural phrasing — "a file created inside the
+secured directory is readable by the process that created it" — describes the one
+case that still works today, and would have gone green on broken code. That is
+the same failure mode as asserting on the SDDL string, one level subtler.
+
+Both tests reach the endpoint through
+`paths.get_runtime_control_ipc_endpoint_path()` rather than a literal path, so
+they state the required behaviour rather than the chosen remedy and would have
+held against either candidate fix. They ride the existing `windows-control-ipc`
+job, which already runs `tests/test_control_ipc.py`, so no workflow change was
+needed.
+
+The red run settled a fact neither the lane nor the orchestrator had
+established. At `7981a1c9e`, job `107054477281` reported **1 failed, 31 passed**:
+the pre-existing-sibling case died on `lock.open("a+")` with `[Errno 13]` —
+the same call and errno that killed rc9 — while the create-path case **passed**.
+So a child of a directory created by `CreateDirectoryW` with a protected,
+non-inheritable descriptor takes the creating token's *default* DACL, which is
+explicit rather than inherited, and propagation never touches it. Only children
+that hold inherited ACEs can be orphaned. The create path is therefore a
+regression guard, not a second instance of the defect.
+
+## H16 — `vibe stop` hung because the process scan shelled out per process
+
+`gh-v3.1.1rc10` got further on Windows than any candidate before it: the ACL fix
+held, the service took the lock, the readiness poll passed, and `vibe start`
+printed a valid receipt. Then `vibe stop` produced **not one byte on either
+stream and never returned**, and the packaging probe killed it at its 60s
+budget. `vibe_remote.log` has no shutdown entry, so the service was never asked
+to exit — the hang was inside the stop command, before it signalled anything.
+
+### Mechanism
+
+`cmd_stop` prints nothing before `runtime.stop_service()`, and `stop_service`
+calls `extra_service_process_pids()` unconditionally after resolving the lock
+owner. That runs `service_processes()`, which walks **every process on the
+machine**. Per process it did a liveness probe and then `_process_command_from_info`,
+which fell through to `get_process_command(pid)` whenever psutil could not read
+the command line — and `process_iter` fills a denied attribute with `None`,
+which on Windows is the ordinary outcome for most system processes.
+
+On Windows `get_process_command` spawns `powershell -NoProfile -Command
+Get-CimInstance Win32_Process ...` with **no timeout**, then retries with `pwsh`
+when the first returns nothing. Two process launches per unreadable process,
+several hundred processes, on the platform where a process launch is most
+expensive.
+
+The defect is not Windows-only, only Windows-visible. The same fallback runs
+`ps -p` once per process on macOS — the reproduction launched 64 of them for 64
+scanned processes — and escapes notice only because a fork is cheap there.
+Linux never reaches it, because `get_process_command` reads `/proc` first.
+
+Nothing else on the stop path can account for the 60s. `stop_pid` does call
+`get_process_command`, but every one of those calls sits on the POSIX branch:
+on Windows it returns through `_terminate_process_windows` first. The remaining
+Windows lookups are single-pid ones — owner resolution, UI identity — a handful
+of calls, not one per process.
+
+### The fix
+
+`_process_command_from_info` now answers from what `process_iter` already
+collected, or not at all. Nothing is lost. The scan is explicitly secondary to
+the service lock: it exists to find lock-less daemons left by older lifecycle
+bugs, and such a daemon is a process this install started, whose command line
+psutil can read. A process whose command line we cannot read is by construction
+not ours. The one case that could have made this wrong — a lock holder with an
+unreadable command line — was never findable this way either, because
+`service_lock_held_by` is only reached *after* the command filter passes; the
+authoritative owner comes from `resolve_service_owner_pid` and the lock.
+`_process_command_from_info` has exactly one caller, so the change cannot reach
+anything else.
+
+`_get_process_command_windows` keeps its shell, because naming one specific pid
+is what it is for, but now runs it under a 5s timeout per shell. The existing
+`except Exception: continue` already catches `TimeoutExpired` and moves on.
+
+Rejected: making that lookup try psutil before the shell. psutil returns a
+shlex-joined argv while the CIM query returns the raw Windows command line, and
+`_command_looks_like_service_entry` and `_tool_family_from_text` parse those
+strings — a quiet format change on an identity path, to save a little on calls
+that are now bounded anyway.
+
+### What the tests prove
+
+`tests/test_runtime_process_scan.py` asserts the mechanism, not a duration: over
+64 processes whose command line psutil cannot read, the scan must start **zero**
+external processes. A timing assertion alone would be flaky and silent about the
+cause; this one is red on every platform, so it keeps defending the invariant
+without a Windows runner. A second test requires the single-pid Windows lookup
+to pass a positive timeout. A third, Windows-only and read-only, runs the real
+scan against the real process table under a budget priced off that machine's own
+`process_iter` walk — `process_iter` never shells out, so the defect cannot
+inflate the measurement and buy itself room. It rides the existing
+`windows-control-ipc` job, which needs neither a packaged Runtime nor an
+installer, so this class never has to cost a release candidate again.
+
+## H17 — the endpoint budget was sized for a warm launch
+
+rc11 installed on macOS and met the bootstrap error screen —
+`runtime_discovery_failed`. Not Gatekeeper, not the config, not the descriptor:
+`query_endpoint` gave `<private python> -I -m vibe desktop endpoint --json` 10s,
+and a genuinely first launch cannot answer that fast.
+
+Measured on an M-series Mac with the exact environment `RuntimeCommand::private`
+builds:
+
+| condition | wall time |
+| --- | --- |
+| cold — fresh extraction, fresh HOME | 15.81s |
+| cold — fresh extraction, fresh HOME (independent repeat) | 18.36s |
+| cold — x86_64 runtime under Rosetta | 19.99s |
+| warm binaries, fresh HOME (config creation only) | 4.12s |
+| warm binaries, warm HOME | 2.31s / 2.73s |
+| warm binaries with `com.apple.quarantine` applied recursively | 3.26s, exit 0 |
+
+The command is correct and always succeeds; it just could not finish inside 10s
+the one time it mattered. `PrivateRuntimeBundle::prepare()` has only just
+extracted the runtime tree, so nothing in it has been paged in or evaluated yet
+and the interpreter pays for all of it on this one call. That cost is paid
+**once per installed runtime version** — the second launch is warm and works,
+which is exactly why our own DMG verification never caught it. Quarantine is not
+a factor: these are ad-hoc/linker-signed binaries spawned directly rather than
+through LaunchServices.
+
+The asymmetry is what makes it a defect rather than a tuning question. Readiness
+already budgets 120s (`DEFAULT_READY_TIMEOUT`, matching
+`SERVICE_SLOW_START_TIMEOUT_SECONDS`); the endpoint query was the last step on
+the cold path still holding a number sized for a warm one. Raised to 60s: 3x the
+worst measurement for slower hardware, still well under readiness so discovery
+cannot dominate a launch. The budget is only spent in full when the endpoint is
+genuinely broken, and that failure is already retryable — so no adaptive tier,
+no first-run flag, no persisted state.
+
+The test drives the real `query_endpoint` deadline with a fake runtime that
+sleeps past the old budget and then prints a valid descriptor, so it fails on the
+constant rather than on a value read back from it. It is `#[cfg(unix)]`, like
+every other process-spawning test in that module, which reuses the existing
+`write_fake_runtime` harness instead of inventing a Windows equivalent for a
+mechanism that has no platform-specific branch. **Ruled by the orchestrator:
+accepted.** The 60s constant has no platform branch, so a Windows fake-runtime
+harness would test the harness rather than the deadline.
+
+## H18 — the rollback belonged to the region, not to the branch
+
+Two reviewed heads, one root-cause class, which is what the review-loop circuit
+breaker exists to catch:
+
+| head | finding | shape |
+| --- | --- | --- |
+| `a09e74a2d` | roll back a newly started service when UI startup is **refused** | `start_ui` returns `None` |
+| `5f6f47cdc` | roll back the service when UI startup **raises** | `start_ui` throws |
+
+The invariant behind both is one sentence: *a service this command started must
+not survive a start that never printed a receipt.* An unreceipted service is
+adopted as `reused` on the next launch, so the desktop shell never acquires
+scoped stop authority and Stop Runtime silently stops working.
+
+The first fix encoded that invariant as a branch-local undo inside the single
+failure mode the reviewer had named. That is why a second finding was not bad
+luck: the invariant is a property of the whole pre-receipt region, and any region
+guarded one named branch at a time yields findings one at a time forever. The
+region runs from `start_service` returning through `print(receipt_line)`, and it
+contains a UI restart, a process spawn, three status writes, a readiness wait
+that can run to `SERVICE_SLOW_START_TIMEOUT_SECONDS`, the receipt builder and a
+browser launch — every one of which can fail into the same orphan.
+
+So the second fix does not add a second undo next to the first. One
+`try/except BaseException` spans the region, the `ui_pid is None` branch loses
+its local `stop_service()` and reaches the same mechanism by raising, and the
+bare `raise` leaves the original failure unchanged. Exactly one stop per failed
+start, none once the receipt is out, never against a reused service.
+
+`BaseException` rather than `Exception` is deliberate. `KeyboardInterrupt` is not
+an `Exception`, and the readiness wait is both the longest step in the region and
+the likeliest moment for a user to give up — an interrupted start orphans the
+service exactly like a crash does. `SystemExit` is included on the same logic:
+nothing in the region exits on purpose, and to the next launch an exit before the
+receipt is indistinguishable from any other start that never finished.
+
+Four mutations, each mapped to one requirement: restoring the old branch-local
+shape fails the three new region tests while still passing the two the first
+review earned; `except Exception` fails only the interrupt test; dropping the
+`not service_reused` scope fails both reused-service tests; and turning the guard
+into a `finally` fails the receipt-boundary test.
+
+**The lesson, generalised.** When a fix encodes an invariant, encode it for the
+region that owns the invariant, not for the branch the reviewer happened to name.
+A finding names an instance; the fix has to name the class, or the next instance
+is already written.
+
+## H19 — rc12: the private Runtime invalidated its own install
+
+rc12 launched once, then paid a full 358MB re-extraction on every later launch,
+and after two launches refused to start at all.
+
+### Mechanism
+
+`RuntimeCommand::private` runs the interpreter with `-I`, and `-I` implies `-E`:
+every `PYTHON*` variable is ignored, including the `PYTHONDONTWRITEBYTECODE=1`
+the launcher sets. The interpreter therefore wrote `__pycache__/*.pyc` into its
+own install tree. `verify_installed_tree` checks that tree against the archive
+manifest, so the next launch saw extra files, judged the copy invalid and
+extracted a fresh one into the repair slot. That copy was then invalidated the
+same way, and with both slots invalid `prepare()` returned
+`ArchiveVerification`: a bricked install whose only exit was deleting a
+directory by hand.
+
+### The fix
+
+- **`-B` beside `-I`.** A flag cannot be dropped by `-E`, so the launcher now
+ passes `-I -B -m vibe`. The test runs the real interpreter prefix against a
+ scratch tree and asserts no bytecode appears in it. Cost, measured on the
+ endpoint command: 7.50s cold, 3.30s warm — inside H17's 60s budget. Shipping
+ precompiled bytecode would remove that cost, but it is a packaging change and
+ `desktop-package.yml` is frozen for this release.
+- **Two invalid copies recover instead of stranding.** The old refusal existed
+ because a daemon started from a copy that was valid at launch may still have
+ its files open. `discard_install_path` keeps that safety: it renames the
+ primary slot to `.discard-<pid>-<seq>` (atomic, and open handles survive it),
+ then deletes the renamed copy best-effort, so the reinstall lands on a name
+ nothing is reading. A tampered tree is still never executed. This is a
+ deliberate contract change: `two_tampered_install_slots_fail_closed` is
+ replaced by `two_tampered_install_slots_are_reinstalled_rather_than_stranded`,
+ which repeats the double-tamper three times and asserts that exactly two slots
+ and no discarded copies remain after each round.
+- **A bootstrap log.** This takes up the deferred `stderr(Stdio::null())` ledger
+ entry below. The shell appends to `bootstrap.log` in the application's local
+ data directory (`~/Library/Application Support/bot.avibe.desktop/bootstrap.log`
+ on macOS), capped at 64 KiB and trimmed at line boundaries from the front
+ through a sibling file and a rename. It records one `runtime.prepare` line
+ (`reused` / `extracted` / `failed`, duration, root or error) and one
+ `endpoint.query` line per attempt (outcome, duration, exit status, error, and
+ up to 4 KiB of stderr tail). `reused` exists for this line: an install that
+ reports `extracted` on every launch is the rc12 defect in one word. Writing the
+ log never changes an outcome — every I/O error in it is dropped.
+
+**Known residual, accepted by the orchestrator.** `discard_install_path` renames
+the primary slot away even while a Runtime of the same version is still running
+from it, and that Runtime outlives the window. Files it already holds open
+survive the rename; imports it has not yet made do not. With `-B` in place, both
+slots can go invalid only through external tampering, and the alternative is the
+permanent brick this section removed, so the trade stands.
+
+### A timing fact the timeout test had to learn
+
+The endpoint-timeout test passed alone and failed under the full `cargo test`
+run. Instrumented, the first execution of a just-written executable on macOS
+took ~4.85s to reach its first line under that load; later executions of the
+same file took 10–25ms, and the spawn call itself returned in ~1.6ms. The test
+now runs its fixture once before the measured call, so that one-time cost sits
+outside the deadline by construction rather than inside a wider margin. The
+fixture writes its stderr through `/bin/echo`, because `exec` would discard the
+shell's own unflushed buffer.
+
+## H20 — review of `5da131969`: three findings
+
+- **F1 — rollback undid the service but not the UI.** This is the third reviewed
+ head in H18's class, so the breaker applies and the fix names the invariant
+ rather than the branch: *this invocation leaves running nothing it created.*
+ Created means `pid is not None and not reused` in the `ProcessStartInfo` that
+ `start_service` and `start_ui` already fill in, so no new state is needed. The
+ region's `except BaseException` undoes in reverse order: the UI, then the
+ service. `stop_ui` is called with `stop_remote_access=False`, because
+ `vibe start` never brings a tunnel up — `remote_access.start()` is reached only
+ from the UI's explicit endpoint and from `vibe remote` — so any tunnel alive at
+ rollback predates the command, and stopping it would destroy a remote URL this
+ invocation did not create. Consumers: an interrupt before the receipt with a UI
+ this invocation started (both stopped, UI first, tunnel kept); the same failure
+ with an adopted UI and a reused service (neither stopped); a receipt-builder
+ failure (both stopped); the success path (neither stopped). Mutations: dropping
+ the `ui_start.reused` scope fails only the adopted-UI test; removing the UI
+ stop fails the interrupt and receipt-builder tests.
+- **F2 — a missing private backend could upgrade an external CLI.**
+ `resolve_cli_path` falls back to basename discovery on `PATH`, so when the
+ configured desktop-managed path was missing, ownership was judged on whatever
+ external binary discovery found, and the generic upgrade ran against it.
+ Ownership is now judged on the configured path first and the discovered one
+ second. A missing managed backend routes to `_run_desktop_backend_install`,
+ and a missing private-runtime `codex` with no toolchain returns
+ `desktop_managed_backend` naming the configured path. Tests put a real external
+ CLI on `PATH` behind tripwires on every process-spawning seam. Mutation:
+ judging ownership on the discovered path alone fails four cases.
+- **F3 — `*` as the setup host.** `*` is a word, not an address; `getaddrinfo`
+ rejects it. **Fixed here, pre-existing on `master`, not introduced by this
+ PR:** uvicorn's bind on `master` fails the same way for the same input. It is
+ now normalised once, in `_normalized_bind_host` (to `0.0.0.0`, next to the
+ existing `[::1]` → `::1` unbracketing), which every listener derives from, and
+ the separate `*` rule in `requires_desktop_loopback_listener` is gone.
+ `_is_wildcard_setup_host` is unchanged. A test binds the `*` spelling for real.
+ Mutation: removing the normalisation fails three tests, including a real
+ `gaierror`.
+
+Also fixed in this head: `test_start_ui_replaces_stale_live_pid_when_health_check_fails`
+stubbed `ui_server_healthy`, but adoption on this branch is decided by
+`_ui_server_compatible`, which probes the real listener. The test therefore
+adopted whatever answered on `127.0.0.1:5123` — on a developer machine, their own
+running UI — and failed. It fails the same way at `5da131969` without this
+round's changes, and passes on CI only because nothing listens there. It now
+stubs the seam that decides. The listener it found was the rc11 desktop app the
+orchestrator had launched on the same machine to prove H17's root cause: the
+"real services are production data" case in `AGENTS.md`, met in practice.
+
+## H21 — review of `bb0c8de75`, native Settings, and what this head leaves out
+
+Three review findings, fixed in their own commits, plus one owner item.
+
+- **F1 — a spawned child could outlive the step that was meant to record it.**
+ Every rollback could undo only what it had been told it created, and it was
+ told only after the spawn primitive returned. The work between `Popen` and
+ that return (the Memory UI secret written to stdin, the pid record) could
+ raise with the child already running, and H18 and H20 each closed one such
+ window at a consumer. The fix is at the primitive: `spawn_background` and
+ `spawn_service_background_process` share one implementation that kills and
+ reaps the child if anything after `Popen` fails, then re-raises, and the
+ service start applies the same rule to its reservation write. `cmd_start`
+ opens its rollback region before `start_service`, so an interrupt during the
+ lock wait undoes a service it created. Consuming tests use real sleeping
+ children with the failure injected at the pid write, the stdin write and the
+ reservation. This head still returned the child before its caller captured
+ it, and closed the parent's handles after the region; H22 closes both gaps.
+- **F2 — the main window dropped every new browsing context.** `target="_blank"`
+ links and `window.open(url)` did nothing, so the OAuth dialog's provider link
+ could not be followed. The main window now answers each request with one
+ decision: http(s) goes to the system browser and the request is denied;
+ anything else, `about:blank` included, is denied. There is deliberately no
+ relay webview: on macOS a popup webview must share the opener's
+ `WKWebViewConfiguration`, and wry registers each webview's init scripts and IPC
+ handler on that shared content controller, so a relay would copy its scripts
+ into the main window and, when dropped, remove the main window's IPC handler.
+ The window's config entry is `create: false`, so the startup window and every
+ recreated one come from `ensure_main_window` and carry the handler.
+ **Accepted UX limitations of this release:**
+ - The OAuth dialog pre-opens `about:blank`, which is now denied, so it falls
+ back to its visible provider link. That link needs one extra click; it opens
+ in the system browser, and the callback still completes through loopback
+ polling.
+ - The Show Page launch menu hides "New link" in the shell, because that item
+ navigates a pre-opened tab that never exists here. "New window" is kept.
+ - Every other "open in new tab" affordance (Dock, Library, app search, Show
+ Pages list) now opens the Workbench URL in the system browser instead of
+ doing nothing.
+- **F3 — the private Runtime inherited the shell's `PYTHON*` variables.** `-I`
+ shields only the interpreter it is passed to; the Controller and UI
+ interpreters the Runtime starts run without it, so an inherited `PYTHONHOME`
+ aborted both and a `PYTHONPATH` imported code from outside the verified tree.
+ The private `RuntimeCommand` now strips every inherited `PYTHON*` variable
+ (case-insensitively on Windows) before its own overlay. The development shell
+ keeps the user's environment.
+- **The desktop marker.** The main window defines a non-writable
+ `window.__AVIBE_DESKTOP_SHELL__ = true` through an initialization script before
+ any Workbench script runs, top-level document only: macOS injects it into the
+ main frame alone, and the script checks `window.self === window.top` because
+ WebView2 injects into subframes too. The UI reads it through `isDesktopShell()`
+ in `ui/src/lib/desktopShell.ts`, deliberately separate from `useIsDesktop`,
+ which is the viewport breakpoint. No user agent sniffing and no
+ `__TAURI_INTERNALS__` check.
+- **Settings… in the app menu and the tray** (`CmdOrCtrl+,`). It delivers
+ `avibe://settings` through the existing deep-link path, which maps it to
+ `/admin/settings/service`; the Workbench redirects that legacy path to
+ `/settings/service`. The item is enabled only while the shell monitors a
+ Workbench it navigated to, and the handler applies the same rule before
+ delivering, so the bootstrap window is never navigated to the Workbench origin
+ and nothing is queued for a later start. No new Tauri command.
+
+**Deferred by the orchestrator: Check for Updates.** The runtime's update checker
+short-circuits for a managed runtime; PyPI cannot see the `gh-v` desktop builds;
+and answering from GitHub Releases is a new resolver, not a small change. It
+moves to a follow-up PR.
+
+**Not in this head: the overlay title bar.** The owner's shape (macOS overlay
+title bar, hidden title, a shell-only top inset under the traffic lights, a drag
+region on the top strip) needs a drag path, and on macOS there is only one.
+WKWebView honours no `app-region` CSS and swallows the mouse events that would
+move the window natively (tao notes the same about
+`movable_by_window_background`); wry enables non-client regions only on
+WebView2. Tauri's `data-tauri-drag-region` script invokes
+`plugin:window|start_dragging` over IPC, and the Workbench is a remote origin
+with no capability, so the call is refused. Making it work means adding a
+capability with a `remote` URL for the loopback Workbench origin, which would
+break this shell's stated invariant that no capability names a remote URL. The
+lane will not change that boundary on its own authority. Shipping the overlay
+without a drag region would leave an undraggable window, so the item was dropped
+from this head, as the owner allowed.
+
+## H22 — orchestrator hold on `f654f245b`
+
+Two more boundaries in F1's class, one Settings gap, and the title-bar ruling.
+
+- **F1, the parent's handles.** The spawn primitive closed its copies of the
+ child's stdin and log-sink handles in a `finally`, after the region that owns
+ the child. A close that raised therefore propagated with a running child the
+ caller never received. The closes now run inside the region, before the
+ hand-over; the failure path closes whatever is left quietly and re-raises the
+ original error. Tests fail each of the three closes with a real sleeping child.
+ Mutations: moving the closes back to `finally` fails all three; closing loudly
+ on the failure path fails the two secret-write tests.
+- **F1, the capture.** H21 accepted a window between `spawn_background`
+ returning and `start_ui` calling `start_info.capture(pid, reused=False)`: a
+ created UI that `cmd_start`'s rollback could not see. The service had the same
+ window between its reservation and `result(pid, reused=False)`. The primitive
+ now takes a `hand_over` callback and runs it inside the region, so nothing is
+ returned before it is captured. For the UI it writes the pid record, then
+ captures; for the service it registers the process, writes the reservation,
+ then captures. A failure or interrupt at any step kills and reaps the child.
+ A `withdraw` callback then removes the record, but only when the child was
+ reaped and the record still names it, so a child that could not be confirmed
+ dead stays findable by `vibe stop`. The existing `ProcessStartInfo` is the only
+ ownership state; reused and adopted paths are unchanged; no signal masking.
+ Tests inject a `KeyboardInterrupt` after the record or reservation and before
+ the capture, with real sleeping children, both at the primitive and through
+ `cmd_start`: no child survives, no record is left, no receipt is printed and
+ the status never reads `running`. A third `cmd_start` test interrupts after a
+ real UI was captured and proves rollback stops it through its record, before
+ the service. Mutations: capturing after the return fails the UI and service
+ tests at both layers; no `withdraw` fails four; withdrawing unconditionally
+ fails the confirmed-dead test; skipping the UI capture fails four, including
+ the real rollback; skipping the kill fails eleven.
+- **Settings at the Workbench hand-off.** The item's availability was
+ recomputed only on tray status refreshes, so after the shell navigated to the
+ Workbench it stayed disabled until the monitor's first tick. The main window's
+ page-load `Finished` handler now refreshes every native control through the
+ same `refresh_native_controls` rule, passing no status, so the status already
+ shown is kept and a bootstrap page still enables nothing. Mutations: dropping
+ the page-load refresh fails the boundary test; a page load that invents a
+ status, or ignores the one shown, fails the unit test.
+- **Title bar.** The orchestrator's ruling: this TEST release keeps the stock
+ native title bar, and no capability is widened. Removing it is a follow-up,
+ scoped independently of Check for Updates.
+
+## H23 — Start at Login terminal policy on `1f869b519`
+
+- **Windows checkout.** `1f869b519` makes `shell_boundaries.rs` normalize CRLF
+ to LF once, in `shipping_text`, before any source assertion. A Windows
+ checkout had failed a multi-line check. Test-only; a CRLF copy of `lib.rs`
+ must read as the same shipping text.
+- **The finding.** Codex P2 4086509105 found the uninstall's restore closure
+ discarding the result of `enable()`. When the disable succeeds, the removal
+ fails and the re-enable also fails, Start at Login stays off with nothing
+ reported, and the menu can show a stale check.
+- **Circuit breaker.** This was the third head in one root-cause class:
+ compensation for a failed multi-step operation is incomplete (reviewed heads
+ `d65847228`, `b85261e41` and `1f869b519`). The orchestrator diagnosed the
+ class and ruled that the chain ends in a terminal policy, not a deeper
+ compensation.
+- **The ruling.** Every Start at Login write that must settle the menu goes
+ through one policy, `settle_start_at_login`:
+ 1. write the requested state once;
+ 2. read it back;
+ 3. draw the checkbox from what was read, even on error;
+ 4. report a failed write, a failed read, or a read that disagrees with the
+ request using the existing `login_failure` message.
+
+ The write is an `FnOnce`, so nothing is retried and nothing is persisted.
+- **Where the policy is used.** The menu toggle and the uninstall's restore
+ both reach it through `set_start_at_login`. The restore callback now returns
+ whether the registration came back. A failed restore ends as
+ `UninstallOutcome::KeptWithoutLogin`: the login failure is reported, the
+ existing runtime-removal failure is still reported, and neither the success
+ dialog nor the exit runs.
+- **Not covered by the policy.** The pre-removal disable stays outside it. Its
+ failure already fails the uninstall closed, with the existing report, before
+ the Runtime is touched.
+- **Tightening.** Counting a disagreeing read as unsettled narrows the toggle.
+ Before, it reported only errors; now a write that claims success but reads
+ back the other state is reported too.
+- **Tests.** Unit tests drive the policy directly, and the uninstall tests
+ drive the restore through it. A new case: disable succeeds, removal fails,
+ restore is attempted and fails. That run draws the observed state, reports
+ both failures and never reaches `Removed`. A boundary test pins the one
+ adapter, one call to the policy, one `.enable()` and one checkbox write.
+- **Mutations.** Each mutation below fails at least one test:
+ - ignoring the restore's result;
+ - dropping the failure report;
+ - counting only errors as unsettled;
+ - skipping the redraw on error;
+ - restoring outside the helper;
+ - retrying in the adapter.
+- **Scope.** No new command, capability, dependency or copy. No UI or title-bar
+ change. This commit touches only `desktop/src-tauri/src/lib.rs`,
+ `desktop/src-tauri/tests/shell_boundaries.rs` and this plan.
+- **Correction to the release-file freeze.** Earlier sections, from H4 on, say
+ the release implementation files are byte-identical to
+ `13082a8501ce5d1e771f56395a72fc062859cf8b`, apart from the two
+ `release_ai.yml` checkout pins. Each claim held at the head it named. As a
+ cumulative statement it has not held since `51784cc2b`, the merge of master
+ `fb460f2bf` (#2120, Memory removal).
+- **Where the release files stand.** Object hashes against `13082a850`:
+ - Unchanged: `desktop/README.md`, `docs/desktop-test-installation.md`,
+ `scripts/desktop_release.py` and `.github/workflows/desktop-package.yml`.
+ - Changed: `.github/workflows/release_ai.yml`,
+ `tests/test_desktop_release.py` and `tests/test_release_verification.py`.
+
+ Every change beyond the pins comes from master and entered only through that
+ merge: #2120's own removal of the Memory runtime job and its verifier tests,
+ and the merge's conflict resolution adapting this branch's release tests to
+ that removal. The resolution dropped the Memory assets and `needs` entries,
+ and added a focused source-SHA assertion in place of a check #2120 removed.
+ No commit after `51784cc2b` changes these three files, and this candidate
+ does not either.
+
+## H24 — review of `5c02720`: three findings, one fixed here
+
+Codex review 5296471145 on `5c02720dcbe86b2b25a08cccf4ee5f3334f8a17f` raised
+three P2 findings, none in code that commit changed. Two repeat a class already
+seen on an earlier reviewed head, so the lane stopped patching and the
+orchestrator took the inventory and made the scope ruling below.
+
+- **4087030728, OAuth `about:blank`: accepted, no change.** Same surface as
+ 4081302902 on `bb0c8de75`, which produced F2. The finding restates F2's first
+ accepted UX limitation. The shell denies the `about:blank` preopen because it
+ cannot safely create a relay webview, so the dialog falls back to its visible
+ provider link. That link opens in the system browser, and the rest of the
+ journey is unchanged. The thread was answered with that contract and resolved,
+ not claimed as fixed.
+- **4087030743, queued startup dependencies: fixed here.** Same predicate as
+ 4071875523 on `d65847228`. One level down, `dependencyIsStartupRepairing`
+ answered two questions:
+ - "Is this being installed right now?" This drives the status badge, the
+ spinner and the button label.
+ - "May the user start an install now?" This drives the button's enablement.
+
+ The earlier fix narrowed the predicate to the active step, which the first
+ question needed, and that also narrowed the second. So while askill installed,
+ a later missing Model Hub engine stayed actionable, and the reconciler could
+ reach it with a manual job already holding its lock. The backend locks already
+ stop two installers writing at once, so the cost was an `already_running`
+ result on one side, not corrupted state.
+ - **Fix.** A separate `dependencyNeedsStartupRepair` decides the action: the
+ dependency is startup-managed and missing, `upgrade_required` or `error`.
+ While `reconciling` is true, every such dependency's install, update or
+ repair button is disabled, whether or not it is the active step.
+ The button also stays disabled for the active step if its status is outside
+ that pending set. `dependencyIsStartupRepairing` keeps its active-ID filter
+ for the badge, spinner and label. Ready dependencies stay actionable.
+ - **Deliberate over-block.** A dependency the reconciler skips this pass, such
+ as Show Runtime without Node or tmux under `VIBE_INSTALL_SKIP_TMUX`, is also
+ withheld until the pass ends. The page keeps polling while `reconciling` is
+ true, so the action comes back when the pass does.
+ - **Tests.** A page test renders a pass with askill active, a missing Model Hub
+ engine and a ready avault. It asserts:
+ - only askill shows installing and a spinner;
+ - Model Hub reads missing, its button is disabled, and clicking it installs
+ nothing;
+ - avault's Reinstall stays enabled;
+ - once the pass ends, both install buttons are enabled.
+
+ A second page test covers an active step with `unknown` status: it shows
+ installing but cannot start a manual install. Pure tests cover the pending
+ states and the active-ID status boundary. The focused Settings suite passed
+ 1,627 tests in 100 files; `npm run build` (including TypeScript checks) and
+ `npm run lint` passed with no baseline drift.
+ - **Mutations.** Each fails at least one test: disabling only the active step;
+ drawing the spinner or the label from the pending set; dropping `error` from
+ the repair states; withholding regardless of `reconciling`.
+ - **Not changed.** Backend locks, API semantics and every other part of the
+ UI.
+- **4087030754, superseded private backend releases: deferred to #2131.**
+ Confirmed. Each successful install publishes to `releases/<uuid>`, and nothing
+ removes a release once `current.json` moves past it. So every Reinstall or
+ backend upgrade keeps another complete npm tree. Safe reclamation needs to
+ know whether a running process still uses an old release: Windows keeps open
+ handles, and Node loads files from its tree lazily. That is the same
+ cross-language in-use contract #2131 needs for the uninstall fence. Deleting
+ by age, or by `current.json` alone, could break a running agent, so no cleanup
+ heuristic is added. The ledger entry below records the residual.
+- **Scope.** This commit touches only
+ `ui/src/components/settings/SettingsDependenciesPage.logic.ts`, its page, the
+ page's two test files and this plan.
+
+## H25 — review of `c802848b`: two fixes and one false positive
+
+Codex review 5296978965 on `c802848b98417b51dfa8c3c4da4332ab99dcc6e9`
+raised three P2 findings. The orchestrator inspected the full inventory and
+approved a bounded resolver/probe fix; no identity or environment model change
+was needed. The older queued-dependency finding 4087030743 was already covered
+on that head by H24's global repair-action gate. Its active-ID-only status and
+spinner and the later Model Hub action were rechecked by the 16 focused UI
+tests; the thread was answered and resolved.
+
+- **4087472327, damaged private backend selector: fixed.** The shared CLI
+ resolver used to try a missing private absolute path, then discover the same
+ basename on PATH before consulting the desktop publication descriptor.
+ Runtime projection could silently select an external executable when an
+ app-private release disappeared. A missing path under the private backend
+ root now resolves only through the verified published descriptor, or stays
+ unresolved so the saved selector remains visible. Generic non-private
+ absolute paths keep basename discovery. A `to_app_config` consumer provides
+ same-name external executables for Claude, Codex and OpenCode and verifies
+ that none replaces a missing private selection; it also covers non-private
+ fallback and the private published-descriptor path.
+- **4087472342, wildcard UI health probe: fixed.** Binding already turns `*`
+ into `0.0.0.0`, but the first health URL still used the literal `*` and
+ returned before probing `/ready`. The health URL now uses the same bind-host
+ normalization, then probes loopback for wildcard binds. Direct URL coverage
+ and a `_ui_server_readiness` consumer verify both requests and successful
+ structured identity reuse.
+- **4087472352, Codex home: false positive, no production change.** The
+ validated private launch helper copies its caller-provided environment;
+ CodexAgent supplies `os.environ`, and CodexTransport passes that mapping as
+ the app-server subprocess environment. Custom `CODEX_HOME` is already kept.
+ `_safe_process_environment` filters separate npm installation and version
+ probe commands, not the private app-server launch. The publication consumer
+ now asserts `CODEX_HOME` reaches the launch environment while the installer
+ still excludes a fixture API key. The review thread was answered with the
+ exact call chain and resolved.
+
+This round does not change the TEST release implementation or native package
+workflow. Local validation: 309 focused Python tests passed across CLI path,
+desktop Runtime and private backend suites; changed-file Ruff and diff checks
+passed. The two focused Settings page test files passed 16/16, and UI build and
+lint passed without baseline drift. Exact-head CI, Codex review and publication
+remain separate gates.
+
+## H26 — rc13 distribution verification source boundary
+
+The `gh-v3.1.1rc13` Release (AI Notes) build-assets job 35927306218 built a
+wheel and sdist with all 21 builtin skill files, then failed their installed
+mirror checks. The expected snapshot was read from the release-automation
+sparse checkout, which contains the verification test but no `skills/**`, so
+the comparison used an empty expected set. The artifacts were not published;
+rc13 remains immutable evidence and cannot be reused.
+
+The expected skill bytes now come from the build-source checkout, which is
+also the working directory of the verification step. The test still compares
+every installed skill's path, hash and mode for both wheel and sdist and
+requires a nonempty source snapshot. This matters when a manually dispatched
+workflow checks out automation from a different revision than the requested
+release source: adding `skills/**` to the automation checkout would compare
+against the wrong commit. A sparse-checkout fixture exercises both workflows
+with distinct source and automation revisions, and installed wheel/sdist
+consumers check real built artifacts. The asset matrix and release workflows
+are unchanged; a new reviewed head and unused TEST tag are required.
+
+## H27 — latest master integration and owner-deferred P2 findings
+
+On 2026-09-24 the owner reopened the integration lane to include the actual
+current `origin/master` `ebebb64d3ca56f85032435576e2acf90c1197a34` in the
+desktop PR lineage. GitHub's PR `baseRefOid` was stale, so the merge used the
+explicitly fetched remote branch. The merge has the desktop candidate
+`e3fc4fa0c10bfb7126f2e12c6f134acdb3980534` and that master commit as its two
+parents.
+
+The merge had one textual conflict, in
+`tests/test_release_verification.py`. The desktop H26 contract copies the
+source-controlled `tests/test_distribution_artifacts.py` into the sparse
+fixture so its installed skill snapshot is authoritative. The master contract
+also copies `tests/e2e/**` and `tests/__init__.py` for the `publish.yml`
+release-automation checkout and consumes the retired-updater test from that
+checkout. The resolution keeps the union of both copy predicates and retains
+both consuming assertion sets. All other master paths, including the Memory
+release-upgrade gates and setup/onboarding UI, are preserved by the real merge;
+release workflow semantics and H26 packaging behavior are unchanged.
+
+The owner explicitly deferred the two unresolved Codex P2 findings on the
+pre-integration head. `4088247715` (legacy private Runtime CLI selectors must
+not fall through to PATH) and `4088247722` (initial adoption of a managed
+Runtime must retain liveness after the first shell navigation failure) are
+recorded as owner-deferred for this round. Neither finding is fixed by this
+integration commit, neither thread is replied to or resolved here, and the
+candidate must not be described as having a Codex pass until a later review
+disposition is explicitly established. The local H27 draft fixes remain
+outside the candidate and are preserved separately for recovery.
+
+## Known-by-design ledger additions
+
+- **Taken up in H19.** `query_endpoint` sets `stderr(Stdio::null())` and the
+ shell keeps no log file, so an endpoint that fails on a user machine yields
+ zero diagnostics — the reason H17 had to be reproduced offline before it could
+ be explained. The bootstrap log now records the endpoint's stderr tail and
+ whether each launch reused or extracted its Runtime.
+- **Deferred.** `vibe start` logged *"Started UI pid=6116 but required health
+ checks did not pass"* during the rc10 run at 05:51:35, yet the packaging
+ probe's own readiness poll passed moments later and the start receipt reported
+ `outcome=started`. The UI health wait is tighter than a cold Windows runner's
+ real startup, so the warning is noise on a start that in fact succeeded.
+ Recorded, not chased: widening that wait is a separate change with its own
+ evidence to gather.
+- **Deferred.** `clamp_window_frame` picks the single largest-overlap monitor and
+ clamps unconditionally, so a saved frame that legitimately spans two adjacent
+ displays is moved on restore. Window geometry only, off the packaging path, and
+ recoverable by moving the window. Tracked in issue 2139.
+- **Deferred.** `BackendLifecycleChip` returns the desktop-managed hint before it
+ reaches the error branch, so a failing desktop-managed backend reads as
+ healthy in the popover text. The error badge and Reinstall action still render,
+ so the failure stays visible while the wording is wrong. Tracked in issue 2140.
+- **Deferred.** Private backend releases are never reclaimed. Every successful
+ install or reinstall publishes under a fresh `releases/<uuid>` and moves
+ `current.json` to it. No path removes the release it replaced. So repeated
+ Reinstall or backend upgrades each keep a complete npm package tree in the
+ app-private data directory. The directory grows only on those installs. No
+ reclamation is safe within this PR: an old release may still be in use by a
+ running process, and deciding that needs the cross-language in-use contract
+ the uninstall fence also needs. Tracked in issue 2131.
+- **Fixed here.** This PR gave `runtime.start_ui` a `None` return for a stale UI
+ it could not stop, and left `cmd_start` unaware of it: the command ran on to a
+ receipt `validate_start_receipt` rejects, so the service it had just started
+ stayed alive with no receipt ever printed, and an unreceipted service is
+ adopted as `reused` on the next attempt. `cmd_start` now rolls back the
+ service *it* started and fails there. Consequence class is #2135's, but the
+ `None` return is ours, so the one caller this PR broke is fixed here and
+ nothing in receipt or adoption semantics is touched. A start that fails this
+ way still leaves the status file reading `starting`, exactly as the adjacent
+ `start_service` failure path already does; correcting that is a separate,
+ pre-existing concern and was deliberately left out rather than half-fixed.
+- **Known flake, not chased.** `test_lifecycle_status_report_does_not_block_stop`
+ asserts a `< 0.5s` wall-clock bound and failed once under a loaded local run,
+ then passed alone 5/5 and on the full re-run. This PR does not touch it.
+- **Known flake, not chased.** CI run 35844911380 at `bb0c8de75` failed only
+ `tests/test_reply_enhancer_platform.py::test_file_link_parser_handles_many_openers_in_bounded_time`:
+ 12.84s against its 10.0s wall-clock bound. This PR does not touch
+ `core/reply_enhancer.py` or that test, and it passes locally at about 4.6s.
+ Classified by the orchestrator as runner timing, not a finding.
diff --git a/docs/plans/desktop-tray-lifecycle.md b/docs/plans/desktop-tray-lifecycle.md
new file mode 100644
index 000000000..85c8b9beb
--- /dev/null
+++ b/docs/plans/desktop-tray-lifecycle.md
@@ -0,0 +1,144 @@
+# Desktop tray lifecycle and login item
+
+## Contract
+
+The native shell remains available after its main window closes. Its tray and
+first application menu expose the same Runtime status and explicit lifecycle
+actions. Closing a window hides it; it neither exits nor stops a Runtime.
+Status is derived from the existing bootstrap state and `/ready` monitor, not
+another endpoint or Webview-provided signal. Serving includes the proved
+listener; transient probe failures show unreachable while the existing
+three-failure recovery threshold remains unchanged.
+
+Stop is offered only for a shell-started Runtime. Confirmation stops it without
+exiting the shell. The bootstrap then shows a localized stopped notice and an
+explicit Retry action; automatic recovery must not undo a user's Stop.
+Quit with launch ownership offers stop-and-quit, keep-running-and-quit, or
+cancel. Quit without ownership leaves the adopted Runtime alone. Startup and
+uninstall serialize against lifecycle actions; no stop may race a launch.
+
+Start at Login is a native checkable menu item backed by
+`tauri-plugin-autostart`. Registration is opt-in, never enabled during setup.
+The OS registration is authoritative and is read back after every toggle.
+There are no new webview commands or permissions. Workbench and Show Pages
+remain unprivileged.
+
+## Frozen stop semantics
+
+- `avibe-runtime-host` owns the Tauri-free operation.
+- A retained launch attempt only deduplicates starts; it is never stop authority.
+ Only a successful launcher exit plus a valid schema-v1 `started` receipt grants
+ authority. `reused`, absent/malformed/duplicate receipts, failed helpers, and
+ helpers still running grant none. Readiness alone never grants authority.
+- The producer contract is `docs/plans/desktop-start-receipt.md` in the separate
+ `feat/desktop-start-receipt` lane. Its receipt is sourced from the service
+ startup function's actual spawn/reuse branch, never before/after snapshots.
+ UI reuse does not change the service's provenance outcome.
+- Startup stdout is drained without forwarding it to a webview. At most 64 KiB
+ is retained; oversized output is drained and discards authority. Exactly one
+ line beginning `@avibe-start-receipt:` is accepted. Schema, positive PIDs, and
+ finite positive creation timestamps are validated, including fractional ms.
+- Missing proven ownership is an error, never a best-effort stop.
+- The host retains the exact resolved launcher/interpreter that launched the
+ Runtime. Stopping does not resolve an executable, search PATH, or invoke a
+ shell interpreter.
+- The Runtime's own `stop --receipt <JSON>` command owns shutdown. The helper
+ uses the same process isolation as startup and null standard streams. This
+ path never falls back to an unscoped stop or re-resolves an executable.
+- Python validates the current service PID and creation time (2 ms tolerance)
+ at its service-owner gate. Exit 3, including invalid receipt, replaced PID,
+ unavailable identity, and changed creation time, revokes authority and returns
+ a localized `runtime_ownership_lost` bootstrap screen with explicit Retry.
+ Retry uses the existing endpoint discovery and `/ready` state machine; no
+ second status channel or automatic stop/restart is introduced.
+- Successful stop releases ownership. Other stop failures preserve it for an
+ explicit retry. Confirmed Runtime loss releases ownership as before.
+- Tests prove adopted refusal, launch/stop executable identity, argument shape,
+ failure retention, and stop/monitor/bootstrap exclusion.
+
+## Scope and dependencies
+
+Based on `origin/desktop` at `b2ed55f11`. The authoritative gap document is
+the orchestrator's desktop worktree copy, not a file copied into this branch.
+The orchestrator approved generated `desktop/Cargo.lock` changes, new
+`desktopBootstrap` locale keys in the central English/Chinese catalogs, and
+the ownership-gated runtime-host stop API. Tauri core gains the `tray-icon`
+feature; the only new plugin is `tauri-plugin-autostart = "2"`, matching the
+existing plugin version style. Signing/packaging files are untouched.
+The additive stopped and ownership-lost notices also update the desktop i18n
+verifier's frozen notice list, with the orchestrator's explicit approval.
+This consumer requires #1977 merged first (the startup-receipt producer);
+it does not copy or stack on that lane's Python implementation.
+
+## Verification
+
+- Hermetic Rust unit and source-boundary tests; no local Runtime or OS login
+ registration is changed by tests.
+- Bootstrap i18n parity and frontend build before Cargo compilation.
+- `cargo fmt --all -- --check`, workspace/all-feature Clippy with warnings
+ denied, and workspace/all-feature tests.
+- CI exercises macOS and Windows. Manual integration must verify tray rendering,
+ close/reopen, all quit choices, stop confirmation/cancellation, status recovery,
+ and opt-in login registration across a real OS login on both platforms.
+
+## Known by design
+
+- Workbench Settings integration is deferred; the native toggle is the only
+ login-item control in this slice.
+- A Runtime deliberately kept running is adopted on the next shell launch and
+ cannot then be stopped via this session's tray ownership path.
+- Receipt v1 is a service-owner gate, not a per-process capability: a matching
+ service identity invokes today's full graceful stop, including UI, service
+ sweep, OpenCode, and tunnel. UI reuse does not prevent this full stop. The
+ gate does not prevent replacement after validation or independently authorize
+ each auxiliary process. The orchestrator explicitly accepted these v1 limits
+ on 2026-09-10; no per-process guarantee is claimed.
+- Older Runtime packages without receipt support can still serve/adopt, but
+ cannot gain tray stop authority. A ready Runtime whose helper has not finished
+ is also treated conservatively until a successful receipt becomes available.
+- Runtime version reporting is not added to `/ready`; the tray shows the
+ already-proved listener and current readiness without creating a status API.
+- Native GUI/login testing remains an integration acceptance step, not a claim
+ made from a source-boundary test or a successful compile.
+- While bootstrap, uninstall, or stop owns the lifecycle activity, a competing
+ Stop or Quit reports busy instead of interrupting a launch/removal command.
+ The user retries when that bounded startup or explicit operation finishes.
+
+## Pre-review local evidence (2026-09-10, macOS, head 8856b1648)
+
+- Bootstrap dependency install, i18n parity, and production frontend build pass.
+- Central Workbench build passes with existing third-party annotation/chunk-size
+ warnings; no unrelated dependency or bundle changes were made.
+- Rust format check and all-target/all-feature Clippy pass with warnings denied.
+- Workspace all-feature tests pass: 15 shell unit, 20 shell boundary, 69 host
+ unit, 21 bootstrap integration, and one host documentation test.
+- Default-feature workspace tests also pass, exercising the installed-Runtime
+ build alongside the private-Runtime feature build.
+- All stop tests use fakes or test-owned executables; no running local service,
+ login item, real user home, or private Runtime install was modified.
+
+## P1 review correction
+
+Review comment 3975484212 identified invocation-based ownership as invalid:
+an initial readiness miss can lead an idempotent start helper to reuse an
+external service. That review concerns head 8856b1648; this is the first
+findings-bearing head and the root-cause class is launch provenance.
+The consuming correction separates launch deduplication from receipt-proven
+stop authority and passes the exact receipt to Python's service-owner gate.
+Corrected local validation passes after integrating baseline #1972 with a
+history-preserving merge: bootstrap `npm ci`, i18n parity and build; Cargo format
+check; workspace/all-target/all-feature Clippy with warnings denied; all-feature
+tests (15 shell + 21 boundary + 78 host + 21 bootstrap = 135, plus one doctest);
+default-feature tests (132 plus one doctest); central UI `npm ci` and build.
+One initial full run hit two existing health fixture read timeouts; all eight
+health tests passed the focused rerun and the unchanged full suites then passed.
+No health fixture or unrelated code was modified. Existing npm audit/build
+warnings and a non-fatal Cargo global-cache cleanup permission warning remain
+outside this lane; no user cache or dependency repair was attempted.
+
+## Progress
+
+- [x] Inspect ownership, bootstrap, monitoring, localization, and capability gates.
+- [x] Implement native lifecycle and opt-in login control.
+- [x] Verify the frozen contract with hermetic tests and builds.
+- [ ] Deliver a desktop-base PR with exact-head review and passing CI.
diff --git a/docs/plans/desktop-window-state.md b/docs/plans/desktop-window-state.md
new file mode 100644
index 000000000..c88f73c40
--- /dev/null
+++ b/docs/plans/desktop-window-state.md
@@ -0,0 +1,111 @@
+# Desktop window state persistence
+
+## Status
+
+Frozen implementation contract for gap G6. Companion to
+`desktop-product-gaps.md` (G6) and `tauri-desktop-vertical-slice.md`.
+
+Owner: Avibe core
+Date: 2026-09-10
+Baseline: `desktop` branch after #1975. The main window is still a
+single Tauri window labeled `main` (`tauri.conf.json`: 1200×800,
+min 880×600, centered).
+
+## Product outcome
+
+The Avibe window reopens at the size and position the user last left
+it, including after a Runtime adopt/start cycle. Maximized is
+restored as maximized. Full-screen / Spaces assignment is **not**
+restored (macOS Spaces restore is a common way to lose the window).
+
+If the saved frame would land off the current display configuration
+(external display unplugged), the window is clamped onto a visible
+display and kept at or above `minWidth` × `minHeight`. A missing or
+corrupt save falls back to the current 1200×800 centered default.
+
+## Frozen mechanism
+
+`tauri-plugin-window-state` (Tauri v2), keyed by window label.
+
+What is persisted, per label:
+
+- `x`, `y`, `width`, `height`
+- `maximized` (bool)
+
+What is not persisted:
+
+- full-screen / simple-fullscreen;
+- workspace / Spaces / virtual-desktop membership;
+- monitor identity (clamp-to-visible is the recovery, not a saved
+ display id);
+- Workbench scroll / SPA route (that is product UI state, not the
+ shell frame).
+
+The plugin hooks the **native window frame**, not the WebView
+document. Bootstrap content swapping and the later navigation to the
+Runtime origin do not reset the frame. Order of operations at
+launch, frozen:
+
+1. Create the `main` window (hidden or shown — plugin-dependent,
+ but the restored frame is applied **before** the user sees it).
+2. Existing bootstrap state machine runs (content changes; frame
+ does not).
+3. On successful `/ready`, navigate the WebView to the Runtime
+ origin (content changes; frame does not).
+4. User moves/resizes: the shell debounces calls to the plugin's
+ existing `save_window_state` (the plugin writes on demand / on
+ close, it does not debounce to disk by itself). Do not introduce a
+ second store. Debounce is a shell-side timer around that API.
+
+Closing to tray and re-showing ("Open Avibe") must restore the
+**last shown frame**, not re-center. Quit and relaunch reads the
+same store.
+
+## Multi-window (G8) without a contract change
+
+The plugin already namespaces by label. G8 adding `settings` or
+`show-<id>` windows gets a frame per label for free, provided each
+new window has a stable label. This contract does not require G8;
+G8 must not invent a second persistence path.
+
+v1 of this contract only guarantees the `main` label. Additional
+labels become guaranteed when those windows exist.
+
+## Tests (invariants)
+
+- Saved frame round-trip: a `main` window at a non-default size and
+ position is restored on the next launch of the same app data
+ directory.
+- Off-screen clamp: a saved origin that lies entirely outside the
+ current display bounds is moved so at least the title bar is
+ visible; size stays ≥ minWidth × minHeight.
+- Corrupt / missing store → 1200×800 centered, no panic, no
+ bootstrap failure.
+- Bootstrap then navigate does not overwrite a restored frame with
+ the config.json defaults.
+- `shell_boundaries.rs` still forbids remote capabilities; the
+ plugin is not WebView-callable as a command the Workbench can
+ invoke to move the window (if the plugin exposes commands, they
+ stay off the Workbench capability).
+
+Prefer a focused integration test over mocking the plugin: launch
+the shell against a fake Runtime in a throwaway config dir, set
+frame, quit, relaunch, assert. If that is too heavy for CI, a unit
+test of the clamp function plus a source assertion that
+`tauri-plugin-window-state` is registered for `main` is the
+minimum; the clamp tests must not enumerate display sizes — they
+state the "title bar visible, size ≥ min" property.
+
+## Explicit non-goals (v1)
+
+- Remembering the Workbench route or scroll.
+- Remembering full-screen.
+- Per-display docking layouts.
+- Syncing frame state across machines.
+
+## Sequencing
+
+No dependency on G1, G4, G5, or G8. Cheapest desktop-feel win;
+safe to ship before deep links. If G8 is scheduled, doing G6 first
+means the new windows inherit persistence instead of growing a
+second store.
diff --git a/docs/plans/tauri-desktop-vertical-slice.md b/docs/plans/tauri-desktop-vertical-slice.md
new file mode 100644
index 000000000..e4b64f57e
--- /dev/null
+++ b/docs/plans/tauri-desktop-vertical-slice.md
@@ -0,0 +1,689 @@
+# Tauri Desktop Vertical Slice
+
+## Status
+
+- Owner: Avibe core
+- Target platforms: macOS and native Windows
+- Mobile: deferred until the desktop shell and shared WebView constraints are proven
+- Delivery strategy: a retained product scaffold, not a disposable prototype
+- Integration branch: every desktop PR targets `desktop`; only an
+ owner-authorized final integration PR may target `master`
+
+The first credible native Windows closure is intentionally narrow:
+
+> Windows x64 + uv-managed system Python + Tauri WebView2 + Codex only + a
+> native `C:\...` workspace + authenticated loopback Controller IPC + Windows
+> ProcessHost + pywinpty/ConPTY.
+
+Vault, Show Runtime, askill, OpenCode, Claude, ARM64, private Python, NSIS, and
+signing remain product requirements, but none blocks the first D07/D12 proof.
+
+## Background
+
+Avibe already has the right high-level split for a desktop application:
+
+- the React Workbench is the primary user interface;
+- the Python service owns agents, sessions, local state, Show Pages, Vault
+ orchestration, terminal transport, and IM integrations;
+- the browser talks to the service over loopback HTTP, SSE, and WebSocket.
+
+The first desktop release should preserve this split. Tauri should own native
+application lifecycle and distribution, while the existing Avibe service
+remains the single business-logic and data authority.
+
+Windows is a first-class native target. WSL remains a compatibility option, not
+the architecture or the default path.
+
+## Goals
+
+1. Prove that the complete Workbench runs reliably inside Tauri on macOS
+ WKWebView and Windows WebView2.
+2. Start or adopt one local Avibe Runtime without creating duplicate daemons.
+3. Keep long-running Avibe work independent from the desktop window lifecycle.
+4. Make native Windows capable of running a real agent session without
+ invoking WSL.
+5. Preserve Show Pages, Vault, Monaco, xterm, files, clipboard, drag and drop,
+ HTTP streaming, and WebSocket behavior.
+6. Keep the shell replaceable: if Tauri fails the gate, Electron can replace
+ the native shell without rewriting Workbench or Runtime.
+
+## Non-Goals
+
+- Rewriting Workbench in Rust, Swift, Kotlin, or native widgets.
+- Moving business logic or persistent data into Tauri commands.
+- Bundling a private Python Runtime in the first host-capability milestone.
+- Implementing auto-update before startup, lifecycle, and packaging are stable.
+- Removing or weakening Show Pages to reduce WebView surface area.
+- Delivering mobile applications in this milestone.
+- Reproducing every tmux persistence feature on Windows before ConPTY is proven.
+- Making Vault, Show Runtime, askill, OpenCode, Claude, ARM64, private Python,
+ NSIS, or signing prerequisites for the first native Windows Agent/terminal
+ closure.
+
+## Architecture
+
+```text
+┌─────────────────────────────────────────────────────────────┐
+│ Tauri Desktop Shell │
+│ │
+│ bootstrap/error UI window/tray single instance │
+│ Runtime discovery process start native integration │
+└──────────────────────────────┬──────────────────────────────┘
+ │ loopback URL
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ Existing React Workbench │
+│ │
+│ Chat Sessions Show Pages Vault Monaco xterm Settings │
+└──────────────────────────────┬──────────────────────────────┘
+ │ HTTP + SSE + WebSocket
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ Avibe Python Runtime │
+│ │
+│ Agents Harness state files terminal IM Show Runtime │
+└─────────────────────────────────────────────────────────────┘
+```
+
+### Ownership Rules
+
+| Concern | Owner | Contract |
+| --- | --- | --- |
+| Native window, tray, single instance | Tauri shell | No business state |
+| Runtime endpoint discovery | Python Runtime | Versioned descriptor derived from effective UI binding |
+| Runtime launch | Tauri shell | Resolve installed CLI, probe first, start second, adopt after readiness |
+| Workbench UI and navigation | React Workbench | Browser-compatible HTTP origin |
+| Sessions, agents, tasks, watches | Python Runtime | Existing APIs and durable state |
+| Show Pages | Python and Show Runtime | Full capability preserved |
+| Terminal bytes and resize events | Runtime platform adapter | Existing WebSocket protocol |
+| Credentials and custody | Vault / platform adapter | Tauri never receives secret values |
+| Long-running background work | Python Runtime / Harness | Survives window close and shell crash |
+
+### Security Boundary
+
+The Workbench loads from a dedicated loopback Avibe origin. Tauri commands
+are available only to the bootstrap shell code that needs native lifecycle
+operations. Normal Workbench routes and Show Page content must not inherit
+filesystem, shell, process, or unrestricted Tauri capabilities.
+
+This boundary preserves Show Pages as a core feature without turning page
+content into native application code.
+
+M1 uses one WebView in two phases:
+
+1. the bundled Tauri-origin bootstrap page may call only the fixed,
+ argument-free Runtime bootstrap and installation-help commands;
+2. after readiness, Rust navigates that WebView to the loopback Workbench.
+
+The loopback origin is never listed in a Tauri capability `remote.urls` rule.
+Every application command also verifies that its caller is still on the bundled
+bootstrap origin. Single-instance, focus, window, and process lifecycle remain
+Rust-owned after navigation; Workbench does not need Tauri IPC.
+
+M1 has no privileged `postMessage` bridge. If the Workbench later needs a
+native operation, it must not be enabled by adding the loopback origin to
+`remote.urls`. That change requires a separate architecture contract: a
+Tauri-origin privileged surface, a narrow schema-validated message protocol,
+and exact checks of message source and origin before any native command runs.
+Agent-authored content is never an allowed bridge caller.
+
+The Python server's existing Host-header validation is a frozen security
+invariant, but it must preserve Avibe's authenticated remote-access product:
+
+- the desktop loopback listener grants local trust only when the request has
+ both a loopback peer and a syntactic loopback Host (`localhost` or an address
+ parsed by `ipaddress` as loopback);
+- an untrusted forwarded header must prevent local classification;
+- a non-loopback Host must enter the configured remote-auth path or fail closed;
+ it must never inherit local trust merely because its peer is loopback.
+
+The existing configured setup-host trust and trusted public-origin exceptions
+remain valid for their matching LAN, Tailscale, and Avibe Cloud request paths.
+The desktop contract adds a stricter loopback path; it does not redefine every
+server request as loopback-only.
+
+The named contract
+`test_desktop_runtime_host_header_contract_rejects_non_loopback_local_trust`
+must cover the loopback-peer/arbitrary-Host, remote-peer/loopback-Host, malformed
+`127.*` hostname, and untrusted-forwarding cases. The desktop shell is stricter:
+it navigates only to the exact literal IP whose readiness probe succeeded
+(`127.0.0.1` or `[::1]`), never the hostname `localhost`.
+
+Show Pages keep their existing product capability. D04 must include a negative
+assertion that Show Page JavaScript cannot invoke a Tauri command. Existing
+same-origin Show Page access remains a browser/server risk, but it cannot cross
+the native boundary because neither the Workbench nor Show Page origin has
+Tauri capabilities.
+
+Two pre-existing server hardening items remain explicit:
+
+- `/api/events` currently has no explicit Origin gate. Browser same-origin/CORS
+ enforcement prevents a cross-origin page from reading the stream in the
+ current deployment, so this is not equivalent to granting native capability
+ or demonstrated data exfiltration. Before desktop security sign-off, add
+ exact-Origin validation or a short-lived connection token issued through an
+ authenticated same-origin mutation, and test the chosen contract.
+- `/p/{share_id}/__vite_hmr` must validate the WebSocket Origin against the
+ public page's effective origin. Public visibility is not authorization to
+ accept a cross-site WebSocket. This hardening must retain public Show Page HMR.
+
+Neither item is solved by disabling or reducing Show Pages, and neither is
+allowed to support a claim that the desktop release adds no attack surface
+until its focused server PR has landed.
+
+### Runtime Discovery
+
+M1 assumes an installed `vibe` executable and resolves it in this order:
+
+1. the explicit development/test `AVIBE_DESKTOP_VIBE_PATH` override;
+2. the inherited process `PATH`;
+3. `UV_TOOL_BIN_DIR` when configured;
+4. uv's default `$HOME/.local/bin` or `%USERPROFILE%\.local\bin`;
+5. platform fallbacks: `$HOME/bin`, `$HOME/.cargo/bin`, `/opt/homebrew/bin`,
+ and `/usr/local/bin` on macOS/POSIX, and `%APPDATA%\Python\Scripts` on
+ Windows;
+6. the app-private Runtime path only after M3 introduces one.
+
+Candidates resolve directly to `vibe` on macOS and `vibe.exe` on Windows.
+Failure produces a retryable bootstrap error with an install-docs action; it
+never falls back to a shell command or exposes candidate paths to the WebView.
+A macOS application bundle cannot assume the interactive shell's rc files were
+loaded.
+
+`vibe start --no-open-browser` is a short-lived launcher that starts or adopts
+the background service and UI processes, then exits. Tauri does not retain or
+kill that launcher or the daemons it creates.
+
+## Frozen Desktop Bootstrap Contract
+
+Python, not Rust, owns the effective UI binding and desktop endpoint:
+
+1. `vibe desktop endpoint --json` loads the same V2 config as `vibe start` and
+ emits exactly one JSON object on stdout:
+
+ ```json
+ {
+ "schema_version": 1,
+ "origin": "http://127.0.0.1:5123"
+ }
+ ```
+
+2. `origin` is produced from `effective_ui_bind_host()` and `ui.setup_port`.
+ It contains a literal `127.0.0.1` or bracketed `::1` address, never
+ `localhost`, a configured LAN/Tailscale address, a wildcard, or a public URL.
+3. The UI process always serves that origin. When the existing primary listener
+ is bound to a specific non-loopback address, the same UI process and ASGI app
+ add a same-port loopback listener of the matching address family. Wildcard
+ and loopback bindings already cover loopback and do not add another socket.
+ A second UI process or a local reverse proxy is forbidden.
+4. The primary listener and remote-access authentication remain unchanged.
+ Requests to the additional listener receive local trust only when both the
+ peer and Host are syntactic loopback values.
+5. Rust treats the descriptor as untrusted process output: stdout has a small
+ size bound, stderr is never exposed to the WebView, the schema version must
+ be exactly `1`, there must be no unknown fields, and `origin` must pass the
+ existing literal-loopback validator.
+
+`GET /ready` is the one desktop readiness contract:
+
+```text
+UI route reachable
+AND resolve_service_owner_pid(include_starting=False) is present
+AND await internal_client.health_identity() returns the Controller identity
+AND the same service owner still holds the lock after that health check
+```
+
+It returns
+`200 {"schema_version": 1, "product": "avibe", "ready": true}` only when all
+conditions hold. A desktop-managed Runtime adds its full archive SHA-256 as
+`desktop_runtime_id`; an external installed Runtime omits that field. The
+Controller process owns this identity in `/internal/health`; the UI only
+forwards the validated Controller value after the same service owner survives
+the probe. It never derives the identity from the UI process environment. The
+exact product marker prevents accidental adoption of an unrelated service that
+happens to occupy the configured loopback port. It returns
+`503 {"schema_version": 1, "product": "avibe", "ready": false, "code": ...}`
+with one of `service_starting`, `service_unavailable`,
+`controller_unavailable`, `ownership_lost`, or `owner_probe_failed` otherwise.
+IM login, Agent credentials, terminal capability, Vault, and Show Runtime are
+feature states, not shell readiness gates. `/health` proves only the UI HTTP
+process; `/status` cannot prove that Controller initialization and control IPC
+completed. Neither is sufficient for adoption or navigation.
+
+The first implementation uses a small state machine:
+
+```text
+probing -> ready
+ -> starting -> ready
+ -> failed
+probing -> failed
+```
+
+The shell produces these states:
+
+| Field | Producer | Consumer | Meaning |
+| --- | --- | --- | --- |
+| `phase` | Rust Runtime host | Bootstrap UI | `probing`, `starting`, `ready`, or `failed` |
+| `origin` | Python descriptor, validated by Rust | WebView navigation | Validated loopback HTTP origin |
+| `attempt` | Rust Runtime host | Bootstrap UI | Current readiness probe attempt |
+| `notice` | Rust Runtime host | Bootstrap UI | Typed code plus bounded typed arguments; never display prose |
+| `retryable` | Rust Runtime host | Bootstrap UI | Whether the user may retry safely |
+
+Behavior:
+
+1. Resolve one installed `vibe` executable.
+2. Unless the explicit development/test origin override is set, execute
+ `vibe desktop endpoint --json` directly and validate its descriptor.
+3. Accept only literal `http://127.0.0.1` or `http://[::1]` loopback origins.
+4. Probe `GET /ready`.
+5. If ready, adopt the existing Runtime and navigate to Workbench.
+6. If absent, launch the same executable with
+ `vibe start --no-open-browser`, without a shell.
+7. Poll `/ready` with a bounded timeout.
+8. Navigate only after a successful combined readiness response.
+9. After navigation, Rust probes `/ready` every two seconds. A single transient
+ failure does nothing. After three consecutive failures, Rust returns the same
+ WebView to the bundled bootstrap origin, releases only its stale
+ launch-attempt guard, and runs the normal probe/adopt/launch state machine.
+ It never stops the Runtime.
+10. Never kill an adopted Runtime when a window closes or the shell exits.
+11. Never expose command strings, environment variables, or secret-bearing
+ process output to the WebView.
+
+The initial shell assumes `vibe` is installed. Private Runtime bundling belongs
+to the distribution milestone.
+
+Bootstrap copy is represented by stable message codes and localized in bundled
+offline English and Chinese catalogs selected from the WebView locale. Rust
+does not emit user-facing prose, and the bootstrap does not depend on the
+loopback Workbench being reachable to load translations.
+
+The exact notice shape is
+`{"code": "<enum>", "seconds": <optional positive integer>}`. M1 freezes the
+codes `probing`, `adopted`, `starting`, `ready`, `invalid_origin`,
+`runtime_not_found`, `runtime_discovery_failed`, `runtime_spawn_failed`,
+`launcher_exited`, and `ready_timeout`. The UI must exhaustively map them to
+`ui/src/i18n/en.json` and `ui/src/i18n/zh.json`; an unknown value maps to a
+localized generic failure and is never rendered as raw text. The desktop Vite
+build extracts only the `desktopBootstrap` subtree into the offline bundle.
+Locale selection uses `navigator.languages` (`zh-*` selects Chinese, all other
+values fall back to English) and updates the document `lang`.
+
+## Native Windows Runtime Contract
+
+Windows support must be expressed behind platform interfaces rather than
+scattered `os.name` branches. `core/platforms/__init__.py` selects an
+implementation once; callers depend only on the narrow protocols:
+
+```text
+ControlIpcHost
+├── PosixUnixSocketHost
+└── WindowsLoopbackHost
+
+ProcessHost
+├── PosixProcessHost
+└── WindowsProcessHost
+
+TerminalHost
+├── PosixPtyTmuxHost
+└── WindowsConPtyHost
+
+CredentialIpcHost
+├── PosixSocketHost
+└── WindowsNamedPipeHost
+
+DependencyHost
+├── PosixDependencyHost
+└── WindowsDependencyHost
+```
+
+The interfaces preserve current product behavior while allowing different
+platform mechanisms:
+
+- Controller IPC keeps its current HTTP/SSE behavior. POSIX retains the Unix
+ domain socket; Windows uses an ephemeral loopback listener with an atomically
+ written endpoint descriptor, instance nonce, and bearer credential. It does
+ not invent a custom named-pipe HTTP stack. The descriptor must have a
+ user-and-SYSTEM-only DACL even when `AVIBE_HOME` is inherited from a permissive
+ directory; readers validate the file owner and ACL before accepting it.
+ Startup rotates the nonce and bearer, and graceful or forced shutdown removes
+ the descriptor.
+- `ProcessHost` models three explicit ownership classes:
+ `DAEMON`, `OWNED_TREE`, and `ADOPTABLE_DAEMON`. The Runtime service is
+ independent from Tauri; service-owned workers enter a Windows Job Object only
+ after the service owns their lifecycle. Graceful control shutdown precedes
+ forced whole-tree termination.
+- daemon launch never passes POSIX-only `start_new_session` semantics on
+ Windows; Controller internal-server startup failure must make the service
+ unhealthy, and UI restart treats `WSAEADDRINUSE` (`10048`) as the Windows
+ equivalent of the existing POSIX address-in-use errors.
+- Windows terminal sessions use ConPTY through a maintained binding and retain
+ the existing xterm WebSocket protocol. `TerminalService` continues to own
+ session state; the host owns only `open`, `read`, `write`, `resize`, `wait`,
+ and `close`.
+- Process stop/restart uses native process-tree semantics and never calls
+ `wsl.exe`.
+- Vault credential IPC uses a Windows named-pipe byte stream only after the
+ matching avault CLI transport contract exists. Avibe must not invent one
+ unilaterally.
+- dependency installation resolves native PowerShell and Windows assets;
+ POSIX-only dependencies such as tmux return `not_applicable` on Windows
+ rather than failing startup.
+- paths are native Windows paths end to end; `/mnt/c` translation is forbidden.
+
+## Milestones
+
+### M1: Tauri Host Capability
+
+Deliver a buildable Tauri v2 shell that:
+
+- probes and adopts an existing Runtime;
+- launches an installed Runtime when absent;
+- shows a compact startup/error state with retry;
+- navigates the main WebView to Workbench after readiness;
+- monitors combined Runtime readiness after navigation and returns to bootstrap
+ after confirmed loss;
+- prevents duplicate shell instances;
+- keeps Runtime lifecycle independent from window lifecycle;
+- includes unit tests for origin validation and state transitions;
+- builds on macOS and Windows CI.
+
+No updater or bundled Python is required.
+
+### M2: Native Windows Runtime Slice
+
+The first native target is Windows x64 with a uv-managed system Python and the
+Codex backend. ARM64, bundled Python, Vault, Show Runtime, askill, OpenCode, and
+Claude do not block the first D07/D12 proof. They remain required product
+follow-ups; they are not removed or weakened.
+
+Deliver the slice through six ordered contracts. A PR must not combine adjacent
+contracts merely because they share the Windows target:
+
+1. replace the Controller's fixed Unix-socket assumption with `ControlIpcHost`
+ while preserving the existing HTTP routes, SSE ordering, and authentication;
+2. add Windows process ownership, graceful stop, and whole-tree cleanup without
+ making Tauri the owner of the Runtime process tree. Before this contract may
+ claim M2 lifecycle support, `_spawn_runtime_log_sink`, `spawn_background`,
+ and `spawn_service_background_process` in `vibe/runtime.py`, plus the
+ long-lived supervisor spawn in `vibe/restart_supervisor.py`, must use
+ `isolated_subprocess_kwargs()` or the selected `ProcessHost`, never raw
+ `start_new_session=True`; Windows CI must execute the shared spawn
+ abstraction tests;
+3. complete one real Codex session in a native `C:\...` workspace, including
+ `.cmd`/`.exe` argument fidelity, streamed output, a file modification, and
+ no `wsl.exe` or `/mnt/` path in the process lineage;
+4. extract a `TerminalHost` conformance seam around the existing POSIX PTY/tmux
+ behavior without changing the WebSocket or `TerminalView` contract;
+5. implement the same contract on Windows with
+ `pywinpty>=3.0.5,<4; sys_platform == "win32"` and pin the wheel in
+ `uv.lock`;
+6. follow with Vault named-pipe work across Avibe/avault, Show Runtime and
+ dependency proofs, then private Runtime packaging, installers, signing, and
+ ARM64.
+
+The resulting product workflow is:
+
+1. install Avibe in Windows without WSL;
+2. start the service from PowerShell;
+3. open the Tauri Workbench;
+4. start one real agent backend;
+5. stream its output;
+6. read and modify a file in a `C:\...` working directory;
+7. open a ConPTY terminal, send Unicode input, resize, and interrupt;
+8. stop and restart cleanly without orphaning the process tree.
+
+The first slice may omit detached terminal persistence across a full machine
+reboot. That behavior must be designed after ConPTY lifecycle evidence exists.
+
+The Windows terminal implementation uses dedicated reader and writer workers,
+not the shared asyncio executor. Its close path must drain or close the output
+pipe before `ClosePseudoConsole`, which can otherwise block on older Windows
+releases. The supported floor is Windows 10 version 1809; release CI installs
+pywinpty wheel-only.
+
+Vault and Show Pages remain in the desktop acceptance catalog. Their native
+Windows proof follows the first Agent/terminal slice because Vault requires a
+matching avault transport contract and Show Runtime already has Windows bundle
+assets but lacks a native lifecycle CI proof.
+
+### M3: Product Distribution
+
+- macOS signed and notarized DMG;
+- Windows NSIS x64 installer first, ARM64 after the x64 gate;
+- app-private CPython, Avibe wheel, Node, and npm; `uv` is build-time only and
+ is not shipped or required on the user's machine;
+- Agent backends are detected externally first and otherwise installed lazily
+ into app-private storage;
+- versioned Runtime directories with rollback;
+- uninstall preserves user data under the Avibe home;
+- updater only after cold start, upgrade, rollback, and process lifecycle pass.
+
+#### Self-contained Runtime contract
+
+A Desktop product package is not allowed to resolve its primary Runtime from
+the system `PATH`. Each architecture-specific installer embeds one immutable
+`runtime.zip` and one `runtime-manifest.json` as Tauri resources. The manifest
+pins and records:
+
+- the target OS and architecture;
+- the CPython and Node source URLs plus SHA-256 digests;
+- the exact Avibe wheel name and SHA-256 digest;
+- the archive's compressed and uncompressed sizes, entry count, SHA-256 digest,
+ extracted-tree SHA-256 digest, and the relative Python, Node, and npm
+ entrypoints.
+
+Release CI builds the wheel from the same checkout and installs its
+hash-locked dependencies into the pinned standalone CPython distribution.
+Binary wheels are mandatory except for the explicit audited sdist allowlist in
+`desktop/runtime-sources.json`. `http-ece` does not publish wheels;
+`claude-agent-sdk` is intentionally built from its pure-Python sdist because its
+platform wheels embed a Claude Code executable, which belongs to the lazy
+backend lifecycle instead of the immutable Runtime. CI builds those dependencies
+on the target runner. The
+builder then copies native Node plus its complete npm package. The private
+launch environment exports the exact Node and npm CLI paths. A fully isolated
+`AVIBE_HOME` proves the real `start --no-open-browser -> /ready -> stop`
+lifecycle as well as Node-driven npm execution. Source downloads and the
+completed archive are both hash-verified. The package also contains the Python
+distribution inventory and third-party license material.
+
+On first launch the Rust host validates the bounded manifest and exact target,
+checks the archive length and SHA-256 digest, rejects path traversal, symlinks,
+oversized expansion, and entry-count mismatches, and extracts into a private
+staging directory. Only a complete install with the Python, Node, and npm
+entrypoints and a durable marker is atomically renamed to:
+
+```text
+<OS application data>/runtime/<avibe-version>/<archive-sha-prefix>/
+```
+
+Every later launch recomputes the extracted file-tree digest before executing
+the Runtime, rejects symlinks and extra/missing files, and may install one
+separate repair slot from the immutable archive when the primary slot is
+corrupt. If both slots fail validation, startup fails closed rather than
+executing user-writable modified code.
+
+The application bundle is read-only after installation. Content-addressed,
+versioned directories let an update install a successor while an older daemon
+is still using its files. The archive SHA-256 is passed into the private
+Runtime. Its Controller returns that identity through internal health and the
+UI forwards the Controller-owned value through `/ready`. A matching Runtime is
+adopted. Before `vibe start` reuses an existing service, a different
+desktop-managed Controller is stopped gracefully; the shell also performs this
+handover when a predecessor UI is still reachable. Superseded trees are pruned
+only after the successor Controller proves the expected identity. Reopening an
+older package reinstalls its own immutable archive, so rollback does not depend
+on retaining every historical extraction.
+
+The shell launches the private interpreter directly as `python -I -m vibe`; it
+supplies the exact Node and npm CLI paths plus a separate mutable backend root.
+It marks the process as desktop-managed: Python package checks and in-place
+`vibe upgrade` are disabled, while Codex, Claude Code, and OpenCode can be
+installed or updated independently through the Workbench. Backend installation
+invokes bundled npm through bundled Node without a shell or global prefix. The
+Runtime launch itself does not invoke a shell, system Python, `uv`, or an
+interactive shell startup file.
+
+Development builds retain the installed-`vibe` resolver. A distributable build
+must enable the Rust `bundled-runtime` feature; producing a consumer installer
+without it is a release failure. `desktop-self-contained-package` builds the
+artifacts and signs them credential-gated: with the Apple secrets configured it
+Developer ID signs and notarizes the macOS app (`SIGNATURE:
+app-identity-signed`); without them the macOS app copy receives only an ad-hoc
+structural signature and all artifacts remain unsigned acceptance builds. The
+manual workflow requires a SemVer input and stamps it into Tauri metadata and
+artifact names. Remaining signing layers are tracked release gates (see the
+distribution-signing-completion issue): sign executable code inside the
+private Runtime before archiving it, sign and notarize the outer DMG, and
+apply the corresponding Authenticode coverage on Windows. Signing,
+notarization, and publication are separate release gates.
+
+The D11 clean-install gate uses a fresh VM with Python, `uv`, Node, npm, and all
+Agent backends absent from `PATH`. It must prove:
+
+1. the installer completes without downloading prerequisites;
+2. first launch reaches Workbench and starts exactly one Runtime;
+3. the private Runtime answers `vibe desktop endpoint --json`;
+4. bundled Node and npm execute, Workbench loads without a backend, and one
+ selected backend can be installed lazily without system package managers;
+5. closing and reopening the shell adopts the same daemon;
+6. a second package version installs beside the first, cuts over only after
+ readiness, and can roll back without changing `~/.avibe`;
+7. uninstall removes application/runtime/private-backend files but preserves
+ `~/.avibe` and external backend installations.
+
+### M4: Mobile Reassessment
+
+Re-evaluate Tauri mobile using the proven Workbench compatibility results.
+Mobile work must have mobile-specific navigation, input, safe-area, keyboard,
+and gesture design; it is not a desktop viewport shrink.
+
+## Acceptance Scenarios
+
+| ID | Scenario | Required evidence |
+| --- | --- | --- |
+| D01 | Cold launch with no Runtime | one Runtime starts and Workbench loads |
+| D02 | Launch with existing Runtime | Runtime is adopted; no duplicate daemon |
+| D03 | Streaming chat | SSE streams and reconnects after transient loss |
+| D04 | Show Page | page renders, hot reloads, and remains interactive |
+| D05 | Files | upload, download, drag/drop, and clipboard work |
+| D06 | Vault | WebAuthn/PRF flow completes without secrets entering Tauri |
+| D07 | Terminal | PTY/tmux on macOS and ConPTY on Windows use the same UI protocol |
+| D08 | Sleep and wake | UI reconnects without duplicate Runtime |
+| D09 | Window lifecycle | close/reopen and single-instance behavior are deterministic |
+| D10 | Runtime crash | after consecutive `/ready` failures, shell returns to bootstrap and reconnects without duplicate launch |
+| D11 | Clean install | application starts without system Python |
+| D12 | Native Windows | real agent task completes with no WSL process or path |
+
+D03 also verifies that the loopback origin sets its CSRF cookie on first load
+and that subsequent mutations still succeed in both WKWebView and WebView2
+after an ordinary reload, WebView/window recreation, sleep/wake recovery, and a
+history back/return cycle where the platform exposes one. The cookie belongs to
+the loopback origin; the bootstrap Tauri origin neither reads nor writes it.
+
+### Verification Matrix
+
+| Scenario | First-pass automation | Residual evidence |
+| --- | --- | --- |
+| D01, D02 | Tauri integration: cold start and adopt without duplicate launch | packaged-app smoke on both OSes |
+| D03 | SSE unit/integration plus WebView cookie and reconnect instrumentation | sleep/wake cookie continuity |
+| D04 | shell-boundary assertion that Show JS has no Tauri IPC; Show proxy integration | live Show Runtime HMR in packaged app |
+| D05 | API and browser integration where supported | OS drag/drop and clipboard automation |
+| D06 | browser contract with a virtual authenticator where supported | physical/passkey evidence on both OSes |
+| D07 | POSIX PTY integration now; Windows ConPTY gate in M2 | Unicode, resize, Ctrl-C, disconnect |
+| D08 | reconnect state-machine tests | OS power-event evidence |
+| D09, D10 | Tauri lifecycle integration: close/reopen and Runtime crash/recovery | packaged-app process inspection |
+| D11 | clean macOS/Windows CI image | signed installer proof in M3 |
+| D12 | Windows x64 workflow with fake Codex; protected real-backend job | real credential and native `C:\...` edit |
+
+The shell PR may automate only the rows it owns. Manual-first rows stay open
+acceptance evidence; they are not silently counted as passing because the
+underlying browser code has unit coverage.
+
+### Required Windows Gates
+
+| Gate | Coverage |
+| --- | --- |
+| `windows-runtime-contract` | isolated `AVIBE_HOME`, wheel install, service and authenticated control IPC, fake Codex, graceful stop/restart, no orphan tree |
+| `windows-terminal-e2e` | real ConPTY with PowerShell Unicode, resize, `\x03`, exit, disconnect, and idempotent terminate; no bash or WSL |
+| `windows-agent-e2e` | protected/nightly real Codex credential, stream and native file edit, no `wsl.exe`, no `/mnt/` |
+| `desktop-windows-build` | required Windows x64 Tauri/WebView2 build |
+
+ARM64 remains off the required matrix until the Claude SDK wheel constraint is
+removed. D12 file proof covers drive roots and a native read/edit/rename in a
+`C:\...` workspace; no Windows path translation layer is added.
+
+## Go / No-Go Gate
+
+Proceed with Tauri when all are true:
+
+- no core Workbench feature has an unworkable WKWebView or WebView2 blocker;
+- browser and desktop behavior remain materially equivalent;
+- a native Windows agent session completes end to end;
+- background tasks survive window close, shell restart, and WebView crash;
+- platform differences remain inside the defined adapters;
+- macOS and Windows have automated build and focused lifecycle verification.
+
+Replace only the shell with Electron if any are true:
+
+- Vault, Show Pages, terminal, or streaming requires a long-lived WebView fork;
+- reliable lifecycle behavior cannot be tested or reproduced;
+- Wry/Tauri must be permanently patched to ship core flows;
+- business components accumulate Tauri-specific branches;
+- OS WebView differences create recurring release-blocking regressions.
+
+## Implementation Sequence
+
+1. Land this plan and the `desktop` integration-branch policy in a documentation
+ PR targeting `desktop`.
+2. Land the small `vibe start --no-open-browser` launcher contract in its own
+ Python PR.
+3. Land the Python-owned desktop endpoint contract: versioned descriptor,
+ same-process loopback listener, combined `/ready`, and Host/auth regression
+ tests.
+4. Land the desktop-host PR containing `desktop/**`, its two central locale
+ catalog sections, and the desktop workflow: frozen probe/adopt/launch state
+ machine, capability boundary, combined readiness/recovery, unit tests, and
+ macOS/Windows build jobs.
+5. Exercise D01-D05 and D08-D10 locally where the host permits.
+6. Land the Windows Controller IPC contract and cross-platform conformance tests.
+7. Land `ProcessHost`: graceful control request, daemon ownership, Job Object
+ worker cleanup, PID birth identity, restart, and UI port recovery.
+8. Prove D12 with Codex on Windows x64 and a real native workspace.
+9. Extract the POSIX terminal seam and shared conformance suite without changing
+ product behavior.
+10. Land pywinpty/ConPTY and prove D07.
+11. Prove Vault and Show Runtime on Windows without reducing their capability.
+12. Reuse the existing managed-Runtime parsing, validation, caching, and asset
+ resolution for private Python/installer work; do not create a parallel
+ Windows downloader.
+13. Add packaging and signing only after M1 and M2 pass.
+
+Every implementation PR is non-draft, targets `desktop`, and requires GitHub
+Codex review on its current head, zero unresolved review threads, and green
+required CI before merge.
+
+## Desktop Host PR Scope
+
+Included:
+
+- `desktop/**` Tauri v2 scaffold and bootstrap contract;
+- the exact `desktopBootstrap` keys in the central English and Chinese frontend
+ catalogs; no other Workbench code;
+- consumption and strict validation of the Python-owned desktop descriptor;
+- safe loopback Runtime discovery, combined readiness, launch, and recovery;
+- bootstrap status/error/retry UI;
+- unit tests for the Rust host logic;
+- `.github/workflows/desktop-shell.yml` for macOS and Windows.
+
+Excluded:
+
+- this plan and repository workflow policy, which land separately;
+- Python Runtime or CLI changes, including the headless launcher and desktop
+ endpoint contracts;
+- ConPTY and Windows credential IPC;
+- bundled Python and installer artifacts;
+- tray and updater polish beyond what D01/D02/D09 require;
+- any reduction of Show Page functionality;
+- mobile projects.
diff --git a/docs/plans/windows-control-ipc.md b/docs/plans/windows-control-ipc.md
new file mode 100644
index 000000000..e3fbb53f8
--- /dev/null
+++ b/docs/plans/windows-control-ipc.md
@@ -0,0 +1,278 @@
+# Windows Controller Control IPC
+
+## Status
+
+- Owner: Avibe Controller control IPC
+- Scope: the existing internal HTTP routes and SSE streams
+- POSIX transport: unchanged Unix-domain socket
+- Windows transport: authenticated ephemeral IPv4 loopback TCP
+- Contract version: 1
+
+## Goal
+
+The Controller and its local UI/CLI child processes need one HTTP transport on
+native Windows without changing the routes, response bodies, or SSE event
+ordering that already run over a Unix-domain socket on POSIX.
+
+This contract does not introduce custom HTTP over named pipes. It does not
+change Runtime process ownership, Tauri lifecycle, terminal, Vault credential
+IPC, agent backends, Show Runtime, dependency installation, or packaging.
+
+## Endpoint Selection
+
+### POSIX
+
+POSIX keeps the existing endpoint and behavior:
+
+- default socket: `${AVIBE_HOME}/state/dispatch.sock`;
+- override: `VIBE_INTERNAL_DISPATCH_SOCKET`;
+- transport: `AF_UNIX` stream socket;
+- socket mode: best-effort `0600` under a restrictive bind-time umask;
+- HTTP base URL used by clients: `http://localhost`;
+- no bearer header or endpoint descriptor.
+
+An explicit `socket_path` passed by an existing caller remains an explicit UDS
+endpoint. Existing POSIX callers do not read the Windows descriptor.
+
+### Windows
+
+The Controller pre-binds an `AF_INET` listener to `127.0.0.1:0`, calls
+`listen`, and then publishes:
+
+`%AVIBE_HOME%\runtime\control-ipc\endpoint.json`
+
+`AVIBE_HOME` retains its existing meaning. The default therefore lives below
+the current user's Avibe home, not a machine-wide temporary directory.
+
+The descriptor sits in its own `control-ipc` directory rather than the runtime
+root because the Controller hardens the containing directory, not only the
+file. That hardening is only safe where every entry belongs to control IPC.
+
+The UTF-8 JSON descriptor has exactly this version-1 shape:
+
+```json
+{
+ "schema_version": 1,
+ "transport": "tcp",
+ "host": "127.0.0.1",
+ "port": 49152,
+ "instance_id": "d69b9554dfb64cb6a1ca1df963fb3888",
+ "bearer_token": "43-or-more-URL-safe-random-characters"
+}
+```
+
+| Field | Producer | Consumer | Contract |
+| --- | --- | --- | --- |
+| `schema_version` | Controller host | internal clients | Integer `1`; any other value is unsupported |
+| `transport` | Controller host | internal clients | Literal `tcp` |
+| `host` | Controller host | internal clients | Literal `127.0.0.1`; hostnames, wildcard addresses, and non-loopback addresses are rejected |
+| `port` | bound listener | internal clients | Integer `1..65535`; it is read from the pre-bound listener |
+| `instance_id` | Controller host | server middleware and internal clients | 128-bit random lowercase hexadecimal identifier |
+| `bearer_token` | Controller host | server middleware and internal clients | At least 256 bits from the OS CSPRNG, encoded as URL-safe text |
+
+Unknown top-level fields are rejected in version 1. The descriptor is a local
+secret because it contains the bearer token.
+
+The Controller creates the runtime directory, lock file, temporary descriptor,
+and stable descriptor with explicit private security:
+
+- POSIX uses `0700` for the directory and `0600` for files;
+- Windows uses a protected, non-inherited DACL with full access granted only to
+ the current user SID and Local System, and records the current user SID as
+ owner.
+
+Windows creation passes this security descriptor to `CreateDirectoryW` and
+`CreateFileW`; it does not expose an inherited-permission file and tighten it
+afterward. Before consuming a descriptor, the client validates the opened
+file's owner and exact protected DACL. A descriptor, lock, or runtime directory
+with a different owner, an inherited DACL, or any additional allow entry is
+rejected. A producer may tighten an existing current-user-owned artifact during
+publication for upgrade compatibility, but it never changes or accepts an
+artifact owned by another principal. Windows security API failures fail startup
+or discovery closed.
+
+Descriptor contents, authorization headers, and bearer tokens must not appear
+in logs, exceptions, HTTP response bodies, or test failure output.
+
+## Producer And Consumer Ownership
+
+The Controller-side `ControlIpcHost` owns:
+
+1. transport selection;
+2. listener creation and pre-bind;
+3. instance ID and bearer generation;
+4. atomic descriptor publication;
+5. request authentication and instance response headers on Windows;
+6. owner-safe endpoint cleanup.
+
+`vibe.internal_client` owns:
+
+1. platform-specific endpoint discovery;
+2. strict descriptor parsing;
+3. attaching authentication to every Windows request and stream;
+4. checking the responding instance on every Windows response and stream;
+5. translating discovery, connect, authentication, and stale-instance failures
+ into the existing unavailable/timeout behavior.
+
+The UI-process Model Hub RPC client uses this same endpoint discovery,
+transport, bearer header, and instance-response validation contract. It does
+not inspect `dispatch.sock` or construct a UDS transport independently.
+
+Any internal caller that opens `dispatch.sock` directly instead of using the
+shared client connection contract remains POSIX-only until its owning lane
+migrates it. The Windows server never provides an unauthenticated compatibility
+path for such callers.
+
+## Authentication And Instance Binding
+
+Every Windows request, including `GET /internal/health`, both SSE routes, and
+all mutating routes, carries:
+
+```text
+Authorization: Bearer <bearer_token>
+```
+
+The server compares the credential in constant time. Missing, malformed, or
+incorrect credentials receive a generic `401` response. The response does not
+echo the credential or explain which part failed.
+
+Every authenticated Windows response carries:
+
+```text
+X-Avibe-Control-Instance: <instance_id>
+```
+
+This includes framework-generated `500 Internal Server Error` responses for
+unhandled route exceptions. The Windows-only error handler preserves the
+framework's status and plain-text body while adding the instance header.
+
+The client compares that value with the descriptor's `instance_id` before it
+accepts a response or consumes an SSE body. A missing or mismatched header is a
+stale-instance failure. This prevents a stale descriptor from silently
+connecting to an unrelated listener or a successor Controller that reused the
+same port.
+
+POSIX remains authenticated by possession and filesystem permissions of the
+Unix socket and does not require these HTTP headers.
+
+## Descriptor Validation
+
+A Windows client rejects the descriptor before opening a connection when any
+of the following is true:
+
+- the path is absent, a symlink, not a regular file, unreadable, or larger than
+ the bounded descriptor size;
+- JSON is malformed, is not an object, has missing or unknown fields, or uses
+ the wrong primitive types;
+- `schema_version` or `transport` is unsupported;
+- `host` is not exactly `127.0.0.1`;
+- `port` is outside `1..65535`;
+- `instance_id` is not the version-1 128-bit hexadecimal form;
+- `bearer_token` is not the version-1 URL-safe minimum-strength form.
+
+Errors identify only the descriptor category and path. They never include raw
+descriptor data.
+
+## Startup And Atomic Publication
+
+Windows startup is ordered:
+
+1. create the runtime directory and user-only lock file;
+2. create a fresh instance ID and bearer token;
+3. create a fresh TCP socket;
+4. enable exclusive-address semantics where Windows supports them;
+5. bind to `127.0.0.1:0`, call `listen`, and set non-blocking mode;
+6. read the assigned port from `getsockname`;
+7. write and `fsync` a user-only temporary descriptor in the control IPC
+ directory;
+8. while holding the descriptor lock, atomically replace
+ `endpoint.json`;
+9. hand the already-bound listener to uvicorn.
+
+The stable descriptor never contains an unbound or requested port. Bind
+failure publishes nothing. Publication failure closes the listener and leaves
+the previous stable descriptor untouched.
+
+An `EADDRINUSE` result while binding the ephemeral listener is retried with a
+fresh socket up to three total bind attempts. Other bind errors fail startup
+immediately. The OS still selects every candidate port; Avibe does not scan or
+persist a preferred port.
+
+## Shutdown And Stale Instances
+
+Graceful shutdown first stops the server task and closes its listener. The
+Windows host then acquires the same descriptor lock used by publication,
+re-reads the stable descriptor, and removes it only when both `instance_id` and
+`bearer_token` match the current host.
+
+A stale Controller whose descriptor has already been atomically replaced by a
+successor therefore leaves the successor descriptor untouched. Missing,
+malformed, or non-owned descriptors are also left untouched.
+
+A hard crash can leave a descriptor behind. Clients treat connect failure,
+authentication failure, or instance-header mismatch as unavailable. A
+successor binds a fresh listener and atomically replaces the stale descriptor
+after bind succeeds. Each new host instance generates a new instance ID and
+bearer credential; neither credential is reused across a successor publication.
+
+POSIX keeps its existing stale socket replacement on startup and socket unlink
+on graceful server shutdown.
+
+## Retry And Reconnect
+
+- Listener bind: only `EADDRINUSE`, at most three total attempts, always with a
+ fresh socket.
+- Descriptor publication: one atomic replace attempt while locked; a failure is
+ a startup failure and does not publish partial JSON.
+- Ordinary request: no hidden application-level retry. The existing caller
+ decides whether unavailable/timeout is retryable.
+- SSE connection: one descriptor snapshot per connection. The client does not
+ switch instances inside a live stream.
+- SSE reconnect: the existing subscriber reconnect loop calls the client again;
+ that new call re-reads the descriptor, re-authenticates, and validates the new
+ instance header.
+
+This avoids replaying mutating requests while allowing a long-lived SSE
+consumer to follow a restarted Controller safely.
+
+## HTTP And SSE Compatibility
+
+Windows exposes the same FastAPI application, methods, paths, status codes,
+JSON bodies, and SSE payloads as POSIX. Authentication is transport middleware,
+not route logic.
+
+For both `POST /internal/dispatch` and `GET /internal/events`:
+
+- uvicorn receives the pre-bound listener;
+- SSE framing remains `event:` followed by JSON `data:` and one blank line;
+- non-ASCII JSON content remains UTF-8 end to end;
+- event order is unchanged;
+- authentication and instance validation complete before the client consumes
+ the first SSE event;
+- a disconnect does not replay or reorder events; the existing route/caller
+ semantics decide what a new request observes.
+
+## Verification Contract
+
+Focused automated evidence must cover:
+
+- unchanged POSIX UDS selection and explicit UDS override;
+- Windows TCP descriptor selection and strict validation;
+- Windows current-user/SYSTEM-only owner and DACL enforcement for the runtime
+ directory, lock, temporary descriptor, and stable descriptor;
+- rejection of widened or non-owner Windows artifacts, plus upgrade-time repair
+ only for current-user-owned artifacts;
+- real loopback HTTP/SSE with non-ASCII dispatch data and preserved event order;
+- missing and incorrect bearer rejection;
+- stale descriptor and mismatched instance rejection;
+- Model Hub sync and async RPCs through the shared Windows endpoint, bearer,
+ and instance validation;
+- instance headers on authenticated framework-generated 500 responses;
+- atomic descriptor replacement without partial reads;
+- owner-safe cleanup after successor replacement;
+- occupied-port rebind behavior with a fresh socket;
+- SSE reconnect through a successor descriptor;
+- Ruff on every changed Python file.
+
+A focused `windows-latest` CI job is required until an existing Windows job
+installs the test dependencies and exercises this contract.
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 21c93ec9a..2571e4e92 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -8,6 +8,7 @@ import logging
import os
import shlex
import time
+from collections.abc import Mapping
from contextlib import AsyncExitStack
from dataclasses import dataclass
from pathlib import Path
@@ -67,6 +68,7 @@ from modules.agents.codex.session import CodexSessionManager
from modules.agents.codex.transport import CodexResponseTooLargeError, CodexRPCError, CodexTransport
from modules.agents.codex.turn_state import CodexTurnRegistry
from vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_ID
+from vibe.desktop_backends import desktop_backend_subprocess_environment
from vibe.i18n import t as i18n_t
from vibe.message_identity import is_input_turn
@@ -2223,7 +2225,7 @@ class CodexAgent(BaseAgent):
pass
else:
runtime_args: list[str] = []
- runtime_env: dict[str, str] | None = None
+ runtime_env = dict(self._codex_runtime_environment())
runtime_fingerprint = "direct"
catalog = None
if launch is not None:
@@ -2237,7 +2239,7 @@ class CodexAgent(BaseAgent):
catalog_pins.callback(catalog.close)
runtime_args, runtime_env = build_codex_hub_launch(
[],
- os.environ.copy(),
+ runtime_env,
launch,
model_catalog_path=catalog.path if catalog is not None else None,
)
@@ -2418,6 +2420,7 @@ class CodexAgent(BaseAgent):
from core.git_runtime import prepend_vendored_git_to_path
env = self._caller_env_for_request(request)
+ runtime_env = self._codex_runtime_environment()
config = dict(params.get("config") or {})
config["skills.include_instructions"] = False
params["config"] = config
@@ -2429,10 +2432,10 @@ class CodexAgent(BaseAgent):
set_env.update({**env, "BASH_ENV": str(env_script_path)})
git_path_changed = prepend_vendored_git_to_path(
set_env,
- base_env=os.environ,
+ base_env=runtime_env,
working_dir=getattr(request, "working_path", None),
)
- git_path_state = set_env["PATH"] if "PATH" in set_env else os.environ.get("PATH", "")
+ git_path_state = set_env["PATH"] if "PATH" in set_env else runtime_env.get("PATH", "")
path_managed = had_path or git_path_changed or force_path
if force_path:
set_env["PATH"] = git_path_state
@@ -2446,13 +2449,24 @@ class CodexAgent(BaseAgent):
def _git_path_state_for_request(self, request: AgentRequest) -> str:
from core.git_runtime import prepend_vendored_git_to_path
+ runtime_env = self._codex_runtime_environment()
env: dict[str, str] = {}
prepend_vendored_git_to_path(
env,
- base_env=os.environ,
+ base_env=runtime_env,
working_dir=getattr(request, "working_path", None),
)
- return env["PATH"] if "PATH" in env else os.environ.get("PATH", "")
+ return env["PATH"] if "PATH" in env else runtime_env.get("PATH", "")
+
+ def _codex_runtime_environment(self) -> Mapping[str, str]:
+ base_env = os.environ
+ binary = getattr(getattr(self, "codex_config", None), "binary", "codex")
+ managed = desktop_backend_subprocess_environment(
+ "codex",
+ binary,
+ base_env,
+ )
+ return managed if managed is not None else base_env
async def _start_thread(
self,
diff --git a/scripts/desktop_release.py b/scripts/desktop_release.py
new file mode 100644
index 000000000..2e379f58a
--- /dev/null
+++ b/scripts/desktop_release.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+"""Produce and verify desktop TEST release assets for the existing release workflow."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+from runpy import run_path
+
+
+_versions = run_path(str(Path(__file__).with_name("release_package_version.py")))
+package_version_from_release_tag = _versions["package_version_from_release_tag"]
+_github = run_path(str(Path(__file__).with_name("github_release.py")))
+TARGETS = {
+ "aarch64-apple-darwin": ("macos", "aarch64", ".dmg"),
+ "x86_64-apple-darwin": ("macos", "x86_64", ".dmg"),
+ "x86_64-pc-windows-msvc": ("windows", "x86_64", ".exe"),
+}
+RC_TAG = re.compile(r"gh-v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)rc(0|[1-9][0-9]*)")
+SHA = re.compile(r"[0-9a-f]{40}")
+SEMVER = re.compile(
+ r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
+ r"(?:-(?P<pre>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
+)
+
+
+def desktop_version_from_tag(tag: str) -> str:
+ match = RC_TAG.fullmatch(tag)
+ if match is None:
+ raise ValueError("desktop TEST release requires a canonical gh-vX.Y.ZrcN tag")
+ package_version = package_version_from_release_tag(tag)
+ return package_version.replace("rc", "-rc.")
+
+
+def git_output(*args: str) -> str:
+ return subprocess.check_output(["git", *args], text=True).strip()
+
+
+def resolve(tag: str, source_sha: str | None = None) -> dict[str, str]:
+ version = desktop_version_from_tag(tag)
+ actual = git_output("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")
+ if SHA.fullmatch(actual) is None or (source_sha is not None and actual != source_sha):
+ raise ValueError("desktop release tag does not match the exact source SHA")
+ return {"tag": tag, "source_sha": actual, "version": version,
+ "package_version": package_version_from_release_tag(tag)}
+
+
+def prepare(version: str, tag: str, source_sha: str, config: Path, env_file: Path) -> None:
+ match = SEMVER.fullmatch(version)
+ if match is None or any(
+ part.isdigit() and len(part) > 1 and part.startswith("0")
+ for part in (match["pre"] or "").split(".")
+ ):
+ raise ValueError("version must be valid SemVer")
+ override = {"version": version}
+ if tag:
+ resolved = resolve(tag, source_sha)
+ if git_output("rev-parse", "HEAD") != source_sha or version != resolved["version"]:
+ raise ValueError("desktop checkout/version does not match the release tag")
+ # The reusable TEST path receives no secrets and overrides any identity
+ # configuration. The manual path retains its optional credential policy.
+ override["bundle"] = {
+ "macOS": {"signingIdentity": "-"},
+ "windows": {"certificateThumbprint": None, "signCommand": None},
+ }
+ with env_file.open("a", encoding="utf-8") as stream:
+ for key in ("SETUPTOOLS_SCM_PRETEND_VERSION", "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS"):
+ stream.write(f"{key}={resolved['package_version']}\n")
+ config.write_text(json.dumps(override) + "\n", encoding="utf-8")
+
+
+def digest(path: Path) -> str:
+ result = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ result.update(block)
+ return result.hexdigest()
+
+
+def signature(target: str) -> str:
+ if TARGETS[target][0] == "macos":
+ return "app-adhoc\ndmg-unsigned-unnotarized\n"
+ return "installer-unsigned\n"
+
+
+def asset_names(version: str, target: str) -> list[str]:
+ prefix = f"Avibe_{version}_{target}"
+ return [prefix + TARGETS[target][2], prefix + ".runtime-manifest.json",
+ prefix + ".SOURCE.json", prefix + ".SIGNATURE", prefix + ".SHA256SUMS"]
+
+
+def validate_manifest(manifest: dict, target: str, tag: str) -> None:
+ expected_os, arch, _ = TARGETS[target]
+ if (manifest.get("schema_version"), manifest.get("os"), manifest.get("arch")) != (2, expected_os, arch):
+ raise ValueError("Runtime manifest target/schema mismatch")
+ if tag and manifest.get("runtime_version") != package_version_from_release_tag(tag):
+ raise ValueError("bundled Avibe version does not match the release tag")
+ for field in ("archive_sha256", "tree_sha256"):
+ if re.fullmatch(r"[0-9a-f]{64}", str(manifest.get(field))) is None:
+ raise ValueError(f"Invalid Runtime {field}")
+ for field in ("archive_size", "entry_count", "unpacked_size"):
+ if type(manifest.get(field)) is not int or manifest[field] <= 0:
+ raise ValueError(f"Invalid Runtime {field}")
+
+
+def record(*, version: str, target: str, tag: str, source_sha: str,
+ installer: Path, runtime: Path, output: Path, signing: str) -> None:
+ if SHA.fullmatch(source_sha) is None:
+ raise ValueError("Invalid source SHA")
+ if tag and (version != desktop_version_from_tag(tag) or signing != signature(target).strip()):
+ raise ValueError("TEST version/signature policy mismatch")
+ manifest_path = runtime / "runtime-manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ validate_manifest(manifest, target, tag)
+ archive = runtime / "runtime.zip"
+ if (manifest.get("archive") != archive.name or archive.stat().st_size != manifest["archive_size"]
+ or digest(archive) != manifest["archive_sha256"]):
+ raise ValueError("Runtime archive hash/size mismatch")
+ if installer.suffix != TARGETS[target][2] or installer.stat().st_size == 0:
+ raise ValueError("Missing or wrong installer")
+ output.mkdir(parents=True, exist_ok=True)
+ if list(output.iterdir()):
+ raise ValueError("Desktop artifact output must be empty")
+ names = asset_names(version, target)
+ shutil.copyfile(installer, output / names[0])
+ shutil.copyfile(manifest_path, output / names[1])
+ (output / names[2]).write_text(json.dumps({
+ "schema_version": 1, "tag": tag, "source_sha": source_sha,
+ "version": version, "target": target,
+ "package_version": manifest["runtime_version"],
+ }, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ (output / names[3]).write_text(signing + "\n", encoding="utf-8")
+ (output / names[4]).write_text(
+ "".join(f"{digest(output / name)} {name}\n" for name in sorted(names[:4])), encoding="utf-8",
+ )
+
+
+def verify(directory: Path, tag: str, source_sha: str) -> list[Path]:
+ version = desktop_version_from_tag(tag)
+ if SHA.fullmatch(source_sha) is None:
+ raise ValueError("Invalid source SHA")
+ expected = {name for target in TARGETS for name in asset_names(version, target)}
+ if {path.name for path in directory.iterdir()} != expected:
+ raise ValueError("Desktop asset set must contain exactly all three targets and their metadata")
+ for target in TARGETS:
+ names = asset_names(version, target)
+ for name in names:
+ path = directory / name
+ if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
+ raise ValueError(f"Missing/empty/non-regular desktop asset: {name}")
+ checksums = "".join(f"{digest(directory / name)} {name}\n" for name in sorted(names[:4]))
+ if (directory / names[4]).read_text(encoding="utf-8") != checksums:
+ raise ValueError("Desktop asset hash mismatch")
+ source = json.loads((directory / names[2]).read_text(encoding="utf-8"))
+ if source != {"schema_version": 1, "tag": tag, "source_sha": source_sha,
+ "version": version, "target": target,
+ "package_version": package_version_from_release_tag(tag)}:
+ raise ValueError("Desktop source provenance mismatch")
+ if (directory / names[3]).read_text(encoding="utf-8") != signature(target):
+ raise ValueError("Desktop TEST signature policy mismatch")
+ validate_manifest(json.loads((directory / names[1]).read_text(encoding="utf-8")), target, tag)
+ return [directory / name for name in sorted(expected)]
+
+
+def check_remote(directory: Path, tag: str, source_sha: str, repo: str, *, complete: bool) -> None:
+ paths = verify(directory, tag, source_sha)
+ state = _github["get_release"](repo, tag)
+ if state is None:
+ if complete:
+ raise ValueError("Release is missing before finalization")
+ return
+ remote = json.loads(subprocess.check_output(
+ ["gh", "release", "view", tag, "--repo", repo, "--json", "assets"], text=True,
+ ))
+ names = {asset["name"] for asset in remote["assets"]}
+ expected = {path.name for path in paths}
+ if (complete or not state.draft) and not expected <= names:
+ raise ValueError("Missing desktop assets; published tags cannot be retrofitted, cut a new rc")
+ if complete:
+ # Read back uploaded bytes before the sole workflow finalizer publishes.
+ with tempfile.TemporaryDirectory(prefix="desktop-release-verify-") as temporary:
+ for path in paths:
+ subprocess.run(["gh", "release", "download", tag, "--repo", repo,
+ "--pattern", path.name, "--dir", temporary], check=True)
+ if digest(Path(temporary) / path.name) != digest(path):
+ raise ValueError(f"Uploaded desktop asset differs: {path.name}")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest="command", required=True)
+ resolver = sub.add_parser("resolve")
+ resolver.add_argument("--tag", required=True)
+ resolver.add_argument("--output", type=Path, required=True)
+ prep = sub.add_parser("prepare")
+ prep.add_argument("--version", required=True)
+ prep.add_argument("--tag", default="")
+ prep.add_argument("--source-sha", default="")
+ prep.add_argument("--config", type=Path, required=True)
+ prep.add_argument("--env-file", type=Path, required=True)
+ producer = sub.add_parser("record")
+ producer.add_argument("--version", required=True)
+ producer.add_argument("--target", choices=TARGETS, required=True)
+ producer.add_argument("--tag", default="")
+ producer.add_argument("--source-sha", required=True)
+ producer.add_argument("--installer", type=Path, required=True)
+ producer.add_argument("--runtime", type=Path, required=True)
+ producer.add_argument("--output", type=Path, required=True)
+ producer.add_argument("--signing", required=True)
+ for command in ("verify", "check-remote"):
+ consumer = sub.add_parser(command)
+ consumer.add_argument("--directory", type=Path, required=True)
+ consumer.add_argument("--tag", required=True)
+ consumer.add_argument("--source-sha", required=True)
+ if command == "check-remote":
+ consumer.add_argument("--repo", required=True)
+ consumer.add_argument("--complete", action="store_true")
+ args = vars(parser.parse_args())
+ command = args.pop("command")
+ if command == "resolve":
+ args["output"].write_text("".join(f"{key}={value}\n" for key, value in resolve(args["tag"]).items()),
+ encoding="utf-8")
+ elif command == "prepare":
+ prepare(**args)
+ elif command == "record":
+ record(**args)
+ elif command == "verify":
+ verify(**args)
+ else:
+ check_remote(**args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/storage/background.py b/storage/background.py
index 9444b3c45..8923ea2ee 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2426,13 +2426,16 @@ def _publish_run_rows_updated(rows: list[Any]) -> None:
if not run_id:
continue
try:
+ status = normalize_run_status(row.get("status"))
payload = run_updated_payload(
run_id=run_id,
- status=normalize_run_status(row.get("status")),
+ status=status,
run_type=row.get("run_type"),
session_id=row.get("session_id"),
definition_id=row.get("definition_id"),
updated_at=row.get("updated_at"),
+ started_at=row.get("started_at") if status in TERMINAL_RUN_STATUSES else None,
+ completed_at=row.get("completed_at") if status in TERMINAL_RUN_STATUSES else None,
cancel_requested=bool(row.get("cancel_requested")),
)
bus.publish(RUNS_UPDATED_EVENT, payload)
diff --git a/tests/fixtures/desktop_ready_external_controller_bundled_ui.json b/tests/fixtures/desktop_ready_external_controller_bundled_ui.json
new file mode 100644
index 000000000..209d0c64f
--- /dev/null
+++ b/tests/fixtures/desktop_ready_external_controller_bundled_ui.json
@@ -0,0 +1,6 @@
+{
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": true,
+ "desktop_ui_runtime_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+}
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index c86ff7b75..f5d4d0a8f 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -40,6 +40,18 @@ def native_safety(monkeypatch, _isolate_vibe_remote_home):
monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
monkeypatch.setattr(psutil, "process_iter", forbidden)
+ # The connection projection deliberately observes inherited launch
+ # credentials. Keep the fixture independent from the coding agent's own
+ # process environment so direct native-store cases exercise their stated
+ # source and do not accidentally select an ambient API key.
+ for name in (
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_BASE_URL",
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ ):
+ monkeypatch.delenv(name, raising=False)
monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index e40cabe9e..242db6dd1 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import os
from dataclasses import dataclass, field
from pathlib import Path
import sys
@@ -15,7 +16,15 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core.handlers.session_handler as session_handler_module
from config.v2_compat import to_app_config
-from config.v2_config import AgentsConfig, ClaudeConfig, RuntimeConfig, SlackConfig, V2Config
+from config.v2_config import (
+ AgentsConfig,
+ ClaudeConfig,
+ CodexConfig,
+ OpenCodeConfig,
+ RuntimeConfig,
+ SlackConfig,
+ V2Config,
+)
from config.v2_settings import RoutingSettings
from core import git_runtime as git_runtime_module
from core.handlers.session_handler import SessionHandler
@@ -155,6 +164,90 @@ def test_to_app_config_preserves_claude_cli_path() -> None:
assert compat.claude.cli_path == "/usr/local/bin/claude-proxy"
+def test_to_app_config_resolves_all_desktop_backend_executables(monkeypatch, tmp_path: Path) -> None:
+ binaries = {
+ "claude": tmp_path / ".local" / "bin" / "claude",
+ "codex": tmp_path / ".local" / "bin" / "codex",
+ "opencode": tmp_path / ".opencode" / "bin" / "opencode",
+ }
+ for binary in binaries.values():
+ binary.parent.mkdir(parents=True, exist_ok=True)
+ binary.write_text("#!/bin/sh\n", encoding="utf-8")
+ binary.chmod(0o755)
+
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr("vibe.cli_paths.Path.home", lambda: tmp_path)
+ v2 = V2Config(
+ mode="self_host",
+ version="2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd="/tmp/workdir"),
+ agents=AgentsConfig(
+ claude=ClaudeConfig(cli_path="claude"),
+ codex=CodexConfig(cli_path="codex"),
+ opencode=OpenCodeConfig(cli_path="opencode"),
+ ),
+ )
+
+ compat = to_app_config(v2)
+
+ assert compat.claude.cli_path == str(binaries["claude"])
+ assert compat.codex is not None
+ assert compat.codex.binary == str(binaries["codex"])
+ assert compat.opencode is not None
+ assert compat.opencode.binary == str(binaries["opencode"])
+
+
+def test_to_app_config_keeps_missing_private_backend_selectors_off_path(monkeypatch, tmp_path: Path) -> None:
+ from vibe.cli_paths import resolve_cli_path
+
+ private_root = tmp_path / "private-backends"
+ external_root = tmp_path / "external-bin"
+ external_root.mkdir()
+ suffix = ".exe" if os.name == "nt" else ""
+ selected = {}
+ for backend in ("claude", "codex", "opencode"):
+ name = backend + suffix
+ selected[backend] = private_root / backend / "releases" / "missing" / name
+ external = external_root / name
+ external.write_bytes(b"MZ\0\0" if os.name == "nt" else b"#!/bin/sh\n")
+ external.chmod(0o755)
+
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ROOT", str(tmp_path / "runtime"))
+ monkeypatch.setenv("AVIBE_DESKTOP_BACKENDS_ROOT", str(private_root))
+ monkeypatch.setenv("PATH", str(external_root))
+ monkeypatch.setattr(
+ "vibe.cli_paths._candidate_cli_paths",
+ lambda binary, **_kwargs: [Path(binary)] if Path(binary).is_absolute() else [],
+ )
+ v2 = V2Config(
+ mode="self_host",
+ version="2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd=str(tmp_path)),
+ agents=AgentsConfig(
+ claude=ClaudeConfig(cli_path=str(selected["claude"])),
+ codex=CodexConfig(cli_path=str(selected["codex"])),
+ opencode=OpenCodeConfig(cli_path=str(selected["opencode"])),
+ ),
+ )
+
+ compat = to_app_config(v2)
+
+ assert compat.claude.cli_path == str(selected["claude"])
+ assert compat.codex is not None and compat.codex.binary == str(selected["codex"])
+ assert compat.opencode is not None and compat.opencode.binary == str(selected["opencode"])
+ assert resolve_cli_path(str(tmp_path / "other" / ("claude" + suffix)), include_npm_global=False) == str(
+ external_root / ("claude" + suffix)
+ )
+
+ published = tmp_path / "published" / ("codex" + suffix)
+ monkeypatch.setattr("vibe.cli_paths.resolve_published_desktop_backend", lambda _backend: str(published))
+ assert resolve_cli_path(str(selected["codex"]), include_npm_global=False) == str(published)
+
+
def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_path: Path) -> None:
captured: dict[str, Any] = {}
@@ -3500,3 +3593,51 @@ def test_tracking_a_create_retires_the_previous_teardown_record(monkeypatch, tmp
assert asyncio.run(scenario()) is False
assert composite_key not in handler.claude_intentional_teardowns
+
+
+def test_to_app_config_never_spawns_npm_on_async_request_paths(monkeypatch, tmp_path: Path) -> None:
+ """Runtime path projection must not shell out to npm.
+
+ ``to_app_config`` is reached from async request handlers, and the npm-global
+ branch of the resolver runs ``npm config get prefix`` with a five-second
+ timeout. One missing backend would stall an event loop for that long.
+ """
+
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr("vibe.cli_paths.Path.home", lambda: tmp_path)
+
+ # Recorded rather than raised: ``_npm_prefix_for`` wraps its spawn in a bare
+ # ``except Exception``, so an assertion raised here would be swallowed and
+ # the test would pass while the subprocess still ran.
+ spawned: list[object] = []
+
+ def _record_spawn(*args, **kwargs):
+ spawned.append(args)
+ raise FileNotFoundError("npm")
+
+ monkeypatch.setattr("vibe.cli_paths.subprocess.run", _record_spawn)
+
+ v2 = V2Config(
+ mode="self_host",
+ version="2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd="/tmp/workdir"),
+ # Names no host can resolve, so every cheap candidate misses and the
+ # npm-global branch is actually reached. Real binary names would be
+ # found in Homebrew or /usr/local on a developer machine and the test
+ # would pass without proving anything.
+ agents=AgentsConfig(
+ claude=ClaudeConfig(cli_path="avibe-absent-claude-cli"),
+ codex=CodexConfig(cli_path="avibe-absent-codex-cli"),
+ opencode=OpenCodeConfig(cli_path="avibe-absent-opencode-cli"),
+ ),
+ )
+
+ compat = to_app_config(v2)
+
+ assert spawned == [], f"resolution spawned {len(spawned)} subprocess(es) on an async request path"
+ # Unresolvable selectors fall through to the saved value rather than failing.
+ assert compat.claude.cli_path == "avibe-absent-claude-cli"
+ assert compat.codex is not None and compat.codex.binary == "avibe-absent-codex-cli"
+ assert compat.opencode is not None and compat.opencode.binary == "avibe-absent-opencode-cli"
diff --git a/tests/test_cli_setup_status.py b/tests/test_cli_setup_status.py
index 9c01685aa..a29117cea 100644
--- a/tests/test_cli_setup_status.py
+++ b/tests/test_cli_setup_status.py
@@ -1,9 +1,12 @@
from __future__ import annotations
+import json
+from functools import partial
from types import SimpleNamespace
from unittest.mock import patch
from vibe import cli
+from vibe.runtime import ProcessStartInfo
def _config_with_setup_state(*, ready: bool) -> SimpleNamespace:
@@ -14,6 +17,26 @@ def _config_with_setup_state(*, ready: bool) -> SimpleNamespace:
)
+def _start_process(pid: int, *args, start_info: ProcessStartInfo, **kwargs) -> int:
+ start_info.pid = pid
+ start_info.create_unix_ms = 1789010100000.5 + pid
+ start_info.reused = False
+ return pid
+
+
+def _assert_start_receipt(output: str) -> None:
+ receipts = [line for line in output.splitlines() if line.startswith("@avibe-start-receipt:")]
+ assert len(receipts) == 1
+ assert json.loads(receipts[0].split(":", 1)[1]) == {
+ "schema_version": 1,
+ "outcome": "started",
+ "service_pid": 101,
+ "ui_pid": 202,
+ "service_create_unix_ms": 1789010100101.5,
+ "ui_create_unix_ms": 1789010100202.5,
+ }
+
+
def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -> None:
config = _config_with_setup_state(ready=False)
@@ -22,8 +45,8 @@ def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -
patch("vibe.cli._ensure_config", return_value=config),
patch("vibe.cli.runtime.stop_service") as stop_service,
patch("vibe.cli.runtime.stop_ui") as stop_ui,
- patch("vibe.cli.runtime.start_service", return_value=101),
- patch("vibe.cli.runtime.start_ui", return_value=202),
+ patch("vibe.cli.runtime.start_service", side_effect=partial(_start_process, 101)),
+ patch("vibe.cli.runtime.start_ui", side_effect=partial(_start_process, 202)),
patch("vibe.cli.runtime.wait_for_service_ready", return_value=101),
patch("vibe.cli.runtime.write_status"),
patch("vibe.cli._write_status") as write_status,
@@ -36,9 +59,10 @@ def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -
output = capsys.readouterr().out
assert "Run: vibe remote" in output
assert "SSH port forwarding" not in output
+ _assert_start_receipt(output)
-def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> None:
+def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured(capsys) -> None:
config = _config_with_setup_state(ready=True)
with (
@@ -46,8 +70,8 @@ def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> None
patch("vibe.cli._ensure_config", return_value=config),
patch("vibe.cli.runtime.stop_service") as stop_service,
patch("vibe.cli.runtime.stop_ui") as stop_ui,
- patch("vibe.cli.runtime.start_service", return_value=101),
- patch("vibe.cli.runtime.start_ui", return_value=202),
+ patch("vibe.cli.runtime.start_service", side_effect=partial(_start_process, 101)),
+ patch("vibe.cli.runtime.start_ui", side_effect=partial(_start_process, 202)),
patch("vibe.cli.runtime.wait_for_service_ready", return_value=101),
patch("vibe.cli.runtime.write_status"),
patch("vibe.cli._write_status") as write_status,
@@ -57,3 +81,4 @@ def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> None
stop_service.assert_not_called()
stop_ui.assert_not_called()
write_status.assert_called_once_with("starting")
+ _assert_start_receipt(capsys.readouterr().out)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index a84383377..6f3c5d621 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -2053,6 +2053,37 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
+ def test_inject_caller_env_config_preserves_private_codex_helpers_with_vendored_git(self):
+ agent = object.__new__(CodexAgent)
+ agent.codex_config = SimpleNamespace(binary="/private/codex")
+ params = {}
+ request = SimpleNamespace(
+ working_path="/tmp/workspace",
+ context=SimpleNamespace(platform_specific={}),
+ )
+ managed_env = {"PATH": "/private/codex-path:/usr/bin"}
+
+ def inject_git(env, *, base_env, working_dir):
+ self.assertEqual(base_env, managed_env)
+ self.assertEqual(working_dir, "/tmp/workspace")
+ env["PATH"] = f"/managed/git/bin:{base_env['PATH']}"
+ return True
+
+ with (
+ patch.object(
+ _MODULE,
+ "desktop_backend_subprocess_environment",
+ return_value=managed_env,
+ ),
+ patch("core.git_runtime.prepend_vendored_git_to_path", side_effect=inject_git),
+ ):
+ agent._inject_caller_env_config(params, request)
+
+ self.assertEqual(
+ params["config"]["shell_environment_policy"]["set"]["PATH"],
+ "/managed/git/bin:/private/codex-path:/usr/bin",
+ )
+
def test_inject_caller_env_config_adds_vendored_git_for_gitless_session(self):
agent = object.__new__(CodexAgent)
params = {"config": {"shell_environment_policy": {"set": {"PATH": ""}}}}
@@ -5797,6 +5828,75 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
self.assertIs(result, fresh)
self.assertEqual(calls, [(2468, "codex app-server")])
+ async def test_get_or_create_transport_launches_with_private_codex_helpers(self):
+ import tempfile
+
+ agent = self._agent()
+ agent.codex_config.binary = "/private/release/vendor/target/bin/codex"
+ managed_env = {"PATH": "/private/release/vendor/target/codex-path:/usr/bin"}
+ with tempfile.TemporaryDirectory() as cwd:
+ fresh = SimpleNamespace(
+ is_initialized=True,
+ pid=2468,
+ start=AsyncMock(),
+ on_notification=Mock(),
+ on_server_request=Mock(),
+ )
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=fresh) as constructor,
+ patch.object(
+ _MODULE,
+ "desktop_backend_subprocess_environment",
+ return_value=managed_env,
+ ),
+ ):
+ await agent._get_or_create_transport(cwd)
+
+ self.assertEqual(constructor.call_args.kwargs["runtime_env"], managed_env)
+
+ async def test_model_hub_transport_preserves_private_codex_helpers(self):
+ import tempfile
+
+ agent = self._agent()
+ agent.codex_config.binary = "/private/release/vendor/target/bin/codex"
+ managed_env = {
+ "PATH": "/private/release/vendor/target/codex-path:/usr/bin",
+ "OPENAI_API_KEY": "native-token",
+ }
+ launch = SimpleNamespace(
+ channel="hub",
+ gateway_base_url="http://127.0.0.1:18443",
+ gateway_token="gateway-token",
+ fingerprint="hub:test",
+ )
+ with tempfile.TemporaryDirectory() as cwd:
+ fresh = SimpleNamespace(
+ is_initialized=True,
+ pid=2468,
+ start=AsyncMock(),
+ on_notification=Mock(),
+ on_server_request=Mock(),
+ )
+ with (
+ patch.object(_MODULE, "CodexTransport", return_value=fresh) as constructor,
+ patch.object(
+ _MODULE,
+ "desktop_backend_subprocess_environment",
+ return_value=managed_env,
+ ),
+ patch(
+ "vibe.backend_model_catalog.prepare_codex_hub_catalog",
+ return_value=_catalog_reference(Path(cwd) / "codex-hub-catalog.json"),
+ ) as prepare_catalog,
+ ):
+ await agent._get_or_create_transport(cwd, launch)
+
+ runtime_env = constructor.call_args.kwargs["runtime_env"]
+ self.assertEqual(runtime_env["PATH"], managed_env["PATH"])
+ self.assertEqual(runtime_env["AVIBE_MODEL_HUB_TOKEN"], "gateway-token")
+ self.assertNotIn("OPENAI_API_KEY", runtime_env)
+ prepare_catalog.assert_called_once_with(agent.codex_config.binary, None, None)
+
async def test_cached_transport_evicted_when_cwd_inode_changes(self):
import tempfile
diff --git a/tests/test_control_ipc.py b/tests/test_control_ipc.py
new file mode 100644
index 000000000..6079f81de
--- /dev/null
+++ b/tests/test_control_ipc.py
@@ -0,0 +1,785 @@
+"""Contract tests for POSIX UDS and Windows loopback Controller IPC."""
+
+from __future__ import annotations
+
+import asyncio
+import errno
+import json
+import os
+import socket
+import subprocess
+import threading
+from contextlib import suppress
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+
+from config import paths
+from core import control_ipc, internal_server, session_turns
+from vibe import internal_client, model_hub_client
+
+
+def _descriptor(
+ *,
+ port: int = 45678,
+ instance_id: str = "a" * 32,
+ bearer_token: str = "A" * 43,
+) -> control_ipc.ControlIpcDescriptor:
+ return control_ipc.ControlIpcDescriptor(
+ schema_version=1,
+ transport="tcp",
+ host="127.0.0.1",
+ port=port,
+ instance_id=instance_id,
+ bearer_token=bearer_token,
+ )
+
+
+def _controller_double() -> MagicMock:
+ controller = MagicMock()
+ controller._t = lambda key, **_kwargs: key
+ controller._delivery_recovery_complete = None
+ return controller
+
+
+async def _wait_until_ready(
+ task: asyncio.Task,
+ descriptor_path: Path,
+) -> control_ipc.ControlIpcDescriptor:
+ for _ in range(300):
+ if task.done():
+ await task
+ if descriptor_path.exists() and await internal_client.health():
+ return control_ipc.load_descriptor(descriptor_path)
+ await asyncio.sleep(0.01)
+ raise AssertionError("control IPC server did not become ready")
+
+
+async def _stop_server(task: asyncio.Task) -> None:
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+
+
+def test_endpoint_selection_keeps_posix_uds_and_uses_windows_descriptor(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.delenv("VIBE_INTERNAL_DISPATCH_SOCKET", raising=False)
+
+ posix = control_ipc.resolve_client_endpoint(platform_name="posix")
+ assert posix.transport == "unix"
+ assert posix.socket_path == (tmp_path / "state" / "dispatch.sock").resolve()
+ assert posix.descriptor is None
+
+ descriptor_path = control_ipc.default_descriptor_path()
+ expected = _descriptor()
+ control_ipc.write_descriptor_atomic(descriptor_path, expected)
+ windows = control_ipc.resolve_client_endpoint(platform_name="nt")
+ assert windows.transport == "tcp"
+ assert windows.socket_path is None
+ assert windows.descriptor == expected
+ assert windows.base_url == "http://127.0.0.1:45678"
+ assert windows.headers == {"Authorization": f"Bearer {expected.bearer_token}"}
+
+
+ ("update", "message"),
+ [
+ ({"schema_version": 2}, "schema"),
+ ({"transport": "unix"}, "transport"),
+ ({"host": "0.0.0.0"}, "loopback"),
+ ({"host": "localhost"}, "loopback"),
+ ({"port": 0}, "port"),
+ ({"port": True}, "port"),
+ ({"instance_id": "short"}, "instance"),
+ ({"bearer_token": "guessable"}, "credential"),
+ ({"extra": "field"}, "fields"),
+ ],
+)
+def test_descriptor_validation_rejects_malformed_or_unsupported_data(update, message):
+ payload = _descriptor().to_dict()
+ payload.update(update)
+ with pytest.raises(control_ipc.ControlIpcDescriptorError, match=message):
+ control_ipc.validate_descriptor(payload)
+
+
+def test_descriptor_reader_rejects_malformed_json_without_echoing_contents(tmp_path):
+ target = tmp_path / "control-ipc.json"
+ marker = "must-not-appear-in-error"
+ target.write_text(f'{{"bearer_token":"{marker}"', encoding="utf-8")
+
+ with pytest.raises(control_ipc.ControlIpcDescriptorError) as exc:
+ control_ipc.load_descriptor(target)
+
+ assert marker not in str(exc.value)
+
+
+def test_descriptor_atomic_replace_preserves_previous_endpoint_on_failure(monkeypatch, tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ first = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ second = _descriptor(instance_id="2" * 32, bearer_token="C" * 43)
+ control_ipc.write_descriptor_atomic(target, first)
+
+ def _fail_replace(_source, _target):
+ raise PermissionError("replace blocked")
+
+ monkeypatch.setattr(control_ipc.os, "replace", _fail_replace)
+ with pytest.raises(PermissionError, match="replace blocked"):
+ control_ipc.write_descriptor_atomic(target, second)
+
+ assert control_ipc.load_descriptor(target) == first
+ assert not list(target.parent.glob(f".{target.name}.*.tmp"))
+ if os.name != "nt":
+ assert target.stat().st_mode & 0o077 == 0
+
+
+def test_new_windows_hosts_rotate_instance_and_bearer_credentials(tmp_path):
+ first = control_ipc.WindowsLoopbackHost(tmp_path / "control-ipc.json")
+ second = control_ipc.WindowsLoopbackHost(tmp_path / "control-ipc.json")
+
+ assert first.instance_id != second.instance_id
+ assert first.bearer_token != second.bearer_token
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_control_ipc_artifacts_have_exact_private_security(monkeypatch, tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ descriptor = _descriptor()
+ security = control_ipc._windows_security()
+ original_replace = control_ipc.os.replace
+ temporary_checked = False
+
+ def _validate_temporary_before_replace(source, destination):
+ nonlocal temporary_checked
+ security.validate_path(Path(source))
+ temporary_checked = True
+ original_replace(source, destination)
+
+ monkeypatch.setattr(control_ipc.os, "replace", _validate_temporary_before_replace)
+
+ control_ipc.write_descriptor_atomic(target, descriptor)
+
+ assert temporary_checked
+ security.validate_path(target.parent)
+ security.validate_path(target.with_name(f"{target.name}.lock"))
+ security.validate_path(target)
+ assert control_ipc.load_descriptor(target) == descriptor
+ assert not list(target.parent.glob(f".{target.name}.*.tmp"))
+
+
+def _restore_windows_inheritance(root: Path) -> None:
+ """Undo a protected DACL so pytest can still delete *root* afterwards.
+
+ Teardown only, and deliberately not ``check=True``: a cleanup failure must
+ never replace the assertion failure the test exists to report.
+ """
+
+ for arguments in (["/inheritance:e"], ["/reset", "/T", "/C", "/Q"]):
+ subprocess.run(["icacls", str(root), *arguments], capture_output=True, text=True)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_control_ipc_hardening_keeps_existing_runtime_siblings_readable(monkeypatch, tmp_path):
+ """Hardening the descriptor must not orphan files the runtime already owns.
+
+ ``SetNamedSecurityInfoW`` with ``PROTECTED_DACL`` propagates: when the DACL
+ it applies carries no inheritable ACE, the inherited ACEs are stripped from
+ every child that already exists. Children created purely by inheritance hold
+ no explicit ACE of their own, so they are left unreadable to the very
+ process that made them. This is what killed the gh-v3.1.1rc9 Windows leg --
+ the service lock, both captured stdio logs and the model-hub tree all became
+ ``[Errno 13]`` about twenty milliseconds after the Controller started.
+
+ The assertion is deliberately about a file that exists *before* the securing
+ call. A file created after it stays readable even with the defect present,
+ so testing that direction would pass on broken code.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path)
+ runtime = paths.get_runtime_dir()
+ runtime.mkdir(parents=True)
+
+ lock = runtime / "service.lock"
+ lock.write_text("4321\n", encoding="utf-8")
+ service_log = runtime / "service_stderr.log"
+ service_log.write_text("started\n", encoding="utf-8")
+ hub = runtime / "model-hub"
+ hub.mkdir()
+ (hub / "manifest.json").write_text("{}", encoding="utf-8")
+
+ descriptor = _descriptor()
+ try:
+ control_ipc.write_descriptor_atomic(paths.get_runtime_control_ipc_endpoint_path(), descriptor)
+
+ # vibe/runtime.py opens the service lock exactly this way on every lease
+ # poll, and rc9 died on this call.
+ with lock.open("a+", encoding="utf-8") as handle:
+ handle.seek(0)
+ assert handle.read() == "4321\n"
+ # The probe's own diagnostics: losing these is what made rc9 tell us
+ # less than rc8 did.
+ assert service_log.read_text(encoding="utf-8") == "started\n"
+ # rc9 failed here twice, on scandir and again on the chmod that
+ # TemporaryDirectory cleanup falls back to.
+ assert sorted(entry.name for entry in os.scandir(hub)) == ["manifest.json"]
+ assert control_ipc.load_descriptor(paths.get_runtime_control_ipc_endpoint_path()) == descriptor
+ finally:
+ _restore_windows_inheritance(tmp_path)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_control_ipc_hardening_survives_a_second_service_start(monkeypatch, tmp_path):
+ """Cover the create path and the repair path in the order a service hits them.
+
+ The first write reaches ``CreateDirectoryW``; the second reaches
+ ``secure_existing_owned_path``. Between them the launcher writes the files a
+ running service produces, so a second start must not strand them.
+ """
+
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path)
+ endpoint = paths.get_runtime_control_ipc_endpoint_path()
+ first = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ successor = _descriptor(instance_id="2" * 32, bearer_token="C" * 43)
+
+ try:
+ control_ipc.write_descriptor_atomic(endpoint, first)
+
+ lock = paths.get_runtime_dir() / "service.lock"
+ lock.write_text("8765\n", encoding="utf-8")
+
+ control_ipc.write_descriptor_atomic(endpoint, successor)
+
+ with lock.open("a+", encoding="utf-8") as handle:
+ handle.seek(0)
+ assert handle.read() == "8765\n"
+ assert control_ipc.load_descriptor(endpoint) == successor
+ finally:
+ _restore_windows_inheritance(tmp_path)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_descriptor_reader_rejects_widened_dacl_and_writer_repairs_it(tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ first = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ successor = _descriptor(instance_id="2" * 32, bearer_token="C" * 43)
+ control_ipc.write_descriptor_atomic(target, first)
+
+ subprocess.run(
+ ["icacls", str(target), "/grant", "*S-1-1-0:R"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ with pytest.raises(control_ipc.ControlIpcDescriptorError):
+ control_ipc.load_descriptor(target)
+
+ control_ipc.write_descriptor_atomic(target, successor)
+ assert control_ipc.load_descriptor(target) == successor
+ control_ipc._windows_security().validate_path(target)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_descriptor_reader_rejects_widened_lock_and_writer_repairs_it(tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ descriptor = _descriptor()
+ control_ipc.write_descriptor_atomic(target, descriptor)
+ lock_path = target.with_name(f"{target.name}.lock")
+
+ subprocess.run(
+ ["icacls", str(lock_path), "/grant", "*S-1-1-0:R"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ with pytest.raises(control_ipc.ControlIpcDescriptorError):
+ control_ipc.load_descriptor(target)
+
+ control_ipc.write_descriptor_atomic(target, descriptor)
+ assert control_ipc.load_descriptor(target) == descriptor
+ control_ipc._windows_security().validate_path(lock_path)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_descriptor_reader_rejects_widened_runtime_directory(tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ descriptor = _descriptor()
+ control_ipc.write_descriptor_atomic(target, descriptor)
+
+ subprocess.run(
+ ["icacls", str(target.parent), "/grant", "*S-1-1-0:R"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ with pytest.raises(control_ipc.ControlIpcDescriptorError):
+ control_ipc.load_descriptor(target)
+
+ control_ipc.write_descriptor_atomic(target, descriptor)
+ assert control_ipc.load_descriptor(target) == descriptor
+ control_ipc._windows_security().validate_path(target.parent)
+
+
[email protected](os.name != "nt", reason="requires native Windows ACLs")
+def test_windows_descriptor_rejects_non_owner_and_security_api_failure(
+ monkeypatch,
+ tmp_path,
+):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ descriptor = _descriptor()
+ control_ipc.write_descriptor_atomic(target, descriptor)
+ security = control_ipc._windows_security()
+
+ fd = os.open(target, os.O_RDONLY)
+ try:
+ with monkeypatch.context() as scoped:
+ scoped.setattr(security.advapi32, "EqualSid", lambda *_args: False)
+ with pytest.raises(
+ control_ipc.ControlIpcSecurityError,
+ match="owner or DACL",
+ ):
+ security.validate_file_descriptor(fd, target)
+ finally:
+ os.close(fd)
+
+ with monkeypatch.context() as scoped:
+ scoped.setattr(security.advapi32, "GetSecurityInfo", lambda *_args: 5)
+ with pytest.raises(control_ipc.ControlIpcDescriptorError):
+ control_ipc.load_descriptor(target)
+
+
+def test_descriptor_read_blocks_successor_publication_until_file_is_closed(monkeypatch, tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ first = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ successor = _descriptor(instance_id="2" * 32, bearer_token="C" * 43)
+ control_ipc.write_descriptor_atomic(target, first)
+
+ reader_open = threading.Event()
+ release_reader = threading.Event()
+ replace_started = threading.Event()
+ original_fdopen = control_ipc.os.fdopen
+ original_replace = control_ipc.os.replace
+
+ def _paused_fdopen(fd, mode, *args, **kwargs):
+ stream = original_fdopen(fd, mode, *args, **kwargs)
+ if mode == "r":
+ reader_open.set()
+ assert release_reader.wait(timeout=5)
+ return stream
+
+ def _observed_replace(source, destination):
+ replace_started.set()
+ return original_replace(source, destination)
+
+ monkeypatch.setattr(control_ipc.os, "fdopen", _paused_fdopen)
+ monkeypatch.setattr(control_ipc.os, "replace", _observed_replace)
+
+ read_result: list[control_ipc.ControlIpcDescriptor] = []
+ reader = threading.Thread(target=lambda: read_result.append(control_ipc.load_descriptor(target)))
+ publisher = threading.Thread(target=lambda: control_ipc.write_descriptor_atomic(target, successor))
+ reader.start()
+ assert reader_open.wait(timeout=5)
+ publisher.start()
+ assert not replace_started.wait(timeout=0.1)
+
+ release_reader.set()
+ reader.join(timeout=5)
+ publisher.join(timeout=5)
+
+ assert not reader.is_alive()
+ assert not publisher.is_alive()
+ assert read_result == [first]
+ assert replace_started.is_set()
+ assert control_ipc.load_descriptor(target) == successor
+
+
+def test_shutdown_cleanup_does_not_remove_successor_descriptor(tmp_path):
+ target = tmp_path / "runtime" / "control-ipc.json"
+ first = control_ipc.WindowsLoopbackHost(
+ target,
+ instance_id="1" * 32,
+ bearer_token="B" * 43,
+ )
+ successor = control_ipc.WindowsLoopbackHost(
+ target,
+ instance_id="2" * 32,
+ bearer_token="C" * 43,
+ )
+ first_bound = first.bind()
+ successor_bound = successor.bind()
+ try:
+ assert not target.exists()
+ first.publish(first_bound)
+ successor.publish(successor_bound)
+
+ first.cleanup(first_bound)
+ assert control_ipc.load_descriptor(target) == successor_bound.descriptor
+ finally:
+ first_bound.listener.close()
+ successor.cleanup(successor_bound)
+
+ assert not target.exists()
+
+
+def test_ephemeral_bind_retries_address_in_use_with_fresh_socket(tmp_path):
+ attempts: list[object] = []
+
+ class OccupiedSocket:
+ def setsockopt(self, *_args):
+ return None
+
+ def bind(self, _address):
+ raise OSError(errno.EADDRINUSE, "occupied")
+
+ def close(self):
+ return None
+
+ def _socket_factory(family, kind):
+ attempts.append(object())
+ if len(attempts) == 1:
+ return OccupiedSocket()
+ return socket.socket(family, kind)
+
+ host = control_ipc.WindowsLoopbackHost(
+ tmp_path / "control-ipc.json",
+ socket_factory=_socket_factory,
+ )
+ bound = host.bind()
+ try:
+ assert len(attempts) == 2
+ assert bound.descriptor is not None
+ assert bound.descriptor.host == "127.0.0.1"
+ assert bound.descriptor.port > 0
+ finally:
+ host.cleanup(bound)
+
+
+def test_windows_client_rejects_stale_instance_header(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(internal_client, "_platform_name", lambda: "nt")
+ descriptor = _descriptor(instance_id="1" * 32)
+ control_ipc.write_descriptor_atomic(control_ipc.default_descriptor_path(), descriptor)
+
+ app = internal_server.create_app(
+ _controller_double(),
+ instance_id="2" * 32,
+ bearer_token=descriptor.bearer_token,
+ )
+ transport = httpx.ASGITransport(app=app)
+ monkeypatch.setattr(internal_client.httpx, "AsyncHTTPTransport", lambda **_kwargs: transport)
+
+ with pytest.raises(internal_client.InternalServerUnavailable, match="stale instance"):
+ asyncio.run(internal_client.turn_state("ses_stale"))
+
+
+def test_model_hub_client_uses_windows_endpoint_auth_and_instance_validation(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(internal_client, "_platform_name", lambda: "nt")
+ descriptor = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ control_ipc.write_descriptor_atomic(control_ipc.default_descriptor_path(), descriptor)
+ requests: list[tuple[str, str]] = []
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ payload = json.loads(request.content)
+ requests.append((payload["operation"], request.headers["authorization"]))
+ response_instance = "2" * 32 if payload["operation"] == "stale" else descriptor.instance_id
+ return httpx.Response(
+ 200,
+ json={"ok": True, "result": payload["operation"]},
+ headers={control_ipc.CONTROL_IPC_INSTANCE_HEADER: response_instance},
+ )
+
+ transport = httpx.MockTransport(_handler)
+ monkeypatch.setattr(internal_client.httpx, "HTTPTransport", lambda **_kwargs: transport)
+ monkeypatch.setattr(internal_client.httpx, "AsyncHTTPTransport", lambda **_kwargs: transport)
+
+ assert model_hub_client._rpc_sync("sync") == "sync"
+ assert asyncio.run(model_hub_client._rpc("async")) == "async"
+ with pytest.raises(model_hub_client.ModelHubError) as exc_info:
+ model_hub_client._rpc_sync("stale")
+
+ assert exc_info.value.code == "engine_down"
+ assert requests == [
+ ("sync", f"Bearer {descriptor.bearer_token}"),
+ ("async", f"Bearer {descriptor.bearer_token}"),
+ ("stale", f"Bearer {descriptor.bearer_token}"),
+ ]
+
+
+def test_archive_client_uses_windows_endpoint_auth_and_instance_validation(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(internal_client, "_platform_name", lambda: "nt")
+ descriptor = _descriptor(instance_id="3" * 32, bearer_token="C" * 43)
+ control_ipc.write_descriptor_atomic(control_ipc.default_descriptor_path(), descriptor)
+ requests: list[tuple[str, str, dict]] = []
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ payload = json.loads(request.content)
+ requests.append((request.url.path, request.headers["authorization"], payload))
+ response_instance = "4" * 32 if payload["session_id"] == "ses_stale" else descriptor.instance_id
+ return httpx.Response(
+ 200,
+ json={"ok": True},
+ headers={control_ipc.CONTROL_IPC_INSTANCE_HEADER: response_instance},
+ )
+
+ transport = httpx.MockTransport(_handler)
+ monkeypatch.setattr(internal_client.httpx, "AsyncHTTPTransport", lambda **_kwargs: transport)
+
+ assert asyncio.run(internal_client.archive_session("ses_ok")) == {
+ "status_code": 200,
+ "body": {"ok": True},
+ }
+ with pytest.raises(internal_client.InternalServerUnavailable, match="stale instance"):
+ asyncio.run(internal_client.archive_session("ses_stale"))
+ assert requests == [
+ ("/internal/sessions/archive", f"Bearer {descriptor.bearer_token}", {"session_id": "ses_ok"}),
+ ("/internal/sessions/archive", f"Bearer {descriptor.bearer_token}", {"session_id": "ses_stale"}),
+ ]
+
+
+def test_windows_unhandled_500_response_carries_instance_header():
+ descriptor = _descriptor(instance_id="1" * 32, bearer_token="B" * 43)
+ app = internal_server.create_app(
+ _controller_double(),
+ instance_id=descriptor.instance_id,
+ bearer_token=descriptor.bearer_token,
+ )
+
+ @app.get("/internal/test-unhandled-error")
+ async def _unhandled_error():
+ raise RuntimeError("test failure")
+
+ async def _run():
+ transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ headers={"Authorization": f"Bearer {descriptor.bearer_token}"},
+ ) as client:
+ return await client.get("/internal/test-unhandled-error")
+
+ response = asyncio.run(_run())
+
+ assert response.status_code == 500
+ assert response.text == "Internal Server Error"
+ assert response.headers[control_ipc.CONTROL_IPC_INSTANCE_HEADER] == descriptor.instance_id
+ internal_client._validate_response(
+ response,
+ control_ipc.ControlIpcClientEndpoint(
+ transport="tcp",
+ descriptor=descriptor,
+ ),
+ )
+
+
+def test_real_windows_loopback_auth_and_non_ascii_event_sse(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(internal_client, "_platform_name", lambda: "nt")
+ monkeypatch.setattr(
+ session_turns.SessionTurnManager,
+ "recover_persisted_agent_run_queue",
+ lambda _self: asyncio.sleep(0, result=[]),
+ )
+ async def _run():
+ descriptor_path = control_ipc.default_descriptor_path()
+ task = asyncio.create_task(
+ internal_server.serve(
+ _controller_double(),
+ platform_name="nt",
+ descriptor_path=descriptor_path,
+ )
+ )
+ try:
+ descriptor = await _wait_until_ready(task, descriptor_path)
+ async with httpx.AsyncClient(base_url=f"http://{descriptor.host}:{descriptor.port}") as client:
+ missing = await client.get("/internal/health")
+ incorrect = await client.get(
+ "/internal/health",
+ headers={"Authorization": "Bearer definitely-wrong"},
+ )
+ assert missing.status_code == 401
+ assert incorrect.status_code == 401
+ assert descriptor.bearer_token not in missing.text
+ assert descriptor.bearer_token not in incorrect.text
+
+ stream = internal_client.stream_events()
+ try:
+ assert await anext(stream) == ("connected", {})
+ next_event = asyncio.create_task(anext(stream))
+ published = await internal_client.publish_event(
+ "queue.updated",
+ {"text": "请处理 café 文件:你好,Windows ✓"},
+ )
+ assert published == {"ok": True}
+ assert await asyncio.wait_for(next_event, timeout=2.0) == (
+ "queue.updated",
+ {"text": "请处理 café 文件:你好,Windows ✓"},
+ )
+ finally:
+ await stream.aclose()
+ finally:
+ await _stop_server(task)
+ assert not descriptor_path.exists()
+
+ asyncio.run(_run())
+
+
+def test_sse_reconnect_loads_successor_descriptor(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(internal_client, "_platform_name", lambda: "nt")
+ monkeypatch.setattr(
+ session_turns.SessionTurnManager,
+ "recover_persisted_agent_run_queue",
+ lambda _self: asyncio.sleep(0, result=[]),
+ )
+
+ async def _first_event():
+ stream = internal_client.stream_events()
+ try:
+ return await anext(stream)
+ finally:
+ await stream.aclose()
+
+ async def _run():
+ descriptor_path = control_ipc.default_descriptor_path()
+ first_task = asyncio.create_task(
+ internal_server.serve(
+ _controller_double(),
+ platform_name="nt",
+ descriptor_path=descriptor_path,
+ )
+ )
+ first = await _wait_until_ready(first_task, descriptor_path)
+ assert await _first_event() == ("connected", {})
+
+ successor_task = asyncio.create_task(
+ internal_server.serve(
+ _controller_double(),
+ platform_name="nt",
+ descriptor_path=descriptor_path,
+ )
+ )
+ try:
+ successor = await _wait_until_ready(successor_task, descriptor_path)
+ assert successor.instance_id != first.instance_id
+ assert successor.bearer_token != first.bearer_token
+ assert await _first_event() == ("connected", {})
+ finally:
+ await _stop_server(successor_task)
+ await _stop_server(first_task)
+
+ asyncio.run(_run())
+
+
+class _FakeSid:
+ """A SID pointer stand-in that compares by the SDDL text that produced it."""
+
+ def __init__(self, value: str | None = None) -> None:
+ self.value = value
+
+ def __bool__(self) -> bool:
+ return self.value is not None
+
+
+class _FakeCtypes:
+ @staticmethod
+ def byref(cell):
+ return cell
+
+
+class _FakeWinTypes:
+ LPVOID = _FakeSid
+ BOOL = _FakeSid
+ DWORD = _FakeSid
+
+
+def _windows_security_stub(*, user_sid: str, owner_sid: str):
+ """Drive the real owner-acceptance logic without Windows ctypes bindings.
+
+ ``_WindowsSecurity.__init__`` loads ``advapi32``/``kernel32``, so it cannot
+ run off Windows. Every method under test reads only instance attributes, so
+ a bypassed constructor with fake bindings exercises the real decision.
+ """
+
+ security = object.__new__(control_ipc._WindowsSecurity)
+ security.ctypes = _FakeCtypes
+ security.wintypes = _FakeWinTypes
+ security.current_user_sid = user_sid
+ security.current_owner_sid = owner_sid
+ security.sddl = f"O:{user_sid}D:P(A;;FA;;;{user_sid})(A;;FA;;;SY)"
+
+ def _convert(sddl, _revision, descriptor_ref, _size_ref):
+ descriptor_ref.value = sddl
+ return 1
+
+ def _descriptor_owner(descriptor, owner_ref, _defaulted_ref):
+ owner_ref.value = descriptor.value.split("D:", 1)[0][len("O:") :]
+ return 1
+
+ security.advapi32 = MagicMock(
+ ConvertStringSecurityDescriptorToSecurityDescriptorW=_convert,
+ GetSecurityDescriptorOwner=_descriptor_owner,
+ EqualSid=lambda left, right: left.value == right.value,
+ )
+ security.kernel32 = MagicMock(LocalFree=lambda *_args: None)
+ return security
+
+
+_USER_SID = "S-1-5-21-1111-2222-3333-1001"
+_ADMINISTRATORS_SID = "S-1-5-32-544"
+_STRANGER_SID = "S-1-5-21-9999-8888-7777-500"
+
+
+def test_elevated_token_default_owner_is_accepted_as_self():
+ """An elevated token stamps BUILTIN\\Administrators on what it creates."""
+
+ security = _windows_security_stub(user_sid=_USER_SID, owner_sid=_ADMINISTRATORS_SID)
+
+ assert security._owner_is_self(_FakeSid(_USER_SID)) is True
+ assert security._owner_is_self(_FakeSid(_ADMINISTRATORS_SID)) is True
+ assert security._owner_is_self(_FakeSid(_STRANGER_SID)) is False
+ assert security._owner_is_self(_FakeSid(None)) is False
+
+
+def test_administrators_is_not_trusted_when_it_is_not_this_token_owner():
+ """Acceptance follows the process token, not a hardcoded well-known SID."""
+
+ security = _windows_security_stub(user_sid=_USER_SID, owner_sid=_USER_SID)
+
+ assert security._self_owner_sddls() == (security.sddl,)
+ assert security._owner_is_self(_FakeSid(_USER_SID)) is True
+ assert security._owner_is_self(_FakeSid(_ADMINISTRATORS_SID)) is False
+
+
+def test_relaxed_owner_still_requires_the_protected_private_dacl():
+ """Only the owner rule moved; the DACL contract is unchanged."""
+
+ security = _windows_security_stub(user_sid=_USER_SID, owner_sid=_ADMINISTRATORS_SID)
+ security._descriptor_dacl = lambda _descriptor: "private-dacl"
+ security._acl_signature = lambda acl: (str(acl).encode(),)
+ control = control_ipc._WindowsSecurity._SE_DACL_PRESENT | control_ipc._WindowsSecurity._SE_DACL_PROTECTED
+
+ security._descriptor_control = lambda _descriptor: control
+ security._validate_security_descriptor(
+ _FakeSid(_ADMINISTRATORS_SID), "private-dacl", object(), Path("runtime")
+ )
+
+ for broken_control, dacl in (
+ (control_ipc._WindowsSecurity._SE_DACL_PRESENT, "private-dacl"),
+ (control, "inherited-dacl"),
+ ):
+ security._descriptor_control = lambda _descriptor, value=broken_control: value
+ with pytest.raises(control_ipc.ControlIpcSecurityError, match="owner or DACL"):
+ security._validate_security_descriptor(
+ _FakeSid(_ADMINISTRATORS_SID), dacl, object(), Path("runtime")
+ )
diff --git a/tests/test_dependency_inspection.py b/tests/test_dependency_inspection.py
index 0c9523ab8..9c4ead3e6 100644
--- a/tests/test_dependency_inspection.py
+++ b/tests/test_dependency_inspection.py
@@ -73,7 +73,11 @@ def test_selective_checks_preserve_complete_rows_and_only_probe_their_owners(pro
result = api.dependencies_status(dependency_ids=requested)
- assert result == {"ok": True, "deps": [row for row in complete["deps"] if row["id"] in requested]}
+ assert result["ok"] is True
+ assert result["deps"] == [row for row in complete["deps"] if row["id"] in requested]
+ assert result["reconciling"] is False
+ assert result["reconciling_dependencies"] == []
+ assert set(result) == {"ok", "deps", "reconciling", "reconciling_dependencies"}
assert [group for group, _ in probes] == [group for group in GROUPS if set(group).intersection(requested)]
diff --git a/tests/test_desktop_backends.py b/tests/test_desktop_backends.py
new file mode 100644
index 000000000..381b3a502
--- /dev/null
+++ b/tests/test_desktop_backends.py
@@ -0,0 +1,317 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from vibe import desktop_backends
+
+
+def _desktop_env(tmp_path: Path) -> dict[str, str]:
+ runtime = tmp_path / "runtime" / "1.0.0" / "digest"
+ node = runtime / "tools" / ("node.exe" if os.name == "nt" else "node")
+ npm_cli = runtime / "tools" / "npm" / "bin" / "npm-cli.js"
+ node.parent.mkdir(parents=True)
+ npm_cli.parent.mkdir(parents=True)
+ node.write_bytes(b"MZ\0\0" if os.name == "nt" else b"\x7fELF")
+ node.chmod(0o755)
+ npm_cli.write_text("// npm\n", encoding="utf-8")
+ return {
+ "AVIBE_DESKTOP_RUNTIME_ROOT": str(runtime),
+ "VIBE_SHOW_RUNTIME_NODE_BIN": str(node),
+ "AVIBE_DESKTOP_NPM_CLI": str(npm_cli),
+ "AVIBE_DESKTOP_BACKENDS_ROOT": str(tmp_path / "backends"),
+ "PATH": str(tmp_path / "external-bin"),
+ "NPM_CONFIG_REGISTRY": "https://attacker.invalid/",
+ "npm_config_prefix": str(tmp_path / "system-prefix"),
+ "NODE_OPTIONS": "--require attacker.js",
+ }
+
+
+def _write_native(path: Path) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"MZ\0\0" if os.name == "nt" else b"\x7fELF")
+ path.chmod(0o755)
+
+
+def _fake_npm_install(
+ backend: str,
+ *,
+ codex_layout: str = "hoisted",
+ calls: list[tuple[list[str], dict[str, str], Path]] | None = None,
+):
+ spec = desktop_backends.BACKEND_SPECS[backend]
+
+ def fake_run(command, *, cwd, env, timeout_seconds):
+ staging = Path(command[command.index("--prefix") + 1])
+ package_dir = staging / "node_modules" / Path(*spec.package_path)
+ package_dir.mkdir(parents=True)
+ (package_dir / "package.json").write_text(
+ json.dumps({"name": spec.package, "version": "1.2.3"}),
+ encoding="utf-8",
+ )
+ if backend == "codex":
+ os_name, arch = desktop_backends._native_target()
+ target_name = f"codex-{os_name}-{arch}"
+ if codex_layout == "nested":
+ target_root = package_dir / "node_modules" / "@openai" / target_name
+ else:
+ target_root = staging / "node_modules" / "@openai" / target_name
+ executable = target_root / "vendor" / "target-triple" / "bin" / (
+ "codex.exe" if os_name == "win32" else "codex"
+ )
+ elif backend == "claude":
+ os_name, arch = desktop_backends._native_target()
+ target_root = staging / "node_modules" / "@anthropic-ai" / f"claude-code-{os_name}-{arch}"
+ executable = target_root / ("claude.exe" if os_name == "win32" else "claude")
+ else:
+ os_name, arch = desktop_backends._native_target()
+ target_os = "windows" if os_name == "win32" else os_name
+ target_root = staging / "node_modules" / f"opencode-{target_os}-{arch}"
+ executable = target_root / "bin" / ("opencode.exe" if os_name == "win32" else "opencode")
+ _write_native(executable)
+ if backend == "codex":
+ runtime_root = executable.parent.parent
+ (runtime_root / "codex-package.json").write_text("{}", encoding="utf-8")
+ helpers = [
+ runtime_root
+ / "bin"
+ / ("codex-code-mode-host.exe" if os_name == "win32" else "codex-code-mode-host"),
+ runtime_root / "codex-path" / ("rg.exe" if os_name == "win32" else "rg"),
+ ]
+ if os_name == "win32":
+ helpers.extend(
+ [
+ runtime_root / "codex-resources" / "codex-command-runner.exe",
+ runtime_root / "codex-resources" / "codex-windows-sandbox-setup.exe",
+ ]
+ )
+ else:
+ helpers.append(runtime_root / "codex-resources" / "zsh" / "bin" / "zsh")
+ if os_name == "linux":
+ helpers.append(runtime_root / "codex-resources" / "bwrap")
+ for helper in helpers:
+ _write_native(helper)
+ if calls is not None:
+ calls.append((command, dict(env), cwd))
+ return subprocess.CompletedProcess(command, 0, "installed", "")
+
+ return fake_run
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_install_publishes_verified_native_backend(monkeypatch, tmp_path, backend):
+ env = _desktop_env(tmp_path)
+ env["CODEX_HOME"] = str(tmp_path / "custom-codex-home")
+ env["OPENAI_API_KEY"] = "fixture-key"
+ calls: list[tuple[list[str], dict[str, str], Path]] = []
+ monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install(backend, calls=calls))
+ monkeypatch.setattr(
+ desktop_backends.subprocess,
+ "run",
+ lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, f"{backend} 1.2.3", ""),
+ )
+ activated: list[str] = []
+
+ result = desktop_backends.install_desktop_backend(
+ backend,
+ base_env=env,
+ activate=lambda path: activated.append(path),
+ )
+
+ assert result.version == "1.2.3"
+ assert result.path == activated[0]
+ assert desktop_backends.resolve_published_desktop_backend(backend, env) == result.path
+ descriptor = json.loads((Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / backend / "current.json").read_text())
+ assert descriptor["package"] == desktop_backends.BACKEND_SPECS[backend].package
+ assert not Path(descriptor["executable"]).is_absolute()
+ assert ".staging-" not in descriptor["executable"]
+
+ command, install_env, cwd = calls[0]
+ assert command[:2] == [env["VIBE_SHOW_RUNTIME_NODE_BIN"], env["AVIBE_DESKTOP_NPM_CLI"]]
+ assert command[-1] == desktop_backends.BACKEND_SPECS[backend].package
+ assert "--ignore-scripts" in command
+ assert f"--registry={desktop_backends.NPM_REGISTRY}" in command
+ assert cwd == Path(install_env["NPM_CONFIG_PREFIX"])
+ assert install_env["NPM_CONFIG_REGISTRY"] == desktop_backends.NPM_REGISTRY
+ assert install_env["NPM_CONFIG_PREFIX"] == command[command.index("--prefix") + 1]
+ assert install_env["NPM_CONFIG_CACHE"] == str(cwd / ".npm-cache")
+ assert install_env["NPM_CONFIG_USERCONFIG"].startswith(install_env["NPM_CONFIG_PREFIX"])
+ assert "npm_config_prefix" not in install_env
+ assert "NODE_OPTIONS" not in install_env
+ assert "OPENAI_API_KEY" not in install_env
+ if backend == "codex":
+ runtime_env = desktop_backends.desktop_backend_subprocess_environment(
+ "codex",
+ result.path,
+ env,
+ )
+ assert runtime_env is not None
+ assert runtime_env["CODEX_HOME"] == env["CODEX_HOME"]
+ assert runtime_env["OPENAI_API_KEY"] == env["OPENAI_API_KEY"]
+ expected_helper_dir = Path(result.path).parent.parent / "codex-path"
+ assert Path(runtime_env["PATH"].split(os.pathsep)[0]) == expected_helper_dir
+
+
+def test_codex_accepts_nested_target_package(monkeypatch, tmp_path):
+ env = _desktop_env(tmp_path)
+ monkeypatch.setattr(
+ desktop_backends,
+ "_run_command",
+ _fake_npm_install("codex", codex_layout="nested"),
+ )
+ monkeypatch.setattr(
+ desktop_backends.subprocess,
+ "run",
+ lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "codex-cli 1.2.3", ""),
+ )
+
+ result = desktop_backends.install_desktop_backend("codex", base_env=env)
+
+ assert Path(result.path).name == ("codex.exe" if os.name == "nt" else "codex")
+
+
+def test_codex_rejects_an_incomplete_runtime_before_publication(monkeypatch, tmp_path):
+ env = _desktop_env(tmp_path)
+ complete_install = _fake_npm_install("codex")
+
+ def install_without_ripgrep(command, **kwargs):
+ completed = complete_install(command, **kwargs)
+ staging = Path(command[command.index("--prefix") + 1])
+ ripgrep_name = "rg.exe" if os.name == "nt" else "rg"
+ next(
+ staging.glob(
+ f"node_modules/@openai/codex-*/vendor/*/codex-path/{ripgrep_name}"
+ )
+ ).unlink()
+ return completed
+
+ monkeypatch.setattr(desktop_backends, "_run_command", install_without_ripgrep)
+
+ with pytest.raises(desktop_backends.DesktopBackendError) as raised:
+ desktop_backends.install_desktop_backend("codex", base_env=env)
+
+ assert raised.value.code == "incomplete_backend_runtime"
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "codex"
+ assert not (backend_root / "current.json").exists()
+ assert list(backend_root.glob("releases/*")) == []
+
+
+def test_failed_install_keeps_current_descriptor_and_removes_staging(monkeypatch, tmp_path):
+ env = _desktop_env(tmp_path)
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude"
+ backend_root.mkdir(parents=True)
+ previous = b'{"existing":true}\n'
+ (backend_root / "current.json").write_bytes(previous)
+ monkeypatch.setattr(
+ desktop_backends,
+ "_run_command",
+ lambda command, **_kwargs: subprocess.CompletedProcess(command, 1, "", "npm failed"),
+ )
+
+ with pytest.raises(desktop_backends.DesktopBackendError) as raised:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+
+ assert raised.value.code == "npm_install_failed"
+ assert (backend_root / "current.json").read_bytes() == previous
+ assert list(backend_root.glob(".staging-*")) == []
+ assert list(backend_root.glob("releases/*")) == []
+
+
+def test_descriptor_publication_failure_does_not_activate_config(monkeypatch, tmp_path):
+ env = _desktop_env(tmp_path)
+ monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install("opencode"))
+ monkeypatch.setattr(
+ desktop_backends.subprocess,
+ "run",
+ lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "opencode 1.2.3", ""),
+ )
+ state = {"path": "opencode"}
+
+ def activate(path):
+ state["path"] = path
+
+ monkeypatch.setattr(
+ desktop_backends,
+ "_write_current_descriptor",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("disk full")),
+ )
+
+ with pytest.raises(desktop_backends.DesktopBackendError):
+ desktop_backends.install_desktop_backend("opencode", base_env=env, activate=activate)
+
+ assert state["path"] == "opencode"
+ assert list((Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "opencode" / "releases").iterdir()) == []
+
+
+def test_descriptor_is_published_before_activation_and_restored_on_failure(monkeypatch, tmp_path):
+ env = _desktop_env(tmp_path)
+ root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"])
+ backend_root = root / "claude"
+ old_executable = backend_root / "releases" / "old" / "claude"
+ _write_native(old_executable)
+ old_descriptor = {
+ "schema_version": desktop_backends.CURRENT_DESCRIPTOR_SCHEMA_VERSION,
+ "backend": "claude",
+ "package": "@anthropic-ai/claude-code",
+ "version": "1.0.0",
+ "executable": old_executable.relative_to(root).as_posix(),
+ }
+ backend_root.mkdir(parents=True, exist_ok=True)
+ (backend_root / "current.json").write_text(json.dumps(old_descriptor), encoding="utf-8")
+ monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install("claude"))
+ monkeypatch.setattr(
+ desktop_backends.subprocess,
+ "run",
+ lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "claude 1.2.3", ""),
+ )
+
+ def fail_activation(new_path):
+ assert desktop_backends.resolve_published_desktop_backend("claude", env) == new_path
+ raise OSError("config write failed")
+
+ with pytest.raises(desktop_backends.DesktopBackendError):
+ desktop_backends.install_desktop_backend("claude", base_env=env, activate=fail_activation)
+
+ assert desktop_backends.resolve_published_desktop_backend("claude", env) == str(old_executable)
+ assert [path.name for path in (backend_root / "releases").iterdir()] == ["old"]
+
+
+def test_resolver_rejects_descriptor_traversal_and_non_native_file(tmp_path):
+ env = _desktop_env(tmp_path)
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "codex"
+ backend_root.mkdir(parents=True)
+ outside = tmp_path / "outside" / "codex"
+ outside.parent.mkdir()
+ outside.write_text("#!/bin/sh\n", encoding="utf-8")
+ outside.chmod(0o755)
+
+ base = {
+ "schema_version": desktop_backends.CURRENT_DESCRIPTOR_SCHEMA_VERSION,
+ "backend": "codex",
+ "package": "@openai/codex",
+ "version": "1.2.3",
+ }
+ (backend_root / "current.json").write_text(
+ json.dumps({**base, "executable": "../outside/codex"}),
+ encoding="utf-8",
+ )
+ assert desktop_backends.resolve_published_desktop_backend("codex", env) is None
+
+ local = backend_root / "releases" / "one" / "codex"
+ local.parent.mkdir(parents=True)
+ local.write_text("#!/bin/sh\n", encoding="utf-8")
+ local.chmod(0o755)
+ (backend_root / "current.json").write_text(
+ json.dumps(
+ {
+ **base,
+ "executable": local.relative_to(Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"])).as_posix(),
+ }
+ ),
+ encoding="utf-8",
+ )
+ assert desktop_backends.resolve_published_desktop_backend("codex", env) is None
diff --git a/tests/test_desktop_release.py b/tests/test_desktop_release.py
new file mode 100644
index 000000000..00087b3d5
--- /dev/null
+++ b/tests/test_desktop_release.py
@@ -0,0 +1,370 @@
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+
+import pytest
+import yaml
+
+from scripts import desktop_release as release
+from tests.test_desktop_runtime_bundle_builder import builder
+
+
+ROOT = Path(__file__).resolve().parents[1]
+TAG = "gh-v3.1.2rc1"
+VERSION = "3.1.2-rc.1"
+SOURCE = "a" * 40
+
+
+def workflow(name):
+ return yaml.safe_load((ROOT / ".github/workflows" / name).read_text())
+
+
+def step(name, job="package", file="desktop-package.yml"):
+ return next(item for item in workflow(file)["jobs"][job]["steps"] if item.get("name") == name)
+
+
+def assemble_assets(root, source=SOURCE):
+ """Use the real Runtime archive writer and desktop producer, then merge downloads."""
+ directory = root / "desktop-dist"
+ directory.mkdir()
+ for target, (system, arch, suffix) in release.TARGETS.items():
+ work = root / target
+ payload = work / "payload"
+ payload.mkdir(parents=True)
+ (payload / "说明.txt").write_text("Runtime fixture 中文", encoding="utf-8")
+ runtime = work / "runtime"
+ runtime.mkdir()
+ archive = runtime / "runtime.zip"
+ size, count, tree = builder.create_runtime_zip(payload, archive)
+ manifest = {
+ "schema_version": 2, "runtime_version": "3.1.2rc1", "os": system, "arch": arch,
+ "archive": archive.name, "archive_sha256": release.digest(archive),
+ "archive_size": archive.stat().st_size, "unpacked_size": size,
+ "entry_count": count, "tree_sha256": tree,
+ }
+ (runtime / "runtime-manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
+ installer = work / ("native installer" + suffix)
+ installer.write_bytes(f"installer bytes for {target}".encode())
+ output = work / "output"
+ release.record(version=VERSION, target=target, tag=TAG, source_sha=source,
+ installer=installer, runtime=runtime, output=output,
+ signing=release.signature(target).strip())
+ for path in output.iterdir():
+ shutil.copyfile(path, directory / path.name)
+ return directory
+
+
+def git(directory, *args):
+ return subprocess.check_output(["git", "-C", str(directory), *args], text=True).strip()
+
+
[email protected]("annotated", [False, True])
+def test_real_tag_resolution_and_prepare_pin_runtime_before_build(tmp_path, monkeypatch, annotated):
+ git(tmp_path, "init", "-q")
+ git(tmp_path, "-c", "user.name=Test", "-c", "[email protected]",
+ "commit", "--allow-empty", "-qm", "tagged source")
+ source = git(tmp_path, "rev-parse", "HEAD")
+ if annotated:
+ git(tmp_path, "-c", "user.name=Test", "-c", "[email protected]",
+ "tag", "-a", TAG, "-m", "test only")
+ else:
+ git(tmp_path, "tag", TAG)
+ monkeypatch.chdir(tmp_path)
+ assert release.resolve(TAG) == {"tag": TAG, "source_sha": source, "version": VERSION,
+ "package_version": "3.1.2rc1"}
+ config, environment = tmp_path / "config.json", tmp_path / "env"
+ release.prepare(VERSION, TAG, source, config, environment)
+ assert environment.read_text().splitlines() == [
+ "SETUPTOOLS_SCM_PRETEND_VERSION=3.1.2rc1",
+ "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=3.1.2rc1",
+ ]
+ override = json.loads(config.read_text())
+ assert override["version"] == VERSION
+ assert override["bundle"]["macOS"]["signingIdentity"] == "-"
+ assert override["bundle"]["windows"] == {"certificateThumbprint": None, "signCommand": None}
+ git(tmp_path, "-c", "user.name=Test", "-c", "[email protected]",
+ "commit", "--allow-empty", "-qm", "different caller branch")
+ with pytest.raises(ValueError, match="checkout/version"):
+ release.prepare(VERSION, TAG, source, config, environment)
+ with pytest.raises(ValueError, match="source SHA"):
+ release.resolve(TAG, "b" * 40)
+
+
[email protected]("tag", ["gh-v3.1.2", "gh-v3.1.2-rc1", "gh-v03.1.2rc1", "gh-v3.1.2rc01",
+ "v3.1.2rc1", "gh-vnext", "gh-v3.1.2rc1\n", "--help", ""])
+def test_malformed_test_tags_fail_before_git_or_publication(tag, monkeypatch):
+ monkeypatch.setattr(release, "git_output", lambda *_: pytest.fail("invalid tag reached git"))
+ with pytest.raises(ValueError, match="canonical"):
+ release.resolve(tag)
+
+
+def test_manual_prepare_retains_optional_signing_and_native_version(tmp_path):
+ config, environment = tmp_path / "config.json", tmp_path / "env"
+ release.prepare("2.0.0-beta.1+build.4", "", "", config, environment)
+ assert json.loads(config.read_text()) == {"version": "2.0.0-beta.1+build.4"}
+ assert not environment.exists()
+ with pytest.raises(ValueError, match="SemVer"):
+ release.prepare("2.0.0-01", "", "", config, environment)
+
+
+def test_real_assembled_assets_pass_the_release_consumer(tmp_path):
+ directory = assemble_assets(tmp_path)
+ paths = release.verify(directory, TAG, SOURCE)
+ assert len(paths) == len({path.name for path in paths}) == 15
+ assert {path.suffix for path in paths} >= {".dmg", ".exe"}
+
+
[email protected]("target", release.TARGETS)
+def test_workflow_record_command_feeds_the_release_consumer(tmp_path, target):
+ directory = assemble_assets(tmp_path)
+ work = tmp_path / target
+ scripts = work / "scripts"
+ scripts.mkdir()
+ for name in ("desktop_release.py", "release_package_version.py", "github_release.py"):
+ shutil.copyfile(ROOT / "scripts" / name, scripts / name)
+ runtime = work / "desktop/src-tauri/resources/runtime"
+ runtime.parent.mkdir(parents=True)
+ shutil.copytree(work / "runtime", runtime)
+ matrix = next(item for item in workflow("desktop-package.yml")["jobs"]["package"]["strategy"]["matrix"]["include"]
+ if item["target"] == target)
+ installer = work / matrix["artifact_glob"].replace("*", "Avibe_fixture")
+ installer.parent.mkdir(parents=True)
+ shutil.copyfile(work / ("native installer" + release.TARGETS[target][2]), installer)
+ binaries = work / "bin"
+ binaries.mkdir()
+ (binaries / "python").symlink_to(sys.executable)
+ (binaries / "git").write_text(f"#!/bin/sh\nprintf '%s\\n' '{SOURCE}'\n")
+ (binaries / "git").chmod(0o755)
+ command = step("Record artifact hashes")["run"].replace("${{ matrix.artifact_glob }}", matrix["artifact_glob"])
+ result = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", command], cwd=work,
+ env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "AVIBE_DESKTOP_VERSION": VERSION, "RELEASE_TAG": TAG, "TARGET": target,
+ "RUNNER_OS": "macOS" if "darwin" in target else "Windows",
+ "signature_state": "app-adhoc"},
+ capture_output=True, text=True, timeout=10)
+ assert result.returncode == 0, result.stderr
+ for path in (work / "desktop-package").iterdir():
+ shutil.copyfile(path, directory / path.name)
+ assert len(release.verify(directory, TAG, SOURCE)) == 15
+
+
[email protected]("mutation", ["missing-target", "extra-file", "installer-bytes", "runtime-version",
+ "runtime-target", "source-sha", "signature", "missing-hashes"])
+def test_consumer_rejects_incomplete_or_mismatched_release(tmp_path, mutation):
+ directory = assemble_assets(tmp_path)
+ target = next(iter(release.TARGETS))
+ names = release.asset_names(VERSION, target)
+ if mutation == "missing-target":
+ for name in names:
+ (directory / name).unlink()
+ elif mutation == "extra-file":
+ (directory / "SIGNATURE").write_text("ambiguous metadata")
+ elif mutation == "missing-hashes":
+ (directory / names[4]).unlink()
+ elif mutation == "installer-bytes":
+ (directory / names[0]).write_bytes(b"changed installer")
+ else:
+ if mutation == "signature":
+ (directory / names[3]).write_text("app-identity-signed\n")
+ else:
+ name = names[2] if mutation == "source-sha" else names[1]
+ path = directory / name
+ data = json.loads(path.read_text())
+ data[{"source-sha": "source_sha", "runtime-version": "runtime_version",
+ "runtime-target": "arch"}[mutation]] = "incorrect"
+ path.write_text(json.dumps(data))
+ # Matching hashes alone cannot substitute for the semantic contract.
+ (directory / names[4]).write_text("".join(
+ f"{release.digest(directory / name)} {name}\n" for name in sorted(names[:4])
+ ))
+ with pytest.raises(ValueError):
+ release.verify(directory, TAG, SOURCE)
+
+
[email protected]("mutation", ["archive", "version", "signing"])
+def test_producer_rejects_incorrect_runtime_or_signing(tmp_path, mutation):
+ assemble_assets(tmp_path)
+ target = next(iter(release.TARGETS))
+ work = tmp_path / target
+ if mutation == "archive":
+ (work / "runtime/runtime.zip").write_bytes(b"tampered archive")
+ if mutation == "version":
+ path = work / "runtime/runtime-manifest.json"
+ data = json.loads(path.read_text())
+ data["runtime_version"] = "0.1.0"
+ path.write_text(json.dumps(data))
+ with pytest.raises(ValueError):
+ release.record(version=VERSION, target=target, tag=TAG, source_sha=SOURCE,
+ installer=work / "native installer.dmg", runtime=work / "runtime",
+ output=work / "rejected", signing="identity" if mutation == "signing"
+ else release.signature(target).strip())
+ assert not (work / "rejected").exists()
+
+
+def test_workflow_preserves_manual_path_and_isolates_test_signing():
+ package = workflow("desktop-package.yml")
+ triggers = package.get("on", package.get(True))
+ assert set(triggers) == {"workflow_dispatch", "workflow_call"}
+ assert "secrets" not in triggers["workflow_call"]
+ jobs = workflow("release_ai.yml")["jobs"]
+ caller = jobs["desktop-packages"]
+ assert caller["uses"] == "./.github/workflows/desktop-package.yml"
+ assert "secrets" not in caller
+ assert caller["with"]["source_sha"] == "${{ needs.resolve-desktop-release.outputs.source_sha }}"
+ build = package["jobs"]["package"]
+ steps = build["steps"]
+ assert steps[0]["with"]["ref"] == "${{ inputs.source_sha || github.sha }}"
+ assert {entry["target"] for entry in build["strategy"]["matrix"]["include"]} == set(release.TARGETS)
+ assert steps.index(step("Prepare package version")) < steps.index(step("Build verified private Runtime"))
+ credentials = step("Export Apple signing credentials when configured")
+ assert credentials["if"] == "runner.os == 'macOS' && inputs.release_tag == ''"
+ assert "codesign --force --deep --sign -" in step("Verify macOS app signature matches the signing path")["run"]
+ assert "NotSigned" in step("Verify unsigned Windows installer")["run"]
+ assert steps[-1]["uses"] == "actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f"
+
+
[email protected]("configured", [False, True])
+def test_manual_apple_export_still_consumes_complete_optional_credentials(tmp_path, configured):
+ export = step("Export Apple signing credentials when configured")
+ env = {**os.environ, **{key: "" for key in export["env"]},
+ "GITHUB_ENV": str(tmp_path / "env"), "TMPDIR": str(tmp_path)}
+ if configured:
+ env.update({key: "fixture-value" for key in export["env"]})
+ result = subprocess.run(["bash", "-e", "-c", export["run"]], env=env, capture_output=True, text=True)
+ assert result.returncode == 0, result.stderr
+ exported = (tmp_path / "env").read_text()
+ assert f"apple_signing={'enabled' if configured else 'absent'}" in exported
+ if configured:
+ key = next(line.split("=", 1)[1] for line in exported.splitlines() if line.startswith("APPLE_API_KEY_PATH="))
+ assert Path(key).read_text() == "fixture-value"
+
+
[email protected]("state", ["new", "draft-partial", "published-identical", "published-legacy",
+ "changed-desktop", "changed-package", "upload-corrupt", "missing-local"])
+def test_real_publication_shell_checks_assets_before_finalize(tmp_path, state):
+ directory = assemble_assets(tmp_path)
+ dist = tmp_path / "dist"
+ dist.mkdir()
+ for name in ("vibe-show-runtime-node-darwin-arm64.tgz", "show-runtime-manifest.json",
+ "avibe_os-3.1.2rc1.whl", "avibe_os-3.1.2rc1.tar.gz",
+ "avibe_memory-3.1.2rc1-py3-none-any.whl"):
+ (dist / name).write_bytes(name.encode())
+ remote = tmp_path / "remote"
+ remote.mkdir()
+ desktop_paths = sorted(directory.iterdir())
+ if state in {"published-identical", "changed-desktop", "changed-package"}:
+ for path in [*desktop_paths, *dist.iterdir()]:
+ shutil.copyfile(path, remote / path.name)
+ elif state == "draft-partial":
+ shutil.copyfile(desktop_paths[0], remote / desktop_paths[0].name)
+ elif state == "published-legacy":
+ for path in dist.iterdir():
+ shutil.copyfile(path, remote / path.name)
+ if state == "changed-desktop":
+ (remote / desktop_paths[0].name).write_bytes(b"different published bytes")
+ if state == "changed-package":
+ (remote / "avibe_os-3.1.2rc1.whl").write_bytes(b"different published wheel")
+ if state == "missing-local":
+ desktop_paths[0].unlink()
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ for name in ("desktop_release.py", "release_package_version.py", "github_release.py"):
+ shutil.copyfile(ROOT / "scripts" / name, scripts / name)
+ (tmp_path / "release.md").write_text("# TEST release\n")
+ binaries = tmp_path / "bin"
+ binaries.mkdir()
+ (binaries / "python").symlink_to(sys.executable)
+ gh = binaries / "gh"
+ gh.write_text(f"#!{sys.executable}\n" + '''
+import json, pathlib, shutil, sys
+args = sys.argv[1:]
+root = pathlib.Path.cwd()
+remote = root / 'remote'
+with (root / 'events.jsonl').open('a') as stream:
+ stream.write(json.dumps(args) + '\\n')
+state_path = root / 'state.json'
+state = json.loads(state_path.read_text()) if state_path.exists() else None
+if args[0] == 'api':
+ if '--jq' in args:
+ print('v1.0.0')
+ elif '--paginate' in args:
+ print(json.dumps([[state]] if state else [[]]))
+ elif state:
+ print(json.dumps(state))
+ else:
+ print('HTTP 404', file=sys.stderr)
+ sys.exit(1)
+elif args[1] == 'create':
+ state = dict(tag_name=args[2], draft=True, prerelease=False, body='', html_url='https://example.invalid/release')
+elif args[1] == 'edit':
+ if '--notes-file' in args:
+ state['body'] = pathlib.Path(args[args.index('--notes-file') + 1]).read_text()
+ if '--draft=false' in args:
+ state['draft'] = False
+ state['prerelease'] = '--prerelease' in args
+elif args[1] == 'view':
+ names = sorted(path.name for path in remote.iterdir())
+ print('\\n'.join(names) if '--jq' in args else json.dumps({'assets': [{'name': n} for n in names]}))
+elif args[1] == 'download':
+ name = args[args.index('--pattern') + 1]
+ shutil.copyfile(remote / name, pathlib.Path(args[args.index('--dir') + 1]) / name)
+elif args[1] == 'upload':
+ assert '--clobber' not in args
+ for item in args[args.index('--repo') + 2:]:
+ path = pathlib.Path(item)
+ assert not (remote / path.name).exists()
+ shutil.copyfile(path, remote / path.name)
+ if (root / 'corrupt').exists() and path.suffix == '.dmg':
+ (remote / path.name).write_bytes(b'corrupt uploaded file')
+else:
+ raise AssertionError(args)
+if state:
+ state_path.write_text(json.dumps(state))
+''')
+ gh.chmod(0o755)
+ if state != "new":
+ (tmp_path / "state.json").write_text(json.dumps({
+ "tag_name": TAG, "draft": not state.startswith("published"), "prerelease": True,
+ "body": "prior notes", "html_url": "https://example.invalid/release",
+ }))
+ if state == "upload-corrupt":
+ (tmp_path / "corrupt").touch()
+ command = step("Create GitHub-only Release", "release", "release_ai.yml")["run"]
+ command = command.replace("${{ steps.tag.outputs.tag }}", TAG)
+ command = command.replace("${{ steps.release_type.outputs.prerelease }}", "true")
+ result = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", command], cwd=tmp_path,
+ env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "SOURCE_SHA": SOURCE, "GITHUB_REPOSITORY": "avibe-bot/avibe"},
+ capture_output=True, text=True, timeout=30)
+ success = state in {"new", "draft-partial", "published-identical"}
+ assert (result.returncode == 0) == success, result.stdout + result.stderr
+ events_path = tmp_path / "events.jsonl"
+ events = [json.loads(line) for line in events_path.read_text().splitlines()] if events_path.exists() else []
+ finalizations = [args for args in events if "--draft=false" in args]
+ assert bool(finalizations) == success
+ if success:
+ assert {path.name for path in remote.iterdir()} == {path.name for path in [*directory.iterdir(), *dist.iterdir()]}
+ assert json.loads((tmp_path / "state.json").read_text())["draft"] is False
+ if state == "published-identical":
+ assert not any(args[:2] == ["release", "upload"] for args in events)
+ elif state != "upload-corrupt":
+ assert not any(args[:2] == ["release", "upload"] for args in events)
+ else:
+ assert json.loads((tmp_path / "state.json").read_text())["draft"] is True
+
+
+def test_workflow_shell_syntax():
+ for file in ("desktop-package.yml", "release_ai.yml"):
+ for job in workflow(file)["jobs"].values():
+ for item in job.get("steps", []):
+ if "run" not in item or item.get("shell") == "pwsh":
+ continue
+ command = re.sub(r"\$\{\{.*?\}\}", "fixture", item["run"])
+ result = subprocess.run(["bash", "-n"], input=command, text=True, capture_output=True)
+ assert result.returncode == 0, (file, item.get("name"), result.stderr)
diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.py
new file mode 100644
index 000000000..9c50e3f62
--- /dev/null
+++ b/tests/test_desktop_runtime.py
@@ -0,0 +1,1414 @@
+from __future__ import annotations
+
+import asyncio
+import io
+import json
+import socket
+import threading
+import urllib.error
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from config import paths
+from config.v2_config import (
+ AgentsConfig,
+ PlatformsConfig,
+ RemoteAccessConfig,
+ RuntimeConfig,
+ SlackConfig,
+ UiConfig,
+ V2Config,
+)
+from vibe import cli, internal_client, runtime
+from vibe.desktop_runtime import (
+ desktop_runtime_id,
+ desktop_endpoint_payload,
+ desktop_origin,
+ is_private_desktop_runtime_path,
+ private_desktop_backends_root,
+ private_desktop_node_bin,
+ private_desktop_npm_cli,
+ private_desktop_runtime_root,
+ requires_desktop_loopback_listener,
+ ui_listener_hosts,
+)
+from vibe.ui_server import _bind_ui_sockets, app
+
+
+READY_EXTERNAL_CONTROLLER_BUNDLED_UI_FIXTURE = json.loads(
+ (
+ Path(__file__).parent
+ / "fixtures"
+ / "desktop_ready_external_controller_bundled_ui.json"
+ ).read_text(encoding="utf-8")
+)
+
+
+ ("bind_host", "expected_origin", "expected_listeners"),
+ [
+ ("127.0.0.1", "http://127.0.0.1:5123", ("127.0.0.1",)),
+ ("127.0.0.2", "http://127.0.0.1:5123", ("127.0.0.2", "127.0.0.1")),
+ ("0.0.0.0", "http://127.0.0.1:5123", ("0.0.0.0",)),
+ ("192.168.1.20", "http://127.0.0.1:5123", ("192.168.1.20", "127.0.0.1")),
+ ("100.97.103.112", "http://127.0.0.1:5123", ("100.97.103.112", "127.0.0.1")),
+ ("::1", "http://[::1]:5123", ("::1",)),
+ ("::", "http://[::1]:5123", ("::",)),
+ ("*", "http://127.0.0.1:5123", ("0.0.0.0",)),
+ ("[::1]", "http://[::1]:5123", ("::1",)),
+ ("fd7a:115c:a1e0::42", "http://[::1]:5123", ("fd7a:115c:a1e0::42", "::1")),
+ ],
+)
+def test_desktop_origin_and_listener_contract(bind_host, expected_origin, expected_listeners):
+ assert desktop_origin(bind_host, 5123) == expected_origin
+ assert desktop_endpoint_payload(bind_host, 5123) == {
+ "schema_version": 1,
+ "origin": expected_origin,
+ }
+ assert ui_listener_hosts(bind_host) == expected_listeners
+
+
+def test_specific_hostname_gets_ipv4_desktop_listener(monkeypatch):
+ def unresolved(*_args, **_kwargs):
+ raise socket.gaierror("unresolved test hostname")
+
+ monkeypatch.setattr(socket, "getaddrinfo", unresolved)
+
+ assert requires_desktop_loopback_listener("192.0.2.20.example.invalid") is True
+ assert ui_listener_hosts("192.0.2.20.example.invalid") == (
+ "192.0.2.20.example.invalid",
+ "127.0.0.1",
+ )
+
+
+def test_localhost_does_not_add_duplicate_listener(monkeypatch):
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0))
+ ],
+ )
+
+ assert requires_desktop_loopback_listener("localhost") is False
+ assert ui_listener_hosts("localhost") == ("localhost",)
+
+
+def test_hostname_resolving_to_loopback_does_not_add_duplicate_listener(monkeypatch):
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0))
+ ],
+ )
+ assert requires_desktop_loopback_listener("avibe-loopback.test") is False
+ assert ui_listener_hosts("avibe-loopback.test") == ("avibe-loopback.test",)
+
+
+def test_hostname_resolving_to_another_ipv4_loopback_adds_advertised_listener(monkeypatch):
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.2", 0))
+ ],
+ )
+ assert requires_desktop_loopback_listener("avibe-other-loopback.test") is True
+ assert ui_listener_hosts("avibe-other-loopback.test") == (
+ "avibe-other-loopback.test",
+ "127.0.0.1",
+ )
+
+
+def test_numeric_string_port_is_normalized_for_endpoint_and_health_urls():
+ assert desktop_origin("127.0.0.1", "05123") == "http://127.0.0.1:5123"
+ assert desktop_endpoint_payload("127.0.0.1", "5123") == {
+ "schema_version": 1,
+ "origin": "http://127.0.0.1:5123",
+ }
+ assert runtime._ui_health_urls("127.0.0.1", "5123") == (
+ "http://127.0.0.1:5123/health",
+ "http://127.0.0.1:5123/ready",
+ )
+
+
+def test_desktop_runtime_id_accepts_only_lowercase_sha256():
+ runtime_id = "a" * 64
+
+ assert desktop_runtime_id({"AVIBE_DESKTOP_RUNTIME_ID": runtime_id}) == runtime_id
+ assert desktop_runtime_id({"AVIBE_DESKTOP_RUNTIME_ID": "A" * 64}) is None
+ assert desktop_runtime_id({"AVIBE_DESKTOP_RUNTIME_ID": "short"}) is None
+ assert desktop_runtime_id({}) is None
+
+
+def test_private_desktop_runtime_path_is_confined_to_absolute_launcher_root(tmp_path):
+ root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
+ env = {"AVIBE_DESKTOP_RUNTIME_ROOT": str(root)}
+
+ assert private_desktop_runtime_root(env) == root
+ assert is_private_desktop_runtime_path(root / "tools" / "bin" / "codex", env)
+ assert not is_private_desktop_runtime_path(tmp_path / "runtime-other" / "codex", env)
+ assert not is_private_desktop_runtime_path("tools/bin/codex", env)
+ assert private_desktop_runtime_root({"AVIBE_DESKTOP_RUNTIME_ROOT": "relative/runtime"}) is None
+
+
+def test_private_desktop_backend_toolchain_paths_are_separate_and_confined(tmp_path):
+ runtime_root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
+ node = runtime_root / "tools" / "node"
+ npm_cli = runtime_root / "tools" / "npm" / "bin" / "npm-cli.js"
+ node.parent.mkdir(parents=True)
+ npm_cli.parent.mkdir(parents=True)
+ node.write_text("node", encoding="utf-8")
+ node.chmod(0o755)
+ npm_cli.write_text("npm", encoding="utf-8")
+ backends_root = tmp_path / "backends"
+ env = {
+ "AVIBE_DESKTOP_RUNTIME_ROOT": str(runtime_root),
+ "VIBE_SHOW_RUNTIME_NODE_BIN": str(node),
+ "AVIBE_DESKTOP_NPM_CLI": str(npm_cli),
+ "AVIBE_DESKTOP_BACKENDS_ROOT": str(backends_root),
+ }
+
+ assert private_desktop_node_bin(env) == node
+ assert private_desktop_npm_cli(env) == npm_cli
+ assert private_desktop_backends_root(env) == backends_root
+ assert private_desktop_backends_root(
+ {**env, "AVIBE_DESKTOP_BACKENDS_ROOT": str(runtime_root / "backends")}
+ ) is None
+ assert private_desktop_npm_cli(
+ {**env, "AVIBE_DESKTOP_NPM_CLI": str(tmp_path / "outside-npm.js")}
+ ) is None
+
+
+ "port",
+ [
+ 0,
+ -1,
+ 65536,
+ True,
+ None,
+ 5123.0,
+ "",
+ "0",
+ "65536",
+ " 5123",
+ "+5123",
+ "5123.0",
+ "1234",
+ ],
+)
+def test_desktop_origin_rejects_invalid_ports(port):
+ with pytest.raises(ValueError, match="between 1 and 65535"):
+ desktop_origin("127.0.0.1", port)
+
+
+def test_bind_ui_sockets_adds_same_port_loopback_for_specific_bind(monkeypatch):
+ calls = []
+ sockets = [object(), object()]
+
+ def fake_bind(host, port):
+ calls.append((host, port))
+ return sockets[len(calls) - 1]
+
+ monkeypatch.setattr("vibe.ui_server._bind_ui_socket", fake_bind)
+
+ assert _bind_ui_sockets("100.97.103.112", 5123) == sockets
+ assert calls == [("100.97.103.112", 5123), ("127.0.0.1", 5123)]
+
+
+ ("bind_host", "expected_listener"),
+ [
+ ("0.0.0.0", "0.0.0.0"),
+ ("127.0.0.1", "127.0.0.1"),
+ ("::", "::"),
+ ("::1", "::1"),
+ # The two spellings a person can configure that are not addresses: the
+ # listener they produce has to be one a socket can be given.
+ ("*", "0.0.0.0"),
+ ("[::1]", "::1"),
+ ],
+)
+def test_bind_ui_sockets_does_not_duplicate_wildcard_or_loopback(bind_host, expected_listener, monkeypatch):
+ calls = []
+
+ def fake_bind(host, port):
+ calls.append((host, port))
+ return object()
+
+ monkeypatch.setattr("vibe.ui_server._bind_ui_socket", fake_bind)
+
+ assert len(_bind_ui_sockets(bind_host, 5123)) == 1
+ assert calls == [(expected_listener, 5123)]
+
+
+def test_bind_ui_sockets_binds_the_wildcard_spelling_for_real():
+ """A stubbed bind cannot tell an address from a word, which is how this hid.
+
+ ``getaddrinfo`` is what rejects ``*``, so only a real bind shows whether the
+ resolved listener host is one the kernel accepts. Port 0 keeps it ephemeral
+ and the socket is closed straight away -- it is never listened on.
+ """
+
+ sockets = _bind_ui_sockets("*", 0)
+ try:
+ assert len(sockets) == 1
+ finally:
+ for sock in sockets:
+ sock.close()
+
+
+def test_bind_ui_sockets_closes_primary_when_loopback_bind_fails(monkeypatch):
+ class FakeSocket:
+ closed = False
+
+ def close(self):
+ self.closed = True
+
+ primary = FakeSocket()
+
+ def fake_bind(host, _port):
+ if host == "127.0.0.1":
+ raise OSError("loopback unavailable")
+ return primary
+
+ monkeypatch.setattr("vibe.ui_server._bind_ui_socket", fake_bind)
+
+ with pytest.raises(OSError, match="loopback unavailable"):
+ _bind_ui_sockets("192.168.1.20", 5123)
+
+ assert primary.closed is True
+
+
+def test_ui_health_urls_require_primary_and_desktop_listener():
+ assert runtime._ui_health_urls("100.97.103.112", 5123) == (
+ "http://100.97.103.112:5123/health",
+ "http://127.0.0.1:5123/ready",
+ )
+ assert runtime._ui_health_urls("fd7a:115c:a1e0::42", 5123) == (
+ "http://[fd7a:115c:a1e0::42]:5123/health",
+ "http://[::1]:5123/ready",
+ )
+
+
+def test_ui_health_urls_require_ready_identity_on_default_loopback_bind():
+ assert runtime._ui_health_urls("127.0.0.1", 5123) == (
+ "http://127.0.0.1:5123/health",
+ "http://127.0.0.1:5123/ready",
+ )
+ assert runtime._ui_health_urls("0.0.0.0", 5123) == (
+ "http://127.0.0.1:5123/health",
+ "http://127.0.0.1:5123/ready",
+ )
+ assert runtime._ui_health_urls("*", 5123) == (
+ "http://127.0.0.1:5123/health",
+ "http://127.0.0.1:5123/ready",
+ )
+
+
+def test_ui_server_readiness_reuses_wildcard_listener(monkeypatch):
+ calls = []
+
+ class Response:
+ status = 200
+
+ def __init__(self, payload=b""):
+ self.payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self.payload
+
+ def fake_urlopen(url, timeout):
+ calls.append((url, timeout))
+ if url.endswith("/ready"):
+ return Response(json.dumps(READY_EXTERNAL_CONTROLLER_BUNDLED_UI_FIXTURE).encode("utf-8"))
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime._ui_server_readiness("*", 5123) is True
+ assert calls == [
+ ("http://127.0.0.1:5123/health", 0.5),
+ ("http://127.0.0.1:5123/ready", 0.5),
+ ]
+
+
+def test_ui_server_health_fails_when_old_specific_bind_lacks_desktop_listener(monkeypatch):
+ calls = []
+
+ class Response:
+ def __init__(self, payload=b""):
+ self.status = 200
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self._payload
+
+ def fake_urlopen(url, timeout):
+ calls.append((url, timeout))
+ if url == "http://127.0.0.1:5123/ready":
+ raise OSError("connection refused")
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime.ui_server_healthy("100.97.103.112", 5123) is False
+ assert calls == [
+ ("http://100.97.103.112:5123/health", 0.5),
+ ("http://127.0.0.1:5123/ready", 0.5),
+ ]
+
+
+def test_ui_server_health_requires_versioned_ready_identity_for_companion_listener(monkeypatch):
+ class Response:
+ def __init__(self, payload):
+ self.status = 200
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self._payload
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ return Response(b'{\"ready\":true}')
+ return Response(b"")
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime.ui_server_healthy("100.97.103.112", 5123) is False
+
+
+def test_ui_server_health_accepts_the_external_controller_bundled_ui_shape(monkeypatch):
+ class Response:
+ status = 200
+
+ def __init__(self, payload=b""):
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self._payload
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ return Response(json.dumps(READY_EXTERNAL_CONTROLLER_BUNDLED_UI_FIXTURE).encode("utf-8"))
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime.ui_server_healthy("100.97.103.112", 5123) is True
+
+
+ ("status", "payload"),
+ [
+ (
+ 200,
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": 1,
+ },
+ ),
+ (
+ 503,
+ {
+ "schema_version": True,
+ "product": "avibe",
+ "ready": False,
+ "code": "service_starting",
+ },
+ ),
+ (
+ 503,
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": 0,
+ "code": "service_starting",
+ },
+ ),
+ ],
+)
+def test_ready_identity_rejects_bool_integer_equivalence(status, payload):
+ class Response:
+ def __init__(self):
+ self.status = status
+
+ def read(self):
+ return json.dumps(payload).encode("utf-8")
+
+ assert runtime._ui_ready_identity_state(Response()) is None
+
+
+def test_ready_identity_accepts_valid_desktop_runtime_id():
+ class Response:
+ status = 200
+
+ def read(self):
+ return json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_runtime_id": "a" * 64,
+ }
+ ).encode("utf-8")
+
+ assert runtime._ui_ready_identity_state(Response()) is True
+
+
+def test_ready_identity_accepts_valid_external_controller_ui_runtime_id():
+ class Response:
+ status = 200
+
+ def read(self):
+ return json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_ui_runtime_id": "b" * 64,
+ }
+ ).encode("utf-8")
+
+ assert runtime._ui_ready_identity_state(Response()) is True
+
+
+ "payload",
+ [
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_ui_runtime_id": "short",
+ },
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_runtime_id": "a" * 64,
+ "desktop_ui_runtime_id": "b" * 64,
+ },
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_ui_runtime_id": None,
+ },
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_ui_runtime_id": "A" * 64,
+ },
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_ui_runtime_id": "b" * 64,
+ "unexpected": True,
+ },
+ ],
+)
+def test_ready_identity_rejects_invalid_or_ambiguous_runtime_ids(payload):
+ class Response:
+ status = 200
+
+ def read(self):
+ return json.dumps(payload).encode("utf-8")
+
+ assert runtime._ui_ready_identity_state(Response()) is None
+
+
+def test_ui_server_compatibility_accepts_versioned_not_ready_identity(monkeypatch):
+ payload = json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "controller_unavailable",
+ }
+ ).encode("utf-8")
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise urllib.error.HTTPError(
+ url,
+ 503,
+ "Service Unavailable",
+ {},
+ io.BytesIO(payload),
+ )
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime.ui_server_healthy("100.97.103.112", 5123) is False
+ assert runtime._ui_server_compatible("100.97.103.112", 5123) is True
+
+
+ "payload",
+ [
+ {"ready": False, "code": "controller_unavailable"},
+ {
+ "schema_version": 1,
+ "product": "other",
+ "ready": False,
+ "code": "controller_unavailable",
+ },
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ },
+ ],
+)
+def test_ui_server_compatibility_rejects_invalid_not_ready_identity(monkeypatch, payload):
+ encoded_payload = json.dumps(payload).encode("utf-8")
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise urllib.error.HTTPError(
+ url,
+ 503,
+ "Service Unavailable",
+ {},
+ io.BytesIO(encoded_payload),
+ )
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime._ui_server_compatible("100.97.103.112", 5123) is False
+
+
+def test_ui_server_compatibility_rejects_a_valid_runtime_identity_invalid_response(monkeypatch):
+ payload = json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "runtime_identity_invalid",
+ }
+ ).encode("utf-8")
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise urllib.error.HTTPError(
+ url,
+ 503,
+ "Service Unavailable",
+ {},
+ io.BytesIO(payload),
+ )
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+
+ assert runtime._ui_server_compatible("100.97.103.112", 5123) is False
+
+
+def test_start_ui_replaces_a_ui_with_an_invalid_runtime_identity(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")
+ payload = json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "runtime_identity_invalid",
+ }
+ ).encode("utf-8")
+ stopped = []
+ spawned = []
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise urllib.error.HTTPError(
+ url,
+ 503,
+ "Service Unavailable",
+ {},
+ io.BytesIO(payload),
+ )
+ return Response()
+
+ def fake_spawn(_args, pid_path, _stdout_name, _stderr_name, env=None):
+ del env
+ spawned.append(True)
+ pid_path.write_text("67890", encoding="utf-8")
+ return 67890
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "from vibe.ui_server import run_ui_server; run_ui_server('100.97.103.112', 5123)"
+ if pid == 12345
+ else None,
+ )
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid: stopped.append(pid) or True)
+ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda _host, _port: True)
+
+ assert runtime.start_ui("100.97.103.112", 5123) == 67890
+ assert stopped == [12345]
+ assert spawned == [True]
+
+
+def test_start_ui_restarts_old_specific_bind_without_desktop_listener(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")
+ stopped = []
+
+ class Response:
+ def __init__(self, payload=b""):
+ self.status = 200
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self._payload
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url == "http://127.0.0.1:5123/ready":
+ raise OSError("old UI has no loopback listener")
+ return Response()
+
+ def fake_spawn(_args, pid_path, _stdout_name, _stderr_name, env=None):
+ del env
+ pid_path.write_text("67890", encoding="utf-8")
+ return 67890
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "from vibe.ui_server import run_ui_server; run_ui_server('100.97.103.112', 5123)"
+ if pid == 12345
+ else None,
+ )
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid: stopped.append(pid) or True)
+ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda _host, _port: True)
+
+ assert runtime.start_ui("100.97.103.112", 5123) == 67890
+ assert stopped == [12345]
+
+
+def test_start_ui_adopts_versioned_not_ready_ui(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")
+ payload = json.dumps(
+ {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "service_starting",
+ }
+ ).encode("utf-8")
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ probe_timeouts = []
+
+ def fake_urlopen(url, timeout):
+ probe_timeouts.append(timeout)
+ if url.endswith("/ready"):
+ raise urllib.error.HTTPError(
+ url,
+ 503,
+ "Service Unavailable",
+ {},
+ io.BytesIO(payload),
+ )
+ return Response()
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "from vibe.ui_server import run_ui_server; run_ui_server('100.97.103.112', 5123)"
+ if pid == 12345
+ else None,
+ )
+ monkeypatch.setattr(runtime, "stop_pid", lambda _pid: pytest.fail("compatible UI must not be stopped"))
+ monkeypatch.setattr(
+ runtime,
+ "spawn_background",
+ lambda *_args, **_kwargs: pytest.fail("compatible UI must not be replaced"),
+ )
+
+ assert runtime.start_ui("100.97.103.112", 5123) == 12345
+ assert probe_timeouts == [runtime.UI_ADOPTION_PROBE_TIMEOUT_SECONDS] * 2
+
+
+def test_start_ui_normalizes_numeric_string_port_before_spawning(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ spawned = []
+
+ def fake_spawn(args, pid_path, stdout_name, stderr_name, env=None):
+ spawned.append((args, pid_path, stdout_name, stderr_name, env))
+ return 67890
+
+ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)
+
+ assert runtime.start_ui("127.0.0.1", "05123", wait_for_ready=False) == 67890
+ assert spawned[0][0] == [
+ runtime.sys.executable,
+ "-c",
+ "from vibe.ui_server import run_ui_server; run_ui_server('127.0.0.1', 5123)",
+ ]
+
+
[email protected]("host", ["127.0.0.1", "0.0.0.0"])
+def test_start_ui_restarts_old_default_or_wildcard_ui_without_ready_identity(tmp_path, monkeypatch, host):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")
+ stopped = []
+
+ class Response:
+ def __init__(self, payload=b""):
+ self.status = 200
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return self._payload
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise OSError("old UI lacks ready contract")
+ return Response()
+
+ def fake_spawn(_args, pid_path, _stdout_name, _stderr_name, env=None):
+ del env
+ pid_path.write_text("67890", encoding="utf-8")
+ return 67890
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: f"from vibe.ui_server import run_ui_server; run_ui_server('{host}', 5123)"
+ if pid == 12345
+ else None,
+ )
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid: stopped.append(pid) or True)
+ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda _host, _port: True)
+
+ assert runtime.start_ui(host, 5123) == 67890
+ assert stopped == [12345]
+
+
+def test_start_ui_refuses_to_replace_a_stale_ui_that_will_not_stop(tmp_path, monkeypatch):
+ # The stale process still owns the configured listener when the stop fails, so a
+ # replacement could only die on bind. Starting one anyway would also repoint the
+ # pid record at that dead replacement and leave nothing naming the process that
+ # actually has to be stopped.
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".avibe")
+ runtime.ensure_dirs()
+ pid_path = paths.get_runtime_ui_pid_path()
+ pid_path.write_text("12345", encoding="utf-8")
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return b""
+
+ def fake_urlopen(url, timeout):
+ del timeout
+ if url.endswith("/ready"):
+ raise OSError("old UI lacks ready contract")
+ return Response()
+
+ stop_attempts = []
+
+ monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "from vibe.ui_server import run_ui_server; run_ui_server('127.0.0.1', 5123)"
+ if pid == 12345
+ else None,
+ )
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid: stop_attempts.append(pid) or False)
+ monkeypatch.setattr(
+ runtime,
+ "spawn_background",
+ lambda *_args, **_kwargs: pytest.fail("a UI that would not stop must not be replaced"),
+ )
+
+ assert runtime.start_ui("127.0.0.1", 5123) is None
+ assert stop_attempts == [12345]
+ assert pid_path.read_text(encoding="utf-8") == "12345"
+
+
+def test_desktop_endpoint_cli_emits_only_schema_v1_json(monkeypatch, capsys):
+ config = SimpleNamespace(ui=SimpleNamespace(setup_port=6123))
+ monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "100.97.103.112")
+ monkeypatch.setattr(cli, "_open_browser", lambda _url: pytest.fail("desktop endpoint must not open a browser"))
+
+ assert cli.cmd_desktop_endpoint() == 0
+
+ captured = capsys.readouterr()
+ assert captured.out == '{"schema_version":1,"origin":"http://127.0.0.1:6123"}\n'
+ assert captured.err == ""
+
+
+def test_desktop_endpoint_cli_parser_requires_explicit_json():
+ args = cli.build_parser().parse_args(["desktop", "endpoint", "--json"])
+ assert args.command == "desktop"
+ assert args.desktop_command == "endpoint"
+ assert args.json is True
+
+ with pytest.raises(SystemExit) as exc:
+ cli.build_parser().parse_args(["desktop", "endpoint"])
+ assert exc.value.code == 2
+
+
+def _ready_response(
+ monkeypatch,
+ owners,
+ *,
+ controller_ready,
+ controller_runtime_id=None,
+ ui_runtime_id=None,
+):
+ if ui_runtime_id is None:
+ monkeypatch.delenv("AVIBE_DESKTOP_RUNTIME_ID", raising=False)
+ else:
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", ui_runtime_id)
+ owner_iter = iter(owners)
+
+ def resolve_owner(*, include_starting):
+ return next(owner_iter)
+
+ async def health_identity():
+ if not controller_ready:
+ return None
+ identity = {"ok": True, "service": "vibe-remote-internal", "version": 1}
+ if controller_runtime_id is not None:
+ identity["desktop_runtime_id"] = controller_runtime_id
+ return identity
+
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", resolve_owner)
+ monkeypatch.setattr("vibe.internal_client.health_identity", health_identity)
+ return app.test_client().get("/ready", base_url="http://127.0.0.1:5123")
+
+
+def test_ready_reports_service_starting(monkeypatch):
+ response = _ready_response(monkeypatch, [None, 1234], controller_ready=False)
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "service_starting",
+ }
+
+
+def test_ready_reports_service_unavailable(monkeypatch):
+ response = _ready_response(monkeypatch, [None, None], controller_ready=False)
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "service_unavailable",
+ }
+
+
+def test_ready_reports_controller_unavailable(monkeypatch):
+ response = _ready_response(monkeypatch, [1234, 1234], controller_ready=False)
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "controller_unavailable",
+ }
+
+
+def test_ready_reports_owner_race_after_controller_probe(monkeypatch):
+ response = _ready_response(monkeypatch, [1234, 5678], controller_ready=True)
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "ownership_lost",
+ }
+
+
+def test_ready_reports_owner_loss_even_when_controller_probe_fails(monkeypatch):
+ response = _ready_response(monkeypatch, [1234, None], controller_ready=False)
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "ownership_lost",
+ }
+
+
+def test_ready_requires_stable_owner_and_healthy_controller(monkeypatch):
+ response = _ready_response(monkeypatch, [1234, 1234], controller_ready=True)
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ }
+ assert response.headers["Cache-Control"] == "no-store"
+
+
+def test_ready_reports_desktop_runtime_identity(monkeypatch):
+ response = _ready_response(
+ monkeypatch,
+ [1234, 1234],
+ controller_ready=True,
+ controller_runtime_id="a" * 64,
+ ui_runtime_id="a" * 64,
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": True,
+ "desktop_runtime_id": "a" * 64,
+ }
+
+
+ ("controller_runtime_id", "ui_runtime_id"),
+ [
+ ("a" * 64, "b" * 64),
+ ("a" * 64, None),
+ ],
+)
+def test_ready_rejects_a_runtime_identity_mismatch(
+ monkeypatch,
+ controller_runtime_id,
+ ui_runtime_id,
+):
+ response = _ready_response(
+ monkeypatch,
+ [1234, 1234],
+ controller_ready=True,
+ controller_runtime_id=controller_runtime_id,
+ ui_runtime_id=ui_runtime_id,
+ )
+
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "runtime_identity_mismatch",
+ **(
+ {"desktop_runtime_id": controller_runtime_id}
+ if controller_runtime_id is not None
+ else {}
+ ),
+ }
+
+
+def test_ready_adopts_a_healthy_untagged_controller_even_when_ui_inherits_bundle_identity(monkeypatch):
+ response = _ready_response(
+ monkeypatch,
+ [1234, 1234],
+ controller_ready=True,
+ controller_runtime_id=None,
+ ui_runtime_id="a" * 64,
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == READY_EXTERNAL_CONTROLLER_BUNDLED_UI_FIXTURE
+
+
+def test_ready_rejects_an_invalid_bundled_ui_identity(monkeypatch):
+ response = _ready_response(
+ monkeypatch,
+ [1234, 1234],
+ controller_ready=True,
+ controller_runtime_id=None,
+ ui_runtime_id="invalid",
+ )
+
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "runtime_identity_invalid",
+ }
+
+
+def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(
+ monkeypatch,
+ capsys,
+):
+ """The reused-service path must start only the missing UI and become adoptable."""
+
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ language="en",
+ )
+ spawned = []
+ process_times = {1234: 1789010100.1235, 5678: 1789010100.4565}
+
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "a" * 64)
+ monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(cli, "_write_status", lambda *args: None)
+ monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")
+ monkeypatch.setattr(cli.runtime, "process_create_time", lambda pid: process_times[pid])
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
+ monkeypatch.setattr(cli, "_open_browser", lambda _url: pytest.fail("browser is disabled"))
+
+ def reused_service(**kwargs):
+ kwargs["start_info"].capture(1234, reused=True)
+ return 1234
+
+ monkeypatch.setattr(cli.runtime, "start_service", reused_service)
+ monkeypatch.setattr(
+ internal_client,
+ "health_identity_sync",
+ lambda: {"ok": True, "service": "vibe-remote-internal", "version": 1},
+ )
+
+ async def health_identity():
+ return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+
+ monkeypatch.setattr("vibe.internal_client.health_identity", health_identity)
+ def spawn_ui(args, pid_path, *logs, **kwargs):
+ # The spawn primitive records and captures the child before returning it.
+ spawned.append((args, logs, kwargs))
+ pid_path.write_text("5678", encoding="utf-8")
+ kwargs["start_info"].capture(5678, reused=False)
+ return 5678
+
+ monkeypatch.setattr(cli.runtime, "spawn_background", spawn_ui)
+
+ def wait_for_ui(host, port):
+ response = app.test_client().get("/ready", base_url=f"http://{host}:{port}")
+ assert response.status_code == 200
+ assert response.get_json() == READY_EXTERNAL_CONTROLLER_BUNDLED_UI_FIXTURE
+ return True
+
+ monkeypatch.setattr(cli.runtime, "wait_for_ui_server", wait_for_ui)
+ monkeypatch.setattr(cli.runtime, "stop_service", lambda: pytest.fail("reused Controller must survive"))
+ monkeypatch.setattr(
+ cli.runtime,
+ "stop_ui",
+ lambda **_kwargs: pytest.fail("the missing UI path must not stop a surviving UI"),
+ )
+
+ assert cli.cmd_start(open_browser=False) == 0
+
+ receipt_line = next(
+ line for line in capsys.readouterr().out.splitlines() if line.startswith("@avibe-start-receipt:")
+ )
+ assert json.loads(receipt_line.split(":", 1)[1]) == {
+ "schema_version": 1,
+ "outcome": "reused",
+ "service_pid": 1234,
+ "ui_pid": 5678,
+ "service_create_unix_ms": process_times[1234] * 1000,
+ "ui_create_unix_ms": process_times[5678] * 1000,
+ }
+ assert len(spawned) == 1
+
+
+ ("owners", "controller_ready"),
+ [
+ ([OSError("lock unreadable")], False),
+ ([None, OSError("lock unreadable")], False),
+ ([1234, OSError("lock unreadable")], True),
+ ],
+)
+def test_ready_preserves_schema_when_owner_probe_fails(monkeypatch, owners, controller_ready):
+ owner_iter = iter(owners)
+
+ def resolve_owner(*, include_starting):
+ del include_starting
+ result = next(owner_iter)
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ async def health_identity():
+ if not controller_ready:
+ return None
+ return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", resolve_owner)
+ monkeypatch.setattr("vibe.internal_client.health_identity", health_identity)
+
+ response = app.test_client().get("/ready", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 503
+ assert response.get_json() == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": "owner_probe_failed",
+ }
+
+
+def test_ready_offloads_all_service_owner_probes(monkeypatch):
+ owner_iter = iter([1234, 1234, None, 5678])
+ owner_calls = []
+ offloaded_calls = []
+ original_to_thread = asyncio.to_thread
+
+ def resolve_owner(*, include_starting):
+ owner_calls.append((include_starting, threading.get_ident()))
+ return next(owner_iter)
+
+ async def health_identity():
+ return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+
+ async def track_to_thread(func, *args, **kwargs):
+ event_loop_thread = threading.get_ident()
+ result = await original_to_thread(func, *args, **kwargs)
+ offloaded_calls.append((func, kwargs, event_loop_thread))
+ return result
+
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", resolve_owner)
+ monkeypatch.setattr("vibe.internal_client.health_identity", health_identity)
+ monkeypatch.setattr("vibe.ui_server.asyncio.to_thread", track_to_thread)
+
+ client = app.test_client()
+ ready_response = client.get("/ready", base_url="http://127.0.0.1:5123")
+ starting_response = client.get("/ready", base_url="http://127.0.0.1:5123")
+
+ assert ready_response.status_code == 200
+ assert starting_response.status_code == 503
+ assert [include_starting for include_starting, _thread in owner_calls] == [
+ False,
+ False,
+ False,
+ True,
+ ]
+ assert [kwargs["include_starting"] for _func, kwargs, _thread in offloaded_calls] == [
+ False,
+ False,
+ False,
+ True,
+ ]
+ assert all(func is resolve_owner for func, _kwargs, _thread in offloaded_calls)
+ assert all(
+ worker_thread != event_loop_thread
+ for (_include_starting, worker_thread), (_func, _kwargs, event_loop_thread) in zip(
+ owner_calls,
+ offloaded_calls,
+ strict=True,
+ )
+ )
+
+
+def _save_remote_access_config(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.public_url = "https://alex.avibe.bot"
+ cloud.client_id = "vr_client_123"
+ cloud.instance_id = "inst_123"
+ cloud.session_secret = "session-secret"
+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"
+ config.save()
+
+
+ ("base_url", "remote_addr", "headers"),
+ [
+ ("http://attacker.example", "127.0.0.1", {}),
+ ("http://127.0.0.1:5123", "203.0.113.10", {}),
+ ("http://127.0.0.1.example", "127.0.0.1", {}),
+ (
+ "http://127.0.0.1:5123",
+ "127.0.0.1",
+ {"X-Forwarded-For": "203.0.113.10"},
+ ),
+ ],
+)
+def test_desktop_runtime_host_header_contract_rejects_non_loopback_local_trust(
+ monkeypatch,
+ tmp_path,
+ base_url,
+ remote_addr,
+ headers,
+):
+ _save_remote_access_config(monkeypatch, tmp_path)
+
+ async def fail_health_identity():
+ pytest.fail("blocked Host must not reach the readiness route")
+
+ monkeypatch.setattr("vibe.internal_client.health_identity", fail_health_identity)
+
+ response = app.test_client().get(
+ "/ready",
+ base_url=base_url,
+ environ_base={"REMOTE_ADDR": remote_addr},
+ headers=headers,
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 503
+ assert response.get_json()["error"] == "remote_access_host_mismatch"
+
+
+def test_bind_ui_socket_uses_ipv6_family(monkeypatch):
+ created_families = []
+
+ class FakeSocket:
+ def setsockopt(self, *_args):
+ return None
+
+ def bind(self, address):
+ assert address == ("::1", 5123)
+
+ def set_inheritable(self, _value):
+ return None
+
+ def fake_socket(family):
+ created_families.append(family)
+ return FakeSocket()
+
+ monkeypatch.setattr(socket, "socket", fake_socket)
+
+ from vibe.ui_server import _bind_ui_socket
+
+ _bind_ui_socket("::1", 5123)
+ assert created_families == [socket.AF_INET6]
diff --git a/tests/test_desktop_runtime_bundle_builder.py b/tests/test_desktop_runtime_bundle_builder.py
new file mode 100644
index 000000000..bf934c645
--- /dev/null
+++ b/tests/test_desktop_runtime_bundle_builder.py
@@ -0,0 +1,263 @@
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import subprocess
+import zipfile
+from pathlib import Path
+
+import pytest
+
+
+SCRIPT = Path(__file__).parents[1] / "desktop" / "scripts" / "build-runtime-bundle.py"
+SPEC = importlib.util.spec_from_file_location("desktop_runtime_bundle_builder", SCRIPT)
+assert SPEC is not None and SPEC.loader is not None
+builder = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(builder)
+
+
+def test_private_probe_environment_does_not_inherit_credentials(monkeypatch, tmp_path):
+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-cross-boundary")
+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "must-not-cross-boundary")
+ monkeypatch.setenv("CODEX_HOME", "/real/codex-home")
+ monkeypatch.setenv("HOME", "/real/home")
+
+ probe_home = tmp_path / "probe"
+ node = tmp_path / "payload" / "tools" / "bin" / "node"
+ npm_cli = tmp_path / "payload" / "tools" / "npm" / "bin" / "npm-cli.js"
+ environment = builder.private_probe_environment(probe_home, node, npm_cli)
+
+ assert "OPENAI_API_KEY" not in environment
+ assert "ANTHROPIC_AUTH_TOKEN" not in environment
+ assert environment["HOME"] == str(probe_home)
+ assert environment["CODEX_HOME"] == str(probe_home / "codex")
+ assert environment["PATH"].split(builder.os.pathsep)[0] == str(node.parent)
+ assert environment["AVIBE_DESKTOP_NPM_CLI"] == str(npm_cli)
+ assert environment["AVIBE_DESKTOP_BACKENDS_ROOT"] == str(probe_home / "backends")
+
+
+def test_runtime_sources_schema_two_contains_only_node_and_npm_tools():
+ sources = json.loads((SCRIPT.parents[1] / "runtime-sources.json").read_text(encoding="utf-8"))
+
+ assert sources["schema_version"] == 2
+ assert sources["npm_version"] == "10.9.8"
+ assert set(sources["sdist_build_allowlist"]) == {"claude-agent-sdk", "http-ece"}
+ assert "codex_version" not in sources
+ assert "codex_license" not in sources
+ for target, config in sources["targets"].items():
+ expected_source = "node_modules/npm" if "windows" in target else "lib/node_modules/npm"
+ assert config["npm_source"] == expected_source
+ assert config["npm_entrypoint"] == "tools/npm/bin/npm-cli.js"
+ assert not any(key.startswith("codex") for key in config)
+
+
+def test_python_runtime_verification_checks_bundled_claude_paths(monkeypatch, tmp_path):
+ calls = []
+
+ def fake_run(command, **kwargs):
+ calls.append((command, kwargs))
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(builder.subprocess, "run", fake_run)
+ private_python = tmp_path / "python" / "bin" / "python3"
+
+ builder.verify_python_runtime_excludes_agent_backends(private_python, tmp_path)
+
+ assert len(calls) == 1
+ command, kwargs = calls[0]
+ assert command[:3] == [str(private_python), "-I", "-c"]
+ assert 'for name in ("claude", "claude.exe")' in command[3]
+ assert kwargs == {"cwd": tmp_path, "check": True}
+
+
+def test_node_toolchain_normalizes_bundled_npm_without_command_shims(monkeypatch, tmp_path):
+ repository = tmp_path / "repository"
+ repository.mkdir()
+ (repository / "LICENSE").write_text("avibe license", encoding="utf-8")
+ node_root = tmp_path / "node-distribution"
+ (node_root / "bin").mkdir(parents=True)
+ (node_root / "bin" / "node").write_bytes(b"node")
+ npm = node_root / "lib" / "node_modules" / "npm"
+ (npm / "bin").mkdir(parents=True)
+ (npm / "bin" / "npm-cli.js").write_text("npm cli", encoding="utf-8")
+ (npm / "lib").mkdir()
+ (npm / "lib" / "npm.js").write_text("npm library", encoding="utf-8")
+ semver = npm / "node_modules" / "semver" / "bin" / "semver.js"
+ semver.parent.mkdir(parents=True)
+ semver.write_text("semver cli", encoding="utf-8")
+ bin_dir = npm / "node_modules" / ".bin"
+ bin_dir.mkdir()
+ if os.name != "nt":
+ (bin_dir / "semver").symlink_to("../semver/bin/semver.js")
+ (npm / "package.json").write_text('{"version":"10.9.8"}', encoding="utf-8")
+ (npm / "LICENSE").write_text("npm license", encoding="utf-8")
+ (node_root / "LICENSE").write_text("node license", encoding="utf-8")
+ monkeypatch.setattr(builder, "REPO_ROOT", repository)
+ monkeypatch.setattr(builder, "extract_source", lambda _archive, _destination: node_root)
+ calls = []
+
+ def fake_run(command, **_kwargs):
+ calls.append(command)
+ return subprocess.CompletedProcess(command, 0, stdout="10.9.8\n", stderr="")
+
+ monkeypatch.setattr(builder.subprocess, "run", fake_run)
+ payload = tmp_path / "payload"
+ work_dir = tmp_path / "work"
+ work_dir.mkdir()
+
+ builder.install_node_toolchain(
+ {
+ "os": "macos",
+ "node_source": "bin/node",
+ "node_entrypoint": "tools/bin/node",
+ "npm_source": "lib/node_modules/npm",
+ "npm_entrypoint": "tools/npm/bin/npm-cli.js",
+ },
+ tmp_path / "node.tar.gz",
+ payload,
+ work_dir,
+ "10.9.8",
+ )
+
+ assert {path.name for path in (payload / "tools").iterdir()} == {"bin", "npm"}
+ assert {path.name for path in (payload / "tools" / "bin").iterdir()} == {"node"}
+ assert (payload / "tools" / "npm" / "lib" / "npm.js").read_text() == "npm library"
+ if os.name != "nt":
+ copied_semver = payload / "tools" / "npm" / "node_modules" / ".bin" / "semver"
+ assert copied_semver.read_text() == "semver cli"
+ assert not copied_semver.is_symlink()
+ assert (payload / "licenses" / "npm-LICENSE").read_text() == "npm license"
+ assert calls == [
+ [
+ str(payload / "tools" / "bin" / "node"),
+ str(payload / "tools" / "npm" / "bin" / "npm-cli.js"),
+ "--version",
+ ]
+ ]
+
+
[email protected](os.name == "nt", reason="symlink creation requires extra Windows privileges")
+def test_node_toolchain_rejects_npm_links_outside_package(monkeypatch, tmp_path):
+ node_root = tmp_path / "node-distribution"
+ (node_root / "bin").mkdir(parents=True)
+ (node_root / "bin" / "node").write_bytes(b"node")
+ npm = node_root / "lib" / "node_modules" / "npm"
+ npm.mkdir(parents=True)
+ outside = node_root / "outside"
+ outside.write_text("outside", encoding="utf-8")
+ (npm / "link").symlink_to(outside)
+ monkeypatch.setattr(builder, "extract_source", lambda _archive, _destination: node_root)
+
+ with pytest.raises(SystemExit, match="link escapes its package"):
+ builder.install_node_toolchain(
+ {
+ "os": "macos",
+ "node_source": "bin/node",
+ "node_entrypoint": "tools/bin/node",
+ "npm_source": "lib/node_modules/npm",
+ "npm_entrypoint": "tools/npm/bin/npm-cli.js",
+ },
+ tmp_path / "node.tar.gz",
+ tmp_path / "payload",
+ tmp_path,
+ "10.9.8",
+ )
+
+
+def test_existing_show_manifest_must_match_the_pinned_digest(monkeypatch, tmp_path):
+ repository = tmp_path / "repository"
+ manifest = repository / "vibe" / "show_runtime_manifest.json"
+ manifest.parent.mkdir(parents=True)
+ manifest.write_text("tampered", encoding="utf-8")
+ monkeypatch.setattr(builder, "REPO_ROOT", repository)
+
+ with pytest.raises(SystemExit, match="does not match"):
+ builder.ensure_show_runtime_manifest(
+ {"show_runtime_manifest": {"sha256": "0" * 64}},
+ tmp_path / "cache",
+ )
+
+
+def test_runtime_zip_uses_portable_relative_path_order(tmp_path):
+ payload = tmp_path / "payload"
+ (payload / "z").mkdir(parents=True)
+ (payload / "A").mkdir()
+ (payload / "z" / "entry").write_bytes(b"z")
+ (payload / "A" / "entry").write_bytes(b"a")
+ archive = tmp_path / "runtime.zip"
+
+ builder.create_runtime_zip(payload, archive)
+
+ with zipfile.ZipFile(archive) as runtime:
+ assert runtime.namelist() == ["A/entry", "z/entry"]
+
+
+def test_runtime_zip_is_byte_for_byte_deterministic(tmp_path):
+ payload = tmp_path / "payload"
+ payload.mkdir()
+ (payload / "runtime").write_bytes(b"immutable runtime")
+ first = tmp_path / "first.zip"
+ second = tmp_path / "second.zip"
+
+ first_metadata = builder.create_runtime_zip(payload, first)
+ second_metadata = builder.create_runtime_zip(payload, second)
+
+ assert first_metadata == second_metadata
+ assert first.read_bytes() == second.read_bytes()
+
+
+def test_probe_diagnostics_report_every_log_including_the_ones_that_are_missing(tmp_path):
+ probe_home = tmp_path / "avibe-probe-xyz"
+ (probe_home / "runtime").mkdir(parents=True)
+ (probe_home / "logs").mkdir()
+ (probe_home / "runtime" / "service_stderr.log").write_text(
+ "ModuleNotFoundError: No module named 'win32api'\n", encoding="utf-8"
+ )
+ (probe_home / "runtime" / "ui_stdout.log").write_text("", encoding="utf-8")
+ (probe_home / "logs" / "vibe_remote.log").write_bytes(b"head\n" + b"pad\n" * 64 + b"tail line\n")
+
+ report = builder.collect_probe_diagnostics(probe_home, tail_bytes=64)
+
+ # The reason the probe failed has to survive into the job log.
+ assert "ModuleNotFoundError: No module named 'win32api'" in report
+ # A log that was never written is itself evidence, so it is named rather
+ # than silently skipped.
+ assert "runtime/service_stdout.log: absent" in report
+ assert "runtime/ui_stdout.log (0 bytes)" in report
+ assert "(empty)" in report
+ # Truncation keeps the tail: a crash is at the end of a log, not the start.
+ assert "tail line" in report
+ assert "head" not in report
+ assert "last 64 of 271 bytes" in report
+
+
+def test_timed_out_stop_renders_the_streams_a_timeout_leaves_undecoded(monkeypatch, tmp_path):
+ # `subprocess.run` decodes its streams on the completion path a timeout
+ # never reaches, so `TimeoutExpired` carries bytes even though the call asked
+ # for text, and an unwritten stream as None. This runs from a `finally`:
+ # formatting bytes there would raise a TypeError over the probe failure the
+ # report exists to explain.
+ def timing_out(command, **_kwargs):
+ raise subprocess.TimeoutExpired(command, 60, output=captured_stdout, stderr=captured_stderr)
+
+ monkeypatch.setattr(builder.subprocess, "run", timing_out)
+
+ captured_stdout = b"stopping the private runtime\n"
+ captured_stderr = b"dispatch socket still held \xff\n"
+ stopped, report = builder.stop_private_runtime(["vibe"], tmp_path, {})
+
+ assert stopped is False
+ assert "timed out after 60s" in report
+ assert "stopping the private runtime" in report
+ # Undecodable output is reported, not raised.
+ assert "dispatch socket still held �" in report
+
+ # The shape the Windows job actually produced: output captured, nothing on
+ # stderr at all.
+ captured_stderr = None
+ stopped, report = builder.stop_private_runtime(["vibe"], tmp_path, {})
+
+ assert stopped is False
+ assert "stopping the private runtime" in report
+ assert "vibe stop stderr" not in report
diff --git a/tests/test_distribution_artifacts.py b/tests/test_distribution_artifacts.py
index 994675d00..b0228a6c4 100644
--- a/tests/test_distribution_artifacts.py
+++ b/tests/test_distribution_artifacts.py
@@ -148,15 +148,27 @@ print(json.dumps({"snapshot": snapshot, "files": files}, sort_keys=True))
capture_output=True, text=True, timeout=60)
assert result.returncode == 0, result.stdout + result.stderr
observed = json.loads(result.stdout.strip())
+ expected = _expected_builtin_skills_snapshot()
+ assert observed["files"] == expected
+ assert len(observed["snapshot"]) == 64
+
+
+def _expected_builtin_skills_snapshot() -> dict[str, dict[str, int | str]]:
+ # The current working directory is the source checkout used to build the
+ # distributions; the test module may come from a different sparse checkout.
+ source_root = Path.cwd()
+ assert (source_root / "pyproject.toml").is_file(), source_root
+ skill_root = source_root / "skills"
+ assert skill_root.is_dir(), skill_root
expected = {}
- for path in (ROOT / "skills").rglob("*"):
+ for path in skill_root.rglob("*"):
if path.is_file() and "__pycache__" not in path.parts:
- expected[path.relative_to(ROOT / "skills").as_posix()] = {
+ expected[path.relative_to(skill_root).as_posix()] = {
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
"mode": path.stat().st_mode & 0o777,
}
- assert observed["files"] == expected
- assert len(observed["snapshot"]) == 64
+ assert expected, skill_root
+ return expected
def test_installed_wheel_mirrors_complete_builtin_skills_snapshot(tmp_path):
diff --git a/tests/test_harness_run_projection.py b/tests/test_harness_run_projection.py
index 8659397e1..9c5720a01 100644
--- a/tests/test_harness_run_projection.py
+++ b/tests/test_harness_run_projection.py
@@ -275,15 +275,27 @@ def test_get_run_enriches_identically_to_the_list(tmp_path: Path) -> None:
}
)
store.enqueue_run(
- _run("run_detail", run_type="watch", definition_id="watch_detail", session_id=session_id)
+ _run(
+ "run_detail",
+ run_type="watch",
+ definition_id="watch_detail",
+ session_id=session_id,
+ started_at="2026-07-25T23:59:20Z",
+ completed_at=NOW,
+ )
)
listed = store.list_runs_page(page_request=None).items[0]
detail = store.get_run("run_detail")
finally:
store.close()
- projected = ("session_title", "session_label", "session_is_workbench", "definition_name", "definition_kind")
+ projected = (
+ "session_title", "session_label", "session_is_workbench", "definition_name", "definition_kind",
+ "started_at", "completed_at",
+ )
assert {key: detail[key] for key in projected} == {key: listed[key] for key in projected}
+ assert detail["started_at"] == "2026-07-25T23:59:20Z"
+ assert detail["completed_at"] == NOW
def test_run_enrichment_is_batched(tmp_path: Path) -> None:
diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.py
index 7f2c8889a..72c223a87 100644
--- a/tests/test_inbox_events.py
+++ b/tests/test_inbox_events.py
@@ -24,6 +24,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.inbox_events import InboxEventBus
+from storage.background import EXECUTION_RUN_TYPES, RUN_STATUS_ALIASES, TERMINAL_RUN_STATUSES
def test_publish_delivers_to_subscriber():
@@ -106,7 +107,64 @@ def test_synchronous_callback_failure_does_not_break_queue_delivery():
assert asyncio.run(scenario()) == ("turn.end", {"session_id": "s1"})
-def test_sqlite_background_store_publishes_run_updates(tmp_path):
[email protected]("started_at", [None, "2026-07-04T00:00:01+00:00"])
[email protected]("completed_at", [None, "2026-07-04T00:00:02+00:00"])
+def test_run_updated_publisher_preserves_available_timestamps(monkeypatch, started_at, completed_at):
+ from core import inbox_events
+
+ published = []
+ monkeypatch.setattr(inbox_events.bus, "publish", lambda *event: published.append(event))
+ inbox_events.publish_run_updated(
+ run_id="run_stamps",
+ status="succeeded",
+ started_at=started_at,
+ completed_at=completed_at,
+ )
+
+ expected = {"run_id": "run_stamps", "status": "succeeded"}
+ expected.update(
+ (key, value)
+ for key, value in {"started_at": started_at, "completed_at": completed_at}.items()
+ if value is not None
+ )
+ assert published == [(inbox_events.RUNS_UPDATED_EVENT, expected)]
+
+
[email protected]("stored_status, status", RUN_STATUS_ALIASES.items())
[email protected]("started_at", [None, "2026-07-04T00:00:01+00:00"])
[email protected]("completed_at", [None, "2026-07-04T00:00:02+00:00"])
+def test_run_row_events_only_add_available_terminal_timestamps(
+ monkeypatch, stored_status, status, started_at, completed_at
+):
+ from core import inbox_events
+ from storage.background import _publish_run_rows_updated
+
+ published = []
+ bridged = []
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", False)
+ monkeypatch.setattr(inbox_events.bus, "publish", lambda *event: published.append(event))
+ monkeypatch.setattr(
+ "vibe.internal_client.publish_event_sync",
+ lambda event_type, data, **kwargs: bridged.append((event_type, data)),
+ )
+ _publish_run_rows_updated(
+ [{"id": "run_stamps", "status": stored_status, "started_at": started_at, "completed_at": completed_at}]
+ )
+
+ expected = {"run_id": "run_stamps", "status": status, "cancel_requested": False}
+ if status in TERMINAL_RUN_STATUSES:
+ expected.update(
+ (key, value)
+ for key, value in {"started_at": started_at, "completed_at": completed_at}.items()
+ if value is not None
+ )
+ assert published == [(inbox_events.RUNS_UPDATED_EVENT, expected)]
+ assert bridged == published
+
+
[email protected]("terminal_status", sorted(TERMINAL_RUN_STATUSES))
[email protected]("run_type", sorted(EXECUTION_RUN_TYPES | {"watch_runtime", "future_run_type"}))
+def test_sqlite_background_store_publishes_run_updates(tmp_path, run_type, terminal_status):
async def scenario():
from core import inbox_events
from storage.background import SQLiteBackgroundTaskStore
@@ -117,7 +175,7 @@ def test_sqlite_background_store_publishes_run_updates(tmp_path):
store.enqueue_run(
{
"id": "run_evt_1",
- "request_type": "agent_run",
+ "request_type": run_type,
"status": "queued",
"message": "hello",
"created_at": "2026-07-04T00:00:00+00:00",
@@ -133,35 +191,44 @@ def test_sqlite_background_store_publishes_run_updates(tmp_path):
store.update_run_status(
"run_evt_1",
- status="failed",
- updated_at="2026-07-04T00:00:02+00:00",
+ status=terminal_status,
+ updated_at="2026-07-04T00:01:02+00:00",
completed_at="2026-07-04T00:00:02+00:00",
- error="boom",
)
- failed = await asyncio.wait_for(queue.get(), timeout=1.0)
- return queued, running, failed
+ terminal = await asyncio.wait_for(queue.get(), timeout=1.0)
+ return queued, running, terminal, store.get_run("run_evt_1")
finally:
store.close()
inbox_events.bus.unsubscribe(sub_id)
- queued, running, failed = asyncio.run(scenario())
+ queued, running, terminal, persisted = asyncio.run(scenario())
assert queued == (
"runs.updated",
{
"run_id": "run_evt_1",
"status": "queued",
- "run_type": "agent_run",
+ "run_type": run_type,
"session_id": "ses_evt",
"updated_at": "2026-07-04T00:00:00+00:00",
"cancel_requested": False,
},
)
- assert running[0] == "runs.updated"
- assert running[1]["run_id"] == "run_evt_1"
- assert running[1]["status"] == "running"
- assert failed[0] == "runs.updated"
- assert failed[1]["run_id"] == "run_evt_1"
- assert failed[1]["status"] == "failed"
+ assert running == (
+ "runs.updated",
+ {**queued[1], "status": "running", "updated_at": "2026-07-04T00:00:01+00:00"},
+ )
+ assert persisted["started_at"] == "2026-07-04T00:00:01+00:00"
+ assert persisted["completed_at"] == "2026-07-04T00:00:02+00:00"
+ assert terminal == (
+ "runs.updated",
+ {
+ **queued[1],
+ "status": terminal_status,
+ "started_at": persisted["started_at"],
+ "completed_at": persisted["completed_at"],
+ "updated_at": "2026-07-04T00:01:02+00:00",
+ },
+ )
def test_hfr_156_sqlite_commit_bridges_run_update_to_controller(tmp_path, monkeypatch):
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index d2519a43c..deba534ad 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -54,7 +54,79 @@ def test_default_socket_path_honors_env_override(monkeypatch, tmp_path):
assert internal_client.default_socket_path() == target
-def test_cancel_dispatch_round_trip(tmp_path, socket_path):
+def test_health_identity_round_trip_includes_the_controller_runtime_id(socket_path):
+ app = FastAPI()
+
+ @app.get("/internal/health")
+ async def _health():
+ return {
+ "ok": True,
+ "service": "vibe-remote-internal",
+ "version": 1,
+ "desktop_runtime_id": "a" * 64,
+ }
+
+ sock = socket_path
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):
+ return await internal_client.health_identity(socket_path=sock)
+
+ assert asyncio.run(_go()) == {
+ "ok": True,
+ "service": "vibe-remote-internal",
+ "version": 1,
+ "desktop_runtime_id": "a" * 64,
+ }
+
+
+def test_health_identity_rejects_a_malformed_runtime_id(socket_path):
+ app = FastAPI()
+
+ @app.get("/internal/health")
+ async def _health():
+ return {
+ "ok": True,
+ "service": "vibe-remote-internal",
+ "version": 1,
+ "desktop_runtime_id": "not-a-sha256",
+ }
+
+ sock = socket_path
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):
+ return await internal_client.health_identity(socket_path=sock)
+
+ assert asyncio.run(_go()) is None
+
+
+def test_health_identity_sync_uses_the_same_validated_contract(socket_path):
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "ok": True,
+ "service": "vibe-remote-internal",
+ "version": 1,
+ "desktop_runtime_id": "b" * 64,
+ },
+ )
+
+ sock = socket_path
+ with patch(
+ "vibe.internal_client.httpx.HTTPTransport",
+ return_value=httpx.MockTransport(handler),
+ ):
+ identity = internal_client.health_identity_sync(socket_path=sock)
+
+ assert identity is not None
+ assert identity["desktop_runtime_id"] == "b" * 64
+
+
+def test_cancel_dispatch_round_trip(socket_path):
"""``cancel_dispatch`` should forward the session id to the
controller's ``POST /internal/cancel/<session_id>`` endpoint and
surface the JSON body verbatim so the UI can render it.
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 21186779b..173daabde 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -478,12 +478,27 @@ async def _health_round_trip():
return resp
-def test_health_endpoint():
+def test_health_endpoint(monkeypatch):
+ monkeypatch.delenv("AVIBE_DESKTOP_RUNTIME_ID", raising=False)
resp = asyncio.run(_health_round_trip())
assert resp.status_code == 200
assert resp.json() == {"ok": True, "service": "vibe-remote-internal", "version": 1}
+def test_health_endpoint_reports_the_controller_runtime_identity(monkeypatch):
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "a" * 64)
+
+ resp = asyncio.run(_health_round_trip())
+
+ assert resp.status_code == 200
+ assert resp.json() == {
+ "ok": True,
+ "service": "vibe-remote-internal",
+ "version": 1,
+ "desktop_runtime_id": "a" * 64,
+ }
+
+
@pytest.mark.parametrize("env_value", [None, "1"])
def test_model_hub_rpc_uses_controller_owned_service(monkeypatch, env_value):
if env_value is None:
@@ -7903,7 +7918,6 @@ def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
def test_boot_publishes_app_then_waits_for_controller_recovery(
monkeypatch,
- tmp_path,
):
"""HFR-152: HTTP serving waits for controller-owned runtime recovery."""
import uvicorn
@@ -7931,6 +7945,14 @@ def test_boot_publishes_app_then_waits_for_controller_recovery(
calls.append("serve")
listener = SimpleNamespace(close=lambda: calls.append("close"))
+ bound = SimpleNamespace(listener=listener)
+ host = SimpleNamespace(
+ instance_id=None,
+ bearer_token=None,
+ bind=lambda: bound,
+ publish=lambda _bound: None,
+ cleanup=lambda _bound: listener.close(),
+ )
def _create_app(_controller):
calls.append("app")
@@ -7939,9 +7961,9 @@ def test_boot_publishes_app_then_waits_for_controller_recovery(
monkeypatch.setattr(internal_server, "create_app", _create_app)
monkeypatch.setattr(
- internal_server,
- "_bind_socket",
- lambda _path: (listener, tmp_path / "internal.sock"),
+ internal_server.control_ipc,
+ "select_control_ipc_host",
+ lambda **_kwargs: host,
)
monkeypatch.setattr(uvicorn, "Config", lambda *_args, **_kwargs: object())
monkeypatch.setattr(uvicorn, "Server", _Server)
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 25958936e..c023067af 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -2144,6 +2144,8 @@ def test_dependencies_status_shape(monkeypatch):
)
out = api.dependencies_status()
assert out["ok"]
+ assert out["reconciling"] is False
+ assert out["reconciling_dependencies"] == []
by = {d["id"]: d for d in out["deps"]}
assert list(by) == [
"askill",
@@ -2167,6 +2169,65 @@ def test_dependencies_status_shape(monkeypatch):
assert by["node"]["installed"] and by["node"]["version"] == "20.11"
+def test_dependencies_status_preserves_reconciliation_seen_before_probes(monkeypatch):
+ monkeypatch.setattr(
+ api,
+ "askill_update_status",
+ lambda **_: {"installed": True, "version": "0.1.13", "status": "ready"},
+ )
+ monkeypatch.setattr(api, "avault_status", lambda: {"installed": True, "version": "0.0.1", "status": "ready"})
+ import core.show_runtime as srt_mod
+
+ class _ShowRuntime:
+ def status(self):
+ return {"installed": True, "node_available": True, "node_version": "22.0"}
+
+ monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _ShowRuntime())
+
+ class _LockSnapshot:
+ def __init__(self):
+ self._calls = 0
+
+ def locked(self):
+ self._calls += 1
+ return self._calls == 1
+
+ monkeypatch.setattr(api, "_STARTUP_DEPENDENCY_RECONCILE_LOCK", _LockSnapshot())
+
+ assert api.dependencies_status(offline=True)["reconciling"] is True
+
+
+def test_dependencies_status_detects_reconciliation_during_probes(monkeypatch):
+ monkeypatch.setattr(
+ api,
+ "askill_update_status",
+ lambda **_: {"installed": True, "version": "0.1.13", "status": "ready"},
+ )
+ monkeypatch.setattr(api, "avault_status", lambda: {"installed": True, "version": "0.0.1", "status": "ready"})
+ import core.show_runtime as srt_mod
+
+ class _ShowRuntime:
+ def status(self):
+ return {"installed": True, "node_available": True, "node_version": "22.0"}
+
+ monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _ShowRuntime())
+
+ import core.tmux_runtime as tmux_mod
+
+ monkeypatch.setattr(tmux_mod, "tmux_status", lambda: {"installed": False, "version": None, "status": "missing"})
+ monkeypatch.setattr(api, "_startup_dependency_state_snapshot", iter([(7, set()), (8, set())]).__next__)
+
+ class _Unlocked:
+ def locked(self):
+ return False
+
+ monkeypatch.setattr(api, "_STARTUP_DEPENDENCY_RECONCILE_LOCK", _Unlocked())
+ result = api.dependencies_status()
+
+ assert result["reconciling"] is True
+ assert result["reconciling_dependencies"] == []
+
+
@pytest.mark.parametrize(
("runtime_status", "expected"),
(
@@ -2329,6 +2390,7 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeyp
askill_calls = []
avault_calls = []
model_hub_calls = []
+ model_hub_active_dependencies = []
def fake_ensure(force=False):
askill_calls.append(force)
@@ -2341,18 +2403,40 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeyp
return {"ok": True, "installed": True, "changed": False, "path": "/x/avault"}
monkeypatch.setattr(api, "ensure_avault_installed", fake_ensure_avault)
+
monkeypatch.setattr(
api,
- "ensure_model_hub_engine_installed",
- lambda *, force=False: model_hub_calls.append(force)
- or {"ok": True, "installed": True, "changed": True, "version": "v7.2.149"},
+ "_model_hub_engine_dependency_status",
+ lambda: {
+ "id": "model-hub-engine",
+ "kind": "runtime",
+ "required": True,
+ "installed": True,
+ "version": "v7.2.149",
+ "latest_version": "v7.2.149",
+ "has_update": False,
+ "status": "ready",
+ "action_class": "none",
+ "reason": None,
+ "download_error": None,
+ },
)
+ def fake_ensure_model_hub_engine(*, force=False):
+ model_hub_calls.append(force)
+ model_hub_active_dependencies.append(
+ api.dependencies_status(dependency_ids=["model-hub-engine"])["reconciling_dependencies"]
+ )
+ return {"ok": True, "installed": True, "changed": True, "version": "v7.2.149"}
+
+ monkeypatch.setattr(api, "ensure_model_hub_engine_installed", fake_ensure_model_hub_engine)
+
import core.show_runtime as srt_mod
class _Mgr:
def __init__(self):
self.prepared = []
+ self.auto_install = True
def status(self, *, offline=False):
assert offline is True
@@ -2384,6 +2468,8 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeyp
assert askill_calls == [False]
assert avault_calls == [False]
assert model_hub_calls == [False]
+ assert model_hub_active_dependencies == [["model-hub-engine"]]
+ assert api.dependencies_status(dependency_ids=["model-hub-engine"])["reconciling_dependencies"] == []
assert out["model_hub_engine"]["version"] == "v7.2.149"
assert manager.prepared == [(False, True)]
assert out["node"]["status"] == "ready"
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index d1c72f0ba..aa07c809f 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -90,6 +90,39 @@ def test_partial_multi_backend_acquire_releases_earlier_locks(tmp_path):
pass
[email protected](os.name != "posix", reason="the rejected half needs real POSIX permission bits")
+def test_lease_permission_mask_is_posix_only(tmp_path, monkeypatch):
+ """The 0o077 mask describes POSIX permissions; elsewhere it describes nothing.
+
+ Windows synthesizes st_mode from file attributes, so a lease file there
+ always reports 0o666 and the mask would reject every acquire rather than
+ describe one -- the failure that kept the Windows desktop package from
+ building (see issue #2132). Both directions are asserted: POSIX still
+ refuses a group-accessible lease file, and the identical file acquires once
+ os.name is not posix.
+ """
+ directory = tmp_path / "native-takeover"
+ directory.mkdir(mode=0o700)
+ (directory / "codex.lock").touch(mode=0o600)
+ (directory / "codex.lock").chmod(0o660)
+
+ with pytest.raises(OSError, match="Unsafe native lease file"):
+ NativeCredentialLease(("codex",), state_dir=tmp_path).acquire()
+
+ class _NonPosixOs:
+ """Scoped to the module under test, so storage.lock keeps using this
+ host's real locking primitive instead of importing msvcrt."""
+
+ name = "nt"
+
+ def __getattr__(self, attr):
+ return getattr(os, attr)
+
+ monkeypatch.setattr("core.backend_restart.os", _NonPosixOs())
+ with NativeCredentialLease(("codex",), state_dir=tmp_path):
+ pass
+
+
@pytest.mark.parametrize("data", [
None, [], {}, {"version": 1, "phase": "prepared", "backends": [{}]},
{"version": 2, "phase": "prepared", "backends": ["codex"]},
diff --git a/tests/test_release_checkout_pinning.py b/tests/test_release_checkout_pinning.py
new file mode 100644
index 000000000..10414e147
--- /dev/null
+++ b/tests/test_release_checkout_pinning.py
@@ -0,0 +1,41 @@
+"""Release tooling must run from the released source, not from a dispatched branch."""
+
+from __future__ import annotations
+
+import re
+
+from tests.test_desktop_release import workflow
+
+
+TOOLING = (
+ "scripts/desktop_release.py",
+ "scripts/github_release.py",
+ "scripts/release_package_version.py",
+ "gh release",
+)
+
+
+def test_release_tooling_never_runs_from_an_unpinned_checkout():
+ covered = set()
+ for file in ("desktop-package.yml", "release_ai.yml"):
+ jobs = workflow(file)["jobs"]
+ for name, job in jobs.items():
+ steps = job.get("steps", [])
+ if not any(marker in item.get("run", "") for item in steps for marker in TOOLING):
+ continue
+ covered.add(name)
+ for item in steps:
+ if not str(item.get("uses", "")).startswith("actions/checkout@"):
+ continue
+ ref = item.get("with", {}).get("ref", "")
+ assert ref, (file, name, item.get("name"))
+ for producer in re.findall(r"needs\.([\w-]+)\.outputs", ref):
+ if "if" not in jobs[producer]:
+ continue
+ # Skip propagation normally keeps a dependent off whenever its
+ # producer is gated out, but a job that opts out of it still runs
+ # and then reads that output as the empty string, which silently
+ # restores the unpinned default.
+ if re.search(r"\b(always|cancelled)\s*\(", str(job.get("if", ""))):
+ assert "||" in ref, (file, name, producer)
+ assert covered == {"package", "resolve-desktop-release", "build-assets", "release"}
diff --git a/tests/test_release_verification.py b/tests/test_release_verification.py
index 353081692..09999e5f5 100644
--- a/tests/test_release_verification.py
+++ b/tests/test_release_verification.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import hashlib
+import importlib.util
import json
from http.server import BaseHTTPRequestHandler
import os
@@ -170,7 +172,7 @@ def test_noncanonical_official_tags_fail_before_artifact_construction(
@pytest.mark.parametrize(("workflow_name", "job_name", "checkout_name", "workflow_ref"), WORKFLOWS)
-def test_workflow_owned_checkout_supplies_the_executed_contract(tmp_path, workflow_name, job_name, checkout_name, workflow_ref):
+def test_workflow_owned_checkout_supplies_the_executed_contract(tmp_path, monkeypatch, workflow_name, job_name, checkout_name, workflow_ref):
job = _job(workflow_name, job_name)
checkout = _step(job, checkout_name)
assert checkout["uses"].startswith("actions/checkout@")
@@ -182,21 +184,31 @@ def test_workflow_owned_checkout_supplies_the_executed_contract(tmp_path, workfl
verification = _step(job, "Verify built distribution contracts")
assert "release-automation/tests/test_distribution_artifacts.py" in verification["run"]
assert "AVIBE_CORE_WHEEL=" in verification["run"] and "AVIBE_CORE_SDIST=" in verification["run"]
+ assert "working-directory" not in verification
assert job["steps"].index(checkout) < job["steps"].index(verification)
# Replay the path/ref contract: release source lacks the automation, while
# the workflow commit supplies it via the declared sparse checkout.
remote = tmp_path / "remote"
remote.mkdir()
_fixture_git(remote, "init")
- _fixture_git(remote, "commit", "--allow-empty", "-m", "release source")
+ source_skill = remote / "skills" / "use-avibe" / "SKILL.md"
+ source_skill.parent.mkdir(parents=True)
+ source_skill.write_text("Released skill content\n", encoding="utf-8")
+ (remote / "pyproject.toml").write_text("[build-system]\n", encoding="utf-8")
+ _fixture_git(remote, "add", ".")
+ _fixture_git(remote, "commit", "-m", "release source")
release = _fixture_git(remote, "rev-parse", "HEAD")
+ source_skill.write_text("Workflow-only revision\n", encoding="utf-8")
for name in files:
target = remote / name
target.parent.mkdir(parents=True, exist_ok=True)
- if workflow_name == "publish.yml" and (name.startswith("tests/e2e/") or name == "tests/__init__.py"):
+ if name == "tests/test_distribution_artifacts.py" or (
+ workflow_name == "publish.yml"
+ and (name.startswith("tests/e2e/") or name == "tests/__init__.py")
+ ):
shutil.copy2(ROOT / name, target)
else:
- target.write_text("print('workflow-owned automation')\n")
+ target.write_text("print('workflow-owned automation')\n", encoding="utf-8")
_fixture_git(remote, "add", ".")
_fixture_git(remote, "commit", "-m", "workflow automation")
workflow = _fixture_git(remote, "rev-parse", "HEAD")
@@ -207,6 +219,21 @@ def test_workflow_owned_checkout_supplies_the_executed_contract(tmp_path, workfl
assert _fixture_git(destination, "rev-parse", "HEAD") != release
for name in files:
assert (destination / name).is_file()
+ assert not (destination / "skills").exists()
+ source_checkout = tmp_path / "build-source"
+ _fixture_git(tmp_path, "clone", "--no-checkout", str(remote), str(source_checkout))
+ _fixture_git(source_checkout, "checkout", release)
+ contract = destination / "tests/test_distribution_artifacts.py"
+ spec = importlib.util.spec_from_file_location("sparse_distribution_contract", contract)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ with monkeypatch.context() as scoped:
+ scoped.chdir(source_checkout)
+ expected = module._expected_builtin_skills_snapshot()
+ assert expected["use-avibe/SKILL.md"]["sha256"] == hashlib.sha256(
+ b"Released skill content\n"
+ ).hexdigest()
if workflow_name == "publish.yml":
upload = _step(job, "Upload GitHub release assets")
script = "release-automation/scripts/github_release.py"
@@ -224,6 +251,13 @@ def test_workflow_owned_checkout_supplies_the_executed_contract(tmp_path, workfl
assert "1 test collected" in collected.stdout
+def test_preview_python_assets_build_from_the_desktop_source_sha():
+ # The desktop packages are built from the resolved TEST source; the Python
+ # assets published beside them must come from that same commit.
+ checkout = _step(_job("release_ai.yml", "build-assets"), "Checkout")
+ assert checkout["with"]["ref"] == "${{ needs.resolve-desktop-release.outputs.source_sha }}"
+
+
@pytest.mark.parametrize("workflow", ["publish.yml", "release_ai.yml"])
def test_release_shell_steps_parse(workflow):
document = yaml.safe_load((ROOT / ".github/workflows" / workflow).read_text())
@@ -245,6 +279,9 @@ def test_preview_upload_validates_all_existing_bytes_before_runtime_then_package
"avibe_memory-1.0.0-py3-none-any.whl"]
for name in names:
(dist / name).write_bytes(b"immutable asset")
+ desktop_asset = "desktop-dist/Avibe-1.0.0rc1-macos-aarch64.dmg"
+ (tmp_path / "desktop-dist").mkdir()
+ (tmp_path / desktop_asset).write_bytes(b"desktop asset")
binaries = tmp_path / "bin"
binaries.mkdir()
log = tmp_path / "calls.jsonl"
@@ -266,7 +303,8 @@ elif args[:2] == ["release", "download"]:
command = command.replace("${{ steps.tag.outputs.tag }}", "gh-v1.0.0rc1").replace("${{ steps.release_type.outputs.prerelease }}", "true")
result = subprocess.run(["bash", "-c", command], cwd=tmp_path,
env={**os.environ, "PATH": f"{binaries}:{os.environ['PATH']}",
- "GITHUB_REPOSITORY": "fixture/repo"}, capture_output=True, text=True)
+ "GITHUB_REPOSITORY": "fixture/repo", "SOURCE_SHA": "0" * 40},
+ capture_output=True, text=True)
calls = [json.loads(line) for line in log.read_text().splitlines()]
uploads = [call for call in calls if call[1:3] == ["release", "upload"]]
if existing == "different":
@@ -277,7 +315,10 @@ elif args[:2] == ["release", "download"]:
assert result.returncode == 0, result.stdout + result.stderr
assert len(uploads) == 2
assert uploads[0][-2:] == [f"dist/{name}" for name in names[:2]]
- assert uploads[1][6:] == [f"dist/{name}" for name in names[2:] if existing == "none" or name != names[-1]]
+ assert uploads[1][6:] == [
+ *(f"dist/{name}" for name in names[2:] if existing == "none" or name != names[-1]),
+ desktop_asset,
+ ]
assert "finalize" in calls[-1]
@@ -466,7 +507,14 @@ def test_upload_protects_all_existing_bytes_before_any_write(tmp_path, workflow_
for directory, assets in ((dist, packages), (runtime, runtimes)):
for name, data in assets.items():
(directory / name).write_bytes(data)
- all_assets = {**packages, **runtimes}
+ desktop = {}
+ if workflow_name == "release_ai.yml":
+ desktop_dir = workspace / "desktop-dist"
+ desktop_dir.mkdir()
+ desktop = {"Avibe_3.1.0-rc.1_aarch64-apple-darwin.dmg": b"desktop installer"}
+ for name, data in desktop.items():
+ (desktop_dir / name).write_bytes(data)
+ all_assets = {**packages, **runtimes, **desktop}
existing = dict(all_assets) if state == "identical" else {}
if state not in {"empty", "identical"}:
existing = {name: all_assets[name] for name in (
@@ -526,7 +574,7 @@ def test_upload_protects_all_existing_bytes_before_any_write(tmp_path, workflow_
result = subprocess.run(
["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", command],
cwd=workspace, env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
- "TMPDIR": str(temporary), "GITHUB_REPOSITORY": "avibe-bot/avibe"},
+ "TMPDIR": str(temporary), "GITHUB_REPOSITORY": "avibe-bot/avibe", "SOURCE_SHA": "a" * 40},
capture_output=True, text=True, timeout=20,
)
success = state in {"empty", "identical", "partial"}
@@ -542,38 +590,43 @@ def test_upload_protects_all_existing_bytes_before_any_write(tmp_path, workflow_
if uploads:
first_upload = events.index(uploads[0])
assert all(event[1] != "download" for event in events[first_upload:])
- kinds = [name in packages for name in uploaded]
+ kinds = [name in packages or name in desktop for name in uploaded]
assert kinds == sorted(kinds), "Runtime uploads must complete before package uploads"
assert not list(temporary.iterdir())
@pytest.mark.parametrize("tag", ["v3.1.0", "v3.2.0rc1", "gh-v3.2.0rc1"])
@pytest.mark.parametrize("build_result", ["success", "skipped", "failure", "cancelled"])
[email protected]("desktop_result", ["success", "skipped", "failure", "cancelled"])
@pytest.mark.parametrize("cancelled", [False, True])
@pytest.mark.parametrize("event", ["push", "workflow_dispatch"])
-def test_notes_skip_unused_official_build_but_never_publish_a_failed_preview(tag, build_result, cancelled, event):
+def test_notes_skip_unused_official_build_but_never_publish_a_failed_preview(
+ tag, build_result, desktop_result, cancelled, event,
+):
workflow = yaml.safe_load((ROOT / ".github/workflows/release_ai.yml").read_text())
jobs = workflow["jobs"]
preview_condition = "startsWith(github.event.inputs.tag || github.ref_name, 'gh-v')"
for name in ("resolve-show-runtime-ref",):
assert jobs[name]["if"] == preview_condition
assert jobs["show-runtime-bundles"]["needs"] == "resolve-show-runtime-ref"
- assert jobs["build-assets"]["needs"] == ["show-runtime-bundles"]
- assert jobs["release"]["needs"] == "build-assets"
+ assert jobs["build-assets"]["needs"] == ["resolve-desktop-release", "show-runtime-bundles"]
+ assert jobs["release"]["needs"] == ["build-assets", "resolve-desktop-release", "desktop-packages"]
# Evaluate the actual bounded job expression for both event kinds. This
# catches skipped-needs propagation without replacing the condition itself.
expression = jobs["release"]["if"].strip().removeprefix("${{").removesuffix("}}").strip()
expression = expression.replace("needs.build-assets.result", "build_result")
+ expression = expression.replace("needs.desktop-packages.result", "desktop_result")
+ expression = expression.replace("needs.resolve-desktop-release.result", "desktop_result")
expression = expression.replace("github.event.inputs.tag", "input_tag").replace("github.ref_name", "ref")
expression = expression.replace("&&", " and ").replace("||", " or ").replace("!", " not ")
expression = " ".join(expression.split())
result = eval(expression, {"__builtins__": {}}, {
- "build_result": build_result, "input_tag": tag if event == "workflow_dispatch" else "",
+ "build_result": build_result, "desktop_result": desktop_result, "input_tag": tag if event == "workflow_dispatch" else "",
"ref": "master" if event == "workflow_dispatch" else tag,
"cancelled": lambda: cancelled,
"startsWith": lambda value, prefix: value.startswith(prefix),
})
expected = not cancelled and (
build_result == "success" or (build_result == "skipped" and not tag.startswith("gh-v"))
- )
+ ) and (not tag.startswith("gh-v") or desktop_result == "success")
assert result == expected
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 370af4a17..3b211e166 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -50,6 +50,7 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_
monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: {"PATH": "/bin"})
monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)
+ monkeypatch.setattr(restart_supervisor, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
monkeypatch.setattr(restart_supervisor, "atomic_upgrade_lock", Lock)
def fake_popen(command, **kwargs):
@@ -72,7 +73,8 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_
assert calls["command"][:2] == ["/bin/vibe", "__restart-supervisor"]
assert calls["command"][calls["command"].index("--delay-seconds") + 1] == "60"
assert "--prepare-show-runtime" not in calls["command"]
- assert calls["kwargs"]["start_new_session"] is True
+ assert calls["kwargs"]["creationflags"] == 0x200
+ assert "start_new_session" not in calls["kwargs"]
assert calls["kwargs"]["env"] == {"PATH": "/bin"}
assert runtime.read_json(runtime.get_restart_status_path())["job_id"] == result["job_id"]
assert events == ["lock-enter", "spawn", "lock-exit"]
diff --git a/tests/test_runtime_process_scan.py b/tests/test_runtime_process_scan.py
new file mode 100644
index 000000000..92a33bcf3
--- /dev/null
+++ b/tests/test_runtime_process_scan.py
@@ -0,0 +1,143 @@
+"""What the whole-machine service-process scan is allowed to cost.
+
+``vibe stop`` resolves the authoritative lock owner and then walks every
+process on the machine looking for lock-less Avibe daemons left behind by older
+lifecycle bugs. Whatever that walk does per process, it does a few hundred
+times per stop -- so anything in it that starts an external process is paid
+that many times over, before the service has been asked to exit or a single
+byte has been printed.
+
+On Linux the per-process fallback is a ``/proc`` read and the design is
+invisible. On Windows it was a ``powershell`` launch, and that is why
+``gh-v3.1.1rc10`` timed out in ``vibe stop`` with no output at all.
+"""
+
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from vibe import runtime
+
+# Generous by design. A scan that only reads what psutil already collected
+# finishes in about a second on a CI runner, and the packaging probe allows the
+# whole stop 60s -- so this catches a per-process external call without ever
+# being close enough to the real cost to go flaky.
+SCAN_BUDGET_SECONDS = 20.0
+
+
+class _UnreadableProcess:
+ """A process psutil can see but whose command line it cannot read.
+
+ ``process_iter`` fills a field it was denied with its ``ad_value``, which
+ defaults to ``None``. On Windows that is the ordinary outcome for every
+ process the current user cannot open, which is most of the system ones.
+ """
+
+ def __init__(self, pid: int) -> None:
+ self.info = {"pid": pid, "cmdline": None}
+
+ def cwd(self) -> None:
+ return None
+
+ def environ(self) -> dict:
+ return {}
+
+
+def test_the_service_scan_starts_no_external_process_per_scanned_process(monkeypatch):
+ """The scan must answer from what psutil already collected, or not at all.
+
+ Asserting the mechanism rather than a duration: a per-process shell launch
+ is the defect whatever it costs on the machine running the test, and a
+ timing assertion alone would be both flaky and silent about the cause.
+
+ Nothing is lost by refusing to look further. The scan exists to find
+ lock-less Avibe daemons, and those are processes this install started,
+ whose command line psutil can read. One it cannot read is, by construction,
+ not ours -- and the authoritative owner comes from the service lock, not
+ from this scan.
+ """
+
+ processes = [_UnreadableProcess(90000 + offset) for offset in range(64)]
+ launched = []
+
+ def record_launch(command, *args, **kwargs):
+ launched.append(command)
+ return SimpleNamespace(stdout="", stderr="", returncode=0)
+
+ monkeypatch.setattr(runtime.psutil, "process_iter", lambda attrs=None: list(processes))
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(runtime.subprocess, "run", record_launch)
+
+ assert runtime.service_processes() == []
+ assert launched == [], (
+ f"the scan started {len(launched)} external process(es) for {len(processes)} scanned processes: {launched[:2]}"
+ )
+
+
+def test_the_windows_command_lookup_cannot_hang_its_caller(monkeypatch):
+ """The single-pid diagnostic lookup keeps its shell, but on a leash.
+
+ Dropping it from the scan leaves it right for what it is actually for:
+ naming one specific process. It still runs on lifecycle paths such as
+ ``vibe stop``, though, so it must not be able to wait forever on a shell
+ that never answers.
+ """
+
+ calls = []
+
+ def record(command, **kwargs):
+ calls.append(kwargs)
+ return SimpleNamespace(stdout="", stderr="")
+
+ monkeypatch.setattr(runtime.subprocess, "run", record)
+
+ runtime._get_process_command_windows(4321)
+
+ assert calls, "the lookup never ran its shell, so this asserts nothing"
+ assert all(isinstance(call.get("timeout"), (int, float)) and call["timeout"] > 0 for call in calls), (
+ f"an unbounded external shell on a lifecycle path: {calls}"
+ )
+
+
[email protected](os.name != "nt", reason="only a real Windows process table holds enough unreadable processes")
+def test_the_service_scan_finishes_promptly_on_a_real_windows_process_table():
+ """The same claim again, end to end, on the platform that pays for it.
+
+ Read-only: it walks the process table and stops. The mechanism assertion
+ above is the primary signal; this one exists because the defect class this
+ release has kept hitting is a POSIX cost assumption that only a Windows
+ process table can expose, and no unit test of our own fakes can expose it.
+ """
+
+ walk_started = time.monotonic()
+ visible = len(list(runtime.psutil.process_iter(attrs=["pid", "cmdline"])))
+ walk_seconds = time.monotonic() - walk_started
+
+ # Price the budget off what this machine actually charges for the same walk
+ # rather than off a guess. `process_iter` never shells out, so the defect
+ # does not inflate this measurement and cannot buy itself room -- it only
+ # keeps a slow runner from failing a test about external processes.
+ budget = max(SCAN_BUDGET_SECONDS, walk_seconds * 4)
+ finished = threading.Event()
+
+ def scan() -> None:
+ try:
+ runtime.service_processes()
+ finally:
+ finished.set()
+
+ # Daemon on purpose: the bound says we stop waiting, not that we can call
+ # back a scan that is already busy launching shells.
+ threading.Thread(target=scan, daemon=True).start()
+
+ assert finished.wait(budget), (
+ f"service_processes() did not finish within {budget:.1f}s over {visible} processes, "
+ f"while the raw psutil walk of the same table took {walk_seconds:.2f}s"
+ )
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index 3a168880e..67cb94f8d 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -12,6 +12,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe import runtime
+def _spawned(process):
+ """Stand in for the spawn primitive, which hands a child over before returning it."""
+
+ def spawn(*args, hand_over=None, **kwargs):
+ if hand_over is not None:
+ hand_over(process)
+ return process
+
+ return spawn
+
+
class RuntimeServiceLockTests(unittest.TestCase):
def setUp(self):
self._extra_service_pids = patch("vibe.runtime.extra_service_process_pids", return_value=[])
@@ -63,8 +74,11 @@ class RuntimeServiceLockTests(unittest.TestCase):
pid_path = Path(tmpdir) / "service.pid"
pid_path.write_text("12345", encoding="utf-8")
- def fake_spawn(args, stdout_name, stderr_name, env=None):
- return SimpleNamespace(pid=67890, poll=lambda: None)
+ def fake_spawn(args, stdout_name, stderr_name, env=None, *, hand_over, **kwargs):
+ # The primitive hands the child over before it returns it.
+ process = SimpleNamespace(pid=67890, poll=lambda: None)
+ hand_over(process)
+ return process
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
with patch("vibe.runtime.pid_alive", return_value=True):
@@ -185,7 +199,7 @@ class RuntimeServiceLockTests(unittest.TestCase):
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
- with patch("vibe.runtime.spawn_service_background_process", return_value=process):
+ with patch("vibe.runtime.spawn_service_background_process", side_effect=_spawned(process)):
with patch("vibe.runtime.wait_for_service_pid", return_value=False):
with patch("vibe.runtime.pid_alive", return_value=True):
pid = runtime.start_service(wait_for_ready=False)
@@ -200,7 +214,7 @@ class RuntimeServiceLockTests(unittest.TestCase):
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
- with patch("vibe.runtime.spawn_service_background_process", return_value=process):
+ with patch("vibe.runtime.spawn_service_background_process", side_effect=_spawned(process)):
with patch("vibe.runtime.wait_for_service_pid", return_value=True) as wait_for_pid:
with patch("vibe.runtime.pid_alive", return_value=True):
pid = runtime.start_service(wait_for_ready=False, initial_ready_timeout=0)
@@ -216,7 +230,7 @@ class RuntimeServiceLockTests(unittest.TestCase):
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
- with patch("vibe.runtime.spawn_service_background_process", return_value=process):
+ with patch("vibe.runtime.spawn_service_background_process", side_effect=_spawned(process)):
with patch("vibe.runtime.wait_for_service_pid", return_value=False):
with patch("vibe.runtime.pid_alive", return_value=True):
with self.assertRaises(RuntimeError):
@@ -231,7 +245,7 @@ class RuntimeServiceLockTests(unittest.TestCase):
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):
- with patch("vibe.runtime.spawn_service_background_process", return_value=process):
+ with patch("vibe.runtime.spawn_service_background_process", side_effect=_spawned(process)):
with patch("vibe.runtime.wait_for_service_pid", side_effect=[False, True]) as wait_for_pid:
with patch("vibe.runtime.pid_alive", return_value=True):
pid = runtime.start_service()
@@ -1000,8 +1014,10 @@ class ServiceReadinessGateTests(unittest.TestCase):
if already_recorded:
pid_path.write_text(str(pid), encoding="utf-8")
- def fake_spawn(args, stdout_name, stderr_name, env=None, **kwargs):
- return SimpleNamespace(pid=pid, poll=lambda: None)
+ def fake_spawn(args, stdout_name, stderr_name, env=None, *, hand_over, **kwargs):
+ process = SimpleNamespace(pid=pid, poll=lambda: None)
+ hand_over(process)
+ return process
with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
diff --git a/tests/test_runtime_spawn_ownership.py b/tests/test_runtime_spawn_ownership.py
new file mode 100644
index 000000000..005e7b2c9
--- /dev/null
+++ b/tests/test_runtime_spawn_ownership.py
@@ -0,0 +1,254 @@
+"""A spawn either hands its caller a child the caller owns, or leaves no child.
+
+Each test starts a real, long-sleeping child and makes one step between
+``Popen`` and the handover fail. Before the rule, every one of them left that
+child running with nothing recording it: no pid file, no ``start_info``, so no
+rollback could find it. The assertion is on the process itself -- killed and
+reaped -- not on a mock having been called.
+"""
+
+from __future__ import annotations
+
+import errno
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from vibe import runtime
+
+MARKER = "avibe-spawn-ownership-probe"
+
+
+class _Spawned(list):
+ """The probe children, plus the log sinks started for them."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.sinks: list[subprocess.Popen] = []
+
+
+def spawned(monkeypatch, tmp_path: Path):
+ """Every real child started with the probe marker, still inspectable afterwards.
+
+ The spy is a real ``Popen`` subclass, so the log sinks and the child are
+ started exactly as in production; it only keeps a handle the code under test
+ would otherwise have dropped with its exception.
+ """
+
+ monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path / "runtime")
+ children = _Spawned()
+ real_popen = subprocess.Popen
+
+ class SpyPopen(real_popen):
+ def __init__(self, args, *rest, **kwargs):
+ super().__init__(args, *rest, **kwargs)
+ if any(MARKER in str(argument) for argument in args):
+ children.append(self)
+ elif "vibe.log_sink" in args:
+ children.sinks.append(self)
+
+ monkeypatch.setattr(runtime.subprocess, "Popen", SpyPopen)
+ yield children
+ for child in [*children, *children.sinks]:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=5)
+
+
+def _sleeper() -> list[str]:
+ return [sys.executable, "-c", "import time; time.sleep(60)", MARKER]
+
+
+def _assert_killed_and_reaped(children: list[subprocess.Popen]) -> None:
+ assert len(children) == 1, f"expected exactly one probe child, got {children}"
+ child = children[0]
+ assert child.returncode is not None, f"pid={child.pid} was left running after its spawn failed"
+ assert not runtime.pid_alive(child.pid)
+
+
+def _assert_log_sinks_released(spawned: _Spawned) -> None:
+ """Every parent-side handle was closed, so each sink saw end-of-file and exited."""
+
+ assert len(spawned.sinks) == 2, f"expected the two log sinks, got {spawned.sinks}"
+ for sink in spawned.sinks:
+ assert sink.wait(timeout=10) is not None
+
+
+def test_a_child_whose_pid_record_cannot_be_written_does_not_survive(spawned, tmp_path: Path) -> None:
+ # A real write failure: the record's directory does not exist.
+ pid_path = tmp_path / "missing" / "vibe-ui.pid"
+
+ with pytest.raises(FileNotFoundError):
+ runtime.spawn_background(_sleeper(), pid_path, "ui_stdout.log", "ui_stderr.log")
+
+ _assert_killed_and_reaped(spawned)
+ assert not pid_path.exists()
+ _assert_log_sinks_released(spawned)
+
+
+class _HandleThatFailsToClose:
+ """A parent-side handle whose close releases the descriptor, then raises.
+
+ That is what a buffered file does when its final flush fails: the
+ descriptor is gone, the error still propagates. ``Popen`` only needs
+ ``fileno()`` from it.
+ """
+
+ def __init__(self, real) -> None:
+ self._real = real
+
+ def fileno(self) -> int:
+ return self._real.fileno()
+
+ def close(self) -> None:
+ already_closed = self._real.closed
+ self._real.close()
+ if not already_closed:
+ raise OSError(errno.EIO, "injected: closing the parent's spawn handle failed")
+
+
[email protected]("failing_handle", ["stdin", "stdout_sink", "stderr_sink"])
+def test_a_child_whose_parent_handles_cannot_be_closed_does_not_survive(
+ spawned, monkeypatch, tmp_path: Path, failing_handle: str
+) -> None:
+ real_sinks = runtime._spawn_runtime_log_sinks # noqa: SLF001
+
+ def sinks_with_one_failing_close(stdout_path, stderr_path):
+ stdout_sink, stderr_sink = real_sinks(stdout_path, stderr_path)
+ target = {"stdout_sink": stdout_sink, "stderr_sink": stderr_sink}.get(failing_handle)
+ if target is not None:
+ target.stdin = _HandleThatFailsToClose(target.stdin)
+ return stdout_sink, stderr_sink
+
+ monkeypatch.setattr(runtime, "_spawn_runtime_log_sinks", sinks_with_one_failing_close)
+ if failing_handle == "stdin":
+ real_open = open
+
+ def open_with_failing_devnull(file, *rest, **kwargs):
+ handle = real_open(file, *rest, **kwargs)
+ return _HandleThatFailsToClose(handle) if file == runtime.os.devnull else handle
+
+ monkeypatch.setattr(runtime, "open", open_with_failing_devnull, raising=False)
+ pid_path = tmp_path / "vibe-ui.pid"
+
+ with pytest.raises(OSError) as raised:
+ runtime.spawn_background(_sleeper(), pid_path, "ui_stdout.log", "ui_stderr.log")
+
+ assert raised.value.errno == errno.EIO
+ _assert_killed_and_reaped(spawned)
+ # The handles close before the record, so a failed close never names a
+ # process that was then killed.
+ assert not pid_path.exists()
+ _assert_log_sinks_released(spawned)
+
+
+def test_a_service_whose_reservation_cannot_be_written_does_not_survive(
+ spawned, monkeypatch, tmp_path: Path
+) -> None:
+ launcher = _marked_service(tmp_path, monkeypatch)
+
+ def disk_full(pid: int) -> None:
+ raise OSError(errno.ENOSPC, "injected: no space left for the service reservation")
+
+ monkeypatch.setattr(runtime, "_record_service_pid_reservation", disk_full)
+ start_info = runtime.ProcessStartInfo()
+
+ with pytest.raises(OSError) as raised:
+ runtime.start_service(wait_for_ready=False, start_info=start_info, launcher=launcher)
+
+ assert raised.value.errno == errno.ENOSPC
+ _assert_killed_and_reaped(spawned)
+ # Nothing is recorded as created, and nothing is left for a reaper thread.
+ assert start_info.pid is None
+ assert spawned[0].pid not in runtime._SERVICE_START_PROCESSES # noqa: SLF001
+
+
+class _InterruptedCapture(runtime.ProcessStartInfo):
+ """A signal that lands after the child's record is written, before its capture.
+
+ It notes what the record said at that moment, so a test can show the
+ intrusion came where it was aimed rather than earlier.
+ """
+
+ def __init__(self, record: Path) -> None:
+ super().__init__()
+ self.record = record
+ self.record_at_intrusion: str | None = None
+
+ def capture(self, pid: int, *, reused: bool) -> int:
+ self.record_at_intrusion = self.record.read_text(encoding="utf-8")
+ raise KeyboardInterrupt
+
+
+def _marked_interpreter(tmp_path: Path) -> Path:
+ """A stand-in UI interpreter that only sleeps, named so the spy can see it."""
+
+ interpreter = tmp_path / f"{MARKER}-python"
+ interpreter.write_text("#!/bin/sh\nexec sleep 60\n", encoding="utf-8")
+ interpreter.chmod(0o755)
+ return interpreter
+
+
+def test_a_ui_interrupted_between_its_record_and_its_capture_does_not_survive(spawned, tmp_path: Path) -> None:
+ launcher = runtime.ServiceLauncher(python=str(_marked_interpreter(tmp_path)), main="unused")
+ pid_path = runtime.paths.get_runtime_ui_pid_path()
+ start_info = _InterruptedCapture(pid_path)
+
+ with pytest.raises(KeyboardInterrupt):
+ runtime.start_ui("127.0.0.1", 5123, wait_for_ready=False, start_info=start_info, launcher=launcher)
+
+ _assert_killed_and_reaped(spawned)
+ assert start_info.record_at_intrusion == str(spawned[0].pid)
+ # The record goes with the child, and nothing was captured as created.
+ assert not pid_path.exists()
+ assert start_info.pid is None
+ _assert_log_sinks_released(spawned)
+
+
+def _marked_service(tmp_path: Path, monkeypatch) -> runtime.ServiceLauncher:
+ # The service launch has no free argument slot, so the entry point's own
+ # name is what marks it.
+ script = tmp_path / f"{MARKER}.py"
+ script.write_text("import time\ntime.sleep(60)\n", encoding="utf-8")
+ # The real service a developer has running must not be seen as the holder.
+ monkeypatch.setattr(runtime, "extra_service_process_pids", lambda **kwargs: [])
+ monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: [])
+ return runtime.ServiceLauncher(python=sys.executable, main=str(script))
+
+
+def test_a_service_interrupted_between_its_reservation_and_its_capture_does_not_survive(
+ spawned, monkeypatch, tmp_path: Path
+) -> None:
+ launcher = _marked_service(tmp_path, monkeypatch)
+ reservation = runtime.paths.get_runtime_pid_path()
+ start_info = _InterruptedCapture(reservation)
+
+ with pytest.raises(KeyboardInterrupt):
+ runtime.start_service(wait_for_ready=False, start_info=start_info, launcher=launcher)
+
+ _assert_killed_and_reaped(spawned)
+ assert start_info.record_at_intrusion == str(spawned[0].pid)
+ assert not reservation.exists()
+ assert start_info.pid is None
+ assert spawned[0].pid not in runtime._SERVICE_START_PROCESSES # noqa: SLF001
+ _assert_log_sinks_released(spawned)
+
+
+def test_a_child_that_could_not_be_confirmed_dead_keeps_its_record(spawned, monkeypatch, tmp_path: Path) -> None:
+ # A kill that did not take leaves a live child; withdrawing its record too
+ # would leave it running with nothing that names it.
+ monkeypatch.setattr(runtime, "discard_spawned_child", lambda process: None)
+ launcher = runtime.ServiceLauncher(python=str(_marked_interpreter(tmp_path)), main="unused")
+ pid_path = runtime.paths.get_runtime_ui_pid_path()
+
+ with pytest.raises(KeyboardInterrupt):
+ runtime.start_ui(
+ "127.0.0.1", 5123, wait_for_ready=False, start_info=_InterruptedCapture(pid_path), launcher=launcher
+ )
+
+ assert len(spawned) == 1
+ assert spawned[0].poll() is None
+ assert pid_path.read_text(encoding="utf-8") == str(spawned[0].pid)
diff --git a/tests/test_service_lock_record.py b/tests/test_service_lock_record.py
new file mode 100644
index 000000000..a8ce141b4
--- /dev/null
+++ b/tests/test_service_lock_record.py
@@ -0,0 +1,258 @@
+"""The service lock must never make its own holder record unreadable.
+
+``service.lock`` is two things at once: the exclusion primitive, and the record
+naming who holds it. On POSIX that costs nothing -- ``fcntl.flock`` is advisory,
+so the bytes stay readable whether or not anyone holds the lock. On Windows a
+byte-range lock is mandatory and scoped to a HANDLE rather than to a process: an
+exclusive lock denies every other handle, including a second handle opened by
+the locking process itself, both read and write access to the locked range.
+
+Locking the bytes the record lives in therefore hid that record for exactly as
+long as the lock meant anything, and every reader in ``vibe.runtime`` treats an
+unreadable record as "nobody is holding this". A Windows service consequently
+could not be seen to have started by the process that launched it, and could not
+recognise itself as the lock owner, so it tore itself down over a lease it had
+never lost.
+
+Each test below asserts one consequence of that. They run on every platform:
+red on Windows until the lock byte moved past the record, green on POSIX before
+and after, where their job is to pin the semantics the Windows fix must not
+change.
+"""
+
+import json
+import os
+import sys
+import unittest
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from vibe import runtime
+
+
+class _HeldServiceLockTestCase(unittest.TestCase):
+ """Holds the real service lock over a temporary runtime directory.
+
+ Nothing here is faked: the lock is taken through the same entry point
+ ``main.py`` uses, so the handle under test is the one a live service holds.
+ Only the paths are redirected, and ``ensure_dirs`` is stubbed because its
+ bootstrap guard is about the real data directory, not about this lock.
+ """
+
+ def setUp(self) -> None:
+ self._tmp = TemporaryDirectory()
+ runtime_dir = Path(self._tmp.name) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ self.lock_path = runtime_dir / "service.lock"
+ self.pid_path = runtime_dir / "vibe.pid"
+ self._patches = [
+ patch("vibe.runtime.ensure_dirs", return_value=None),
+ patch(
+ "vibe.runtime.paths.get_runtime_service_lock_path",
+ return_value=self.lock_path,
+ ),
+ patch("vibe.runtime.paths.get_runtime_pid_path", return_value=self.pid_path),
+ ]
+ for started in self._patches:
+ started.start()
+ self.addCleanup(self._tmp.cleanup)
+ for started in reversed(self._patches):
+ self.addCleanup(started.stop)
+ self.addCleanup(runtime.release_service_instance_lock)
+ runtime.acquire_service_instance_lock()
+
+
+class ServiceLockRecordReadableWhileHeldTests(_HeldServiceLockTestCase):
+ def test_the_holder_record_is_readable_while_the_lock_is_held(self):
+ """The record only ever gets read while the lock is held.
+
+ Every caller asks "who holds this" of a lock that is, by construction,
+ currently held. A lock that hides its own record answers that question
+ with silence at the only moment the question is asked.
+ """
+
+ record = runtime.read_service_instance_lock_record()
+ self.assertIsNotNone(record)
+ self.assertEqual(record.get("pid"), os.getpid())
+
+ def test_a_probe_learns_the_holder_pid_rather_than_nothing(self):
+ """``service_instance_lock_available`` is how a second process finds out
+ who beat it to the lock. Returning ``None`` for the holder turns a
+ precise refusal into an anonymous one.
+ """
+
+ available, holder_pid = runtime.service_instance_lock_available()
+ self.assertFalse(available)
+ self.assertEqual(holder_pid, os.getpid())
+
+ def test_the_holder_recognises_itself_through_a_second_handle(self):
+ """This is the in-process two-handle case, and the expensive one.
+
+ ``current_process_owns_service_instance`` re-opens the lock file instead
+ of consulting the handle it already holds, so it reads the record back
+ through a handle that is not the one holding the lock. Reading ``False``
+ here is what makes a healthy service tear itself down for a lease it
+ never lost.
+ """
+
+ self.assertTrue(runtime.service_lock_held_by(os.getpid()))
+ self.assertTrue(runtime.current_process_owns_service_instance())
+
+ def test_a_launcher_can_see_the_service_it_just_spawned(self):
+ """The bounded wait a launcher runs against a freshly spawned service.
+
+ ``service_pid_recorded`` is the predicate behind that wait; when it can
+ never become true the launcher reports the service as having failed to
+ acquire a lock the service is in fact holding.
+ """
+
+ self.assertTrue(runtime.service_pid_recorded(os.getpid()))
+
+ def test_the_phase_the_holder_wrote_is_visible_to_a_watcher(self):
+ """An upgrade watcher waits for exactly this transition to call the new
+ release good. It is written through the locked handle and read back
+ through an unlocked one.
+ """
+
+ runtime.mark_service_instance_started()
+ self.assertTrue(runtime.service_instance_started(os.getpid()))
+
+ def test_the_lock_file_holds_the_record_and_nothing_else(self):
+ """Pins the on-disk shape against a fix that reserves bytes inside the
+ file rather than past it.
+
+ Keeping the locked byte at offset 0 and moving the record to offset 1
+ would also make ``_lock_file_pid`` work, and would break every reader
+ that takes the file at face value -- ``read_service_instance_lock_record``
+ among them, and a human running ``type service.lock`` as well.
+ """
+
+ payload = json.loads(self.lock_path.read_text(encoding="utf-8"))
+ self.assertEqual(payload.get("pid"), os.getpid())
+
+
+class ServiceLockStillExcludesTests(unittest.TestCase):
+ """Moving the Windows lock byte must not cost the lock its only real job."""
+
+ def test_the_lock_is_free_before_taken_during_and_free_again_after(self):
+ with TemporaryDirectory() as tmpdir:
+ runtime_dir = Path(tmpdir) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ lock_path = runtime_dir / "service.lock"
+ pid_path = runtime_dir / "vibe.pid"
+
+ with patch("vibe.runtime.ensure_dirs", return_value=None), patch(
+ "vibe.runtime.paths.get_runtime_service_lock_path",
+ return_value=lock_path,
+ ), patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ self.assertEqual(runtime.service_instance_lock_available(), (True, None))
+ runtime.acquire_service_instance_lock()
+ try:
+ available, _holder = runtime.service_instance_lock_available()
+ self.assertFalse(available)
+ finally:
+ runtime.release_service_instance_lock()
+ self.assertEqual(runtime.service_instance_lock_available(), (True, None))
+
+
[email protected](os.name == "nt", "POSIX locking path")
+class PosixServiceLockUnchangedTests(unittest.TestCase):
+ """The POSIX branch has no lock byte, and must not acquire one.
+
+ The Windows fix moves an offset that POSIX does not have and does not need,
+ because an advisory whole-file lock never denied a reader anything. This
+ pins that asymmetry so the platform with an installed base cannot be
+ silently migrated to a different locked range.
+ """
+
+ def test_posix_takes_an_advisory_whole_file_flock_at_offset_zero(self):
+ import fcntl
+
+ observed: list[tuple[int, int]] = []
+ real_flock = fcntl.flock
+
+ def _record(fd, operation):
+ observed.append((os.lseek(fd, 0, os.SEEK_CUR), operation))
+ return real_flock(fd, operation)
+
+ with TemporaryDirectory() as tmpdir:
+ runtime_dir = Path(tmpdir) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ lock_path = runtime_dir / "service.lock"
+ pid_path = runtime_dir / "vibe.pid"
+
+ with patch("vibe.runtime.ensure_dirs", return_value=None), patch(
+ "vibe.runtime.paths.get_runtime_service_lock_path",
+ return_value=lock_path,
+ ), patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path), patch(
+ "fcntl.flock", _record
+ ):
+ runtime.acquire_service_instance_lock()
+ runtime.release_service_instance_lock()
+
+ self.assertEqual(observed[0], (0, fcntl.LOCK_EX | fcntl.LOCK_NB))
+ self.assertEqual(observed[-1][1], fcntl.LOCK_UN)
+
+
[email protected](os.name == "nt", "Windows byte-range lock semantics")
+class WindowsMandatoryLockFactTests(unittest.TestCase):
+ """The platform fact the fix rests on, pinned so nobody re-derives it.
+
+ This asserts nothing about Avibe. It asserts that Windows denies a read of a
+ locked range through a second handle opened by the same process. If that
+ ever stops being true, the reason the service lock byte lives past the
+ record stops applying, and this is the test that will say so.
+ """
+
+ def test_a_second_handle_in_this_process_cannot_read_a_locked_byte(self):
+ import msvcrt
+
+ with TemporaryDirectory() as tmpdir:
+ target = Path(tmpdir) / "locked.bin"
+ target.write_bytes(b"payload")
+
+ with open(target, "r+b") as holder:
+ holder.seek(0)
+ msvcrt.locking(holder.fileno(), msvcrt.LK_NBLCK, 1)
+ try:
+ with open(target, "rb") as reader:
+ with self.assertRaises(OSError):
+ reader.read()
+ finally:
+ holder.seek(0)
+ msvcrt.locking(holder.fileno(), msvcrt.LK_UNLCK, 1)
+
+ self.assertEqual(target.read_bytes(), b"payload")
+
+ def test_a_byte_past_the_end_can_be_locked_without_hiding_the_content(self):
+ """The other half of the fix: a lock beyond end-of-file is legal, does
+ not extend the file, and leaves every byte a reader cares about
+ readable. The offset here is the service lock's own idea, written out
+ locally so this stays a statement about Windows rather than about us.
+ """
+
+ import msvcrt
+
+ past_any_record = 1 << 30
+
+ with TemporaryDirectory() as tmpdir:
+ target = Path(tmpdir) / "sentinel.bin"
+ target.write_bytes(b"payload")
+
+ with open(target, "r+b") as holder:
+ os.lseek(holder.fileno(), past_any_record, os.SEEK_SET)
+ msvcrt.locking(holder.fileno(), msvcrt.LK_NBLCK, 1)
+ try:
+ self.assertEqual(target.read_bytes(), b"payload")
+ finally:
+ os.lseek(holder.fileno(), past_any_record, os.SEEK_SET)
+ msvcrt.locking(holder.fileno(), msvcrt.LK_UNLCK, 1)
+
+ self.assertEqual(target.stat().st_size, len(b"payload"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.py
index 1896354c0..d9db86147 100644
--- a/tests/test_service_logging_handlers.py
+++ b/tests/test_service_logging_handlers.py
@@ -72,12 +72,15 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatc
# the full slow-start timeout and then raise.
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout=None: pid)
- def fake_spawn_service_background_process(args, stdout_name, stderr_name, env=None):
+ def fake_spawn_service_background_process(args, stdout_name, stderr_name, env=None, *, hand_over, **kwargs):
captured["args"] = args
captured["stdout_name"] = stdout_name
captured["stderr_name"] = stderr_name
captured["env"] = env
- return type("Process", (), {"pid": 12345, "poll": lambda self: None})()
+ process = type("Process", (), {"pid": 12345, "poll": lambda self: None})()
+ # The real primitive hands the child over before it returns.
+ hand_over(process)
+ return process
monkeypatch.setattr(runtime, "spawn_service_background_process", fake_spawn_service_background_process)
@@ -95,6 +98,7 @@ def test_spawn_background_detaches_stdin(monkeypatch, tmp_path):
sink_paths: list[Path] = []
monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
class FakeSink:
def __init__(self, path: Path):
@@ -121,12 +125,63 @@ def test_spawn_background_detaches_stdin(monkeypatch, tmp_path):
stdin = captured["kwargs"]["stdin"]
assert stdin.name == os.devnull
assert stdin.closed is True
- assert captured["kwargs"]["start_new_session"] is True
+ assert captured["kwargs"]["creationflags"] == 0x200
+ assert "start_new_session" not in captured["kwargs"]
assert captured["kwargs"]["stdout"].closed is True
assert captured["kwargs"]["stderr"].closed is True
assert sink_paths == [tmp_path / "stdout.log", tmp_path / "stderr.log"]
+def test_runtime_log_sink_uses_platform_isolation(monkeypatch, tmp_path):
+ captured: dict[str, object] = {}
+
+ class FakePopen:
+ def __init__(self, args, **kwargs):
+ captured["args"] = args
+ captured["kwargs"] = kwargs
+
+ monkeypatch.setattr(runtime.subprocess, "Popen", FakePopen)
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
+
+ runtime._spawn_runtime_log_sink(tmp_path / "runtime.log")
+
+ assert captured["kwargs"]["creationflags"] == 0x200
+ assert "start_new_session" not in captured["kwargs"]
+
+
+def test_generic_background_spawn_uses_platform_isolation(monkeypatch, tmp_path):
+ captured: dict[str, object] = {}
+ sink_paths: list[Path] = []
+
+ monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
+
+ class FakeSink:
+ def __init__(self, path: Path):
+ self.stdin = path.open("wb")
+
+ def fake_sinks(stdout_path: Path, stderr_path: Path):
+ sink_paths.extend((stdout_path, stderr_path))
+ return FakeSink(tmp_path / "generic-stdout.pipe"), FakeSink(tmp_path / "generic-stderr.pipe")
+
+ class FakePopen:
+ pid = 24680
+
+ def __init__(self, args, **kwargs):
+ captured["args"] = args
+ captured["kwargs"] = kwargs
+
+ monkeypatch.setattr(runtime, "_spawn_runtime_log_sinks", fake_sinks)
+ monkeypatch.setattr(runtime.subprocess, "Popen", FakePopen)
+ pid_path = tmp_path / "ui.pid"
+
+ assert runtime.spawn_background(["python3", "ui.py"], pid_path, "ui-out.log", "ui-err.log") == 24680
+ assert captured["kwargs"]["creationflags"] == 0x200
+ assert "start_new_session" not in captured["kwargs"]
+ assert pid_path.read_text(encoding="utf-8") == "24680"
+ assert sink_paths == [tmp_path / "ui-out.log", tmp_path / "ui-err.log"]
+
+
def test_main_import_does_not_load_controller() -> None:
code = "import sys; import main; raise SystemExit(1 if 'core.controller' in sys.modules else 0)"
result = subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[1], check=False)
diff --git a/tests/test_skill_observability.py b/tests/test_skill_observability.py
index 7ddd87b1f..f20460058 100644
--- a/tests/test_skill_observability.py
+++ b/tests/test_skill_observability.py
@@ -486,15 +486,23 @@ async def test_internal_server_owns_recorder_cleanup(engine, monkeypatch, tmp_pa
if exit_mode == "cancel":
await asyncio.Event().wait()
- def bind_socket(_path):
- if exit_mode == "bind_error":
- raise OSError("socket unavailable")
- return listener, tmp_path / "dispatch.sock"
+ host = SimpleNamespace(
+ instance_id=None,
+ bearer_token=None,
+ bind=Mock(
+ side_effect=(
+ OSError("socket unavailable")
+ if exit_mode == "bind_error"
+ else lambda: SimpleNamespace(listener=listener)
+ )
+ ),
+ publish=Mock(),
+ cleanup=Mock(side_effect=lambda bound: bound.listener.close()),
+ )
monkeypatch.setattr(internal_server, "_create_controller_loop_server", lambda _config: SimpleNamespace(serve=serve))
- monkeypatch.setattr(internal_server, "_bind_socket", bind_socket)
+ monkeypatch.setattr(internal_server.control_ipc, "select_control_ipc_host", lambda **_: host)
monkeypatch.setattr(internal_server, "_write_internal_server_status", Mock())
- monkeypatch.setattr(internal_server, "_remove_owned_socket", Mock())
if exit_mode != "recovery_cancel":
controller._delivery_recovery_complete.set()
task = asyncio.create_task(internal_server.serve(controller))
@@ -520,6 +528,7 @@ async def test_internal_server_owns_recorder_cleanup(engine, monkeypatch, tmp_pa
if exit_mode not in {"recovery_cancel", "bind_error"}:
assert counts(engine) == (1, 1)
listener.close.assert_called_once()
+ host.cleanup.assert_called_once()
def test_config_flag_is_strict_and_serialized():
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 6f9cd481f..045ea81bd 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1,5 +1,6 @@
import asyncio
import json
+import subprocess
import time
from dataclasses import dataclass
from types import SimpleNamespace
@@ -21,7 +22,7 @@ from config import paths
from config.v2_settings import ChannelSettings, SettingsStore
from core.vibe_agents import VibeAgentStore
from core import chat_discovery
-from vibe import api, backend_model_catalog
+from vibe import api, backend_model_catalog, cli_paths
from vibe.opencode_config import parse_jsonc_object
@@ -1978,16 +1979,17 @@ def test_resolve_cli_path_fast_probe_never_queries_npm(monkeypatch, tmp_path):
def only_tmp_binaries(monkeypatch, tmp_path):
"""Make CLI discovery hermetic: only executables under ``tmp_path`` count as
installed, so the runner's real ``/usr/local/bin/{npm,codex}`` (or a dev box's
- homebrew/nvm binaries) can't leak into detection. ``api._candidate_cli_paths``
+ homebrew/nvm binaries) can't leak into detection. ``cli_paths``
scans hardcoded common bin dirs (``/usr/local/bin``, ``/opt/homebrew/bin``)
that these tests cannot otherwise neutralize; without this they pass locally
but fail on a CI runner that has a real npm installed."""
- real_is_exec = api._is_executable_file
- monkeypatch.setattr(
- api,
- "_is_executable_file",
- lambda p: str(p).startswith(str(tmp_path)) and real_is_exec(p),
- )
+ real_is_exec = cli_paths._is_executable_file
+
+ def is_fixture_executable(path):
+ return str(path).startswith(str(tmp_path)) and real_is_exec(path)
+
+ monkeypatch.setattr(api, "_is_executable_file", is_fixture_executable)
+ monkeypatch.setattr(cli_paths, "_is_executable_file", is_fixture_executable)
def test_detect_cli_finds_npm_in_nvm(monkeypatch, tmp_path, only_tmp_binaries):
@@ -2108,6 +2110,307 @@ def test_detect_cli_finds_codex_in_npm_global_prefix(monkeypatch, tmp_path, only
assert result["path"] == str(codex_path)
+def test_install_agent_blocks_private_desktop_codex_self_update(monkeypatch, tmp_path):
+ runtime_root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
+ codex_path = runtime_root / "tools" / "bin" / "codex"
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ROOT", str(runtime_root))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _binary: str(codex_path))
+ monkeypatch.setattr(
+ api.subprocess,
+ "Popen",
+ lambda *_args, **_kwargs: pytest.fail("desktop-managed Codex must not self-update"),
+ )
+
+ result = api.install_agent("codex")
+
+ assert result == {
+ "ok": False,
+ "code": "desktop_managed_backend",
+ "message": (
+ "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. "
+ "Reopen the current desktop app to install it privately."
+ ),
+ "output": None,
+ "path": str(codex_path),
+ }
+
+
+def test_backend_runtime_skips_latest_probe_for_private_desktop_codex(monkeypatch, tmp_path):
+ runtime_root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
+ codex_path = runtime_root / "tools" / "bin" / "codex"
+ config = SimpleNamespace(
+ agents=SimpleNamespace(
+ codex=SimpleNamespace(enabled=True, cli_path=str(codex_path))
+ )
+ )
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ROOT", str(runtime_root))
+ monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _binary: str(codex_path))
+ monkeypatch.setattr(api, "_cached_version", lambda _name, _path: "1.2.3")
+ monkeypatch.setattr(
+ api,
+ "_cached_latest",
+ lambda _name: pytest.fail("desktop-managed Codex must not query npm for updates"),
+ )
+ monkeypatch.setattr(api, "_codex_process_status", lambda _path: "stopped")
+
+ result = api.get_backend_runtime("codex")
+
+ assert result["current_version"] == "1.2.3"
+ assert result["latest_version"] is None
+ assert result["has_update"] is False
+ assert result["managed_by"] == "desktop"
+
+
+def test_install_agent_upgrades_exact_configured_external_path(monkeypatch, tmp_path):
+ external = tmp_path / "custom" / "claude"
+ external.parent.mkdir()
+ external.write_text("#!/bin/sh\n", encoding="utf-8")
+ external.chmod(0o755)
+ config = SimpleNamespace(
+ agents=SimpleNamespace(claude=SimpleNamespace(cli_path=str(external)))
+ )
+ resolved: list[str] = []
+ commands: list[list[str]] = []
+
+ def fake_resolve(value):
+ resolved.append(value)
+ return str(external) if value == str(external) else None
+
+ def fake_run(command, **_kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0, "updated", "")
+
+ monkeypatch.setattr(api, "load_config", lambda: config)
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+ monkeypatch.setattr(api, "desktop_backend_toolchain", lambda: object())
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda _path: False)
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api.subprocess, "Popen", _PopenFromRun)
+ monkeypatch.setattr(api, "_persist_agent_cli_path", lambda *_args, **_kwargs: str(external))
+ monkeypatch.setattr(
+ api,
+ "install_desktop_backend",
+ lambda *_args, **_kwargs: pytest.fail("valid external CLI must win"),
+ )
+
+ result = api.install_agent("claude")
+
+ assert result["ok"] is True
+ assert result["path"] == str(external)
+ assert commands == [[str(external), "update"]]
+ assert resolved == [str(external), str(external)]
+
+
+def test_install_agent_uses_private_desktop_installer_when_external_is_missing(monkeypatch, tmp_path):
+ installed = tmp_path / "backends" / "codex" / "releases" / "new" / "codex"
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+
+ config = api.V2Config.default()
+ config.agents.codex.cli_path = "codex"
+ config.save()
+ invalidated: list[str] = []
+
+ def fake_install(name, *, activate):
+ assert name == "codex"
+ assert activate(str(installed)) is None
+ return SimpleNamespace(path=str(installed), version="1.2.3", output="installed")
+
+ monkeypatch.setattr(api, "resolve_cli_path", lambda value: None)
+ monkeypatch.setattr(api, "desktop_backend_toolchain", lambda: object())
+ monkeypatch.setattr(api, "install_desktop_backend", fake_install)
+ monkeypatch.setattr(api, "_invalidate_version_cache", invalidated.append)
+ monkeypatch.setattr(
+ api.subprocess,
+ "Popen",
+ lambda *_args, **_kwargs: pytest.fail("system installer must not run"),
+ )
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is True
+ assert result["managed_by"] == "desktop"
+ assert result["path"] == str(installed)
+ assert result["message"] == "Codex installed successfully."
+ assert api.V2Config.load().agents.codex.cli_path == str(installed)
+ assert invalidated == ["codex"]
+
+
+def test_desktop_backend_install_localizes_structured_failure(monkeypatch):
+ monkeypatch.setattr(api, "load_config", lambda: SimpleNamespace(language="zh"))
+
+ def fail_install(*_args, **_kwargs):
+ raise api.DesktopBackendError(
+ "Desktop backend install failed (exit code 1)",
+ code="npm_install_failed",
+ output="npm failed",
+ )
+
+ monkeypatch.setattr(api, "install_desktop_backend", fail_install)
+
+ result = api._run_desktop_backend_install("claude", lambda output: output)
+
+ assert result == {
+ "ok": False,
+ "code": "npm_install_failed",
+ "message": "无法安装 Claude Code。",
+ "output": "npm failed",
+ }
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_desktop_runtime_does_not_fall_back_to_global_installer(monkeypatch, backend):
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setattr(api, "load_config", lambda: SimpleNamespace(language="en"))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _value: None)
+ monkeypatch.setattr(
+ api,
+ "install_desktop_backend",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(
+ api.DesktopBackendError(
+ "private toolchain unavailable",
+ code="desktop_toolchain_unavailable",
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ api.subprocess,
+ "Popen",
+ lambda *_args, **_kwargs: pytest.fail("desktop Runtime must not run a global installer"),
+ )
+
+ result = api.install_agent(backend)
+
+ assert result["ok"] is False
+ assert result["code"] == "desktop_toolchain_unavailable"
+ assert result["message"] == "The desktop backend installer is unavailable."
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_install_agent_updates_existing_private_backend(monkeypatch, tmp_path, backend):
+ existing = tmp_path / "backends" / backend / "releases" / "old" / backend
+ config = SimpleNamespace(
+ agents=SimpleNamespace(**{backend: SimpleNamespace(cli_path=str(existing))})
+ )
+ calls: list[str] = []
+
+ monkeypatch.setattr(api, "load_config", lambda: config)
+ monkeypatch.setattr(api, "resolve_cli_path", lambda value: str(existing))
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda path: path == str(existing))
+ monkeypatch.setattr(
+ api,
+ "_run_desktop_backend_install",
+ lambda name, _truncate: calls.append(name) or {"ok": True, "path": "managed"},
+ )
+
+ result = api.install_agent(backend)
+
+ assert result["ok"] is True
+ assert calls == [backend]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_install_agent_never_upgrades_an_external_cli_for_a_missing_private_backend(
+ monkeypatch, tmp_path, backend
+):
+ """A deleted private backend must not hand the upgrade to the user's own CLI.
+
+ The configured path still names the backend this Runtime installed; only the
+ executable is gone. ``resolve_cli_path`` then falls back to the bare name on
+ PATH and finds whatever the user has installed themselves. Deciding
+ ownership from that result alone ran ``claude update`` / the Codex npm
+ upgrade / ``opencode upgrade`` against a binary this Runtime does not own --
+ the one thing an app-private backend promises never to touch -- and the
+ fail-closed guard further down was never reached, because something had
+ resolved.
+ """
+
+ missing = tmp_path / "backends" / backend / "releases" / "old" / backend
+ external = tmp_path / "usr" / "local" / "bin" / backend
+ config = SimpleNamespace(
+ agents=SimpleNamespace(**{backend: SimpleNamespace(cli_path=str(missing))})
+ )
+ managed: list[str] = []
+
+ def never_runs(*args, **kwargs):
+ raise AssertionError(f"the user's own {backend} was invoked: {args} {kwargs}")
+
+ monkeypatch.setattr(api, "load_config", lambda: config)
+ # Exactly what discovery does once the configured executable is gone.
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _value: str(external))
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda path: path == str(missing))
+ monkeypatch.setattr(api, "is_private_desktop_runtime_path", lambda _path: False)
+ monkeypatch.setattr(api, "_run_install_command", never_runs)
+ monkeypatch.setattr(api.subprocess, "run", never_runs)
+ monkeypatch.setattr(api.subprocess, "Popen", never_runs)
+ monkeypatch.setattr(
+ api,
+ "_run_desktop_backend_install",
+ lambda name, _truncate: managed.append(name) or {"ok": True, "path": "managed"},
+ )
+
+ result = api.install_agent(backend)
+
+ assert result["ok"] is True
+ assert managed == [backend], "the missing private backend was not reinstalled privately"
+
+
+def test_install_agent_blocks_a_missing_private_runtime_codex_without_reaching_the_external_one(
+ monkeypatch, tmp_path
+):
+ """Same hole, one branch over: the older Runtime's Codex tree.
+
+ Nothing installs it back here -- that Runtime is gone -- so the honest answer
+ names the path it refused, not the external binary discovery substituted.
+ """
+
+ runtime_root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
+ missing = runtime_root / "tools" / "bin" / "codex"
+ external = tmp_path / "usr" / "local" / "bin" / "codex"
+ config = SimpleNamespace(agents=SimpleNamespace(codex=SimpleNamespace(cli_path=str(missing))))
+
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ROOT", str(runtime_root))
+ monkeypatch.setattr(api, "load_config", lambda: config)
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _value: str(external))
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda _path: False)
+ monkeypatch.setattr(api, "desktop_backend_toolchain", lambda: None)
+ monkeypatch.setattr(
+ api.subprocess,
+ "Popen",
+ lambda *_args, **_kwargs: pytest.fail("a desktop-managed Codex must not self-update"),
+ )
+
+ result = api.install_agent("codex")
+
+ assert result["ok"] is False
+ assert result["code"] == "desktop_managed_backend"
+ assert result["path"] == str(missing)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_backend_runtime_checks_updates_for_private_backend(monkeypatch, tmp_path, backend):
+ managed = tmp_path / "backends" / backend / "releases" / "one" / backend
+ config = SimpleNamespace(
+ agents=SimpleNamespace(
+ **{backend: SimpleNamespace(enabled=True, cli_path=str(managed))}
+ )
+ )
+ monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _value: str(managed))
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda path: path == str(managed))
+ monkeypatch.setattr(api, "is_private_desktop_runtime_path", lambda _path: False)
+ monkeypatch.setattr(api, "_cached_version", lambda _name, _path: "1.0.0")
+ monkeypatch.setattr(api, "_cached_latest", lambda _name: "1.1.0")
+ monkeypatch.setattr(api, "_opencode_process_status", lambda: "stopped")
+ monkeypatch.setattr(api, "_codex_process_status", lambda _path: "stopped")
+
+ result = api.get_backend_runtime(backend)
+
+ assert result["managed_by"] == "desktop"
+ assert result["latest_version"] == "1.1.0"
+ assert result["has_update"] is True
+
+
def test_resolve_cli_paths_queries_npm_prefix_once_for_a_backend_batch(
monkeypatch,
tmp_path,
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 0629d054f..ae4439c83 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -253,13 +253,16 @@ def test_archive_http_rpc_waits_for_accepted_durable_outcome(monkeypatch, tmp_pa
}
return await httpx.ASGITransport(app=internal_app).handle_async_request(request)
- async def verified(_path):
- return tmp_path / "test-only.sock"
+ async def resolved(_path):
+ return internal_client.control_ipc.ControlIpcClientEndpoint(
+ transport="unix",
+ socket_path=tmp_path / "test-only.sock",
+ )
async def noop(*args, **kwargs):
return None
- monkeypatch.setattr(internal_client, "_verified_socket_path_async", verified)
+ monkeypatch.setattr(internal_client, "_resolve_endpoint_async", resolved)
monkeypatch.setattr(internal_client.httpx, "AsyncHTTPTransport", lambda **kwargs: ArchiveTransport())
monkeypatch.setattr(ui_server, "_archive_cancel_turn", noop)
client = app.test_client()
@@ -1437,6 +1440,37 @@ def test_normalize_response_supports_body_headers_tuple():
assert response.body == b"ok"
[email protected]("started_at", [None, "2026-07-04T00:00:01+00:00"])
[email protected]("completed_at", [None, "2026-07-04T00:00:02+00:00"])
+def test_harness_run_detail_preserves_stored_duration_timestamps(started_at, completed_at):
+ from storage.background import SQLiteBackgroundTaskStore
+
+ ensure_sqlite_state()
+ store = SQLiteBackgroundTaskStore()
+ try:
+ store.enqueue_run(
+ {
+ "id": "run-duration",
+ "run_type": "agent_run",
+ "status": "succeeded",
+ "created_at": "2026-07-04T00:00:00+00:00",
+ "updated_at": "2026-07-04T00:01:02+00:00",
+ "started_at": started_at,
+ "completed_at": completed_at,
+ }
+ )
+ finally:
+ store.close()
+
+ response = app.test_client().get("/api/harness/runs/run-duration")
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["ok"] is True
+ assert payload["run"]["started_at"] == started_at
+ assert payload["run"]["completed_at"] == completed_at
+
+
def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):
from storage.background import SQLiteBackgroundTaskStore
@@ -2217,6 +2251,30 @@ def test_changed_agent_backend_runtimes_uses_backend_runtime_projection():
assert ui_server._changed_agent_backend_runtimes(None, current, {"agents": changed_payload["agents"]}) == []
+def test_changed_agent_backend_runtimes_keeps_saved_selector_changes_visible(monkeypatch, tmp_path):
+ from config.v2_config import V2Config
+
+ resolved = tmp_path / ".local" / "bin" / "claude"
+ resolved.parent.mkdir(parents=True)
+ resolved.write_text("#!/bin/sh\n", encoding="utf-8")
+ resolved.chmod(0o755)
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setattr("vibe.cli_paths.resolve_cli_path", lambda _selector: str(resolved))
+
+ payload = _full_config_payload()
+ payload["agents"]["claude"]["cli_path"] = "claude"
+ previous = V2Config.from_payload(payload)
+ changed_payload = json.loads(json.dumps(payload))
+ changed_payload["agents"]["claude"]["cli_path"] = str(resolved)
+ current = V2Config.from_payload(changed_payload)
+
+ assert ui_server._changed_agent_backend_runtimes(
+ previous,
+ current,
+ {"agents": changed_payload["agents"]},
+ ) == ["claude"]
+
+
def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path):
"""Scenario: AUTH-SETUP-902."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index 286064e25..9e23575b6 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -7,7 +7,7 @@ from unittest.mock import Mock
import pytest
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
-from vibe import api
+from vibe import api, desktop_backends
from vibe.ui_server import app
from tests.ui_server_test_helpers import csrf_headers
@@ -156,25 +156,31 @@ def test_dependency_install_route_allows_model_hub_engine(monkeypatch, tmp_path)
assert response.get_json()["backend"] == "model-hub-engine"
-def test_install_job_fails_when_runtime_refresh_fails(monkeypatch):
- monkeypatch.setattr(api, "is_agent_backend", lambda name: name == "codex")
- monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == "codex")
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_install_job_fails_when_runtime_refresh_fails(monkeypatch, backend):
+ monkeypatch.setattr(api, "is_agent_backend", lambda name: name == backend)
+ monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == backend)
monkeypatch.setattr(api, "_agent_runtime_fingerprint", lambda name: None)
monkeypatch.setattr(
api,
"install_agent",
- lambda name: {"ok": True, "message": "Installed", "output": "done", "path": "/usr/local/bin/codex"},
+ lambda name: {
+ "ok": True,
+ "message": "Installed",
+ "output": "done",
+ "path": f"/usr/local/bin/{backend}",
+ },
)
monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": False, "message": "refresh timeout"})
with api._AGENT_INSTALL_JOB_LOCK:
api._AGENT_INSTALL_JOBS.clear()
api._AGENT_INSTALL_LATEST_BY_BACKEND.clear()
- started = api.start_agent_install_job("codex")
+ started = api.start_agent_install_job(backend)
deadline = time.time() + 2.0
result = {}
while time.time() < deadline:
- result = api.get_agent_install_job(started["job_id"], backend="codex")
+ result = api.get_agent_install_job(started["job_id"], backend=backend)
if result.get("status") != "running":
break
time.sleep(0.01)
@@ -404,3 +410,11 @@ def test_install_job_dedupes_running_backend(monkeypatch):
assert second["job_id"] == first["job_id"]
assert second["status"] == "running"
assert calls == ["codex"]
+ private_install_budget = (
+ desktop_backends.DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS
+ + desktop_backends.DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS
+ + desktop_backends.DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS
+ + desktop_backends.DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS
+ + 4.0
+ )
+ assert first["poll_timeout_seconds"] > private_install_budget
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 8a2ea0826..8252a7790 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -296,6 +296,43 @@ def test_set_show_runtime_manager_stops_previous_manager():
assert second.stopped is True
+def test_get_show_runtime_manager_initializes_once_across_threads(monkeypatch):
+ import core.show_runtime as srt
+
+ srt.set_show_runtime_manager_for_tests(None)
+ constructor_entered = threading.Event()
+ release_constructor = threading.Event()
+ constructor_calls = 0
+
+ class _Manager:
+ def __init__(self):
+ nonlocal constructor_calls
+ constructor_calls += 1
+ constructor_entered.set()
+ assert release_constructor.wait(timeout=2)
+
+ def stop(self):
+ return None
+
+ monkeypatch.setattr(srt, "ShowRuntimeManager", _Manager)
+ managers = []
+ threads = [threading.Thread(target=lambda: managers.append(srt.get_show_runtime_manager())) for _ in range(2)]
+ for thread in threads:
+ thread.start()
+ assert constructor_entered.wait(timeout=2)
+ release_constructor.set()
+ for thread in threads:
+ thread.join(timeout=2)
+
+ try:
+ assert all(not thread.is_alive() for thread in threads)
+ assert constructor_calls == 1
+ assert len(managers) == 2
+ assert managers[0] is managers[1]
+ finally:
+ srt.set_show_runtime_manager_for_tests(None)
+
+
def _create_show_page(session_id: str, visibility: str) -> str | None:
page_dir = ensure_show_page_dir(session_id)
(page_dir / "index.html").write_text("<!doctype html><title>Show</title><h1>Show Page</h1>", encoding="utf-8")
@@ -11928,6 +11965,49 @@ def test_show_runtime_manager_status_does_not_read_manifest_for_legacy_sources(t
assert status["reason"] is None
+def test_show_runtime_retired_github_source_uses_manifest_prepare_contract(monkeypatch, tmp_path):
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ runtime_source="github",
+ )
+ command = ["/bin/node", str(tmp_path / "runtime.js")]
+ installs = []
+
+ def install(*, force, offline):
+ installs.append((force, offline))
+ return command
+
+ monkeypatch.setattr(manager, "_install_managed_runtime_locked", install)
+
+ assert manager.runtime_source == "manifest-cache"
+ assert manager.prepare()["command"] == command
+ assert installs == [(False, False)]
+
+ assert manager.prepare(force=True)["command"] == command
+ assert installs == [(False, False), (True, False)]
+
+
+def test_show_runtime_prepare_uses_current_archive_install_contract(monkeypatch, tmp_path):
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ runtime_source="archive",
+ )
+ command = ["/bin/node", str(tmp_path / "runtime.js")]
+ installs = []
+
+ def install(*, force, offline):
+ installs.append((force, offline))
+ return command
+
+ monkeypatch.setattr(manager, "_install_managed_runtime_locked", install)
+
+ assert manager.prepare()["command"] == command
+ assert asyncio.run(manager._resolve_managed_command()) == command
+ assert installs == [(False, False)]
+
+
def test_show_runtime_manager_can_disable_auto_install(tmp_path):
manager = ShowRuntimeManager(
workspace_root=tmp_path / "show",
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 4eb6dfe5c..b51eaecc3 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -7,6 +7,7 @@ import subprocess
import sys
from types import SimpleNamespace
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
@@ -1001,6 +1002,24 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
}
+def test_do_upgrade_rejects_desktop_managed_runtime(monkeypatch):
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "true")
+ monkeypatch.setattr(api.V2Config, "load", lambda: SimpleNamespace(language="en"))
+ monkeypatch.setattr(
+ api,
+ "build_upgrade_plan",
+ lambda **_kwargs: (_ for _ in ()).throw(AssertionError("must not build an upgrade plan")),
+ )
+
+ assert api.do_upgrade() == {
+ "ok": False,
+ "message": "This Runtime is managed by the Avibe desktop app.",
+ "output": None,
+ "restarting": False,
+ "code": "desktop_managed_runtime",
+ }
+
+
def test_do_upgrade_auto_restart_does_not_block_on_runtime_prepare(monkeypatch):
plan = UpgradePlan(
command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
@@ -1216,6 +1235,42 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
}
+def test_cmd_upgrade_rejects_desktop_managed_runtime(monkeypatch, capsys):
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "yes")
+ monkeypatch.setattr(cli.V2Config, "load", lambda: SimpleNamespace(language="en"))
+ monkeypatch.setattr(
+ cli,
+ "get_latest_version",
+ lambda: (_ for _ in ()).throw(AssertionError("must not check PyPI")),
+ )
+
+ assert cli.cmd_upgrade() == 0
+ assert "Update the app to update Avibe." in capsys.readouterr().out
+
+
+def test_cmd_check_update_reports_desktop_managed_runtime(monkeypatch, capsys):
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "on")
+ monkeypatch.setattr(cli.V2Config, "load", lambda: SimpleNamespace(language="en"))
+ monkeypatch.setattr(
+ cli,
+ "get_latest_version",
+ lambda: (_ for _ in ()).throw(AssertionError("must not check PyPI")),
+ )
+
+ assert cli.cmd_check_update() == 0
+ assert "Updates are delivered with the Avibe desktop app." in capsys.readouterr().out
+
+
+def test_desktop_managed_runtime_messages_follow_configured_language(monkeypatch, capsys):
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setattr(cli.V2Config, "load", lambda: SimpleNamespace(language="zh"))
+ monkeypatch.setattr(api.V2Config, "load", lambda: SimpleNamespace(language="zh"))
+
+ assert cli.cmd_check_update() == 0
+ assert "更新由 Avibe 桌面应用统一提供。" in capsys.readouterr().out
+ assert api.do_upgrade()["message"] == "此 Runtime 由 Avibe 桌面应用管理。"
+
+
def test_cmd_upgrade_running_runtime_honors_show_runtime_skip_for_restart(monkeypatch):
plan = UpgradePlan(
command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
diff --git a/tests/test_version_identity.py b/tests/test_version_identity.py
index 519672f73..bedfb3e2c 100644
--- a/tests/test_version_identity.py
+++ b/tests/test_version_identity.py
@@ -61,6 +61,24 @@ def test_source_build_skips_background_package_update_check(monkeypatch, tmp_pat
}
+def test_desktop_managed_runtime_skips_background_package_update_check(monkeypatch) -> None:
+ monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setattr("vibe.__version__", "3.0.6", raising=False)
+ monkeypatch.setattr(
+ update_checker.urllib.request,
+ "urlopen",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("desktop Runtime must not query PyPI")),
+ )
+
+ assert update_checker._fetch_pypi_version_sync() == {
+ "current": "3.0.6",
+ "latest": None,
+ "has_update": False,
+ "error": None,
+ }
+
+
def test_packaged_install_keeps_semantic_update_behavior(monkeypatch) -> None:
expected = {"current": "3.0.6", "latest": "3.0.7", "has_update": True, "error": None}
monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)
@@ -70,6 +88,26 @@ def test_packaged_install_keeps_semantic_update_behavior(monkeypatch) -> None:
assert api.get_version_info() == {**expected, "build": {"kind": "package"}}
+def test_desktop_managed_runtime_skips_package_update_check(monkeypatch) -> None:
+ monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setattr("vibe.__version__", "3.0.6", raising=False)
+ monkeypatch.setattr(
+ api,
+ "get_latest_version_info",
+ lambda _current: (_ for _ in ()).throw(AssertionError("desktop Runtime must not query PyPI")),
+ )
+
+ assert api.get_version_info() == {
+ "current": "3.0.6",
+ "latest": None,
+ "has_update": False,
+ "error": None,
+ "build": {"kind": "package"},
+ "managed_by": "desktop",
+ }
+
+
def test_configured_missing_metadata_stays_a_source_build(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("VIBE_BUILD_METADATA_PATH", str(tmp_path / "not-written-yet.json"))
monkeypatch.setattr("vibe.__version__", "3.0.6rc5", raising=False)
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 1f164567c..d51f0bc80 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -18,6 +18,7 @@ from unittest.mock import patch
from config import paths
from vibe import runtime
from vibe import cli
+from vibe import internal_client
from vibe import remote_access
@@ -692,6 +693,152 @@ def test_cmd_restart_schedules_supervisor_by_default(monkeypatch):
assert calls == [{"delay_seconds": 0.0, "vibe_path": "/usr/local/bin/vibe", "trigger": "cli"}]
+def _startup_receipt_payload():
+ return {
+ "schema_version": 1, "outcome": "started",
+ "service_pid": 1234, "ui_pid": 5678,
+ "service_create_unix_ms": 1789010100.1235 * 1000,
+ "ui_create_unix_ms": 1789010100.4565 * 1000,
+ }
+
+
+def receipt_shutdown(monkeypatch):
+ pid_path = paths.get_runtime_pid_path()
+ pid_path.parent.mkdir(parents=True, exist_ok=True)
+ pid_path.write_text("1234\n", encoding="utf-8")
+ calls = []
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1789010100.1235)
+ monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: True)
+ monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("service") or True)
+ monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("ui") or True)
+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda: calls.append("opencode") or True)
+ monkeypatch.setattr(cli, "_write_status", lambda *args: calls.append(args))
+ return SimpleNamespace(pid_path=pid_path, calls=calls)
+
+
[email protected]("delta_ms", [-2, -1.999, 0, 1.999, 2])
[email protected]("outcome", ["started", "reused"])
+def test_cmd_stop_receipt_matches_with_inclusive_tolerance(capsys, receipt_shutdown, delta_ms, outcome):
+ receipt = _startup_receipt_payload()
+ receipt["service_create_unix_ms"] += delta_ms
+ receipt["outcome"] = outcome
+
+ assert cli.cmd_stop(receipt=json.dumps(receipt)) == 0
+
+ assert receipt_shutdown.calls == ["service", "ui", "opencode", ("stopped",)]
+ output = capsys.readouterr()
+ assert output.out == "OpenCode server stopped\n"
+ assert output.err == ""
+
+
+ ("state", "reason"),
+ [
+ ("replaced", "service_pid_mismatch"),
+ ("missing", "service_pid_mismatch"),
+ ("unreadable_pid", "service_pid_mismatch"),
+ ("recycled", "service_create_time_mismatch"),
+ ("older_time", "service_create_time_mismatch"),
+ ("dead", "service_identity_unavailable"),
+ ("unreadable_time", "service_identity_unavailable"),
+ ("invalid_live_time", "service_create_time_mismatch"),
+ ],
+)
+def test_cmd_stop_receipt_refuses_without_any_shutdown_side_effect(
+ monkeypatch, capsys, receipt_shutdown, state, reason,
+):
+ receipt = _startup_receipt_payload()
+ if state == "replaced":
+ receipt_shutdown.pid_path.write_text("9012\n", encoding="utf-8")
+ elif state == "missing":
+ receipt_shutdown.pid_path.unlink()
+ elif state == "unreadable_pid":
+ receipt_shutdown.pid_path.write_bytes(b"\xff")
+ elif state in ("recycled", "older_time"):
+ receipt["service_create_unix_ms"] += 2.001 if state == "recycled" else -2.001
+ elif state == "dead":
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)
+ else:
+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: None if state == "unreadable_time" else float("nan"))
+ before = receipt_shutdown.pid_path.read_bytes() if receipt_shutdown.pid_path.exists() else None
+
+ assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
+
+ output = capsys.readouterr()
+ assert output.out == ""
+ assert json.loads(output.err) == {"reason": reason}
+ assert receipt_shutdown.calls == []
+ assert (receipt_shutdown.pid_path.read_bytes() if receipt_shutdown.pid_path.exists() else None) == before
+
+
[email protected]("field", list(_startup_receipt_payload()))
+def test_cmd_stop_rejects_incomplete_receipt(capsys, receipt_shutdown, field):
+ receipt = _startup_receipt_payload()
+ del receipt[field]
+
+ assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
+
+ assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
+ assert receipt_shutdown.calls == []
+
+
+ ("field", "value"),
+ [
+ ("schema_version", True), ("schema_version", 1.0), ("schema_version", 2),
+ ("outcome", "unknown"), ("outcome", ["started"]),
+ ("service_pid", True), ("service_pid", -1234), ("service_pid", 1234.0),
+ ("ui_pid", 0), ("ui_pid", "5678"),
+ ("service_create_unix_ms", None), ("service_create_unix_ms", "1789010100123.5"),
+ ("service_create_unix_ms", float("nan")), ("service_create_unix_ms", float("inf")),
+ ("ui_create_unix_ms", -1), ("ui_create_unix_ms", True),
+ ("ui_create_unix_ms", float("-inf")), ("ui_create_unix_ms", 10 ** 400),
+ ],
+)
+def test_cmd_stop_rejects_invalid_receipt_values(capsys, receipt_shutdown, field, value):
+ receipt = _startup_receipt_payload()
+ receipt[field] = value
+
+ assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
+
+ assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
+ assert receipt_shutdown.calls == []
+
+
[email protected]("receipt", ["", "{", "null", "[]", '"receipt"', "[" * 2000 + "]" * 2000])
+def test_cmd_stop_rejects_malformed_receipt(capsys, receipt_shutdown, receipt):
+ assert cli.cmd_stop(receipt=receipt) == 3
+
+ assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
+ assert receipt_shutdown.calls == []
+
+
+def test_cmd_stop_without_receipt_keeps_legacy_full_stop(monkeypatch, capsys, receipt_shutdown):
+ def unexpected_identity_read(pid):
+ raise AssertionError("Unscoped stop must not inspect receipt identity")
+
+ monkeypatch.setattr(runtime, "process_create_time", unexpected_identity_read)
+ receipt_shutdown.pid_path.unlink()
+
+ assert cli.cmd_stop() == 0
+
+ assert receipt_shutdown.calls == ["service", "ui", "opencode", ("stopped",)]
+ output = capsys.readouterr()
+ assert output.out == "OpenCode server stopped\n"
+ assert output.err == ""
+
+
+def test_cmd_stop_matched_receipt_preserves_stop_failure_exit_code(monkeypatch, capsys, receipt_shutdown):
+ monkeypatch.setattr(runtime, "stop_service", lambda: receipt_shutdown.calls.append("service") or False)
+
+ assert cli.cmd_stop(receipt=json.dumps(_startup_receipt_payload())) == 2
+
+ assert receipt_shutdown.calls == ["service", "ui", "opencode", ("error", "service stop failed")]
+ assert capsys.readouterr().err == "ERROR: Avibe service did not stop; preserving pidfile and aborting.\n"
+
+
def test_cmd_stop_ignores_absent_services(monkeypatch):
status = []
@@ -850,6 +997,208 @@ def _no_live_runtime_processes(monkeypatch):
monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **kwargs: None)
+#: Captured at import, before any test replaces it, for the tests that drive
+#: the real UI start underneath an otherwise stubbed `cmd_start`.
+_REAL_START_UI = runtime.start_ui
+_REAL_STOP_UI = runtime.stop_ui
+_REAL_START_SERVICE = runtime.start_service
+
+
+def _fake_start_result(pid, kwargs, *, reused=False):
+ start_info = kwargs.get("start_info")
+ if start_info is not None:
+ start_info.pid = pid
+ start_info.create_unix_ms = 1789010100000.5 + pid
+ start_info.reused = reused
+ return pid
+
+
+def receipt_runtime(monkeypatch):
+ service_path = paths.get_runtime_pid_path()
+ ui_path = paths.get_runtime_ui_pid_path()
+ service_path.parent.mkdir(parents=True, exist_ok=True)
+ process_times = {1234: 1789010100.1235, 5678: 1789010100.4565, 9012: 1789010100.7895}
+ spawned = []
+ captured = []
+ opened = []
+ stopped = []
+
+ def fake_process(pid):
+ captured.append(pid)
+ return SimpleNamespace(create_time=lambda: process_times[pid])
+
+ # Both stand in for the spawn primitives, so both honour their contract:
+ # the child is recorded and captured before it is returned.
+ def spawn_service(*args, hand_over, **kwargs):
+ spawned.append("service")
+ process = SimpleNamespace(pid=1234, poll=lambda: None)
+ hand_over(process)
+ return process
+
+ def spawn_ui(args, pid_path, *logs, start_info=None, **kwargs):
+ spawned.append("ui")
+ pid_path.write_text("5678", encoding="utf-8")
+ if start_info is not None:
+ start_info.capture(5678, reused=False)
+ return 5678
+
+ monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=True),
+ ))
+ monkeypatch.setattr(cli, "_write_status", lambda *args: None)
+ monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)
+ monkeypatch.setattr(cli, "_open_browser", lambda url: opened.append(url) or True)
+ monkeypatch.setattr(runtime, "write_status", lambda *args: None)
+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")
+ monkeypatch.setattr(runtime, "_SERVICE_START_PROCESSES", {})
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in process_times)
+ monkeypatch.setattr(runtime.psutil, "Process", fake_process)
+ monkeypatch.setattr(runtime, "_pid_mismatches_service", lambda pid: False)
+ monkeypatch.setattr(runtime, "_pid_matches_ui_server", lambda pid: True)
+ monkeypatch.setattr(runtime, "_ui_server_compatible", lambda host, port: True)
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: True)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: pid)
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
+ monkeypatch.setattr(runtime, "extra_service_process_pids", lambda **kwargs: [])
+ monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: [])
+ monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: True)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port: True)
+ monkeypatch.setattr(runtime, "spawn_service_background_process", spawn_service)
+ monkeypatch.setattr(runtime, "spawn_background", spawn_ui)
+ # A failed start now rolls the service back, and the real stop_service()
+ # resolves its target from the live process table rather than from anything
+ # this fixture controls. Record the call instead of making it.
+ monkeypatch.setattr(runtime, "stop_service", lambda: stopped.append("stop_service") or True)
+ return SimpleNamespace(
+ service_path=service_path, ui_path=ui_path, process_times=process_times,
+ spawned=spawned, captured=captured, opened=opened, stopped=stopped,
+ )
+
+
[email protected]("reused", [False, True])
[email protected]("open_browser", [None, False])
+def test_cmd_start_receipt_uses_launch_provenance_and_psutil_identity(
+ monkeypatch, capsys, receipt_runtime, reused, open_browser,
+):
+ if reused:
+ receipt_runtime.service_path.write_text("1234", encoding="utf-8")
+ receipt_runtime.ui_path.write_text("5678", encoding="utf-8")
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: None if reused else 1234)
+
+ assert cli.cmd_start(open_browser=open_browser) == 0
+
+ output = capsys.readouterr().out
+ receipts = [line for line in output.splitlines() if line.startswith("@avibe-start-receipt:")]
+ assert len(receipts) == 1
+ assert json.loads(receipts[0].split(":", 1)[1]) == {
+ "schema_version": 1, "outcome": "reused" if reused else "started",
+ "service_pid": 1234, "ui_pid": 5678,
+ "service_create_unix_ms": receipt_runtime.process_times[1234] * 1000,
+ "ui_create_unix_ms": receipt_runtime.process_times[5678] * 1000,
+ }
+ assert receipt_runtime.spawned == ([] if reused else ["service", "ui"])
+ assert receipt_runtime.captured == [1234, 5678]
+ assert bool(receipt_runtime.opened) == (open_browser is None)
+ assert "Web UI:\n http://127.0.0.1:5123\n" in output
+ assert "Run: vibe remote" in output
+
+
[email protected]("reused", [False, True])
+def test_start_ui_captures_its_own_provenance_before_readiness(monkeypatch, receipt_runtime, reused):
+ if reused:
+ receipt_runtime.ui_path.write_text("5678", encoding="utf-8")
+ before = receipt_runtime.process_times[5678] * 1000
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port: receipt_runtime.process_times.update({5678: 9999}) or True)
+ info = runtime.ProcessStartInfo()
+
+ assert runtime.start_ui("127.0.0.1", 5123, start_info=info) == 5678
+
+ assert info.reused is reused
+ assert info.create_unix_ms == before
+ assert receipt_runtime.spawned == ([] if reused else ["ui"])
+
+
[email protected]("branch", ["recorded", "starting", "ready_owner", "mismatched_command", "lock_owner"])
+def test_start_service_receipt_marks_every_existing_return_as_reused(monkeypatch, receipt_runtime, branch):
+ receipt_runtime.service_path.write_text("1234", encoding="utf-8")
+ alive_checks = iter([False, True]) if branch == "lock_owner" else None
+ if alive_checks is not None:
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: next(alive_checks))
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: branch == "recorded")
+ monkeypatch.setattr(runtime, "_pid_reservation_is_fresh", lambda *args: True)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 9012)
+ monkeypatch.setattr(runtime, "_pid_mismatches_service", lambda pid: branch == "mismatched_command")
+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, 1234))
+ info = runtime.ProcessStartInfo()
+ expected_pid = 1234 if branch == "starting" else 9012
+
+ assert runtime.start_service(wait_for_ready=branch != "starting", start_info=info) == expected_pid
+
+ assert info.reused is True
+ assert info.pid == expected_pid
+ assert info.create_unix_ms == receipt_runtime.process_times[expected_pid] * 1000
+ assert receipt_runtime.spawned == []
+
+
+def test_start_service_receipt_adopts_scoped_owner(monkeypatch, receipt_runtime):
+ monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: ["systemd-run", "--scope"])
+ monkeypatch.setattr(runtime, "_start_scoped_service_result", lambda *args, **kwargs: 9012)
+ info = runtime.ProcessStartInfo()
+
+ assert runtime.start_service(start_info=info) == 9012
+
+ assert info.reused is False
+ assert info.create_unix_ms == receipt_runtime.process_times[9012] * 1000
+ assert receipt_runtime.captured == [1234, 9012]
+ assert receipt_runtime.spawned == ["service"]
+
+
+def test_start_service_receipt_keeps_identity_captured_before_readiness(monkeypatch, receipt_runtime):
+ before = receipt_runtime.process_times[1234] * 1000
+ monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: receipt_runtime.process_times.update({1234: 9999}) or True)
+ info = runtime.ProcessStartInfo()
+
+ assert runtime.start_service(start_info=info) == 1234
+
+ assert info.reused is False
+ assert info.create_unix_ms == before
+ assert receipt_runtime.captured == [1234]
+
+
+def test_cmd_start_receipt_tracks_late_authoritative_service_pid(monkeypatch, capsys, receipt_runtime):
+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: False)
+ monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: False)
+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 9012)
+
+ assert cli.cmd_start(open_browser=False) == 0
+
+ receipt_line = next(line for line in capsys.readouterr().out.splitlines() if line.startswith("@avibe-start-receipt:"))
+ receipt = json.loads(receipt_line.split(":", 1)[1])
+ assert receipt["service_pid"] == 9012
+ assert receipt["service_create_unix_ms"] == receipt_runtime.process_times[9012] * 1000
+ assert receipt["outcome"] == "started"
+ assert receipt_runtime.captured == [1234, 5678, 9012]
+
+
+def test_cmd_start_does_not_emit_a_receipt_with_unreadable_identity(monkeypatch, capsys, receipt_runtime):
+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: None)
+
+ with pytest.raises(ValueError, match="service_create_unix_ms"):
+ cli.cmd_start(open_browser=False)
+
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+ # The far end of the pre-receipt region, and the only failure in it that
+ # needs no monkeypatched failure to reach: the receipt builder rejects an
+ # identity it cannot read, with the service this command started already up.
+ assert receipt_runtime.stopped == ["stop_service"], (
+ f"a start that could not build its receipt left its own service running: {receipt_runtime.stopped}"
+ )
+
+
def test_cmd_start_ensures_services_without_stopping(monkeypatch):
calls = []
config = SimpleNamespace(
@@ -860,13 +1209,18 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
_no_live_runtime_processes(monkeypatch)
monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(
+ cli,
+ "_handover_superseded_desktop_runtime",
+ lambda: calls.append(("handover",)),
+ )
monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))
- monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or 1234)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or _fake_start_result(1234, kwargs))
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
monkeypatch.setattr(
cli.runtime,
"start_ui",
- lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or 5678,
+ lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or _fake_start_result(5678, kwargs),
)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))
@@ -875,11 +1229,93 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
service_call = next(call for call in calls if call[0] == "start_service")
ui_call = next(call for call in calls if call[0] == "start_ui")
+ assert calls.index(("handover",)) < calls.index(service_call)
assert service_call[1]["wait_for_ready"] is False
assert ui_call[1:3] == ("127.0.0.1", 5123)
assert not any(call == "stop" for call in calls)
+def test_desktop_start_hands_over_a_superseded_controller(monkeypatch):
+ calls = []
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "b" * 64)
+ monkeypatch.setattr(
+ internal_client,
+ "health_identity_sync",
+ lambda: {"desktop_runtime_id": "a" * 64},
+ )
+ monkeypatch.setattr(
+ cli.runtime,
+ "resolve_service_owner_pid",
+ lambda include_starting: 1234,
+ )
+ monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: True)
+ monkeypatch.setattr(
+ cli.runtime,
+ "stop_service",
+ lambda: calls.append(("service",)) or True,
+ )
+ monkeypatch.setattr(
+ cli.runtime,
+ "stop_ui",
+ lambda **kwargs: calls.append(("ui", kwargs)) or True,
+ )
+
+ cli._handover_superseded_desktop_runtime()
+
+ assert calls == [
+ ("service",),
+ ("ui", {"stop_remote_access": False}),
+ ]
+
+
[email protected]("controller_runtime_id", [None, "b" * 64])
+def test_desktop_start_preserves_external_or_matching_controllers(
+ monkeypatch,
+ controller_runtime_id,
+):
+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "b" * 64)
+ monkeypatch.setattr(
+ internal_client,
+ "health_identity_sync",
+ lambda: {"desktop_runtime_id": controller_runtime_id}
+ if controller_runtime_id is not None
+ else {"ok": True},
+ )
+ monkeypatch.setattr(
+ cli.runtime,
+ "stop_service",
+ lambda: pytest.fail("controller must be preserved"),
+ )
+ monkeypatch.setattr(
+ cli.runtime,
+ "stop_ui",
+ lambda **_kwargs: pytest.fail("UI must be preserved"),
+ )
+
+ cli._handover_superseded_desktop_runtime()
+
+
+def test_cmd_start_can_suppress_configured_browser_open(monkeypatch):
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=True),
+ )
+ opened = []
+
+ _no_live_runtime_processes(monkeypatch)
+ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: _fake_start_result(1234, kwargs))
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: _fake_start_result(5678, kwargs))
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
+ monkeypatch.setattr(cli, "_open_browser", lambda url: opened.append(url) or True)
+
+ assert cli.cmd_start(open_browser=False) == 0
+
+ assert opened == []
@pytest.mark.parametrize("reused_service", [False, True])
@pytest.mark.parametrize("ui_state", ["healthy", "absent", "stale"])
def test_cmd_start_reuses_independent_ui_or_recovers_only_unhealthy_ui(monkeypatch, ui_state, reused_service):
@@ -894,19 +1330,29 @@ def test_cmd_start_reuses_independent_ui_or_recovers_only_unhealthy_ui(monkeypat
stopped, spawned = [], []
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: 222 if reused_service else None)
- monkeypatch.setattr(runtime, "start_service", lambda **kwargs: 222)
+ monkeypatch.setattr(
+ runtime,
+ "start_service",
+ lambda **kwargs: _fake_start_result(222, kwargs, reused=reused_service),
+ )
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {111, 222})
monkeypatch.setattr(runtime, "_pid_matches_ui_server", lambda pid: pid == 111)
monkeypatch.setattr(runtime, "ui_server_healthy", lambda *args: ui_state == "healthy")
+ # This tree adopts a UI through its identity-checked readiness probe; stub it
+ # like the health probe so no real loopback listener is consulted.
+ monkeypatch.setattr(runtime, "_ui_server_compatible", lambda *args, **kwargs: ui_state == "healthy")
+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1789010100.0 + pid)
monkeypatch.setattr(runtime, "wait_for_ui_server", lambda *args: True)
monkeypatch.setattr(runtime, "current_service_launcher", lambda: SimpleNamespace(python="test-owned-python"))
monkeypatch.setattr(runtime, "stop_pid", lambda pid: stopped.append(pid) or True)
- def spawn(command, path, *args, **kwargs):
+ def spawn(command, path, *args, start_info=None, **kwargs):
spawned.append(command)
path.write_text("333")
+ if start_info is not None:
+ start_info.capture(333, reused=False)
return 333
def no_full_stop(*args, **kwargs):
@@ -967,12 +1413,12 @@ def test_cmd_start_keeps_ui_up_while_service_lock_is_slow(monkeypatch):
monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))
- monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or 1234)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or _fake_start_result(1234, kwargs))
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
monkeypatch.setattr(
cli.runtime,
"start_ui",
- lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or 5678,
+ lambda host, port, **kwargs: calls.append(("start_ui", host, port, kwargs)) or _fake_start_result(5678, kwargs),
)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)
monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: pid == 1234)
@@ -1016,9 +1462,17 @@ def test_cmd_start_against_a_live_service_neither_resets_its_uptime_nor_skips_th
# The live pair: `start_service` hands back the pid that already holds the
# lock, which is what makes this a reuse rather than a start.
monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **kwargs: 1234)
- monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
+ monkeypatch.setattr(
+ cli.runtime,
+ "start_service",
+ lambda **kwargs: _fake_start_result(1234, kwargs, reused=True),
+ )
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
- monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: 5678)
+ monkeypatch.setattr(
+ cli.runtime,
+ "start_ui",
+ lambda host, port, **kwargs: _fake_start_result(5678, kwargs, reused=True),
+ )
monkeypatch.setattr(
cli.runtime,
"wait_for_service_ready",
@@ -1044,9 +1498,10 @@ def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):
monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)
- monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: _fake_start_result(1234, kwargs))
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
- monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: 5678)
+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: _fake_start_result(5678, kwargs))
+ monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)
monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: False)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: statuses.append(args))
@@ -1057,6 +1512,522 @@ def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):
assert ("error", "service process exited before startup completed", 1234, 5678) in statuses
+def _ui_refuses_to_start(
+ monkeypatch,
+ *,
+ reused: bool,
+ ui_outcome=None,
+ on_wait=None,
+ ui_reused: bool = False,
+ on_receipt=None,
+):
+ """Wire cmd_start for a start that cannot finish, with every stop recorded.
+
+ ``ui_outcome`` decides how ``runtime.start_ui`` ends. ``None`` is the refusal
+ it returns when the recorded UI process is alive, is a UI server, is
+ incompatible with the requested host and port, and will not stop: it
+ deliberately starts no replacement -- one would only die on bind while the
+ stale process kept serving -- and keeps the pid record naming the process
+ that has to be stopped. An exception instance is raised instead, which is
+ what an unwritable or malformed ``vibe-ui.pid`` or a failing process spawn
+ does. ``on_wait`` fails later still, once the UI is already up, and
+ ``on_receipt`` fails last of all, inside the receipt builder.
+
+ ``ui_reused`` is the other half of the picture: ``start_ui`` returns a pid
+ both when it spawns one and when it adopts a live, compatible UI, and only
+ the provenance it records tells the two apart.
+
+ ``runtime.stop_ui`` is stubbed for every caller, not only the ones that
+ assert on it: a rollback reaching the real one would stop the developer's
+ own UI and its remote access from a unit test.
+ """
+
+ from vibe.desktop_runtime import start_receipt_line as real_receipt_line
+
+ calls: list[str] = []
+ statuses: list[tuple] = []
+ stop_ui_kwargs: list[dict] = []
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ )
+
+ def start_service(**kwargs):
+ calls.append("start_service")
+ return _fake_start_result(1234, kwargs, reused=reused)
+
+ def refuse_ui(host, port, **kwargs):
+ calls.append("start_ui")
+ if isinstance(ui_outcome, BaseException):
+ raise ui_outcome
+ return _fake_start_result(ui_outcome, kwargs, reused=ui_reused) if ui_outcome else None
+
+ def stop_service():
+ calls.append("stop_service")
+ return True
+
+ def stop_ui(**kwargs):
+ calls.append("stop_ui")
+ stop_ui_kwargs.append(kwargs)
+ return True
+
+ def wait_for_service_ready(pid, timeout):
+ calls.append("wait_for_service_ready")
+ if on_wait is not None:
+ raise on_wait
+ return pid
+
+ def build_receipt(payload):
+ calls.append("start_receipt_line")
+ if on_receipt is not None:
+ raise on_receipt
+ return real_receipt_line(payload)
+
+ monkeypatch.setattr("vibe.desktop_runtime.start_receipt_line", build_receipt)
+ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)
+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)
+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **kwargs: 1234 if reused else None)
+ monkeypatch.setattr(cli.runtime, "start_service", start_service)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
+ monkeypatch.setattr(cli.runtime, "start_ui", refuse_ui)
+ monkeypatch.setattr(cli.runtime, "stop_service", stop_service)
+ monkeypatch.setattr(cli.runtime, "stop_ui", stop_ui)
+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", wait_for_service_ready)
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: statuses.append(args))
+ return SimpleNamespace(calls=calls, statuses=statuses, stop_ui_kwargs=stop_ui_kwargs)
+
+
+def test_cmd_start_does_not_leave_its_own_service_running_when_the_ui_refuses(monkeypatch, capsys):
+ """A start that cannot finish must not leave a service nobody can stop.
+
+ No UI pid ends the start: the status writes carry that pid and
+ ``validate_start_receipt`` rejects a receipt without one. Carrying on
+ regardless left the service this command had just started alive with no
+ receipt ever printed -- and an unreceipted service is adopted as ``reused``
+ on the next attempt, so the desktop shell never owns the stop again.
+
+ Deliberately fix-agnostic: rolling the service back and refusing to start it
+ at all both satisfy the invariant below.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False)
+
+ failure = None
+ try:
+ cli.cmd_start()
+ except Exception as error: # noqa: BLE001 - the shape of the failure is asserted below
+ failure = error
+
+ assert failure is not None, "cmd_start reported success after the UI refused to start"
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+ assert "start_service" not in started.calls or "stop_service" in started.calls, (
+ f"cmd_start left the service it started running with no start receipt: {started.calls}"
+ )
+ assert started.calls.count("stop_service") <= 1, (
+ f"cmd_start rolled the same failed start back more than once: {started.calls}"
+ )
+ assert "running" not in [entry[0] for entry in started.statuses], (
+ f"cmd_start announced a running pair for a start that could not finish: {started.statuses}"
+ )
+
+
+def test_cmd_start_never_stops_a_service_it_did_not_start_when_the_ui_refuses(monkeypatch, capsys):
+ """The rollback is scoped to this command's own start, and nothing else.
+
+ A reused service belongs to whoever started it. The UI refusing still fails
+ the command, because there is no pid to receipt, but it must not touch the
+ service and must not restate the pair's status -- the stale UI is still
+ running with its pid record preserved, so a write naming no UI pid would
+ contradict it.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=True)
+
+ with pytest.raises(RuntimeError):
+ cli.cmd_start()
+
+ assert "stop_service" not in started.calls, "cmd_start stopped a service it did not start"
+ assert started.statuses == [], f"cmd_start restated the status of a reused pair: {started.statuses}"
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
[email protected]("reused", [False, True])
+def test_cmd_start_rolls_its_own_service_back_when_the_ui_start_raises(monkeypatch, capsys, reused):
+ """The refusal is not the only way the UI start ends without a pid.
+
+ ``start_ui`` also raises -- an unwritable or malformed ``vibe-ui.pid`` fails
+ while it cleans or writes that record, and the process spawn itself can fail.
+ The orphan is identical either way, so the rollback cannot belong to the
+ ``None`` branch; it belongs to the whole pre-receipt region. And it stays
+ scoped: a reused service belongs to whoever started it.
+ """
+
+ started = _ui_refuses_to_start(
+ monkeypatch, reused=reused, ui_outcome=OSError("vibe-ui.pid is not writable")
+ )
+
+ with pytest.raises(OSError, match="vibe-ui.pid"):
+ cli.cmd_start()
+
+ assert started.calls.count("stop_service") == (0 if reused else 1), (
+ f"a raising UI start left the wrong service state behind (reused={reused}): {started.calls}"
+ )
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
+def test_cmd_start_rolls_back_when_an_interrupt_arrives_before_the_receipt(monkeypatch, capsys):
+ """Ctrl-C during the readiness wait orphans both processes, not just one.
+
+ The wait is the longest thing in the region -- it runs to
+ ``SERVICE_SLOW_START_TIMEOUT_SECONDS`` against a service that is still
+ migrating its database -- so it is the likeliest moment for a user to give
+ up. ``KeyboardInterrupt`` is not an ``Exception``, which is why the guard
+ catches ``BaseException``: an interrupted start that leaves a running,
+ unreceipted service is adopted as ``reused`` next time just the same, and a
+ UI left behind keeps its pid file, its listener and the port that the next
+ attempt then has to fight.
+
+ The order is the reverse of creation, because a UI stopped after the service
+ beneath it has already spent that window serving a backend that is gone.
+ """
+
+ started = _ui_refuses_to_start(
+ monkeypatch, reused=False, ui_outcome=5678, on_wait=KeyboardInterrupt()
+ )
+
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert started.calls.count("stop_service") == 1, (
+ f"an interrupted start left its own service running: {started.calls}"
+ )
+ assert started.calls.count("stop_ui") == 1, (
+ f"an interrupted start left the UI it had just spawned running: {started.calls}"
+ )
+ assert started.calls.index("stop_ui") < started.calls.index("stop_service"), (
+ f"the rollback stopped the service before the UI pointed at it: {started.calls}"
+ )
+ # A tunnel is never brought up by `vibe start`, so one alive here predates
+ # the command and is not this rollback's to tear down.
+ assert started.stop_ui_kwargs == [{"stop_remote_access": False}], (
+ f"the rollback destroyed a remote URL it did not create: {started.stop_ui_kwargs}"
+ )
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
+def test_cmd_start_leaves_a_ui_and_service_it_only_adopted_alone(monkeypatch, capsys):
+ """Adoption is not creation, and the same failure must undo nothing.
+
+ ``start_ui`` returns a pid both when it spawns a UI and when it finds a live,
+ compatible one and adopts it; only ``reused`` on the start record tells the
+ two apart. Scoping the rollback to the pid instead of to the provenance would
+ make a failed ``vibe start`` kill the UI and service a user already had --
+ the command would become destructive precisely when it achieved nothing.
+ """
+
+ started = _ui_refuses_to_start(
+ monkeypatch,
+ reused=True,
+ ui_outcome=5678,
+ ui_reused=True,
+ on_wait=KeyboardInterrupt(),
+ )
+
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert "stop_ui" not in started.calls, f"cmd_start stopped a UI it did not start: {started.calls}"
+ assert "stop_service" not in started.calls, (
+ f"cmd_start stopped a service it did not start: {started.calls}"
+ )
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
+def test_cmd_start_rolls_both_back_when_the_receipt_builder_fails(monkeypatch, capsys):
+ """The last statement of the region can fail too, and it orphans the most.
+
+ By this point both processes are up and the status says ``running``; only the
+ receipt is missing. That is the worst orphan of the set, because everything
+ except the one line the desktop shell needs to own the stop succeeded.
+ """
+
+ started = _ui_refuses_to_start(
+ monkeypatch,
+ reused=False,
+ ui_outcome=5678,
+ on_receipt=RuntimeError("receipt payload is not serializable"),
+ )
+
+ with pytest.raises(RuntimeError, match="receipt payload"):
+ cli.cmd_start()
+
+ assert started.calls.count("stop_ui") == 1, (
+ f"a failed receipt left the UI this command started running: {started.calls}"
+ )
+ assert started.calls.count("stop_service") == 1, (
+ f"a failed receipt left the service this command started running: {started.calls}"
+ )
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
+ ("captured", "reused", "expected"),
+ [
+ # Spawned and reserved, then interrupted while waiting for the lock.
+ (True, False, ["start_service", "stop_service"]),
+ # Adopted from a previous launch, then interrupted: not ours to stop.
+ (True, True, ["start_service"]),
+ # Refused before it identified any process, e.g. another holder.
+ (False, False, ["start_service"]),
+ ],
+)
+def test_cmd_start_undoes_a_service_it_created_even_when_start_service_itself_raises(
+ monkeypatch, capsys, captured, reused, expected
+):
+ """`start_service` spawns and then waits, and the wait can be interrupted.
+
+ The call used to sit in front of the region the rollback guards, so a Ctrl-C
+ during the lock wait left a live, reserved service that the next `vibe
+ start` adopted as `reused` -- the orphan the region exists to prevent.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=reused)
+
+ def interrupted_start(**kwargs):
+ started.calls.append("start_service")
+ if captured:
+ _fake_start_result(1234, kwargs, reused=reused)
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(cli.runtime, "start_service", interrupted_start)
+
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert started.calls == expected
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+
+
+def test_cmd_start_leaves_no_ui_running_when_the_ui_pid_record_cannot_be_written(monkeypatch, tmp_path):
+ """The reviewed failure, end to end, with a real UI child.
+
+ `spawn_background` started the UI and then failed writing `vibe-ui.pid`, so
+ `start_ui` never captured it and the rollback -- which only undoes what it
+ was told it created -- had nothing to undo. The orphan kept the listener.
+ Here the real `start_ui` and the real spawn run against a stand-in
+ interpreter that just sleeps, and the pid record's directory is missing.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False)
+ children = _real_ui_children(monkeypatch, tmp_path, tmp_path / "missing" / "vibe-ui.pid")
+
+ try:
+ with pytest.raises(FileNotFoundError):
+ cli.cmd_start()
+
+ assert len(children) == 1, children
+ assert children[0].returncode is not None, "the UI this start spawned was left running"
+ assert not runtime.pid_alive(children[0].pid)
+ # The service this start created is still undone.
+ assert started.calls.count("stop_service") == 1, started.calls
+ finally:
+ _kill_children(children)
+
+
+def _real_ui_children(monkeypatch, tmp_path, ui_pid_path):
+ """Let cmd_start's real `start_ui` spawn a real UI child that only sleeps.
+
+ Everything else stays as `_ui_refuses_to_start` wired it. The returned list
+ fills with every UI child spawned, so a test can check the process itself.
+ """
+
+ fake_python = tmp_path / "avibe-ui-probe-python"
+ fake_python.write_text("#!/bin/sh\nexec sleep 60\n", encoding="utf-8")
+ fake_python.chmod(0o755)
+ monkeypatch.setattr(cli.runtime, "start_ui", _REAL_START_UI)
+ monkeypatch.setattr(
+ runtime,
+ "current_service_launcher",
+ lambda: runtime.ServiceLauncher(python=str(fake_python), main="unused"),
+ )
+ monkeypatch.setattr(runtime.paths, "get_runtime_ui_pid_path", lambda: ui_pid_path)
+ children = []
+ real_popen = runtime.subprocess.Popen
+
+ class SpyPopen(real_popen):
+ def __init__(self, args, *rest, **kwargs):
+ super().__init__(args, *rest, **kwargs)
+ if args and args[0] == str(fake_python):
+ children.append(self)
+
+ monkeypatch.setattr(runtime.subprocess, "Popen", SpyPopen)
+ return children
+
+
+def _kill_children(children) -> None:
+ for child in children:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=5)
+
+
+def test_cmd_start_leaves_no_ui_running_when_interrupted_between_the_ui_record_and_its_capture(
+ monkeypatch, capsys, tmp_path
+):
+ """The last gap in the UI handover, end to end, with a real UI child.
+
+ `start_ui` used to capture the child only after `spawn_background` had
+ returned it with its pid record written. A Ctrl-C in between left a live UI
+ that `start_info` did not name, so the rollback -- which undoes only what it
+ was told it created -- never stopped it. The capture now runs inside the
+ spawn's guarded region; here a signal lands after the record and before the
+ capture.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False)
+ ui_pid_path = tmp_path / "vibe-ui.pid"
+ children = _real_ui_children(monkeypatch, tmp_path, ui_pid_path)
+ records_at_intrusion = []
+
+ def interrupted_capture(self, pid, *, reused):
+ records_at_intrusion.append(ui_pid_path.read_text(encoding="utf-8"))
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(runtime.ProcessStartInfo, "capture", interrupted_capture)
+
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert len(children) == 1, children
+ # The signal landed where it was aimed: the record already named the child.
+ assert records_at_intrusion == [str(children[0].pid)]
+ assert children[0].returncode is not None, "the UI this start spawned was left running"
+ assert not runtime.pid_alive(children[0].pid)
+ assert not ui_pid_path.exists(), "the record of a discarded UI was left behind"
+ # The service this start created is still undone, and nothing claims success.
+ assert started.calls.count("stop_service") == 1, started.calls
+ assert "running" not in [entry[0] for entry in started.statuses], started.statuses
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+ finally:
+ _kill_children(children)
+
+
+def test_cmd_start_leaves_no_service_running_when_interrupted_between_its_reservation_and_its_capture(
+ monkeypatch, capsys, tmp_path
+):
+ """The service side of the same boundary, through the real `start_service`.
+
+ The reservation is what `stop_service()` finds, and the capture is what tells
+ the rollback it created the service. A signal between the two used to leave
+ a reserved service no rollback was asked about.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False)
+ script = tmp_path / "avibe-service-probe.py"
+ script.write_text("import time\ntime.sleep(60)\n", encoding="utf-8")
+ monkeypatch.setattr(cli.runtime, "start_service", _REAL_START_SERVICE)
+ monkeypatch.setattr(
+ runtime,
+ "current_service_launcher",
+ lambda: runtime.ServiceLauncher(python=sys.executable, main=str(script)),
+ )
+ # The real service a developer has running must not be seen as the holder.
+ monkeypatch.setattr(runtime, "extra_service_process_pids", lambda **kwargs: [])
+ monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: [])
+ reservation = paths.get_runtime_pid_path()
+ children = []
+ real_popen = runtime.subprocess.Popen
+
+ class SpyPopen(real_popen):
+ def __init__(self, args, *rest, **kwargs):
+ super().__init__(args, *rest, **kwargs)
+ if str(script) in args:
+ children.append(self)
+
+ monkeypatch.setattr(runtime.subprocess, "Popen", SpyPopen)
+ reservations_at_intrusion = []
+
+ def interrupted_capture(self, pid, *, reused):
+ reservations_at_intrusion.append(reservation.read_text(encoding="utf-8"))
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(runtime.ProcessStartInfo, "capture", interrupted_capture)
+
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert len(children) == 1, children
+ assert reservations_at_intrusion == [str(children[0].pid)]
+ assert children[0].returncode is not None, "the service this start spawned was left running"
+ assert not runtime.pid_alive(children[0].pid)
+ assert not reservation.exists(), "the reservation of a discarded service was left behind"
+ # Nothing was captured, so nothing is left for the rollback, and the UI
+ # was never reached.
+ assert started.calls == [], started.calls
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+ finally:
+ _kill_children(children)
+
+
+def test_cmd_start_rolls_back_a_real_ui_it_captured_through_its_record(monkeypatch, capsys, tmp_path):
+ """Once captured, the UI is the rollback's to stop, and the rollback finds it.
+
+ The other side of the handover boundary: a Ctrl-C after `start_ui` returned
+ is `cmd_start`'s to undo, through the pid record the spawn wrote. The real
+ `stop_ui` runs against the real child; it is only guarded so that a rollback
+ asking for remote access to stop fails here instead of reaching it.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False, on_wait=KeyboardInterrupt())
+ ui_pid_path = tmp_path / "vibe-ui.pid"
+ children = _real_ui_children(monkeypatch, tmp_path, ui_pid_path)
+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port: True)
+
+ def stop_ui(**kwargs):
+ started.calls.append("stop_ui")
+ assert kwargs == {"stop_remote_access": False}, kwargs
+ return _REAL_STOP_UI(**kwargs)
+
+ monkeypatch.setattr(cli.runtime, "stop_ui", stop_ui)
+
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start()
+
+ assert len(children) == 1, children
+ # Stopped by the rollback's managed SIGTERM, not by this test's cleanup.
+ assert children[0].wait(timeout=5) == -signal.SIGTERM
+ assert not ui_pid_path.exists()
+ assert started.calls.index("stop_ui") < started.calls.index("stop_service"), started.calls
+ assert "@avibe-start-receipt:" not in capsys.readouterr().out
+ finally:
+ _kill_children(children)
+
+
+def test_cmd_start_keeps_the_service_it_started_once_the_receipt_is_out(monkeypatch, capsys):
+ """The region ends at the receipt, and a finished start is never undone.
+
+ This is the boundary the guard must not overrun: the receipt is the last
+ statement in the region, so a start that printed one has handed the desktop
+ shell everything it needs to own the stop itself -- both processes stay up.
+ """
+
+ started = _ui_refuses_to_start(monkeypatch, reused=False, ui_outcome=5678)
+
+ assert cli.cmd_start() == 0
+
+ assert "stop_service" not in started.calls, (
+ f"cmd_start rolled back a start that had already succeeded: {started.calls}"
+ )
+ assert "stop_ui" not in started.calls, (
+ f"cmd_start stopped the UI of a start that had already succeeded: {started.calls}"
+ )
+ assert "@avibe-start-receipt:" in capsys.readouterr().out
+
+
def test_ui_pid_probe_accepts_only_a_verified_ui_process(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
cli.paths.get_runtime_ui_pid_path().parent.mkdir(parents=True, exist_ok=True)
@@ -2939,6 +3910,33 @@ def test_start_parser_accepts_start_command():
args = parser.parse_args(["start"])
assert args.command == "start"
+ assert args.open_browser is None
+
+
+def test_start_parser_accepts_no_open_browser():
+ parser = cli.build_parser()
+ args = parser.parse_args(["start", "--no-open-browser"])
+
+ assert args.command == "start"
+ assert args.open_browser is False
+
+
[email protected]("receipt", [None, json.dumps(_startup_receipt_payload())])
+def test_stop_parser_and_main_preserve_optional_receipt(monkeypatch, receipt):
+ arguments = ["stop"] if receipt is None else ["stop", "--receipt", receipt]
+ parsed = cli.build_parser().parse_args(arguments)
+ assert parsed.command == "stop"
+ assert parsed.receipt == receipt
+ calls = []
+ monkeypatch.setattr(cli.sys, "argv", ["vibe", *arguments])
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
+ monkeypatch.setattr(cli, "cmd_stop", lambda **kwargs: calls.append(kwargs) or 3)
+
+ with pytest.raises(SystemExit) as exited:
+ cli.main()
+
+ assert exited.value.code == 3
+ assert calls == ([{}] if receipt is None else [{"receipt": receipt}])
def test_remote_parser_accepts_pairing_command():
@@ -3234,7 +4232,11 @@ def test_start_ui_reuses_existing_live_pid(tmp_path, monkeypatch):
paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
- monkeypatch.setattr(runtime, "ui_server_healthy", lambda host, port: host == "127.0.0.1" and port == 5123)
+ monkeypatch.setattr(
+ runtime,
+ "_ui_server_compatible",
+ lambda host, port: host == "127.0.0.1" and port == 5123,
+ )
monkeypatch.setattr(
runtime,
"get_process_command",
@@ -3285,7 +4287,10 @@ def test_start_ui_replaces_stale_live_pid_when_health_check_fails(tmp_path, monk
stopped = []
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
- monkeypatch.setattr(runtime, "ui_server_healthy", lambda host, port: False)
+ # Adoption is decided by `_ui_server_compatible`, which probes the real
+ # listener. Stubbing only `ui_server_healthy` let this test reach whatever
+ # answers on 127.0.0.1:5123 -- a developer's own running UI -- and adopt it.
+ monkeypatch.setattr(runtime, "_ui_server_compatible", lambda host, port: False)
monkeypatch.setattr(
runtime,
"get_process_command",
@@ -3666,6 +4671,16 @@ def test_doctor_parser_accepts_managed_dependency_repair_targets():
assert args.yes is True
+def test_doctor_parser_rejects_unknown_repair_targets(capsys):
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as error:
+ parser.parse_args(["doctor", "repair", "not-a-repair-target"])
+
+ assert error.value.code == 2
+ assert "invalid choice" in capsys.readouterr().err
+
+
def test_doctor_parser_accepts_fast_and_deep_modes():
parser = cli.build_parser()
diff --git a/ui/scripts/repoRelativePosix.mjs b/ui/scripts/repoRelativePosix.mjs
new file mode 100644
index 000000000..ac865bc4d
--- /dev/null
+++ b/ui/scripts/repoRelativePosix.mjs
@@ -0,0 +1,18 @@
+import path from 'node:path';
+
+/**
+ * A repository-relative path in POSIX form.
+ *
+ * Callers that compare a host path against something written in POSIX — a
+ * Dockerfile's ``COPY`` sources, a ``path.posix`` join, a ``startsWith(`${dir}/`)``
+ * prefix test — need the separator shed at the one place the host path becomes
+ * repository-relative, because ``path.relative`` answers in the host's separator.
+ * On Windows that is ``\``, so an un-normalized target compares unequal to every
+ * POSIX form of itself and the comparison fails against correct input.
+ *
+ * ``platform`` selects the path flavour and exists so the Windows behaviour is
+ * reachable from a test on any host: Node binds ``path`` to the running platform,
+ * so ``path.win32`` is the only way to exercise the separator that breaks.
+ */
+export const repoRelativePosix = (from, to, platform = path) =>
+ platform.relative(from, to).split(platform.sep).join('/');
diff --git a/ui/scripts/repoRelativePosix.test.mjs b/ui/scripts/repoRelativePosix.test.mjs
new file mode 100644
index 000000000..5e17d558a
--- /dev/null
+++ b/ui/scripts/repoRelativePosix.test.mjs
@@ -0,0 +1,67 @@
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { repoRelativePosix } from './repoRelativePosix.mjs';
+
+// The out-of-tree import guard compares the paths ``ui/src`` reaches for against the
+// ``COPY`` sources in the Dockerfile's ui-builder stage. Those sources are POSIX, and
+// so is every join and prefix test the guard does afterwards. ``path.relative`` is not:
+// it answers in the host separator. That mismatch is invisible on Linux and macOS, and
+// only the desktop Windows package job runs ``npm run build`` on Windows, so it shipped
+// and broke a release there. These cases pin the normalization on every host by driving
+// ``path.win32`` explicitly, which is the only way to reach Windows' separator from CI.
+
+// The two repo-root catalogs ``ui/src`` imports, as the Dockerfile spells them.
+const COPY_SOURCES = ['vibe/message_types.json', 'vibe/data/api_key_vendors.json'];
+
+describe('repoRelativePosix normalizes a host path into the form the guard compares', () => {
+ it('rewrites a Windows result into POSIX', () => {
+ expect(
+ repoRelativePosix('C:\\repo', 'C:\\repo\\vibe\\data\\api_key_vendors.json', path.win32),
+ ).toBe('vibe/data/api_key_vendors.json');
+ });
+
+ it('leaves a POSIX result exactly as it was', () => {
+ expect(repoRelativePosix('/repo', '/repo/vibe/data/api_key_vendors.json', path.posix)).toBe(
+ 'vibe/data/api_key_vendors.json',
+ );
+ });
+
+ it('defaults to the running host, so callers pass nothing', () => {
+ const root = path.resolve('/repo');
+ expect(repoRelativePosix(root, path.join(root, 'vibe', 'message_types.json'))).toBe(
+ 'vibe/message_types.json',
+ );
+ });
+});
+
+describe('the Windows separator is what made the guard reject a correct Dockerfile', () => {
+ // Both catalogs are copied as exact files, so the guard matches them by equality with
+ // the COPY source. A backslash target equals none of them and matches no prefix either,
+ // which is why the failure read "puts it at no path at all".
+ it.each(COPY_SOURCES)('%s only matches its COPY source once normalized', (source) => {
+ const windowsRoot = 'C:\\repo';
+ const absolute = path.win32.join(windowsRoot, ...source.split('/'));
+
+ const raw = path.win32.relative(windowsRoot, absolute);
+ expect(raw).not.toBe(source);
+ expect(raw.startsWith(`${source}/`)).toBe(false);
+
+ expect(repoRelativePosix(windowsRoot, absolute, path.win32)).toBe(source);
+ });
+
+ it('keeps the expected image path from being mangled', () => {
+ const windowsRoot = 'C:\\repo';
+ const absolute = 'C:\\repo\\vibe\\data\\api_key_vendors.json';
+
+ // What the guard would have claimed the Dockerfile must provide, before the fix.
+ expect(path.posix.join('/app', path.win32.relative(windowsRoot, absolute))).toBe(
+ '/app/vibe\\data\\api_key_vendors.json',
+ );
+
+ expect(path.posix.join('/app', repoRelativePosix(windowsRoot, absolute, path.win32))).toBe(
+ '/app/vibe/data/api_key_vendors.json',
+ );
+ });
+});
diff --git a/ui/scripts/validate-out-of-tree-imports.mjs b/ui/scripts/validate-out-of-tree-imports.mjs
index 66c848004..ee12f4633 100644
--- a/ui/scripts/validate-out-of-tree-imports.mjs
+++ b/ui/scripts/validate-out-of-tree-imports.mjs
@@ -9,6 +9,8 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { repoRelativePosix } from './repoRelativePosix.mjs';
+
const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));
const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url));
const DOCKERFILE = fileURLToPath(new URL('../../Dockerfile', import.meta.url));
@@ -28,14 +30,20 @@ const sourceFiles = (dir) =>
return /\.tsx?$/.test(entry.name) ? [full] : [];
});
-/** Repository-relative paths that ``ui/src`` imports from outside ``ui/``. */
+/**
+ * Repository-relative POSIX paths that ``ui/src`` imports from outside ``ui/``.
+ *
+ * POSIX because everything these targets meet below is written that way — the
+ * Dockerfile's ``COPY`` sources, the ``${source}/`` prefix test, and the
+ * ``path.posix`` joins — and this is the one place a host path becomes one of them.
+ */
function escapingImports() {
const found = new Set();
for (const file of sourceFiles(path.join(UI_ROOT, 'src'))) {
const source = fs.readFileSync(file, 'utf8');
for (const [, specifier] of source.matchAll(RELATIVE_SPECIFIER)) {
const resolved = path.resolve(path.dirname(file), specifier);
- if (!resolved.startsWith(UI_ROOT)) found.add(path.relative(REPO_ROOT, resolved));
+ if (!resolved.startsWith(UI_ROOT)) found.add(repoRelativePosix(REPO_ROOT, resolved));
}
}
return [...found].sort();
diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsx
index 3b0a13d18..38484457e 100644
--- a/ui/src/components/VersionBadge.tsx
+++ b/ui/src/components/VersionBadge.tsx
@@ -116,6 +116,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
};
const hasUpdate = versionInfo?.has_update === true;
+ const isDesktopManaged = versionInfo?.managed_by === 'desktop';
const currentVersion = versionInfo?.current || '...';
const isSourceBuild = versionInfo?.build?.kind === 'source';
const sourceRevision = versionInfo?.build?.revision;
@@ -231,7 +232,12 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
)}
{/* Update Status */}
- {!isSourceBuild && (hasUpdate ? (
+ {!isSourceBuild && (isDesktopManaged ? (
+ <div className="flex items-center gap-2 rounded-md border border-cyan/30 bg-cyan/10 px-3 py-2 text-sm text-cyan-ink">
+ <Check size={16} className="shrink-0" />
+ <span>{t('dashboard.desktopManagedUpdate')}</span>
+ </div>
+ ) : hasUpdate ? (
<div className="flex items-center gap-2 rounded-md border border-gold/30 bg-gold/10 px-3 py-2 text-sm text-gold-ink">
<AlertCircle size={16} className="shrink-0" />
<span>
@@ -279,7 +285,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
)}
{/* Auto Update Toggle */}
- {!isSourceBuild && autoUpdate !== null && (
+ {!isSourceBuild && !isDesktopManaged && autoUpdate !== null && (
<div className="flex items-center justify-between gap-3 border-t border-border pt-3">
<div className="min-w-0">
<div className="text-sm text-foreground">{t('dashboard.autoUpdate')}</div>
@@ -296,7 +302,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
</div>
{/* Actions */}
- {hasUpdate && !restarting && (
+ {hasUpdate && !isDesktopManaged && !restarting && (
<div className="flex justify-end border-t border-border px-4 py-3">
<Button variant="brand" size="xs" onClick={handleUpgrade} disabled={upgrading}>
<Download size={14} className={upgrading ? 'animate-bounce' : ''} />
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
index f425c6530..ac7ebda6b 100644
--- a/ui/src/components/settings/BackendLifecycleChip.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -410,6 +410,14 @@ const StateBlock: React.FC<{
</div>
);
}
+ if (runtime?.managed_by === 'desktop') {
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-cyan/25 bg-cyan/10 px-3 py-2 text-sm text-cyan">
+ <Check size={16} className="shrink-0" />
+ <span>{t('backendLifecycle.desktopManagedHint')}</span>
+ </div>
+ );
+ }
if (visual === 'error') {
return (
<div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink">
diff --git a/ui/src/components/settings/SettingsDependenciesPage.logic.ts b/ui/src/components/settings/SettingsDependenciesPage.logic.ts
index 2e765d03c..1e822ba7b 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.logic.ts
+++ b/ui/src/components/settings/SettingsDependenciesPage.logic.ts
@@ -1,4 +1,4 @@
-import type { DependencyItem } from '@/context/ApiContext';
+import type { DependenciesResult, DependencyItem } from '@/context/ApiContext';
const INSTALLABLE_DEPENDENCIES = new Set([
'askill',
@@ -8,6 +8,8 @@ const INSTALLABLE_DEPENDENCIES = new Set([
'tmux',
]);
+const STARTUP_MANAGED_DEPENDENCIES = new Set(['askill', 'avault', 'show-runtime', 'model-hub-engine', 'tmux']);
+
export const dependencyHasInstallAction = (
dependency: Pick<DependencyItem, 'id' | 'status' | 'action_class'>,
): boolean => (
@@ -17,3 +19,32 @@ export const dependencyHasInstallAction = (
&& dependency.action_class !== 'operator_only'
&& INSTALLABLE_DEPENDENCIES.has(dependency.id)
);
+
+export const dependencyIsStartupManaged = (dependency: Pick<DependencyItem, 'id'>): boolean =>
+ STARTUP_MANAGED_DEPENDENCIES.has(dependency.id);
+
+/** Manual repair must wait for the startup pass, even before this step starts. */
+export const dependencyNeedsStartupRepair = (
+ dependency: Pick<DependencyItem, 'id' | 'status'>,
+): boolean =>
+ dependencyIsStartupManaged(dependency) &&
+ (dependency.status === 'missing' || dependency.status === 'upgrade_required' || dependency.status === 'error');
+
+export const dependencyIsStartupRepairing = (
+ dependency: Pick<DependencyItem, 'id' | 'installed' | 'status'>,
+ activeIds?: ReadonlySet<string>,
+): boolean =>
+ dependencyIsStartupManaged(dependency) &&
+ (activeIds === undefined || activeIds.has(dependency.id)) &&
+ (!dependency.installed || dependency.status === 'upgrade_required' || dependency.status === 'error');
+
+export const dependenciesNeedAutomaticRefresh = (
+ result: DependenciesResult,
+ allowInitialRetry = false,
+): boolean => {
+ const activeIds = Array.isArray(result.reconciling_dependencies)
+ ? new Set(result.reconciling_dependencies)
+ : undefined;
+ return Boolean(result.reconciling) ||
+ (allowInitialRetry && result.deps.some((dependency) => dependencyIsStartupRepairing(dependency, activeIds)));
+};
diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.ts b/ui/src/components/settings/SettingsDependenciesPage.test.ts
index 63b8f174c..59dd50c37 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.test.ts
+++ b/ui/src/components/settings/SettingsDependenciesPage.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { dependencyHasInstallAction } from './SettingsDependenciesPage.logic';
+import {
+ dependencyHasInstallAction,
+ dependencyIsStartupManaged,
+ dependencyIsStartupRepairing,
+ dependencyNeedsStartupRepair,
+ dependenciesNeedAutomaticRefresh,
+} from './SettingsDependenciesPage.logic';
describe('dependencyHasInstallAction', () => {
it('keeps generic dependency evidence and admission distinct', () => {
@@ -11,3 +17,96 @@ describe('dependencyHasInstallAction', () => {
expect(dependencyHasInstallAction({ id: 'node', status: 'missing' })).toBe(false);
});
});
+
+describe('startup dependency refresh', () => {
+ const dependency = (id: string, installed: boolean) => ({
+ id,
+ kind: 'tool' as const,
+ required: true,
+ installed,
+ version: null,
+ status: installed ? ('ready' as const) : ('missing' as const),
+ });
+
+ it('tracks every dependency repaired by the startup reconciler', () => {
+ for (const id of ['askill', 'avault', 'show-runtime', 'tmux']) {
+ expect(dependencyIsStartupManaged({ id })).toBe(true);
+ }
+ expect(dependencyIsStartupManaged({ id: 'node' })).toBe(false);
+ expect(dependencyIsStartupManaged({ id: 'memory-runtime' })).toBe(false);
+ });
+
+ it('allows one initial retry when startup reconciliation has not acquired its lock yet', () => {
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: false,
+ deps: [dependency('show-runtime', false)],
+ }, true),
+ ).toBe(true);
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: false,
+ deps: [dependency('show-runtime', false)],
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps polling while startup reconciliation is active', () => {
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: true,
+ deps: [dependency('show-runtime', true)],
+ }),
+ ).toBe(true);
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: false,
+ deps: [dependency('show-runtime', true), dependency('memory-runtime', false)],
+ }),
+ ).toBe(false);
+ });
+
+ it('treats installed dependencies requiring an upgrade as startup repairs', () => {
+ expect(
+ dependencyIsStartupRepairing({ id: 'avault', installed: true, status: 'upgrade_required' }),
+ ).toBe(true);
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: false,
+ deps: [{ ...dependency('avault', true), status: 'upgrade_required' }],
+ }, true),
+ ).toBe(true);
+ });
+
+ it('keeps a later step pending even though only the running step is active', () => {
+ const active = new Set(['askill']);
+ const later = dependency('model-hub-engine', false);
+ expect(dependencyIsStartupRepairing(later, active)).toBe(false);
+ expect(dependencyNeedsStartupRepair(later)).toBe(true);
+ expect(dependencyNeedsStartupRepair({ id: 'avault', installed: true, status: 'upgrade_required' })).toBe(true);
+ expect(dependencyNeedsStartupRepair({ id: 'tmux', installed: true, status: 'error' })).toBe(true);
+ expect(dependencyNeedsStartupRepair(dependency('avault', true))).toBe(false);
+ expect(dependencyNeedsStartupRepair({ id: 'show-runtime', installed: null, status: 'unknown' })).toBe(false);
+ expect(dependencyIsStartupRepairing({ id: 'show-runtime', installed: null, status: 'unknown' }, new Set(['show-runtime']))).toBe(true);
+ expect(dependencyNeedsStartupRepair(dependency('node', false))).toBe(false);
+ });
+
+ it('limits startup repair status to dependencies currently active in the backend', () => {
+ const showRuntime = dependency('show-runtime', false);
+ expect(dependencyIsStartupRepairing(showRuntime, new Set(['tmux']))).toBe(false);
+ expect(dependencyIsStartupRepairing(showRuntime, new Set(['show-runtime']))).toBe(true);
+ expect(
+ dependenciesNeedAutomaticRefresh({
+ ok: true,
+ reconciling: false,
+ reconciling_dependencies: [],
+ deps: [showRuntime],
+ }, true),
+ ).toBe(false);
+ });
+});
diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsx
index fdd2aae4f..fdd217154 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx
@@ -140,6 +140,55 @@ describe('SettingsDependenciesPage Model Hub engine', () => {
});
});
+describe('SettingsDependenciesPage startup reconciliation', () => {
+ it('blocks the active step even when its status is outside the queued repair set', async () => {
+ stubDependencies({
+ ok: true,
+ reconciling: true,
+ reconciling_dependencies: ['askill'],
+ deps: [dependency({ id: 'askill', installed: null, status: 'unknown', action_class: 'repairable' })],
+ });
+ renderPage();
+
+ const active = await screen.findByRole('button', { name: 'settings.dependencies.installing' });
+ expect((active as HTMLButtonElement).disabled).toBe(true);
+ expect(active.querySelector('.animate-spin')).not.toBeNull();
+ await userEvent.click(active);
+ expect(api.installDependency).not.toHaveBeenCalled();
+ });
+
+ it('withholds a later step while another step installs, and releases it when the pass ends', async () => {
+ const deps = [
+ dependency({ id: 'askill', installed: false, status: 'missing', action_class: 'repairable', version: null }),
+ dependency({ id: 'model-hub-engine', installed: false, status: 'missing', action_class: 'repairable', version: null }),
+ dependency({ id: 'avault' }),
+ ];
+ stubDependencies({ ok: true, reconciling: true, reconciling_dependencies: ['askill'], deps });
+ renderPage();
+
+ const running = await screen.findByRole('button', { name: 'settings.dependencies.installing' });
+ const later = screen.getByRole('button', { name: 'settings.dependencies.install' }) as HTMLButtonElement;
+ const ready = screen.getByRole('button', { name: 'settings.dependencies.reinstall' }) as HTMLButtonElement;
+ expect((running as HTMLButtonElement).disabled).toBe(true);
+ expect(later.disabled).toBe(true);
+ expect(ready.disabled).toBe(false);
+ // Only the running step reads as installing; the later one is still missing.
+ expect(running.querySelector('.animate-spin')).not.toBeNull();
+ expect(later.querySelector('.animate-spin')).toBeNull();
+ expect(screen.getAllByText('settings.dependencies.installing')).toHaveLength(2);
+ expect(screen.getByText('settings.dependencies.statusMissing')).toBeTruthy();
+ await userEvent.click(later);
+ expect(api.installDependency).not.toHaveBeenCalled();
+
+ stubDependencies({ ok: true, reconciling: false, reconciling_dependencies: [], deps });
+ await userEvent.click(screen.getByRole('button', { name: 'settings.dependencies.recheckAll' }));
+ await waitFor(() => expect(screen.getAllByRole('button', { name: 'settings.dependencies.install' })).toHaveLength(2));
+ for (const button of screen.getAllByRole('button', { name: 'settings.dependencies.install' })) {
+ expect((button as HTMLButtonElement).disabled).toBe(false);
+ }
+ });
+});
+
describe('SettingsDependenciesPage independent checks', () => {
it('shows completed checks and permits their actions while another check waits', async () => {
stubDependencies({ ok: true, deps: [dependency({ id: 'avault' })] });
diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsx
index 4292a3a68..634075e3d 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx
@@ -25,7 +25,9 @@ import { useApi } from '@/context/ApiContext';
import type { DependencyItem, InstallResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import {
+ dependencyIsStartupRepairing,
dependencyHasInstallAction,
+ dependencyNeedsStartupRepair,
} from './SettingsDependenciesPage.logic';
import { errorMessage } from '@/lib/errorMessage';
import { useDependencyChecks } from './useDependencyChecks';
@@ -93,6 +95,7 @@ export const SettingsDependenciesPage: React.FC = () => {
};
const statusText = (d: DependencyItem) => {
+ if (checks[d.id]?.reconciling && dependencyIsStartupRepairing(d, checks[d.id].reconcilingDependencies)) return t('settings.dependencies.installing');
// Closed non-installed failure states render distinctly, ahead
// of the generic "not installed" fallback.
if (d.status === 'unsupported') return t('settings.dependencies.statusUnsupported');
@@ -109,6 +112,7 @@ export const SettingsDependenciesPage: React.FC = () => {
};
const statusVariant = (d: DependencyItem): 'secondary' | 'success' | 'warning' | 'destructive' => {
+ if (checks[d.id]?.reconciling && dependencyIsStartupRepairing(d, checks[d.id].reconcilingDependencies)) return 'warning';
if (d.status === 'not_required') return 'secondary';
if (d.status === 'error') return 'destructive';
if (d.status === 'unknown') return 'warning';
@@ -194,6 +198,8 @@ export const SettingsDependenciesPage: React.FC = () => {
);
}
const installing = busy === d.id;
+ const startupInstalling = Boolean(check.reconciling) && dependencyIsStartupRepairing(d, check.reconcilingDependencies);
+ const startupRepairPending = Boolean(check.reconciling) && dependencyNeedsStartupRepair(d);
const showAction = dependencyHasInstallAction(d);
const repairBlockedBySidecar = false;
const dependencyOperationBusy = busy !== null || check.checking || check.error !== null;
@@ -238,17 +244,17 @@ export const SettingsDependenciesPage: React.FC = () => {
<Button
variant={d.installed ? 'secondary' : 'brand'}
size="xs"
- disabled={dependencyOperationBusy || repairBlockedBySidecar}
+ disabled={dependencyOperationBusy || repairBlockedBySidecar || startupInstalling || startupRepairPending}
onClick={() => void install(d, id)}
>
- {installing ? (
+ {installing || startupInstalling ? (
<Loader2 className="size-3.5 animate-spin" />
) : d.installed || d.status === 'error' ? (
<RefreshCw className="size-3.5" />
) : (
<Download className="size-3.5" />
)}
- {actionText(d, installing)}
+ {actionText(d, installing || startupInstalling)}
</Button>
)}
</>
diff --git a/ui/src/components/settings/shared/useBackendRuntime.test.tsx b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
new file mode 100644
index 000000000..7031c08a3
--- /dev/null
+++ b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
@@ -0,0 +1,87 @@
+/* @vitest-environment jsdom */
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useBackendRuntime } from './useBackendRuntime';
+
+
+const mocks = vi.hoisted(() => ({
+ api: {
+ getConfig: vi.fn(),
+ detectCli: vi.fn(),
+ installAgent: vi.fn(),
+ saveConfig: vi.fn(),
+ },
+ showToast: vi.fn(),
+}));
+
+vi.mock('@/context/ApiContext', () => ({ useApi: () => mocks.api }));
+vi.mock('@/context/ToastContext', () => ({
+ useToast: () => ({ showToast: mocks.showToast }),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.api.getConfig.mockResolvedValue({
+ agents: { claude: { enabled: true, cli_path: 'claude' } },
+ });
+ mocks.api.detectCli.mockImplementation(async (binary: string) => ({
+ found: true,
+ path: binary,
+ }));
+ mocks.api.installAgent.mockResolvedValue({
+ ok: true,
+ message: 'installed',
+ path: '/private/backends/claude',
+ });
+ mocks.api.saveConfig.mockResolvedValue({});
+});
+
+const mountRuntime = async () => {
+ const hook = renderHook(() =>
+ useBackendRuntime({ backend: 'claude', defaultCli: 'claude' }),
+ );
+ await waitFor(() => expect(hook.result.current.loaded).toBe(true));
+ await waitFor(() => expect(hook.result.current.detecting).toBe(false));
+ return hook;
+};
+
+describe('persisted backend install paths', () => {
+ it('does not mark a lifecycle install as an unsaved path edit', async () => {
+ const hook = await mountRuntime();
+
+ await act(async () => {
+ await hook.result.current.handleLifecycleChanged({
+ installedPath: '/private/backends/claude',
+ });
+ });
+
+ expect(hook.result.current.cliPath).toBe('/private/backends/claude');
+ expect(hook.result.current.runtimeDirty).toBe(false);
+ });
+
+ it('preserves a newer draft while adopting the installed saved path', async () => {
+ const hook = await mountRuntime();
+ act(() => hook.result.current.setCliPath('/user/edit'));
+ await act(async () => {
+ await hook.result.current.handleLifecycleChanged({ installedPath: '/private/backends/claude' });
+ });
+ expect(hook.result.current.cliPath).toBe('/user/edit');
+ expect(hook.result.current.runtimeDirty).toBe(true);
+ });
+
+ it('does not mark the direct install action as an unsaved path edit', async () => {
+ const hook = await mountRuntime();
+
+ await act(async () => {
+ await hook.result.current.install();
+ });
+
+ expect(hook.result.current.cliPath).toBe('/private/backends/claude');
+ expect(hook.result.current.runtimeDirty).toBe(false);
+ });
+});
diff --git a/ui/src/components/settings/useDependencyChecks.test.tsx b/ui/src/components/settings/useDependencyChecks.test.tsx
index 2a615bd3f..22dc3dc0e 100644
--- a/ui/src/components/settings/useDependencyChecks.test.tsx
+++ b/ui/src/components/settings/useDependencyChecks.test.tsx
@@ -89,6 +89,35 @@ describe('independent dependency checks', () => {
},
);
+ it('refreshes a startup repair until settled without waiting on another group', async () => {
+ vi.useFakeTimers();
+ try {
+ const slow = deferred();
+ let repairing = true;
+ const read = vi.fn(async (options: DependencyReadOptions = {}) => (
+ options.ids?.includes('askill') ? slow.promise : {
+ ...ready(options), reconciling: repairing,
+ reconciling_dependencies: repairing ? ['show-runtime'] : [],
+ }
+ ));
+ const { result, unmount } = renderHook(() => useDependencyChecks(read));
+ act(() => { void result.current.refresh(); });
+ await act(async () => { await Promise.resolve(); });
+ expect(result.current.checks.askill.checking).toBe(true);
+ expect(result.current.checks['show-runtime'].reconciling).toBe(true);
+ repairing = false;
+ await act(async () => { await vi.advanceTimersByTimeAsync(1_500); });
+ expect(result.current.checks['show-runtime'].reconciling).toBe(false);
+ const calls = read.mock.calls.length;
+ await act(async () => { await vi.advanceTimersByTimeAsync(3_000); });
+ expect(read).toHaveBeenCalledTimes(calls);
+ unmount();
+ await act(async () => slow.resolve(ready({ ids: ['askill'] })));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('cancels every owned request on unmount', async () => {
const slow = deferred();
const read = vi.fn((_options?: DependencyReadOptions) => slow.promise);
diff --git a/ui/src/components/settings/useDependencyChecks.ts b/ui/src/components/settings/useDependencyChecks.ts
index 5400ffd38..0b73bc281 100644
--- a/ui/src/components/settings/useDependencyChecks.ts
+++ b/ui/src/components/settings/useDependencyChecks.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import type { DependenciesResult, DependencyItem, DependencyReadOptions } from '@/context/ApiContext';
import { isApiFetchDeadlineAbort } from '@/lib/apiFetch';
+import { dependenciesNeedAutomaticRefresh } from './SettingsDependenciesPage.logic';
// Coupled rows use one inspection, including its failure evidence.
export const DEPENDENCY_CHECK_GROUPS = [
@@ -16,6 +17,8 @@ export type DependencyCheck = {
data: DependencyItem | null;
checking: boolean;
error: 'failed' | 'timeout' | null;
+ reconciling?: boolean;
+ reconcilingDependencies?: ReadonlySet<string>;
};
type ReadDependencies = (options?: DependencyReadOptions) => Promise<DependenciesResult>;
@@ -27,22 +30,28 @@ export function useDependencyChecks(read: ReadDependencies) {
])),
));
const requests = useRef(new Map<string, AbortController>());
+ const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
useEffect(() => {
const active = requests.current;
+ const scheduled = timers.current;
return () => {
for (const request of active.values()) request.abort();
active.clear();
+ for (const timer of scheduled.values()) clearTimeout(timer);
+ scheduled.clear();
};
}, []);
- const refresh = useCallback(async (dependencyId?: string) => {
+ const refresh = useCallback(async (dependencyId?: string, allowInitialRetry = true) => {
const groups = DEPENDENCY_CHECK_GROUPS.filter((ids) => (
dependencyId === undefined || ids.some((id) => id === dependencyId)
));
await Promise.all(groups.map(async (ids) => {
const key = ids[0];
requests.current.get(key)?.abort();
+ clearTimeout(timers.current.get(key));
+ timers.current.delete(key);
const controller = new AbortController();
requests.current.set(key, controller);
const update = (change: (previous: DependencyCheck, id: string) => DependencyCheck) => {
@@ -58,7 +67,16 @@ export function useDependencyChecks(read: ReadDependencies) {
throw new Error('Incomplete dependency inspection');
}
const byId = new Map(result.deps.map((dep) => [dep.id, dep]));
- update((_previous, id) => ({ data: byId.get(id)!, checking: false, error: null }));
+ update((_previous, id) => ({
+ data: byId.get(id)!, checking: false, error: null,
+ reconciling: result.reconciling,
+ reconcilingDependencies: result.reconciling_dependencies
+ ? new Set(result.reconciling_dependencies) : undefined,
+ }));
+ if (requests.current.get(key) === controller && !controller.signal.aborted
+ && dependenciesNeedAutomaticRefresh(result, allowInitialRetry)) {
+ timers.current.set(key, setTimeout(() => void refresh(key, false), 1_500));
+ }
} catch (error) {
update((previous) => ({
...previous,
diff --git a/ui/src/components/workbench/ShowPageLaunchControl.test.tsx b/ui/src/components/workbench/ShowPageLaunchControl.test.tsx
new file mode 100644
index 000000000..8974ef62e
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageLaunchControl.test.tsx
@@ -0,0 +1,68 @@
+/** @vitest-environment jsdom */
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import { ShowPageLaunchControl } from './ShowPageLaunchControl';
+
+const windowManager = vi.hoisted(() => ({ openApp: vi.fn(), setGestureActive: vi.fn() }));
+const dock = vi.hoisted(() => ({ isPinned: vi.fn(() => false), dock: vi.fn(), pin: vi.fn() }));
+const showPageDrag = vi.hoisted(() => ({ begin: vi.fn(), end: vi.fn() }));
+
+vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => windowManager }));
+vi.mock('../../context/DockContext', () => ({ useDock: () => dock }));
+vi.mock('../../context/showPageDrag', () => ({ useShowPageDrag: () => showPageDrag }));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const DESKTOP_SHELL_FLAG = '__AVIBE_DESKTOP_SHELL__';
+
+afterEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, DESKTOP_SHELL_FLAG);
+ vi.clearAllMocks();
+});
+
+/** Renders the control and opens its launch menu the way a keyboard user does. */
+const openLaunchMenu = () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ShowPageLaunchControl
+ sessionId="ses-1"
+ title="Plan"
+ showPageMode={false}
+ busy={false}
+ onToggle={vi.fn()}
+ onPrepareLaunch={vi.fn(async () => true)}
+ />
+ </I18nextProvider>,
+ );
+ fireEvent.keyDown(screen.getByRole('button', { name: en.chat.showPage.open }), { key: 'ArrowDown' });
+ return screen.getByRole('menu', { name: en.chat.showPage.launchMenu });
+};
+
+describe('ShowPageLaunchControl launch menu', () => {
+ it('offers a new window and a new link in a browser', () => {
+ openLaunchMenu();
+
+ expect(screen.getByRole('menuitem', { name: en.chat.showPage.newWindow })).toBeTruthy();
+ expect(screen.getByRole('menuitem', { name: en.chat.showPage.newLink })).toBeTruthy();
+ });
+
+ it('offers only the new window inside the desktop shell, which never yields a pre-opened tab', () => {
+ Object.defineProperty(window, DESKTOP_SHELL_FLAG, { value: true, configurable: true });
+
+ openLaunchMenu();
+
+ expect(screen.getByRole('menuitem', { name: en.chat.showPage.newWindow })).toBeTruthy();
+ expect(screen.queryByRole('menuitem', { name: en.chat.showPage.newLink })).toBeNull();
+ });
+});
diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsx
index 95eda502a..7a4cca712 100644
--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx
+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx
@@ -19,6 +19,7 @@ import {
showPageWindowOrigin,
type ViewportPoint,
} from '../../lib/showPageLaunch';
+import { isDesktopShell } from '../../lib/desktopShell';
import { isDesktopViewport } from '../../lib/useIsDesktop';
import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';
import { Button } from '../ui/button';
@@ -62,7 +63,9 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({
const canLaunch = !showPageMode && !busy && Boolean(sessionId);
const windowTitle = title?.trim() || t('chat.untitled');
- const linkHref = appTabHref({ appId: 'showpage', sessionId });
+ // The desktop shell hands web links to the system browser and never yields a
+ // pre-opened tab, so this document has nothing to navigate: offer no link item.
+ const linkHref = isDesktopShell() ? null : appTabHref({ appId: 'showpage', sessionId });
const clearHoverTimer = useCallback(() => {
if (hoverTimerRef.current === null) return;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 2f639beb5..a97f77080 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1858,6 +1858,7 @@ export type VersionInfo = {
latest: string | null;
has_update: boolean;
error: string | null;
+ managed_by?: 'desktop';
build?: {
kind: 'package' | 'source';
revision?: string;
@@ -1870,6 +1871,7 @@ export type UpgradeResult = {
message: string;
output: string | null;
restarting: boolean;
+ code?: string;
};
export type InstallResult = {
@@ -1879,6 +1881,7 @@ export type InstallResult = {
path?: string | null;
job_id?: string;
status?: 'running' | 'succeeded' | 'failed' | 'rejected';
+ poll_timeout_seconds?: number;
reason?: string | null;
action_class?: 'operator_only';
download_error?: DependencyDownloadError | null;
@@ -1911,7 +1914,12 @@ export type DependencyItem = {
inspection_error?: { kind: string; message: string } | null;
};
-export type DependenciesResult = { ok: boolean; deps: DependencyItem[] };
+export type DependenciesResult = {
+ ok: boolean;
+ deps: DependencyItem[];
+ reconciling?: boolean;
+ reconciling_dependencies?: string[];
+};
export type DependencyReadOptions = { ids?: readonly string[]; signal?: AbortSignal };
export type BackendConnectionState = {
@@ -1939,6 +1947,7 @@ export type BackendRuntimeInfo = {
current_version?: string | null;
latest_version?: string | null;
has_update?: boolean;
+ managed_by?: 'desktop';
supports_restart?: boolean;
process_status?: 'running' | 'stopped' | 'unknown';
error?: string;
@@ -3293,7 +3302,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const jobId = typeof started?.job_id === 'string' ? started.job_id : null;
if (!jobId) return started;
- const deadline = Date.now() + 310_000;
+ const serverBudgetSeconds = started?.poll_timeout_seconds;
+ const pollBudgetMs =
+ typeof serverBudgetSeconds === 'number' && Number.isFinite(serverBudgetSeconds)
+ ? Math.max(310_000, serverBudgetSeconds * 1000)
+ : 390_000;
+ const deadline = Date.now() + pollBudgetMs;
let last = started;
while (Date.now() < deadline) {
await sleep(1000);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e0fbaf873..c4ad7e97a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1,4 +1,84 @@
{
+ "desktopBootstrap": {
+ "retry": "Try again",
+ "installationHelp": "Installation help",
+ "notRunningTitle": "Avibe — not running",
+ "shellUnavailable": "The Avibe desktop shell stopped responding. Quit and open Avibe again.",
+ "genericFailure": "Avibe could not connect to its Runtime.",
+ "notices": {
+ "probing": "Looking for a running Avibe Runtime…",
+ "adopted": "Connected to the Avibe Runtime already running on this machine.",
+ "starting": "Starting the Avibe Runtime…",
+ "ready": "The Avibe Runtime is ready.",
+ "invalid_origin": "Avibe refused an unsafe Runtime address.",
+ "runtime_not_found": "No Avibe Runtime is installed on this machine.",
+ "runtime_install_failed": "Avibe could not prepare its built-in Runtime. Try again or reinstall the app.",
+ "runtime_discovery_failed": "Avibe could not determine the local Runtime address.",
+ "runtime_spawn_failed": "Avibe could not start the installed Runtime.",
+ "runtime_stopped": "The Runtime was stopped. Choose Try again to start it when you are ready.",
+ "runtime_ownership_lost": "The Runtime changed and this app can no longer stop it. Choose Try again to check the current Runtime.",
+ "launcher_exited": "The Avibe Runtime stopped instead of starting. Update Avibe, then try again.",
+ "ready_timeout": "The Avibe Runtime did not become ready within {{seconds}} seconds.",
+ "workbench_navigation_failed": "Avibe could not open the Workbench in this window."
+ },
+ "tray": {
+ "open": "Open Avibe",
+ "starting": "Runtime: starting…",
+ "serving": "Runtime: serving on {{address}}",
+ "unreachable": "Runtime: unreachable",
+ "stopped": "Runtime: stopped",
+ "stopping": "Runtime: stopping…",
+ "stop": "Stop Runtime…",
+ "quit": "Quit",
+ "login": "Start at Login",
+ "settings": "Settings…",
+ "stopTitle": "Stop Runtime",
+ "stopMessage": "Stop the Runtime started by this app? Active work will be interrupted. The desktop app stays open and your data is preserved.",
+ "stopAction": "Stop Runtime",
+ "quitTitle": "Quit Avibe",
+ "quitMessage": "This app started the Runtime. Stop it when quitting, or keep it running so active work can continue?",
+ "quitStop": "Quit and stop Runtime",
+ "quitKeep": "Keep Runtime running",
+ "cancel": "Cancel",
+ "busyTitle": "Avibe Is Busy",
+ "busyMessage": "The Runtime is starting or another lifecycle action is in progress. Please try again when it finishes.",
+ "failureTitle": "Action Could Not Be Completed",
+ "stopFailure": "The Runtime could not be stopped safely. Avibe remains open. Try again after checking the Runtime.",
+ "loginFailure": "The login setting could not be read or changed. Check your operating system's login settings and try again."
+ },
+ "notifications": {
+ "toggle": "Notifications",
+ "approvalRequested": {
+ "title": "Approval needed",
+ "body": "A Vault request is waiting for your approval."
+ },
+ "runSucceeded": {
+ "title": "Run completed",
+ "body": "Background work has finished successfully."
+ },
+ "runFailed": {
+ "title": "Run failed",
+ "body": "Background work could not finish. Open the Workbench to review it."
+ },
+ "runCanceled": {
+ "title": "Run canceled",
+ "body": "Background work was canceled."
+ }
+ },
+ "uninstall": {
+ "menuLabel": "Uninstall Avibe…",
+ "confirmTitle": "Uninstall Avibe",
+ "confirmMessage": "This removes Avibe's private Runtime and privately installed agent backends, then quits the desktop app. External tools and your projects, sessions, and settings under ~/.avibe are preserved.",
+ "confirmAction": "Remove Private Files",
+ "cancelAction": "Cancel",
+ "busyTitle": "Avibe Is Busy",
+ "busyMessage": "Wait for Avibe to finish starting, then choose Uninstall Avibe again.",
+ "successTitle": "Avibe Private Files Removed",
+ "successMessage": "The private Runtime and agent backends were removed. Avibe will now quit. You can delete the application or run the system uninstaller.",
+ "failureTitle": "Uninstall Failed",
+ "failureMessage": "Avibe could not remove all private Runtime and backend files. The desktop app remains installed and your user data was not changed."
+ }
+ },
"installHint": {
"cta": "Add to Home Screen",
"title": "Use Avibe like an app",
@@ -3011,6 +3091,7 @@
"currentVersion": "Current version",
"latestVersion": "Latest version",
"readyHint": "Running the latest release.",
+ "desktopManagedHint": "Installed privately by Avibe. System tools are unchanged.",
"updateHint": "Update available: {{from}} → {{to}}",
"errorHint": "{{name}} CLI is not installed. Install it from this card to enable the backend.",
"disabledHint": "Toggle this backend on in the card header to activate.",
@@ -3279,7 +3360,8 @@
"updateHint": "Update from {{from}} to {{to}}",
"restarting": "Restarting...",
"autoUpdate": "Auto Update",
- "autoUpdateHint": "Auto-install when idle"
+ "autoUpdateHint": "Auto-install when idle",
+ "desktopManagedUpdate": "Updates are delivered with the Avibe desktop app"
},
"doctor": {
"title": "System Status",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 6c5cc98bf..0b7861452 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1,4 +1,84 @@
{
+ "desktopBootstrap": {
+ "retry": "重试",
+ "installationHelp": "安装帮助",
+ "notRunningTitle": "Avibe — 未运行",
+ "shellUnavailable": "Avibe 桌面端已停止响应,请退出后重新打开。",
+ "genericFailure": "Avibe 无法连接到 Runtime。",
+ "notices": {
+ "probing": "正在查找运行中的 Avibe Runtime…",
+ "adopted": "已连接到本机正在运行的 Avibe Runtime。",
+ "starting": "正在启动 Avibe Runtime…",
+ "ready": "Avibe Runtime 已就绪。",
+ "invalid_origin": "Avibe 已拒绝不安全的 Runtime 地址。",
+ "runtime_not_found": "本机尚未安装 Avibe Runtime。",
+ "runtime_install_failed": "Avibe 无法准备内置 Runtime。请重试或重新安装应用。",
+ "runtime_discovery_failed": "Avibe 无法确定本地 Runtime 地址。",
+ "runtime_spawn_failed": "Avibe 无法启动已安装的 Runtime。",
+ "runtime_stopped": "运行时已停止。准备就绪后,点击“重试”即可启动。",
+ "runtime_ownership_lost": "运行时已更换,此应用已无法停止它。点击“重试”以检查当前运行时。",
+ "launcher_exited": "Avibe Runtime 未能启动。请更新 Avibe 后重试。",
+ "ready_timeout": "Avibe Runtime 未能在 {{seconds}} 秒内就绪。",
+ "workbench_navigation_failed": "Avibe 无法在当前窗口中打开工作台。"
+ },
+ "tray": {
+ "open": "打开应用",
+ "starting": "运行时:正在启动…",
+ "serving": "运行时:正在 {{address}} 提供服务",
+ "unreachable": "运行时:无法连接",
+ "stopped": "运行时:已停止",
+ "stopping": "运行时:正在停止…",
+ "stop": "停止运行时…",
+ "quit": "退出",
+ "login": "登录时启动",
+ "settings": "设置…",
+ "stopTitle": "停止运行时",
+ "stopMessage": "要停止由本应用启动的运行时吗?正在进行的工作会被中断。桌面应用将保持打开,你的数据会被保留。",
+ "stopAction": "停止运行时",
+ "quitTitle": "退出应用",
+ "quitMessage": "运行时由本应用启动。退出时要将其停止,还是让它继续运行以完成正在进行的工作?",
+ "quitStop": "退出并停止运行时",
+ "quitKeep": "保持运行时运行",
+ "cancel": "取消",
+ "busyTitle": "应用正忙",
+ "busyMessage": "运行时正在启动,或另一个生命周期操作正在进行。请等待完成后重试。",
+ "failureTitle": "无法完成操作",
+ "stopFailure": "无法安全停止运行时,应用将保持打开。请检查运行时后重试。",
+ "loginFailure": "无法读取或更改登录启动设置。请检查操作系统的登录设置后重试。"
+ },
+ "notifications": {
+ "toggle": "通知",
+ "approvalRequested": {
+ "title": "需要授权",
+ "body": "有一项密钥库请求正等待你的授权。"
+ },
+ "runSucceeded": {
+ "title": "运行已完成",
+ "body": "后台工作已成功完成。"
+ },
+ "runFailed": {
+ "title": "运行失败",
+ "body": "后台工作未能完成,请打开工作台查看详情。"
+ },
+ "runCanceled": {
+ "title": "运行已取消",
+ "body": "后台工作已取消。"
+ }
+ },
+ "uninstall": {
+ "menuLabel": "卸载 Avibe…",
+ "confirmTitle": "卸载 Avibe",
+ "confirmMessage": "此操作会移除 Avibe 的私有 Runtime 和私有安装的 Agent 后端,然后退出桌面应用。外部工具以及 ~/.avibe 下的项目、会话和设置将被保留。",
+ "confirmAction": "移除私有文件",
+ "cancelAction": "取消",
+ "busyTitle": "Avibe 正忙",
+ "busyMessage": "请等待 Avibe 完成启动,然后再次选择“卸载 Avibe”。",
+ "successTitle": "Avibe 私有文件已移除",
+ "successMessage": "私有 Runtime 和 Agent 后端已移除,Avibe 现在将退出。你可以删除应用或运行系统卸载程序。",
+ "failureTitle": "卸载失败",
+ "failureMessage": "Avibe 无法完整移除私有 Runtime 和后端文件。桌面应用仍保持安装状态,你的用户数据没有发生变化。"
+ }
+ },
"installHint": {
"cta": "装到主屏幕",
"title": "把 Avibe 当 App 用",
@@ -3011,6 +3091,7 @@
"currentVersion": "当前版本",
"latestVersion": "最新版本",
"readyHint": "当前已是最新版本。",
+ "desktopManagedHint": "由 Avibe 私有安装,不会修改系统工具。",
"updateHint": "可升级:{{from}} → {{to}}",
"errorHint": "{{name}} CLI 未安装,请在卡片上点击安装以启用该后端。",
"disabledHint": "请在卡片顶部开关中启用该后端。",
@@ -3279,7 +3360,8 @@
"updateHint": "从 {{from}} 更新到 {{to}}",
"restarting": "正在重启...",
"autoUpdate": "自动更新",
- "autoUpdateHint": "空闲时自动安装"
+ "autoUpdateHint": "空闲时自动安装",
+ "desktopManagedUpdate": "更新将随 Avibe 桌面应用提供"
},
"doctor": {
"title": "系统状态",
diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.ts
new file mode 100644
index 000000000..3222c7ba1
--- /dev/null
+++ b/ui/src/lib/desktopShell.ts
@@ -0,0 +1,15 @@
+declare global {
+ interface Window {
+ /** Defined by the Avibe desktop shell before any page script runs, top-level document only. */
+ readonly __AVIBE_DESKTOP_SHELL__?: true;
+ }
+}
+
+/**
+ * True when this document is the Avibe desktop shell's own window rather than a
+ * browser tab or an installed PWA. This is the host, not the viewport size: see
+ * `useIsDesktop` for the layout breakpoint.
+ */
+export function isDesktopShell(): boolean {
+ return typeof window !== 'undefined' && window.__AVIBE_DESKTOP_SHELL__ === true;
+}
diff --git a/vibe/api.py b/vibe/api.py
index 9e57b46ae..60cbd4f62 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -56,6 +56,28 @@ from vibe.opencode_config import (
set_jsonc_top_level_string_property,
)
from vibe.build_identity import get_build_identity
+from vibe.desktop_backends import (
+ DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS,
+ DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS,
+ DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS,
+ DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS,
+ DesktopBackendError,
+ desktop_backend_toolchain,
+ install_desktop_backend,
+ is_desktop_backend_path,
+)
+from vibe.desktop_runtime import is_private_desktop_runtime_path
+from vibe.cli_paths import (
+ _candidate_cli_paths,
+ _command_env_for,
+ _is_executable_file,
+ _npm_binary_candidates_for_prefix,
+ _npm_global_binary_candidates,
+ _npm_global_prefixes,
+ _npm_prefix_for,
+ _windows_executable_candidates,
+ resolve_cli_path as _resolve_cli_path,
+)
from vibe.upgrade import (
_candidate_python,
activation_block_reason,
@@ -68,6 +90,7 @@ from vibe.upgrade import (
get_latest_version_info,
get_running_vibe_path,
get_safe_cwd,
+ is_desktop_managed_runtime,
launcher_is_current_process,
restart_is_pending,
should_skip_show_runtime_prepare,
@@ -244,265 +267,14 @@ def _ensure_builtin_default_agents(config: Optional[V2Config] = None) -> None:
store.close()
-def _is_executable_file(path: Path) -> bool:
- return path.exists() and path.is_file() and os.access(path, os.X_OK)
-
-
-_NVM_VERSION_RE = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(.*)$")
-_NVM_SUFFIX_TOKEN_RE = re.compile(r"\d+|\D+")
-
-
-def _nvm_suffix_tokens(suffix: str) -> tuple[tuple[int, int, str], ...]:
- # Tokenize the prerelease suffix into (kind, num, text) triples so all
- # tokens are structurally identical and comparable. kind=0 marks numeric
- # tokens (compared by num) and kind=1 marks alphanumeric tokens (compared
- # by text). Numeric tokens compare numerically, so "-rc.10" beats
- # "-rc.2"; cross-kind tokens never compare int-vs-str, ruling out
- # TypeError for arbitrary suffix shapes.
- triples: list[tuple[int, int, str]] = []
- for tok in _NVM_SUFFIX_TOKEN_RE.findall(suffix):
- if tok.isdigit():
- triples.append((0, int(tok), ""))
- else:
- triples.append((1, 0, tok))
- return tuple(triples)
-
-
-def _nvm_version_sort_key(entry: Path) -> tuple:
- # Returns (major, minor, patch, is_released, suffix_tokens). is_released
- # is True for plain "vX.Y.Z" and False for any "-suffix"; with reverse=True
- # released versions outrank pre-releases of the same triple. Within
- # pre-releases, suffix_tokens compares numerically where digits appear.
- m = _NVM_VERSION_RE.match(entry.name)
- if not m:
- return (-1, -1, -1, False, ())
- major = int(m.group(1))
- minor = int(m.group(2)) if m.group(2) else 0
- patch = int(m.group(3)) if m.group(3) else 0
- suffix = m.group(4) or ""
- return (major, minor, patch, not suffix, _nvm_suffix_tokens(suffix))
-
-
-def _nvm_binary_candidates(binary: str) -> list[Path]:
- versions_dir = Path.home() / ".nvm" / "versions" / "node"
- if not versions_dir.exists():
- return []
-
- valid: list[Path] = []
- for entry in versions_dir.iterdir():
- # Skip non-directory entries (e.g. macOS .DS_Store) and non-version
- # dirs (e.g. nvm's "system" alias) before sorting.
- if not entry.is_dir():
- continue
- if not _NVM_VERSION_RE.match(entry.name):
- continue
- valid.append(entry)
-
- candidates: list[Path] = []
- for version_dir in sorted(valid, key=_nvm_version_sort_key, reverse=True):
- candidate = version_dir / "bin" / binary
- if candidate not in candidates:
- candidates.append(candidate)
- return candidates
-
-
-def _npm_global_binary_candidates(binary: str) -> list[Path]:
- if not binary or binary == "npm":
- return []
-
- candidates: list[Path] = []
- for prefix_path in _npm_global_prefixes():
- for candidate in _npm_binary_candidates_for_prefix(prefix_path, binary):
- if candidate not in candidates:
- candidates.append(candidate)
-
- return candidates
-
-
-def _npm_global_prefixes() -> list[Path]:
- # Global packages belong to the npm selected by the current environment.
- # Querying every historical NVM installation makes one missing CLI cost up
- # to five seconds per Node version without improving that answer.
- which_npm = shutil.which("npm")
- npm_path = Path(which_npm) if which_npm else next(
- (
- candidate
- for candidate in _candidate_cli_paths(
- "npm",
- include_npm_global=False,
- )
- if _is_executable_file(candidate)
- ),
- None,
- )
- if npm_path is None:
- return []
- prefix_path = _npm_prefix_for(npm_path)
- return [prefix_path] if prefix_path is not None else []
-
-
-def _npm_prefix_for(npm_path: str | Path) -> Path | None:
- try:
- result = subprocess.run(
- [str(npm_path), "config", "get", "prefix"],
- capture_output=True,
- text=True,
- timeout=5,
- env=_command_env_for(str(npm_path)),
- )
- except Exception:
- return None
-
- if result.returncode != 0:
- return None
-
- prefix = (result.stdout or "").strip().splitlines()
- if not prefix:
- return None
-
- return Path(os.path.expanduser(prefix[-1]))
-
-
-def _npm_binary_candidates_for_prefix(prefix_path: Path, binary: str) -> list[Path]:
- derived_candidates = [
- prefix_path / "bin" / binary,
- prefix_path / binary,
- prefix_path / "node_modules" / ".bin" / binary,
- ]
- if os.name == "nt":
- derived_candidates.extend(
- [
- prefix_path / f"{binary}.cmd",
- prefix_path / f"{binary}.exe",
- prefix_path / "node_modules" / ".bin" / f"{binary}.cmd",
- ]
- )
- return derived_candidates
-
-
-def _windows_executable_candidates(candidates: list[Path]) -> list[Path]:
- result: list[Path] = []
- for candidate in candidates:
- result.append(candidate)
- if candidate.suffix.lower() not in {".cmd", ".exe"}:
- result.extend(
- [
- candidate.with_name(f"{candidate.name}.exe"),
- candidate.with_name(f"{candidate.name}.cmd"),
- ]
- )
- return result
-
-
-def _candidate_cli_paths(
- binary: str,
- *,
- include_npm_global: bool = True,
-) -> list[Path]:
- if not binary:
- return []
-
- expanded = Path(os.path.expanduser(binary))
- has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)
- if expanded.is_absolute() or has_path_separator:
- return [expanded]
-
- home = Path.home()
- candidates: list[Path] = []
- if binary == "claude":
- candidates.append(home / ".claude" / "local" / "claude")
- elif binary == "opencode":
- candidates.extend(
- [
- home / ".opencode" / "bin" / "opencode",
- home / ".local" / "bin" / "opencode",
- ]
- )
-
- common_candidates = [
- home / ".local" / "bin" / binary,
- home / ".bun" / "bin" / binary,
- Path("/opt/homebrew/bin") / binary,
- Path("/usr/local/bin") / binary,
- ]
- if os.name == "nt":
- common_candidates = _windows_executable_candidates(common_candidates)
- for candidate in common_candidates + _nvm_binary_candidates(binary):
- if candidate not in candidates:
- candidates.append(candidate)
- if include_npm_global:
- for candidate in _npm_global_binary_candidates(binary):
- if candidate not in candidates:
- candidates.append(candidate)
-
- return candidates
-
-
-def _resolve_cli_path_once(
- binary: str,
- *,
- include_npm_global: bool,
-) -> str | None:
- for candidate in _candidate_cli_paths(binary, include_npm_global=False):
- if _is_executable_file(candidate):
- return str(candidate)
-
- path = shutil.which(os.path.expanduser(binary)) if binary else None
- if path:
- return path
-
- if include_npm_global:
- for candidate in _npm_global_binary_candidates(binary):
- if _is_executable_file(candidate):
- return str(candidate)
- return None
-
-
-def resolve_cli_path(
- binary: str,
- *,
- include_npm_global: bool = True,
-) -> str | None:
- path = _resolve_cli_path_once(
+def resolve_cli_path(binary: str, *, include_npm_global: bool = True) -> str | None:
+ return _resolve_cli_path(
binary,
include_npm_global=include_npm_global,
+ candidate_paths=_candidate_cli_paths,
+ is_executable_file=_is_executable_file,
+ include_desktop=include_npm_global,
)
- if path:
- return path
-
- # The stored cli_path was an absolute path that no longer exists. Most
- # common cause: an upstream installer moved the binary out from under us.
- # Real-world example: Claude Code's official ``install.sh`` puts the
- # native binary at ``~/.local/bin/claude`` (via ``~/.local/share/claude/
- # versions/<ver>``), while the legacy ``npm install -g
- # @anthropic-ai/claude-code`` install used ``/usr/local/bin/claude``.
- # After clicking "Upgrade" in the UI, V2Config still points at the
- # /usr/local/bin path, so the runtime probe reports ``installed=false``
- # and the chip flips to "not installed". Fall back to discovery using
- # only the basename — if a binary with that name is on any of the
- # standard candidate paths (~/.local/bin, /opt/homebrew/bin, npm/nvm/bun
- # globals, etc.) we treat that as the live install. The basename
- # restriction means custom callers passing ``"/path/to/my-claude"``
- # don't get silently redirected to the system claude.
- if not binary:
- return None
- expanded = Path(os.path.expanduser(binary))
- has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)
- if expanded.is_absolute() or has_path_separator:
- basename = expanded.name
- if basename and basename != binary:
- fallback = _resolve_cli_path_once(
- basename,
- include_npm_global=include_npm_global,
- )
- if fallback:
- logger.info(
- "resolve_cli_path: stored path %s missing; falling back to %s",
- binary,
- fallback,
- )
- return fallback
- return None
def resolve_cli_paths(
@@ -559,18 +331,15 @@ def resolve_cli_paths(
npm_path,
)
break
- return resolved
+ from vibe.desktop_backends import resolve_published_desktop_backend
+ for binary, path in resolved.items():
+ if path is None:
+ name = Path(os.path.expanduser(binary)).name
+ if name in {"claude", "codex", "opencode"}:
+ resolved[binary] = resolve_published_desktop_backend(name)
+ return resolved
-def _command_env_for(binary_path: str | None) -> dict[str, str]:
- env = {**os.environ, "PATH": os.environ.get("PATH", "")}
- if not binary_path:
- return env
-
- binary_dir = str(Path(binary_path).expanduser().resolve().parent)
- path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry and entry != binary_dir]
- env["PATH"] = os.pathsep.join([binary_dir, *path_entries])
- return env
def _codex_npm_install_env(npm_path: str, *, prefix: str | Path | None = None) -> dict[str, str]:
@@ -6357,17 +6126,23 @@ def get_version_info() -> dict:
"latest": str | None,
"has_update": bool,
"error": str | None,
- "build": {"kind": "package" | "source", ...}
+ "build": {"kind": "package" | "source", ...},
+ "managed_by": "desktop" | None
}
"""
from vibe import __version__
build = get_build_identity()
- if build.kind == "source":
+ managed_by = "desktop" if is_desktop_managed_runtime() else None
+ if managed_by:
+ result = {"current": __version__, "latest": None, "has_update": False, "error": None}
+ elif build.kind == "source":
result = {"current": __version__, "latest": None, "has_update": False, "error": None}
else:
result = get_latest_version_info(__version__)
result["build"] = build.as_dict()
+ if managed_by:
+ result["managed_by"] = managed_by
return result
@@ -6380,6 +6155,15 @@ def do_upgrade(auto_restart: bool = True) -> dict:
Returns:
{"ok": bool, "message": str, "output": str | None, "restarting": bool}
"""
+ if is_desktop_managed_runtime():
+ return {
+ "ok": False,
+ "message": backend_t("desktopRuntime.apiUpgrade", V2Config.load().language),
+ "output": None,
+ "restarting": False,
+ "code": "desktop_managed_runtime",
+ }
+
current_vibe_path = get_running_vibe_path()
try:
plan = build_upgrade_plan(
@@ -7108,6 +6892,14 @@ _AGENT_INSTALL_JOB_LOCK = threading.Lock()
_AGENT_INSTALL_JOBS: dict[str, dict] = {}
_AGENT_INSTALL_LATEST_BY_BACKEND: dict[str, str] = {}
_AGENT_INSTALL_JOB_TTL_SECONDS = 3600.0
+_AGENT_INSTALL_POLL_TIMEOUT_SECONDS = (
+ DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS
+ + DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS
+ + DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS
+ + DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS
+ + 4.0 # Controller refresh acknowledgement.
+ + 30.0 # Filesystem publication, persistence, and polling margin.
+)
def _prune_agent_install_jobs(now: float | None = None) -> None:
@@ -7179,6 +6971,7 @@ def start_agent_install_job(name: str) -> dict:
"message": "Upgrade started",
"output": "",
"path": None,
+ "poll_timeout_seconds": _AGENT_INSTALL_POLL_TIMEOUT_SECONDS,
"started_at": now,
"finished_at": None,
}
@@ -7271,6 +7064,115 @@ def get_agent_install_job(job_id: str | None = None, *, backend: str | None = No
return dict(job)
+def _configured_agent_cli_path(name: str) -> str:
+ try:
+ config = load_config()
+ except (FileNotFoundError, OSError, ValueError):
+ return name
+ backend = getattr(getattr(config, "agents", None), name, None)
+ configured = getattr(backend, "cli_path", "") if backend is not None else ""
+ return configured or name
+
+
+def _persist_agent_cli_path(name: str, installed_path: str, *, required: bool = False) -> str | None:
+ """Persist one backend path and return its previous configured value."""
+
+ try:
+ from config.v2_config import update_config_fields
+
+ if not paths.get_config_path().exists():
+ raise FileNotFoundError("Avibe config is not initialized")
+ previous: str | None = None
+
+ def persist(config) -> None:
+ nonlocal previous
+ target = getattr(getattr(config, "agents", None), name, None)
+ if target is None:
+ raise ValueError(f"Agent backend config is unavailable: {name}")
+ previous = getattr(target, "cli_path", "") or name
+ target.cli_path = installed_path
+
+ update_config_fields(persist)
+ return previous
+ except FileNotFoundError:
+ if required:
+ raise
+ logger.debug(
+ "install_agent: config is not initialized; skipping cli_path persistence for %s",
+ name,
+ )
+ except Exception:
+ if required:
+ raise
+ logger.warning("install_agent: failed to persist cli_path for %s", name, exc_info=True)
+ return None
+
+
+_DESKTOP_BACKEND_LABELS = {
+ "claude": "Claude Code",
+ "codex": "Codex",
+ "opencode": "OpenCode",
+}
+_DESKTOP_BACKEND_ERROR_I18N_KEYS = {
+ "unknown_backend": "desktopBackendInstall.unknownBackend",
+ "desktop_toolchain_unavailable": "desktopBackendInstall.toolchainUnavailable",
+ "install_locked": "desktopBackendInstall.installLocked",
+ "npm_install_failed": "desktopBackendInstall.installFailed",
+ "desktop_install_failed": "desktopBackendInstall.installFailed",
+ "invalid_backend_root": "desktopBackendInstall.invalidInstall",
+ "invalid_package": "desktopBackendInstall.invalidInstall",
+ "native_executable_missing": "desktopBackendInstall.invalidInstall",
+ "invalid_executable": "desktopBackendInstall.invalidInstall",
+ "unsupported_platform": "desktopBackendInstall.unsupportedPlatform",
+ "install_timeout": "desktopBackendInstall.timedOut",
+ "executable_probe_failed": "desktopBackendInstall.probeFailed",
+}
+
+
+def _configured_backend_language() -> str:
+ try:
+ return str(getattr(load_config(), "language", "en") or "en")
+ except (FileNotFoundError, OSError, ValueError):
+ return "en"
+
+
+def _desktop_backend_install_message(name: str, code: str) -> str:
+ key = _DESKTOP_BACKEND_ERROR_I18N_KEYS.get(code, "desktopBackendInstall.installFailed")
+ return backend_t(
+ key,
+ _configured_backend_language(),
+ backend=_DESKTOP_BACKEND_LABELS.get(name, name),
+ )
+
+
+def _run_desktop_backend_install(name: str, truncate_output) -> dict:
+ def _activate(installed_path: str) -> None:
+ _persist_agent_cli_path(name, installed_path, required=True)
+
+ try:
+ result = install_desktop_backend(name, activate=_activate)
+ except DesktopBackendError as exc:
+ return {
+ "ok": False,
+ "code": exc.code,
+ "message": _desktop_backend_install_message(name, exc.code),
+ "output": truncate_output(exc.output) if exc.output else None,
+ }
+ _invalidate_version_cache(name)
+ return {
+ "ok": True,
+ "message": backend_t(
+ "desktopBackendInstall.success",
+ _configured_backend_language(),
+ backend=_DESKTOP_BACKEND_LABELS.get(name, name),
+ ),
+ "path": result.path,
+ "version": result.version,
+ "managed_by": "desktop",
+ "output": truncate_output(result.output) if result.output else None,
+ }
+
+
def install_agent(name: str) -> dict:
"""Install (or upgrade) an agent CLI tool.
@@ -7320,7 +7222,44 @@ def install_agent(name: str) -> dict:
# Upgrade branch: if the binary is already on disk, keep the install
# source stable. Some CLIs own a reliable self-update command; Codex has
# multiple install sources, so choose npm/brew/self-update by source.
- existing_path = resolve_cli_path(name)
+ configured_path = _configured_agent_cli_path(name)
+ existing_path = resolve_cli_path(configured_path)
+
+ def _owned_path(under_app_root) -> str | None:
+ """The app-private path this Runtime owns, configured or discovered.
+
+ The configured path has to be judged too, and on its own. It names the
+ backend this Runtime installed and it keeps naming it after the
+ executable is deleted -- at which point ``resolve_cli_path`` falls back
+ to finding the bare name on PATH and hands back the user's own
+ ``claude``/``codex``/``opencode``. Judging only that result would run the
+ external upgrade against a binary this Runtime does not own, mutating
+ user or system state, and would never reach the fail-closed guard below,
+ which is only entered when nothing resolved at all.
+ """
+
+ if under_app_root(configured_path):
+ return configured_path
+ if existing_path is not None and under_app_root(existing_path):
+ return existing_path
+ return None
+
+ if _owned_path(is_desktop_backend_path) is not None:
+ return _run_desktop_backend_install(name, _truncate_output)
+ if name == "codex":
+ private_runtime_path = _owned_path(is_private_desktop_runtime_path)
+ if private_runtime_path is not None:
+ if desktop_backend_toolchain() is not None:
+ return _run_desktop_backend_install(name, _truncate_output)
+ return {
+ "ok": False,
+ "code": "desktop_managed_backend",
+ "message": backend_t("desktopRuntime.backendUpgrade", _configured_backend_language()),
+ "output": None,
+ # The path we refused to update, not whatever discovery found in
+ # its place -- the message is about that backend.
+ "path": private_runtime_path,
+ }
if existing_path:
if name == "claude":
cmd = [existing_path, "update"]
@@ -7339,7 +7278,20 @@ def install_agent(name: str) -> dict:
else:
cmd = None
if cmd is not None:
- return _run_install_command(name, cmd, _truncate_output, mode="upgrade", env=command_env)
+ return _run_install_command(
+ name,
+ cmd,
+ _truncate_output,
+ mode="upgrade",
+ env=command_env,
+ resolve_from=configured_path,
+ )
+
+ # A damaged private toolchain must fail closed. Falling through here would
+ # run the legacy global installers and mutate user/system state from a
+ # desktop Runtime that promises app-private backend ownership.
+ if is_desktop_managed_runtime():
+ return _run_desktop_backend_install(name, _truncate_output)
command_env: dict[str, str] | None = None
@@ -7408,6 +7360,7 @@ def _run_install_command(
*,
mode: str = "install",
env: dict[str, str] | None = None,
+ resolve_from: str | None = None,
) -> dict:
"""Shared subprocess + post-success bookkeeping for install / upgrade.
@@ -7447,7 +7400,7 @@ def _run_install_command(
output = result.stdout + ("\n" + result.stderr if result.stderr else "")
output = truncate_output(output.strip())
if result.returncode == 0:
- installed_path = resolve_cli_path(name)
+ installed_path = resolve_cli_path(resolve_from or name)
if installed_path:
logger.info("Agent %s %s succeeded at %s", name, mode, installed_path)
else:
@@ -7467,42 +7420,7 @@ def _run_install_command(
# as askill reuse this runner but do not have ``agents.<name>``
# config entries, so they must not touch V2Config bookkeeping.
if installed_path and is_agent_backend(name):
- try:
- from config.v2_config import update_config_fields
- from config import paths as _paths
-
- if not _paths.get_config_path().exists():
- logger.debug(
- "install_agent: config is not initialized; skipping cli_path persistence for %s",
- name,
- )
- else:
-
- def _persist_cli_path(cfg) -> None:
- # Read-decide-write INSIDE the transaction (#1458
- # stage ③): the comparison runs on the
- # lock-fresh config, so a concurrent save cannot
- # be reverted by a stale snapshot.
- target = getattr(getattr(cfg, "agents", None), name, None)
- if target is None:
- return
- previous = getattr(target, "cli_path", "") or ""
- if previous != installed_path:
- target.cli_path = installed_path
- logger.info(
- "install_agent: updated V2Config cli_path for %s: %s -> %s",
- name,
- previous or "<unset>",
- installed_path,
- )
-
- update_config_fields(_persist_cli_path)
- except Exception as exc: # noqa: BLE001
- logger.warning(
- "install_agent: failed to persist cli_path for %s: %s",
- name,
- exc,
- )
+ _persist_agent_cli_path(name, installed_path)
return {
"ok": True,
@@ -8822,6 +8740,9 @@ _ALLOWED_DEP_INSTALLS = {
"tmux",
}
_STARTUP_DEPENDENCY_RECONCILE_LOCK = threading.Lock()
+_STARTUP_DEPENDENCY_STATE_LOCK = threading.Lock()
+_STARTUP_DEPENDENCY_RECONCILING: set[str] = set()
+_STARTUP_DEPENDENCY_RECONCILE_GENERATION = 0
_DEFAULT_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 3
_MAX_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 10
_MODEL_HUB_CONTROLLER_POLL_INTERVAL_SECONDS = 0.05
@@ -8830,6 +8751,19 @@ _MODEL_HUB_ENGINE_PLATFORM_UNSUPPORTED_REASON = (
)
+def _startup_dependency_state_snapshot() -> tuple[int, set[str]]:
+ with _STARTUP_DEPENDENCY_STATE_LOCK:
+ return _STARTUP_DEPENDENCY_RECONCILE_GENERATION, set(_STARTUP_DEPENDENCY_RECONCILING)
+
+
+def _set_startup_dependency_reconciling(dependency: str, active: bool) -> None:
+ with _STARTUP_DEPENDENCY_STATE_LOCK:
+ if active:
+ _STARTUP_DEPENDENCY_RECONCILING.add(dependency)
+ else:
+ _STARTUP_DEPENDENCY_RECONCILING.discard(dependency)
+
+
def _published_running_version() -> str | None:
from packaging.version import InvalidVersion, Version
from vibe import __version__
@@ -8907,7 +8841,7 @@ def _model_hub_engine_dependency_status() -> dict:
}
-def _model_hub_controller_owns_engine(socket_path: Path) -> bool:
+def _model_hub_controller_owns_engine(socket_path: Path | None) -> bool:
"""Wait out controller startup before deciding direct-install ownership.
A missing dispatch socket means only that the endpoint is not ready. The
@@ -8973,7 +8907,7 @@ def ensure_model_hub_engine_installed(
EngineRuntimeManager(offline=offline).ensure(force=force)
)
- socket_path = default_socket_path().expanduser().resolve()
+ socket_path = None if os.name == "nt" else default_socket_path().expanduser().resolve()
if not _model_hub_controller_owns_engine(socket_path):
return ensure_directly()
@@ -9087,6 +9021,8 @@ def dependencies_status(*, offline: bool = False, dependency_ids: list[str] | No
CLI probes. Coupled rows share their existing inspection; no health result
is cached or inferred from a different dependency.
"""
+ generation_before, active_before = _startup_dependency_state_snapshot()
+ reconciling_before = _STARTUP_DEPENDENCY_RECONCILE_LOCK.locked()
requested = set(DEPENDENCY_IDS if dependency_ids is None else dependency_ids)
unknown = requested.difference(DEPENDENCY_IDS)
if unknown:
@@ -9138,7 +9074,17 @@ def dependencies_status(*, offline: bool = False, dependency_ids: list[str] | No
"download_error": tmux.get("download_error"),
}
- return {"ok": True, "deps": [deps[dep] for dep in DEPENDENCY_IDS if dep in requested]}
+ generation_after, active_after = _startup_dependency_state_snapshot()
+ return {
+ "ok": True,
+ "deps": [deps[dep] for dep in DEPENDENCY_IDS if dep in requested],
+ "reconciling": (
+ reconciling_before
+ or _STARTUP_DEPENDENCY_RECONCILE_LOCK.locked()
+ or generation_before != generation_after
+ ),
+ "reconciling_dependencies": sorted(active_before | active_after),
+ }
def _prepare_show_runtime_job() -> dict:
@@ -9273,6 +9219,12 @@ def reconcile_startup_dependencies() -> dict:
if not _STARTUP_DEPENDENCY_RECONCILE_LOCK.acquire(blocking=False):
return {"ok": True, "skipped": True, "reason": "already_running"}
+ global _STARTUP_DEPENDENCY_RECONCILE_GENERATION
+
+ with _STARTUP_DEPENDENCY_STATE_LOCK:
+ _STARTUP_DEPENDENCY_RECONCILE_GENERATION += 1
+ _STARTUP_DEPENDENCY_RECONCILING.clear()
+
started_at = time.monotonic()
result: dict[str, Any] = {
"ok": True,
@@ -9284,20 +9236,27 @@ def reconcile_startup_dependencies() -> dict:
"tmux": {"ok": False, "status": "unknown"},
}
try:
+ _set_startup_dependency_reconciling("askill", True)
try:
askill = ensure_askill_installed(force=False)
except Exception as exc: # noqa: BLE001
logger.warning("Startup dependency reconcile failed to ensure askill: %s", exc, exc_info=True)
askill = {"ok": False, "message": str(exc)}
+ finally:
+ _set_startup_dependency_reconciling("askill", False)
result["askill"] = askill
+ _set_startup_dependency_reconciling("avault", True)
try:
avault = ensure_avault_installed(force=False)
except Exception as exc: # noqa: BLE001
logger.warning("Startup dependency reconcile failed to ensure avault: %s", exc, exc_info=True)
avault = {"ok": False, "message": str(exc)}
+ finally:
+ _set_startup_dependency_reconciling("avault", False)
result["avault"] = avault
+ _set_startup_dependency_reconciling("model-hub-engine", True)
try:
model_hub_engine = ensure_model_hub_engine_installed(force=False)
except Exception as exc: # noqa: BLE001
@@ -9307,6 +9266,8 @@ def reconcile_startup_dependencies() -> dict:
exc_info=True,
)
model_hub_engine = {"ok": False, "message": str(exc)}
+ finally:
+ _set_startup_dependency_reconciling("model-hub-engine", False)
result["model_hub_engine"] = model_hub_engine
try:
@@ -9326,7 +9287,11 @@ def reconcile_startup_dependencies() -> dict:
"version": status.get("node_version"),
}
if node_ok:
- prepared = manager.prepare(force=False, automatic=True)
+ _set_startup_dependency_reconciling("show-runtime", True)
+ try:
+ prepared = manager.prepare(force=False, automatic=True)
+ finally:
+ _set_startup_dependency_reconciling("show-runtime", False)
status = prepared.get("status") if isinstance(prepared.get("status"), dict) else status
else:
reason = "runtime_node_unsupported" if node_available else "runtime_node_missing"
@@ -9355,6 +9320,7 @@ def reconcile_startup_dependencies() -> dict:
elif os.environ.get("VIBE_INSTALL_SKIP_TMUX", "").strip().lower() in _TRUTHY_ENV_VALUES:
result["tmux"] = {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_TMUX"}
else:
+ _set_startup_dependency_reconciling("tmux", True)
try:
from core.tmux_runtime import ensure_tmux_installed
@@ -9362,6 +9328,8 @@ def reconcile_startup_dependencies() -> dict:
except Exception as exc: # noqa: BLE001
logger.warning("Startup dependency reconcile failed to ensure tmux runtime: %s", exc, exc_info=True)
result["tmux"] = {"ok": False, "status": "failed", "reason": str(exc)}
+ finally:
+ _set_startup_dependency_reconciling("tmux", False)
result["duration_ms"] = int((time.monotonic() - started_at) * 1000)
result["ok"] = (
@@ -9372,6 +9340,9 @@ def reconcile_startup_dependencies() -> dict:
)
return result
finally:
+ with _STARTUP_DEPENDENCY_STATE_LOCK:
+ _STARTUP_DEPENDENCY_RECONCILING.clear()
+ _STARTUP_DEPENDENCY_RECONCILE_GENERATION += 1
_STARTUP_DEPENDENCY_RECONCILE_LOCK.release()
@@ -9970,9 +9941,20 @@ def get_backend_runtime(name: str) -> dict:
resolved_path = resolve_cli_path(configured_path)
installed = resolved_path is not None
+ private_backend = resolved_path is not None and is_desktop_backend_path(resolved_path)
+ legacy_bundled_codex = (
+ name == "codex"
+ and resolved_path is not None
+ and is_private_desktop_runtime_path(resolved_path)
+ )
+ managed_by = (
+ "desktop"
+ if private_backend or legacy_bundled_codex
+ else None
+ )
current_version = _cached_version(name, resolved_path) if installed else None
- latest_version = _cached_latest(name)
+ latest_version = None if legacy_bundled_codex else _cached_latest(name)
has_update = _compare_versions(current_version, latest_version)
if name == "opencode":
@@ -9994,6 +9976,7 @@ def get_backend_runtime(name: str) -> dict:
"current_version": current_version,
"latest_version": latest_version,
"has_update": has_update,
+ "managed_by": managed_by,
"supports_restart": supports_runtime_refresh(name),
"process_status": process_status,
}
diff --git a/vibe/cli.py b/vibe/cli.py
index b2c11ffb0..8a6eb5f58 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -86,6 +86,7 @@ from vibe.upgrade import (
defer_upgrade_activation,
get_latest_version_info,
get_safe_cwd,
+ is_desktop_managed_runtime,
_launcher_generation,
_candidate_python,
launcher_is_current_process,
@@ -138,6 +139,17 @@ DOCTOR_REPAIR_TARGETS = (
)
DOCTOR_DEFAULT_REPAIR_TARGETS = DOCTOR_REPAIR_TARGETS[:4]
DOCTOR_DEPENDENCY_REPAIR_TARGETS = frozenset(DOCTOR_REPAIR_TARGETS[4:])
+
+
+def _doctor_repair_target(value: str) -> str:
+ """Validate one repair target without argparse's empty-list choices bug."""
+
+ if value not in DOCTOR_REPAIR_TARGETS:
+ choices = ", ".join(repr(target) for target in DOCTOR_REPAIR_TARGETS)
+ raise argparse.ArgumentTypeError(f"invalid choice: {value!r} (choose from {choices})")
+ return value
+
+
DOCTOR_REPAIR_DRY_RUN_I18N_KEYS = {
"home-migration": "doctor.repair.dryHomeMigration",
"stale-install-runtime": "doctor.repair.dryStaleInstall",
@@ -13316,10 +13328,35 @@ def _confirm_doctor_repair(targets: list[str]) -> bool:
return answer.strip().lower() == "yes"
-def cmd_start():
+def _handover_superseded_desktop_runtime() -> None:
+ """Replace a different desktop-managed Controller before service reuse."""
+
+ from vibe import internal_client
+ from vibe.desktop_runtime import desktop_runtime_id
+
+ expected_runtime_id = desktop_runtime_id()
+ if expected_runtime_id is None:
+ return
+ controller_identity = internal_client.health_identity_sync()
+ if controller_identity is None:
+ return
+ actual_runtime_id = controller_identity.get("desktop_runtime_id")
+ if actual_runtime_id is None or actual_runtime_id == expected_runtime_id:
+ return
+
+ service_was_running = runtime.resolve_service_owner_pid(include_starting=True) is not None
+ ui_was_running = runtime.ui_pid_file_points_to_running_ui()
+ if service_was_running and runtime.stop_service() is not True:
+ raise RuntimeError("Failed to stop the superseded desktop-managed Avibe service")
+ if ui_was_running and runtime.stop_ui(stop_remote_access=False) is not True:
+ raise RuntimeError("Failed to stop the superseded desktop-managed Avibe UI")
+
+
+def cmd_start(*, open_browser: bool | None = None):
_guard_cli_default_state_migration()
paths.ensure_data_dirs()
config = _ensure_config()
+ _handover_superseded_desktop_runtime()
has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)
if callable(has_configured_platform_credentials):
@@ -13332,67 +13369,169 @@ def cmd_start():
else:
_write_status("starting")
- live_service_pid = runtime.resolve_service_owner_pid(include_starting=True)
- service_pid = runtime.start_service(
- wait_for_ready=False,
- )
- service_reused = live_service_pid is not None and service_pid == live_service_pid
- bind_host = runtime.effective_ui_bind_host(config)
- ui_pid = runtime.start_ui(
- bind_host,
- config.ui.setup_port,
- )
- # The WAIT below is asked unconditionally. The predicate that used to guard
- # it is the lock, which is taken before the database is migrated -- so it is
- # already true of a process that has not finished starting and may never, and
- # guarding with it skipped the wait in exactly the case the wait exists for.
- # Nothing is paid for asking: a service that is up answers on the first probe.
+ service_start = runtime.ProcessStartInfo()
+ ui_start = runtime.ProcessStartInfo()
+ # Everything from here to the receipt line is one region under one invariant:
+ # nothing THIS invocation created may survive a start that never printed a
+ # receipt. Both processes count. An unreceipted service is adopted as
+ # `reused` on the next attempt, so the desktop shell never owns its stop
+ # again; an unreceipted UI keeps its pid file and its listener, which the
+ # next attempt then has to fight. Every failure in the region produces those
+ # orphans, whichever line raised.
#
- # The provisional "starting" WRITE is guarded, and the difference is the
- # point: `write_status` carries `started_at` forward only across consecutive
- # `running` writes, so announcing a transition for a service this command did
- # not start resets its recorded uptime to now and briefly shows a starting
- # service to every status consumer. `vibe start` against a live instance is
- # idempotent and must stay observably so.
- if not service_reused:
- runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)
- # The wait resolves the authoritative service.lock holder rather than waiting
- # on the raw pid start_service handed back: under a delegated user scope that
- # pid can be a launcher that never takes the lock, so wait_for_service_ready
- # adopts and returns the real owner instead of stalling the full timeout.
- resolved_pid = runtime.wait_for_service_ready(
- service_pid,
- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
- )
- service_ready = resolved_pid is not None
- if resolved_pid is not None:
- service_pid = resolved_pid
- if service_ready:
- runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
- elif runtime.pid_alive(service_pid):
- runtime.write_status("starting", "service process is still starting", service_pid, ui_pid)
- else:
- runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)
- raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")
+ # The guard is regional on purpose. Undoing one named failure inside its own
+ # branch -- which is what the `ui_pid is None` refusal below used to do --
+ # leaves every other failure in the same region to be discovered one at a
+ # time, because the invariant belongs to the region, not to the branch a
+ # reviewer happened to name first.
+ #
+ # `BaseException`, not `Exception`: a Ctrl-C during the readiness wait, the
+ # longest thing in here, orphans the service exactly like a crash does.
+ # `SystemExit` is included deliberately -- nothing in the region exits on
+ # purpose, and an exit before the receipt is indistinguishable, to the next
+ # launch, from any other start that never finished. The bare `raise` keeps
+ # the original failure and its traceback unchanged.
+ #
+ # The region opens before `start_service`, not after it: that call spawns
+ # the service and then waits for it to take the lock, and a Ctrl-C in that
+ # wait left a live, reserved service that no rollback had been asked about.
+ try:
+ service_pid = runtime.start_service(
+ wait_for_ready=False,
+ start_info=service_start,
+ )
+ service_reused = service_start.reused
+ bind_host = runtime.effective_ui_bind_host(config)
+ ui_pid = runtime.start_ui(
+ bind_host,
+ config.ui.setup_port,
+ start_info=ui_start,
+ )
+ if ui_pid is None:
+ # No pid means start_ui found a stale UI it could not stop and refused
+ # to start a replacement that would only die on bind. Nothing below can
+ # complete without that pid: the status writes carry it and
+ # validate_start_receipt rejects a receipt missing it. Fail here rather
+ # than further down in the receipt builder, and let the region's guard
+ # undo the start.
+ raise RuntimeError("Vibe UI could not be started because a stale UI process could not be stopped")
+ # The WAIT below is asked unconditionally. The predicate that used to guard
+ # it is the lock, which is taken before the database is migrated -- so it is
+ # already true of a process that has not finished starting and may never, and
+ # guarding with it skipped the wait in exactly the case the wait exists for.
+ # Nothing is paid for asking: a service that is up answers on the first probe.
+ #
+ # The provisional "starting" WRITE is guarded, and the difference is the
+ # point: `write_status` carries `started_at` forward only across consecutive
+ # `running` writes, so announcing a transition for a service this command did
+ # not start resets its recorded uptime to now and briefly shows a starting
+ # service to every status consumer. `vibe start` against a live instance is
+ # idempotent and must stay observably so.
+ if not service_reused:
+ runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)
+ # The wait resolves the authoritative service.lock holder rather than waiting
+ # on the raw pid start_service handed back: under a delegated user scope that
+ # pid can be a launcher that never takes the lock, so wait_for_service_ready
+ # adopts and returns the real owner instead of stalling the full timeout.
+ resolved_pid = runtime.wait_for_service_ready(
+ service_pid,
+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
+ )
+ service_ready = resolved_pid is not None
+ if resolved_pid is not None:
+ service_pid = resolved_pid
+ service_start.capture(service_pid, reused=service_reused)
+ if service_ready:
+ runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
+ elif runtime.pid_alive(service_pid):
+ runtime.write_status("starting", "service process is still starting", service_pid, ui_pid)
+ else:
+ runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)
+ raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")
+
+ from vibe.desktop_runtime import start_receipt_line
+
+ receipt_line = start_receipt_line(
+ {
+ "schema_version": 1,
+ "outcome": "reused" if service_reused else "started",
+ "service_pid": service_pid,
+ "ui_pid": ui_pid,
+ "service_create_unix_ms": service_start.create_unix_ms,
+ "ui_create_unix_ms": ui_start.create_unix_ms,
+ }
+ )
+ ui_url = "http://{}:{}".format(config.ui.setup_host, config.ui.setup_port)
- ui_url = "http://{}:{}".format(config.ui.setup_host, config.ui.setup_port)
+ # Always print Web UI access instructions.
+ print("Web UI:")
+ print(f" {ui_url}")
+ print("")
+ print("Want to open this Web UI from another device or a remote server?")
+ print(" Run: vibe remote")
+ print(" Avibe will guide you through creating a private avibe.bot URL.")
+ print("")
- # Always print Web UI access instructions.
- print("Web UI:")
- print(f" {ui_url}")
- print("")
- print("Want to open this Web UI from another device or a remote server?")
- print(" Run: vibe remote")
- print(" Avibe will guide you through creating a private avibe.bot URL.")
- print("")
+ # If running over SSH, avoid trying to open a browser on the server.
+ should_open_browser = config.ui.open_browser if open_browser is None else open_browser
+ if should_open_browser and not _in_ssh_session():
+ opened = _open_browser(ui_url)
+ if not opened:
+ print(f"(Tip) Could not auto-open a browser. Open this URL manually: {ui_url}")
+ print("")
- # If running over SSH, avoid trying to open a browser on the server.
- if config.ui.open_browser and not _in_ssh_session():
- opened = _open_browser(ui_url)
- if not opened:
- print(f"(Tip) Could not auto-open a browser. Open this URL manually: {ui_url}")
- print("")
+ print(receipt_line, flush=True)
+ except BaseException:
+ # The invariant is that this invocation leaves running nothing it
+ # created -- not just the service. The region starts two processes, and
+ # a guard that undid one left the other exactly as orphaned: a UI this
+ # command spawned kept its pid file and its listener after the service
+ # beneath it was stopped.
+ #
+ # The set does not need a new mechanism to be known. `start_service` and
+ # `start_ui` already record what they did in their `ProcessStartInfo`:
+ # a process adopted from a previous launch comes back as `reused`, and a
+ # refusal that returned no pid captured nothing. So "what did this
+ # invocation create" is exactly `pid is not None and not reused`, and
+ # the undo runs in reverse order of creation -- the UI, then the service
+ # it was pointed at.
+ #
+ # Both undos find their process through its pid record rather than the
+ # captured pid, and that is sound by construction, not by luck: the
+ # spawn primitives write the record and then capture the child, both
+ # inside the region that kills the child if either step fails. So every
+ # live process this sees as created has a record naming it, and no
+ # child that missed the capture is still alive.
+ if ui_start.pid is not None and not ui_start.reused:
+ # `stop_remote_access=False`, the same distinction the stale-UI
+ # restart above makes, and for the same reason: `vibe start` never
+ # brings a tunnel up. `remote_access.start()` is reached only from
+ # the UI's explicit endpoint and from `vibe remote`; UI startup only
+ # starts monitors. Any tunnel alive here therefore predates this
+ # command, and tearing it down would destroy a remote URL this
+ # invocation did not create -- the one irreversible mistake
+ # available to a rollback.
+ runtime.stop_ui(stop_remote_access=False)
+ if service_start.pid is not None and not service_start.reused:
+ # A service that was already running is not ours to stop, and against
+ # one this command has then changed nothing to undo. stop_service()
+ # logs any pid it could not stop, so a rollback that itself fails
+ # still leaves evidence; either way the start has failed.
+ runtime.stop_service()
+ raise
+ return 0
+
+def cmd_desktop_endpoint() -> int:
+ """Print the desktop shell's loopback endpoint descriptor."""
+
+ from vibe.desktop_runtime import desktop_endpoint_payload
+
+ _guard_cli_default_state_migration()
+ config = _ensure_config()
+ bind_host = runtime.effective_ui_bind_host(config)
+ payload = desktop_endpoint_payload(bind_host, config.ui.setup_port)
+ print(json.dumps(payload, separators=(",", ":")))
return 0
@@ -13450,7 +13589,35 @@ def _runtime_process_was_running() -> bool:
return runtime.service_process_running() or runtime.ui_pid_file_points_to_running_ui()
-def cmd_stop():
+def _stop_receipt_refusal(receipt_json: str) -> str | None:
+ from vibe.desktop_runtime import START_RECEIPT_TIME_TOLERANCE_MS, validate_start_receipt
+
+ try:
+ receipt = validate_start_receipt(json.loads(receipt_json))
+ except (ValueError, RecursionError):
+ return "invalid_receipt"
+ try:
+ recorded_pid = int(paths.get_runtime_pid_path().read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ return "service_pid_mismatch"
+ if recorded_pid != receipt["service_pid"]:
+ return "service_pid_mismatch"
+ if not runtime.pid_alive(recorded_pid):
+ return "service_identity_unavailable"
+ created = runtime.process_create_time(recorded_pid)
+ if created is None:
+ return "service_identity_unavailable"
+ if not abs(created * 1000 - receipt["service_create_unix_ms"]) <= START_RECEIPT_TIME_TOLERANCE_MS:
+ return "service_create_time_mismatch"
+ return None
+
+
+def cmd_stop(*, receipt: str | None = None):
+ if receipt is not None:
+ reason = _stop_receipt_refusal(receipt)
+ if reason is not None:
+ print(json.dumps({"reason": reason}, separators=(",", ":")), file=sys.stderr)
+ return 3
service_was_running = _pid_file_points_to_live_process(paths.get_runtime_pid_path())
ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())
@@ -15156,6 +15323,9 @@ def get_latest_version() -> dict:
def cmd_check_update():
"""Check for available updates."""
print(f"Current version: {__version__}")
+ if is_desktop_managed_runtime():
+ print(i18n_t("desktopRuntime.checkUpdate", V2Config.load().language))
+ return 0
print("Checking for updates...")
info = get_latest_version()
@@ -15176,6 +15346,9 @@ def cmd_check_update():
def cmd_upgrade():
"""Upgrade avibe-os to the latest version."""
print(f"Current version: {__version__}")
+ if is_desktop_managed_runtime():
+ print(i18n_t("desktopRuntime.upgrade", V2Config.load().language))
+ return 0
print("Checking for updates...")
info = get_latest_version()
@@ -16001,8 +16174,23 @@ def build_parser():
parser = VibeArgumentParser(prog="vibe")
subparsers = parser.add_subparsers(dest="command")
- subparsers.add_parser("stop", help="Stop all services")
- subparsers.add_parser("start", help="Start services if needed without stopping running processes")
+ stop_parser = subparsers.add_parser("stop", help="Stop all services")
+ stop_parser.add_argument(
+ "--receipt",
+ help="Stop only if the service identity matches this startup receipt JSON.",
+ )
+ start_parser = subparsers.add_parser("start", help="Start services if needed without stopping running processes")
+ start_parser.add_argument(
+ "--no-open-browser",
+ dest="open_browser",
+ action="store_false",
+ default=None,
+ help="Start services without opening the Web UI in the system browser.",
+ )
+ desktop_parser = subparsers.add_parser("desktop", help=argparse.SUPPRESS)
+ desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)
+ desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint", help=argparse.SUPPRESS)
+ desktop_endpoint_parser.add_argument("--json", action="store_true", required=True, help=argparse.SUPPRESS)
restart_parser = subparsers.add_parser("restart", help="Restart all services")
restart_parser.add_argument(
"--delay-seconds",
@@ -16030,7 +16218,7 @@ def build_parser():
doctor_parser.add_argument(
"doctor_repair_targets",
nargs="*",
- choices=DOCTOR_REPAIR_TARGETS,
+ type=_doctor_repair_target,
help="Repair target(s). Defaults to all safe first-phase repair targets.",
)
doctor_depth_group = doctor_parser.add_mutually_exclusive_group()
@@ -17856,6 +18044,7 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {
("version",): None,
("check-update",): None,
("status",): None,
+ ("desktop", "endpoint"): "member",
# Host scope, not instance scope: these act on this machine's screen and on
# authored files, and have no role contract to repair here.
("screenshot",): None,
@@ -18092,9 +18281,11 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
"""Run the admitted command. Every branch exits; nothing returns to ``main``."""
if args.command == "stop":
- sys.exit(cmd_stop())
+ sys.exit(cmd_stop(receipt=args.receipt) if args.receipt is not None else cmd_stop())
if args.command == "start":
- sys.exit(cmd_start())
+ sys.exit(cmd_start(open_browser=args.open_browser))
+ if args.command == "desktop" and args.desktop_command == "endpoint":
+ sys.exit(cmd_desktop_endpoint())
if args.command == "restart":
sys.exit(_cmd_restart_with_delay(args.delay_seconds))
if args.command == "status":
diff --git a/vibe/cli_paths.py b/vibe/cli_paths.py
new file mode 100644
index 000000000..2e6860418
--- /dev/null
+++ b/vibe/cli_paths.py
@@ -0,0 +1,305 @@
+"""Shared executable discovery for configured local CLI tools."""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+from vibe.desktop_backends import is_desktop_backend_path, resolve_published_desktop_backend
+
+logger = logging.getLogger(__name__)
+
+def _is_executable_file(path: Path) -> bool:
+ return path.exists() and path.is_file() and os.access(path, os.X_OK)
+
+
+_NVM_VERSION_RE = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(.*)$")
+_NVM_SUFFIX_TOKEN_RE = re.compile(r"\d+|\D+")
+
+
+def _nvm_suffix_tokens(suffix: str) -> tuple[tuple[int, int, str], ...]:
+ # Tokenize the prerelease suffix into (kind, num, text) triples so all
+ # tokens are structurally identical and comparable. kind=0 marks numeric
+ # tokens (compared by num) and kind=1 marks alphanumeric tokens (compared
+ # by text). Numeric tokens compare numerically, so "-rc.10" beats
+ # "-rc.2"; cross-kind tokens never compare int-vs-str, ruling out
+ # TypeError for arbitrary suffix shapes.
+ triples: list[tuple[int, int, str]] = []
+ for tok in _NVM_SUFFIX_TOKEN_RE.findall(suffix):
+ if tok.isdigit():
+ triples.append((0, int(tok), ""))
+ else:
+ triples.append((1, 0, tok))
+ return tuple(triples)
+
+
+def _nvm_version_sort_key(entry: Path) -> tuple:
+ # Returns (major, minor, patch, is_released, suffix_tokens). is_released
+ # is True for plain "vX.Y.Z" and False for any "-suffix"; with reverse=True
+ # released versions outrank pre-releases of the same triple. Within
+ # pre-releases, suffix_tokens compares numerically where digits appear.
+ m = _NVM_VERSION_RE.match(entry.name)
+ if not m:
+ return (-1, -1, -1, False, ())
+ major = int(m.group(1))
+ minor = int(m.group(2)) if m.group(2) else 0
+ patch = int(m.group(3)) if m.group(3) else 0
+ suffix = m.group(4) or ""
+ return (major, minor, patch, not suffix, _nvm_suffix_tokens(suffix))
+
+
+def _nvm_binary_candidates(binary: str) -> list[Path]:
+ versions_dir = Path.home() / ".nvm" / "versions" / "node"
+ if not versions_dir.exists():
+ return []
+
+ valid: list[Path] = []
+ for entry in versions_dir.iterdir():
+ # Skip non-directory entries (e.g. macOS .DS_Store) and non-version
+ # dirs (e.g. nvm's "system" alias) before sorting.
+ if not entry.is_dir():
+ continue
+ if not _NVM_VERSION_RE.match(entry.name):
+ continue
+ valid.append(entry)
+
+ candidates: list[Path] = []
+ for version_dir in sorted(valid, key=_nvm_version_sort_key, reverse=True):
+ candidate = version_dir / "bin" / binary
+ if candidate not in candidates:
+ candidates.append(candidate)
+ return candidates
+
+
+def _npm_global_binary_candidates(binary: str) -> list[Path]:
+ if not binary or binary == "npm":
+ return []
+
+ candidates: list[Path] = []
+ for prefix_path in _npm_global_prefixes():
+ for candidate in _npm_binary_candidates_for_prefix(prefix_path, binary):
+ if candidate not in candidates:
+ candidates.append(candidate)
+
+ return candidates
+
+
+def _npm_global_prefixes() -> list[Path]:
+ # Global packages belong to the npm selected by the current environment.
+ # Querying every historical NVM installation makes one missing CLI cost up
+ # to five seconds per Node version without improving that answer.
+ which_npm = shutil.which("npm")
+ npm_path = Path(which_npm) if which_npm else next(
+ (
+ candidate
+ for candidate in _candidate_cli_paths(
+ "npm",
+ include_npm_global=False,
+ )
+ if _is_executable_file(candidate)
+ ),
+ None,
+ )
+ if npm_path is None:
+ return []
+ prefix_path = _npm_prefix_for(npm_path)
+ return [prefix_path] if prefix_path is not None else []
+
+
+def _npm_prefix_for(npm_path: str | Path) -> Path | None:
+ try:
+ result = subprocess.run(
+ [str(npm_path), "config", "get", "prefix"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ env=_command_env_for(str(npm_path)),
+ )
+ except Exception:
+ return None
+
+ if result.returncode != 0:
+ return None
+
+ prefix = (result.stdout or "").strip().splitlines()
+ if not prefix:
+ return None
+
+ return Path(os.path.expanduser(prefix[-1]))
+
+
+def _npm_binary_candidates_for_prefix(prefix_path: Path, binary: str) -> list[Path]:
+ derived_candidates = [
+ prefix_path / "bin" / binary,
+ prefix_path / binary,
+ prefix_path / "node_modules" / ".bin" / binary,
+ ]
+ if os.name == "nt":
+ derived_candidates.extend(
+ [
+ prefix_path / f"{binary}.cmd",
+ prefix_path / f"{binary}.exe",
+ prefix_path / "node_modules" / ".bin" / f"{binary}.cmd",
+ ]
+ )
+ return derived_candidates
+
+
+def _windows_executable_candidates(candidates: list[Path]) -> list[Path]:
+ result: list[Path] = []
+ for candidate in candidates:
+ result.append(candidate)
+ if candidate.suffix.lower() not in {".cmd", ".exe"}:
+ result.extend(
+ [
+ candidate.with_name(f"{candidate.name}.exe"),
+ candidate.with_name(f"{candidate.name}.cmd"),
+ ]
+ )
+ return result
+
+
+def _candidate_cli_paths(
+ binary: str,
+ *,
+ include_npm_global: bool = True,
+) -> list[Path]:
+ if not binary:
+ return []
+
+ expanded = Path(os.path.expanduser(binary))
+ has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)
+ if expanded.is_absolute() or has_path_separator:
+ return [expanded]
+
+ home = Path.home()
+ candidates: list[Path] = []
+ if binary == "claude":
+ candidates.append(home / ".claude" / "local" / "claude")
+ elif binary == "opencode":
+ candidates.extend(
+ [
+ home / ".opencode" / "bin" / "opencode",
+ home / ".local" / "bin" / "opencode",
+ ]
+ )
+
+ common_candidates = [
+ home / ".local" / "bin" / binary,
+ home / ".bun" / "bin" / binary,
+ Path("/opt/homebrew/bin") / binary,
+ Path("/usr/local/bin") / binary,
+ ]
+ if os.name == "nt":
+ common_candidates = _windows_executable_candidates(common_candidates)
+ for candidate in common_candidates + _nvm_binary_candidates(binary):
+ if candidate not in candidates:
+ candidates.append(candidate)
+ if include_npm_global:
+ for candidate in _npm_global_binary_candidates(binary):
+ if candidate not in candidates:
+ candidates.append(candidate)
+
+ return candidates
+
+
+def _resolve_cli_path_once(
+ binary: str,
+ *,
+ include_npm_global: bool,
+ candidate_paths=None,
+ is_executable_file=None,
+) -> str | None:
+ candidate_paths = candidate_paths or _candidate_cli_paths
+ is_executable_file = is_executable_file or _is_executable_file
+ for candidate in candidate_paths(binary, include_npm_global=False):
+ if is_executable_file(candidate):
+ return str(candidate)
+
+ path = shutil.which(os.path.expanduser(binary)) if binary else None
+ if path:
+ return path
+
+ if include_npm_global:
+ for candidate in _npm_global_binary_candidates(binary):
+ if _is_executable_file(candidate):
+ return str(candidate)
+ return None
+
+
+def resolve_cli_path(
+ binary: str,
+ *,
+ include_npm_global: bool = True,
+ candidate_paths=None,
+ is_executable_file=None,
+ include_desktop: bool = True,
+) -> str | None:
+ path = _resolve_cli_path_once(
+ binary,
+ include_npm_global=include_npm_global,
+ candidate_paths=candidate_paths,
+ is_executable_file=is_executable_file,
+ )
+ if path:
+ return path
+
+ # The stored cli_path was an absolute path that no longer exists. Most
+ # common cause: an upstream installer moved the binary out from under us.
+ # Real-world example: Claude Code's official ``install.sh`` puts the
+ # native binary at ``~/.local/bin/claude`` (via ``~/.local/share/claude/
+ # versions/<ver>``), while the legacy ``npm install -g
+ # @anthropic-ai/claude-code`` install used ``/usr/local/bin/claude``.
+ # After clicking "Upgrade" in the UI, V2Config still points at the
+ # /usr/local/bin path, so the runtime probe reports ``installed=false``
+ # and the chip flips to "not installed". Fall back to discovery using
+ # only the basename — if a binary with that name is on any of the
+ # standard candidate paths (~/.local/bin, /opt/homebrew/bin, npm/nvm/bun
+ # globals, etc.) we treat that as the live install. The basename
+ # restriction means custom callers passing ``"/path/to/my-claude"``
+ # don't get silently redirected to the system claude.
+ if not binary:
+ return None
+ expanded = Path(os.path.expanduser(binary))
+ has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)
+ if expanded.is_absolute() and is_desktop_backend_path(expanded):
+ lookup_name = expanded.stem if expanded.suffix.lower() == ".exe" else expanded.name
+ if include_desktop and lookup_name in {"claude", "codex", "opencode"}:
+ return resolve_published_desktop_backend(lookup_name)
+ return None
+ if expanded.is_absolute() or has_path_separator:
+ basename = expanded.name
+ if basename and basename != binary:
+ fallback = _resolve_cli_path_once(
+ basename,
+ include_npm_global=include_npm_global,
+ candidate_paths=candidate_paths,
+ is_executable_file=is_executable_file,
+ )
+ if fallback:
+ logger.info(
+ "resolve_cli_path: stored path %s missing; falling back to %s",
+ binary,
+ fallback,
+ )
+ return fallback
+ if include_desktop:
+ lookup_name = expanded.name if expanded.is_absolute() or has_path_separator else binary
+ if lookup_name in {"claude", "codex", "opencode"}:
+ return resolve_published_desktop_backend(lookup_name)
+ return None
+
+
+def _command_env_for(binary_path: str | None) -> dict[str, str]:
+ env = {**os.environ, "PATH": os.environ.get("PATH", "")}
+ if not binary_path:
+ return env
+
+ binary_dir = str(Path(binary_path).expanduser().resolve().parent)
+ path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry and entry != binary_dir]
+ env["PATH"] = os.pathsep.join([binary_dir, *path_entries])
+ return env
diff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.py
new file mode 100644
index 000000000..649c66dc2
--- /dev/null
+++ b/vibe/desktop_backends.py
@@ -0,0 +1,797 @@
+"""App-private agent backend installation for the self-contained desktop app."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import platform
+import shutil
+import subprocess
+import tempfile
+import uuid
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+from storage.lock import MigrationFileLock, MigrationLockTimeout
+from vibe.desktop_runtime import (
+ private_desktop_backends_root,
+ private_desktop_node_bin,
+ private_desktop_npm_cli,
+)
+
+
+logger = logging.getLogger(__name__)
+
+CURRENT_DESCRIPTOR_SCHEMA_VERSION = 1
+MAX_DESCRIPTOR_BYTES = 16 * 1024
+MAX_INSTALL_OUTPUT_CHARS = 8192
+NPM_REGISTRY = "https://registry.npmjs.org/"
+DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS = 30.0
+DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS = 300.0
+DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS = 15.0
+DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS = 10.0
+
+
+@dataclass(frozen=True)
+class DesktopBackendSpec:
+ package: str
+ package_path: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class DesktopBackendToolchain:
+ runtime_root: Path
+ backends_root: Path
+ node: Path
+ npm_cli: Path
+
+
+@dataclass(frozen=True)
+class DesktopBackendInstallResult:
+ backend: str
+ package: str
+ version: str
+ path: str
+ output: str | None
+
+
+class DesktopBackendError(RuntimeError):
+ def __init__(self, message: str, *, code: str, output: str | None = None):
+ super().__init__(message)
+ self.code = code
+ self.output = output
+
+
+BACKEND_SPECS: dict[str, DesktopBackendSpec] = {
+ "codex": DesktopBackendSpec(
+ package="@openai/codex",
+ package_path=("@openai", "codex"),
+ ),
+ "claude": DesktopBackendSpec(
+ package="@anthropic-ai/claude-code",
+ package_path=("@anthropic-ai", "claude-code"),
+ ),
+ "opencode": DesktopBackendSpec(
+ package="opencode-ai",
+ package_path=("opencode-ai",),
+ ),
+}
+
+
+ActivationCallback = Callable[[str], None]
+
+
+def desktop_backend_toolchain(
+ base_env: Mapping[str, str] | None = None,
+) -> DesktopBackendToolchain | None:
+ """Return the complete launcher-supplied private install contract."""
+
+ from vibe.desktop_runtime import private_desktop_runtime_root
+
+ runtime_root = private_desktop_runtime_root(base_env)
+ backends_root = private_desktop_backends_root(base_env)
+ node = private_desktop_node_bin(base_env)
+ npm_cli = private_desktop_npm_cli(base_env)
+ if runtime_root is None or backends_root is None or node is None or npm_cli is None:
+ return None
+ return DesktopBackendToolchain(
+ runtime_root=runtime_root,
+ backends_root=backends_root,
+ node=node,
+ npm_cli=npm_cli,
+ )
+
+
+def resolve_published_desktop_backend(
+ backend: str,
+ base_env: Mapping[str, str] | None = None,
+) -> str | None:
+ """Resolve one verified executable from its bounded ``current.json``."""
+
+ if backend not in BACKEND_SPECS:
+ return None
+ root = private_desktop_backends_root(base_env)
+ if root is None:
+ return None
+ backend_root = root / backend
+ descriptor_path = backend_root / "current.json"
+ try:
+ if descriptor_path.is_symlink() or not descriptor_path.is_file():
+ return None
+ if descriptor_path.stat().st_size > MAX_DESCRIPTOR_BYTES:
+ return None
+ payload = json.loads(descriptor_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+
+ spec = BACKEND_SPECS[backend]
+ if (
+ payload.get("schema_version") != CURRENT_DESCRIPTOR_SCHEMA_VERSION
+ or payload.get("backend") != backend
+ or payload.get("package") != spec.package
+ or not isinstance(payload.get("version"), str)
+ ):
+ return None
+
+ executable = _descriptor_relative_path(payload.get("executable"))
+ if executable is None or not executable.parts or executable.parts[0] != backend:
+ return None
+ candidate = root / executable
+ if not _verified_direct_executable(candidate, root=backend_root, require_native=True):
+ return None
+ try:
+ _backend_runtime_path_entries(backend, candidate, root=backend_root)
+ except DesktopBackendError:
+ return None
+ return str(candidate.resolve(strict=True))
+
+
+def is_desktop_backend_path(
+ path: str | os.PathLike[str] | None,
+ base_env: Mapping[str, str] | None = None,
+) -> bool:
+ """Whether *path* is contained by the mutable private backend root."""
+
+ if not path:
+ return False
+ root = private_desktop_backends_root(base_env)
+ if root is None:
+ return False
+ candidate = Path(path).expanduser()
+ if not candidate.is_absolute():
+ return False
+ try:
+ candidate.resolve(strict=False).relative_to(root)
+ except (OSError, ValueError):
+ return False
+ return True
+
+
+def desktop_backend_subprocess_environment(
+ backend: str,
+ executable: str | os.PathLike[str],
+ base_env: Mapping[str, str] | None = None,
+) -> dict[str, str] | None:
+ """Return the launch environment required by an app-private backend.
+
+ The desktop shell starts before a backend may be installed, so mutable
+ backend support directories cannot be added to the Runtime's process-wide
+ ``PATH``. Derive them from the exact configured executable at the backend
+ process boundary instead.
+ """
+
+ source = os.environ if base_env is None else base_env
+ root = private_desktop_backends_root(source)
+ if (
+ backend not in BACKEND_SPECS
+ or root is None
+ or not is_desktop_backend_path(executable, source)
+ ):
+ return None
+ backend_root = root / backend
+ candidate = Path(executable).expanduser()
+ if not _verified_direct_executable(candidate, root=backend_root, require_native=True):
+ raise DesktopBackendError(
+ f"Published {backend} executable failed validation.",
+ code="invalid_executable",
+ )
+ runtime_paths = _backend_runtime_path_entries(backend, candidate, root=backend_root)
+ environment = dict(source)
+ if runtime_paths:
+ _prepend_path_entries(environment, runtime_paths)
+ return environment
+
+
+def install_desktop_backend(
+ backend: str,
+ *,
+ base_env: Mapping[str, str] | None = None,
+ activate: ActivationCallback | None = None,
+ timeout_seconds: float = DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS,
+) -> DesktopBackendInstallResult:
+ """Install or update one backend and atomically publish its descriptor.
+
+ ``activate`` lets the config owner persist the final executable while the
+ cross-process install lock is still held. The descriptor is published first
+ so configuration can never point at an unpublished release.
+ """
+
+ spec = BACKEND_SPECS.get(backend)
+ if spec is None:
+ raise DesktopBackendError(
+ f"Unknown desktop backend: {backend}",
+ code="unknown_backend",
+ )
+ toolchain = desktop_backend_toolchain(base_env)
+ if toolchain is None:
+ raise DesktopBackendError(
+ "The desktop backend installer is unavailable.",
+ code="desktop_toolchain_unavailable",
+ )
+
+ backend_root = toolchain.backends_root / backend
+ _prepare_backend_root(toolchain.backends_root, backend_root)
+ lock = MigrationFileLock(
+ backend_root / ".install.lock",
+ timeout_seconds=DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS,
+ )
+ try:
+ lock.acquire()
+ except MigrationLockTimeout as exc:
+ raise DesktopBackendError(
+ f"Another {backend} install is already running.",
+ code="install_locked",
+ ) from exc
+
+ staging = backend_root / f".staging-{uuid.uuid4().hex}"
+ try:
+ staging.mkdir(mode=0o700)
+ user_config = staging / "npm-user.conf"
+ global_config = staging / "npm-global.conf"
+ user_config.write_text("", encoding="utf-8")
+ global_config.write_text("", encoding="utf-8")
+ command = [
+ str(toolchain.node),
+ str(toolchain.npm_cli),
+ "install",
+ "--prefix",
+ str(staging),
+ "--no-save",
+ "--package-lock=false",
+ "--omit=dev",
+ "--ignore-scripts",
+ "--no-audit",
+ "--no-fund",
+ f"--registry={NPM_REGISTRY}",
+ spec.package,
+ ]
+ completed = _run_command(
+ command,
+ cwd=staging,
+ env=_npm_environment(toolchain, staging, user_config, global_config, base_env),
+ timeout_seconds=timeout_seconds,
+ )
+ output = _bounded_output(completed.stdout, completed.stderr)
+ if completed.returncode != 0:
+ raise DesktopBackendError(
+ f"Desktop backend install failed (exit code {completed.returncode})",
+ code="npm_install_failed",
+ output=output,
+ )
+ _remove_internal_directory(staging / ".npm-cache", staging)
+ user_config.unlink(missing_ok=True)
+ global_config.unlink(missing_ok=True)
+
+ package_dir = staging / "node_modules" / Path(*spec.package_path)
+ version = _installed_package_version(package_dir, spec.package)
+ executable = _installed_native_executable(backend, spec, staging, package_dir)
+ runtime_paths = _backend_runtime_path_entries(backend, executable, root=staging)
+ _verify_backend_executable(
+ backend,
+ executable,
+ root=staging,
+ env=_backend_command_environment(
+ toolchain,
+ base_env,
+ runtime_paths=runtime_paths,
+ ),
+ )
+
+ releases_root = backend_root / "releases"
+ releases_root.mkdir(mode=0o700, exist_ok=True)
+ release_root = releases_root / uuid.uuid4().hex
+ os.replace(staging, release_root)
+ published_executable = release_root / executable.relative_to(staging)
+
+ relative_executable = published_executable.relative_to(toolchain.backends_root).as_posix()
+ descriptor = {
+ "schema_version": CURRENT_DESCRIPTOR_SCHEMA_VERSION,
+ "backend": backend,
+ "package": spec.package,
+ "version": version,
+ "executable": relative_executable,
+ }
+ descriptor_path = backend_root / "current.json"
+ previous_descriptor = _read_descriptor_bytes(descriptor_path)
+ try:
+ # The descriptor is the publication boundary. Configuration may
+ # point at a release only after this atomic replacement succeeds,
+ # so a crash can never activate an unpublished executable.
+ _write_current_descriptor(descriptor_path, descriptor)
+ if activate is not None:
+ activate(str(published_executable))
+ except Exception:
+ _restore_descriptor_bytes(descriptor_path, previous_descriptor)
+ # Once staging has been renamed, the outer cleanup can no longer
+ # reach it. Remove the release only after restoring the descriptor;
+ # if restoration itself fails, retaining the files is safer than a
+ # descriptor that points at a deleted executable.
+ _remove_staging_directory(release_root, backend_root)
+ raise
+
+ return DesktopBackendInstallResult(
+ backend=backend,
+ package=spec.package,
+ version=version,
+ path=str(published_executable),
+ output=output,
+ )
+ except DesktopBackendError:
+ raise
+ except Exception as exc:
+ raise DesktopBackendError(
+ f"Desktop backend install failed: {exc}",
+ code="desktop_install_failed",
+ ) from exc
+ finally:
+ _remove_staging_directory(staging, backend_root)
+ lock.release()
+
+
+def _prepare_backend_root(root: Path, backend_root: Path) -> None:
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if root.is_symlink() or not root.is_dir():
+ raise DesktopBackendError("Invalid desktop backend root.", code="invalid_backend_root")
+ backend_root.mkdir(mode=0o700, exist_ok=True)
+ if backend_root.is_symlink() or not backend_root.is_dir():
+ raise DesktopBackendError("Invalid desktop backend directory.", code="invalid_backend_root")
+ if os.name != "nt":
+ root.chmod(0o700)
+ backend_root.chmod(0o700)
+
+
+def _npm_environment(
+ toolchain: DesktopBackendToolchain,
+ staging: Path,
+ user_config: Path,
+ global_config: Path,
+ base_env: Mapping[str, str] | None,
+) -> dict[str, str]:
+ source = os.environ if base_env is None else base_env
+ env = _safe_process_environment(source)
+ path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry]
+ node_dir = str(toolchain.node.parent)
+ env["PATH"] = os.pathsep.join([node_dir, *(entry for entry in path_entries if entry != node_dir)])
+ env.update(
+ {
+ "NPM_CONFIG_PREFIX": str(staging),
+ "NPM_CONFIG_CACHE": str(staging / ".npm-cache"),
+ "NPM_CONFIG_USERCONFIG": str(user_config),
+ "NPM_CONFIG_GLOBALCONFIG": str(global_config),
+ "NPM_CONFIG_REGISTRY": NPM_REGISTRY,
+ "NPM_CONFIG_AUDIT": "false",
+ "NPM_CONFIG_FUND": "false",
+ "NPM_CONFIG_UPDATE_NOTIFIER": "false",
+ }
+ )
+ return env
+
+
+def _backend_command_environment(
+ toolchain: DesktopBackendToolchain,
+ base_env: Mapping[str, str] | None,
+ *,
+ runtime_paths: tuple[Path, ...] = (),
+) -> dict[str, str]:
+ source = os.environ if base_env is None else base_env
+ env = _safe_process_environment(source)
+ entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry]
+ node_dir = str(toolchain.node.parent)
+ env["PATH"] = os.pathsep.join([node_dir, *(entry for entry in entries if entry != node_dir)])
+ _prepend_path_entries(env, runtime_paths)
+ return env
+
+
+def _prepend_path_entries(environment: dict[str, str], paths: tuple[Path, ...]) -> None:
+ entries = [entry for entry in environment.get("PATH", "").split(os.pathsep) if entry]
+ prefixes = [str(path) for path in paths]
+ environment["PATH"] = os.pathsep.join(
+ [*prefixes, *(entry for entry in entries if entry not in prefixes)]
+ )
+
+
+def _safe_process_environment(source: Mapping[str, str]) -> dict[str, str]:
+ allowed = {
+ "APPDATA",
+ "COMSPEC",
+ "HOME",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "LANG",
+ "LOCALAPPDATA",
+ "NODE_EXTRA_CA_CERTS",
+ "NO_PROXY",
+ "PATH",
+ "PATHEXT",
+ "SSL_CERT_DIR",
+ "SSL_CERT_FILE",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "USERPROFILE",
+ "WINDIR",
+ "http_proxy",
+ "https_proxy",
+ "no_proxy",
+ }
+ return {
+ key: value
+ for key, value in source.items()
+ if key in allowed or key.startswith("LC_")
+ }
+
+
+def _run_command(
+ command: list[str],
+ *,
+ cwd: Path,
+ env: Mapping[str, str],
+ timeout_seconds: float,
+) -> subprocess.CompletedProcess[str]:
+ logger.info("Installing desktop backend package %s", command[-1])
+ process = subprocess.Popen(
+ command,
+ cwd=cwd,
+ env=dict(env),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ **isolated_subprocess_kwargs(),
+ )
+ try:
+ stdout, stderr = process.communicate(timeout=timeout_seconds)
+ except subprocess.TimeoutExpired as exc:
+ signal_process_tree(process, KILL_SIGNAL, logger, "desktop backend install")
+ stdout, stderr = process.communicate(
+ timeout=DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS,
+ )
+ raise DesktopBackendError(
+ "Desktop backend install timed out.",
+ code="install_timeout",
+ output=_bounded_output(stdout, stderr),
+ ) from exc
+ return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
+
+
+def _installed_package_version(package_dir: Path, expected_package: str) -> str:
+ manifest = package_dir / "package.json"
+ try:
+ if manifest.is_symlink() or manifest.stat().st_size > MAX_DESCRIPTOR_BYTES:
+ raise ValueError("invalid package manifest")
+ payload = json.loads(manifest.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
+ raise DesktopBackendError(
+ "Installed package metadata is missing or invalid.",
+ code="invalid_package",
+ ) from exc
+ name = payload.get("name") if isinstance(payload, dict) else None
+ version = payload.get("version") if isinstance(payload, dict) else None
+ if name != expected_package or not isinstance(version, str) or not version or len(version) > 128:
+ raise DesktopBackendError(
+ "Installed package identity does not match the requested backend.",
+ code="invalid_package",
+ )
+ return version
+
+
+def _installed_native_executable(
+ backend: str,
+ spec: DesktopBackendSpec,
+ staging: Path,
+ package_dir: Path,
+) -> Path:
+ os_name, arch = _native_target()
+ if backend == "codex":
+ executable_name = "codex.exe" if os_name == "win32" else "codex"
+ target_package = staging / "node_modules" / "@openai" / f"codex-{os_name}-{arch}"
+ target_roots = [target_package, package_dir / "node_modules" / "@openai" / target_package.name]
+ candidates = [
+ candidate
+ for target_root in target_roots
+ for candidate in target_root.glob(f"vendor/*/bin/{executable_name}")
+ ]
+ elif backend == "claude":
+ executable_name = "claude.exe" if os_name == "win32" else "claude"
+ target_package = staging / "node_modules" / "@anthropic-ai" / f"claude-code-{os_name}-{arch}"
+ target_roots = [target_package, package_dir / "node_modules" / "@anthropic-ai" / target_package.name]
+ candidates = [target_root / executable_name for target_root in target_roots]
+ elif backend == "opencode":
+ target_os = "windows" if os_name == "win32" else os_name
+ executable_name = "opencode.exe" if os_name == "win32" else "opencode"
+ target_package = staging / "node_modules" / f"opencode-{target_os}-{arch}"
+ target_roots = [target_package, package_dir / "node_modules" / target_package.name]
+ candidates = [target_root / "bin" / executable_name for target_root in target_roots]
+ else: # BACKEND_SPECS and callers keep this unreachable.
+ candidates = []
+
+ unique: dict[Path, Path] = {}
+ for candidate in candidates:
+ try:
+ unique[candidate.resolve(strict=True)] = candidate
+ except OSError:
+ continue
+ if len(unique) != 1:
+ raise DesktopBackendError(
+ f"Installed {backend} package contains no unique target-native executable.",
+ code="native_executable_missing",
+ )
+ executable = next(iter(unique))
+ if not _verified_direct_executable(executable, root=staging, require_native=True):
+ raise DesktopBackendError(
+ f"Installed {backend} executable failed validation.",
+ code="invalid_executable",
+ )
+ return executable
+
+
+def _backend_runtime_path_entries(
+ backend: str,
+ executable: Path,
+ *,
+ root: Path,
+) -> tuple[Path, ...]:
+ if backend != "codex":
+ return ()
+
+ windows = os.name == "nt"
+ target_root = executable.parent.parent
+ executable_paths = [
+ target_root
+ / "bin"
+ / ("codex-code-mode-host.exe" if windows else "codex-code-mode-host"),
+ target_root / "codex-path" / ("rg.exe" if windows else "rg"),
+ ]
+ if windows:
+ executable_paths.extend(
+ [
+ target_root / "codex-resources" / "codex-command-runner.exe",
+ target_root / "codex-resources" / "codex-windows-sandbox-setup.exe",
+ ]
+ )
+ else:
+ executable_paths.append(
+ target_root / "codex-resources" / "zsh" / "bin" / "zsh"
+ )
+ if platform.system().lower() == "linux":
+ executable_paths.append(target_root / "codex-resources" / "bwrap")
+
+ package_manifest = target_root / "codex-package.json"
+ if not _verified_direct_regular_file(package_manifest, root=root) or not all(
+ _verified_direct_executable(path, root=root, require_native=True)
+ for path in executable_paths
+ ):
+ raise DesktopBackendError(
+ "Installed Codex package is missing a required native runtime helper.",
+ code="incomplete_backend_runtime",
+ )
+ return (executable_paths[1].parent.resolve(strict=True),)
+
+
+def _verify_backend_executable(
+ backend: str,
+ executable: Path,
+ *,
+ root: Path,
+ env: Mapping[str, str],
+) -> None:
+ if not _verified_direct_executable(executable, root=root, require_native=True):
+ raise DesktopBackendError(
+ f"Installed {backend} executable failed validation.",
+ code="invalid_executable",
+ )
+ try:
+ result = subprocess.run(
+ [str(executable), "--version"],
+ cwd=root,
+ env=dict(env),
+ capture_output=True,
+ text=True,
+ timeout=DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise DesktopBackendError(
+ f"Installed {backend} executable could not be started.",
+ code="executable_probe_failed",
+ ) from exc
+ if result.returncode != 0 or not _version_from_output(result.stdout, result.stderr):
+ raise DesktopBackendError(
+ f"Installed {backend} executable did not report a valid version.",
+ code="executable_probe_failed",
+ output=_bounded_output(result.stdout, result.stderr),
+ )
+
+
+def _verified_direct_executable(path: Path, *, root: Path, require_native: bool) -> bool:
+ try:
+ if path.is_symlink() or not path.is_file():
+ return False
+ resolved = path.resolve(strict=True)
+ resolved.relative_to(root.resolve(strict=True))
+ relative = path.relative_to(root)
+ cursor = root
+ for part in relative.parts:
+ cursor = cursor / part
+ if cursor.is_symlink():
+ return False
+ if path.suffix.lower() in {".cmd", ".ps1", ".js"}:
+ return False
+ if os.name != "nt" and not os.access(resolved, os.X_OK):
+ return False
+ return not require_native or _has_native_magic(resolved)
+ except (OSError, ValueError):
+ return False
+
+
+def _verified_direct_regular_file(path: Path, *, root: Path) -> bool:
+ try:
+ if path.is_symlink() or not path.is_file():
+ return False
+ resolved = path.resolve(strict=True)
+ resolved.relative_to(root.resolve(strict=True))
+ relative = path.relative_to(root)
+ cursor = root
+ for part in relative.parts:
+ cursor = cursor / part
+ if cursor.is_symlink():
+ return False
+ return True
+ except (OSError, ValueError):
+ return False
+
+
+def _has_native_magic(path: Path) -> bool:
+ try:
+ with path.open("rb") as handle:
+ magic = handle.read(4)
+ except OSError:
+ return False
+ return magic.startswith(b"MZ") or magic == b"\x7fELF" or magic in {
+ b"\xfe\xed\xfa\xce",
+ b"\xfe\xed\xfa\xcf",
+ b"\xce\xfa\xed\xfe",
+ b"\xcf\xfa\xed\xfe",
+ b"\xca\xfe\xba\xbe",
+ b"\xbe\xba\xfe\xca",
+ }
+
+
+def _native_target() -> tuple[str, str]:
+ if os.name == "nt":
+ os_name = "win32"
+ elif platform.system().lower() == "darwin":
+ os_name = "darwin"
+ elif platform.system().lower() == "linux":
+ os_name = "linux"
+ else:
+ raise DesktopBackendError("Unsupported desktop platform.", code="unsupported_platform")
+ machine = platform.machine().lower()
+ if machine in {"amd64", "x86_64"}:
+ arch = "x64"
+ elif machine in {"arm64", "aarch64"}:
+ arch = "arm64"
+ else:
+ raise DesktopBackendError("Unsupported desktop architecture.", code="unsupported_platform")
+ return os_name, arch
+
+
+def _descriptor_relative_path(value: Any) -> Path | None:
+ if not isinstance(value, str) or not value or len(value) > 4096 or "\\" in value:
+ return None
+ relative = PurePosixPath(value)
+ if relative.is_absolute() or ".." in relative.parts or "." in relative.parts:
+ return None
+ if any(not part or ":" in part for part in relative.parts):
+ return None
+ return Path(*relative.parts)
+
+
+def _write_current_descriptor(path: Path, payload: dict[str, Any]) -> None:
+ encoded = (json.dumps(payload, sort_keys=True) + "\n").encode("utf-8")
+ if len(encoded) > MAX_DESCRIPTOR_BYTES:
+ raise ValueError("desktop backend descriptor exceeds size limit")
+ _write_descriptor_bytes(path, encoded)
+
+
+def _read_descriptor_bytes(path: Path) -> bytes | None:
+ try:
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_DESCRIPTOR_BYTES:
+ return None
+ return path.read_bytes()
+ except OSError:
+ return None
+
+
+def _restore_descriptor_bytes(path: Path, previous: bytes | None) -> None:
+ if previous is None:
+ path.unlink(missing_ok=True)
+ return
+ _write_descriptor_bytes(path, previous)
+
+
+def _write_descriptor_bytes(path: Path, encoded: bytes) -> None:
+ if len(encoded) > MAX_DESCRIPTOR_BYTES:
+ raise ValueError("desktop backend descriptor exceeds size limit")
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ fd, temporary_name = tempfile.mkstemp(prefix=".current-", suffix=".json", dir=path.parent)
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(encoded)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ if os.name != "nt":
+ directory_fd = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory_fd)
+ finally:
+ os.close(directory_fd)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def _remove_staging_directory(staging: Path, backend_root: Path) -> None:
+ try:
+ staging.relative_to(backend_root)
+ except ValueError:
+ return
+ try:
+ if staging.is_symlink():
+ staging.unlink(missing_ok=True)
+ elif staging.exists():
+ shutil.rmtree(staging)
+ except OSError:
+ logger.warning("Failed to remove desktop backend staging directory %s", staging)
+
+
+def _remove_internal_directory(path: Path, root: Path) -> None:
+ try:
+ path.relative_to(root)
+ except ValueError:
+ return
+ if path.is_symlink():
+ path.unlink(missing_ok=True)
+ elif path.exists():
+ shutil.rmtree(path)
+
+
+def _version_from_output(stdout: str | None, stderr: str | None) -> str | None:
+ import re
+
+ match = re.search(r"\d+(?:\.\d+){1,3}(?:[-+][\w.-]+)?", f"{stdout or ''} {stderr or ''}")
+ return match.group(0) if match else None
+
+
+def _bounded_output(stdout: str | None, stderr: str | None) -> str | None:
+ output = (stdout or "") + ("\n" + stderr if stderr else "")
+ output = output.strip()
+ if len(output) > MAX_INSTALL_OUTPUT_CHARS:
+ output = "...(truncated)\n" + output[-MAX_INSTALL_OUTPUT_CHARS:]
+ return output or None
diff --git a/vibe/desktop_runtime.py b/vibe/desktop_runtime.py
new file mode 100644
index 000000000..bed638001
--- /dev/null
+++ b/vibe/desktop_runtime.py
@@ -0,0 +1,277 @@
+"""Desktop-shell endpoint and listener contracts.
+
+The desktop shell always connects through a literal loopback origin, even when
+the user's primary UI bind is a specific LAN or overlay-network address. The
+UI process owns both listeners so the shell never has to interpret Avibe
+configuration or broaden its navigation policy.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import json
+import math
+import os
+import socket
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Literal, TypedDict, cast
+
+DESKTOP_ENDPOINT_SCHEMA_VERSION: Literal[1] = 1
+DESKTOP_RUNTIME_ID_ENV = "AVIBE_DESKTOP_RUNTIME_ID"
+DESKTOP_RUNTIME_ROOT_ENV = "AVIBE_DESKTOP_RUNTIME_ROOT"
+DESKTOP_NODE_BIN_ENV = "VIBE_SHOW_RUNTIME_NODE_BIN"
+DESKTOP_NPM_CLI_ENV = "AVIBE_DESKTOP_NPM_CLI"
+DESKTOP_BACKENDS_ROOT_ENV = "AVIBE_DESKTOP_BACKENDS_ROOT"
+START_RECEIPT_PREFIX = "@avibe-start-receipt:"
+START_RECEIPT_TIME_TOLERANCE_MS = 2.0
+
+
+class StartReceipt(TypedDict):
+ schema_version: Literal[1]
+ outcome: Literal["started", "reused"]
+ service_pid: int
+ ui_pid: int
+ service_create_unix_ms: float
+ ui_create_unix_ms: float
+
+
+def validate_start_receipt(payload: object) -> StartReceipt:
+ if not isinstance(payload, dict):
+ raise ValueError("Startup receipt must be an object")
+ if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
+ raise ValueError("Unsupported startup receipt schema")
+ if payload.get("outcome") not in ("started", "reused"):
+ raise ValueError("Invalid startup receipt outcome")
+ for field in ("service_pid", "ui_pid"):
+ value = payload.get(field)
+ if type(value) is not int or value <= 0:
+ raise ValueError(f"Invalid startup receipt {field}")
+ for field in ("service_create_unix_ms", "ui_create_unix_ms"):
+ value = payload.get(field)
+ if type(value) not in (int, float) or value <= 0:
+ raise ValueError(f"Invalid startup receipt {field}")
+ try:
+ finite = math.isfinite(value)
+ except OverflowError:
+ finite = False
+ if not finite:
+ raise ValueError(f"Invalid startup receipt {field}")
+ return cast(StartReceipt, payload)
+
+
+def start_receipt_line(payload: object) -> str:
+ receipt = validate_start_receipt(payload)
+ return START_RECEIPT_PREFIX + json.dumps(receipt, separators=(",", ":"), allow_nan=False)
+
+
+class DesktopEndpointPayload(TypedDict):
+ schema_version: Literal[1]
+ origin: str
+
+
+def desktop_runtime_id(base_env: Mapping[str, str] | None = None) -> str | None:
+ """Return the validated identity of a desktop-managed Runtime."""
+
+ env = os.environ if base_env is None else base_env
+ value = env.get(DESKTOP_RUNTIME_ID_ENV, "")
+ if len(value) != 64 or any(character not in "0123456789abcdef" for character in value):
+ return None
+ return value
+
+
+def private_desktop_runtime_root(base_env: Mapping[str, str] | None = None) -> Path | None:
+ """Return the app-private Runtime root supplied by the desktop launcher."""
+
+ env = os.environ if base_env is None else base_env
+ value = env.get(DESKTOP_RUNTIME_ROOT_ENV, "")
+ if not value:
+ return None
+ root = Path(value).expanduser()
+ if not root.is_absolute():
+ return None
+ return root.resolve(strict=False)
+
+
+def private_desktop_node_bin(base_env: Mapping[str, str] | None = None) -> Path | None:
+ """Return the verified bundled Node.js executable, when available."""
+
+ return _private_desktop_runtime_file(DESKTOP_NODE_BIN_ENV, base_env, executable=True)
+
+
+def private_desktop_npm_cli(base_env: Mapping[str, str] | None = None) -> Path | None:
+ """Return the verified bundled npm CLI entrypoint, when available."""
+
+ return _private_desktop_runtime_file(DESKTOP_NPM_CLI_ENV, base_env)
+
+
+def private_desktop_backends_root(base_env: Mapping[str, str] | None = None) -> Path | None:
+ """Return the mutable app-private backend root supplied by the launcher."""
+
+ env = os.environ if base_env is None else base_env
+ value = env.get(DESKTOP_BACKENDS_ROOT_ENV, "")
+ if not value:
+ return None
+ root = Path(value).expanduser()
+ if not root.is_absolute() or root.is_symlink():
+ return None
+ resolved = root.resolve(strict=False)
+ runtime_root = private_desktop_runtime_root(env)
+ if runtime_root is None:
+ return None
+ try:
+ resolved.relative_to(runtime_root)
+ return None
+ except ValueError:
+ pass
+ try:
+ runtime_root.relative_to(resolved)
+ return None
+ except ValueError:
+ return resolved
+
+
+def _private_desktop_runtime_file(
+ env_name: str,
+ base_env: Mapping[str, str] | None,
+ *,
+ executable: bool = False,
+) -> Path | None:
+ env = os.environ if base_env is None else base_env
+ value = env.get(env_name, "")
+ if not value:
+ return None
+ candidate = Path(value).expanduser()
+ if not candidate.is_absolute() or candidate.is_symlink():
+ return None
+ try:
+ resolved = candidate.resolve(strict=True)
+ except OSError:
+ return None
+ root = private_desktop_runtime_root(env)
+ if root is None:
+ return None
+ try:
+ resolved.relative_to(root)
+ except ValueError:
+ return None
+ if not resolved.is_file() or (executable and not os.access(resolved, os.X_OK)):
+ return None
+ return resolved
+
+
+def is_private_desktop_runtime_path(
+ path: str | os.PathLike[str] | None,
+ base_env: Mapping[str, str] | None = None,
+) -> bool:
+ """Whether *path* belongs to the verified app-private Runtime tree."""
+
+ if not path:
+ return False
+ root = private_desktop_runtime_root(base_env)
+ if root is None:
+ return False
+ candidate = Path(path).expanduser()
+ if not candidate.is_absolute():
+ return False
+ try:
+ candidate.resolve(strict=False).relative_to(root)
+ except ValueError:
+ return False
+ return True
+
+
+def _normalized_bind_host(bind_host: str | None) -> str:
+ """Turn a configured setup host into something a socket can actually bind.
+
+ ``ui.setup_host`` holds what a person typed, and two of those spellings are
+ not addresses: ``[::1]`` is a URL rendering and ``*`` is a word for "every
+ interface". ``getaddrinfo`` rejects both, so any listener built from them
+ fails at bind -- which is where ``*`` has always failed, uvicorn's own bind
+ on ``master`` included. Resolving them here keeps the knowledge in one place
+ instead of teaching each listener the spellings.
+ """
+
+ host = (bind_host or "127.0.0.1").strip()
+ if host.startswith("[") and host.endswith("]"):
+ host = host[1:-1]
+ if host == "*":
+ return "0.0.0.0"
+ return host
+
+
+def _bind_family(bind_host: str | None) -> socket.AddressFamily:
+ host = _normalized_bind_host(bind_host)
+ return socket.AF_INET6 if ":" in host else socket.AF_INET
+
+
+def desktop_loopback_host(bind_host: str | None) -> str:
+ """Return the literal loopback matching the primary bind's IP family."""
+
+ return "::1" if _bind_family(bind_host) == socket.AF_INET6 else "127.0.0.1"
+
+
+def requires_desktop_loopback_listener(bind_host: str | None) -> bool:
+ """Whether a specific primary bind needs a second loopback listener."""
+
+ host = _normalized_bind_host(bind_host)
+ try:
+ address = ipaddress.ip_address(host)
+ except ValueError:
+ # Match the first address the same-family socket bind will select. A
+ # loopback-only hostname already serves the desktop; an unresolved or
+ # non-loopback name still needs the companion listener.
+ try:
+ resolved = socket.getaddrinfo(
+ host,
+ None,
+ family=_bind_family(host),
+ type=socket.SOCK_STREAM,
+ )
+ address = ipaddress.ip_address(resolved[0][4][0])
+ except (IndexError, OSError, ValueError):
+ return True
+ advertised = ipaddress.ip_address(desktop_loopback_host(host))
+ return not address.is_unspecified and address != advertised
+
+
+def ui_listener_hosts(bind_host: str | None) -> tuple[str, ...]:
+ """Return the primary listener plus any desktop-only loopback listener."""
+
+ # The same normalisation every other helper here already applies, so the
+ # host that gets bound and the host they reason about cannot disagree.
+ primary = _normalized_bind_host(bind_host)
+ if requires_desktop_loopback_listener(primary):
+ return primary, desktop_loopback_host(primary)
+ return (primary,)
+
+
+def normalize_desktop_port(port: int | str) -> int:
+ if isinstance(port, str):
+ if not port.isascii() or not port.isdecimal():
+ raise ValueError("desktop endpoint port must be between 1 and 65535")
+ port = int(port)
+ if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
+ raise ValueError("desktop endpoint port must be between 1 and 65535")
+ return port
+
+
+def desktop_origin(bind_host: str | None, port: int | str) -> str:
+ """Build the desktop shell's exact loopback origin."""
+
+ normalized_port = normalize_desktop_port(port)
+ loopback = desktop_loopback_host(bind_host)
+ rendered_host = f"[{loopback}]" if ":" in loopback else loopback
+ return f"http://{rendered_host}:{normalized_port}"
+
+
+def desktop_endpoint_payload(
+ bind_host: str | None,
+ port: int | str,
+) -> DesktopEndpointPayload:
+ """Return the frozen schema-v1 descriptor consumed by the desktop shell."""
+
+ return {
+ "schema_version": DESKTOP_ENDPOINT_SCHEMA_VERSION,
+ "origin": desktop_origin(bind_host, port),
+ }
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index e6922d2bc..15f6bea96 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -827,6 +827,23 @@
"en": "English",
"zh": "中文"
},
+ "desktopRuntime": {
+ "checkUpdate": "Updates are delivered with the Avibe desktop app.",
+ "upgrade": "This Runtime is managed by the Avibe desktop app. Update the app to update Avibe.",
+ "apiUpgrade": "This Runtime is managed by the Avibe desktop app.",
+ "backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately."
+ },
+ "desktopBackendInstall": {
+ "success": "{backend} installed successfully.",
+ "unknownBackend": "Unknown desktop backend: {backend}.",
+ "toolchainUnavailable": "The desktop backend installer is unavailable.",
+ "installLocked": "Another {backend} installation is already running.",
+ "installFailed": "Could not install {backend}.",
+ "invalidInstall": "The installed {backend} package is invalid.",
+ "unsupportedPlatform": "{backend} is not supported on this desktop platform.",
+ "timedOut": "Installing {backend} timed out.",
+ "probeFailed": "The installed {backend} executable could not be verified."
+ },
"telegram": {
"commandMenu": {
"start": "Open the main menu",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 639b022bb..a145d6b3a 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -827,6 +827,23 @@
"en": "English",
"zh": "中文"
},
+ "desktopRuntime": {
+ "checkUpdate": "更新由 Avibe 桌面应用统一提供。",
+ "upgrade": "此 Runtime 由 Avibe 桌面应用管理。请更新桌面应用来更新 Avibe。",
+ "apiUpgrade": "此 Runtime 由 Avibe 桌面应用管理。",
+ "backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。"
+ },
+ "desktopBackendInstall": {
+ "success": "{backend} 安装成功。",
+ "unknownBackend": "未知的桌面后端:{backend}。",
+ "toolchainUnavailable": "桌面后端安装器当前不可用。",
+ "installLocked": "另一个 {backend} 安装任务正在运行。",
+ "installFailed": "无法安装 {backend}。",
+ "invalidInstall": "已安装的 {backend} 软件包无效。",
+ "unsupportedPlatform": "当前桌面平台不支持 {backend}。",
+ "timedOut": "安装 {backend} 超时。",
+ "probeFailed": "无法验证已安装的 {backend} 可执行文件。"
+ },
"telegram": {
"commandMenu": {
"start": "打开主菜单",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 6837a1a96..66ad16620 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -1,10 +1,10 @@
-"""``httpx`` wrapper for talking to the controller's internal Unix socket.
+"""``httpx`` wrapper for the Controller's cross-platform control IPC.
C5 of Plan 2 (see ``docs/plans/workbench-dispatch-architecture.md``).
The UI server runs as its own subprocess; this module is how it reaches
``core.internal_server`` to start agent turns and observe their lifecycle.
-Single responsibility: keep all the socket-path / httpx-transport /
+Single responsibility: keep all the endpoint discovery / httpx-transport /
SSE-parsing boilerplate out of the UI route bodies. Routes call
``dispatch_async(...)`` to start a fire-and-forget turn (the reply arrives over
the persistent ``message.new`` session stream, not the response),
@@ -26,7 +26,7 @@ from typing import Any, AsyncIterator, Optional
import httpx
-from config import paths
+from core import control_ipc
logger = logging.getLogger(__name__)
_SOCKET_ERRORS = (httpx.TransportError, OSError)
@@ -60,10 +60,62 @@ def default_socket_path() -> Path:
boundaries clean.
"""
- override = os.environ.get("VIBE_INTERNAL_DISPATCH_SOCKET")
- if override:
- return Path(override).expanduser()
- return paths.get_state_dir() / "dispatch.sock"
+ return control_ipc.default_unix_socket_path()
+
+
+def _platform_name() -> str:
+ return os.name
+
+
+def _resolve_endpoint(socket_path: Optional[Path]) -> control_ipc.ControlIpcClientEndpoint:
+ platform_name = _platform_name()
+ if socket_path is not None or platform_name != "nt":
+ return control_ipc.ControlIpcClientEndpoint(
+ transport="unix",
+ socket_path=_verified_socket_path(socket_path),
+ )
+ try:
+ endpoint = control_ipc.resolve_client_endpoint(
+ platform_name=platform_name,
+ socket_path=socket_path,
+ )
+ except control_ipc.ControlIpcDescriptorError as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return endpoint
+
+
+async def _resolve_endpoint_async(
+ socket_path: Optional[Path],
+) -> control_ipc.ControlIpcClientEndpoint:
+ """Keep endpoint discovery and filesystem checks off the UI event loop."""
+
+ return await asyncio.to_thread(_resolve_endpoint, socket_path)
+
+
+def _async_transport(endpoint: control_ipc.ControlIpcClientEndpoint) -> httpx.AsyncBaseTransport:
+ if endpoint.transport == "unix":
+ return httpx.AsyncHTTPTransport(uds=str(endpoint.socket_path))
+ return httpx.AsyncHTTPTransport()
+
+
+def _sync_transport(endpoint: control_ipc.ControlIpcClientEndpoint) -> httpx.BaseTransport:
+ if endpoint.transport == "unix":
+ return httpx.HTTPTransport(uds=str(endpoint.socket_path))
+ return httpx.HTTPTransport()
+
+
+def _validate_response(
+ response: httpx.Response,
+ endpoint: control_ipc.ControlIpcClientEndpoint,
+) -> None:
+ descriptor = endpoint.descriptor
+ if descriptor is None:
+ return
+ if response.status_code == 401:
+ raise InternalServerUnavailable("control IPC authentication was rejected")
+ response_instance = response.headers.get(control_ipc.CONTROL_IPC_INSTANCE_HEADER)
+ if not control_ipc.response_instance_matches(descriptor, response_instance):
+ raise InternalServerUnavailable("control IPC response came from a stale instance")
def _verified_socket_path(socket_path: Optional[Path]) -> Path:
@@ -85,12 +137,6 @@ def _verified_socket_path(socket_path: Optional[Path]) -> Path:
return target
-async def _verified_socket_path_async(socket_path: Optional[Path]) -> Path:
- """Keep socket metadata checks off the UI server's event loop."""
-
- return await asyncio.to_thread(_verified_socket_path, socket_path)
-
-
async def stream_dispatch(
payload: dict[str, Any],
*,
@@ -109,13 +155,13 @@ async def stream_dispatch(
flow (``_run_show_event_dispatch`` re-publishes each event as ``show.dispatch``).
"""
- target = await _verified_socket_path_async(socket_path)
+ endpoint = await _resolve_endpoint_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url, headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
try:
@@ -124,6 +170,7 @@ async def stream_dispatch(
raise InternalServerUnavailable(str(exc)) from exc
async with stream as resp:
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
detail = await resp.aread()
raise InternalServerUnavailable(
@@ -165,13 +212,13 @@ async def stream_events(
subscriber loop can back off and reconnect.
"""
- target = await _verified_socket_path_async(socket_path)
-
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(None, connect=5.0),
) as client:
try:
@@ -180,6 +227,7 @@ async def stream_events(
raise InternalServerUnavailable(str(exc)) from exc
async with stream as resp:
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
detail = await resp.aread()
raise InternalServerUnavailable(
@@ -216,16 +264,17 @@ async def publish_event(
) -> dict[str, Any]:
"""Ask the Controller process to publish an allowlisted SSE notification."""
- target = await _verified_socket_path_async(socket_path)
-
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=2.0),
) as client:
resp = await client.post("/internal/events", json={"type": event_type, "data": data})
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
detail = await resp.aread()
raise InternalServerUnavailable(f"events publish returned {resp.status_code}: {detail!r}")
@@ -245,16 +294,17 @@ def publish_event_sync(
) -> dict[str, Any]:
"""Synchronous wrapper for CLI/child-process notification publishers."""
- target = _verified_socket_path(socket_path)
-
- transport = httpx.HTTPTransport(uds=str(target))
+ endpoint = _resolve_endpoint(socket_path)
+ transport = _sync_transport(endpoint)
try:
with httpx.Client(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=2.0),
) as client:
resp = client.post("/internal/events", json={"type": event_type, "data": data})
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
raise InternalServerUnavailable(
f"events publish returned {resp.status_code}: {resp.content!r}"
@@ -271,14 +321,15 @@ def record_skill_observation_sync(
timeout: float = 0.25,
) -> dict[str, Any]:
"""Best-effort queue submission; the response is not a durable receipt."""
- target = _verified_socket_path(socket_path)
+ endpoint = _resolve_endpoint(socket_path)
try:
with httpx.Client(
- transport=httpx.HTTPTransport(uds=str(target)),
- base_url="http://localhost",
+ transport=_sync_transport(endpoint),
+ base_url=endpoint.base_url, headers=endpoint.headers,
timeout=httpx.Timeout(timeout),
) as client:
response = client.post("/internal/skill-observations", json=observation)
+ _validate_response(response, endpoint)
if response.status_code != 202:
raise InternalServerUnavailable("Skill observation rejected")
return response.json()
@@ -303,15 +354,17 @@ async def dispatch_async(
``InternalServerTimeout`` because acceptance is unknown.
"""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post("/internal/dispatch_async", json=payload)
+ _validate_response(resp, endpoint)
except _SOCKET_CONNECT_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
except httpx.TimeoutException as exc:
@@ -323,11 +376,17 @@ async def dispatch_async(
async def archive_session(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:
"""Await accepted archive completion, without a transport reporting deadline."""
- target = await _verified_socket_path_async(socket_path)
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
- transport = httpx.AsyncHTTPTransport(uds=str(target))
- async with httpx.AsyncClient(transport=transport, base_url="http://localhost", timeout=httpx.Timeout(None, connect=5.0)) as client:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
+ timeout=httpx.Timeout(None, connect=5.0),
+ ) as client:
resp = await client.post("/internal/sessions/archive", json={"session_id": session_id})
+ _validate_response(resp, endpoint)
except _SOCKET_CONNECT_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
except httpx.TimeoutException as exc:
@@ -342,15 +401,17 @@ async def reconcile_platforms(
) -> dict[str, Any]:
"""Ask the controller to hot-apply the persisted platform configuration."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post("/internal/reconcile-platforms")
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -363,15 +424,16 @@ async def invalidate_activity_streaming(
) -> dict[str, Any]:
"""Make the controller re-read the persisted Agent Activity display flag."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url, headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=2.0),
) as client:
resp = await client.post("/internal/invalidate-activity-streaming")
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -384,13 +446,14 @@ async def backend_application(
if backend not in AGENT_BACKENDS:
raise ValueError("unsupported_backend")
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
- transport=transport, base_url="http://localhost", timeout=timeout,
+ transport=transport, base_url=endpoint.base_url, headers=endpoint.headers, timeout=timeout,
) as client:
response = await client.get(f"/internal/backend-application/{backend}")
+ _validate_response(response, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": response.status_code, "body": response.json() if response.content else {}}
@@ -404,18 +467,20 @@ async def reconcile_agent_backends(
) -> dict[str, Any]:
"""Ask the controller to hot-apply persisted Agent backend config."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post(
"/internal/reconcile-agent-backends",
json={"backends": backends},
)
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -430,18 +495,20 @@ async def test_backend_auth(
) -> dict[str, Any]:
"""Run a Settings connection probe on the controller-owned Agent runtime."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
payload: dict[str, Any] = {"backend": backend}
if model:
payload["model"] = model
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post("/internal/backend-auth/test", json=payload)
+ _validate_response(resp, endpoint)
except _SOCKET_CONNECT_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
except httpx.TimeoutException as exc:
@@ -457,15 +524,17 @@ async def notify_vault_request_created(
) -> dict[str, Any]:
"""Ask the controller to send the IM degradation notice for a Vault request."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=2.0),
) as client:
resp = await client.post("/internal/vault/request-created", json={"request": request_payload})
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
detail = await resp.aread()
raise InternalServerUnavailable(
@@ -486,16 +555,17 @@ def notify_vault_request_created_sync(
) -> dict[str, Any]:
"""Synchronous wrapper for CLI/UI-server Vault request notifications."""
- target = _verified_socket_path(socket_path)
-
- transport = httpx.HTTPTransport(uds=str(target))
+ endpoint = _resolve_endpoint(socket_path)
+ transport = _sync_transport(endpoint)
try:
with httpx.Client(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=2.0),
) as client:
resp = client.post("/internal/vault/request-created", json={"request": request_payload})
+ _validate_response(resp, endpoint)
if resp.status_code >= 400:
raise InternalServerUnavailable(
f"vault request notification returned {resp.status_code}: {resp.content!r}"
@@ -521,12 +591,13 @@ async def cancel_dispatch(
so the UI route can fall back gracefully.
"""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
# The cancel now WAITS for the backend interrupt to confirm before
# acking (so a refused stop keeps the turn cancellable), and a
# Claude interrupt / OpenCode abort can take a few seconds — give it
@@ -537,6 +608,7 @@ async def cancel_dispatch(
f"/internal/cancel/{session_id}",
params={"run_id": run_id} if run_id is not None else None,
)
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -551,15 +623,17 @@ async def end_running_agent(payload: dict[str, Any], *, socket_path: Optional[Pa
so the timeout matches ``cancel_dispatch``.
"""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
resp = await client.post("/internal/running-agents/end", json=payload)
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -572,15 +646,16 @@ async def _show_access_request(
read_timeout: float | None,
socket_path: Optional[Path] = None,
) -> dict[str, Any]:
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url, headers=endpoint.headers,
timeout=httpx.Timeout(read_timeout, connect=1.0),
) as client:
resp = await client.post(path, json=payload)
+ _validate_response(resp, endpoint)
except httpx.ReadTimeout as exc:
raise InternalServerTimeout(str(exc)) from exc
except _SOCKET_ERRORS as exc:
@@ -629,12 +704,13 @@ async def send_now(
failure so the UI route can degrade.
"""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
# send-now interrupts the running turn before flushing, and that
# backend stop can take a few seconds — match the cancel timeout so a
# slow-but-successful interrupt isn't read-timed-out.
@@ -648,6 +724,7 @@ async def send_now(
else None
),
)
+ _validate_response(resp, endpoint)
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -659,15 +736,17 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->
``{status_code, body}``; raises ``InternalServerUnavailable`` on socket
failure so the route can degrade (assume idle)."""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(1.0, connect=0.2),
) as client:
resp = await client.get(f"/internal/turn-state/{session_id}")
+ _validate_response(resp, endpoint)
except httpx.ReadTimeout as exc:
raise InternalServerTimeout(str(exc)) from exc
except _SOCKET_CONNECT_ERRORS as exc:
@@ -689,12 +768,13 @@ async def list_running_agents(
than ``turn_state``.
"""
- target = await _verified_socket_path_async(socket_path)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
try:
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(3.0, connect=0.5),
) as client:
if run_ids is None:
@@ -704,6 +784,7 @@ async def list_running_agents(
"/internal/running-agents/snapshot",
json={"run_ids": run_ids},
)
+ _validate_response(resp, endpoint)
except httpx.ReadTimeout as exc:
raise InternalServerTimeout(str(exc)) from exc
except _SOCKET_CONNECT_ERRORS as exc:
@@ -711,6 +792,73 @@ async def list_running_agents(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+def _parse_health_response(
+ response: httpx.Response,
+ endpoint: control_ipc.ControlIpcClientEndpoint,
+) -> dict[str, Any] | None:
+ _validate_response(response, endpoint)
+ if response.status_code != 200:
+ return None
+ try:
+ payload = response.json()
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return None
+ if (
+ not isinstance(payload, dict)
+ or payload.get("ok") is not True
+ or payload.get("service") != "vibe-remote-internal"
+ or payload.get("version") != 1
+ ):
+ return None
+
+ runtime_id = payload.get("desktop_runtime_id")
+ if runtime_id is not None:
+ from vibe.desktop_runtime import DESKTOP_RUNTIME_ID_ENV, desktop_runtime_id
+
+ if (
+ not isinstance(runtime_id, str)
+ or desktop_runtime_id({DESKTOP_RUNTIME_ID_ENV: runtime_id}) != runtime_id
+ ):
+ return None
+ return payload
+
+
+async def health_identity(socket_path: Optional[Path] = None) -> dict[str, Any] | None:
+ """Return the validated Controller health identity, or ``None`` on failure."""
+
+ try:
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
+ timeout=httpx.Timeout(2.0, connect=1.0),
+ ) as client:
+ response = await client.get("/internal/health")
+ return _parse_health_response(response, endpoint)
+ except Exception:
+ return None
+
+
+def health_identity_sync(socket_path: Optional[Path] = None) -> dict[str, Any] | None:
+ """Synchronous Controller identity probe for CLI lifecycle decisions."""
+
+ try:
+ endpoint = _resolve_endpoint(socket_path)
+ transport = _sync_transport(endpoint)
+ with httpx.Client(
+ transport=transport,
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
+ timeout=httpx.Timeout(2.0, connect=1.0),
+ ) as client:
+ response = client.get("/internal/health")
+ return _parse_health_response(response, endpoint)
+ except Exception:
+ return None
+
+
async def health(socket_path: Optional[Path] = None) -> bool:
"""Probe ``GET /internal/health``. Returns False on any failure.
@@ -719,21 +867,7 @@ async def health(socket_path: Optional[Path] = None) -> bool:
longer-lived dispatch stream.
"""
- try:
- target = await _verified_socket_path_async(socket_path)
- except InternalServerUnavailable:
- return False
- transport = httpx.AsyncHTTPTransport(uds=str(target))
- try:
- async with httpx.AsyncClient(
- transport=transport,
- base_url="http://localhost",
- timeout=httpx.Timeout(2.0, connect=1.0),
- ) as client:
- resp = await client.get("/internal/health")
- return resp.status_code == 200 and (resp.json() or {}).get("ok") is True
- except Exception:
- return False
+ return await health_identity(socket_path) is not None
def health_sync(
@@ -749,17 +883,18 @@ def health_sync(
"""
try:
- target = _verified_socket_path(socket_path)
+ endpoint = _resolve_endpoint(socket_path)
except InternalServerUnavailable:
return False
- transport = httpx.HTTPTransport(uds=str(target))
+ transport = _sync_transport(endpoint)
try:
with httpx.Client(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url, headers=endpoint.headers,
timeout=httpx.Timeout(timeout, connect=min(timeout, 1.0)),
) as client:
resp = client.get("/internal/health")
+ _validate_response(resp, endpoint)
return resp.status_code == 200 and (resp.json() or {}).get("ok") is True
except Exception:
return False
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 2eb4422c9..337c6f2f7 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -7,11 +7,16 @@ from typing import Any, Optional
import httpx
from core.handlers.model_hub import ModelHubError
+from vibe import internal_client
from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
-from vibe.internal_client import default_socket_path
-_TRANSPORT_ERRORS = (httpx.ConnectError, httpx.TimeoutException, OSError)
+_TRANSPORT_ERRORS = (
+ httpx.ConnectError,
+ httpx.TimeoutException,
+ OSError,
+ internal_client.InternalServerUnavailable,
+)
MODEL_HUB_RPC_TIMEOUT_SECONDS = 300.0
_REORDER_ORDER_UNSET = object()
@@ -39,40 +44,40 @@ def _decode(response: httpx.Response) -> Any:
def _rpc_sync(operation: str, payload: Optional[dict[str, Any]] = None) -> Any:
- target = default_socket_path().expanduser().resolve()
- if not target.exists():
- raise ModelHubError("engine_down", status=503)
- transport = httpx.HTTPTransport(uds=str(target))
try:
+ endpoint = internal_client._resolve_endpoint(None)
+ transport = internal_client._sync_transport(endpoint)
with httpx.Client(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(MODEL_HUB_RPC_TIMEOUT_SECONDS, connect=2.0),
) as client:
response = client.post(
"/internal/model-hub",
json={"operation": operation, "payload": payload or {}},
)
+ internal_client._validate_response(response, endpoint)
except _TRANSPORT_ERRORS:
raise ModelHubError("engine_down", status=503) from None
return _decode(response)
async def _rpc(operation: str, payload: Optional[dict[str, Any]] = None) -> Any:
- target = default_socket_path().expanduser().resolve()
- if not target.exists():
- raise ModelHubError("engine_down", status=503)
- transport = httpx.AsyncHTTPTransport(uds=str(target))
try:
+ endpoint = await internal_client._resolve_endpoint_async(None)
+ transport = internal_client._async_transport(endpoint)
async with httpx.AsyncClient(
transport=transport,
- base_url="http://localhost",
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
timeout=httpx.Timeout(MODEL_HUB_RPC_TIMEOUT_SECONDS, connect=2.0),
) as client:
response = await client.post(
"/internal/model-hub",
json={"operation": operation, "payload": payload or {}},
)
+ internal_client._validate_response(response, endpoint)
except _TRANSPORT_ERRORS:
raise ModelHubError("engine_down", status=503) from None
return _decode(response)
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 53bf2477d..4a01de174 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -11,7 +11,7 @@ from pathlib import Path
from typing import NamedTuple
from config import paths
-
+from core.process_isolation import isolated_subprocess_kwargs
from vibe import runtime
from vibe.upgrade import (
RestartState,
@@ -568,12 +568,10 @@ def _schedule_restart_locked(
stdin=None,
stdout=log,
stderr=subprocess.STDOUT,
- start_new_session=True,
close_fds=True,
cwd=get_safe_cwd(),
- env=runtime.independent_process_env(
- env,
- ),
+ env=runtime.independent_process_env(env),
+ **isolated_subprocess_kwargs(),
)
except OSError as exc:
# The seed status above is now "scheduled"; if the job can't be spawned
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 2d998b7c8..11fbde6dc 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -15,8 +15,9 @@ import time
import urllib.error
import urllib.request
import uuid
+from dataclasses import dataclass
from pathlib import Path
-from typing import NamedTuple
+from typing import Callable, NamedTuple
import psutil
@@ -31,6 +32,7 @@ from config.v2_config import (
SlackConfig,
V2Config,
)
+from core.process_isolation import isolated_subprocess_kwargs
from vibe.log_sink import RUNTIME_LOG_MAX_BYTES, RUNTIME_LOG_RETAIN_BYTES
@@ -51,6 +53,21 @@ SERVICE_PHASE_STARTING = "starting"
SERVICE_PHASE_RUNNING = "running"
+@dataclass
+class ProcessStartInfo:
+ pid: int | None = None
+ create_unix_ms: float | None = None
+ reused: bool = False
+
+ def capture(self, pid: int, *, reused: bool) -> int:
+ if self.pid != pid:
+ created = process_create_time(pid)
+ self.pid = pid
+ self.create_unix_ms = created * 1000 if created is not None else None
+ self.reused = reused
+ return pid
+
+
def get_package_root() -> Path:
"""Get the root directory of the vibe package."""
return Path(__file__).resolve().parent
@@ -146,6 +163,8 @@ MAIN_PATH = get_service_main_path()
_SERVICE_LOCK = threading.Lock()
_SERVICE_INSTANCE_LOCK_HANDLE = None
_SERVICE_START_PROCESSES: dict[int, subprocess.Popen] = {}
+# /ready can spend up to two seconds in the Controller health probe.
+UI_ADOPTION_PROBE_TIMEOUT_SECONDS = 3.0
def _rounded_seconds(seconds: float) -> float:
@@ -249,13 +268,48 @@ def _lock_file_pid(lock_file) -> int | None:
return pid if isinstance(pid, int) and pid > 0 else None
+# The byte this file's lock lives on, on Windows only.
+#
+# Windows byte-range locks are mandatory and scoped to a HANDLE, not a process:
+# an exclusive lock denies every other handle -- including a second handle this
+# same process opens -- both read and write access to the locked range. This
+# lock file is also the record naming its holder, so locking the bytes the
+# record occupies hid that record for exactly as long as the lock meant
+# anything, and every reader below treats an unreadable record as "nobody holds
+# this". Locking past end-of-file is legal, costs no disk and does not extend
+# the file, so a byte out here still names this file while leaving every byte
+# anyone reads unlocked. It sits far beyond any record this writes.
+#
+# POSIX keeps its whole-file advisory ``flock``: it never denied a read, so it
+# has no defect to fix and an installed base that must keep excluding today's
+# releases.
+_WINDOWS_LOCK_BYTE_OFFSET = 1 << 30
+
+
+def _windows_lock_byte(lock_file, mode: int) -> None:
+ """Take or drop the Windows lock byte, leaving the handle where it was.
+
+ ``msvcrt.locking`` locks ``nbytes`` from the descriptor's CURRENT position,
+ so the offset has to be applied to the raw descriptor -- a text handle
+ cannot seek to an arbitrary byte. Restoring position 0 afterwards keeps the
+ buffered handle coherent for the record write and read that follow.
+ """
+
+ import msvcrt
+
+ os.lseek(lock_file.fileno(), _WINDOWS_LOCK_BYTE_OFFSET, os.SEEK_SET)
+ try:
+ msvcrt.locking(lock_file.fileno(), mode, 1)
+ finally:
+ lock_file.seek(0)
+
+
def _try_lock_file(lock_file) -> bool:
if os.name == "nt":
import msvcrt
try:
- lock_file.seek(0)
- msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)
+ _windows_lock_byte(lock_file, msvcrt.LK_NBLCK)
return True
except OSError:
return False
@@ -274,8 +328,7 @@ def _unlock_file(lock_file) -> None:
import msvcrt
try:
- lock_file.seek(0)
- msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
+ _windows_lock_byte(lock_file, msvcrt.LK_UNLCK)
except OSError:
logger.debug("Failed to unlock service instance lock", exc_info=True)
return
@@ -586,6 +639,14 @@ def _terminate_process_windows(pid: int, timeout: float = 5) -> bool:
return False
+# One shell that never answers must not be able to hold a `vibe stop` open.
+# This lookup names a single process for a log line or an identity check, so a
+# bound that costs it an unanswered question is cheaper than an unbounded wait
+# on a lifecycle path. The existing `except Exception: continue` already moves
+# on to the next shell, and TimeoutExpired arrives there.
+_WINDOWS_COMMAND_LOOKUP_TIMEOUT_SECONDS = 5.0
+
+
def _get_process_command_windows(pid: int) -> str | None:
script = f'$p = Get-CimInstance Win32_Process -Filter "ProcessId = {pid}"; if ($p) {{ $p.CommandLine }}'
for shell in ("powershell", "pwsh"):
@@ -595,6 +656,7 @@ def _get_process_command_windows(pid: int) -> str | None:
capture_output=True,
text=True,
check=False,
+ timeout=_WINDOWS_COMMAND_LOOKUP_TIMEOUT_SECONDS,
)
except Exception:
continue
@@ -772,13 +834,26 @@ def _process_is_service_session_leader(pid: int) -> bool:
def _process_command_from_info(proc) -> str | None:
+ """Name a scanned process from what psutil already collected, or not at all.
+
+ This is asked for every process on the machine, so it has to be cheap. It
+ used to fall back to `get_process_command`, which on Windows launches
+ `powershell -Command Get-CimInstance ...` -- and a second `pwsh` when the
+ first says nothing -- once per process. A per-process external shell inside
+ a whole-machine walk is invisible on Linux, where that fallback is a /proc
+ read, and on Windows it is a `vibe stop` that prints nothing and never
+ returns. That is how gh-v3.1.1rc10 died.
+
+ Nothing is lost by stopping here. The scan looks for lock-less Avibe
+ daemons; those are processes this install started, whose command line
+ psutil can read. One it cannot read is by construction not ours, and the
+ authoritative owner comes from the service lock rather than from this scan.
+ """
+
info = getattr(proc, "info", {}) or {}
cmdline = info.get("cmdline")
if cmdline:
return shlex.join(str(part) for part in cmdline if str(part))
- pid = info.get("pid")
- if isinstance(pid, int):
- return get_process_command(pid)
return None
@@ -994,9 +1069,9 @@ def _spawn_runtime_log_sink(path: Path) -> subprocess.Popen:
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
- start_new_session=True,
cwd=str(get_working_dir()),
close_fds=True,
+ **isolated_subprocess_kwargs(),
)
@@ -1036,36 +1111,158 @@ def independent_process_env(
return child_env
-def spawn_background(
+#: How long a child that was killed because its spawn failed is waited for.
+#: SIGKILL and TerminateProcess are not refusable, so this only bounds a kernel
+#: that is slow to deliver them.
+SPAWN_DISCARD_REAP_TIMEOUT_SECONDS = 5.0
+
+
+def discard_spawned_child(process: subprocess.Popen) -> None:
+ """Kill and reap a child whose handover to its caller failed.
+
+ Called from inside an ``except`` that re-raises, so it must not replace the
+ failure it is cleaning up after: anything it cannot do is logged instead.
+ """
+
+ try:
+ process.kill()
+ except OSError:
+ logger.error("Failed to kill pid=%s after its spawn failed", process.pid, exc_info=True)
+ return
+ try:
+ process.wait(timeout=SPAWN_DISCARD_REAP_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ logger.error(
+ "Killed pid=%s after its spawn failed, but it had not exited after %.0fs",
+ process.pid,
+ SPAWN_DISCARD_REAP_TIMEOUT_SECONDS,
+ )
+
+
+def _spawn_owned_process(
args,
- pid_path,
stdout_name: str,
stderr_name: str,
- env: dict[str, str] | None = None,
-):
+ env: dict[str, str] | None,
+ *,
+ hand_over: Callable[[subprocess.Popen], None] | None = None,
+ withdraw: Callable[[int], None] | None = None,
+) -> subprocess.Popen:
+ """Start a process the caller owns, or leave no process at all.
+
+ A caller can only undo what it knows about. Every step between ``Popen``
+ and the moment the caller knows -- closing the parent's copies of the
+ child's handles, the pid record that lets any other process find it, the
+ caller's own note that it created the child -- used to be able to raise
+ with the child already running, and then no caller could see it:
+ `cmd_start`'s rollback looked for a UI it had created and found none, and
+ the orphan kept the listener every later start then failed to bind. So a
+ failure anywhere in that span kills and reaps the child before it
+ propagates, and every caller inherits the rule instead of each rolling back
+ a window it cannot observe.
+
+ ``hand_over`` is the caller's side of that span: it records the child and
+ captures it as created, and it runs inside the guarded region so that
+ nothing is handed back half-owned. Once it returns, the caller's own
+ rollback can find the child. If the child is discarded instead,
+ ``withdraw`` removes whatever part of that record already exists -- but
+ only once the child is known to be gone, so a child that could not be
+ reaped stays findable.
+ """
+
stdout_path = _log_path(stdout_name)
stderr_path = _log_path(stderr_name)
stdout_path.parent.mkdir(parents=True, exist_ok=True)
stdout_sink, stderr_sink = _spawn_runtime_log_sinks(stdout_path, stderr_path)
stdin = open(os.devnull, "rb")
+ # The child holds its own copies of these once it starts; the parent's must
+ # still close, or a log sink never sees end-of-file.
+ parent_handles = [stdin, stdout_sink.stdin, stderr_sink.stdin]
+ process: subprocess.Popen | None = None
try:
process = subprocess.Popen(
args,
stdin=stdin,
stdout=stdout_sink.stdin,
stderr=stderr_sink.stdin,
- start_new_session=True,
cwd=str(get_working_dir()),
close_fds=True,
env=independent_process_env(env),
+ **isolated_subprocess_kwargs(),
)
- finally:
- if stdin is not subprocess.PIPE:
- stdin.close()
- stdout_sink.stdin.close()
- stderr_sink.stdin.close()
- pid_path.write_text(str(process.pid), encoding="utf-8")
- return process.pid
+ # Closing can fail too, so it happens inside this region and before the
+ # handover: once the caller owns the child, nothing here can raise.
+ _close_parent_handles(parent_handles)
+ if hand_over is not None:
+ hand_over(process)
+ except BaseException:
+ if process is not None:
+ discard_spawned_child(process)
+ if withdraw is not None and process.returncode is not None:
+ _withdraw_quietly(withdraw, process.pid)
+ _close_parent_handles(parent_handles, quietly=True)
+ raise
+ return process
+
+
+def _withdraw_quietly(withdraw: Callable[[int], None], pid: int) -> None:
+ """Remove a discarded child's record without replacing the failure being raised."""
+
+ try:
+ withdraw(pid)
+ except Exception:
+ logger.error("Failed to remove the record of discarded pid=%s", pid, exc_info=True)
+
+
+def _close_parent_handles(handles: list, *, quietly: bool = False) -> None:
+ """Close every handle, then raise the first failure unless ``quietly``.
+
+ Closing an already closed file is a no-op, so the failure path may call this
+ again after a close that raised part way through the list.
+ """
+
+ first_failure: Exception | None = None
+ for handle in handles:
+ try:
+ handle.close()
+ except Exception as exc:
+ if quietly:
+ logger.debug("Failed to close a spawn handle after the spawn failed", exc_info=True)
+ elif first_failure is None:
+ first_failure = exc
+ if first_failure is not None:
+ raise first_failure
+
+
+def spawn_background(
+ args,
+ pid_path,
+ stdout_name: str,
+ stderr_name: str,
+ env: dict[str, str] | None = None,
+ *,
+ start_info: ProcessStartInfo | None = None,
+):
+ """Start a process recorded in ``pid_path``; the record exists iff the child does.
+
+ With ``start_info`` the child is also captured as created before this
+ returns, inside the same guarded region: a caller that rolls back what
+ ``start_info`` names cannot miss a child this started.
+ """
+
+ def hand_over(process: subprocess.Popen) -> None:
+ pid_path.write_text(str(process.pid), encoding="utf-8")
+ if start_info is not None:
+ start_info.capture(process.pid, reused=False)
+
+ return _spawn_owned_process(
+ args,
+ stdout_name,
+ stderr_name,
+ env,
+ hand_over=hand_over,
+ withdraw=lambda pid: _forget_pid_record(pid_path, pid),
+ ).pid
def spawn_service_background_process(
@@ -1073,29 +1270,18 @@ def spawn_service_background_process(
stdout_name: str,
stderr_name: str,
env: dict[str, str] | None = None,
+ *,
+ hand_over: Callable[[subprocess.Popen], None] | None = None,
+ withdraw: Callable[[int], None] | None = None,
) -> subprocess.Popen:
- stdout_path = _log_path(stdout_name)
- stderr_path = _log_path(stderr_name)
- stdout_path.parent.mkdir(parents=True, exist_ok=True)
- stdout_sink, stderr_sink = _spawn_runtime_log_sinks(stdout_path, stderr_path)
- stdin = open(os.devnull, "rb")
- try:
- process = subprocess.Popen(
- args,
- stdin=stdin,
- stdout=stdout_sink.stdin,
- stderr=stderr_sink.stdin,
- start_new_session=True,
- cwd=str(get_working_dir()),
- close_fds=True,
- env=independent_process_env(env),
- )
- finally:
- if stdin is not subprocess.PIPE:
- stdin.close()
- stdout_sink.stdin.close()
- stderr_sink.stdin.close()
- return process
+ return _spawn_owned_process(
+ args,
+ stdout_name,
+ stderr_name,
+ env,
+ hand_over=hand_over,
+ withdraw=withdraw,
+ )
def spawn_service_background(args, stdout_name: str, stderr_name: str, env: dict[str, str] | None = None) -> int:
@@ -1129,12 +1315,13 @@ def _reap_service_start_process(pid: int) -> None:
def _clear_service_pid_reservation(pid: int) -> None:
_reap_service_start_process(pid)
- pid_path = paths.get_runtime_pid_path()
- try:
- recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())
- except (OSError, ValueError):
- return
- if recorded_pid == pid:
+ _forget_pid_record(paths.get_runtime_pid_path(), pid)
+
+
+def _forget_pid_record(pid_path: Path, pid: int) -> None:
+ """Remove ``pid_path`` only while it still names ``pid``."""
+
+ if _read_pid_file(pid_path) == pid:
pid_path.unlink(missing_ok=True)
@@ -1775,6 +1962,7 @@ def start_service(
*,
wait_for_ready: bool = True,
initial_ready_timeout: float = SERVICE_LOCK_READY_TIMEOUT_SECONDS,
+ start_info: ProcessStartInfo | None = None,
launcher: ServiceLauncher | None = None,
) -> int:
"""Start the service and return the pid, by default only once it is up.
@@ -1812,12 +2000,15 @@ def start_service(
wait_for_ready=wait_for_ready,
initial_ready_timeout=initial_ready_timeout,
launcher=launcher,
+ start_info=start_info,
)
if not wait_for_ready:
return pid
ready_pid = wait_for_service_ready(pid, timeout=max(0.0, deadline - time.monotonic()))
if ready_pid is None:
_raise_service_started_but_never_ran(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)
+ if start_info is not None:
+ start_info.capture(ready_pid, reused=start_info.reused)
return ready_pid
@@ -1826,6 +2017,7 @@ def _resolve_service_pid(
wait_for_ready: bool,
initial_ready_timeout: float,
launcher: ServiceLauncher | None,
+ start_info: ProcessStartInfo | None,
) -> int:
"""Which process is the service, starting one if nothing holds the lock.
@@ -1835,6 +2027,10 @@ def _resolve_service_pid(
"""
from storage.migrations import guard_source_checkout_default_state_bootstrap
+
+ def result(pid: int, *, reused: bool) -> int:
+ return start_info.capture(pid, reused=reused) if start_info is not None else pid
+
guard_source_checkout_default_state_bootstrap()
with _SERVICE_LOCK:
pid_path = paths.get_runtime_pid_path()
@@ -1847,14 +2043,14 @@ def _resolve_service_pid(
if existing_pid and pid_alive(existing_pid):
if not _pid_mismatches_service(existing_pid):
if service_pid_recorded(existing_pid):
- return existing_pid
+ return result(existing_pid, reused=True)
if _pid_reservation_is_fresh(pid_path, existing_pid):
# A reservation this recent names the service whether or
# not it is up yet, so the question is answered. Waiting
# for the running phase used to happen here, and only
# here, which is precisely why every other return below
# answered a question it had not asked.
- return existing_pid
+ return result(existing_pid, reused=True)
logger.warning(
"Ignoring stale service pid file pid=%s because it never acquired the service lock",
existing_pid,
@@ -1868,7 +2064,7 @@ def _resolve_service_pid(
"match this CLI install",
existing_pid,
)
- return lock_holder_pid
+ return result(lock_holder_pid, reused=True)
raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
logger.warning(
@@ -1880,7 +2076,7 @@ def _resolve_service_pid(
lock_available, lock_holder_pid = service_instance_lock_available()
if not lock_available:
if lock_holder_pid and lock_holder_pid == existing_pid and pid_alive(lock_holder_pid):
- return lock_holder_pid
+ return result(lock_holder_pid, reused=True)
raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
extra_pids = extra_service_process_pids()
@@ -1891,7 +2087,18 @@ def _resolve_service_pid(
scope_prefix = maybe_systemd_scope_prefix()
if scope_prefix:
logger.info("cgroup scope bootstrap: launching service inside a delegated user scope")
- spawn_kwargs = {}
+ # The reservation is how anything outside this frame finds a service that
+ # has not taken the lock yet -- `stop_service()` included, and so every
+ # rollback -- and `start_info` is how the caller knows it created one.
+ # Both are written inside the spawn primitive's guarded region, so a
+ # failure or a signal before the last of them kills the child instead of
+ # leaving one that nothing can stop. Only a findable child is recorded as
+ # created: whoever reads `start_info` may rely on the reservation too.
+ def hand_over(process: subprocess.Popen) -> None:
+ _SERVICE_START_PROCESSES[process.pid] = process
+ _record_service_pid_reservation(process.pid)
+ result(process.pid, reused=False)
+
process = spawn_service_background_process(
[*scope_prefix, launcher.python, launcher.main],
"service_stdout.log",
@@ -1901,19 +2108,19 @@ def _resolve_service_pid(
"VIBE_DISABLE_STDOUT_LOGGING": "1",
SHUTDOWN_INTENT_ENV: "1",
},
- **spawn_kwargs,
+ hand_over=hand_over,
+ withdraw=_clear_service_pid_reservation,
)
pid = process.pid
- _SERVICE_START_PROCESSES[pid] = process
- _record_service_pid_reservation(pid)
if scope_prefix:
# Scoped launches resolve their pid via the authoritative lock holder
# (poll-and-adopt), never by trusting the spawn pid alone.
- return _start_scoped_service_result(
+ resolved_pid = _start_scoped_service_result(
pid,
initial_ready_timeout=initial_ready_timeout,
wait_for_ready=wait_for_ready,
)
+ return result(resolved_pid, reused=False)
if initial_ready_timeout > 0 and wait_for_service_pid(pid, timeout=initial_ready_timeout):
return pid
exit_code = _service_start_exit_code(pid)
@@ -1941,7 +2148,9 @@ def _resolve_service_pid(
def _ui_health_url(host: str, port: int) -> str:
- health_host = (host or "127.0.0.1").strip()
+ from vibe.desktop_runtime import _normalized_bind_host
+
+ health_host = _normalized_bind_host(host)
if health_host in {"0.0.0.0", ""}:
health_host = "127.0.0.1"
elif health_host in {"::", "::0"}:
@@ -1953,12 +2162,95 @@ def _ui_health_url(host: str, port: int) -> str:
return f"http://{health_host}:{port}/health"
-def ui_server_healthy(host: str, port: int, timeout: float = 0.5) -> bool:
+def _ui_health_urls(host: str, port: int) -> tuple[str, ...]:
+ from vibe.desktop_runtime import desktop_origin
+
+ primary_url = _ui_health_url(host, port)
+ desktop_url = f"{desktop_origin(host, port)}/ready"
+ urls = [primary_url]
+ if desktop_url not in urls:
+ urls.append(desktop_url)
+ return tuple(urls)
+
+
+def _ui_ready_identity_state(response) -> bool | None:
try:
- with urllib.request.urlopen(_ui_health_url(host, port), timeout=timeout) as response:
- return response.status == 200
- except (OSError, urllib.error.URLError, TimeoutError, ValueError):
- return False
+ payload = json.loads(response.read().decode("utf-8"))
+ except (AttributeError, OSError, UnicodeDecodeError, json.JSONDecodeError):
+ return None
+
+ if not isinstance(payload, dict):
+ return None
+ if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
+ return None
+ if payload.get("product") != "avibe" or type(payload.get("ready")) is not bool:
+ return None
+
+ controller_runtime_id = payload.get("desktop_runtime_id")
+ ui_runtime_id = payload.get("desktop_ui_runtime_id")
+ expected_ready = {"schema_version", "product", "ready"}
+ if controller_runtime_id is not None and ui_runtime_id is not None:
+ return None
+ for field, runtime_id in (
+ ("desktop_runtime_id", controller_runtime_id),
+ ("desktop_ui_runtime_id", ui_runtime_id),
+ ):
+ if runtime_id is None:
+ continue
+ if (
+ not isinstance(runtime_id, str)
+ or len(runtime_id) != 64
+ or any(character not in "0123456789abcdef" for character in runtime_id)
+ ):
+ return None
+ expected_ready.add(field)
+ if response.status == 200 and set(payload) == expected_ready and payload["ready"] is True:
+ return True
+
+ code = payload.get("code")
+ if (
+ response.status == 503
+ and isinstance(code, str)
+ and bool(code)
+ and payload
+ == {
+ "schema_version": 1,
+ "product": "avibe",
+ "ready": False,
+ "code": code,
+ }
+ ):
+ return None if code == "runtime_identity_invalid" else False
+ return None
+
+
+def _ui_server_readiness(host: str, port: int, timeout: float = 0.5) -> bool | None:
+ for health_url in _ui_health_urls(host, port):
+ try:
+ with urllib.request.urlopen(health_url, timeout=timeout) as response:
+ if health_url.endswith("/ready"):
+ return _ui_ready_identity_state(response)
+ if response.status != 200:
+ return None
+ except urllib.error.HTTPError as exc:
+ if health_url.endswith("/ready"):
+ return _ui_ready_identity_state(exc)
+ return None
+ except (OSError, urllib.error.URLError, TimeoutError, ValueError):
+ return None
+ return None
+
+
+def ui_server_healthy(host: str, port: int, timeout: float = 0.5) -> bool:
+ return _ui_server_readiness(host, port, timeout=timeout) is True
+
+
+def _ui_server_compatible(
+ host: str,
+ port: int,
+ timeout: float = UI_ADOPTION_PROBE_TIMEOUT_SECONDS,
+) -> bool:
+ return _ui_server_readiness(host, port, timeout=timeout) is not None
def wait_for_ui_server(host: str, port: int, timeout: float = 5.0) -> bool:
@@ -2054,8 +2346,12 @@ def start_ui(
port,
*,
wait_for_ready: bool = True,
+ start_info: ProcessStartInfo | None = None,
launcher: ServiceLauncher | None = None,
):
+ from vibe.desktop_runtime import normalize_desktop_port
+
+ port = normalize_desktop_port(port)
pid_path = paths.get_runtime_ui_pid_path()
if pid_path.exists():
try:
@@ -2063,15 +2359,27 @@ def start_ui(
except Exception:
existing_pid = 0
if existing_pid and pid_alive(existing_pid):
- if _pid_matches_ui_server(existing_pid) and ui_server_healthy(host, port):
+ if _pid_matches_ui_server(existing_pid) and _ui_server_compatible(host, port):
+ if start_info is not None:
+ start_info.capture(existing_pid, reused=True)
return existing_pid
if _pid_matches_ui_server(existing_pid):
logger.warning(
- "Stopping stale UI process pid=%s because health check failed for %s",
+ "Stopping stale UI process pid=%s because required listener or identity checks failed for %s",
existing_pid,
- _ui_health_url(host, port),
+ ", ".join(_ui_health_urls(host, port)),
)
- stop_pid(existing_pid)
+ if not stop_pid(existing_pid):
+ # The stale process still owns the configured listener, so a
+ # replacement would only die on bind while that process kept
+ # serving. Preserve the pid record naming the process that has
+ # to be stopped: unlinking it here would leave the incompatible
+ # UI running with nothing pointing at it.
+ logger.error(
+ "Failed to stop stale UI process pid=%s; preserving pid state and not starting a replacement",
+ existing_pid,
+ )
+ return None
else:
logger.warning(
"Ignoring stale UI pid file pid=%s because it does not match the Vibe UI server",
@@ -2085,6 +2393,11 @@ def start_ui(
# idea of startup inside the replaced install.
command = "from vibe.ui_server import run_ui_server; run_ui_server('{}', {})".format(host, port)
spawn_kwargs = {}
+ # `start_info` is captured inside the spawn, not after it returns: in between,
+ # a signal left a live UI with a pid record that `cmd_start`'s rollback,
+ # which undoes only what `start_info` names as created, never looked at.
+ if start_info is not None:
+ spawn_kwargs["start_info"] = start_info
pid = spawn_background(
[(launcher or current_service_launcher()).python, "-c", command],
pid_path,
@@ -2093,7 +2406,11 @@ def start_ui(
**spawn_kwargs,
)
if wait_for_ready and not wait_for_ui_server(host, port):
- logger.warning("Started UI pid=%s but health check did not pass for %s", pid, _ui_health_url(host, port))
+ logger.warning(
+ "Started UI pid=%s but required health checks did not pass for %s",
+ pid,
+ ", ".join(_ui_health_urls(host, port)),
+ )
return pid
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 5b47f757b..ac05350e6 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1621,8 +1621,11 @@ def _changed_agent_backend_runtimes(
from config.v2_compat import to_app_config
from modules.agents.catalog import AGENT_BACKENDS
- previous_runtime = to_app_config(previous)
- current_runtime = to_app_config(current)
+ # Historical snapshots must stay pure. Resolving both selectors against
+ # today's filesystem can make a newly saved absolute path compare equal to
+ # the old bare command and suppress the live backend refresh it requires.
+ previous_runtime = to_app_config(previous, resolve_agent_paths=False)
+ current_runtime = to_app_config(current, resolve_agent_paths=False)
return [
backend
for backend in AGENT_BACKENDS
@@ -3257,6 +3260,77 @@ def status():
return jsonify(payload)
+async def ready():
+ """Report whether the UI and its authoritative Controller are ready."""
+
+ from vibe import internal_client, runtime
+ from vibe.desktop_runtime import DESKTOP_RUNTIME_ID_ENV, desktop_runtime_id
+
+ identity = {"schema_version": 1, "product": "avibe"}
+
+ def response(payload: dict[str, Any], status_code: int = 200):
+ result = jsonify(payload)
+ result.headers["Cache-Control"] = "no-store"
+ return result if status_code == 200 else (result, status_code)
+
+ def unavailable(code: str):
+ return response({**identity, "ready": False, "code": code}, 503)
+
+ owner_probe_failed = object()
+
+ async def resolve_owner(*, include_starting: bool):
+ try:
+ return await asyncio.to_thread(
+ runtime.resolve_service_owner_pid,
+ include_starting=include_starting,
+ )
+ except Exception:
+ logger.exception("Failed to resolve service ownership for readiness")
+ return owner_probe_failed
+
+ owner_before = await resolve_owner(include_starting=False)
+ if owner_before is owner_probe_failed:
+ return unavailable("owner_probe_failed")
+ if owner_before is None:
+ starting_owner = await resolve_owner(include_starting=True)
+ if starting_owner is owner_probe_failed:
+ return unavailable("owner_probe_failed")
+ code = "service_starting" if starting_owner is not None else "service_unavailable"
+ return unavailable(code)
+
+ controller_identity = await internal_client.health_identity()
+ owner_after = await resolve_owner(include_starting=False)
+ if owner_after is owner_probe_failed:
+ return unavailable("owner_probe_failed")
+ if owner_after != owner_before:
+ return unavailable("ownership_lost")
+ if controller_identity is None:
+ return unavailable("controller_unavailable")
+ controller_runtime_id = controller_identity.get("desktop_runtime_id")
+ ui_runtime_id = desktop_runtime_id()
+ if os.environ.get(DESKTOP_RUNTIME_ID_ENV) and ui_runtime_id is None:
+ return unavailable("runtime_identity_invalid")
+ # A healthy Controller without a desktop identity is user-managed. The UI
+ # may still inherit a bundled identity when `vibe start` reuses that
+ # Controller, so the absence of a Controller identity is affirmative
+ # external readiness rather than an identity mismatch. A tagged
+ # Controller/UI pair must still agree exactly.
+ if controller_runtime_id is not None and controller_runtime_id != ui_runtime_id:
+ mismatch = {**identity, "ready": False, "code": "runtime_identity_mismatch"}
+ mismatch["desktop_runtime_id"] = controller_runtime_id
+ return response(mismatch, 503)
+ payload = {**identity, "ready": True}
+ if controller_runtime_id is not None:
+ payload["desktop_runtime_id"] = controller_runtime_id
+ elif ui_runtime_id is not None:
+ # The Controller is external, but this UI may still be served from the
+ # bundled Runtime tree. Keep that fact separate from Controller
+ # identity: it never authorizes handover or stopping the Controller.
+ payload["desktop_ui_runtime_id"] = ui_runtime_id
+ return response(payload)
+
+
@app.websocket("/ws/echo")
async def websocket_echo(websocket: WebSocket):
if os.environ.get("VIBE_UI_ENABLE_WS_ECHO", "").lower() not in {"1", "true", "yes", "on"}:
@@ -16686,6 +16760,20 @@ def _bind_ui_socket(host: str, port: int) -> socket.socket:
return sock
+def _bind_ui_sockets(host: str, port: int) -> list[socket.socket]:
+ from vibe.desktop_runtime import ui_listener_hosts
+
+ sockets: list[socket.socket] = []
+ try:
+ for listener_host in ui_listener_hosts(host):
+ sockets.append(_bind_ui_socket(listener_host, port))
+ except OSError:
+ for sock in sockets:
+ sock.close()
+ raise
+ return sockets
+
+
def run_ui_server(host: str, port: int) -> None:
"""Start the FastAPI UI server."""
@@ -16715,7 +16803,7 @@ def run_ui_server(host: str, port: int) -> None:
# Retry binding in case of TIME_WAIT or port still held by old server during reload
for attempt in range(10):
- bound_socket: socket.socket | None = None
+ bound_sockets: list[socket.socket] = []
try:
uvicorn_config = uvicorn.Config(
app,
@@ -16728,7 +16816,7 @@ def run_ui_server(host: str, port: int) -> None:
workers=1,
timeout_keep_alive=_UI_KEEPALIVE_TIMEOUT_SECONDS,
)
- bound_socket = _bind_ui_socket(host, port)
+ bound_sockets = _bind_ui_sockets(host, port)
_server = uvicorn.Server(uvicorn_config)
# Reconcile remote_access in the background so cloudflared download/
# connector start does not block /health and the rest of the UI
@@ -16741,12 +16829,12 @@ def run_ui_server(host: str, port: int) -> None:
).start()
_UI_RUNTIME_ACTIVE = True
try:
- _server.run(sockets=[bound_socket])
+ _server.run(sockets=bound_sockets)
finally:
_UI_RUNTIME_ACTIVE = False
break
except OSError as e:
- if bound_socket is not None:
+ for bound_socket in bound_sockets:
bound_socket.close()
if e.errno == 48 and attempt < 9: # Address already in use (macOS)
print(f"Port {port} in use, retrying in 1s... (attempt {attempt + 1})")
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index c6caaad30..105e6c829 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -45,6 +45,7 @@ PIP_DOWNLOAD_DEST_PLACEHOLDER = "{avibe-pip-download-destination}"
DEFAULT_UPDATE_METADATA_URL = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"
SHOW_RUNTIME_SKIP_ENV = "VIBE_INSTALL_SKIP_SHOW_RUNTIME"
+DESKTOP_MANAGED_RUNTIME_ENV = "AVIBE_DESKTOP_MANAGED_RUNTIME"
TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
UV_FALLBACK_BIN_DIRS = (".local/bin", ".cargo/bin")
UPGRADE_INSTALL_TIMEOUT_SECONDS = 30 * 60
@@ -635,6 +636,12 @@ def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.
_update_launcher_generation_marker(launcher_path, target_path, atomic_uv_install_root().expanduser().resolve())
+def is_desktop_managed_runtime(base_env: Mapping[str, str] | None = None) -> bool:
+ env = os.environ if base_env is None else base_env
+ value = env.get(DESKTOP_MANAGED_RUNTIME_ENV, "")
+ return value.strip().lower() in TRUTHY_ENV_VALUES
+
+
def resolve_command_path(command: str | None, search_path: str | None = None) -> str | None:
if not command:
return None