The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernet66d54ebf51f5
diff --cc .github/workflows/docker.ymlindex 2ed6b2ccc01,df6c3fb501d..750c8fc4b73--- a/.github/workflows/docker.yml+++ b/.github/workflows/docker.yml@@@ -118,24 -65,21 +118,30 @@@ jobsecho "build=false" >> "$GITHUB_OUTPUT"fi- # Build and test the image for each architecture. This job runs PR code,- # so it must remain secret-free. Publishing happens in the separate,- # protected publish job after these tests pass.+ # Build and test the image for each architecture. This job runs PR code, so+ # in standalone mode it must remain secret-free. Publishing happens in the+ # separate, protected publish paths after these tests pass.+ #+ # Runs ONLY in standalone mode and in the release 'test' phase: it builds+ # the SAME Dockerfile and runs the SAME real docker-integration tests, then+ # (test phase) saves the tested per-arch image archive + sha256 as run+ # artifacts. No registry push, no signing secrets. The publish phase never+ # rebuilds — it downloads these exact artifacts.build:- name: Build and test image (${{ matrix.arch }})- needs: [detect]- if: github.repository == 'NousResearch/hermes-agent' && needs.detect.outputs.build == 'true'++ name: Build and test image (${{ matrix.variant }}/${{ matrix.arch }})+ needs: [mode, detect]+ if: >-+ !cancelled() && needs.mode.result == 'success' &&+ ((needs.mode.outputs.release != 'true' && github.repository == 'NousResearch/hermes-agent' && needs.detect.outputs.build == 'true') || needs.mode.outputs.phase == 'test')strategy:fail-fast: falsematrix:+ # Two images per arch. `slim` is what :latest has always been; `desktop`- # adds the Bot Screen packages and a headed Chromium (+1.4 GB) for the- # tier that offers a screen. Both are built on a PR so a change that only- # breaks the gated layers cannot reach publish.++ # adds the Bot Screen packages and distro Chromium fallback for the++ # tier that offers a screen. PM's pinned full Chromium is in both.++ # Both are built on a PR so gated-layer failures cannot reach publish.+ arch: [amd64, arm64]+ variant: [slim, desktop]include:- arch: amd64runner: ubuntu-latest-32-core@@@ -200,7 -116,7 +202,7 @@@# Build once, load into the local daemon for testing. Cached# per-arch; the push step below reuses every layer from this build.-- - name: Build image (${{ matrix.arch }})++ - name: Build image (${{ matrix.variant }}/${{ matrix.arch }})uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0with:context: .@@@ -208,42 -124,50 +210,32 @@@load: trueplatforms: ${{ matrix.platform }}tags: ${{ env.IMAGE_NAME }}:test- cache-from: ${{ matrix.cache-from }}- cache-to: ${{ (github.event_name != 'pull_request') && matrix.cache-to || '' }}--- # Run the docker-integration test suite against the freshly-built- # image already loaded into the local daemon (`:test`).- #- # Piggybacking here avoids a second image build: the build step- # already loaded the image into the daemon under- # `${IMAGE_NAME}:test`, so we just point ``HERMES_TEST_IMAGE`` at- # that. The fixture's ``HERMES_TEST_IMAGE`` branch (see- # tests/docker/conftest.py:62-63) short-circuits the rebuild.- #- # Why this job and not a standalone one: the image is 5GB+; passing- # it between jobs via ``docker save``/``upload-artifact`` is slower- # than the build itself. Reusing the existing daemon state is the- # cheapest path to coverage on every PR that touches docker code.- # (The release path DOES pay that cost — see the save steps below —- # because publish must push the exact tested bytes, not a rebuild.)- # ---------------------------------------------------------------------- # The stamp above marks the checkout as a docker distribution, and PM- # then expects the image's packaged runtime. The runner is not the- # image: park the stamp while the test toolchain is provisioned, then- # put it back — tests/docker compares the image's provenance against it.+ build-args: |- HERMES_GIT_SHA=${{ github.sha }}+ HERMES_BOT_DESKTOP=${{ matrix.variant == 'desktop' && '1' || '0' }}- # Slim owns the scope; desktop is slim plus two RUN steps, so it reads- # and writes nothing — a 5.5 GB mode=max scope would blow the 10 GB cap.++ # Slim owns the scope; desktop adds the gated apt layer, so it reads++ # and writes nothing — a mode=max scope could exceed the cache cap.+ cache-from: type=gha,scope=docker-${{ matrix.arch }}+ cache-to: ${{ (github.event_name != 'pull_request' && matrix.variant == 'slim') && format('type=gha,mode=max,scope=docker-{0}', matrix.arch) || '' }}++- # Run the docker-integration test suite against the freshly-built- # image already loaded into the local daemon (`:test`).- #- # Piggybacking here avoids a second image build: the build step- # already loaded the image into the daemon under- # `${IMAGE_NAME}:test`, so we just point ``HERMES_TEST_IMAGE`` at- # that. The fixture's ``HERMES_TEST_IMAGE`` branch (see- # tests/docker/conftest.py:62-63) short-circuits the rebuild.- #- # Why this job and not a standalone one: the image is 5GB+; passing- # it between jobs via ``docker save``/``upload-artifact`` is slower- # than the build itself. Reusing the existing daemon state is the- # cheapest path to coverage on every PR that touches docker code.- # ---------------------------------------------------------------------- - name: Install uv (for docker tests)- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0- with:- # Pinned: unpinned setup-uv fetches a 'latest' manifest from- # raw.githubusercontent.com every job; transient fetch failures- # fail the job (2026-07-28 incident). Keep in sync with tests.yml.- version: "0.9.28"++ # Run the docker-integration test suite against the freshly-built image++ # already loaded into the local daemon (`:test`). The fixture's++ # HERMES_TEST_IMAGE branch short-circuits the rebuild. Release tests++ # archive these exact bytes rather than rebuilding at publish time.++ # Park the stamp while PM provisions the runner, then restore it so++ # tests/docker can compare the image's provenance with the checkout.+ - name: Park the image install stamp while provisioning the runner toolchain+ run: mv install-stamp.json "$RUNNER_TEMP/install-stamp.json"- - name: Set up Python 3.11 (for docker tests)- uses: ./.github/actions/retry+ - name: Set up locked Python and test dependencies+ uses: ./.github/actions/setup-pmwith:- command: uv python install 3.11-- - name: Install Python dependencies (for docker tests)- # ``dev`` extra pulls in pytest, pytest-asyncio —- # everything tests/docker/ needs. We deliberately avoid ``all``- # here because the docker tests only drive the container via- # subprocess and don't import hermes_agent's optional deps.- uses: ./.github/actions/retry- with:- command: uv sync --locked --python 3.11 --extra dev+ extras: '[]'+ test-environment: 'true'+ prune-python-cache: true++ - name: Restore the image install stamp for the docker tests+ run: mv "$RUNNER_TEMP/install-stamp.json" install-stamp.json- name: Run docker integration testsenv:@@@ -256,76 -180,18 +248,77 @@@NOUS_API_KEY: ""run: |# Each of these tests drives a container, so the docker daemon sets- # the limit and not the processor. This caps the workers. The- # default from run_tests.sh is cpu_count*2, which starts 64- # containers together on the 32-core amd64 runner.- HERMES_TEST_WORKERS=$(nproc) scripts/run_tests.sh tests/docker/ --file-timeout 600+ # the limit and not the processor. This pins the runner's worker+ # count to the core count.+ HERMES_TEST_WORKERS=$(nproc) scripts/run_tests.sh tests/docker/++ - name: Verify release image identity+ if: needs.mode.outputs.phase == 'test'+ env:+ RELEASE_VERSION: ${{ inputs.version }}+ run: |+ actual="$(docker run --rm --entrypoint python "${IMAGE_NAME}:test" -c \+ 'import json; print(json.load(open("/opt/hermes/install-stamp.json"))["baseVersion"])')"+ test "$actual" = "$RELEASE_VERSION"++ # ---------------------------------------------------------------------+ # Release 'test' phase only: hand the EXACT tested bytes to the publish+ # phase via actions artifacts. No registry push, no credentials here.+ # ---------------------------------------------------------------------+ - name: Save tested image archive (release test)+ if: needs.mode.outputs.phase == 'test'+ env:+ ARCH: ${{ matrix.arch }}+ RELEASE_TAG: ${{ inputs.tag }}++ VARIANT: ${{ matrix.variant }}+ run: |+ set -euo pipefail+ mkdir -p /tmp/image-artifacts+ docker image inspect "${IMAGE_NAME}:test" > /tmp/image-artifacts/image-inspect.json+ python3 - <<'PY'+ import json, os+ from pathlib import Path+ image = json.loads(Path('/tmp/image-artifacts/image-inspect.json').read_text())[0]+ if image['Architecture'] != os.environ['ARCH']:+ raise SystemExit('Docker image architecture mismatch')+ Path('/tmp/image-artifacts/identity.json').write_text(json.dumps({+ 'tag': os.environ['RELEASE_TAG'], 'commit': os.environ['GITHUB_SHA'],- 'arch': os.environ['ARCH'], 'imageId': image['Id']}), encoding='utf-8')++ 'arch': os.environ['ARCH'], 'variant': os.environ['VARIANT'], 'imageId': image['Id']}), encoding='utf-8')+ PY+ docker save --output "/tmp/image-artifacts/image-${ARCH}.tar" "${IMAGE_NAME}:test"+ (+ cd /tmp/image-artifacts+ sha256sum "image-${ARCH}.tar" > "image-${ARCH}.tar.sha256"+ )++ - name: Upload tested image archive (release test)+ if: needs.mode.outputs.phase == 'test'+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:- name: docker-test-image-${{ matrix.arch }}-${{ inputs.tag }}++ name: docker-test-image-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}+ path: |+ /tmp/image-artifacts/image-${{ matrix.arch }}.tar+ /tmp/image-artifacts/image-${{ matrix.arch }}.tar.sha256+ /tmp/image-artifacts/identity.json+ if-no-files-found: error+ retention-days: 7+ compression-level: 0# ---------------------------------------------------------------------------- # Rebuild and push each architecture only after the unprivileged build/test- # matrix passes. This job is the sole Docker Hub credential boundary.+ # Standalone publish: rebuild and push each architecture only after the+ # unprivileged build/test matrix passes, on trusted main pushes.+ # This job is the sole Docker Hub credential boundary for merges.+ #+ # NOTE: main pushes tag :main ONLY. :latest is a user-facing stable alias+ # now; the ordered publication controller moves it only after the global+ # release gate, so a main push can never advance the stable channel.# ---------------------------------------------------------------------------publish:- if: github.repository == 'NousResearch/hermes-agent' && (github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'release')- needs: [build]+ if: >-+ needs.mode.outputs.release != 'true' &&+ github.repository == 'NousResearch/hermes-agent' &&+ github.event_name == 'push' && github.ref == 'refs/heads/main'+ needs: [mode, build]environment: container-publishstrategy:fail-fast: false@@@ -384,18 -234,21 +375,20 @@@# Push by digest only (no tag). The merge job assembles the tagged# manifest list after both architecture publishers complete.-- - name: Push ${{ matrix.arch }} by digest++ - name: Push ${{ matrix.variant }}/${{ matrix.arch }} by digestid: pushuses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0with:context: .file: Dockerfileplatforms: ${{ matrix.platform }}- labels: |- org.opencontainers.image.revision=${{ github.sha }}+ build-args: |- HERMES_GIT_SHA=${{ github.sha }}+ HERMES_BOT_DESKTOP=${{ matrix.variant == 'desktop' && '1' || '0' }}+ labels: |+ org.opencontainers.image.revision=${{ github.sha }}outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true- cache-from: ${{ matrix.cache-from }}- cache-to: ${{ matrix.cache-to }}+ cache-from: type=gha,scope=docker-${{ matrix.arch }}+ cache-to: ${{ matrix.variant == 'slim' && format('type=gha,mode=max,scope=docker-{0}', matrix.arch) || '' }}- name: Export digestrun: |@@@ -416,18 -269,28 +409,27 @@@# This is a registry-side operation — no building, no layer re-push —# so it runs in ~30 seconds.#- # On main pushes: tags both :main and :latest.- # On releases: tags :<release_tag_name>.+ # Main pushes tag :main only. :latest is reserved for the ordered stable+ # publication controller.# ---------------------------------------------------------------------------merge:- if: >-- needs.mode.outputs.release != 'true' &&- github.repository == 'NousResearch/hermes-agent' &&- github.event_name == 'push' && github.ref == 'refs/heads/main'- # `needs` is the whole 4-leg matrix and a failed need skips the job, so a- # transient desktop push would take slim's :latest with it. Guard below.- if: ${{ !cancelled() && github.repository == 'NousResearch/hermes-agent' && (github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'release') }}++ # `needs` is the whole 4-leg matrix: only publish both :main variants++ # after every arch and variant publisher succeeds.++ if: ${{ !cancelled() && needs.mode.outputs.release != 'true' && github.repository == 'NousResearch/hermes-agent' && github.event_name == 'push' && github.ref == 'refs/heads/main' }}runs-on: ubuntu-latest- needs: [publish]+ needs: [mode, publish]timeout-minutes: 10environment: container-publish+ strategy:+ fail-fast: false+ matrix:+ # One manifest list per variant. `slim` keeps the unsuffixed tags it has- # always had, so nothing that pulls :latest today changes; `desktop`- # publishes the same digests under a -desktop suffix.++ # always had; `desktop` publishes its own digests under -desktop.+ include:+ - variant: slim+ suffix: ""+ - variant: desktop+ suffix: "-desktop"steps:- name: Download digestsuses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4@@@ -457,13 -320,27 +459,17 @@@working-directory: /tmp/digestsenv:IMAGE_NAME: ${{ env.IMAGE_NAME }}- RELEASE_TAG: ${{ github.event.release.tag_name }}+ SUFFIX: ${{ matrix.suffix }}run: |set -euo pipefail+ # Without nullglob an empty dir yields the literal `*`: one bogus entry.+ shopt -s nullglobargs=()for digest_file in *; doargs+=("${IMAGE_NAME}@sha256:${digest_file}")done- tags=(-t "${IMAGE_NAME}:main")- # One per arch in the publish matrix; a short set means a leg failed, and- # stitching it would publish a single-arch :latest. Keep in step with it.- if [ "${#args[@]}" -ne 2 ]; then- echo "::error::variant ${{ matrix.variant }}: want 2 digests, found ${#args[@]} (a publish leg failed)"- exit 1- fi- if [ "${{ github.event_name }}" = "release" ]; then- tags=(-t "${IMAGE_NAME}:${RELEASE_TAG}${SUFFIX}")- else- tags=(-t "${IMAGE_NAME}:main${SUFFIX}" -t "${IMAGE_NAME}:latest${SUFFIX}")- fi++ if [ "${#args[@]}" -ne 2 ]; then echo "::error::Expected two ${SUFFIX} digests"; exit 1; fi++ tags=(-t "${IMAGE_NAME}:main${SUFFIX}")# Retry: Docker Hub API + just-pushed digest eventual consistency# can transiently fail the create; the operation is idempotent.for i in 1 2 3; do@@@ -481,276 -358,11 +487,276 @@@- name: Inspect imageenv:IMAGE_NAME: ${{ env.IMAGE_NAME }}- run: docker buildx imagetools inspect "${IMAGE_NAME}:main"- RELEASE_TAG: ${{ github.event.release.tag_name }}+ SUFFIX: ${{ matrix.suffix }}++ run: docker buildx imagetools inspect "${IMAGE_NAME}:main${SUFFIX}"++ # ===========================================================================+ # Staged stable-release path (workflow_call from stable-release.yml).+ # The caller is dispatched on the exact stable TAG, so github.sha in every+ # reusable call is the release candidate commit.+ # ===========================================================================++ # Release 'publish' phase: load the EXACT tested image archives uploaded by+ # the 'test' phase of this SAME workflow run, verify their hashes, push+ # per-arch and NEVER rebuild. No owner gate: on a fork the Docker Hub+ # login/push fails loudly (missing credentials) instead of faking green.+ release-publish:- name: Publish tested Docker image (${{ matrix.arch }})++ name: Publish tested Docker image (${{ matrix.variant }}/${{ matrix.arch }})+ if: needs.mode.outputs.phase == 'publish'+ needs: [mode]+ environment: container-publish+ strategy:+ fail-fast: false+ matrix:- include:- - arch: amd64- - arch: arm64++ arch: [amd64, arm64]++ variant: [slim, desktop]+ runs-on: ubuntu-latest-32-core+ timeout-minutes: 45+ env:+ ARCH: ${{ matrix.arch }}+ RELEASE_TAG: ${{ inputs.tag }}++ VARIANT: ${{ matrix.variant }}++ SUFFIX: ${{ matrix.variant == 'desktop' && '-desktop' || '' }}+ steps:+ - name: Checkout release code (helper scripts only, no build)+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}++ - name: Download tested image archive from the test phase (same run)+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:- name: docker-test-image-${{ matrix.arch }}-${{ inputs.tag }}++ name: docker-test-image-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}+ path: /tmp/image-artifacts++ - name: Verify tested archive hash (published bytes == tested bytes)run: |- if [ "${{ github.event_name }}" = "release" ]; then- docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}${SUFFIX}"- else- docker buildx imagetools inspect "${IMAGE_NAME}:main${SUFFIX}"- fi+ set -euo pipefail+ cd /tmp/image-artifacts+ echo " expected: $(cat "image-${ARCH}.tar.sha256")"+ sha256sum --check "image-${ARCH}.tar.sha256"++ - name: Set up Docker Buildx+ id: buildx+ continue-on-error: true+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3++ - name: Set up Docker Buildx (retry)+ if: steps.buildx.outcome == 'failure'+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3++ - name: Load tested image+ run: |+ set -euo pipefail+ docker load --input /tmp/image-artifacts/image-${ARCH}.tar+ docker image inspect "${IMAGE_NAME}:test" > /tmp/image-artifacts/loaded.json+ python3 - <<'PY'+ import json, os+ from pathlib import Path+ identity = json.loads(Path('/tmp/image-artifacts/identity.json').read_text())+ loaded = json.loads(Path('/tmp/image-artifacts/loaded.json').read_text())[0]- expected = (os.environ['RELEASE_TAG'], os.environ['GITHUB_SHA'], os.environ['ARCH'])- if (identity['tag'], identity['commit'], identity['arch']) != expected:++ expected = (os.environ['RELEASE_TAG'], os.environ['GITHUB_SHA'], os.environ['ARCH'], os.environ['VARIANT'])++ if (identity['tag'], identity['commit'], identity['arch'], identity['variant']) != expected:+ raise SystemExit('Tested Docker archive identity mismatch')+ if (loaded['Id'], loaded['Architecture']) != (identity['imageId'], identity['arch']):+ raise SystemExit('Loaded Docker image differs from tested image')+ PY++ - name: Log in to Docker Hub+ uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}++ - name: Push tested image with per-arch release tag+ run: |+ set -euo pipefail- docker tag "${IMAGE_NAME}:test" "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}"- docker push "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}"++ docker tag "${IMAGE_NAME}:test" "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}"++ docker push "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}"++ - name: Record pushed per-arch digest+ run: |+ set -euo pipefail+ mkdir -p /tmp/digests- digest="$(docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}" \++ digest="$(docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}" \+ --format '{{json .Manifest.Digest}}' | tr -d '"')"+ case "$digest" in+ sha256:*) ;;+ *) echo "::error::Unexpected digest format: $digest"; exit 1 ;;+ esac+ printf '%s' "$digest" > "/tmp/digests/${ARCH}.digest"+ cat "/tmp/digests/${ARCH}.digest"++ - name: Upload per-arch digest artifact+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:- name: docker-publish-digest-${{ matrix.arch }}-${{ inputs.tag }}++ name: docker-publish-digest-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}+ path: /tmp/digests/${{ matrix.arch }}.digest+ if-no-files-found: error+ retention-days: 7++ # Assemble the immutable versioned multi-arch manifest and expose its digest+ # to the parent release receipt. Registry-side only; nothing is rebuilt.+ release-publish-manifest:+ name: Assemble versioned manifest and digest receipt+ if: needs.mode.outputs.phase == 'publish'+ needs: [mode, release-publish]+ runs-on: ubuntu-latest+ outputs:+ digest: ${{ steps.list.outputs.digest }}+ timeout-minutes: 15+ environment: container-publish+ env:+ RELEASE_TAG: ${{ inputs.tag }}+ steps:+ - name: Checkout release code (helper scripts only)+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}++ - name: Download per-arch digests+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ path: /tmp/digests+ pattern: docker-publish-digest-*-${{ inputs.tag }}- merge-multiple: true++ - name: Set up Docker Buildx+ id: buildx+ continue-on-error: true+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3++ - name: Set up Docker Buildx (retry)+ if: steps.buildx.outcome == 'failure'+ uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3++ - name: Log in to Docker Hub+ uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}+- - name: Create versioned manifest list++ - name: Create both immutable versioned manifest lists+ env:+ IMAGE_NAME: ${{ env.IMAGE_NAME }}+ run: |+ set -euo pipefail+ cd /tmp/digests- test -f amd64.digest && test -f arm64.digest- args=()- for arch in amd64 arm64; do- args+=("${IMAGE_NAME}@$(cat "${arch}.digest")")- done- verify_manifest() {- python3 - "$1" amd64.digest arm64.digest <<'PY'++ for variant in slim desktop; do++ suffix=""++ [ "$variant" = desktop ] && suffix=-desktop++ digest_files=()++ args=()++ for arch in amd64 arm64; do++ file="docker-publish-digest-${variant}-${arch}-${RELEASE_TAG}/${arch}.digest"++ test -s "$file"++ digest_files+=("$file")++ args+=("${IMAGE_NAME}@$(cat "$file")")++ done++ verify_manifest() {++ python3 - "$1" "${digest_files[@]}" <<'PY'+ import json, pathlib, sys-+ manifest = json.loads(pathlib.Path(sys.argv[1]).read_text())+ expected = {pathlib.Path(path).read_text().strip() for path in sys.argv[2:]}+ actual = {row.get("digest") for row in manifest.get("manifests", [])}- if actual != expected:++ if actual != expected or len(manifest.get("manifests", [])) != 2:+ raise SystemExit(f"versioned Docker manifest differs: expected {sorted(expected)}, got {sorted(actual)}")+ PY- }- if docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}" --raw > existing.json 2>/dev/null; then- verify_manifest existing.json- echo "Verified existing immutable ${IMAGE_NAME}:${RELEASE_TAG}"- else- for i in 1 2 3; do- if docker buildx imagetools create \- -t "${IMAGE_NAME}:${RELEASE_TAG}" \- "${args[@]}"; then- break- fi- if [ "$i" = 3 ]; then- echo "::error::imagetools create failed after 3 attempts"- exit 1- fi- sleep 20- done- fi- docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}" --raw > verified.json- verify_manifest verified.json++ }++ ref="${IMAGE_NAME}:${RELEASE_TAG}${suffix}"++ if docker buildx imagetools inspect "$ref" --raw > existing.json 2>/dev/null; then++ verify_manifest existing.json++ else++ for i in 1 2 3; do++ if docker buildx imagetools create -t "$ref" "${args[@]}"; then break; fi++ if [ "$i" = 3 ]; then echo "::error::imagetools create failed after 3 attempts"; exit 1; fi++ sleep 20++ done++ fi++ docker buildx imagetools inspect "$ref" --raw > verified.json++ verify_manifest verified.json++ done+- - name: Record manifest-list digest++ - name: Record slim manifest-list digest for the release receipt+ id: list+ env:+ IMAGE_NAME: ${{ env.IMAGE_NAME }}+ run: |+ set -euo pipefail+ digest="$(docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}" \+ --format '{{json .Manifest.Digest}}' | tr -d '"')"+ case "$digest" in+ sha256:*) ;;+ *) echo "::error::Unexpected manifest-list digest: $digest"; exit 1 ;;+ esac+ echo "digest=$digest" >> "$GITHUB_OUTPUT"++ - name: Emit release manifest artifact+ id: manifest+ run: |+ set -euo pipefail+ mkdir -p /tmp/manifest+ python3 -m scripts.releases.docker manifest \+ --tag "$RELEASE_TAG" \+ --commit "$GITHUB_SHA" \- --digest-amd64 "$(sed 's/^sha256://' /tmp/digests/amd64.digest)" \- --digest-arm64 "$(sed 's/^sha256://' /tmp/digests/arm64.digest)" \++ --digest-amd64 "$(sed 's/^sha256://' /tmp/digests/docker-publish-digest-slim-amd64-${RELEASE_TAG}/amd64.digest)" \++ --digest-arm64 "$(sed 's/^sha256://' /tmp/digests/docker-publish-digest-slim-arm64-${RELEASE_TAG}/arm64.digest)" \+ > /tmp/manifest/manifest.json+ python3 - "$RELEASE_TAG" "${{ steps.list.outputs.digest }}" <<'EOF'+ import json, sys+ manifest = json.load(open("/tmp/manifest/manifest.json"))+ manifest["list-digest"] = sys.argv[2]+ manifest["image"] = "nousresearch/hermes-agent"+ manifest["tags"] = [sys.argv[1]]+ json.dump(manifest, open("/tmp/manifest/manifest.json", "w"), indent=2)+ EOF+ cat /tmp/manifest/manifest.json++ - name: Verify manifest identity+ run: |+ set -euo pipefail+ python3 -m scripts.releases.docker verify \+ --tag "$RELEASE_TAG" --commit "$GITHUB_SHA" /tmp/manifest/manifest.json++ - name: Upload release manifest artifact+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: docker-publish-manifest-${{ inputs.tag }}+ path: /tmp/manifest/manifest.json+ if-no-files-found: error+ retention-days: 7++ # Strict phase gate: in every release phase, the jobs that phase requires+ # must actually have run and succeeded. `if: always()` keeps this job in+ # the graph even when earlier jobs were skipped, so a skipped/failed+ # publisher turns this red instead of letting the phase go green.+ release-phase-gate:+ name: Docker phase requirements met+ if: always() && inputs.release-phase != ''+ needs: [mode, build, release-publish, release-publish-manifest]+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Validate phase job results+ env:+ PHASE: ${{ needs.mode.outputs.phase }}+ BUILD: ${{ needs.build.result }}+ RELEASE_PUBLISH: ${{ needs.release-publish.result }}+ RELEASE_MANIFEST: ${{ needs.release-publish-manifest.result }}+ MODE: ${{ needs.mode.result }}+ run: |+ set -euo pipefail+ test "$MODE" = success+ case "$PHASE" in+ test)+ failures=()+ [ "$BUILD" = success ] || failures+=("build=$BUILD")+ [ "${#failures[@]}" -eq 0 ] || { printf '::error::%s\n' "${failures[@]}"; exit 1; }+ ;;+ publish)+ failures=()+ [ "$RELEASE_PUBLISH" = success ] || failures+=("release-publish=$RELEASE_PUBLISH")+ [ "$RELEASE_MANIFEST" = success ] || failures+=("release-publish-manifest=$RELEASE_MANIFEST")+ [ "${#failures[@]}" -eq 0 ] || { printf '::error::%s\n' "${failures[@]}"; exit 1; }+ ;;+ *) echo "::error::Unknown phase $PHASE"; exit 1 ;;+ esacdiff --cc Dockerfileindex 973bd1ce3de,ba9cbe87248..f10f5a7acd4--- a/Dockerfile+++ b/Dockerfile@@@ -64,23 -68,19 +64,27 @@@ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/herme# replaces tini with s6-overlay's /init (PID 1 = s6-svscan), which reaps# zombies non-blockingly on SIGCHLD and additionally supervises the main# hermes process, the dashboard, and per-profile gateways.+# The second package list is the shared libraries the pinned Chromium links+# against. `npx playwright install --with-deps` used to apt-install them as+# a side effect; pm stages the pinned browser instead (below), so the libs+# must be declared here. The list is the `ldd ... | grep "not found"` set of+# the pinned chrome binary in this base image, mapped to trixie package+# names (see .hermes/plans/termux-removal-commit-spec.md).RUN apt-get -o Acquire::Retries=3 update && \apt-get -o Acquire::Retries=3 install -y --no-install-recommends \- ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils && \+ ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils \+ libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 libatspi2.0-0t64 libcairo2 libcups2t64 libdbus-1-3 libgbm1 libglib2.0-0t64 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 && \rm -rf /var/lib/apt/lists/*- # Bot Screen (opt-in): TigerVNC + the Xfce components + a headed chromium, so a- # container that cannot run apt at run time (unprivileged user, no sudo — every- # hosted instance) can still stream a desktop. ~550 MB. Nothing here starts at- # boot; the layer costs no memory until a screen is started. Same package list- # as tools/bot_desktop/runtime.py::PACKAGES["apt"].+ # Bot Screen (opt-in): PACKAGES["apt"] from tools/bot_desktop/runtime.py plus apt-# `chromium` for the dock's Browser icon. ~930 MB apt on debian:13.4 (~1.4 GB of-# image once the gated headed Chromium below is counted); nothing starts++# `chromium` for the restricted-userns sandbox fallback. PM already stages++# pinned full Chromium for both variants; no separate Playwright install.++# Nothing starts+ # at boot. docker.yml builds both variants and publishes these packages under+ # the `-desktop` tags: hosted sandboxes pull a prebuilt image and never run a+ # build, and cannot apt at run time either (unprivileged, no sudo). Only this+ # build step needs root —+ # Xvnc is a userspace X server, so the runtime user can drive it.# docker build --build-arg HERMES_BOT_DESKTOP=1 .ARG HERMES_BOT_DESKTOP=0RUN if [ "$HERMES_BOT_DESKTOP" = "1" ]; then \@@@ -267,70 -291,31 +271,78 @@@ FROM runtime_base AS python_dep## Google Chat's [google-chat] extra (google-cloud-pubsub + Chat API clients)# is baked so hosted/immutable images can enable the adapter without writing-# the sealed venv. Runtime --install-deps still routes through lazy_deps into-# HERMES_LAZY_INSTALL_TARGET when the extra is not present.+# the sealed venv.#-# The editable link is created after the source copy below.+# Source binding is created after the source copy below.COPY pyproject.toml uv.lock ./RUN touch ./README.md-RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra matrix --extra google-chat+RUN python3 -m pm.build_env --source /opt/hermes --python /usr/local/bin/python3 \+ --out /opt/hermes/.venv --no-install-project --sealed \+ --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock \+ --extra azure-identity --extra hindsight --extra matrix --extra google-chat++# Icons render on the runtime environment: Pillow and resvg-py are core+# dependencies. A stage of its own so the frontend stage keeps building its+# Node dependencies in parallel with the Python ones.+FROM python_deps AS icons+COPY scripts/generate_icons.py scripts/+COPY assets/ assets/+RUN /opt/hermes/.venv/bin/python -I scripts/generate_icons.py --source /opt/hermes --out /tmp/hermes-icons++# Frontend dependencies never enter the runtime layers.+FROM runtime_base AS frontend_build+COPY package.json package-lock.json ./+COPY web/package.json web/+COPY ui-tui/package.json ui-tui/+COPY ui-tui/packages/hermes-ink/ ui-tui/packages/hermes-ink/+COPY apps/shared/ apps/shared/+COPY scripts/build/node-deps.mjs scripts/build/node-deps.mjs+ENV npm_config_install_links=false+RUN node scripts/build/node-deps.mjs --source /opt/hermes --workspace ui-tui --workspace web-# ---------- Frontend build (cached independently from Python source) -----------# Copy only the frontend source trees first so that Python-only changes don't-# invalidate the (relatively slow) web + ui-tui build layer.+COPY pyproject.toml uv.lock ./COPY web/ web/COPY ui-tui/ ui-tui/-COPY apps/shared/ apps/shared/-RUN cd web && npm run build && \- cd ../ui-tui && npm run build+COPY scripts/build/*.mjs scripts/build/+COPY scripts/generate-icons.mjs scripts/generate_icons.py scripts/+COPY assets/ assets/+COPY --from=icons /tmp/hermes-icons /tmp/hermes-icons+RUN node scripts/build/tui.mjs --source /opt/hermes --out /opt/products/tui && \+ node scripts/build/web.mjs --source /opt/hermes --icons /tmp/hermes-icons --out /opt/products/web++FROM python_deps AS runtime+# Standalone TypeScript linting is a runtime feature; Vite/esbuild are not.+COPY --from=frontend_build /opt/hermes/node_modules/typescript /opt/hermes/node_modules/typescript+RUN mkdir -p /opt/hermes/node_modules/.bin && \+ ln -s ../typescript/bin/tsc /opt/hermes/node_modules/.bin/tsc+# ---------- Photon iMessage sidecar deps (baked, NS-606) ----------+# The photon plugin's Node sidecar needs its own node_modules+# (spectrum-ts). The install tree is immutable at runtime, so a lazy+# `npm ci` on first connect would hit EROFS — bake the deps here instead+# (deterministic installs, NS-559). The patch script is copied alongside+# the manifests because package.json's postinstall runs it, which also+# means the spectrum-ts patch is applied at build time. Layer-cached:+# only re-runs when the sidecar manifests/patch change.+COPY plugins/platforms/photon/sidecar/package.json \+ plugins/platforms/photon/sidecar/package-lock.json \+ plugins/platforms/photon/sidecar/patch-spectrum-mixed-attachments.mjs \+ plugins/platforms/photon/sidecar/+RUN cd plugins/platforms/photon/sidecar && \+ npm ci --no-audit --fetch-retries=5 && \+ npm cache clean --force++# Shared product outputs are independent of application dependency assembly.+COPY --from=frontend_build /opt/products/tui /opt/hermes/ui-tui+COPY --from=frontend_build /opt/products/web /opt/hermes/hermes_cli/web_dist+ # ---------- Bot Screen X socket directory ----------+ # Xvnc would create this itself (/tmp is 1777); pre-creating it keeps ownership+ # deterministic when HERMES_UID is remapped between boots.+ RUN mkdir -p /tmp/.X11-unix && chmod 1777 /tmp/.X11-unix++ # XDG_RUNTIME_DIR (set below) sits under a predictable name in world-writable /tmp.+ # Shipping it root-owned means stage2 finds a directory it trusts and chowns it.+ RUN mkdir -p /tmp/hermes-runtime && chmod 0700 /tmp/hermes-runtime# ---------- Source code ----------# .dockerignore excludes node_modules, so the installs above survive.@@@ -439,9 -428,25 +451,15 @@@ ENV HERMES_TUI_DIR=/opt/hermes/ui-tuENV HERMES_HOME=/opt/dataENV HERMES_WRITE_SAFE_ROOT=/opt/dataENV HERMES_DISABLE_LAZY_INSTALLS=1-# The published image seals /opt/hermes (root-owned, read-only) so a runtime-# lazy install can't mutate the agent's own venv and brick it. But opt-in-# backends (Firecrawl web search, Exa, Feishu, …) keep their SDKs in-# tools/lazy_deps.py — deliberately NOT baked into [all] (see pyproject.toml-# policy 2026-05-12: one quarantined release must not break every install).-# Redirect those lazy installs to a writable dir on the durable data volume.-# lazy_deps appends this dir to the END of sys.path, so a package installed-# here can only ADD modules — it can never shadow or downgrade a core module,-# so the sealed-venv guarantee holds even with installs re-enabled. The dir-# is seeded + chowned to the hermes user by docker/stage2-hook.sh and lives-# on the /opt/data volume, so it persists across container recreates / image-# updates (an ABI stamp invalidates it if a rebuild bumps the interpreter).-ENV HERMES_LAZY_INSTALL_TARGET=/opt/data/lazy-packages+# Lazy installs are fully disabled in the published image (see+# HERMES_DISABLE_LAZY_INSTALLS above): the venv is sealed and opt-in backend+# SDKs are not installed at runtime.++ # Xfce, dbus and the display-allocation lock need one; containers have no logind+ # to create /run/user/<uid>. The default fallback ($HOME/.cache) is the /opt/data+ # volume, which a host-side install may share — two instances would then contend+ # for one lock. Container-scoped instead; seeded 0700 by docker/stage2-hook.sh.+ ENV XDG_RUNTIME_DIR=/tmp/hermes-runtime# `docker exec` privilege-drop shim. When operators run# `docker exec <c> hermes ...` they default to root, and any file thediff --cc apps/desktop/electron/main.tsindex ce5dd3ba79a,cc4c5ceb3ad..1236e5d85cd--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -218,8 -203,9 +218,9 @@@ importterminalScriptExtension,tuiResumeArgs} from './external-terminal'+ import { f12ShortcutDecision, toF12KeyboardEventPayload } from './f12-shortcut'import { type FaviconIo, resolveFavicon } from './favicon'-import { findGitBash as _findGitBash } from './find-git-bash'+import { resolveFeatureFlags } from './feature-flags'import {installFindShortcut,installFoundInPageForwarder,diff --cc apps/desktop/src/app/settings/about-settings.tsxindex 57812566a1e,11947506511..458add687e5--- a/apps/desktop/src/app/settings/about-settings.tsx+++ b/apps/desktop/src/app/settings/about-settings.tsx@@@ -1,21 -1,60 +1,25 @@@import { useStore } from '@nanostores/react'-import { useEffect, useState } from 'react'+import { type ReactElement, useEffect } from 'react'-import { BrandMark } from '@/components/brand-mark'-import { Button } from '@/components/ui/button'-import { Codicon } from '@/components/ui/codicon'-import { type Translations, useI18n } from '@/i18n'-import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'-import { cn } from '@/lib/utils'-import {- $desktopVersion,- $updateApply,- $updateChecking,- $updateStatus,- checkUpdates,- openUpdatesWindow,- refreshDesktopVersion,- startActiveUpdate-} from '@/store/updates'+import { UpdateStatusCard, VersionHero } from '@/components/update-status'+import { VersionDetails } from '@/components/version-details'+import { useI18n } from '@/i18n'+import { RefreshCw } from '@/lib/icons'+import { $connection } from '@/store/session'+import { $desktopVersion, checkBackendUpdates, refreshDesktopVersion } from '@/store/updates'-import { ListRow, SectionHeading, SettingsContent } from './primitives'+import { SectionHeading, SettingsContent } from './primitives'+ import { SETTING_IDS, settingElementId } from './settings-manifest'import { UninstallSection } from './uninstall-section'+ import { useSettingDeepLink } from './use-setting-deep-link'-const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'-const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'--function relativeTime(ms: number | undefined, a: Translations['settings']['about']) {- if (!ms) {- return a.never- }-- const diff = Date.now() - ms-- if (diff < 60_000) {- return a.justNow- }-- if (diff < 3_600_000) {- return a.minAgo(Math.round(diff / 60_000))- }-- if (diff < 86_400_000) {- return a.hoursAgo(Math.round(diff / 3_600_000))- }-- return a.daysAgo(Math.round(diff / 86_400_000))-}-interface AboutSettingsProps {subpage?: string}-export function AboutSettings({ subpage }: AboutSettingsProps = {}) {+export function AboutSettings({ subpage }: AboutSettingsProps = {}): ReactElement {+ useSettingDeepLink('about', page => subpage === undefined || page === subpage)+if (subpage === 'uninstall') {return (<SettingsContent>@@@ -48,19 -121,136 +52,15 @@@ function AppUpdatesSettings({ includeUnreturn (<SettingsContent>- <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">- <BrandMark className="size-16" />- <div>- <h2 className="text-lg font-semibold tracking-tight">{a.heading}</h2>- <p className="mt-1 text-xs text-muted-foreground">- {version?.appVersion ? a.version(version.appVersion) : a.versionUnavailable}- </p>- </div>- {(version?.bundleOutOfSync || version?.bundleSwapPending) && (- <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">- <div className="flex items-start gap-2">- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />- <div className="min-w-0">- {version?.bundleSwapPending ? (- // The updated app is already on disk — the updater swapped it- // under this running process — so a restart loads it. Saying- // "App build out of date" here would repeat the contradiction- // this banner is meant to resolve: the Updates card below- // already reports the runtime as current.- <>- <p className="font-medium">{a.bundleSwapPending}</p>- <p className="mt-1 text-xs text-muted-foreground">{a.bundleSwapPendingDesc}</p>- <Button- className="mt-2"- onClick={() => void window.hermesDesktop?.relaunchApp?.()}- size="sm"- variant="textStrong"- >- <RefreshCw className="size-3" />- {a.bundleSwapPendingAction}- </Button>- </>- ) : (- <>- <p className="font-medium">{a.bundleOutOfSync}</p>- <p className="mt-1 text-xs text-muted-foreground">{a.bundleOutOfSyncDesc}</p>- <Button asChild className="mt-2" size="sm" variant="textStrong">- <a- href={INSTALLER_URL}- onClick={event => {- event.preventDefault()- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)- }}- rel="noreferrer"- target="_blank"- >- <ExternalLink className="size-3" />- {a.bundleOutOfSyncAction}- </a>- </Button>- </>- )}- </div>- </div>- </div>- )}- </div>-+ <VersionHero version={version} />-<div className="mx-auto mt-4 w-full max-w-2xl">- <SectionHeading icon={RefreshCw} title={a.updates} />-- <div- className={cn(- 'rounded-xl border px-4 py-3 text-sm',- statusTone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',- statusTone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',- statusTone === 'idle' && 'border-border/70 bg-muted/20 text-foreground'- )}- >- <div className="flex items-start gap-2">- {statusTone === 'available' ? (- <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />- ) : statusTone === 'error' ? null : (- <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />- )}- <div className="min-w-0">- <p className="font-medium">{statusLine}</p>- <p className="mt-1 text-xs text-muted-foreground">- {a.lastChecked(relativeTime(status?.fetchedAt, a))}- {justChecked && !checking ? a.justNowSuffix : ''}- </p>- </div>- </div>-- <div className="mt-3 flex flex-wrap items-center gap-4">- <Button- disabled={checking || applying || !supported}- onClick={() => void handleCheck()}- size="sm"- variant="textStrong"- >- {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}- {checking ? a.checking : a.checkNow}- </Button>-- {updateAvailable && supported && !applying && (- <>- <Button onClick={() => startActiveUpdate()} size="sm">- {a.updateNow}- </Button>- <Button onClick={() => openUpdatesWindow('client')} size="sm" variant="textStrong">- {a.seeWhatsNew}- </Button>- </>- )}-- <Button asChild className="ml-auto" size="sm" variant="text">- <a- href={RELEASE_NOTES_URL}- onClick={event => {- event.preventDefault()- void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)- }}- rel="noreferrer"- target="_blank"- >- <ExternalLink className="size-3" />- {a.releaseNotes}- </a>- </Button>- </div>+ <SectionHeading icon={RefreshCw} title={t.settings.about.updates} />-- <div className="grid gap-3">++ <div className="grid gap-3" id={settingElementId(SETTING_IDS.about.updates)}>+ <UpdateStatusCard target="client" />+ {/* Client and remote backend updates are independent. Only the client has release notes. */}+ {remote && <UpdateStatusCard showReleaseNotes={false} target="backend" />}</div>-- <ListRow- description={a.automaticUpdatesDesc}- hint={a.branchCommit(status?.branch ?? 'unknown', status?.currentSha?.slice(0, 7) ?? 'unknown')}- id={settingElementId(SETTING_IDS.about.automaticUpdates)}- title={a.automaticUpdates}- />--+ {version && <VersionDetails version={version} />}-{includeUninstall && <UninstallSection />}</div></SettingsContent>diff --cc apps/desktop/src/app/settings/settings-manifest.tsindex 00000000000,df496997000..a6676edc4e2mode 000000,100644..100644--- a/apps/desktop/src/app/settings/settings-manifest.ts+++ b/apps/desktop/src/app/settings/settings-manifest.ts@@@ -1,0 -1,328 +1,328 @@@+ import type { Translations } from '@/i18n'+ import { NATIVE_NOTIFICATION_KINDS } from '@/store/native-notifications'+ import { canUseQuickEntry } from '@/store/quick-entry'+ import { TRANSLUCENCY_SUPPORTED } from '@/store/translucency'++ import type { AppearanceSubpageId } from './appearance-subpages'+ import type { SettingsView } from './types'++ interface SettingCopy {+ description?: string+ label: string+ }++ export interface SettingDefinition {+ /** Rows that only exist on some platforms stay out of search, where a hit would scroll to nothing. */+ available?: () => boolean+ copy: (t: Translations) => SettingCopy+ keywords: readonly string[]+ /** The child page the row lives on; omitted when the view has no subpages. */+ subpage?: string+ }++ type AppearanceCopy = Translations['settings']['appearance']+ type TitledKey = { [K in keyof AppearanceCopy]: K extends `${infer Base}Title` ? Base : never }[keyof AppearanceCopy]++ // Most Appearance rows read `<key>Title` / `<key>Desc` straight from the+ // appearance catalog; a Desc that is a formatter (uiScale) is left to the row.+ const appearanceCopy =+ <K extends TitledKey>(key: K) =>+ (t: Translations): SettingCopy => {+ const catalog: Record<string, unknown> = t.settings.appearance+ const description = catalog[`${key}Desc`]++ return {+ label: t.settings.appearance[`${key}Title`],+ description: typeof description === 'string' ? description : undefined+ }+ }++ const appearanceSetting = (subpage: AppearanceSubpageId, keywords: readonly string[], key: TitledKey) =>+ ({ subpage, keywords, copy: appearanceCopy(key) }) satisfies SettingDefinition++ /**+ * The manifest of every hand-built settings row — the ones that are not a+ * config-schema field, a credential, or a plugin (those index themselves from+ * backend metadata). A key becomes the row's deep-link id+ * (`<view>.<kebab-case>`), its subpage routes that id, and its copy + keywords+ * feed the command palette — so a row cannot exist without being searchable,+ * and search cannot point at a row that is not there.+ *+ * List *items* (an archived chat, a saved connection, a credential) are not+ * settings and do not belong here; their pages own their own deep links.+ */+ export const SETTINGS_MANIFEST = {+ appearance: {+ language: {+ subpage: 'general',+ keywords: ['locale'],+ copy: t => ({ label: t.language.label, description: t.language.description })+ },+ introSplash: appearanceSetting('general', ['splash', 'wordmark', 'empty chat', 'new chat'], 'introSplash'),+ resumeLastSession: appearanceSetting(+ 'general',+ ['resume', 'reopen', 'launch', 'startup', 'last chat', 'session'],+ 'resumeLastSession'+ ),+ tips: appearanceSetting('general', ['tips', 'hints', 'coach marks', 'onboarding', 'help'], 'tips'),+ tours: appearanceSetting('general', ['tour', 'walkthrough', 'guide', 'onboarding', 'help'], 'tours'),+ theme: appearanceSetting('theme', ['color mode', 'skin', 'light', 'dark'], 'theme'),+ uiScale: appearanceSetting('typography', ['zoom', 'size'], 'uiScale'),+ chatFont: appearanceSetting('typography', ['font', 'typeface', 'family', 'text'], 'chatFont'),+ terminalFont: appearanceSetting(+ 'typography',+ ['font', 'monospace', 'nerd font', 'glyphs', 'shell'],+ 'terminalFont'+ ),+ interfaceMode: {+ subpage: 'window-layout',+ keywords: ['simple', 'advanced', 'mode', 'interface', 'chrome', 'minimal', 'focus'],+ copy: t => ({ label: t.interfaceMode.title, description: t.interfaceMode.hint })+ },+ sessionDensity: appearanceSetting(+ 'window-layout',+ ['sidebar', 'sessions', 'compact', 'comfortable', 'density'],+ 'sessionDensity'+ ),+ tabStrip: appearanceSetting('window-layout', ['tabs', 'tab bar', 'strip'], 'tabStrip'),+ appActions: appearanceSetting(+ 'window-layout',+ ['titlebar', 'settings gear', 'layout', 'HUD', 'left', 'right', 'tabs'],+ 'appActions'+ ),+ minimizeToTray: {+ subpage: 'window-layout',+ keywords: ['tray', 'background', 'minimize', 'dock', 'taskbar', 'menu bar'],+ available: () => Boolean(window.hermesDesktop?.minimizeToTray),+ copy: t => ({ label: t.settings.config.minimizeToTrayTitle, description: t.settings.config.minimizeToTrayDesc })+ },+ translucency: {+ ...appearanceSetting('window-layout', ['opacity', 'transparent', 'glass', 'blur'], 'translucency'),+ available: () => TRANSLUCENCY_SUPPORTED+ },+ backdrop: appearanceSetting('window-layout', ['background', 'blur'], 'backdrop'),+ composerPopout: appearanceSetting(+ 'window-layout',+ ['composer', 'floating', 'drag', 'popout', 'dock', 'input'],+ 'composerPopout'+ ),+ userBubble: appearanceSetting('chat-display', ['opacity', 'transparent', 'message', 'bubble'], 'userBubble'),+ textDirection: appearanceSetting(+ 'chat-display',+ ['rtl', 'ltr', 'right to left', 'left to right', 'bidi', 'arabic', 'hebrew', 'persian', 'align'],+ 'textDirection'+ ),+ hideThreadTimeline: appearanceSetting(+ 'chat-display',+ ['thread', 'conversation', 'timeline', 'bars', 'rail', 'navigation', 'hide'],+ 'hideThreadTimeline'+ ),+ reactions: appearanceSetting('chat-display', ['emoji', 'tapback', 'react', 'reactions'], 'reactions'),+ vibeHearts: appearanceSetting('chat-display', ['hearts', 'vibe', 'celebrate', 'confetti', 'fun'], 'vibeHearts'),+ toolView: appearanceSetting('chat-display', ['tool display', 'technical'], 'toolView'),+ hideCodeDiffs: appearanceSetting(+ 'chat-display',+ ['code', 'diff', 'patch', 'file edits', 'inline', 'added', 'removed'],+ 'hideCodeDiffs'+ ),+ reasoningCollapsed: appearanceSetting(+ 'chat-display',+ ['thinking', 'reasoning', 'collapse', 'expand', 'chain of thought'],+ 'reasoningCollapsed'+ ),+ embeds: appearanceSetting('chat-display', ['external content', 'privacy'], 'embeds'),+ pet: {+ subpage: 'pet',+ keywords: ['pet', 'mascot', 'petdex', 'companion', 'buddy'],+ copy: t => ({ label: t.settings.appearance.pet.chooseTitle, description: t.settings.appearance.pet.chooseDesc })+ }+ },+ chat: {+ attachmentSize: {+ subpage: 'attachments',+ keywords: ['attachment', 'image', 'preview', 'upload', 'file size', 'limit', 'MB'],+ copy: t => ({ label: t.settings.config.attachmentSizeTitle, description: t.settings.config.attachmentSizeDesc })+ }+ },+ advanced: {+ keepAwake: {+ subpage: 'desktop',+ keywords: ['sleep', 'awake', 'caffeinate', 'idle', 'overnight', 'power'],+ copy: t => ({ label: t.settings.config.keepAwakeTitle, description: t.settings.config.keepAwakeDesc })+ },+ disableF12: {+ subpage: 'desktop',+ keywords: ['devtools', 'developer tools', 'f12', 'inspector', 'debug'],+ copy: t => ({ label: t.settings.config.disableF12Title, description: t.settings.config.disableF12Desc })+ },+ warmBotBackends: {+ subpage: 'desktop',+ keywords: ['pool', 'backends', 'bots', 'warm', 'concurrency', 'limit'],+ copy: t => ({ label: t.settings.poolLimits.warmBotBackendsTitle })+ },+ backendIdleTimeout: {+ subpage: 'desktop',+ keywords: ['pool', 'backends', 'idle', 'timeout', 'milliseconds'],+ copy: t => ({ label: t.settings.poolLimits.backendIdleTimeoutTitle })+ },+ quickEntry: {+ subpage: 'desktop',+ keywords: ['quick entry', 'global shortcut', 'spotlight', 'summon', 'prompt anywhere'],+ available: canUseQuickEntry,+ copy: t => ({ label: t.settings.quickEntry.enabledTitle, description: t.settings.quickEntry.enabledDesc })+ },+ quickEntryShortcut: {+ subpage: 'desktop',+ keywords: ['quick entry', 'shortcut', 'hotkey', 'keybind', 'chord'],+ available: canUseQuickEntry,+ copy: t => ({ label: t.settings.quickEntry.shortcutTitle, description: t.settings.quickEntry.shortcutDesc })+ }+ },+ keybinds: {+ hudModifier: {+ subpage: 'hud-gesture',+ keywords: ['HUD', 'summon', 'modifier', 'tap', 'Ctrl', 'Alt', 'Command', 'Option'],+ available: () => Boolean(window.hermesDesktop?.hudModifier),+ copy: t => ({ label: t.settings.hudModifier.title, description: t.settings.hudModifier.description })+ },+ screenshot: {+ subpage: 'screen-capture',+ keywords: ['screenshot', 'screen capture', 'window', 'attach', 'command keys'],+ available: () => Boolean(window.hermesDesktop?.screenshot),+ copy: t => ({ label: t.settings.screenshot.enabledTitle, description: t.settings.screenshot.enabledDesc })+ }+ },+ notifications: {+ enableAll: {+ subpage: 'alerts',+ keywords: ['notifications', 'alerts', 'native', 'banner', 'mute', 'do not disturb'],+ copy: t => ({ label: t.settings.notifications.enableAll, description: t.settings.notifications.enableAllDesc })+ },+ ...Object.fromEntries(+ NATIVE_NOTIFICATION_KINDS.map(kind => [+ `kind-${kind}`,+ {+ subpage: 'alerts',+ keywords: ['notification', 'alert', kind],+ copy: (t: Translations) => ({+ label: t.settings.notifications.kinds[kind].label,+ description: t.settings.notifications.kinds[kind].description+ })+ } satisfies SettingDefinition+ ])+ ),+ completionSound: {+ subpage: 'sounds',+ keywords: ['sound', 'chime', 'ding', 'audio', 'done', 'complete', 'mute'],+ copy: t => ({+ label: t.settings.notifications.completionSoundTitle,+ description: t.settings.notifications.completionSoundDesc+ })+ }+ },+ sessions: {+ autoArchive: {+ subpage: 'archived',+ keywords: ['archive', 'stale', 'cleanup', 'old chats', 'days', 'after'],+ copy: t => ({ label: t.settings.sessions.autoArchiveTitle, description: t.settings.sessions.autoArchiveDesc })+ }+ },+ gateway: {+ connectionMode: {+ subpage: 'connection',+ keywords: ['gateway', 'connection', 'local', 'cloud', 'remote', 'ssh', 'url', 'token', 'host', 'port', 'key'],+ copy: t => ({ label: t.settings.gateway.modeTitle, description: t.settings.gateway.intro })+ },+ keychainEncryption: {+ subpage: 'connection',+ keywords: ['keychain', 'encrypt', 'secrets', 'secure storage', 'plain text'],+ copy: t => ({+ label: t.settings.gateway.keychainEncryptionTitle,+ description: t.settings.gateway.keychainEncryptionDesc+ })+ },+ diagnostics: {+ subpage: 'connection',+ keywords: ['diagnostics', 'logs', 'debug', 'report', 'troubleshoot'],+ copy: t => ({ label: t.settings.gateway.diagnostics, description: t.settings.gateway.diagnosticsDesc })+ }+ },+ about: {- automaticUpdates: {++ updates: {+ subpage: 'updates',+ keywords: ['update', 'auto update', 'download', 'release', 'version'],- copy: t => ({ label: t.settings.about.automaticUpdates, description: t.settings.about.automaticUpdatesDesc })++ copy: t => ({ label: t.settings.about.updates })+ }+ }+ } as const satisfies Record<string, Record<string, SettingDefinition>>++ export type ManifestViewKey = keyof typeof SETTINGS_MANIFEST++ /** Manifest keys that are config sections route as `config:<key>`; the rest are views of their own. */+ const CONFIG_SECTION_KEYS: readonly ManifestViewKey[] = ['appearance', 'chat', 'advanced']++ export const manifestView = (key: ManifestViewKey): SettingsView =>+ CONFIG_SECTION_KEYS.includes(key) ? `config:${key}` : (key as SettingsView)++ const manifestKeyForView = (view: SettingsView): ManifestViewKey | undefined => {+ const key = view.startsWith('config:') ? view.slice('config:'.length) : view++ return Object.hasOwn(SETTINGS_MANIFEST, key) ? (key as ManifestViewKey) : undefined+ }++ const kebab = (key: string) => key.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)++ /** The deep-link id of a manifest row: `settingId('appearance', 'tips') === 'appearance.tips'`. */+ export const settingId = (view: ManifestViewKey, key: string) => `${view}.${kebab(key)}`++ /** Notification kinds are generated from the store's kind list, so their ids are looked up by kind. */+ export const notificationKindSettingId = (kind: (typeof NATIVE_NOTIFICATION_KINDS)[number]) =>+ settingId('notifications', `kind-${kind}`)++ type SettingIds = { readonly [V in ManifestViewKey]: { readonly [K in keyof (typeof SETTINGS_MANIFEST)[V]]: string } }++ /** `SETTING_IDS.appearance.tips === 'appearance.tips'` — the id a row carries and a palette hit targets. */+ export const SETTING_IDS = Object.fromEntries(+ (Object.keys(SETTINGS_MANIFEST) as ManifestViewKey[]).map(view => [+ view,+ Object.fromEntries(Object.keys(SETTINGS_MANIFEST[view]).map(key => [key, settingId(view, key)]))+ ])+ ) as SettingIds++ /** The DOM id a settings row carries so a deep link can scroll to and flash it. */+ export const settingElementId = (id: string) => `setting-field-${id}`++ const definitions = (view: ManifestViewKey): Record<string, SettingDefinition> => SETTINGS_MANIFEST[view]++ /** The manifest row behind a deep-link id on a view, if the view owns one. */+ export function settingDefinition(view: SettingsView, id: string): SettingDefinition | undefined {+ const key = manifestKeyForView(view)++ if (!key) {+ return undefined+ }++ const [settingKey] = Object.entries(SETTING_IDS[key]).find(([, candidate]) => candidate === id) ?? []++ return settingKey ? definitions(key)[settingKey] : undefined+ }++ export interface SettingSearchTarget extends SettingCopy {+ id: string+ keywords: string[]+ view: SettingsView+ }++ /** Every manifest row the command palette can land on right now, copy resolved. */+ export function settingSearchTargets(t: Translations): SettingSearchTarget[] {+ return (Object.keys(SETTINGS_MANIFEST) as ManifestViewKey[]).flatMap(viewKey =>+ Object.entries(definitions(viewKey))+ .filter(([, setting]) => setting.available?.() ?? true)+ .map(([key, setting]) => ({+ id: SETTING_IDS[viewKey][key as keyof (typeof SETTING_IDS)[typeof viewKey]],+ keywords: [...setting.keywords],+ view: manifestView(viewKey),+ ...setting.copy(t)+ }))+ )+ }diff --cc apps/desktop/src/app/settings/subpages.test.tsindex b176bc2c16d,3ce0d7d99e3..4bc1a9133b4--- a/apps/desktop/src/app/settings/subpages.test.ts+++ b/apps/desktop/src/app/settings/subpages.test.ts@@@ -63,4 -73,46 +73,46 @@@ describe('settings subpage routing', (expect(resolveSettingsSubpage(view, new URLSearchParams(search))).toBe(expected)}})++ it('makes every manifest row a routed, translated palette hit on a real page', () => {+ for (const viewKey of Object.keys(SETTINGS_MANIFEST) as ManifestViewKey[]) {+ const view = manifestView(viewKey)+ const subpages = settingsSubpages(view).map(page => page.id)+ expect(views).toContain(view)++ for (const [key, setting] of Object.entries(SETTINGS_MANIFEST[viewKey])) {+ const id = SETTING_IDS[viewKey][key as keyof (typeof SETTING_IDS)[typeof viewKey]]+ expect(id).toBe(`${viewKey}.${key.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`)+ expect(settingDefinition(view, id)).toBe(setting)+ expect(setting.keywords.length).toBeGreaterThan(0)++ if (setting.subpage) {+ expect(subpages).toContain(setting.subpage)+ expect(+ resolveSettingsSubpage(view, new URLSearchParams(settingsSearchTargetQuery({ view, setting: id })))+ ).toBe(setting.subpage)+ }++ for (const locale of Object.values(TRANSLATIONS)) {+ expect(setting.copy(locale).label).toBeTruthy()+ }+ }+ }++ // Platform-gated rows aside, the whole manifest reaches the palette.+ const definitions = Object.values(SETTINGS_MANIFEST).flatMap(rows => Object.values(rows))+ const gated = definitions.filter(setting => 'available' in setting).length+ const targets = settingSearchTargets(TRANSLATIONS.en)+ expect(targets.length).toBeGreaterThanOrEqual(definitions.length - gated)+ expect(new Set(targets.map(target => target.id)).size).toBe(targets.length)+ expect(targets.map(target => target.label)).toEqual(+ expect.arrayContaining([+ 'In-App Tips',+ 'Guided Tours',+ 'Keep computer awake',+ 'Auto-archive stale chats',- 'Automatic updates'++ TRANSLATIONS.en.settings.about.updates+ ])+ )+ })})diff --cc apps/desktop/src/components/model-picker.tsxindex 95c67b4b4cc,e30c2dcff5c..785787d60ba--- a/apps/desktop/src/components/model-picker.tsx+++ b/apps/desktop/src/components/model-picker.tsx@@@ -61,8 -59,9 +63,9 @@@ export function ModelPickerDialog(ownerConnectionId,profile = 'default',request,+ setupProfile,contentClassName-}: ModelPickerDialogProps) {+}: ModelPickerDialogProps): ReactElement {const { t } = useI18n()const copy = t.modelPicker// Own the search term so we can filter manually. cmdk's built-indiff --cc apps/desktop/src/global.d.tsindex 28878bf2efb,a10fe6e89b3..52356020606--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -370,9 -386,20 +370,21 @@@ declare globalonChanged: (callback: (status: { enabled: boolean; available: boolean }) => void) => () => void}setDisableF12?: (blocked: boolean) => void+ setF12ShortcutActive?: (active: boolean) => void+ onF12Shortcut?: (+ callback: (input: {+ alt?: boolean+ code?: string+ control?: boolean+ key: string+ meta?: boolean+ repeat?: boolean+ shift?: boolean+ }) => void+ ) => () => voidsetPreviewShortcutActive?: (active: boolean) => voidopenExternal: (url: string) => Promise<void>+ onExternalOpenFailed?: (callback: (payload: ExternalOpenFailedPayload) => void) => () => void/** One-shot loopback callback listener for MCP OAuth against remote* backends (electron/mcp-oauth-callback-ipc.ts): bind on THIS machine,* pass redirectUri as client_redirect_uri to mcp.servers.oauth.start,diff --cc apps/desktop/src/store/local-runtime-jobs.tsindex 36e9a92fb5c,dc2ab720bc3..71173c20172--- a/apps/desktop/src/store/local-runtime-jobs.ts+++ b/apps/desktop/src/store/local-runtime-jobs.ts@@@ -1,125 -1,61 +1,125 @@@-import { atom } from 'nanostores'--import { getApiRequestConnection } from '@/api/client'-import { getLocalModelsJobs, installLocalRuntime } from '@/hermes'+import type { QueryClient } from '@tanstack/react-query'+import {+ MutationObserver,+ type Query,+ type QueryCacheNotifyEvent,+ type QueryKey,+ QueryObserver,+ type QueryObserverResult,+ queryOptions,+ useQuery,+ useQueryClient,+ type UseQueryOptions,+ type UseQueryResult+} from '@tanstack/react-query'+import { useEffect, useMemo } from 'react'++import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile } from '@/api/client'+import type { LocalModelsScope } from '@/api/local-models'+import {+ getLocalCatalog,+ getLocalHardware,+ getLocalModelsJobs,+ getLocalModelsStatus,+ installLocalRuntime+} from '@/hermes'import { translateNow } from '@/i18n'-import { $activeGatewayRoute } from '@/store/gateway'-import { $localModelsEnabled } from '@/store/local-models-flag'+import { queryClient } from '@/lib/query-client'+import { useStoresSelector } from '@/lib/use-session-slice'import { notify, notifyError } from '@/store/notifications'import { $connection } from '@/store/session'-import type { LocalRuntimeJob } from '@/types/hermes'+import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'-// App-level tracker for local-runtime jobs (runtime installs, model-// downloads). The AUTHORITY is the backend job registry — this store is a-// cache of it (desktop guide: server truth is cached, not owned). Living at-// the store layer, not in the settings pane, is what makes a download-// survive the pane unmounting: anything can start a job, the poller follows-// it to completion, and completion/failure notify app-wide exactly once.+export interface LocalModelsOwner extends LocalModelsScope {+ // Legacy primary routes have no registry pin. Fence them by endpoint instead.+ legacyBaseUrl?: string+}- export function localModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {-export const $localRuntimeJobs = atom<readonly LocalRuntimeJob[]>([])++export function localModelsOwner(profile?: string, connectionId?: string | null): LocalModelsOwner {+ const pin: string | null = connectionId ?? getApiRequestConnection()-export const $localRuntimeInstallStarting = atom(false)+ return {+ connectionId: pin,+ profile: profile ?? getApiRequestProfile() ?? 'default',+ ...(pin ? {} : { legacyBaseUrl: $connection.get()?.baseUrl ?? '' })+ }+}- export function useLocalModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {-// Shared by the settings button and the campaign CTA. This is request state,-// not invented job progress; the backend registry still owns the actual work.-export function localRuntimeInstallBusy(): boolean {- return (- $localRuntimeInstallStarting.get() ||- $localRuntimeJobs- .get()- .some(job => job.status === 'running' && (job.kind === 'runtime-install' || job.kind === 'quickstart'))++export function useLocalModelsOwner(profile?: string, connectionId?: string | null): LocalModelsOwner {+ const identity: string = useStoresSelector([$apiRequestScope, $connection], (): string =>+ JSON.stringify(localModelsOwner(profile, connectionId)))++ return useMemo((): LocalModelsOwner => JSON.parse(identity) as LocalModelsOwner, [identity])}-export async function startLocalRuntimeInstall(): Promise<void> {- if (localRuntimeInstallBusy()) {- return+export function localModelsKey(owner: LocalModelsOwner, resource?: string): QueryKey {+ return [+ 'local-models',+ owner.connectionId ?? `legacy:${owner.legacyBaseUrl ?? ''}`,+ owner.profile,+ ...(resource ? [resource] : [])+ ]+}++// A legacy (unpinned) owner is fenced by the endpoint it was minted for;+// once the primary connection moves, its requests and toasts must stop.+export function isLocalModelsOwnerLive(owner: LocalModelsOwner): boolean {+ return Boolean(owner.connectionId) || owner.legacyBaseUrl === ($connection.get()?.baseUrl ?? '')+}++export function localModelsRequestScope(owner: LocalModelsOwner): LocalModelsScope {+ assertLocalModelsOwnerLive(owner)++ return { connectionId: owner.connectionId, profile: owner.profile }+}++export function assertLocalModelsOwnerLive(owner: LocalModelsOwner): void {+ if (!isLocalModelsOwnerLive(owner)) {+ throw new Error(translateNow('settings.localModels.connectionChanged'))}+}- const owner = activeContext- owner.postPending = true- $localRuntimeInstallStarting.set(true)+export function isCurrentLocalModelsOwner(owner: LocalModelsOwner): boolean {+ return JSON.stringify(localModelsKey(owner)) === JSON.stringify(localModelsKey(localModelsOwner()))+}- try {- const { job_id } = await installLocalRuntime()- owner.acceptedIds.add(job_id)- owner.postPending = false- owner.readPending = true- owner.acceptedInstall+++export function localModelsNotificationTitle(owner: LocalModelsOwner): string {+ assertLocalModelsOwnerLive(owner)+ const title: string = translateNow('settings.localModels.title')- if (owner !== activeContext) {- return- }+ return isCurrentLocalModelsOwner(owner)+ ? title+ : `${title} · ${owner.connectionId ?? owner.legacyBaseUrl} / ${owner.profile}`+}++export function localModelsStatusOptions(owner: LocalModelsOwner): UseQueryOptions<LocalModelsStatus> {+ return queryOptions({+ queryKey: localModelsKey(owner, 'status'),+ queryFn: async (): Promise<LocalModelsStatus> => {+ const status: LocalModelsStatus = await getLocalModelsStatus(localModelsRequestScope(owner))+ assertLocalModelsOwnerLive(owner)- // The pane can mount while this POST resolves. Hold the shared lock- // through a fresh read, not merely until the request was accepted.- await polling+ return status+ },+ retry: false+ })+}- if (owner !== activeContext) {+interface StatusWatch {+ observer: QueryObserver<LocalModelsStatus>+ users: number+}+const statusWatches: WeakMap<QueryClient, Map<string, StatusWatch>> = new WeakMap()++export function useLocalModelsStatus(+ owner: LocalModelsOwner,+ enabled: boolean = true+): UseQueryResult<LocalModelsStatus> {+ const client: QueryClient = useQueryClient()+ const result: UseQueryResult<LocalModelsStatus> = useQuery({ ...localModelsStatusOptions(owner), enabled: false })+ useEffect((): (() => void) | undefined => {+ if (!enabled) {return}diff --cc docker/stage2-hook.shindex ac781992d20,9b8e489aa95..cff30f19a18--- a/docker/stage2-hook.sh+++ b/docker/stage2-hook.sh@@@ -384,8 -392,34 +384,33 @@@ as_hermes mkdir -p"$HERMES_HOME/workspace" \"$HERMES_HOME/home" \"$HERMES_HOME/pairing" \- "$HERMES_HOME/platforms/pairing" \- "$HERMES_HOME/lazy-packages"+ "$HERMES_HOME/platforms/pairing"+ # --- XDG_RUNTIME_DIR ---+ # 0700 as dbus requires. It lives in world-writable /tmp under a predictable name+ # and holds the display-allocation lock, so it is a security boundary: refuse a+ # symlink or a directory someone else owns (chowning that one would hand hermes a+ # directory whose creator keeps an fd into it), and chown rather than assume —+ # `usermod -u` above does not chown outside the home dir, so a HERMES_UID remap+ # would leave it owned by the old uid and every Xfce/dbus/lock open would EACCES.+ if [ -n "${XDG_RUNTIME_DIR:-}" ]; then+ xdg_owner=""+ if [ -e "$XDG_RUNTIME_DIR" ]; then xdg_owner=$(stat -c %u "$XDG_RUNTIME_DIR" 2>/dev/null || echo unknown); fi+ if refuse_symlinked_path "create" "$XDG_RUNTIME_DIR"; then+ :+ elif [ -n "$xdg_owner" ] && [ "$xdg_owner" != "0" ] && [ "$xdg_owner" != "$actual_hermes_uid" ]; then+ echo "[stage2] Warning: $XDG_RUNTIME_DIR is owned by uid $xdg_owner (not root or hermes) — refusing to adopt it"+ else+ mkdir -p "$XDG_RUNTIME_DIR" 2>/dev/null || \+ echo "[stage2] Warning: could not create XDG_RUNTIME_DIR $XDG_RUNTIME_DIR (continuing)"+ if [ -d "$XDG_RUNTIME_DIR" ]; then+ chown hermes:hermes "$XDG_RUNTIME_DIR" 2>/dev/null || \+ echo "[stage2] Warning: could not chown XDG_RUNTIME_DIR $XDG_RUNTIME_DIR (rootless?)"+ chmod 0700 "$XDG_RUNTIME_DIR" 2>/dev/null || true+ fi+ fi+ fi+# --- Install-method stamp ---# The 'docker' stamp is baked into the immutable install tree at# /opt/hermes/.install_method (see Dockerfile), NOT written here intodiff --cc hermes_cli/plugins_cmd.pyindex 11b662da123,744ad0bafc4..f8e827f5fc6--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -707,17 -658,46 +726,33 @@@ def _scrub_cloned_origin(repo: Path, gidef _check_manifest_version(manifest: dict, plugin_name: str) -> None:"""Reject manifests declaring a newer ``manifest_version`` than this installer supports."""- mv = manifest.get("manifest_version")- if mv is None:- return- try:- mv_int = int(mv)- except (ValueError, TypeError):- raise PluginOperationError(- f"Plugin '{plugin_name}' has invalid manifest_version '{mv}' (expected an integer).",- ) from None- # Shared with the runtime loader so the installer can never drift behind what the loader- # accepts (#85879): a private cap here refused v2 manifests the runtime happily loads.- from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION- if mv_int > SUPPORTED_MANIFEST_VERSION:+ from pm.plugin_declarations import manifest_version_error++ reason = manifest_version_error(manifest, plugin_name)+ if reason:from hermes_cli.config import recommended_update_command- raise PluginOperationError(- f"Plugin '{plugin_name}' requires manifest_version {mv}, "- f"but this Hermes supports up to {SUPPORTED_MANIFEST_VERSION}. "- f"Run {recommended_update_command()} to update Hermes.",- ) from None+ raise PluginOperationError(f"{reason} Run {recommended_update_command()} to update Hermes.")- def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str]) -> str:+ def _restrict_checkout_to_subdir(repo: Path, git_exe: str, subdir: str) -> None:+ """Sparse-check-out only *subdir*. Written as the classic ``info/sparse-checkout`` file+ rather than ``git sparse-checkout set`` so older Git clients work too."""+ _git_or_raise(git_exe, repo, "config", "core.sparseCheckout", "true", timeout=15,+ failure_prefix="Could not enable sparse checkout:\n")+ pattern_file = repo / ".git" / "info" / "sparse-checkout"+ pattern_file.parent.mkdir(parents=True, exist_ok=True)+ escaped = re.sub(r"([\\*?\[])", r"\\\1", subdir.strip("/"))+ pattern_file.write_text(f"/{escaped}/\n", encoding="utf-8")+++ def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str],+ subdir: Optional[str] = None) -> str:"""Shallow-clone *git_url* into *tmp_clone* (detached at *revision* when given), scrub any- credentials from the recorded origin, and return the installed HEAD SHA."""+ credentials from the recorded origin, and return the installed HEAD SHA.++ A *subdir* install is a blobless clone with a sparse checkout of that subdirectory: a plugin+ living in a monorepo (Hindsight: 170 MB at depth 1, 2 MB for its plugin folder) otherwise+ downloads every file in the repository, which times out on slow connections."""git_exe = _resolve_git_executable()if not git_exe:raise PluginOperationError("git is not installed or not in PATH.")diff --cc tests/ci/test_stable_release_graph.pyindex cfeeb30b27e,00000000000..37dd0a967b3mode 100644,000000..100644--- a/tests/ci/test_stable_release_graph.py+++ b/tests/ci/test_stable_release_graph.py@@@ -1,259 -1,0 +1,262 @@@+"""The release workflow's dependency graph enforces publication ordering."""+import os+import subprocess+from pathlib import Path++from ruamel.yaml import YAML++ROOT = Path(__file__).resolve().parents[2]+++def workflow(name):+ return YAML(typ="base").load((ROOT / ".github/workflows" / name).read_text(encoding="utf-8"))+++def ancestors(jobs, name):+ seen = set()+ pending = [name]+ while pending:+ needs = jobs[pending.pop()].get("needs", [])+ for item in [needs] if isinstance(needs, str) else needs:+ if item not in seen:+ seen.add(item)+ pending.append(item)+ return seen+++def test_admit_can_read_the_claim_draft():+ jobs = workflow("stable-release.yml")["jobs"]+ assert jobs["admit"]["permissions"]["contents"] == "write"+++def test_release_reuses_whole_ci_and_docker_before_publication():+ jobs = workflow("stable-release.yml")["jobs"]+ assert jobs["ci"]["uses"] == "./.github/workflows/ci.yaml"+ assert jobs["ci"]["with"]["release"] == "true"+ assert "secrets" not in jobs["ci"]+ assert jobs["docker"]["uses"] == jobs["publish-docker"]["uses"]+ assert jobs["docker"]["with"]["release-phase"] == "test"+ assert "ci" in ancestors(jobs, "docker")+ candidate_calls = ["candidates-darwin-arm64", "candidates-darwin-x64", "candidates-win32-arm64",+ "candidates-win32-x64", "candidates-win32-bundle", "candidates-termux"]+ required = {"ci", "docker", "nix", "pm-bundle", "install-e2e", "windows-packaged",+ "macos-packaged-arm64", "macos-packaged-x64", "termux-checks", "windows-live",+ "candidate-manifest", "transitions-darwin-arm64", "transitions-darwin-x64",+ "transitions-win32", "bootstrap-version", *candidate_calls}+ assert required <= ancestors(jobs, "acceptance")+ # B3: stable calls one build group at a time; the bundle group waits for+ # both Windows arches, and the Linux groups are not called at all.+ assert "candidates" not in jobs+ for name, group in zip(candidate_calls, ("darwin-arm64", "darwin-x64", "win32-arm64",+ "win32-x64", "win32-bundle", "termux")):+ call = jobs[name]+ assert call["uses"] == "./.github/workflows/desktop-bundled-release.yml"+ assert call["with"]["release-phase"] == "candidate"+ assert call["with"]["jobs"] == group+ assert {"tag", "claim-tag", "claim-object"} <= set(call["with"])+ assert {"candidates-win32-arm64", "candidates-win32-x64"} <= set(jobs["candidates-win32-bundle"]["needs"])+ assert not any("linux" in name for name in jobs)+ # B4: each install arm starts from its own receipt, and the manifest is+ # written after every candidate call (so after every smoke).+ for name in ("transitions", "macos-packaged"):+ assert name not in jobs+ assert set(jobs["candidate-manifest"]["needs"]) == \+ {"admit", *candidate_calls}+ for receipt, call, packaged, matrix in (+ ("transitions-darwin-arm64", "candidates-darwin-arm64", "macos-packaged-arm64", "macos"),+ ("transitions-darwin-x64", "candidates-darwin-x64", "macos-packaged-x64", "macos"),+ ("transitions-win32", "candidates-win32-bundle", "windows-packaged", "windows")):+ assert jobs[receipt]["needs"] == ["admit", call]+ assert jobs[packaged]["needs"] == receipt+ assert jobs[packaged]["strategy"]["matrix"] == \+ "${{ fromJSON(needs." + receipt + ".outputs." + matrix + ") }}"+ # B5: publish-docker starts when the docker tests pass; it does not wait+ # for the acceptance join. publish-bundles still does.+ assert jobs["publish-docker"]["needs"] == ["admit", "docker"]+ assert {"admit", "docker"} <= ancestors(jobs, "publish-docker")+ assert "acceptance" not in ancestors(jobs, "publish-docker")+ assert required <= ancestors(jobs, "publish-bundles")+ assert {"publish-docker", "publish-bundles", "publication"} <= ancestors(jobs, "complete")+ assert "promote-docker" not in jobs and "promote-bundles" not in jobs+ for name in ("acceptance", "publication", "complete"):+ assert jobs[name]["if"] == "always()"+++def test_all_applicable_ci_jobs_are_aggregated_and_desktop_e2e_stays_deferred():+ jobs = workflow("ci.yaml")["jobs"]+ checks = {name for name, job in jobs.items() if "uses" in job}+ assert checks <= set(jobs["all-checks-pass"]["needs"])+ assert jobs["e2e-desktop"]["if"] == "false"+ assert "workflow_call" in workflow("ci.yaml")["on"]+++def test_claim_custody_and_final_payload_identity_reach_every_privileged_phase():+ release = workflow("stable-release.yml")+ jobs = release["jobs"]+ assert "autopublish" not in release["on"]["workflow_dispatch"]["inputs"]+ assert {"claim-tag", "claim-object", "tag", "commit", "version", "release-id", "release-epoch"} <= \+ set(jobs["admit"]["outputs"])+ for name in ("publish-bundles", *("candidates-darwin-arm64", "candidates-darwin-x64",+ "candidates-win32-arm64", "candidates-win32-x64",+ "candidates-win32-bundle", "candidates-termux")):+ call = jobs[name]["with"]+ assert call["tag"] == "${{ needs.admit.outputs.tag }}"+ assert call["claim-tag"] == "${{ needs.admit.outputs.claim-tag }}"+ assert call["claim-object"] == "${{ needs.admit.outputs.claim-object }}"+ desktop = workflow("desktop-bundled-release.yml")+ assert "release-epoch" in desktop["jobs"]["validate"]["outputs"]+ assert "HERMES_RELEASE_EPOCH" not in desktop["jobs"]["termux-deb"]["env"]+ # B3: each build group stages its own receipt before its smoke, and the+ # receipt URL and digest cross the call boundary as workflow outputs.+ assert "manifest-url" not in desktop["on"]["workflow_call"]["outputs"]+ assert "manifest-sha256" not in desktop["on"]["workflow_call"]["outputs"]+ receipts = {"darwin-arm64": "stage-receipt-darwin-arm64", "darwin-x64": "stage-receipt-darwin-x64",+ "win32-bundle": "assemble-win32-bundle"}+ for group, job in receipts.items():+ producer = desktop["jobs"][job]+ assert producer["outputs"]["receipt-url"] == "${{ steps.receipt.outputs.receipt-url }}"+ assert producer["outputs"]["receipt-sha256"] == "${{ steps.receipt.outputs.receipt-sha256 }}"+ for suffix, output in (("url", "receipt-url"), ("sha256", "receipt-sha256")):+ expected = "${{ jobs." + job + ".outputs." + output + " }}"+ assert desktop["on"]["workflow_call"]["outputs"][f"{group}-receipt-{suffix}"]["value"] == expected+ for name in ("smoke-darwin-arm64", "smoke-darwin-x64"):+ assert f"stage-receipt-{name.removeprefix('smoke-')}" in desktop["jobs"][name]["needs"]+ for call, key, output in (("candidates-darwin-arm64", "RECEIPT_URL", "darwin-arm64-receipt-url"),+ ("candidates-darwin-arm64", "RECEIPT_SHA256", "darwin-arm64-receipt-sha256"),+ ("candidates-darwin-x64", "RECEIPT_URL", "darwin-x64-receipt-url"),+ ("candidates-darwin-x64", "RECEIPT_SHA256", "darwin-x64-receipt-sha256"),+ ("candidates-win32-bundle", "RECEIPT_URL", "win32-bundle-receipt-url"),+ ("candidates-win32-bundle", "RECEIPT_SHA256", "win32-bundle-receipt-sha256")):+ receipt_job = {"candidates-darwin-arm64": "transitions-darwin-arm64",+ "candidates-darwin-x64": "transitions-darwin-x64",+ "candidates-win32-bundle": "transitions-win32"}[call]+ expected = "${{ needs." + call + ".outputs." + output + " }}"+ assert jobs[receipt_job]["steps"][-1]["env"][key] == expected+ for name in ("docker", "nix"):+ assert jobs[name]["with"]["version"] == "${{ needs.admit.outputs.version }}"+ assert "version" not in jobs["pm-bundle"]["with"]+ assert "release-epoch" not in jobs["docker"]["with"]+ assert "release-epoch" not in jobs["nix"]["with"]+ assert "release-epoch" not in jobs["pm-bundle"]["with"]+ assert "release-epoch" not in jobs["publish-docker"]["with"]+ complete = jobs["complete"]["steps"]+ # A6: the green workflow validates the accepted candidate archive; the+ # final tag and the retarget move to the publication pass.+ validation = next(i for i, step in enumerate(complete)+ if step.get("name", "").startswith("Validate the accepted candidate archive"))+ assert "DOCKER_MANIFEST_DIGEST" not in complete[validation]["env"]+ assert "RELEASE_ID" not in complete[validation]["env"]+ # B4: complete and the render read the manifest that stable-release.yml's+ # candidate-manifest job wrote.+ assert complete[validation]["env"]["CANDIDATE_MANIFEST_SHA256"] == \+ "${{ needs.candidate-manifest.outputs.manifest-sha256 }}"+ assert jobs["publish-bundles"]["with"]["manifest-sha256"] == \+ "${{ needs.candidate-manifest.outputs.manifest-sha256 }}"+ render = next(i for i, step in enumerate(complete) if step.get("name", "").startswith("Render the admitted"))+ reconcile = next(i for i, step in enumerate(complete) if step.get("name", "").startswith("Reconcile ordered"))+ assert validation < render < reconcile+ assert not any("Create the final tag" in step.get("name", "") for step in complete)+++def test_docker_dev_stamp_checkout_has_release_history():+ build = workflow("docker.yml")["jobs"]["build"]+ checkout = next(step for step in build["steps"] if "actions/checkout@" in step.get("uses", ""))++ assert checkout["with"]["fetch-depth"] == "0"+++def test_release_gates_extract_consumer_facing_versions():+ release_jobs = workflow("stable-release.yml")["jobs"]+ bootstrap = next(+ step["run"] for step in release_jobs["bootstrap-version"]["steps"]+ if step.get("name") == "Stamp and verify the Cargo and Tauri release identity"+ )+ assert "cargo metadata" in bootstrap+ assert "tauri.conf.json" in bootstrap+ assert "uv build --wheel --sdist" not in bootstrap++ docker = workflow("docker.yml")["jobs"]+ image_check = next(+ step["run"] for step in docker["build"]["steps"]+ if step.get("name") == "Verify release image identity"+ )+ assert '["baseVersion"]' in image_check and "$RELEASE_VERSION" in image_check++ nix = workflow("nix.yml")["jobs"]+ nix_check = next(+ step["run"] for step in nix["flake-check"]["steps"]+ if step.get("name") == "Verify release package runtime identity"+ )+ assert '"$package/bin/hermes" --version' in nix_check+ assert "actual != expected" in nix_check+++def test_packaged_stamp_writers_receive_versions_without_rewriting_python_metadata():+ docker_steps = workflow("docker.yml")["jobs"]["build"]["steps"]+ assert not any(step.get("name") == "Stamp release build context" for step in docker_steps)+ write = next(step["run"] for step in docker_steps if step.get("name") == "Write install stamp")+ assert "--base-version" in write and "--display-version" in write++ nix_steps = workflow("nix.yml")["jobs"]["flake-check"]["steps"]+ prepare = next(step["run"] for step in nix_steps if step.get("name") == "Prepare isolated release source")+ assert "scripts/releases/stamping.py" in prepare+++def test_publication_reconciler_has_every_recovery_trigger_and_shared_lock():+ stable = workflow("stable-release.yml")+ publication = workflow("stable-release-publication.yml")++ assert stable["concurrency"] == publication["concurrency"] == {+ "group": "stable-release", "cancel-in-progress": "false",+ }+ assert {"workflow_dispatch", "workflow_run", "schedule"} <= set(publication["on"])+ assert publication["on"]["workflow_run"] == {+ "workflows": ["Stable Release"], "types": ["completed"],+ }+ reconcile = publication["jobs"]["reconcile"]+ assert reconcile["environment"] == "release-signing"+ assert publication["permissions"] == {"contents": "write", "actions": "write"}+ assert "conclusion != 'success'" in reconcile["if"]+ checkout = reconcile["steps"][0]+ assert checkout["with"]["ref"] == "${{ github.event.repository.default_branch }}"+ assert checkout["with"]["persist-credentials"] == "false"+ assert publication["on"]["schedule"] == [{"cron": "*/15 * * * *"}]+ assert not any(step.get("run", "").startswith("sleep ") for step in reconcile["steps"])+++def test_docker_recovery_refuses_to_replace_a_divergent_version_tag(tmp_path):+ publish = workflow("docker.yml")["jobs"]["release-publish-manifest"]- step = next(item for item in publish["steps"] if item.get("name") == "Create versioned manifest list")++ step = next(item for item in publish["steps"] if item.get("name") == "Create both immutable versioned manifest lists")+ digest_dir = tmp_path / "digests"+ digest_dir.mkdir()- for arch, digest in (("amd64", "a" * 64), ("arm64", "b" * 64)):- (digest_dir / f"{arch}.digest").write_text(f"sha256:{digest}\n", encoding="utf-8")++ for variant in ("slim", "desktop"):++ for arch, digest in (("amd64", "a" * 64), ("arm64", "b" * 64)):++ artifact = digest_dir / f"docker-publish-digest-{variant}-{arch}-0.21.5"++ artifact.mkdir()++ (artifact / f"{arch}.digest").write_text(f"sha256:{digest}\n", encoding="utf-8")++ marker = tmp_path / "create-called"+ bindir = tmp_path / "bin"+ bindir.mkdir()+ docker = bindir / "docker"+ docker.write_text(+ "#!/usr/bin/env python3\n"+ "import json, os, pathlib, sys\n"+ "if 'create' in sys.argv:\n"+ " pathlib.Path(os.environ['CREATE_MARKER']).write_text('called')\n"+ " raise SystemExit(0)\n"+ "print(json.dumps({'manifests': [{'digest': 'sha256:' + 'c' * 64}]}))\n",+ encoding="utf-8",+ )+ docker.chmod(0o755)+ result = subprocess.run(+ ["bash", "-e", "-o", "pipefail", "-c",+ step["run"].replace("/tmp/digests", str(digest_dir))], cwd=tmp_path,+ env={**os.environ, "PATH": f"{bindir}:{os.environ['PATH']}",+ "IMAGE_NAME": "owner/repo", "RELEASE_TAG": "0.21.5",+ "CREATE_MARKER": str(marker)},+ capture_output=True, text=True, encoding="utf-8",+ )+ assert result.returncode != 0+ assert "versioned Docker manifest differs" in result.stderr+ assert not marker.exists()diff --cc tests/hermes_cli/test_plugin_install_ref.pyindex 33774bee43d,a02a7e78b22..d36abe526d8--- a/tests/hermes_cli/test_plugin_install_ref.py+++ b/tests/hermes_cli/test_plugin_install_ref.py@@@ -182,6 -169,87 +182,87 @@@ def test_subdir_pin_records_source_iden}+ def test_clone_timeout_applies_to_every_network_step_of_a_pinned_install(monkeypatch, tmp_path):+ from hermes_cli import plugins_cmd++ repo, old_sha, _new_sha = _plugin_repo(tmp_path)+ home = tmp_path / "home"- home.mkdir()++ home.mkdir(exist_ok=True)+ (home / "config.yaml").write_text("plugins:\n clone_timeout_seconds: 137\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ run_git = plugins_cmd._run_plugin_git+ calls = []++ def record_git(git_exe, target, *args, **kwargs):+ calls.append((args[0], kwargs.get("timeout")))+ return run_git(git_exe, target, *args, **kwargs)++ monkeypatch.setattr(plugins_cmd, "_run_plugin_git", record_git)+ target, _manifest, _name = plugins_cmd._install_plugin_core(+ repo.as_uri(), force=False, ref=old_sha+ )++ assert _git(target, "rev-parse", "HEAD") == old_sha+ assert ("clone", 137) in calls+ assert ("fetch", 137) in calls+ assert ("checkout", 137) in calls+++ @pytest.mark.parametrize("pinned", [False, True])+ def test_subdir_install_downloads_only_that_subdirectory(monkeypatch, tmp_path, pinned):+ from hermes_cli.plugins_cmd import _install_plugin_core++ repo = tmp_path / "monorepo"+ plugin = repo / "integrations" / "hermes"+ plugin.mkdir(parents=True)+ _git(repo, "init", "-q")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "config", "user.name", "Fixture")+ _git(repo, "config", "uploadpack.allowFilter", "true")+ (plugin / "plugin.yaml").write_text("name: nested-demo\n", encoding="utf-8")+ (repo / "unrelated.bin").write_bytes(b"x" * 4096)+ _git(repo, "add", ".")+ _git(repo, "commit", "-qm", "init")+ sha = _git(repo, "rev-parse", "HEAD")+ unrelated_blob = _git(repo, "rev-parse", "HEAD:unrelated.bin")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ seen = {}++ def inspect_clone(_manifest, tree):+ clone = tree.parents[1]+ seen["worktree"] = sorted(p.name for p in clone.iterdir() if p.name != ".git")+ seen["missing"] = _git(clone, "rev-list", "--objects", "--missing=print", "HEAD")++ target, _manifest, _name = _install_plugin_core(+ f"{repo.as_uri()}#integrations/hermes", force=False,+ ref=sha if pinned else None, before_swap=inspect_clone)++ assert (target / "plugin.yaml").is_file()+ assert seen["worktree"] == ["integrations"]+ assert f"?{unrelated_blob}" in seen["missing"].splitlines()+++ def test_clone_timeout_uses_active_profile_and_bounds_invalid_values(monkeypatch, tmp_path):+ from hermes_cli.plugins_cmd import _clone_timeout_seconds++ home = tmp_path / "home"- home.mkdir()++ home.mkdir(exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ config = home / "config.yaml"+ config.write_text("plugins:\n clone_timeout_seconds: 137\n", encoding="utf-8")+ assert _clone_timeout_seconds() == 137++ other = tmp_path / "other"+ other.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(other))+ assert _clone_timeout_seconds() == 300+ other_config = other / "config.yaml"+ other_config.write_text("plugins:\n clone_timeout_seconds: 0\n", encoding="utf-8")+ assert _clone_timeout_seconds() == 300+ other_config.write_text("plugins:\n clone_timeout_seconds: 7200\n", encoding="utf-8")+ assert _clone_timeout_seconds() == 3600++def test_force_reinstall_does_not_drift_pin_without_explicit_new_ref(monkeypatch, tmp_path):diff --cc tests/pm/test_node_resolution.pyindex fdecb4437b5,00000000000..dd062581b6emode 100644,000000..100644--- a/tests/pm/test_node_resolution.py+++ b/tests/pm/test_node_resolution.py@@@ -1,376 -1,0 +1,381 @@@+"""Node discovery reads PM state; legacy home-local trees are never activated."""++import hashlib+import json+from pathlib import Path+import shutil+import subprocess++import pytest++import hermes_constants+import pm+from pm import paths+from pm.lock import Facts, Lockfile+from pm.package import Runner+from pm.registry import get_package+from pm.store import current_target, tree_digest+++_REAL_HERMES_HOME = Path.home() / ".hermes" # Captured before per-test HOME isolation.++++def _register_installed_tool(name, executable, companions=()):+ executable = Path(executable)+ version = subprocess.run([str(executable), "--version"], capture_output=True, text=True,+ check=True, timeout=10).stdout.strip().removeprefix("v")+ package, target, store = get_package(name), current_target(), paths.store_root()+ entry = store / package.store_entry(version, target)+ binary = package.binary(entry, target)+ assert binary is not None+ binary.parent.mkdir(parents=True)+ binary.symlink_to(executable)+ for companion in companions:+ binary.with_name(companion.name).symlink_to(companion)+ digest = hashlib.sha256(executable.read_bytes()).hexdigest()+ lock = Lockfile(paths.lockfile_path())+ lock.set_pin(name, version, {target: {"url": executable.as_uri(), "sha256": digest}})+ lock.save()+ Facts(paths.facts_path()).record(name, version, entry.name, package.env(entry, target), store,+ target=target, artifacts=[digest], digest=tree_digest(entry))+ return binary+++def node_store(tmp_path, monkeypatch):+ node = shutil.which("node")+ if node is None:+ pytest.skip("requires an already-installed Node executable")- assert node is not None++ # The fixture hashes its input. Never read the developer's live PM store to++ # fabricate a temporary one; CI's external Node still exercises this path.++ if Path(node).absolute().is_relative_to(_REAL_HERMES_HOME):++ pytest.skip("requires a Node binary outside the real Hermes home")+ monkeypatch.setenv("PATH", str(Path(node).parent))+ home = tmp_path / "home"+ home.mkdir()+ store = home / "tools"+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ lock_path = tmp_path / "lock.json"+ monkeypatch.setattr(paths, "lockfile_path", lambda: lock_path)+ binary = _register_installed_tool("node", node)+ return home, binary, node++[email protected]("posix")+def test_pm_node_wins_over_legacy_tree_and_composes_child_environment(node_store, monkeypatch):+ home, binary, external = node_store+ legacy = home / "node" / "bin" / "node"+ legacy.parent.mkdir(parents=True)+ legacy.symlink_to(external)+ monkeypatch.setenv("PATH", str(Path(external).parent))+ before = paths.facts_path().read_bytes()++ selected = pm.installed_package("node")+ assert selected is not None and selected.binary == binary+ resolved = hermes_constants.find_node_executable("node")+ assert resolved is not None and resolved == str(binary)+ base = {"PATH": str(Path(external).parent), "CALLER_VALUE": "preserved"}+ environment = hermes_constants.with_hermes_node_path(base)+ assert environment == pm.env_for("npm", base_env=base)+ assert shutil.which("node", path=environment["PATH"]) == str(binary)+ child = subprocess.run(+ [resolved, "-p", "process.version"],+ env=environment, capture_output=True, text=True, check=True, timeout=10,+ )+ assert child.stdout.strip().removeprefix("v") == selected.version+ assert paths.facts_path().read_bytes() == before+ assert legacy.is_file()+ assert base == {"PATH": str(Path(external).parent), "CALLER_VALUE": "preserved"}++[email protected]("posix")+def test_passive_discovery_never_installs_or_repairs_a_legacy_tree(tmp_path, monkeypatch):+ home = tmp_path / "home"+ legacy = home / "node" / "bin" / "node"+ legacy.parent.mkdir(parents=True)+ legacy.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")+ legacy.chmod(0o755)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(home / "tools"))+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ monkeypatch.setenv("PATH", "")+ before = {p.relative_to(home): p.read_bytes() for p in home.rglob("*") if p.is_file()}+ attempts = []++ def forbidden_install(*args, **kwargs):+ attempts.append((args, kwargs))+ raise AssertionError("passive lookup must not provision anything")++ monkeypatch.setattr(pm, "ensure", forbidden_install)+ assert hermes_constants.find_node_executable("node") is None+ assert hermes_constants.find_node_executable("npm") is None+ assert hermes_constants.with_hermes_node_path({"PATH": ""}) == {"PATH": ""}+ assert attempts == []+ assert {p.relative_to(home): p.read_bytes() for p in home.rglob("*") if p.is_file()} == before+ assert not (home / "tools").exists()++ # A user-owned PATH toolchain remains usable without acquiring a PM one.+ external = tmp_path / "external"+ external.mkdir()+ npm = external / "npm"+ npm.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ npm.chmod(0o755)+ monkeypatch.setenv("PATH", str(external))+ assert hermes_constants.find_node_executable("npm") == str(npm)+ assert attempts == []+ assert not (home / "tools").exists()++[email protected]("posix")+def test_explicit_node_path_is_not_replaced_by_managed_name(node_store):+ _home, _binary, external = node_store+ assert hermes_constants.find_node_executable(external) == external+ assert hermes_constants.find_node_executable(str(Path(external).with_name("missing-node"))) is None+ assert hermes_constants.find_node_executable("not-a-node-command") is None++[email protected]("posix")+def test_npm_and_npx_use_the_paired_pm_entry(node_store, monkeypatch):+ home, node, external = node_store+ npm = Path(external).with_name("npm")+ npx = Path(external).with_name("npx")+ if not npm.is_file() or not npx.is_file():+ pytest.skip("requires already-installed npm and npx")+ binary = _register_installed_tool("npm", npm, [npx])+ companion = binary.with_name("npx")+ legacy = home / "node" / "bin" / "npm"+ legacy.parent.mkdir(parents=True)+ legacy.symlink_to(npm)+ before = paths.facts_path().read_bytes()+ monkeypatch.setenv("PATH", "")++ assert hermes_constants.find_node_executable("npm") == str(binary)+ assert hermes_constants.find_node_executable("npx") == str(companion)+ environment = hermes_constants.with_hermes_node_path({"PATH": ""})+ assert shutil.which("npm", path=environment["PATH"]) == str(binary)+ assert shutil.which("node", path=environment["PATH"]) == str(node)+ for command in ("npm", "npx"):+ resolved = hermes_constants.find_node_executable(command)+ assert resolved is not None+ result = subprocess.run(+ [resolved, "--version"], env=environment,+ capture_output=True, text=True, check=True, timeout=10,+ )+ assert result.stdout.strip() == Lockfile(paths.lockfile_path()).version("npm")+ assert paths.facts_path().read_bytes() == before+ companion.unlink()+ assert hermes_constants.find_node_executable("npx") is None++[email protected]("windows")+def test_windows_path_prefers_launchable_npm_cmd(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "absent-store"))+ monkeypatch.setenv("PATH", str(tmp_path))+ for name in ("npm", "npm.ps1", "npm.cmd"):+ (tmp_path / name).write_text("@exit /b 0\n", encoding="utf-8")+ assert hermes_constants.find_node_executable("npm") == str(tmp_path / "npm.cmd")+++def npm_probe(node_store, monkeypatch):+ home, node, _external = node_store+ store = paths.store_root()+ package = get_package("npm")+ target = current_target()+ entry = store / package.store_entry("1.0.0", target)+ binary = package.binary(entry, target)+ assert binary is not None+ binary.parent.mkdir(parents=True)+ binary.write_text(+ '#!/usr/bin/env node\n'+ 'const fs = require("fs"); const path = require("path");\n'+ 'const i = process.argv.indexOf("--prefix");\n'+ 'const root = i < 0 ? process.cwd() : process.argv[i + 1];\n'+ 'fs.mkdirSync(path.join(root, "node_modules/.bin"), {recursive:true});\n'+ 'fs.writeFileSync(path.join(root, "node_modules/.bin/test-server"), "ready");\n'+ 'fs.writeFileSync(path.join(root, "called.json"), JSON.stringify({argv: process.argv, env: process.env}));\n',+ encoding="utf-8",+ )+ binary.chmod(0o755)+ lock = Lockfile(paths.lockfile_path())+ lock.set_pin("npm", "1.0.0", {})+ lock.save()++ def publish():+ Facts(paths.facts_path()).record(+ "npm", "1.0.0", entry.name, package.env(entry, target), store,+ )+ return Runner("npm", pm.env_for("npm"))++ monkeypatch.setenv("PATH", "")+ return home, node, binary, publish+++def npm_consumers(npm_probe, tmp_path, monkeypatch):+ from agent.lsp.install import _install_npm+ from gateway.config import PlatformConfig+ from hermes_cli.main_platform_setup import _whatsapp_install_bridge+ from hermes_cli.web_routers.messaging import _ensure_whatsapp_bridge_dependencies+ from plugins.platforms.photon import adapter as photon, cli+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter++ home, _node, _binary, _publish = npm_probe+ bridge = tmp_path / "bridge"+ bridge.mkdir()+ (bridge / "package.json").write_text('{"name":"test-bridge"}', encoding="utf-8")+ adapter = WhatsAppAdapter(PlatformConfig(extra={"bridge_script": str(bridge / "bridge.js")}))+ monkeypatch.setattr(photon, "_sidecar_dir", lambda: bridge)+ monkeypatch.setattr(cli, "_sidecar_dir", lambda: bridge)+ return {+ "lsp": (lambda: _install_npm("test-pkg", "test-server"), home / "lsp"),+ "whatsapp": (lambda: adapter._ensure_bridge_deps(bridge), bridge),+ "photon": (photon._reinstall_sidecar_deps, bridge),+ "photon-cli": (cli._install_sidecar, bridge),+ "cli": (lambda: _whatsapp_install_bridge(bridge), bridge),+ "dashboard": (lambda: _ensure_whatsapp_bridge_dependencies(bridge), bridge),+ }++[email protected]("posix")[email protected]("consumer", ["lsp", "whatsapp", "photon", "photon-cli", "cli", "dashboard"])+def test_npm_consumers_execute_with_pm_node(npm_probe, npm_consumers, consumer):+ _home, node, binary, publish = npm_probe+ publish()+ call, output_dir = npm_consumers[consumer]+ call()+ result = json.loads((output_dir / "called.json").read_text())+ assert Path(result["argv"][1]) == binary+ assert shutil.which("node", path=result["env"]["PATH"]) == str(node)+ if consumer == "lsp":+ assert result["argv"][2:] == [+ "install", "--prefix", str(output_dir), "--silent", "--no-fund", "--no-audit", "test-pkg",+ ]++[email protected]("posix")[email protected]("surface", ["cli", "dashboard", "whatsapp", "photon", "photon-cli"])+def test_missing_npm_acquires_npm_closure_at_install_boundary(npm_probe, npm_consumers, monkeypatch, surface):+ _home, node, binary, publish = npm_probe+ calls = []++ def ensure(name, **kwargs):+ calls.append((name, kwargs.get("explicit", False)))+ assert name == "npm"+ return publish()++ monkeypatch.setattr(pm, "ensure", ensure)+ call, bridge = npm_consumers[surface]+ call()+ assert calls == [("npm", surface in {"cli", "dashboard", "photon-cli"})]+ result = json.loads((bridge / "called.json").read_text())+ assert Path(result["argv"][1]) == binary+ assert shutil.which("node", path=result["env"]["PATH"]) == str(node)++[email protected]("posix")[email protected]("surface", ["whatsapp", "photon"])+def test_runtime_npm_refusal_never_falls_back_to_literal_npm(npm_probe, npm_consumers, monkeypatch, surface):+ call, bridge = npm_consumers[surface]+ spawns = []+ run = subprocess.run++ def forbidden_spawn(*args, **kwargs):+ if args[0][0] == "git": # Fatal-status reporting may read the code revision.+ return run(*args, **kwargs)+ spawns.append(args)+ raise AssertionError("refused PM preparation must not spawn npm")++ monkeypatch.setattr(subprocess, "run", forbidden_spawn)+ call()+ assert spawns == []+ assert not (bridge / "called.json").exists()+ assert pm.installed_package("npm") is None++[email protected]("allowed", [False, True])+def test_adapter_availability_never_provisions_missing_node(tmp_path, monkeypatch, allowed):+ from plugins.platforms.photon import adapter as photon+ from plugins.platforms.whatsapp import adapter as whatsapp++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "missing-tools"))+ monkeypatch.setenv("PATH", "")+ monkeypatch.delenv("PHOTON_NODE_BIN", raising=False)+ monkeypatch.setattr(photon, "_sidecar_dir", lambda: tmp_path)+ monkeypatch.setattr(photon, "HTTPX_AVAILABLE", True)+ monkeypatch.setattr(pm, "lazy_installs_allowed", lambda: allowed)+ installs = []++ def forbidden_ensure(*args, **kwargs):+ installs.append(args)+ raise AssertionError("availability must not install")++ monkeypatch.setattr(pm, "ensure", forbidden_ensure)+ assert whatsapp.check_whatsapp_requirements() is allowed+ assert photon.check_requirements() is allowed+ assert installs == []+ assert not (tmp_path / "missing-tools").exists()++[email protected]("posix")+def test_dashboard_pairing_prepares_npm_before_node_lookup(npm_probe, tmp_path, monkeypatch):+ from gateway.platforms import whatsapp_common+ from hermes_cli.web_routers.messaging import _spawn_whatsapp_pairing_process++ _home, node, _npm, publish = npm_probe+ node_facts = paths.facts_path().read_bytes()+ paths.facts_path().unlink()+ bridge = tmp_path / "bridge"+ bridge.mkdir()+ (bridge / "bridge.js").write_text('console.log(JSON.stringify({argv:process.argv, path:process.env.PATH}));\n')+ monkeypatch.setattr(whatsapp_common, "resolve_whatsapp_bridge_dir", lambda: bridge)+ installs = []++ def ensure(name, **kwargs):+ installs.append((name, kwargs.get("explicit", False)))+ paths.facts_path().write_bytes(node_facts)+ return publish()++ monkeypatch.setattr(pm, "ensure", ensure)+ child = _spawn_whatsapp_pairing_process(tmp_path / "session", "bot")+ try:+ output, _ = child.communicate(timeout=10)+ assert child.returncode == 0+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=10)+ assert installs == [("npm", True)]+ result = json.loads(output)+ assert "--pair-json" in result["argv"]+ assert shutil.which("node", path=result["path"]) == str(node)++[email protected]("posix")+def test_lsp_node_server_inherits_pm_runtime_and_preserves_overrides(node_store, tmp_path, monkeypatch):+ from agent.lsp.servers import ServerContext, find_server_for_file++ _home, node, _external = node_store+ script = tmp_path / "language-server"+ script.write_text('#!/usr/bin/env node\nconsole.log(JSON.stringify({path:process.env.PATH, flag:process.env.LSP_FLAG}));\n')+ script.chmod(0o755)+ monkeypatch.setenv("PATH", "")+ ctx = ServerContext(+ workspace_root=str(tmp_path), install_strategy="off",+ binary_overrides={"typescript": [str(script)]},+ env_overrides={"typescript": {"LSP_FLAG": "project-value"}},+ )+ server = find_server_for_file(str(tmp_path / "test.ts"))+ assert server is not None+ spec = server.build_spawn(str(tmp_path), ctx)+ assert spec is not None+ child = subprocess.run(spec.command, env=spec.env, capture_output=True, text=True, timeout=10)+ assert child.returncode == 0, child.stderr+ observed = json.loads(child.stdout)+ assert shutil.which("node", path=observed["path"]) == str(node)+ assert observed["flag"] == "project-value"+ ctx.env_overrides["typescript"]["PATH"] = "/explicit/project/tools"+ spec = server.build_spawn(str(tmp_path), ctx)+ assert spec is not None and spec.env["PATH"] == "/explicit/project/tools"diff --cc tests/pm/test_node_sidecar.pyindex 6aec43a3b34,00000000000..3beda5cf9e0mode 100644,000000..100644--- a/tests/pm/test_node_sidecar.py+++ b/tests/pm/test_node_sidecar.py@@@ -1,108 -1,0 +1,113 @@@+"""Plugin-local npm installs retain PM's paired Node and consent policy."""++import json+import os+from pathlib import Path+import shutil+import shlex++import pytest++import pm+from pm.package import InstallError, Runner, compose_env+from pm.workspace import install_node_sidecar+++_REAL_HERMES_HOME = Path.home() / ".hermes" # Captured before per-test HOME isolation.++++def test_no_package_json_never_acquires_npm(tmp_path, monkeypatch):+ def unexpected(*args, **kwargs):+ pytest.fail("a dependency-free plugin must not acquire npm")+ monkeypatch.setattr(pm, "ensure", unexpected)+ assert install_node_sidecar(tmp_path) is None++[email protected]("explicit", [False, True])+def test_acquisition_receives_consent_and_reports_refusal(tmp_path, monkeypatch, explicit):+ import importlib++ monkeypatch.setattr(importlib.import_module("pm.install"), "lazy_installs_allowed", lambda: True)+ (tmp_path / "package.json").write_text('{}')+ calls = []+ def refused(name, **kwargs):+ calls.append((name, kwargs))+ raise InstallError(name, "acquisition refused")+ monkeypatch.setattr(pm, "ensure", refused)+ reason = install_node_sidecar(tmp_path, explicit=explicit)+ assert "acquisition refused" in reason+ assert calls == [("npm", {"explicit": explicit})]++[email protected]("posix")+def test_real_npm_uses_paired_node_with_empty_ambient_path(tmp_path, monkeypatch):+ npm, node = shutil.which("npm"), shutil.which("node")+ if not npm or not node:+ pytest.skip("npm and node are required")++ if any(Path(executable).absolute().is_relative_to(_REAL_HERMES_HOME)++ for executable in (npm, node)):++ pytest.skip("requires npm and Node outside the real Hermes home")+ # npm's real JS entrypoint uses /usr/bin/env node. Its paired Node lives+ # in a different PATH entry, just as the two PM packages do.+ npm_cli = next(iter(Path(npm).resolve().parent.parent.glob("lib/npm*/bin/npm-cli.js")), Path(npm).resolve())+ npm_bin, node_bin = tmp_path / "npm/bin", tmp_path / "node/bin"+ npm_bin.mkdir(parents=True)+ node_bin.mkdir(parents=True)+ wrapper = npm_bin / "npm"+ wrapper.write_text(f'#!/bin/sh\nexec node {shlex.quote(str(npm_cli))} "$@"\n')+ wrapper.chmod(0o755)+ (node_bin / "node").symlink_to(node)+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("PATH", "")+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ context = Runner("npm", compose_env([+ {"PATH": [str(node_bin)]}, {"PATH": [str(npm_bin)]},+ ]))+ calls = []+ def acquire(name, **kwargs):+ calls.append((name, kwargs))+ return context+ monkeypatch.setattr(pm, "ensure", acquire)+ dependency, plugin = tmp_path / "side-dep", tmp_path / "plugin"+ dependency.mkdir()+ plugin.mkdir()+ (dependency / "package.json").write_text(json.dumps({"name": "side-dep", "version": "1.0.0", "main": "index.js"}))+ (dependency / "index.js").write_text("module.exports = 'isolated';")+ manifest = {"name": "plugin", "version": "1.0.0", "dependencies": {"side-dep": "file:../side-dep"}}+ (plugin / "package.json").write_text(json.dumps(manifest))+ ambient = dict(os.environ)+ assert install_node_sidecar(plugin, explicit=True) is None+ lock = (plugin / "package-lock.json").read_bytes()+ # ci must remove an extraneous directory; another `install` would not+ # reliably prove that the lockfile selected the clean-install path.+ stale = plugin / "node_modules/stale-file"+ stale.write_text("remove me")+ assert install_node_sidecar(plugin, explicit=True) is None+ assert not stale.exists()+ assert (plugin / "package-lock.json").read_bytes() == lock+ result = context.run(["node", "-e", "console.log(require('side-dep'))"], cwd=plugin, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "isolated"+ assert not (tmp_path / "node_modules").exists()+ assert dict(os.environ) == ambient+ assert calls == [("npm", {"explicit": True})] * 2+ (plugin / "package.json").write_text("{malformed")+ reason = install_node_sidecar(plugin, explicit=True)+ assert "exited" in reason and "JSON" in reason++++def test_on_demand_sidecar_install_respects_lazy_refusal(tmp_path, monkeypatch):+ (tmp_path / "package.json").write_text('{}')+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ binary = tmp_path / ("npm.cmd" if os.name == "nt" else "npm")+ binary.write_text("process boundary fixture")+ binary.chmod(0o755)+ class InstalledRunner:+ env = {"PATH": str(tmp_path)}+ def run(self, *args, **kwargs):+ pytest.fail("installed npm must not mutate sidecars when on-demand installs are disabled")+ monkeypatch.setattr(pm, "ensure", lambda *args, **kwargs: InstalledRunner())+ reason = install_node_sidecar(tmp_path)+ assert reason and "disabled" in reasondiff --cc tests/tools/test_bot_desktop_browser.pyindex d9302c7b959,b5bdab304f3..f7b1af6d028--- a/tests/tools/test_bot_desktop_browser.py+++ b/tests/tools/test_bot_desktop_browser.py@@@ -339,3 -315,40 +339,40 @@@ def test_daemon_idle_timer_defers_to_thmonkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)monkeypatch.setattr(runtime, "published_env", lambda: {})assert session._daemon_idle_timeout_seconds() == 120+++ def test_a_headless_shell_pin_is_replaced_while_a_screen_is_up(tmp_path, monkeypatch):+ """The boot hook exports a chrome-headless-shell path; leaving it would put the agent and the dock on+ two binaries over one --user-data-dir, where the singleton swallows the dock's launch."""+ shell = tmp_path / "chrome-headless-shell"+ shell.write_text("#!/bin/sh\n", encoding="utf-8")+ shell.chmod(0o755)+ headed = tmp_path / "chrome"+ headed.write_text("#!/bin/sh\n", encoding="utf-8")+ headed.chmod(0o755)+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")- monkeypatch.setattr(browser, "_playwright_executable", lambda: str(headed))++ monkeypatch.setattr(browser, "_managed_executable", lambda: str(headed))+ monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)+ # Unpinned, the ubuntu runner (non-root, userns-restricted) flips executable() to+ # its own /usr/bin/google-chrome; host policy is not the subject here.+ monkeypatch.setattr(browser, "_userns_restricted", lambda: False)++ agent_env = browser.env_for_agent({"AGENT_BROWSER_EXECUTABLE_PATH": str(shell)})+ dock_exe, _ = browser.dock_launch()+ assert agent_env["AGENT_BROWSER_EXECUTABLE_PATH"] == dock_exe == str(headed), \+ "the agent and the dock must share one binary once a screen is up"+++ def test_a_real_user_pin_is_still_honoured(tmp_path, monkeypatch):+ """Only a headless-shell pin is overridden; a human's own headed browser stays put."""+ mine = tmp_path / "my-chrome"+ mine.write_text("#!/bin/sh\n", encoding="utf-8")+ mine.chmod(0o755)+ other = tmp_path / "chrome"+ other.write_text("#!/bin/sh\n", encoding="utf-8")+ other.chmod(0o755)+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")- monkeypatch.setattr(browser, "_playwright_executable", lambda: str(other))++ monkeypatch.setattr(browser, "_managed_executable", lambda: str(other))++ env = browser.env_for_agent({"AGENT_BROWSER_EXECUTABLE_PATH": str(mine)})+ assert env["AGENT_BROWSER_EXECUTABLE_PATH"] == str(mine)diff --cc tests/tools/test_bot_desktop_resources.pyindex eb28dc13362,5564b09376e..64f5a41a98f--- a/tests/tools/test_bot_desktop_resources.py+++ b/tests/tools/test_bot_desktop_resources.py@@@ -54,11 -54,45 +54,45 @@@ def test_memory_info_takes_the_tighter_monkeypatch.setattr(resources, "_CGROUP_V1", tmp_path / "nope")meminfo = tmp_path / "meminfo"monkeypatch.setattr(resources, "_MEMINFO", meminfo)- meminfo.write_text("MemTotal: 4194304 kB\nMemAvailable: 3145728 kB\n")- (v2 / "memory.max").write_text(str(16 * 1024 ** 3)); (v2 / "memory.current").write_text(str(1024 ** 3))+ meminfo.write_text("MemTotal: 4194304 kB\nMemAvailable: 3145728 kB\n", encoding="utf-8")+ (v2 / "memory.max").write_text(str(16 * 1024 ** 3), encoding="utf-8"); (v2 / "memory.current").write_text(str(1024 ** 3), encoding="utf-8")assert resources.memory_info().available_mb == 3072- (v2 / "memory.max").write_text(str(2 * 1024 ** 3))+ (v2 / "memory.max").write_text(str(2 * 1024 ** 3), encoding="utf-8")info = resources.memory_info()assert info.available_mb == 1024 and info.limit_mb == 2048- (v2 / "memory.max").write_text("max") # no limit: host numbers+ (v2 / "memory.max").write_text("max", encoding="utf-8") # no limit: host numbersassert resources.memory_info() == resources.MemoryInfo(available_mb=3072, limit_mb=4096)+++ def _cgroup(monkeypatch, tmp_path, *, v2=True, limit, usage, cache):+ """A cgroup tree: ``usage`` consumed, ``cache`` of it reclaimable."""+ root = tmp_path / "cg"+ root.mkdir(exist_ok=True)+ monkeypatch.setattr(resources, "_MEMINFO", tmp_path / "no-meminfo") # cgroup numbers only+ if v2:+ monkeypatch.setattr(resources, "_CGROUP_V2", root)+ monkeypatch.setattr(resources, "_CGROUP_V1", tmp_path / "nope")+ (root / "memory.max").write_text(str(limit))+ (root / "memory.current").write_text(str(usage))+ (root / "memory.stat").write_text(f"anon 123\ninactive_file {cache}\nslab 7\n")+ else:+ monkeypatch.setattr(resources, "_CGROUP_V2", tmp_path / "nope")+ monkeypatch.setattr(resources, "_CGROUP_V1", root)+ (root / "memory.limit_in_bytes").write_text(str(limit))+ (root / "memory.usage_in_bytes").write_text(str(usage))+ (root / "memory.stat").write_text(f"total_inactive_file {cache}\n")+++ @pytest.mark.parametrize("v2", [True, False], ids=["cgroup-v2", "cgroup-v1"])+ def test_page_cache_does_not_count_against_the_limit(tmp_path, monkeypatch, v2):+ """643 MiB of mostly page cache must not read as 643 MiB consumed: charging it would tighten the gate+ over uptime, and refuse to restart a screen the idle auto-stop had just stopped."""+ MB = 1024 * 1024+ _cgroup(monkeypatch, tmp_path, v2=v2, limit=4096 * MB, usage=643 * MB, cache=340 * MB)+ assert resources.memory_info().available_mb == 4096 - (643 - 340)+++ def test_a_zero_floor_disables_the_gate(monkeypatch):+ """config_defaults documents "0 disables the check"."""+ monkeypatch.setattr(resources, "min_free_mb", lambda: 0)+ assert resources.memory_blocker(resources.MemoryInfo(available_mb=10, limit_mb=4096)) is Nonediff --cc tools/bot_desktop/resources.pyindex 6bd21090179,599d8788639..9628dc8fec5--- a/tools/bot_desktop/resources.py+++ b/tools/bot_desktop/resources.py@@@ -54,9 -54,28 +54,28 @@@ def _meminfo() -> dict[str, int]return out+ def _stat_value(path: Path, key: str) -> Optional[int]:+ """One ``<key> <bytes>`` line out of a cgroup ``memory.stat``."""+ try:- for line in path.read_text(encoding="utf-8").splitlines():++ for line in path.read_text(encoding="utf-8-sig").splitlines():+ name, _, rest = line.partition(" ")+ if name == key:+ return int(rest.strip())+ except (OSError, ValueError):+ return None+ return None++def _cgroup_limit_and_usage() -> tuple[Optional[int], Optional[int]]:+ """The cgroup's limit and its *working set* — usage minus reclaimable page cache.++ ``memory.current`` counts page cache, so a container reads several hundred MB above idle right after a+ desktop stops with every process gone. Charging that would make the gate tighten over uptime, so we+ subtract ``inactive_file``, the working-set convention kubelet uses.+ """limit = _read_int(_CGROUP_V2 / "memory.max")usage = _read_int(_CGROUP_V2 / "memory.current")+ cache = _stat_value(_CGROUP_V2 / "memory.stat", "inactive_file")if limit is None and usage is None:limit = _read_int(_CGROUP_V1 / "memory.limit_in_bytes")usage = _read_int(_CGROUP_V1 / "memory.usage_in_bytes")